blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
ec7508e0994ebb27b5fdd5049f31eaee7ecd900d
d4ca98982dbe82e342eddb69662c6aa2e03cab04
/AugmentedBizzClient/jni/renderer/RenderManager.cpp
f89af0dba8030f2b776217a28e6cbe665b990f53
[]
no_license
Vladee/com.client.AugmentedBizz
88469f0bcf76d61a7466938d99d7859f25ab39bf
798233a86d6acc6b7977b2b66efbe3d996cb2016
refs/heads/master
2021-01-10T19:05:17.017499
2011-11-30T16:41:20
2011-11-30T16:41:20
2,528,785
2
0
null
null
null
null
UTF-8
C++
false
false
17,021
cpp
#include "RenderManager.h" #include "../logging/DebugLog.h" #include "../application/ApplicationStateManager.h" #include "indicator.h" #include "android/log.h" #include <QCAR/QCAR.h> #include <QCAR/CameraDevice.h> #include <QCAR/Renderer.h> #include <QCAR/VideoBackgroundConfig.h> #include <QCAR/Trackable.h> #include <QCAR/ImageTarget.h> #include <QCAR/Tool.h> #include <QCAR/Tracker.h> #include <QCAR/Image.h> #include <QCAR/CameraCalibration.h> #include "../Utils.h" #include "CubeShaders.h" RenderManager::RenderManager(ApplicationStateManager* applicationStateManager, ObjectLoader* objectLoader, jobject jrenderManager) { this->applicationStateManager = applicationStateManager; this->renderManagerJavaInterface = new RenderManagerJavaInterface(objectLoader, jrenderManager); this->scanCounter = 0; this->screenWidth = 0; this->screenHeight = 0; this->trackableWidth = 0; this->trackableHeight = 0; this->maxTrackableCount = 1; this->numModelElementsToDraw = 0; this->vertices = 0; this->normals = 0; this->texcoords = 0; this->indices = 0; this->hasIndices = false; this->modelTexture = 0; this->indicatorTexture = 0; this->scaleFactor = 5.0f; this->indicators = 0; this->numIndicators = 0; } RenderManager::~RenderManager() { releaseData(); delete this->renderManagerJavaInterface; this->renderManagerJavaInterface = 0; } void RenderManager::inititializeNative(unsigned short screenWidth, unsigned short screenHeight) { this->setScreenDimensions(screenWidth, screenHeight); QCAR::setHint(QCAR::HINT_MAX_SIMULTANEOUS_IMAGE_TARGETS, this->maxTrackableCount); // Initialize the camera: if(!QCAR::CameraDevice::getInstance().init()) return; // Select the default mode: if(!QCAR::CameraDevice::getInstance().selectVideoMode(QCAR::CameraDevice::MODE_DEFAULT)) return; // Configure the video background configureVideoBackground(); this->shaderProgramID = SampleUtils::createProgramFromBuffer(cubeMeshVertexShader, cubeFragmentShader); this->vertexHandle = glGetAttribLocation(shaderProgramID, "vertexPosition"); this->normalHandle = glGetAttribLocation(shaderProgramID, "vertexNormal"); this->textureCoordHandle = glGetAttribLocation(shaderProgramID, "vertexTexCoord"); this->mvpMatrixHandle = glGetUniformLocation(shaderProgramID, "modelViewProjectionMatrix"); // Define clear color glClearColor(0.0f, 0.0f, 0.0f, QCAR::requiresAlpha() ? 0.0f : 1.0f); SampleUtils::checkGlError("Augmented Bizz GL init error"); } void RenderManager:: setScreenDimensions(unsigned short screenWidth, unsigned short screenHeight) { this->screenWidth = screenWidth; this->screenHeight = screenHeight; } void RenderManager::updateRendering(unsigned short screenWidth, unsigned short screenHeight) { this->setScreenDimensions(screenWidth, screenHeight); // Configure the video background configureVideoBackground(); } void RenderManager::initRendering() { // Define clear color glClearColor(0.0f, 0.0f, 0.0f, QCAR::requiresAlpha() ? 0.0f : 1.0f); // Load the shader and create the handles shaderProgramID = SampleUtils::createProgramFromBuffer(cubeMeshVertexShader, cubeFragmentShader); vertexHandle = glGetAttribLocation(shaderProgramID, "vertexPosition"); normalHandle = glGetAttribLocation(shaderProgramID, "vertexNormal"); textureCoordHandle = glGetAttribLocation(shaderProgramID, "vertexTexCoord"); mvpMatrixHandle = glGetUniformLocation(shaderProgramID, "modelViewProjectionMatrix"); } void RenderManager::startCamera() { // Start the camera: if(!QCAR::CameraDevice::getInstance().start()) return; // Set the focus mode QCAR::CameraDevice::getInstance().setFocusMode(QCAR::CameraDevice::FOCUS_MODE_AUTO); // Start the tracker: QCAR::Tracker::getInstance().start(); // Cache the projection matrix: const QCAR::Tracker& tracker = QCAR::Tracker::getInstance(); const QCAR::CameraCalibration& cameraCalibration = tracker.getCameraCalibration(); projectionMatrix = QCAR::Tool::getProjectionGL(cameraCalibration, 2.0f, 2000.0f); DebugLog::logi("Camera started."); } void RenderManager::stopCamera() { QCAR::Tracker::getInstance().stop(); QCAR::CameraDevice::getInstance().stop(); QCAR::CameraDevice::getInstance().deinit(); DebugLog::logi("Camera stopped."); } void RenderManager::setModel(JNIEnv* env, jfloatArray jvertices, jfloatArray jnormals, jfloatArray jtexcoords, jshortArray jindices) { this->jVertices = jvertices; this->jNormals = jnormals; this->jTexcoords = jtexcoords; this->jIndices = jindices; jboolean copyArrays = true; this->vertices = env->GetFloatArrayElements(jvertices, &copyArrays); this->normals = env->GetFloatArrayElements(jnormals, &copyArrays); this->texcoords = env->GetFloatArrayElements(jtexcoords, &copyArrays); this->hasIndices = false; if(jindices) { this->indices = (unsigned short*)env->GetShortArrayElements(jindices, &copyArrays); this->hasIndices = env->GetArrayLength(jindices) > 0; } this->numModelElementsToDraw = this->hasIndices ? env->GetArrayLength(jindices) : env->GetArrayLength(jvertices) / 3; } void RenderManager::setIndicators(JNIEnv* env, jfloatArray jIndicators) { jboolean copyArrays = true; this->jIndicators = jIndicators; this->indicators = env->GetFloatArrayElements(jIndicators, &copyArrays); this->numIndicators = env->GetArrayLength(jIndicators) / 3; } void RenderManager::setTexture(jobject jtexture) { this->modelTexture = Texture::create(this->renderManagerJavaInterface->getObjectLoader()->getJNIEnv(), jtexture); glGenTextures(1, &(this->modelTexture->mTextureID)); glBindTexture(GL_TEXTURE_2D, this->modelTexture->mTextureID); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this->modelTexture->mWidth, this->modelTexture->mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*) this->modelTexture->mData); } void RenderManager::setIndicatorTexture(jobject jtexture) { this->indicatorTexture = Texture::create(this->renderManagerJavaInterface->getObjectLoader()->getJNIEnv(), jtexture); glGenTextures(1, &(this->indicatorTexture->mTextureID)); glBindTexture(GL_TEXTURE_2D, this->indicatorTexture->mTextureID); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this->indicatorTexture->mWidth, this->indicatorTexture->mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*) this->indicatorTexture->mData); } void RenderManager::setScaleFactor(float scaleFactor) { this->scaleFactor = scaleFactor; } void RenderManager::scanFrameForBarcode(QCAR::State& state) { QCAR::Frame frame = state.getFrame(); for(int i = 0; i < frame.getNumImages(); i++) { const QCAR::Image *frameImage = frame.getImage(i); if(frameImage->getFormat() == QCAR::RGB565) { const char* pixels = (const char*) frameImage->getPixels(); int imageWidth = frameImage->getWidth(); int imageHeight = frameImage->getHeight(); int curNumPixels = imageWidth * imageHeight; //build up the pixel array jbyteArray pixelArray = this->renderManagerJavaInterface->getObjectLoader()->createByteArray(curNumPixels * 2); //fill the pixel array this->renderManagerJavaInterface->getObjectLoader()->setByteArrayRegion(pixelArray, 0, curNumPixels * 2, (const jbyte*)pixels); this->renderManagerJavaInterface->callScanner(imageWidth, imageHeight, pixelArray); //release pixel data this->renderManagerJavaInterface->getObjectLoader()->getJNIEnv()->ReleaseByteArrayElements(pixelArray, (jbyte*)pixels, 0); } } } void RenderManager::renderModel(QCAR::State& state) { if(this->vertices && this->normals && this->texcoords && this->modelTexture) { // Get the trackable (only one available) const QCAR::Trackable* trackable = state.getActiveTrackable(0); QCAR::Matrix44F modelViewMatrix = QCAR::Tool::convertPose2GLMatrix(trackable->getPose()); QCAR::Matrix44F modelViewProjection; SampleUtils::scalePoseMatrix(this->scaleFactor, this->scaleFactor, this->scaleFactor, &modelViewMatrix.data[0]); SampleUtils::multiplyMatrix(&projectionMatrix.data[0], &modelViewMatrix.data[0] , &modelViewProjection.data[0]); glUseProgram(shaderProgramID); glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) this->vertices); glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) this->normals); glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) this->texcoords); glEnableVertexAttribArray(vertexHandle); glEnableVertexAttribArray(normalHandle); glEnableVertexAttribArray(textureCoordHandle); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, this->modelTexture->mTextureID); glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (GLfloat*)&modelViewProjection.data[0] ); if(hasIndices) { glDrawElements(GL_TRIANGLES, this->numModelElementsToDraw, GL_UNSIGNED_SHORT, (const GLvoid*) this->indices); } else { glDrawArrays(GL_TRIANGLES, 0, this->numModelElementsToDraw); } } } void RenderManager::renderIndicators(QCAR::State& state) { if(this->numIndicators > 0) { glDisable(GL_DEPTH_TEST); // Get the trackable (only one available) const QCAR::Trackable* trackable = state.getActiveTrackable(0); //setup the indicator texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, this->indicatorTexture->mTextureID); for(int i = 0; i < this->numIndicators; i++) { QCAR::Matrix44F modelViewMatrix = QCAR::Tool::convertPose2GLMatrix(trackable->getPose()); QCAR::Matrix44F modelViewProjection; SampleUtils::translatePoseMatrix(indicators[3 * i] * this->scaleFactor, indicators[3 * i + 1] * this->scaleFactor, indicators[3 * i + 2] * this->scaleFactor, &modelViewMatrix.data[0]); // SampleUtils::scalePoseMatrix(this->scaleFactor, this->scaleFactor, this->scaleFactor, // &modelViewMatrix.data[0]); // SampleUtils::scalePoseMatrix(this->scaleFactor, this->scaleFactor, this->scaleFactor, // &modelViewMatrix.data[0]); SampleUtils::multiplyMatrix(&projectionMatrix.data[0], &modelViewMatrix.data[0] , &modelViewProjection.data[0]); glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &indicatorVertices[0]); glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &indicatorNormals[0]); glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &indicatorTexcoords[0]); glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (GLfloat*)&modelViewProjection.data[0] ); glDrawElements(GL_TRIANGLES, numIndicatorIndices, GL_UNSIGNED_SHORT, (const GLvoid*) &indicatorIndices[0]); } } } void RenderManager::releaseData() { JNIEnv* env = this->renderManagerJavaInterface->getObjectLoader()->getJNIEnv(); if(this->vertices) { env->ReleaseFloatArrayElements(this->jVertices, this->vertices, 0); this->vertices = 0; this->jVertices = 0; } if(this->normals) { env->ReleaseFloatArrayElements(this->jNormals, this->normals, 0); this->normals = 0; this->jNormals; } if(this->texcoords) { env->ReleaseFloatArrayElements(this->jTexcoords, this->texcoords, 0); this->texcoords = 0; this->jTexcoords = 0; } if(this->indices) { env->ReleaseShortArrayElements(this->jIndices, (short*)this->indices, 0); this->indices = 0; this->jIndices = 0; } if(this->modelTexture) { glBindTexture(GL_TEXTURE_2D, 0); glDeleteTextures(1, &(this->modelTexture->mTextureID)); delete this->modelTexture; this->modelTexture = 0; } if(this->indicatorTexture) { glDeleteTextures(1, &(this->indicatorTexture->mTextureID)); delete this->indicatorTexture; this->indicatorTexture = 0; } if(this->indicators) { env->ReleaseFloatArrayElements(this->jIndicators, this->indicators, 0); this->indicators = 0; this->jIndicators = 0; } this->numIndicators = 0; setScaleFactor(1.0f); this->trackableWidth = 0; this->trackableHeight = 0; } void RenderManager::renderFrame() { // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render video background: QCAR::State state = QCAR::Renderer::getInstance().begin(); if(state.getNumActiveTrackables() > 0) { if(this->applicationStateManager->getCurrentApplicationState() == TRACKING) { //focus the trackable QCAR::CameraDevice::getInstance().startAutoFocus(); //set the trackable width and height const QCAR::Trackable* trackable = state.getTrackable(0); if(trackable->isOfType(QCAR::Trackable::IMAGE_TARGET)) { const QCAR::ImageTarget* imageTarget = (const QCAR::ImageTarget*)trackable; this->trackableWidth = imageTarget->getSize().data[0]; this->trackableHeight = imageTarget->getSize().data[1]; } //update application state this->applicationStateManager->setApplicationState(TRACKED); this->scanCounter = 0; } else if(this->applicationStateManager->getCurrentApplicationState() == TRACKED) { ++this->scanCounter; if(scanCounter > 8) { QCAR::CameraDevice::getInstance().startAutoFocus(); this->scanCounter = 0; } scanFrameForBarcode(state); } else if(this->applicationStateManager->getCurrentApplicationState() == SHOWING_CACHE || this->applicationStateManager->getCurrentApplicationState() == LOADING_INDICATORS) { glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); renderModel(state); } else if(this->applicationStateManager->getCurrentApplicationState() == SHOWING) { glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); renderModel(state); renderIndicators(state); } } else if(this->applicationStateManager->getCurrentApplicationState() != TRACKING) { this->applicationStateManager->setApplicationState(TRACKING); releaseData(); } SampleUtils::checkGlError("Augmented Bizz GL error"); glDisable(GL_DEPTH_TEST); glDisableVertexAttribArray(vertexHandle); glDisableVertexAttribArray(normalHandle); glDisableVertexAttribArray(textureCoordHandle); QCAR::Renderer::getInstance().end(); glFinish(); } void RenderManager::configureVideoBackground() { //get the default video mode: QCAR::CameraDevice& cameraDevice = QCAR::CameraDevice::getInstance(); QCAR::VideoMode videoMode = cameraDevice.getVideoMode(QCAR::CameraDevice::MODE_OPTIMIZE_QUALITY); //set frame format QCAR::setFrameFormat(QCAR::RGB565, true); //configure the video background QCAR::VideoBackgroundConfig config; config.mEnabled = true; config.mSynchronous = true; config.mPosition.data[0] = 0.0f; config.mPosition.data[1] = 0.0f; config.mSize.data[0] = screenWidth; config.mSize.data[1] = videoMode.mHeight * (screenWidth / (float)videoMode.mWidth); //set the config: QCAR::Renderer::getInstance().setVideoBackgroundConfig(config); } int RenderManager::getTrackableWidth() { return this->trackableWidth; } int RenderManager::getTrackableHeight() { return this->trackableHeight; } // ************************************************************* RenderManagerJavaInterface::RenderManagerJavaInterface(ObjectLoader* objectLoader, jobject javaRenderManager): \ JavaInterface(objectLoader) { this->javaRenderManager = javaRenderManager; } jclass RenderManagerJavaInterface::getClass() { return this->getObjectLoader()->getObjectClass(this->javaRenderManager); } void RenderManagerJavaInterface::callScanner(unsigned int width, unsigned int height, jbyteArray pixels) { this->getObjectLoader()->getJNIEnv()->CallVoidMethod(this->javaRenderManager, \ this->getCallScannerMethodID(), width, height, pixels); } jmethodID RenderManagerJavaInterface::getCallScannerMethodID() { return this->getMethodID("callScanner", \ "(II[B)V"); }
[ [ [ 1, 11 ], [ 13, 25 ], [ 27, 30 ], [ 34, 43 ], [ 47, 49 ], [ 52, 55 ], [ 57, 64 ], [ 66, 67 ], [ 71, 80 ], [ 83, 83 ], [ 85, 93 ], [ 97, 98 ], [ 117, 121 ], [ 125, 143 ], [ 150, 151 ], [ 155, 155 ], [ 157, 157 ], [ 162, 162 ], [ 166, 205 ], [ 222, 222 ], [ 224, 225 ], [ 230, 230 ], [ 269, 270 ], [ 286, 288 ], [ 297, 297 ], [ 304, 304 ], [ 307, 307 ], [ 309, 309 ], [ 336, 336 ], [ 338, 338 ], [ 340, 341 ], [ 343, 343 ], [ 345, 345 ], [ 360, 360 ], [ 362, 363 ], [ 365, 366 ], [ 406, 406 ], [ 410, 411 ], [ 413, 413 ], [ 423, 428 ], [ 430, 447 ], [ 456, 475 ] ], [ [ 12, 12 ], [ 26, 26 ], [ 31, 33 ], [ 44, 46 ], [ 50, 51 ], [ 56, 56 ], [ 65, 65 ], [ 68, 70 ], [ 81, 82 ], [ 84, 84 ], [ 94, 96 ], [ 99, 116 ], [ 122, 124 ], [ 144, 149 ], [ 152, 154 ], [ 156, 156 ], [ 158, 161 ], [ 163, 165 ], [ 206, 221 ], [ 223, 223 ], [ 226, 229 ], [ 231, 268 ], [ 271, 285 ], [ 289, 296 ], [ 298, 303 ], [ 305, 306 ], [ 308, 308 ], [ 310, 335 ], [ 337, 337 ], [ 339, 339 ], [ 342, 342 ], [ 344, 344 ], [ 346, 359 ], [ 361, 361 ], [ 364, 364 ], [ 367, 405 ], [ 407, 409 ], [ 412, 412 ], [ 414, 422 ], [ 429, 429 ], [ 448, 455 ] ] ]
4222d73768ad91a5bf51cf98791700a4fd17fd77
74fe7bb48df59ebb939e945a1455b7ba630006cd
/Sqrat/sqrat/sqratGlobalMethods.h
745e7aacb6ec4d276b18ba8402394eae2ea11253
[]
no_license
bombpersons/Dokuro2
d032a6bf7ee9039cd613a01d69600593e4b9397c
bde54681b77628ebb972d06190c243e4457158d0
refs/heads/master
2020-05-30T03:16:01.521223
2011-10-17T18:52:02
2011-10-17T18:52:02
2,593,933
1
0
null
null
null
null
UTF-8
C++
false
false
15,409
h
// // SqratGlobalMethods: Global Methods // // // Copyright (c) 2009 Brandon Jones // // 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. // #if !defined(_SCRAT_GLOBAL_METHODS_H_) #define _SCRAT_GLOBAL_METHODS_H_ #include <squirrel.h> #include "sqratTypes.h" namespace Sqrat { // // Squirrel Global Functions // template <class R> class SqGlobal { public: // Arg Count 0 static SQInteger Func0(HSQUIRRELVM vm) { typedef R (*M)(); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); R ret = (*method)(); if(ret == NULL) return 0; PushVar(vm, ret); return 1; } // Arg Count 1 template <class A1, SQInteger startIdx> static SQInteger Func1(HSQUIRRELVM vm) { typedef R (*M)(A1); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); R ret = (*method)( Var<A1>(vm, startIdx).value ); if(ret == NULL) return 0; PushVar(vm, ret); return 1; } // Arg Count 2 template <class A1, class A2, SQInteger startIdx> static SQInteger Func2(HSQUIRRELVM vm) { typedef R (*M)(A1, A2); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); R ret = (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value ); if(ret == NULL) return 0; PushVar(vm, ret); return 1; } // Arg Count 3 template <class A1, class A2, class A3, SQInteger startIdx> static SQInteger Func3(HSQUIRRELVM vm) { typedef R (*M)(A1, A2, A3); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); R ret = (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value ); if(ret == NULL) return 0; PushVar(vm, ret); return 1; } // Arg Count 4 template <class A1, class A2, class A3, class A4, SQInteger startIdx> static SQInteger Func4(HSQUIRRELVM vm) { typedef R (*M)(A1, A2, A3, A4); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); R ret = (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value ); if(ret == NULL) return 0; PushVar(vm, ret); return 1; } // Arg Count 5 template <class A1, class A2, class A3, class A4, class A5, SQInteger startIdx> static SQInteger Func5(HSQUIRRELVM vm) { typedef R (*M)(A1, A2, A3, A4, A5); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); R ret = (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value, Var<A5>(vm, startIdx + 4).value ); if(ret == NULL) return 0; PushVar(vm, ret); return 1; } // Arg Count 6 template <class A1, class A2, class A3, class A4, class A5, class A6, SQInteger startIdx> static SQInteger Func6(HSQUIRRELVM vm) { typedef R (*M)(A1, A2, A3, A4, A5, A6); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); R ret = (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value, Var<A5>(vm, startIdx + 4).value, Var<A6>(vm, startIdx + 5).value ); if(ret == NULL) return 0; PushVar(vm, ret); return 1; } // Arg Count 7 template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, SQInteger startIdx> static SQInteger Func7(HSQUIRRELVM vm) { typedef R (*M)(A1, A2, A3, A4, A5, A6, A7); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); R ret = (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value, Var<A5>(vm, startIdx + 4).value, Var<A6>(vm, startIdx + 5).value, Var<A7>(vm, startIdx + 6).value ); if(ret == NULL) return 0; PushVar(vm, ret); return 1; } // Arg Count 8 template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, SQInteger startIdx> static SQInteger Func8(HSQUIRRELVM vm) { typedef R (*M)(A1, A2, A3, A4, A5, A6, A7, A8); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); R ret = (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value, Var<A5>(vm, startIdx + 4).value, Var<A6>(vm, startIdx + 5).value, Var<A7>(vm, startIdx + 6).value, Var<A8>(vm, startIdx + 7).value ); if(ret == NULL) return 0; PushVar(vm, ret); return 1; } // Arg Count 9 template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, SQInteger startIdx> static SQInteger Func9(HSQUIRRELVM vm) { typedef R (*M)(A1, A2, A3, A4, A5, A6, A7, A8, A9); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); R ret = (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value, Var<A5>(vm, startIdx + 4).value, Var<A6>(vm, startIdx + 5).value, Var<A7>(vm, startIdx + 6).value, Var<A8>(vm, startIdx + 7).value, Var<A9>(vm, startIdx + 8).value ); if(ret == NULL) return 0; PushVar(vm, ret); return 1; } }; // // void return specialization // template <> class SqGlobal<void> { public: // Arg Count 0 static SQInteger Func0(HSQUIRRELVM vm) { typedef void (*M)(); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); (*method)(); return 0; } // Arg Count 1 template <class A1, SQInteger startIdx> static SQInteger Func1(HSQUIRRELVM vm) { typedef void (*M)(A1); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); (*method)( Var<A1>(vm, startIdx).value ); return 0; } // Arg Count 2 template <class A1, class A2, SQInteger startIdx> static SQInteger Func2(HSQUIRRELVM vm) { typedef void (*M)(A1, A2); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value ); return 0; } // Arg Count 3 template <class A1, class A2, class A3, SQInteger startIdx> static SQInteger Func3(HSQUIRRELVM vm) { typedef void (*M)(A1, A2, A3); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value ); return 0; } // Arg Count 4 template <class A1, class A2, class A3, class A4, SQInteger startIdx> static SQInteger Func4(HSQUIRRELVM vm) { typedef void (*M)(A1, A2, A3, A4); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value ); return 0; } // Arg Count 5 template <class A1, class A2, class A3, class A4, class A5, SQInteger startIdx> static SQInteger Func5(HSQUIRRELVM vm) { typedef void (*M)(A1, A2, A3, A4, A5); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value, Var<A5>(vm, startIdx + 4).value ); return 0; } // Arg Count 6 template <class A1, class A2, class A3, class A4, class A5, class A6, SQInteger startIdx> static SQInteger Func6(HSQUIRRELVM vm) { typedef void (*M)(A1, A2, A3, A4, A5, A6); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value, Var<A5>(vm, startIdx + 4).value, Var<A6>(vm, startIdx + 5).value ); return 0; } // Arg Count 7 template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, SQInteger startIdx> static SQInteger Func7(HSQUIRRELVM vm) { typedef void (*M)(A1, A2, A3, A4, A5, A6, A7); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value, Var<A5>(vm, startIdx + 4).value, Var<A6>(vm, startIdx + 5).value, Var<A7>(vm, startIdx + 6).value ); return 0; } // Arg Count 8 template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, SQInteger startIdx> static SQInteger Func8(HSQUIRRELVM vm) { typedef void (*M)(A1, A2, A3, A4, A5, A6, A7, A8); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value, Var<A5>(vm, startIdx + 4).value, Var<A6>(vm, startIdx + 5).value, Var<A7>(vm, startIdx + 6).value, Var<A8>(vm, startIdx + 7).value ); return 0; } // Arg Count 9 template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, SQInteger startIdx> static SQInteger Func9(HSQUIRRELVM vm) { typedef void (*M)(A1, A2, A3, A4, A5, A6, A7, A8, A9); M* method; sq_getuserdata(vm, -1, (SQUserPointer*)&method, NULL); (*method)( Var<A1>(vm, startIdx).value, Var<A2>(vm, startIdx + 1).value, Var<A3>(vm, startIdx + 2).value, Var<A4>(vm, startIdx + 3).value, Var<A5>(vm, startIdx + 4).value, Var<A6>(vm, startIdx + 5).value, Var<A7>(vm, startIdx + 6).value, Var<A8>(vm, startIdx + 7).value, Var<A9>(vm, startIdx + 8).value ); return 0; } }; // // Global Function Resolvers // // Arg Count 0 template <class R> SQFUNCTION SqGlobalFunc(R (*method)()) { return &SqGlobal<R>::Func0; } // Arg Count 1 template <class R, class A1> SQFUNCTION SqGlobalFunc(R (*method)(A1)) { return &SqGlobal<R>::template Func1<A1, 2>; } // Arg Count 2 template <class R, class A1, class A2> SQFUNCTION SqGlobalFunc(R (*method)(A1, A2)) { return &SqGlobal<R>::template Func2<A1, A2, 2>; } // Arg Count 3 template <class R, class A1, class A2, class A3> SQFUNCTION SqGlobalFunc(R (*method)(A1, A2, A3)) { return &SqGlobal<R>::template Func3<A1, A2, A3, 2>; } // Arg Count 4 template <class R, class A1, class A2, class A3, class A4> SQFUNCTION SqGlobalFunc(R (*method)(A1, A2, A3, A4)) { return &SqGlobal<R>::template Func4<A1, A2, A3, A4, 2>; } // Arg Count 5 template <class R, class A1, class A2, class A3, class A4, class A5> SQFUNCTION SqGlobalFunc(R (*method)(A1, A2, A3, A4, A5)) { return &SqGlobal<R>::template Func5<A1, A2, A3, A4, A5, 2>; } // Arg Count 6 template <class R, class A1, class A2, class A3, class A4, class A5, class A6> SQFUNCTION SqGlobalFunc(R (*method)(A1, A2, A3, A4, A5, A6)) { return &SqGlobal<R>::template Func6<A1, A2, A3, A4, A5, A6, 2>; } // Arg Count 7 template <class R, class A1, class A2, class A3, class A4, class A5, class A6, class A7> SQFUNCTION SqGlobalFunc(R (*method)(A1, A2, A3, A4, A5, A6, A7)) { return &SqGlobal<R>::template Func7<A1, A2, A3, A4, A5, A6, A7, 2>; } // Arg Count 8 template <class R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> SQFUNCTION SqGlobalFunc(R (*method)(A1, A2, A3, A4, A5, A6, A7, A8)) { return &SqGlobal<R>::template Func8<A1, A2, A3, A4, A5, A6, A7, A8, 2>; } // Arg Count 9 template <class R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> SQFUNCTION SqGlobalFunc(R (*method)(A1, A2, A3, A4, A5, A6, A7, A8, A9)) { return &SqGlobal<R>::template Func9<A1, A2, A3, A4, A5, A6, A7, A8, A9, 2>; } // // Member Global Function Resolvers // // Arg Count 1 template <class R, class A1> SQFUNCTION SqMemberGlobalFunc(R (*method)(A1)) { return &SqGlobal<R>::template Func1<A1, 1>; } // Arg Count 2 template <class R, class A1, class A2> SQFUNCTION SqMemberGlobalFunc(R (*method)(A1, A2)) { return &SqGlobal<R>::template Func2<A1, A2, 1>; } // Arg Count 3 template <class R, class A1, class A2, class A3> SQFUNCTION SqMemberGlobalFunc(R (*method)(A1, A2, A3)) { return &SqGlobal<R>::template Func3<A1, A2, A3, 1>; } // Arg Count 4 template <class R, class A1, class A2, class A3, class A4> SQFUNCTION SqMemberGlobalFunc(R (*method)(A1, A2, A3, A4)) { return &SqGlobal<R>::template Func4<A1, A2, A3, A4, 1>; } // Arg Count 5 template <class R, class A1, class A2, class A3, class A4, class A5> SQFUNCTION SqMemberGlobalFunc(R (*method)(A1, A2, A3, A4, A5)) { return &SqGlobal<R>::template Func5<A1, A2, A3, A4, A5, 1>; } // Arg Count 6 template <class R, class A1, class A2, class A3, class A4, class A5, class A6> SQFUNCTION SqMemberGlobalFunc(R (*method)(A1, A2, A3, A4, A5, A6)) { return &SqGlobal<R>::template Func6<A1, A2, A3, A4, A5, A6, 1>; } // Arg Count 7 template <class R, class A1, class A2, class A3, class A4, class A5, class A6, class A7> SQFUNCTION SqMemberGlobalFunc(R (*method)(A1, A2, A3, A4, A5, A6, A7)) { return &SqGlobal<R>::template Func7<A1, A2, A3, A4, A5, A6, A7, 1>; } // Arg Count 8 template <class R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> SQFUNCTION SqMemberGlobalFunc(R (*method)(A1, A2, A3, A4, A5, A6, A7, A8)) { return &SqGlobal<R>::template Func8<A1, A2, A3, A4, A5, A6, A7, A8, 1>; } // Arg Count 9 template <class R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> SQFUNCTION SqMemberGlobalFunc(R (*method)(A1, A2, A3, A4, A5, A6, A7, A8, A9)) { return &SqGlobal<R>::template Func9<A1, A2, A3, A4, A5, A6, A7, A8, A9, 1>; } } #endif
[ [ [ 1, 543 ] ] ]
6544c81f6516311bada5a7f561c3dca0d9c9c358
99c9bf812e25e951f043ebded998a9118051c5e4
/box2d-read-only/Box2D/Box2D/Dynamics/b2WorldCallbacks.h
7a864301f868dda1897e8d0c53bcc354b2d63ed9
[ "Zlib" ]
permissive
BigBadOwl/iPhone-Physics
b20cb1991394de0e19c52f314d92cabda50a23ec
ff7f5e98ea5828f0f5388ac5306ea4099a3f0d1d
refs/heads/master
2016-09-03T07:13:16.938271
2011-03-11T13:30:35
2011-03-11T13:30:35
1,467,940
0
0
null
null
null
null
UTF-8
C++
false
false
5,971
h
/* * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_WORLD_CALLBACKS_H #define B2_WORLD_CALLBACKS_H #include <Box2D/Common/b2Settings.h> struct b2Vec2; struct b2Transform; class b2Fixture; class b2Body; class b2Joint; class b2Contact; struct b2ContactResult; struct b2Manifold; /// Joints and fixtures are destroyed when their associated /// body is destroyed. Implement this listener so that you /// may nullify references to these joints and shapes. class b2DestructionListener { public: virtual ~b2DestructionListener() {} /// Called when any joint is about to be destroyed due /// to the destruction of one of its attached bodies. virtual void SayGoodbye(b2Joint* joint) = 0; /// Called when any fixture is about to be destroyed due /// to the destruction of its parent body. virtual void SayGoodbye(b2Fixture* fixture) = 0; }; /// Implement this class to provide collision filtering. In other words, you can implement /// this class if you want finer control over contact creation. class b2ContactFilter { public: virtual ~b2ContactFilter() {} /// Return true if contact calculations should be performed between these two shapes. /// @warning for performance reasons this is only called when the AABBs begin to overlap. virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB); }; /// Contact impulses for reporting. Impulses are used instead of forces because /// sub-step forces may approach infinity for rigid body collisions. These /// match up one-to-one with the contact points in b2Manifold. struct b2ContactImpulse { float32 normalImpulses[b2_maxManifoldPoints]; float32 tangentImpulses[b2_maxManifoldPoints]; }; /// Implement this class to get contact information. You can use these results for /// things like sounds and game logic. You can also get contact results by /// traversing the contact lists after the time step. However, you might miss /// some contacts because continuous physics leads to sub-stepping. /// Additionally you may receive multiple callbacks for the same contact in a /// single time step. /// You should strive to make your callbacks efficient because there may be /// many callbacks per time step. /// @warning You cannot create/destroy Box2D entities inside these callbacks. class b2ContactListener { public: virtual ~b2ContactListener() {} /// Called when two fixtures begin to touch. virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); } /// Called when two fixtures cease to touch. virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); } /// This is called after a contact is updated. This allows you to inspect a /// contact before it goes to the solver. If you are careful, you can modify the /// contact manifold (e.g. disable contact). /// A copy of the old manifold is provided so that you can detect changes. /// Note: this is called only for awake bodies. /// Note: this is called even when the number of contact points is zero. /// Note: this is not called for sensors. /// Note: if you set the number of contact points to zero, you will not /// get an EndContact callback. However, you may get a BeginContact callback /// the next step. virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { B2_NOT_USED(contact); B2_NOT_USED(oldManifold); } /// This lets you inspect a contact after the solver is finished. This is useful /// for inspecting impulses. /// Note: the contact manifold does not include time of impact impulses, which can be /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly /// in a separate data structure. /// Note: this is only called for contacts that are touching, solid, and awake. virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) { B2_NOT_USED(contact); B2_NOT_USED(impulse); } }; /// Callback class for AABB queries. /// See b2World::Query class b2QueryCallback { public: virtual ~b2QueryCallback() {} /// Called for each fixture found in the query AABB. /// @return false to terminate the query. virtual bool ReportFixture(b2Fixture* fixture) = 0; }; /// Callback class for ray casts. /// See b2World::RayCast class b2RayCastCallback { public: virtual ~b2RayCastCallback() {} /// Called for each fixture found in the query. You control how the ray cast /// proceeds by returning a float: /// return -1: ignore this fixture and continue /// return 0: terminate the ray cast /// return fraction: clip the ray to this point /// return 1: don't clip the ray and continue /// @param fixture the fixture hit by the ray /// @param point the point of initial intersection /// @param normal the normal vector at the point of intersection /// @return -1 to filter, 0 to terminate, fraction to clip the ray for /// closest hit, 1 to continue virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction) = 0; }; #endif
[ [ [ 1, 154 ] ] ]
2897722f4ff4f515954003e7633eef1d811cd11c
11ba7667109ae553162c7329bcd2f4902d841a66
/AugmentedTowerDefense/include/SharedStuff.h
63eeb680d8b827c393b72819b22df19f6a79e2c1
[]
no_license
abmantis/AugmentedTowerDefense
3cd8761034a98667a34650f6a476beb59aa7e818
00008495f538e0d982c0eae3025d02ae21e3dee2
refs/heads/master
2021-01-01T18:37:10.678181
2011-02-09T23:09:51
2011-02-09T23:09:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,085
h
#ifndef SharedStuff_h__ #define SharedStuff_h__ #pragma once namespace AugmentedTowerDefense { class HelperClass { public: HelperClass(void); virtual ~HelperClass(void); static void CreateAxis(Ogre::SceneManager *sceneMgr); static void CreateLineAxis(Ogre::SceneManager *sceneMgr); static void CreateLine(Ogre::SceneManager *sceneMgr, Ogre::Vector3 start, Ogre::Vector3 end); static void Print(Ogre::Vector3 vector3, std::string prefix = "", std::string sufix = "\n"); static void Print(Ogre::Matrix4 matrix4, std::string prefix = "", std::string sufix = "\n"); static std::string ToString(int iVal); static std::string ToString(Ogre::Vector3 vector3); static std::string ToString(Ogre::Vector2 vector2); static void DestroyAllAttachedMovableObjects(Ogre::SceneNode* pNode); static void DoSafeRotation(Ogre::SceneNode *pNode, Ogre::Vector3 src, Ogre::Vector3 direction); }; enum QueryFlags { MASK_NONE = 0, MASK_WALLS = 1<<0, MASK_TOWER = 1<<1, MASK_DEFAULT = 1<<31 }; } #endif // SharedStuff_h__
[ [ [ 1, 36 ] ] ]
574570da0737ec8b9b5a6dc069e920c15e03f064
4fb3fd0e919953153d4d7102faa7e73b022ec58b
/Client/GUI/main.cpp
6be8ed254d78016fa7cfb1689b96ae04f25ac040
[]
no_license
seagel/cppchat
3062092a02fc0827cc42238320bda1a20535aa22
726bbfd13ddef3e5e3e5b13e32086be2ceb4cf72
refs/heads/master
2021-01-10T04:14:31.971383
2008-04-14T16:16:03
2008-04-14T16:16:03
49,497,663
0
0
null
null
null
null
ISO-8859-2
C++
false
false
534
cpp
/* A program ezen része általában senkinek nem érdekes*/ /*egyelőre nem müxik rendesen, csak a chat ablakot próbálja ki -szk 2008.03.18*/ #include <QApplication> #include "MyMainWindow\MyMainWindow.h" #include "ChatWindow\ChatWindow.h" int main(int argc, char *argv[]){ qDebug("Starting program: main"); QApplication app(argc, argv); MyMainWindow mainWindow; mainWindow.show(); mainWindow.changeToSignInWindow(); mainWindow.resize(500,500); //ChatWindow chat; //chat.show(); return app.exec(); }
[ "szkster@bcad9747-8f48-0410-af98-7d41fdaa9659" ]
[ [ [ 1, 19 ] ] ]
246df2c65d6f9432434514c04e44c475472935d2
d2996420f8c3a6bbeef63a311dd6adc4acc40436
/src/server/ServerCalculations.h
b25eeef7342b96ab2649c0583de4f84071af34fd
[]
no_license
aruwen/graviator
4d2e06e475492102fbf5d65754be33af641c0d6c
9a881db9bb0f0de2e38591478429626ab8030e1d
refs/heads/master
2021-01-19T00:13:10.843905
2011-03-13T13:15:25
2011-03-13T13:15:25
32,136,578
0
0
null
null
null
null
UTF-8
C++
false
false
2,074
h
//********************************************************* // Graviator - QPT2a - FH Salzburg // Stefan Ebner - Malte Langkabel - Christian Winkler // // Calculations // contains calculations and objects of the game logic // //********************************************************* #ifndef SERVER_CALCULATIONS_H #define SERVER_CALCULATIONS_H #include "ServerObjectFactory.h" #include "ServerPlayer.h" #include "ServerGravitationalObject.h" #include "LuaStateManager.h" #include "../GraviatorSimpleTypes.h" #include "../src/vec3f.h" #include "../src/Timer.h" #include "../PrecisionTimer.h" #include <map> #include <deque> #include <set> using namespace std; typedef ServerObjectFactory<ServerPlayer> PlayerFactory; typedef ServerObjectFactory<ServerGravitationalObject> ObjectFactory; class ServerCalculations { public: ServerCalculations(void); ~ServerCalculations(void); void runCalculations(); unsigned int createPlayer(); void spawnPlayer(unsigned int id); void deletePlayer(unsigned int id); void handleInput(vec3f camera, bool shooting, bool left, bool right, unsigned int playerId); void deleteObject(unsigned int id); unsigned int getScoreLimit(); unsigned int getNextHighestScore(unsigned int playerId); // ServerNetworkHandler needs full access to this 2 maps map<unsigned int, ServerGravitationalObject*> mCurrentObjects; map<unsigned int, ServerPlayer*> mCurrentPlayers; private: unsigned int getNextUsableId(); void createObject(const char* type, vec3f position); vec3f getNextUsablePosition(); vec3f getDefaultVelocity( vec3f position ); bool doesPlayerCollideWithArenaBounds(vec3f position); void recalcVelocityAndPositionAtArenaBounds(vec3f &velocity, vec3f &position); vec3f getPointOfImpact(vec3f position, vec3f orientation); deque<unsigned int> mNextIdToUse; int mIdCounter; float mStartTimer; Timer mTimer; unsigned int mScoreLimit; float mKillRange; float mSteeringPointDistance; float mFriction; }; #endif
[ "[email protected]@c8d5bfcc-1391-a108-90e5-e810ef6ef867" ]
[ [ [ 1, 74 ] ] ]
5d5012dfd976fc40e5b09c2cfdbfa80411531bf4
bf278d024957a59c6f1efb36aa8b76069eff22a5
/dlginvestigate.h
1b331370840062e9e41fb446a3ec6668c34bed97
[ "BSD-3-Clause", "BSL-1.0" ]
permissive
byplayer/yamy
b84741fe738f5abac33edb934951ea91454fb4ca
031e57e81caeb881a0a219e2a11429795a59d845
refs/heads/master
2020-05-22T12:46:55.516053
2010-05-19T15:57:38
2010-05-19T15:57:38
3,842,546
6
0
null
null
null
null
UTF-8
C++
false
false
621
h
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // dlginvestigate.h #ifndef _DLGINVESTIGATE_H # define _DLGINVESTIGATE_H # include <windows.h> /// dialog procedure of "Investigate" dialog box #ifdef MAYU64 INT_PTR CALLBACK dlgInvestigate_dlgProc( #else BOOL CALLBACK dlgInvestigate_dlgProc( #endif HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam); class Engine; /// parameters for "Investigate" dialog box class DlgInvestigateData { public: Engine *m_engine; /// engine HWND m_hwndLog; /// log }; #endif // !_DLGINVESTIGATE_H
[ [ [ 1, 29 ] ] ]
6417acf93f1349cd51a3b461ebd713e68709fcb3
944e19e1a68ac1d4c5f6e7ccde1061a43e791887
/OBBDetection/OBBDetection/renderer.h
faea13b3e4dfc2d3d2557e6a6975160aea163894
[]
no_license
Fredrib/obbdetection
0a797ecac2c24be1a75ddd67fd928e35ddc586f5
41e065c379ddfb7ec0ca4ec0616be5204736b984
refs/heads/master
2020-04-22T14:03:17.358440
2011-01-17T15:24:09
2011-01-17T15:24:09
41,830,450
1
0
null
null
null
null
UTF-8
C++
false
false
2,434
h
/************************************************************* ** OBBDetection Renderer ** ** -> Graphics Rendering functions, Summer 2009 ** *************************************************************/ // File: renderer.h // Author: Jonathan Tompson // e-mail: [email protected] or [email protected] #ifndef renderer_h #define renderer_h #include "main.h" #include "DrawableTex2D.h" #include "obbox.h" #include "debug_object.h" class debug_object; class renderer { public: renderer(void); // Default Constructor ~renderer(void); // Destructor Destructor void InitRenderer(void); void RenderFrame(void); void buildFX(void); void onResetDevice(void); void onLostDevice(void); void drawShadowMap(void); void InitWireframeRendering(void); void DrawWireframe(IDirect3DVertexBuffer9 * vertBuff, DWORD vertSize, IDirect3DIndexBuffer9 * indBuff, DWORD indSize, D3DXMATRIX * mat); void DrawWireframeLines(IDirect3DVertexBuffer9 * vertBuff, DWORD vertSize, IDirect3DIndexBuffer9 * indBuff, DWORD indSize, D3DXMATRIX * mat); // Next 2 are for color wireframe rendering (added later) void DrawWireframeCol(IDirect3DVertexBuffer9 * vertBuff, DWORD vertSize, IDirect3DIndexBuffer9 * indBuff, DWORD indSize, D3DXMATRIX * mat); void DrawWireframeColLines(IDirect3DVertexBuffer9 * vertBuff, DWORD vertSize, IDirect3DIndexBuffer9 * indBuff, DWORD indSize, D3DXMATRIX * mat); // D3D Effects - less overhead if public ID3DXEffect* m_FX; ID3DXEffect* m_wireFrameFX; ID3DXEffect* m_wireFrameColFX; int m_shaderVersion; // FX Handles - less overhead if public D3DXHANDLE m_hTech, m_hBuildShadowMapTech, m_hLightWVP, m_hWVP, m_hWorld, m_hMtrl, m_hLight, m_hEyePosW, m_hTex, m_hShadowMap, m_hShadowMapSize, m_hWireFrame, m_hWireFrameCol, m_hWireFrameWVP, m_hWireFrameColWVP; IDirect3DTexture9* m_WhiteTex; debug_object * debug_objects; private: D3DXMATRIX m_matProjection; // projection matrix float m_fAspectRatio, // viewport ratio m_fFieldOfView, // view angle m_fNearPlane, // near clipping plane m_fFarPlane; // far clipping plane DrawableTex2D* m_ShadowMap; }; #endif
[ "jonathantompson@5e2a6976-228a-6e25-3d16-ad1625af6446" ]
[ [ [ 1, 74 ] ] ]
6945ec165567075559314b9b82c733d73969a7d6
aaf948c90deab2eb13c4c19b28a0c8c0641d7dc0
/mainwindow.cpp
41d79ff72c1c4dff059e1e39fd7c945c4a21c631
[]
no_license
abbradar/VisualPresent
29e67b3123320fff6a24d386fbe7b6117878f18b
04fe9d8ae9dba4b0914fe43a7975fcf151825a18
refs/heads/master
2022-11-06T02:52:45.477811
2011-06-20T20:41:18
2011-06-20T20:41:18
274,765,702
0
0
null
null
null
null
UTF-8
C++
false
false
7,751
cpp
#include <QScrollBar> #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { this->ui->setupUi(this); this->client = new VPClient(this); this->server = new VPServer(this); QObject::connect(this->client, SIGNAL(connectedToHost()), this, SLOT(client_connected())); QObject::connect(this->client, SIGNAL(disconnectedFromHost()), this, SLOT(client_disconnected())); QObject::connect(this->client, SIGNAL(textChanged()), this, SLOT(client_text_changed())); QObject::connect(this->client, SIGNAL(highlightChanged()), this, SLOT(client_highlight_changed())); this->timer = new QTimer(this); QObject::connect(this->timer, SIGNAL(timeout()), this, SLOT(timer_timeout())); this->timer->setInterval(1000); this->oldText = new QString(); QPalette textColors = this->ui->textEdit_main->palette(); textColors.setColor(QPalette::Inactive, QPalette::Highlight, textColors. color(QPalette::Active, QPalette::Highlight)); textColors.setColor(QPalette::Inactive, QPalette::HighlightedText, textColors.color(QPalette::Active, QPalette::HighlightedText)); this->ui->textEdit_main->setPalette(textColors); this->ui->fontComboBox->setCurrentFont(this->ui->textEdit_main->font()); } MainWindow::~MainWindow() { delete this->timer; delete this->client; delete this->server; delete this->oldText; delete this->ui; } void MainWindow::on_pushButton_server_clicked() { if (this->server->isListening()) { this->timer->stop(); this->server->stop(); this->ui->textEdit_main->clear(); this->ui->textEdit_main->setReadOnly(true); this->ui->formatButtons->setEnabled(false); this->ui->fontComboBox->setCurrentFont(this->ui-> textEdit_main->font()); this->ui->groupBox_client->setEnabled(true); this->ui->pushButton_server->setText(QString::fromUtf8("Включить")); } else { if (!this->server->start(this->ui->spinBox_serverPort->value())) { return; } this->ui->groupBox_client->setEnabled(false); this->oldText->clear(); this->oldHStart = 0; this->oldHEnd = 0; this->cursorChanging = false; this->timer->start(); this->ui->textEdit_main->setReadOnly(false); this->ui->formatButtons->setEnabled(true); this->ui->pushButton_server->setText(QString::fromUtf8("Отключить")); this->ui->tabWidget->setCurrentWidget(this->ui->tab_text); } } void MainWindow::on_pushButton_client_clicked() { if (this->client->isConnected()) { this->client->disconnectFromHost(); } else { this->ui->groupBox_server->setEnabled(false); this->ui->pushButton_client->setEnabled(false); this->ui->lineEdit_clientHost->setReadOnly(true); this->client->connectToHost( this->ui->lineEdit_clientHost->text(), this->ui->spinBox_clientPort->value()); } } void MainWindow::client_connected() { this->ui->tabWidget->setCurrentWidget(this->ui->tab_text); this->ui->pushButton_client->setEnabled(true); this->ui->pushButton_client->setText(QString::fromUtf8("Отключиться")); } void MainWindow::client_disconnected() { this->ui->tabWidget->setCurrentWidget(this->ui->tab_settings); this->ui->textEdit_main->clear(); this->ui->pushButton_client->setText(QString::fromUtf8("Подключиться")); this->ui->pushButton_client->setEnabled(true); this->ui->lineEdit_clientHost->setReadOnly(false); this->ui->groupBox_server->setEnabled(true); } void MainWindow::client_text_changed() { int hPos = this->ui->textEdit_main->horizontalScrollBar()->value(); int vPos = this->ui->textEdit_main->verticalScrollBar()->value(); this->ui->textEdit_main->setHtml(this->client->getText()); QTextCursor current = this->ui->textEdit_main->textCursor(); current.setPosition(this->client->getHighlightStart(), QTextCursor::MoveAnchor); current.setPosition(this->client->getHighlightEnd(), QTextCursor::KeepAnchor); this->ui->textEdit_main->setTextCursor(current); if (this->ui->checkBox_followCursor->checkState() != Qt::Checked) { this->ui->textEdit_main->horizontalScrollBar()->setValue(hPos); this->ui->textEdit_main->verticalScrollBar()->setValue(vPos); } } \ void MainWindow::client_highlight_changed() { int hPos = this->ui->textEdit_main->horizontalScrollBar()->value(); int vPos = this->ui->textEdit_main->verticalScrollBar()->value(); QTextCursor current = this->ui->textEdit_main->textCursor(); current.setPosition(this->client->getHighlightStart(), QTextCursor::MoveAnchor); current.setPosition(this->client->getHighlightEnd(), QTextCursor::KeepAnchor); this->ui->textEdit_main->setTextCursor(current); if (this->ui->checkBox_followCursor->checkState() != Qt::Checked) { this->ui->textEdit_main->horizontalScrollBar()->setValue(hPos); this->ui->textEdit_main->verticalScrollBar()->setValue(vPos); } } void MainWindow::timer_timeout() { this->timer->stop(); QString text = this->ui->textEdit_main->toHtml(); if (text != *(oldText)) { this->server->setText(this->ui->textEdit_main->toHtml()); *(oldText) = text; } QTextCursor cursor = this->ui->textEdit_main->textCursor(); int hStart = cursor.selectionStart(); int hEnd = cursor.selectionEnd(); if (hStart != oldHStart || hEnd != oldHEnd) { this->server->setHighlight(hStart, hEnd); oldHStart = hStart; oldHEnd = hEnd; } this->timer->start(); } void MainWindow::on_toolButton_Bold_clicked() { QFont font = this->ui->textEdit_main->currentFont(); font.setBold(!font.bold()); this->ui->textEdit_main->setCurrentFont(font); } void MainWindow::on_toolButton_Italic_clicked() { this->ui->textEdit_main->setFontItalic(!this->ui->textEdit_main-> fontItalic()); } void MainWindow::on_toolButton_Underline_clicked() { this->ui->textEdit_main->setFontUnderline(!this->ui->textEdit_main-> fontUnderline()); } void MainWindow::on_toolButton_Overline_clicked() { QFont font = this->ui->textEdit_main->currentFont(); font.setOverline(!font.overline()); this->ui->textEdit_main->setCurrentFont(font); } void MainWindow::on_fontComboBox_currentFontChanged(QFont f) { if (!this->cursorChanging) { this->ui->textEdit_main->setFontFamily(f.family()); } } void MainWindow::on_textEdit_main_cursorPositionChanged() { QFont font = this->ui->textEdit_main->currentFont(); this->ui->toolButton_Bold->setChecked(font.bold()); this->ui->toolButton_Italic->setChecked(font.italic()); this->ui->toolButton_Underline->setChecked(font.underline()); this->ui->toolButton_Overline->setChecked(font.overline()); this->cursorChanging = true; this->ui->fontComboBox->setCurrentFont(this->ui->textEdit_main-> fontFamily()); this->cursorChanging = false; }
[ [ [ 1, 202 ] ] ]
cac335045a256c7ff3f54d525651bf5a3a8ab6d2
6581dacb25182f7f5d7afb39975dc622914defc7
/easyMule/easyMule/src/WorkLayer/SharedFileList.cpp
2cf4223819ec617522322e8fc34c65d1a7a92cf0
[]
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
GB18030
C++
false
false
60,649
cpp
/* * $Id: SharedFileList.cpp 18233 2010-03-03 04:31:13Z huby $ * * this file is part of eMule * Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "stdafx.h" #include <io.h> //#include "emule.h" #include "SharedFileList.h" #include "KnownFileList.h" #include "Packets.h" #include "Kademlia/Kademlia/Kademlia.h" #include "kademlia/kademlia/search.h" #include "kademlia/kademlia/SearchManager.h" #include "kademlia/kademlia/prefs.h" #include "DownloadQueue.h" #include "Statistics.h" #include "Preferences.h" #include "OtherFunctions.h" #include "KnownFile.h" #include "Sockets.h" #include "SafeFile.h" #include "Server.h" #include "UpDownClient.h" #include "PartFile.h" //#include "emuledlg.h" //#include "SharedFilesWnd.h" #include "StringConversion.h" #include "ClientList.h" #include "Log.h" #include "Collection.h" #include "kademlia/kademlia/UDPFirewallTester.h" #include "md5sum.h" #include "GlobalVariable.h" #include "UIMessage.h" #include "resource.h" #include "DynamicPref.h" #include "ini2.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif typedef CSimpleArray<CKnownFile*> CSimpleKnownFileArray; /////////////////////////////////////////////////////////////////////////////// // CPublishKeyword class CPublishKeyword { public: CPublishKeyword(const CStringW& rstrKeyword) { m_strKeyword = rstrKeyword; // min. keyword char is allowed to be < 3 in some cases (see also 'CSearchManager::GetWords') //ASSERT( rstrKeyword.GetLength() >= 3 ); ASSERT( !rstrKeyword.IsEmpty() ); KadGetKeywordHash(rstrKeyword, &m_nKadID); SetNextPublishTime(0); SetPublishedCount(0); } const Kademlia::CUInt128& GetKadID() const { return m_nKadID; } const CStringW& GetKeyword() const { return m_strKeyword; } int GetRefCount() const { return m_aFiles.GetSize(); } const CSimpleKnownFileArray& GetReferences() const { return m_aFiles; } UINT GetNextPublishTime() const { return m_tNextPublishTime; } void SetNextPublishTime(UINT tNextPublishTime) { m_tNextPublishTime = tNextPublishTime; } UINT GetPublishedCount() const { return m_uPublishedCount; } void SetPublishedCount(UINT uPublishedCount) { m_uPublishedCount = uPublishedCount; } void IncPublishedCount() { m_uPublishedCount++; } BOOL AddRef(CKnownFile* pFile) { if (m_aFiles.Find(pFile) != -1) { return FALSE; } return m_aFiles.Add(pFile); } int RemoveRef(CKnownFile* pFile) { m_aFiles.Remove(pFile); return m_aFiles.GetSize(); } void RemoveAllReferences() { m_aFiles.RemoveAll(); } void RotateReferences(int iRotateSize) { if (m_aFiles.GetSize() > iRotateSize) { CKnownFile** ppRotated = (CKnownFile**)malloc(m_aFiles.m_nAllocSize * sizeof(*m_aFiles.GetData())); if (ppRotated != NULL) { memcpy(ppRotated, m_aFiles.GetData() + iRotateSize, (m_aFiles.GetSize() - iRotateSize) * sizeof(*m_aFiles.GetData())); memcpy(ppRotated + m_aFiles.GetSize() - iRotateSize, m_aFiles.GetData(), iRotateSize * sizeof(*m_aFiles.GetData())); free(m_aFiles.GetData()); m_aFiles.m_aT = ppRotated; } } } protected: CStringW m_strKeyword; Kademlia::CUInt128 m_nKadID; UINT m_tNextPublishTime; UINT m_uPublishedCount; CSimpleKnownFileArray m_aFiles; }; /////////////////////////////////////////////////////////////////////////////// // CPublishKeywordList class CPublishKeywordList { public: CPublishKeywordList(); ~CPublishKeywordList(); void AddKeywords(CKnownFile* pFile); void RemoveKeywords(CKnownFile* pFile); void RemoveAllKeywords(); void RemoveAllKeywordReferences(); void PurgeUnreferencedKeywords(); int GetCount() const { return m_lstKeywords.GetCount(); } CPublishKeyword* GetNextKeyword(); void ResetNextKeyword(); UINT GetNextPublishTime() const { return m_tNextPublishKeywordTime; } void SetNextPublishTime(UINT tNextPublishKeywordTime) { m_tNextPublishKeywordTime = tNextPublishKeywordTime; } #ifdef _DEBUG void Dump(); #endif protected: // can't use a CMap - too many disadvantages in processing the 'list' //CTypedPtrMap<CMapStringToPtr, CString, CPublishKeyword*> m_lstKeywords; CTypedPtrList<CPtrList, CPublishKeyword*> m_lstKeywords; POSITION m_posNextKeyword; UINT m_tNextPublishKeywordTime; CPublishKeyword* FindKeyword(const CStringW& rstrKeyword, POSITION* ppos = NULL) const; }; CPublishKeywordList::CPublishKeywordList() { ResetNextKeyword(); SetNextPublishTime(0); } CPublishKeywordList::~CPublishKeywordList() { RemoveAllKeywords(); } CPublishKeyword* CPublishKeywordList::GetNextKeyword() { if (m_posNextKeyword == NULL) { m_posNextKeyword = m_lstKeywords.GetHeadPosition(); if (m_posNextKeyword == NULL) return NULL; } return m_lstKeywords.GetNext(m_posNextKeyword); } void CPublishKeywordList::ResetNextKeyword() { m_posNextKeyword = m_lstKeywords.GetHeadPosition(); } CPublishKeyword* CPublishKeywordList::FindKeyword(const CStringW& rstrKeyword, POSITION* ppos) const { POSITION pos = m_lstKeywords.GetHeadPosition(); while (pos) { POSITION posLast = pos; CPublishKeyword* pPubKw = m_lstKeywords.GetNext(pos); if (pPubKw->GetKeyword() == rstrKeyword) { if (ppos) *ppos = posLast; return pPubKw; } } return NULL; } void CPublishKeywordList::AddKeywords(CKnownFile* pFile) { const Kademlia::WordList& wordlist = pFile->GetKadKeywords(); //ASSERT( wordlist.size() > 0 ); Kademlia::WordList::const_iterator it; for (it = wordlist.begin(); it != wordlist.end(); it++) { const CStringW& strKeyword = *it; CPublishKeyword* pPubKw = FindKeyword(strKeyword); if (pPubKw == NULL) { pPubKw = new CPublishKeyword(strKeyword); m_lstKeywords.AddTail(pPubKw); SetNextPublishTime(0); } if(pPubKw->AddRef(pFile) && pPubKw->GetNextPublishTime() > MIN2S(30)) { // User may be adding and removing files, so if this is a keyword that // has already been published, we reduce the time, but still give the user // enough time to finish what they are doing. // If this is a hot node, the Load list will prevent from republishing. pPubKw->SetNextPublishTime(MIN2S(30)); } } } void CPublishKeywordList::RemoveKeywords(CKnownFile* pFile) { const Kademlia::WordList& wordlist = pFile->GetKadKeywords(); //ASSERT( wordlist.size() > 0 ); Kademlia::WordList::const_iterator it; for (it = wordlist.begin(); it != wordlist.end(); it++) { const CStringW& strKeyword = *it; POSITION pos; CPublishKeyword* pPubKw = FindKeyword(strKeyword, &pos); if (pPubKw != NULL) { if (pPubKw->RemoveRef(pFile) == 0) { if (pos == m_posNextKeyword) (void)m_lstKeywords.GetNext(m_posNextKeyword); m_lstKeywords.RemoveAt(pos); delete pPubKw; SetNextPublishTime(0); } } } } void CPublishKeywordList::RemoveAllKeywords() { POSITION pos = m_lstKeywords.GetHeadPosition(); while (pos) delete m_lstKeywords.GetNext(pos); m_lstKeywords.RemoveAll(); ResetNextKeyword(); SetNextPublishTime(0); } void CPublishKeywordList::RemoveAllKeywordReferences() { POSITION pos = m_lstKeywords.GetHeadPosition(); while (pos) m_lstKeywords.GetNext(pos)->RemoveAllReferences(); } void CPublishKeywordList::PurgeUnreferencedKeywords() { POSITION pos = m_lstKeywords.GetHeadPosition(); while (pos) { POSITION posLast = pos; CPublishKeyword* pPubKw = m_lstKeywords.GetNext(pos); if (pPubKw->GetRefCount() == 0) { if (posLast == m_posNextKeyword) (void)m_lstKeywords.GetNext(m_posNextKeyword); m_lstKeywords.RemoveAt(posLast); delete pPubKw; SetNextPublishTime(0); } } } #ifdef _DEBUG void CPublishKeywordList::Dump() { int i = 0; POSITION pos = m_lstKeywords.GetHeadPosition(); while (pos) { CPublishKeyword* pPubKw = m_lstKeywords.GetNext(pos); TRACE(_T("%3u: %-10ls ref=%u %s\n"), i, pPubKw->GetKeyword(), pPubKw->GetRefCount(), CastSecondsToHM(pPubKw->GetNextPublishTime())); i++; } } #endif /////////////////////////////////////////////////////////////////////////////// // CSharedFileList CSharedFileList::CSharedFileList(CServerConnect* in_server) { server = in_server; // output = 0; m_Files_map.InitHashTable(1031); m_keywords = new CPublishKeywordList; m_lastPublishED2K = 0; m_lastPublishED2KFlag = true; m_currFileSrc = 0; m_currFileNotes = 0; m_lastPublishKadSrc = 0; m_lastPublishKadNotes = 0; m_currFileKey = 0; //FindSharedFiles(); } CSharedFileList::~CSharedFileList(){ while (!waitingforhash_list.IsEmpty()){ UnknownFile_Struct* nextfile = waitingforhash_list.RemoveHead(); delete nextfile; } // SLUGFILLER: SafeHash while (!currentlyhashing_list.IsEmpty()){ UnknownFile_Struct* nextfile = currentlyhashing_list.RemoveHead(); delete nextfile; } // SLUGFILLER: SafeHash delete m_keywords; } void CSharedFileList::CopySharedFileMap(CMap<CCKey,const CCKey&,CKnownFile*,CKnownFile*> &Files_Map) { if (!m_Files_map.IsEmpty()) { POSITION pos = m_Files_map.GetStartPosition(); while (pos) { CCKey key; CKnownFile* cur_file; m_Files_map.GetNextAssoc(pos, key, cur_file); Files_Map.SetAt(key, cur_file); } } } /** * <BR>功能说明: 把某个目录下的文件按参数限定的逻辑规则添加到分享列表中 * @author VC-Huby * @param strDir 需要处理的目录.. * @param bSubDirectories 是否处理该目录下的子目录 * @param strListAdded 用于记录已被处理的分享目录列表.. * @param bAddOnlyInKnownFile 只有在knownfile中已经存在的hash记录的才被处理(保证用户从网上下的文件即使移动到子目录后也能被分享) * @param bOnlyAddFileInSubDir 是否只加载该目录下的子目录下的文件,该目录下的被忽略 * @return */ void CSharedFileList::AddShareFilesFromDir(CString strDir, bool bSubDirectories,CStringList& strListAdded,bool bAddOnlyInKnownFile,bool bOnlyAddFileInSubDir,int iLevel) { if(!bOnlyAddFileInSubDir) { AddFilesFromDirectory(strDir,bAddOnlyInKnownFile,true); strDir.MakeLower(); strListAdded.AddTail(strDir); } iLevel--; if(iLevel==0) return; //[VC-Huby-080701]: 目录层数限制 if (bSubDirectories) { if (strDir.Right(1) != _T("\\")) strDir += _T("\\"); CFileFind finder; BOOL bWorking = finder.FindFile(strDir+_T("*.*")); while (bWorking) { bWorking = finder.FindNextFile(); if (finder.IsDots() || finder.IsSystem() || !finder.IsDirectory()) continue; AddShareFilesFromDir(strDir + finder.GetFileName(), true,strListAdded,bAddOnlyInKnownFile,false,iLevel); } finder.Close(); } } void CSharedFileList::FindSharedFiles() { if (!m_Files_map.IsEmpty()) { CSingleLock listlock(&m_mutWriteList); POSITION pos = m_Files_map.GetStartPosition(); while (pos) { CCKey key; CKnownFile* cur_file; m_Files_map.GetNextAssoc(pos, key, cur_file); if (cur_file->IsKindOf(RUNTIME_CLASS(CPartFile)) && !CGlobalVariable::downloadqueue->IsPartFile(cur_file) && !CGlobalVariable::knownfiles->IsFilePtrInList(cur_file) && _taccess(cur_file->GetFilePath(), 0) == 0) continue; m_UnsharedFiles_map.SetAt(CSKey(cur_file->GetFileHash()), true); listlock.Lock(); m_Files_map.RemoveKey(key); listlock.Unlock(); } // Comment By yunchenn //ASSERT( CGlobalVariable::downloadqueue ); //if (CGlobalVariable::downloadqueue) // CGlobalVariable::downloadqueue->AddPartFilesToShare(); // read partfiles } ///initialize filter Ext before add file to share list CIni ini(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("Dynamicref.dat"),_T("eMule")); DynamicPref.m_sFilterExt = ini.GetStringUTF8(L"FilterExt",_T("part.met.backup|part.met.txtsrc|emule.td|td.cfg|qud.cfg|不安全|")); DynamicPref.m_sFilterWCExt = ini.GetStringUTF8(L"FilterWCExt",_T("jc|jc!|jccfg|jccfg3|tdl|")); DynamicPref.OnDownloadFilterExt(); // moved By yunchenn ASSERT( CGlobalVariable::downloadqueue ); if (CGlobalVariable::downloadqueue) CGlobalVariable::downloadqueue->AddPartFilesToShare(); // read partfiles // khaos::kmod+ Fix: Shared files loaded multiple times. CStringList l_sAdded; CString tempDir; CString ltempDir; tempDir = thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR); if (tempDir.Right(1)!=_T("\\")) tempDir+=_T("\\"); AddFilesFromDirectory(tempDir); //缺省下载目录第一级下的所有文件都被分享(包括本地的文件) tempDir.MakeLower(); l_sAdded.AddHead( tempDir ); /// 考虑有些用户会在incoming 下建子目录,然后把incoming 下已下载完成文件的移动到下面的子目录.. AddShareFilesFromDir(tempDir, true,l_sAdded,true,true,3); AddFilesFromDirectory(thePrefs.GetMuleDirectory(EMULE_UPDATEDIR)); for (int ix=1;ix<thePrefs.GetCatCount();ix++) { tempDir=CString( thePrefs.GetCatPath(ix) ); if (tempDir.Right(1)!=_T("\\")) tempDir+=_T("\\"); ltempDir=tempDir; ltempDir.MakeLower(); if( l_sAdded.Find( ltempDir ) ==NULL ) { l_sAdded.AddHead( ltempDir ); AddFilesFromDirectory(tempDir); } } for (POSITION pos = thePrefs.shareddir_list.GetHeadPosition();pos != 0;) { tempDir = thePrefs.shareddir_list.GetNext(pos); if (tempDir.Right(1)!=_T("\\")) tempDir+=_T("\\"); ltempDir= tempDir; ltempDir.MakeLower(); if( l_sAdded.Find( ltempDir ) ==NULL ) { l_sAdded.AddHead( ltempDir ); AddFilesFromDirectory(tempDir); } } // khaos::kmod- // Comment UI if (waitingforhash_list.IsEmpty()) AddLogLine(false,GetResString(IDS_SHAREDFOUND), m_Files_map.GetCount()); else AddLogLine(false,GetResString(IDS_SHAREDFOUNDHASHING), m_Files_map.GetCount(), waitingforhash_list.GetCount()); HashNextFile(); } /// 过滤不需要被分享的文件 [VC-Huby-2008/03/06] bool CSharedFileList::FileIsIgnored( const CFileFind& ff ) { if (ff.IsDirectory() || ff.IsDots() || ff.IsSystem() || ff.IsTemporary() || ff.IsHidden() || ff.GetLength()==0 || ff.GetLength()>MAX_EMULE_FILE_SIZE) return true; // ignore real(!) LNK files TCHAR szExt[_MAX_EXT]; _tsplitpath(ff.GetFileName(), NULL, NULL, NULL, szExt); if (_tcsicmp(szExt, _T(".lnk")) == 0) { SHFILEINFO info; if (SHGetFileInfo(ff.GetFilePath(), 0, &info, sizeof(info), SHGFI_ATTRIBUTES) && (info.dwAttributes & SFGAO_LINK)) { CComPtr<IShellLink> pShellLink; if (SUCCEEDED(pShellLink.CoCreateInstance(CLSID_ShellLink))){ CComQIPtr<IPersistFile> pPersistFile = pShellLink; if (pPersistFile) { USES_CONVERSION; if (SUCCEEDED(pPersistFile->Load(T2COLE(ff.GetFilePath()), STGM_READ))) { TCHAR szResolvedPath[MAX_PATH]; if (pShellLink->GetPath(szResolvedPath, ARRSIZE(szResolvedPath), NULL, 0) == NOERROR) { TRACE(_T("%hs: Did not share file \"%s\" - not supported file type\n"), __FUNCTION__, ff.GetFilePath()); return true; } } } } } } // ignore real(!) thumbs.db files -- seems that lot of ppl have 'thumbs.db' files without the 'System' file attribute if (ff.GetFileName().CompareNoCase(_T("thumbs.db")) == 0) { // if that's a valid 'Storage' file, we declare it as a "thumbs.db" file. USES_CONVERSION; CComPtr<IStorage> pStorage; if (StgOpenStorage(T2CW(ff.GetFilePath()), NULL, STGM_READ | STGM_SHARE_DENY_WRITE, NULL, 0, &pStorage) == S_OK) { CComPtr<IEnumSTATSTG> pEnumSTATSTG; if (SUCCEEDED(pStorage->EnumElements(0, NULL, 0, &pEnumSTATSTG))) { STATSTG statstg = {0}; if (pEnumSTATSTG->Next(1, &statstg, 0) == S_OK) { CoTaskMemFree(statstg.pwcsName); statstg.pwcsName = NULL; TRACE(_T("%hs: Did not share file \"%s\" - not supported file type\n"), __FUNCTION__, ff.GetFilePath()); return true; } } } } CString strTempPath = ff.GetFilePath(); if(strTempPath.Right(5).CompareNoCase(_T(".part"))==0 || strTempPath.Right(9).CompareNoCase(_T(".part.met"))==0 || strTempPath.Right(13).CompareNoCase(_T(".part.met.bak"))==0) { return true; } CString sFilterExtItem; for (int i=0;i<thePrefs.m_aFilterExt.GetCount();i++) { sFilterExtItem = thePrefs.m_aFilterExt.GetAt(i); if(strTempPath.GetLength()<sFilterExtItem.GetLength()+1 ) continue; if( strTempPath.Right(sFilterExtItem.GetLength()).CompareNoCase(sFilterExtItem)==0 ) return true; } for (int i=0;i<thePrefs.m_aFilterWCExt.GetCount();i++) { sFilterExtItem = thePrefs.m_aFilterWCExt.GetAt(i); if(strTempPath.GetLength()<sFilterExtItem.GetLength()+6 ) /// filter *.???.flt continue; ///maybe *.rm.* or *.rmvb.* or *.avi.* if( strTempPath.Right(sFilterExtItem.GetLength()).CompareNoCase(sFilterExtItem)==0 && ( strTempPath.GetAt(strTempPath.GetLength()-sFilterExtItem.GetLength()-4)==_T('.') || strTempPath.GetAt(strTempPath.GetLength()-sFilterExtItem.GetLength()-5)==_T('.') || strTempPath.GetAt(strTempPath.GetLength()-sFilterExtItem.GetLength()-6)==_T('.') ) ) return true; } return false; } // 此函数不处理子目录下的文件.. // bAddOnlyInKnownFile : 是否只添加已经在KnownFile中有hash信息保存的 void CSharedFileList::AddFilesFromDirectory(const CString& rstrDirectory,bool bAddOnlyInKnownFile,bool bOnlyGetKnownPath) { CFileFind ff; CString searchpath; searchpath.Format(_T("%s\\*"),rstrDirectory); bool end = !ff.FindFile(searchpath,0); if (end) return; while (!end) { end = !ff.FindNextFile(); if( FileIsIgnored(ff) ) continue; CTime lwtime; try{ ff.GetLastWriteTime(lwtime); } catch(CException* ex){ ex->Delete(); } uint32 fdate = (UINT)lwtime.GetTime(); if (fdate == 0) fdate = (UINT)-1; if (fdate == -1){ if (thePrefs.GetVerbose()) AddDebugLogLine(false, _T("Failed to get file date of \"%s\""), ff.GetFilePath()); } else AdjustNTFSDaylightFileTime(fdate, ff.GetFilePath()); CKnownFile* toadd = CGlobalVariable::knownfiles->FindKnownFile(ff.GetFileName(), fdate, ff.GetLength()); if (toadd) { CCKey key(toadd->GetFileHash()); CKnownFile* pFileInMap; if (m_Files_map.Lookup(key, pFileInMap)) { TRACE(_T("%hs: File already in shared file list: %s \"%s\"\n"), __FUNCTION__, md4str(pFileInMap->GetFileHash()), pFileInMap->GetFilePath()); TRACE(_T("%hs: File to add: %s \"%s\"\n"), __FUNCTION__, md4str(toadd->GetFileHash()), ff.GetFilePath()); // Comment UI if (!pFileInMap->IsKindOf(RUNTIME_CLASS(CPartFile)) || CGlobalVariable::downloadqueue->IsPartFile(pFileInMap) && pFileInMap->GetFilePath()!=ff.GetFilePath() ) LogWarning( GetResString(IDS_ERR_DUPL_FILES) , pFileInMap->GetFilePath(), ff.GetFilePath()); } else { toadd->SetPath(rstrDirectory); toadd->SetFilePath(ff.GetFilePath()); if(!bOnlyGetKnownPath) AddFile(toadd); } } else { if(!bAddOnlyInKnownFile) { //not in knownfilelist - start adding thread to hash file if the hashing of this file isnt already waiting // SLUGFILLER: SafeHash - don't double hash, MY way if (!IsHashing(rstrDirectory, ff.GetFileName()) && !thePrefs.IsTempFile(rstrDirectory, ff.GetFileName())){ UnknownFile_Struct* tohash = new UnknownFile_Struct; tohash->strDirectory = rstrDirectory; tohash->strName = ff.GetFileName(); waitingforhash_list.AddTail(tohash); } else TRACE(_T("%hs: Did not share file \"%s\" - already hashing or temp. file\n"), __FUNCTION__, ff.GetFilePath()); // SLUGFILLER: SafeHash } } } ff.Close(); } void CSharedFileList::AddFileFromNewlyCreatedCollection(const CString& path, const CString& fileName) { //JOHNTODO: I do not have much knowledge on the hashing // process.. Is this safe for me to do?? if (!IsHashing(path, fileName)) { UnknownFile_Struct* tohash = new UnknownFile_Struct; tohash->strDirectory = path; tohash->strName = fileName; waitingforhash_list.AddTail(tohash); HashNextFile(); } } bool CSharedFileList::SafeAddKFile(CKnownFile* toadd, bool bOnlyAdd) { bool bAdded = false; RemoveFromHashing(toadd); // SLUGFILLER: SafeHash - hashed ok, remove from list, in case it was on the list bAdded = AddFile(toadd); if (bOnlyAdd) return bAdded; // Comment UI //if (bAdded && output) // output->AddFile(toadd); if(bAdded) UINotify(WM_SHAREDFILE_ADDFILE, 0, (LPARAM)toadd, toadd); m_lastPublishED2KFlag = true; return bAdded; } void CSharedFileList::RepublishFile(CKnownFile* pFile) { CServer* pCurServer = server->GetCurrentServer(); if (pCurServer && (pCurServer->GetTCPFlags() & SRV_TCPFLG_COMPRESSION)) { m_lastPublishED2KFlag = true; pFile->SetPublishedED2K(false); // FIXME: this creates a wrong 'No' for the ed2k shared info in the listview until the file is shared again. } } bool CSharedFileList::AddFile(CKnownFile* pFile) { ASSERT( pFile->GetHashCount() == pFile->GetED2KPartHashCount() ); ASSERT( !pFile->IsKindOf(RUNTIME_CLASS(CPartFile)) || !STATIC_DOWNCAST(CPartFile, pFile)->hashsetneeded ); if( this->IsFileAlreadyExist( pFile ) ) return false; if( pFile->HasNullHash() ) return false; CCKey key(pFile->GetFileHash()); CKnownFile* pFileInMap; if (m_Files_map.Lookup(key, pFileInMap)) { TRACE(_T("%hs: File already in shared file list: %s \"%s\" \"%s\"\n"), __FUNCTION__, md4str(pFileInMap->GetFileHash()), pFileInMap->GetFileName(), pFileInMap->GetFilePath()); TRACE(_T("%hs: File to add: %s \"%s\" \"%s\"\n"), __FUNCTION__, md4str(pFile->GetFileHash()), pFile->GetFileName(), pFile->GetFilePath()); // Comment UI if (!pFileInMap->IsKindOf(RUNTIME_CLASS(CPartFile)) || CGlobalVariable::downloadqueue->IsPartFile(pFileInMap) && pFileInMap->GetFilePath()!=pFile->GetFilePath() ) LogWarning(GetResString(IDS_ERR_DUPL_FILES), pFileInMap->GetFilePath(), pFile->GetFilePath()); return false; } m_UnsharedFiles_map.RemoveKey(CSKey(pFile->GetFileHash())); CSingleLock listlock(&m_mutWriteList); listlock.Lock(); m_Files_map.SetAt(key, pFile); listlock.Unlock(); bool bKeywordsNeedUpdated = true; if(!pFile->IsPartFile() && !pFile->m_pCollection && CCollection::HasCollectionExtention(pFile->GetFileName())) { pFile->m_pCollection = new CCollection(); if(!pFile->m_pCollection->InitCollectionFromFile(pFile->GetFilePath(), pFile->GetFileName())) { delete pFile->m_pCollection; pFile->m_pCollection = NULL; } else if (!pFile->m_pCollection->GetCollectionAuthorKeyString().IsEmpty()) { //If the collection has a key, resetting the file name will //cause the key to be added into the wordlist to be stored //into Kad. pFile->SetFileName(pFile->GetFileName()); //During the initial startup, sharedfiles is not accessable //to SetFileName which will then not call AddKeywords.. //But when it is accessable, we don't allow it to readd them. if(CGlobalVariable::sharedfiles) bKeywordsNeedUpdated = false; } } if(bKeywordsNeedUpdated) m_keywords->AddKeywords(pFile); return true; } bool CSharedFileList::IsFileAlreadyExist(CKnownFile* pFile) { POSITION p = this->m_Files_map.GetStartPosition(); CCKey key; CKnownFile* file = 0; while( p != NULL ) { this->m_Files_map.GetNextAssoc( p , key , file ); if( file == pFile ) return true; } return false; } bool CSharedFileList::FileHashingFinished(CKnownFile* file,CKnownFile** ppFileInKnownList) { // File hashing finished for a shared file (none partfile) // - reading shared directories at startup and hashing files which were not found in known.met // - reading shared directories during runtime (user hit Reload button, added a shared directory, ...) ASSERT( !IsFilePtrInList(file) ); ASSERT( !CGlobalVariable::knownfiles->IsFilePtrInList(file) ); CKnownFile* found_file = GetFileByID(file->GetFileHash()); if (found_file == NULL) { SafeAddKFile(file); CGlobalVariable::knownfiles->SafeAddKFile(file,false,ppFileInKnownList); return true; } else { TRACE(_T("%hs: File already in shared file list: %s \"%s\"\n"), __FUNCTION__, md4str(found_file->GetFileHash()), found_file->GetFilePath()); TRACE(_T("%hs: File to add: %s \"%s\"\n"), __FUNCTION__, md4str(file->GetFileHash()), file->GetFilePath()); // Comment UI //LogWarning(GetResString(IDS_ERR_DUPL_FILES), found_file->GetFilePath(), file->GetFilePath()); RemoveFromHashing(file); if (!IsFilePtrInList(file) && !CGlobalVariable::knownfiles->IsFilePtrInList(file)) delete file; else ASSERT(0); return false; } } bool CSharedFileList::RemoveFile(CKnownFile* pFile,bool bOnlyUnShare) { if (pFile->HasNullHash()) { UINotify(WM_SHAREDFILE_REMOVEFILE, 0, (LPARAM)pFile,NULL,true); return true; } CSingleLock listlock(&m_mutWriteList); listlock.Lock(); bool bResult = (m_Files_map.RemoveKey(CCKey(pFile->GetFileHash())) != FALSE); listlock.Unlock(); // CGlobalVariable::filemgr.RemoveFileItem(pFile); if (bResult) { // Comment UI //output->RemoveFile(pFile); //SendMessage(CGlobalVariable::m_hListenWnd, WM_SHAREDFILE_REMOVEFILE, 0, (LPARAM)pFile); if( !bOnlyUnShare ) { UINotify(WM_SHAREDFILE_REMOVEFILE, 0, (LPARAM)pFile,NULL,true); } m_UnsharedFiles_map.SetAt(CSKey(pFile->GetFileHash()), true); } m_keywords->RemoveKeywords(pFile); return bResult; } void CSharedFileList::Reload() { m_keywords->RemoveAllKeywordReferences(); FindSharedFiles(); m_keywords->PurgeUnreferencedKeywords(); RemoveHashingInUnSharedDir( ); CGlobalVariable::filemgr.ReloadLocalSharedFiles(); // Comment UI //if (output) // output->ReloadFileList(); PostMessage(CGlobalVariable::m_hListenWnd, WM_SHAREDFILE_RELOADFILELIST, 0, 0); } void CSharedFileList::AutoReload(BOOL bUpdateUI) { m_keywords->RemoveAllKeywordReferences(); FindSharedFiles(); m_keywords->PurgeUnreferencedKeywords(); //RemoveHashingInUnSharedDir( ); //CGlobalVariable::filemgr.ReloadLocalSharedFiles(); if (bUpdateUI) PostMessage(CGlobalVariable::m_hListenWnd, WM_SHAREDFILE_RELOADFILELIST, 0, 0); } //void CSharedFileList::SetOutputCtrl(CSharedFilesCtrl* in_ctrl) //{ // // Comment UI // /*output = in_ctrl; // output->ReloadFileList();*/ // HashNextFile(); // SLUGFILLER: SafeHash - if hashing not yet started, start it now //} uint8 GetRealPrio(uint8 in) { switch(in) { case 4 : return 0; case 0 : return 1; case 1 : return 2; case 2 : return 3; case 3 : return 4; } return 0; } void CSharedFileList::SendListToServer(){ if (m_Files_map.IsEmpty() || !server->IsConnected()) { return; } CServer* pCurServer = server->GetCurrentServer(); CSafeMemFile files(1024); CCKey bufKey; CKnownFile* cur_file,cur_file2; POSITION pos,pos2; CTypedPtrList<CPtrList, CKnownFile*> sortedList; bool added=false; for(pos=m_Files_map.GetStartPosition(); pos!=0;) { m_Files_map.GetNextAssoc(pos, bufKey, cur_file); added=false; //insertsort into sortedList if(!cur_file->GetPublishedED2K() && (!cur_file->IsLargeFile() || (pCurServer != NULL && pCurServer->SupportsLargeFilesTCP()))) { for (pos2 = sortedList.GetHeadPosition();pos2 != 0 && !added;sortedList.GetNext(pos2)) { if (GetRealPrio(sortedList.GetAt(pos2)->GetUpPriority()) <= GetRealPrio(cur_file->GetUpPriority()) ) { sortedList.InsertBefore(pos2,cur_file); added=true; } } if (!added) { sortedList.AddTail(cur_file); } } } // add to packet uint32 limit = pCurServer ? pCurServer->GetSoftFiles() : 0; if( limit == 0 || limit > 200 ) { limit = 200; } if( (uint32)sortedList.GetCount() < limit ) { limit = sortedList.GetCount(); if (limit == 0) { m_lastPublishED2KFlag = false; return; } } files.WriteUInt32(limit); uint32 count=0; for (pos = sortedList.GetHeadPosition();pos != 0 && count<limit; ) { count++; CKnownFile* file = sortedList.GetNext(pos); CreateOfferedFilePacket(file, &files, pCurServer); file->SetPublishedED2K(true); } sortedList.RemoveAll(); Packet* packet = new Packet(&files); packet->opcode = OP_OFFERFILES; // compress packet // - this kind of data is highly compressable (N * (1 MD4 and at least 3 string meta data tags and 1 integer meta data tag)) // - the min. amount of data needed for one published file is ~100 bytes // - this function is called once when connecting to a server and when a file becomes shareable - so, it's called rarely. // - if the compressed size is still >= the original size, we send the uncompressed packet // therefor we always try to compress the packet if (pCurServer && pCurServer->GetTCPFlags() & SRV_TCPFLG_COMPRESSION){ UINT uUncomprSize = packet->size; packet->PackPacket(); if (thePrefs.GetDebugServerTCPLevel() > 0) Debug(_T(">>> Sending OP__OfferFiles(compressed); uncompr size=%u compr size=%u files=%u\n"), uUncomprSize, packet->size, limit); } else{ if (thePrefs.GetDebugServerTCPLevel() > 0) Debug(_T(">>> Sending OP__OfferFiles; size=%u files=%u\n"), packet->size, limit); } theStats.AddUpDataOverheadServer(packet->size); if (thePrefs.GetVerbose()) AddDebugLogLine(false, _T("Server, Sendlist: Packet size:%u"), packet->size); server->SendPacket(packet,true); } CKnownFile* CSharedFileList::GetFileByIndex(int index){ int count=0; CKnownFile* cur_file; CCKey bufKey; for (POSITION pos = m_Files_map.GetStartPosition();pos != 0;){ m_Files_map.GetNextAssoc(pos,bufKey,cur_file); if (index==count) return cur_file; count++; } return 0; } void CSharedFileList::ClearED2KPublishInfo() { CKnownFile* cur_file; CCKey bufKey; m_lastPublishED2KFlag = true; for (POSITION pos = m_Files_map.GetStartPosition();pos != 0;) { m_Files_map.GetNextAssoc(pos,bufKey,cur_file); cur_file->SetPublishedED2K(false); } } void CSharedFileList::ClearKadSourcePublishInfo() { CKnownFile* cur_file; CCKey bufKey; for (POSITION pos = m_Files_map.GetStartPosition();pos != 0;) { m_Files_map.GetNextAssoc(pos,bufKey,cur_file); cur_file->SetLastPublishTimeKadSrc(0,0); } } void CSharedFileList::CreateOfferedFilePacket(CKnownFile* cur_file, CSafeMemFile* files, CServer* pServer, CUpDownClient* pClient) { UINT uEmuleVer = (pClient && pClient->IsEmuleClient()) ? pClient->GetVersion() : 0; // NOTE: This function is used for creating the offered file packet for Servers _and_ for Clients.. files->WriteHash16(cur_file->GetFileHash()); // *) This function is used for offering files to the local server and for sending // shared files to some other client. In each case we send our IP+Port only, if // we have a HighID. // *) Newer eservers also support 2 special IP+port values which are used to hold basic file status info. uint32 nClientID = 0; uint16 nClientPort = 0; if (pServer) { // we use the 'TCP-compression' server feature flag as indicator for a 'newer' server. if (pServer->GetTCPFlags() & SRV_TCPFLG_COMPRESSION) { if (cur_file->IsPartFile()) { // publishing an incomplete file nClientID = 0xFCFCFCFC; nClientPort = 0xFCFC; } else { // publishing a complete file nClientID = 0xFBFBFBFB; nClientPort = 0xFBFB; } } else { // check eD2K ID state if (CGlobalVariable::serverconnect->IsConnected() && !CGlobalVariable::serverconnect->IsLowID()) { // Comment UI nClientID = CGlobalVariable::GetID(); nClientPort = thePrefs.GetPort(); } } } else { // Comment UI if (CGlobalVariable::IsConnected() && !CGlobalVariable::IsFirewalled()) { nClientID = CGlobalVariable::GetID(); nClientPort = thePrefs.GetPort(); } } files->WriteUInt32(nClientID); files->WriteUInt16(nClientPort); //TRACE(_T("Publishing file: Hash=%s ClientIP=%s ClientPort=%u\n"), md4str(cur_file->GetFileHash()), ipstr(nClientID), nClientPort); CSimpleArray<CTag*> tags; tags.Add(new CTag(FT_FILENAME, cur_file->GetFileName())); if (!cur_file->IsLargeFile()){ tags.Add(new CTag(FT_FILESIZE, (uint32)(uint64)cur_file->GetFileSize())); } else{ // we send 2*32 bit tags to servers, but a real 64 bit tag to other clients. if (pServer != NULL){ if (!pServer->SupportsLargeFilesTCP()){ ASSERT( false ); tags.Add(new CTag(FT_FILESIZE, 0, false)); } else{ tags.Add(new CTag(FT_FILESIZE, (uint32)(uint64)cur_file->GetFileSize())); tags.Add(new CTag(FT_FILESIZE_HI, (uint32)((uint64)cur_file->GetFileSize() >> 32))); } } else{ if (!pClient->SupportsLargeFiles()){ ASSERT( false ); tags.Add(new CTag(FT_FILESIZE, 0, false)); } else{ tags.Add(new CTag(FT_FILESIZE, cur_file->GetFileSize(), true)); } } } // eserver 17.6+ supports eMule file rating tag. There is no TCP-capabilities bit available to determine // whether the server is really supporting it -- this is by intention (lug). That's why we always send it. if (cur_file->GetFileRating()) { uint32 uRatingVal = cur_file->GetFileRating(); if (pClient) { // eserver is sending the rating which it received in a different format (see // 'CSearchFile::CSearchFile'). If we are creating the packet for an other client // we must use eserver's format. uRatingVal *= (255/5/*RatingExcellent*/); } tags.Add(new CTag(FT_FILERATING, uRatingVal)); } // NOTE: Archives and CD-Images are published+searched with file type "Pro" bool bAddedFileType = false; if (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_TYPETAGINTEGER)) { // Send integer file type tags to newer servers EED2KFileType eFileType = GetED2KFileTypeSearchID(GetED2KFileTypeID(cur_file->GetFileName())); if (eFileType >= ED2KFT_AUDIO && eFileType <= ED2KFT_CDIMAGE) { tags.Add(new CTag(FT_FILETYPE, (UINT)eFileType)); bAddedFileType = true; } } if (!bAddedFileType) { // Send string file type tags to: // - newer servers, in case there is no integer type available for the file type (e.g. emulecollection) // - older servers // - all clients CString strED2KFileType(GetED2KFileTypeSearchTerm(GetED2KFileTypeID(cur_file->GetFileName()))); if (!strED2KFileType.IsEmpty()) { tags.Add(new CTag(FT_FILETYPE, strED2KFileType)); bAddedFileType = true; } } // eserver 16.4+ does not need the FT_FILEFORMAT tag at all nor does any eMule client. This tag // was used for older (very old) eDonkey servers only. -> We send it only to non-eMule clients. if (pServer == NULL && uEmuleVer == 0) { CString strExt; int iExt = cur_file->GetFileName().ReverseFind(_T('.')); if (iExt != -1){ strExt = cur_file->GetFileName().Mid(iExt); if (!strExt.IsEmpty()){ strExt = strExt.Mid(1); if (!strExt.IsEmpty()){ strExt.MakeLower(); tags.Add(new CTag(FT_FILEFORMAT, strExt)); // file extension without a "." } } } } // only send verified meta data to servers/clients if (cur_file->GetMetaDataVer() > 0) { static const struct { bool bSendToServer; uint8 nName; uint8 nED2KType; LPCSTR pszED2KName; } _aMetaTags[] = { // Artist, Album and Title are disabled because they should be already part of the filename // and would therefore be redundant information sent to the servers.. and the servers count the // amount of sent data! { false, FT_MEDIA_ARTIST, TAGTYPE_STRING, FT_ED2K_MEDIA_ARTIST }, { false, FT_MEDIA_ALBUM, TAGTYPE_STRING, FT_ED2K_MEDIA_ALBUM }, { false, FT_MEDIA_TITLE, TAGTYPE_STRING, FT_ED2K_MEDIA_TITLE }, { true, FT_MEDIA_LENGTH, TAGTYPE_STRING, FT_ED2K_MEDIA_LENGTH }, { true, FT_MEDIA_BITRATE, TAGTYPE_UINT32, FT_ED2K_MEDIA_BITRATE }, { true, FT_MEDIA_CODEC, TAGTYPE_STRING, FT_ED2K_MEDIA_CODEC } }; for (int i = 0; i < ARRSIZE(_aMetaTags); i++) { if (pServer!=NULL && !_aMetaTags[i].bSendToServer) continue; CTag* pTag = cur_file->GetTag(_aMetaTags[i].nName); if (pTag != NULL) { // skip string tags with empty string values if (pTag->IsStr() && pTag->GetStr().IsEmpty()) continue; // skip integer tags with '0' values if (pTag->IsInt() && pTag->GetInt() == 0) continue; if (_aMetaTags[i].nED2KType == TAGTYPE_STRING && pTag->IsStr()) { if (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_NEWTAGS)) tags.Add(new CTag(_aMetaTags[i].nName, pTag->GetStr())); else tags.Add(new CTag(_aMetaTags[i].pszED2KName, pTag->GetStr())); } else if (_aMetaTags[i].nED2KType == TAGTYPE_UINT32 && pTag->IsInt()) { if (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_NEWTAGS)) tags.Add(new CTag(_aMetaTags[i].nName, pTag->GetInt())); else tags.Add(new CTag(_aMetaTags[i].pszED2KName, pTag->GetInt())); } else if (_aMetaTags[i].nName == FT_MEDIA_LENGTH && pTag->IsInt()) { ASSERT( _aMetaTags[i].nED2KType == TAGTYPE_STRING ); // All 'eserver' versions and eMule versions >= 0.42.4 support the media length tag with type 'integer' if ( pServer!=NULL && (pServer->GetTCPFlags() & SRV_TCPFLG_COMPRESSION) || uEmuleVer >= MAKE_CLIENT_VERSION(0,42,4)) { if (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_NEWTAGS)) tags.Add(new CTag(_aMetaTags[i].nName, pTag->GetInt())); else tags.Add(new CTag(_aMetaTags[i].pszED2KName, pTag->GetInt())); } else { CString strValue; SecToTimeLength(pTag->GetInt(), strValue); tags.Add(new CTag(_aMetaTags[i].pszED2KName, strValue)); } } else ASSERT(0); } } } EUtf8Str eStrEncode; if (pServer != NULL && (pServer->GetTCPFlags() & SRV_TCPFLG_UNICODE)){ // eserver doesn't properly support searching with ASCII-7 strings in BOM-UTF8 published strings //eStrEncode = utf8strOptBOM; eStrEncode = utf8strRaw; } else if (pClient && !pClient->GetUnicodeSupport()) eStrEncode = utf8strNone; else eStrEncode = utf8strRaw; files->WriteUInt32(tags.GetSize()); for (int i = 0; i < tags.GetSize(); i++) { const CTag* pTag = tags[i]; //TRACE(_T(" %s\n"), pTag->GetFullInfo(DbgGetFileMetaTagName)); if (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_NEWTAGS) || (uEmuleVer >= MAKE_CLIENT_VERSION(0,42,7))) pTag->WriteNewEd2kTag(files, eStrEncode); else pTag->WriteTagToFile(files, eStrEncode); delete pTag; } } // -khaos--+++> New param: pbytesLargest, pointer to uint64. // Various other changes to accomodate our new statistic... // Point of this is to find the largest file currently shared. uint64 CSharedFileList::GetDatasize(uint64 &pbytesLargest) const { pbytesLargest=0; // <-----khaos- uint64 fsize; fsize=0; CCKey bufKey; CKnownFile* cur_file; for (POSITION pos = m_Files_map.GetStartPosition();pos != 0;){ m_Files_map.GetNextAssoc(pos,bufKey,cur_file); fsize += (uint64)cur_file->GetFileSize(); // -khaos--+++> If this file is bigger than all the others...well duh. if (cur_file->GetFileSize() > pbytesLargest) pbytesLargest = cur_file->GetFileSize(); // <-----khaos- } return fsize; } CKnownFile* CSharedFileList::GetFileByID(const uchar* hash) const { if (hash) { CKnownFile* found_file; CCKey key(hash); if (m_Files_map.Lookup(key, found_file)) return found_file; } return NULL; } bool CSharedFileList::IsFilePtrInList(const CKnownFile* file) const { if (file) { POSITION pos = m_Files_map.GetStartPosition(); while (pos) { CCKey key; CKnownFile* cur_file; m_Files_map.GetNextAssoc(pos, key, cur_file); if (file == cur_file) return true; } } return false; } void CSharedFileList::HashNextFile() { // SLUGFILLER: SafeHash // Comment UI /*if (!theApp.emuledlg || !::IsWindow(theApp.emuledlg->m_hWnd)) // wait for the dialog to open return; if (theApp.emuledlg && theApp.emuledlg->IsRunning()) theApp.emuledlg->sharedfileswnd->sharedfilesctrl.ShowFilesCount();*/ if(CGlobalVariable::IsRunning()) PostMessage( CGlobalVariable::m_hListenWnd,WM_SHAREDFILE_SHOWCOUNT,0,0 ); else return ; if (!currentlyhashing_list.IsEmpty()) // one hash at a time return; // SLUGFILLER: SafeHash if (waitingforhash_list.IsEmpty()) return; UnknownFile_Struct* nextfile = waitingforhash_list.RemoveHead(); m_hashingLocker.Lock(); currentlyhashing_list.AddTail(nextfile); // SLUGFILLER: SafeHash - keep track m_hashingLocker.Unlock(); CAddFileThread* addfilethread = (CAddFileThread*) AfxBeginThread(RUNTIME_CLASS(CAddFileThread), THREAD_PRIORITY_BELOW_NORMAL,0, CREATE_SUSPENDED); addfilethread->SetValues(this,nextfile->strDirectory,nextfile->strName); addfilethread->ResumeThread(); // SLUGFILLER: SafeHash - nextfile deleting handled elsewhere //delete nextfile; } // SLUGFILLER: SafeHash bool CSharedFileList::IsHashing(const CString& rstrDirectory, const CString& rstrName,bool* pbWaiting){ CString strDir = rstrDirectory; if (strDir.Right(1) != _T("\\") ) { strDir += _T("\\"); } if(pbWaiting) *pbWaiting = false; for (POSITION pos = waitingforhash_list.GetHeadPosition(); pos != 0; ) { const UnknownFile_Struct* pFile = waitingforhash_list.GetNext(pos); if (!pFile->strName.CompareNoCase(rstrName) && !CompareDirectories(pFile->strDirectory, strDir)) { if(pbWaiting) *pbWaiting = true; return true; } } m_hashingLocker.Lock(); for (POSITION pos = currentlyhashing_list.GetHeadPosition(); pos != 0; ) { const UnknownFile_Struct* pFile = currentlyhashing_list.GetNext(pos); if (!pFile->strName.CompareNoCase(rstrName) && !CompareDirectories(pFile->strDirectory, strDir)) { m_hashingLocker.Unlock(); return true; } } m_hashingLocker.Unlock(); return false; } bool CSharedFileList::IsHashing(const CString& rstrDirectory) { CString strDir = rstrDirectory; if (strDir.Right(1) != _T("\\") ) { strDir += _T("\\"); } if (rstrDirectory.IsEmpty()) { return false; } for (POSITION pos = waitingforhash_list.GetHeadPosition(); pos != 0; ) { const UnknownFile_Struct* pFile = waitingforhash_list.GetNext(pos); if (!CompareDirectories(pFile->strDirectory, strDir)) { return true; } } m_hashingLocker.Lock(); for (POSITION pos = currentlyhashing_list.GetHeadPosition(); pos != 0; ) { const UnknownFile_Struct* pFile = currentlyhashing_list.GetNext(pos); if (!CompareDirectories(pFile->strDirectory, strDir)) { m_hashingLocker.Unlock(); return true; } CString tempDir(rstrDirectory); tempDir.MakeLower(); if (pFile->strDirectory.Find(tempDir) == 0) { m_hashingLocker.Unlock(); return true; } } m_hashingLocker.Unlock(); return false; } bool CSharedFileList::IsShared(const CString& rstrFilePath) { POSITION pos = m_Files_map.GetStartPosition(); while (pos) { CCKey key; CKnownFile* cur_file; m_Files_map.GetNextAssoc(pos, key, cur_file); if ( 0==rstrFilePath.CompareNoCase(cur_file->GetFilePath()) ) return true; } return false; } void CSharedFileList::RemoveFromHashing(CKnownFile* hashed){ for (POSITION pos = currentlyhashing_list.GetHeadPosition(); pos != 0; ){ POSITION posLast = pos; const UnknownFile_Struct* pFile = currentlyhashing_list.GetNext(pos); if (!pFile->strName.CompareNoCase(hashed->GetFileName()) && !CompareDirectories(pFile->strDirectory, hashed->GetPath())){ currentlyhashing_list.RemoveAt(posLast); delete pFile; HashNextFile(); // start next hash if possible, but only if a previous hash finished return; } } } void CSharedFileList::RemoveHashing(const CString& rstrDirectory, const CString& rstrName) { CString strDir = rstrDirectory; if( strDir.Right(1)!=_T("\\")) strDir +=_T("\\"); for (POSITION pos = waitingforhash_list.GetHeadPosition(); pos != 0; ){ POSITION posLast = pos; const UnknownFile_Struct* pFile = waitingforhash_list.GetNext(pos); if (!pFile->strName.CompareNoCase(rstrName) && !CompareDirectories(pFile->strDirectory, strDir)) { waitingforhash_list.RemoveAt(posLast); delete pFile; HashNextFile(); // start next hash if possible, but only if a previous hash finished return; } } m_hashingLocker.Lock(); for (POSITION pos = currentlyhashing_list.GetHeadPosition(); pos != 0; ) { POSITION posLast = pos; const UnknownFile_Struct* pFile = currentlyhashing_list.GetNext(pos); if (!pFile->strName.CompareNoCase(rstrName) && !CompareDirectories(pFile->strDirectory, strDir)){ currentlyhashing_list.RemoveAt(posLast); delete pFile; HashNextFile(); // start next hash if possible, but only if a previous hash finished m_hashingLocker.Unlock(); return; } } m_hashingLocker.Unlock(); } void CSharedFileList::RemoveHashingInUnSharedDir( bool bRemoveAll ) { m_hashingLocker.Lock(); for (POSITION pos = currentlyhashing_list.GetHeadPosition(); pos != 0; ) { POSITION posLast = pos; const UnknownFile_Struct* pFile = currentlyhashing_list.GetNext(pos); if( !IsSharedPath(pFile->strDirectory ) ) { CString strFilePath = pFile->strDirectory; if(strFilePath.Right(1)!=_T("\\")) strFilePath+=_T("\\"); strFilePath += pFile->strName; if( !bRemoveAll && CGlobalVariable::filemgr.IsWaitforHash(strFilePath) ) continue; currentlyhashing_list.RemoveAt(posLast); delete pFile; } } m_hashingLocker.Unlock(); for (POSITION pos = waitingforhash_list.GetHeadPosition(); pos != 0; ) { POSITION posLast = pos; const UnknownFile_Struct* pFile = waitingforhash_list.GetNext(pos); if( !IsSharedPath(pFile->strDirectory ) ) { CString strFilePath = pFile->strDirectory; if(strFilePath.Right(1)!=_T("\\")) strFilePath+=_T("\\"); strFilePath += pFile->strName; if( !bRemoveAll && CGlobalVariable::filemgr.IsWaitforHash(strFilePath) ) continue; waitingforhash_list.RemoveAt(posLast); delete pFile; } } } void CSharedFileList::HashFailed(UnknownFile_Struct* hashed){ for (POSITION pos = currentlyhashing_list.GetHeadPosition(); pos != 0; ){ POSITION posLast = pos; const UnknownFile_Struct* pFile = currentlyhashing_list.GetNext(pos); if (!pFile->strName.CompareNoCase(hashed->strName) && !CompareDirectories(pFile->strDirectory, hashed->strDirectory)){ currentlyhashing_list.RemoveAt(posLast); delete pFile; HashNextFile(); // start next hash if possible, but only if a previous hash finished break; } } delete hashed; } // SLUGFILLER: SafeHash IMPLEMENT_DYNCREATE(CAddFileThread, CWinThread) CAddFileThread::CAddFileThread() { m_pOwner = NULL; m_partfile = NULL; } void CAddFileThread::SetValues(CSharedFileList* pOwner, LPCTSTR directory, LPCTSTR filename, CPartFile* partfile) { m_pOwner = pOwner; m_strDirectory = directory; m_strFilename = filename; m_partfile = partfile; } BOOL CAddFileThread::InitInstance() { InitThreadLocale(); return TRUE; } int CAddFileThread::Run() { try { DbgSetThreadName("Hashing %s", m_strFilename); // Comment UI if ( !(m_pOwner || m_partfile) || m_strFilename.IsEmpty() || !CGlobalVariable::IsRunning() ) return 0; CoInitialize(NULL); // if (m_partfile) // { // //CString strFileHash = (CString)m_partfile->GetFileHash(); // // if ( !strFileHash.IsEmpty()) // // { // //CKnownFile* newrecord = new CKnownFile(); // // // // // // CString strFilePath; // // _tmakepathlimit(strFilePath.GetBuffer(MAX_PATH), NULL, m_strDirectory, m_strFilename, NULL); // // newrecord->SetFilePath( strFilePath ); // // newrecord->SetFileSize( m_partfile->GetFileSize() ); // // // if (m_partfile->GetPartCount() > 0) // { // m_partfile->SetHash(m_partfile); // } // // if(m_partfile && m_partfile->GetFileOp() == PFOP_HASHING ) // m_partfile->SetFileOp(PFOP_NONE); // // CGlobalVariable::filemgr.HashCompleted( m_partfile ); // VERIFY( PostMessage(CGlobalVariable::m_hListenWnd, WM_FILE_FINISHEDHASHING, (m_pOwner ? 0: (WPARAM)m_partfile), (LPARAM)m_partfile) ); // // CoUninitialize(); // // return 0; // // } // } // locking that hashing thread is needed because we may create a couple of those threads at startup when rehashing // potentially corrupted downloading part files. if all those hash threads would run concurrently, the io-system would be // under very heavy load and slowly progressing // Comment UI CSingleLock sLock1(&CGlobalVariable::hashing_mut); // only one filehash at a time sLock1.Lock(); CString strFilePath; _tmakepathlimit(strFilePath.GetBuffer(MAX_PATH), NULL, m_strDirectory, m_strFilename, NULL); strFilePath.ReleaseBuffer(); if (m_partfile) Log(GetResString(IDS_HASHINGFILE) + _T(" \"%s\" \"%s\""), m_partfile->GetFileName(), strFilePath); else Log(GetResString(IDS_HASHINGFILE) + _T(" \"%s\""), strFilePath); CKnownFile* newrecord = new CKnownFile(); if (newrecord->CreateFromFile(m_strDirectory, m_strFilename, m_partfile) && CGlobalVariable::IsRunning()) // SLUGFILLER: SafeHash - in case of shutdown while still hashing { if (m_partfile && m_partfile->GetFileOp() == PFOP_HASHING) m_partfile->SetFileOp(PFOP_NONE); CGlobalVariable::filemgr.HashCompleted(newrecord); VERIFY( PostMessage(CGlobalVariable::m_hListenWnd, WM_FILE_FINISHEDHASHING, (m_pOwner ? 0: (WPARAM)m_partfile), (LPARAM)newrecord) ); } else { if (CGlobalVariable::IsRunning()) { if (m_partfile && m_partfile->GetFileOp() == PFOP_HASHING) m_partfile->SetFileOp(PFOP_NONE); CGlobalVariable::filemgr.HashFailed(strFilePath); // SLUGFILLER: SafeHash - inform main program of hash failure if (m_pOwner) { UnknownFile_Struct* hashed = new UnknownFile_Struct; hashed->strDirectory = m_strDirectory; hashed->strName = m_strFilename; VERIFY( PostMessage(CGlobalVariable::m_hListenWnd,WM_FILE_HASHFAILED,0,(LPARAM)hashed) ); } } // SLUGFILLER: SafeHash delete newrecord; } sLock1.Unlock(); CoUninitialize(); } catch(...) { ASSERT(0); } return 0; } void CSharedFileList::UpdateFile(CKnownFile* toupdate) { // Comment UI UINotify(WM_SHAREDFILE_UPDATE, 0, (LPARAM)toupdate, toupdate); } void CSharedFileList::Process() { Publish(); if( !m_lastPublishED2KFlag || ( ::GetTickCount() - m_lastPublishED2K < ED2KREPUBLISHTIME ) ) { return; } SendListToServer(); m_lastPublishED2K = ::GetTickCount(); } void CSharedFileList::Publish() { // Variables to save cpu. UINT tNow = time(NULL); bool isFirewalled =true; // Comment UI isFirewalled= CGlobalVariable::IsFirewalled(); bool bDirectCallback = Kademlia::CKademlia::IsRunning() && !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified(); if( Kademlia::CKademlia::IsConnected() && ( !isFirewalled || ( isFirewalled && CGlobalVariable::clientlist->GetBuddyStatus() == Connected) || bDirectCallback) && GetCount() && Kademlia::CKademlia::GetPublish()) { //We are connected to Kad. We are either open or have a buddy. And Kad is ready to start publishing. if( Kademlia::CKademlia::GetTotalStoreKey() < KADEMLIATOTALSTOREKEY) { //We are not at the max simultaneous keyword publishes if (tNow >= m_keywords->GetNextPublishTime()) { //Enough time has passed since last keyword publish //Get the next keyword which has to be (re)-published CPublishKeyword* pPubKw = m_keywords->GetNextKeyword(); if(pPubKw) { //We have the next keyword to check if it can be published //Debug check to make sure things are going well. ASSERT( pPubKw->GetRefCount() != 0 ); if (tNow >= pPubKw->GetNextPublishTime()) { //This keyword can be published. Kademlia::CSearch* pSearch = Kademlia::CSearchManager::PrepareLookup(Kademlia::CSearch::STOREKEYWORD, false, pPubKw->GetKadID()); if (pSearch) { //pSearch was created. Which means no search was already being done with this HashID. //This also means that it was checked to see if network load wasn't a factor. //This sets the filename into the search object so we can show it in the gui. pSearch->SetFileName(pPubKw->GetKeyword()); //Add all file IDs which relate to the current keyword to be published const CSimpleKnownFileArray& aFiles = pPubKw->GetReferences(); uint32 count = 0; for (int f = 0; f < aFiles.GetSize(); f++) { //Debug check to make sure things are working well. ASSERT_VALID( aFiles[f] ); // JOHNTODO - Why is this happening.. I think it may have to do with downloading a file that is already // in the known file list.. // ASSERT( IsFilePtrInList(aFiles[f]) ); //Only publish complete files as someone else should have the full file to publish these keywords. //As a side effect, this may help reduce people finding incomplete files in the network. if( !aFiles[f]->IsPartFile() && IsFilePtrInList(aFiles[f])) { count++; pSearch->AddFileID(Kademlia::CUInt128(aFiles[f]->GetFileHash())); if( count > 150 ) { //We only publish up to 150 files per keyword publish then rotate the list. pPubKw->RotateReferences(f); break; } } } if( count ) { //Start our keyword publish pPubKw->SetNextPublishTime(tNow+(KADEMLIAREPUBLISHTIMEK)); pPubKw->IncPublishedCount(); Kademlia::CSearchManager::StartSearch(pSearch); } else { //There were no valid files to publish with this keyword. delete pSearch; } } } } m_keywords->SetNextPublishTime(KADEMLIAPUBLISHTIME+tNow); } } if( Kademlia::CKademlia::GetTotalStoreSrc() < KADEMLIATOTALSTORESRC) { if(tNow >= m_lastPublishKadSrc) { if(m_currFileSrc > GetCount()) m_currFileSrc = 0; CKnownFile* pCurKnownFile = GetFileByIndex(m_currFileSrc); if(pCurKnownFile) { if(pCurKnownFile->PublishSrc()) { if(Kademlia::CSearchManager::PrepareLookup(Kademlia::CSearch::STOREFILE, true, Kademlia::CUInt128(pCurKnownFile->GetFileHash()))==NULL) pCurKnownFile->SetLastPublishTimeKadSrc(0,0); } } m_currFileSrc++; // even if we did not publish a source, reset the timer so that this list is processed // only every KADEMLIAPUBLISHTIME seconds. m_lastPublishKadSrc = KADEMLIAPUBLISHTIME+tNow; } } if( Kademlia::CKademlia::GetTotalStoreNotes() < KADEMLIATOTALSTORENOTES) { if(tNow >= m_lastPublishKadNotes) { if(m_currFileNotes > GetCount()) m_currFileNotes = 0; CKnownFile* pCurKnownFile = GetFileByIndex(m_currFileNotes); if(pCurKnownFile) { if(pCurKnownFile->PublishNotes()) { if(Kademlia::CSearchManager::PrepareLookup(Kademlia::CSearch::STORENOTES, true, Kademlia::CUInt128(pCurKnownFile->GetFileHash()))==NULL) pCurKnownFile->SetLastPublishTimeKadNotes(0); } } m_currFileNotes++; // even if we did not publish a source, reset the timer so that this list is processed // only every KADEMLIAPUBLISHTIME seconds. m_lastPublishKadNotes = KADEMLIAPUBLISHTIME+tNow; } } } } void CSharedFileList::AddKeywords(CKnownFile* pFile) { m_keywords->AddKeywords(pFile); } void CSharedFileList::RemoveKeywords(CKnownFile* pFile) { m_keywords->RemoveKeywords(pFile); } void CSharedFileList::DeletePartFileInstances() const { // this is only allowed during shut down ASSERT( CGlobalVariable::m_app_state == APP_STATE_SHUTTINGDOWN ); ASSERT( CGlobalVariable::knownfiles ); POSITION pos = m_Files_map.GetStartPosition(); while (pos) { CCKey key; CKnownFile* cur_file; m_Files_map.GetNextAssoc(pos, key, cur_file); if (cur_file->IsKindOf(RUNTIME_CLASS(CPartFile))) { if (!CGlobalVariable::downloadqueue->IsPartFile(cur_file) && !CGlobalVariable::knownfiles->IsFilePtrInList(cur_file)) delete cur_file; // this is only allowed during shut down } } } bool CSharedFileList::IsUnsharedFile(const uchar* auFileHash) const { bool bFound; if (auFileHash){ CSKey key(auFileHash); if (m_UnsharedFiles_map.Lookup(key, bFound)) return true; } return false; } CKnownFile * CSharedFileList::GetKnownFile(const CCKey & key) { CKnownFile* pFileInMap=NULL; m_Files_map.Lookup(key, pFileInMap); return pFileInMap; } int CSharedFileList::GetHashingCount() { int waitingforhash = waitingforhash_list.GetCount(); int currentlyhashing = currentlyhashing_list.GetCount(); return waitingforhash+currentlyhashing; } bool CSharedFileList::HashNewFile(const CString & strFilePath,bool bAddtoWaiting/*=true*/) { int nPathEnd=strFilePath.ReverseFind('\\'); CString strDirectory = strFilePath.Mid(0, nPathEnd+1); CString strName = strFilePath.Mid(nPathEnd+1); CKnownFile* pKnownFileExist = CGlobalVariable::knownfiles->FindKnownFileByPath(strFilePath,true); if( NULL!=pKnownFileExist ) { CGlobalVariable::filemgr.HashCompleted(pKnownFileExist); PostMessage( CGlobalVariable::m_hListenWnd, WM_FILE_FINISHEDHASHING, 0, (LPARAM)pKnownFileExist ); } else if (!IsHashing(strDirectory, strName) && !thePrefs.IsTempFile(strDirectory, strFilePath)) { UnknownFile_Struct* tohash = new UnknownFile_Struct; tohash->strDirectory = strDirectory; tohash->strName = strFilePath.Mid(nPathEnd+1); if( bAddtoWaiting ) { waitingforhash_list.AddTail(tohash); HashNextFile(); return true; } else { m_hashingLocker.Lock(); currentlyhashing_list.AddTail(tohash); m_hashingLocker.Unlock(); return true; } } return false; } void CSharedFileList::Initialize() { FindSharedFiles(); } int CSharedFileList::GetAllSharedFile(CList<CKnownFile *, CKnownFile*> & filelist) { filelist.RemoveAll(); CCKey bufKey; CKnownFile* cur_file; for (POSITION pos = m_Files_map.GetStartPosition(); pos != 0; ) { m_Files_map.GetNextAssoc(pos, bufKey, cur_file); filelist.AddTail(cur_file); } return filelist.GetCount(); } bool CSharedFileList::IsSharedPath(CString strPath) { if(strPath.Right(1)!=_T("\\")) strPath+=_T("\\"); CString tempDir=thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR); if (tempDir.Right(1)!=_T("\\")) tempDir+=_T("\\"); if(tempDir.CompareNoCase(strPath)==0) return true; for (POSITION pos = thePrefs.shareddir_list.GetHeadPosition();pos != 0;) { tempDir = thePrefs.shareddir_list.GetNext(pos); if (tempDir.Right(1)!=_T("\\")) tempDir+=_T("\\"); if(tempDir.CompareNoCase(strPath)==0) return true; } return false; }
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 1943 ] ] ]
61935ccdbe3504206a13a66d6acb4db5c984f78e
42a799a12ffd61672ac432036b6fc8a8f3b36891
/cpp/IGC_Tron/IGC_Tron/D3DRenderer.h
501f4d6f77f67947bb092375c7f424186000a3f8
[]
no_license
timotheehub/igctron
34c8aa111dbcc914183d5f6f405e7a07b819e12e
e608de209c5f5bd0d315a5f081bf0d1bb67fe097
refs/heads/master
2020-02-26T16:18:33.624955
2010-04-08T16:09:10
2010-04-08T16:09:10
71,101,932
0
0
null
null
null
null
UTF-8
C++
false
false
6,017
h
/**************************************************************************/ /* This file is part of IGC Tron */ /* (c) IGC Software 2009 - 2010 */ /* Author : Pierre-Yves GATOUILLAT */ /**************************************************************************/ /* This program is free software: you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation, either version 3 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /**************************************************************************/ #ifdef _WIN32 #ifndef _D3DRENDERER #define _D3DRENDERER /***********************************************************************************/ /** INCLUSIONS **/ /***********************************************************************************/ #include "Common.h" #include <windows.h> #include <d3dx9.h> #include <dxerr.h> #include "IRenderer.h" /***********************************************************************************/ namespace IGC { class Engine; class D3DRenderer : public IRenderer { /***********************************************************************************/ /** CLASSES AMIES **/ /***********************************************************************************/ friend class D3DCamera; friend class D3DFont; friend class D3DMesh; friend class D3DModel; /***********************************************************************************/ /** ATTRIBUTS **/ /***********************************************************************************/ private: LPDIRECT3D9 lpD3D; LPDIRECT3DDEVICE9 lpD3DDevice; LPDIRECT3DTEXTURE9 lpRenderTexture; LPDIRECT3DPIXELSHADER9 lpPixelShader; LPDIRECT3DVERTEXSHADER9 lpVertexShader; LPDIRECT3DVERTEXDECLARATION9 lpVertexDeclaration; LPDIRECT3DVERTEXBUFFER9 lpVertexBuffer; LPDIRECT3DINDEXBUFFER9 lpIndexBuffer; LPD3DXFONT lpFont; /***********************************************************************************/ /** CONSTRUCTEURS / DESTRUCTEUR **/ /***********************************************************************************/ public: /* Instancie la classe et alloue la m�moire vid�o pour une surface de rendu dont la taille correspond � celle de la fen�tre associ�e � _engine. */ D3DRenderer( Engine* _engine ); /* Lib�re la m�moire vid�o r�serv�e pour une surface de rendu. */ virtual ~D3DRenderer(); /***********************************************************************************/ /** ACCESSEURS **/ /***********************************************************************************/ public: /* Renvoie le device associ� � cette instance ou NULL si celui-ci n'a pas encore �t� cr��. */ LPDIRECT3DDEVICE9 getDevice(); private: /* Sp�cifie une police pour le prochain rendu de texte. */ void setFont( LPD3DXFONT _lpFont ); /***********************************************************************************/ /** METHODES PUBLIQUES **/ /***********************************************************************************/ public: /* Initialise Direct3D et lui associe la surface de rendu. */ virtual void initialize(); /* Lib�re toutes les ressources relatives ? Direct3D. */ virtual void finalize(); /* Met � jour l'affichage en copiant le contenu du back buffer vers le frame buffer. */ virtual void update(); /* Active ou non la transparence pour le prochain rendu. */ virtual void setTransparency( bool _value ); /* Remplit le back buffer de la couleur sp�cifi�e et le depth buffer de la profondeur sp�cifi�e. */ virtual void clear( float _r = 0.0f, float _g = 0.0f, float _b = 0.0f, float _depth = 1.0f ); /* Affiche du texte � la position absolue sp�cifi�e avec la couleur sp�cifi�e en fonction de la police qui aura pr�c�demment �t� d�finie. */ virtual void drawText( const char* _text, int _x, int _y, float _r, float _g, float _b, float _a ); /* Affiche une image � la position absolue sp�cifi�e avec la couleur sp�cifi�e en fonction de la texture qui aura pr�c�demment �t� d�finie. */ virtual void drawImage( int _x0, int _y0, int _x1, int _y1, float _px = 0.0f, float _py = 0.0f, float _sx = 1.0f, float _sy = 1.0f, float _r = 1.0f, float _g = 1.0f, float _b = 1.0f, float _a = 1.0f ); /* Redimensionne la scène. */ virtual void resizeScene ( int newWidth, int newHeight ) { }; }; } /***********************************************************************************/ #endif #endif
[ "fenrhil@de5929ad-f5d8-47c6-8969-ac6c484ef978", "raoul12@de5929ad-f5d8-47c6-8969-ac6c484ef978", "[email protected]" ]
[ [ [ 1, 133 ], [ 139, 148 ], [ 150, 151 ], [ 156, 158 ], [ 161, 168 ] ], [ [ 134, 138 ], [ 149, 149 ], [ 152, 155 ], [ 160, 160 ] ], [ [ 159, 159 ] ] ]
90560cdf9a8d1a36da9114948cedbd601352e356
e9fd66e6db68ca4d1a9f14aece84a0aff99323e4
/CCB2010/RGBSAMP/ColorSpace.cpp
1346d111afd6fea23d35ca26611037e071f3150f
[]
no_license
radtek/bbmonitoring
70fd4a4c4d553503717a474da39bef67834cc675
ff77607e77616b84395e095f396df496e7f0054a
refs/heads/master
2020-09-22T07:27:15.827047
2011-01-04T05:37:46
2011-01-04T05:37:46
null
0
0
null
null
null
null
GB18030
C++
false
false
15,501
cpp
// ColorSpace.cpp: implementation of the CColorSpace class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ColorSpace.h" //#include "WorkThreadPool.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #define asm __asm //颜色饱和函数 __forceinline long border_color(long color) { if (color>255) return 255; else if (color<0) return 0; else return color; } const int csY_coeff_16 = 1.164383*(1<<16); const int csU_blue_16 = 2.017232*(1<<16); const int csU_green_16 = (-0.391762)*(1<<16); const int csV_green_16 = (-0.812968)*(1<<16); const int csV_red_16 = 1.596027*(1<<16); __forceinline void YUVToRGB32_Two(TARGB32* pDst, const TUInt8 Y0, const TUInt8 Y1, const TUInt8 U, const TUInt8 V) { int Ye0 = csY_coeff_16 * (Y0 - 16); int Ye1 = csY_coeff_16 * (Y1 - 16); int Ue = (U-128); int Ve = (V-128); int Ue_blue = csU_blue_16 * Ue; int Ue_green = csU_green_16 * Ue; int Ve_green = csV_green_16 * Ve; int Ve_red = csV_red_16 * Ve; int UeVe_green = Ue_green + Ve_green; pDst->b = border_color( ( Ye0 + Ue_blue ) >>16 ); pDst->g = border_color( ( Ye0 + UeVe_green ) >>16 ); pDst->r = border_color( ( Ye0 + Ve_red ) >>16 ); pDst->a = 255; ++pDst; pDst->b = border_color( ( Ye1 + Ue_blue ) >>16 ); pDst->g = border_color( ( Ye1 + UeVe_green ) >>16 ); pDst->r = border_color( ( Ye1 + Ve_red ) >>16 ); pDst->a = 255; } void DECODE_UYVY_Common_line(TARGB32 *pDstLine, const TUInt8 *pUYVY, long width) { for (long x = 0 ; x < width ; x += 2) { YUVToRGB32_Two(&pDstLine[x], pUYVY[1], pUYVY[3], pUYVY[0], pUYVY[2]); pUYVY+=4; } } const UInt64 csMMX_16_b = 0x1010101010101010; // byte{16,16,16,16,16,16,16,16} const UInt64 csMMX_128_w = 0x0080008000800080; //short{ 128, 128, 128, 128} const UInt64 csMMX_0x00FF_w = 0x00FF00FF00FF00FF; //掩码 const UInt64 csMMX_Y_coeff_w = 0x2543254325432543; //short{ 9539, 9539, 9539, 9539} =1.164383*(1<<13) const UInt64 csMMX_U_blue_w = 0x408D408D408D408D; //short{16525,16525,16525,16525} =2.017232*(1<<13) const UInt64 csMMX_U_green_w = 0xF377F377F377F377; //short{-3209,-3209,-3209,-3209} =(-0.391762)*(1<<13) const UInt64 csMMX_V_green_w = 0xE5FCE5FCE5FCE5FC; //short{-6660,-6660,-6660,-6660} =(-0.812968)*(1<<13) const UInt64 csMMX_V_red_w = 0x3313331333133313; //short{13075,13075,13075,13075} =1.596027*(1<<13) //一次处理8个颜色输出 #define YUV422ToRGB32_MMX(out_RGB_reg,WriteCode) \ /*input : mm0 = Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */ \ /* mm1 = 00 u3 00 u2 00 u1 00 u0 */ \ /* mm2 = 00 v3 00 v2 00 v1 00 v0 */ \ /*output : [out_RGB_reg -- out_RGB_reg+8*4] */ \ \ asm psubusb mm0,csMMX_16_b /* mm0 : Y -= 16 */ \ asm psubsw mm1,csMMX_128_w /* mm1 : u -= 128 */ \ asm movq mm7,mm0 \ asm psubsw mm2,csMMX_128_w /* mm2 : v -= 128 */ \ asm pand mm0,csMMX_0x00FF_w /* mm0 = 00 Y6 00 Y4 00 Y2 00 Y0 */ \ asm psllw mm1,3 /* mm1 : u *= 8 */ \ asm psllw mm2,3 /* mm2 : v *= 8 */ \ asm psrlw mm7,8 /* mm7 = 00 Y7 00 Y5 00 Y3 00 Y1 */ \ asm movq mm3,mm1 \ asm movq mm4,mm2 \ \ asm pmulhw mm1,csMMX_U_green_w /* mm1 = u * U_green */ \ asm psllw mm0,3 /* y*=8 */ \ asm pmulhw mm2,csMMX_V_green_w /* mm2 = v * V_green */ \ asm psllw mm7,3 /* y*=8 */ \ asm pmulhw mm3,csMMX_U_blue_w \ asm paddsw mm1,mm2 \ asm pmulhw mm4,csMMX_V_red_w \ asm movq mm2,mm3 \ asm pmulhw mm0,csMMX_Y_coeff_w \ asm movq mm6,mm4 \ asm pmulhw mm7,csMMX_Y_coeff_w \ asm movq mm5,mm1 \ asm paddsw mm3,mm0 /* mm3 = B6 B4 B2 B0 */ \ asm paddsw mm2,mm7 /* mm2 = B7 B5 B3 B1 */ \ asm paddsw mm4,mm0 /* mm4 = R6 R4 R2 R0 */ \ asm paddsw mm6,mm7 /* mm6 = R7 R5 R3 R1 */ \ asm paddsw mm1,mm0 /* mm1 = G6 G4 G2 G0 */ \ asm paddsw mm5,mm7 /* mm5 = G7 G5 G3 G1 */ \ \ asm packuswb mm3,mm4 /* mm3 = R6 R4 R2 R0 B6 B4 B2 B0 to [0-255] */ \ asm packuswb mm2,mm6 /* mm2 = R7 R5 R3 R1 B7 B5 B3 B1 to [0-255] */ \ asm packuswb mm5,mm1 /* mm5 = G6 G4 G2 G0 G7 G5 G3 G1 to [0-255] */ \ asm movq mm4,mm3 \ asm punpcklbw mm3,mm2 /* mm3 = B7 B6 B5 B4 B3 B2 B1 B0 */ \ asm punpckldq mm1,mm5 /* mm1 = G7 G5 G3 G1 xx xx xx xx */ \ asm punpckhbw mm4,mm2 /* mm4 = R7 R6 R5 R4 R3 R2 R1 R0 */ \ asm punpckhbw mm5,mm1 /* mm5 = G7 G6 G5 G4 G3 G2 G1 G0 */ \ \ /*out*/ \ asm pcmpeqb mm2,mm2 /* mm2 = FF FF FF FF FF FF FF FF */ \ \ asm movq mm0,mm3 \ asm movq mm7,mm4 \ asm punpcklbw mm0,mm5 /* mm0 = G3 B3 G2 B2 G1 B1 G0 B0 */ \ asm punpcklbw mm7,mm2 /* mm7 = FF R3 FF R2 FF R1 FF R0 */ \ asm movq mm1,mm0 \ asm movq mm6,mm3 \ asm punpcklwd mm0,mm7 /* mm0 = FF R1 G1 B1 FF R0 G0 B0 */ \ asm punpckhwd mm1,mm7 /* mm1 = FF R3 G3 B3 FF R2 G2 B2 */ \ asm WriteCode [out_RGB_reg],mm0 \ asm movq mm7,mm4 \ asm punpckhbw mm6,mm5 /* mm6 = G7 B7 G6 B6 G5 B5 G4 B4 */ \ asm WriteCode [out_RGB_reg+8],mm1 \ asm punpckhbw mm7,mm2 /* mm7 = FF R7 FF R6 FF R5 FF R4 */ \ asm movq mm0,mm6 \ asm punpcklwd mm6,mm7 /* mm6 = FF R5 G5 B5 FF R4 G4 B4 */ \ asm punpckhwd mm0,mm7 /* mm0 = FF R7 G7 B7 FF R6 G6 B6 */ \ asm WriteCode [out_RGB_reg+8*2],mm6 \ asm WriteCode [out_RGB_reg+8*3],mm0 #define UYVY_Loader_MMX(in_yuv_reg) \ asm movq mm0,[in_yuv_reg ] /*mm0=Y3 V1 Y2 U1 Y1 V0 Y0 U0 */ \ asm movq mm4,[in_yuv_reg+8] /*mm4=Y7 V3 Y6 U3 Y5 V2 Y4 U2 */ \ asm movq mm1,mm0 \ asm movq mm5,mm4 \ asm psrlw mm0,8 /*mm0=00 Y3 00 Y2 00 Y1 00 Y0 */ \ asm psrlw mm4,8 /*mm4=00 Y7 00 Y6 00 Y5 00 Y4 */ \ asm pand mm1,csMMX_0x00FF_w /*mm1=00 V1 00 U1 00 V0 00 U0 */ \ asm pand mm5,csMMX_0x00FF_w /*mm5=00 V3 00 U3 00 V2 00 U2 */ \ asm packuswb mm1,mm5 /*mm1=V3 U3 V2 U2 V1 U1 V0 U0 */ \ asm movq mm2,mm1 \ asm packuswb mm0,mm4 /*mm0=Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */ \ asm psllw mm1,8 /*mm1=U3 00 U2 00 U1 00 U0 00 */ \ asm psrlw mm2,8 /*mm2=00 V3 00 V2 00 V1 00 V0 */ \ asm psrlw mm1,8 /*mm1=00 U3 00 U2 00 U1 00 U0 */ void DECODE_UYVY_MMX_line(TARGB32* pDstLine,const TUInt8* pUYVY,long width) { long expand8_width=(width>>3)<<3; if (expand8_width>0) { asm { mov ecx,expand8_width mov eax,pUYVY mov edx,pDstLine lea eax,[eax+ecx*2] lea edx,[edx+ecx*4] neg ecx loop_beign: UYVY_Loader_MMX(eax+ecx*2) YUV422ToRGB32_MMX(edx+ecx*4,movq) add ecx,8 jnz loop_beign mov pUYVY,eax mov pDstLine,edx } } //处理边界 DECODE_UYVY_Common_line(pDstLine, pUYVY, width-expand8_width); } //在x86CPU上可以使用CPUID指令来得到各种关于当前CPU的特性, //包括制造商、CPU家族号、缓存信息、是否支持MMX\SSE\SSE2指令集 等等; //要使用CPUID指令,首先应该判断CPU是否支持该指令;方法是判断EFLAGS寄存器的第21位 //是否可以改写;如果可以改写,那么说明这块CPU支持CPUID指令 bool _CPUSupportCPUID() { long int CPUIDInfOld = 0; long int CPUIDInfNew = 0; try { asm { pushfd // 保存原 EFLAGS pop eax mov edx, eax mov CPUIDInfOld, eax // xor eax, 00200000h // 改写 第21位 push eax popfd // 改写 EFLAGS pushfd // 保存新 EFLAGS pop eax mov CPUIDInfNew, eax push edx // 恢复原 EFLAGS popfd } return (CPUIDInfOld != CPUIDInfNew); // EFLAGS 第21位 可以改写 } catch(...) { return false; } } //那么判断CPU是否支持MMX指令的函数如下: bool _CPUSupportMMX() //判断CPU是否支持MMX指令 { if (!_CPUSupportCPUID()) return false; long int MMXInf=0; try { asm { push ebx mov eax,1 cpuid mov MMXInf,edx pop ebx } MMXInf=MMXInf & (1 << 23); //检测edx第23位 return (MMXInf == (1 << 23)); } catch(...) { return false; } } const bool _IS_MMX_ACTIVE = _CPUSupportMMX(); typedef void (*TDECODE_UYVY_line_proc)(TARGB32 *pDstLine, const TUInt8 *pUYVY, long width); const TDECODE_UYVY_line_proc DECODE_UYVY_Auto_line = ( _IS_MMX_ACTIVE ? DECODE_UYVY_MMX_line : DECODE_UYVY_Common_line ); __forceinline void DECODE_filish() { if (_IS_MMX_ACTIVE) { asm emms } } void DECODE_UYVY_Auto(const TUInt8 *pUYVY, const TPicRegion &DstPic) { long YUV_byte_width = (DstPic.width >> 1) << 2; TARGB32 *pDstLine = DstPic.pdata; for (long y = 0 ; y < DstPic.height ; ++y) { DECODE_UYVY_Auto_line(pDstLine, pUYVY, DstPic.width); pUYVY += YUV_byte_width; ((TUInt8*&)pDstLine) += DstPic.byte_width; } DECODE_filish(); } struct TDECODE_UYVY_Parallel_WorkData { const TUInt8* pUYVY; TPicRegion DstPic; }; void DECODE_UYVY_Parallel_callback(void* wd) { TDECODE_UYVY_Parallel_WorkData* WorkData = (TDECODE_UYVY_Parallel_WorkData*)wd; DECODE_UYVY_Auto(WorkData->pUYVY, WorkData->DstPic); } bool DECODE_UYVY_TO_RGB32(const TUInt8 *pUYVY, const TPicRegion &DstPic) { if (NULL == pUYVY) { TRACE ("DECODE_UYVY_TO_RGB32() error, NULL == pUYVY\n"); return false; } if (NULL == DstPic.pdata) { TRACE ("DECODE_UYVY_TO_RGB32() error, NULL == DstPic.pdata\n"); return false; } //long work_count = CWorkThreadPool::best_work_count(); 将这句话注释掉,改为下面的语句即可 long work_count = 1; if (work_count > 1) { std::vector<TDECODE_UYVY_Parallel_WorkData> work_list(work_count); std::vector<TDECODE_UYVY_Parallel_WorkData*> pwork_list(work_count); long cheight = DstPic.height / work_count; for (long i = 0 ; i < work_count ; ++i) { work_list[i].pUYVY = pUYVY + i * cheight * (DstPic.width << 1); work_list[i].DstPic.pdata = DstPic.pixel_pos(0, cheight*i); work_list[i].DstPic.byte_width = DstPic.byte_width; work_list[i].DstPic.width = DstPic.width; work_list[i].DstPic.height = cheight; pwork_list[i] = &work_list[i]; } work_list[work_count-1].DstPic.height = DstPic.height-cheight*(work_count-1); // CWorkThreadPool::work_execute(DECODE_UYVY_Parallel_callback, (void**)&pwork_list[0],work_count); } else { DECODE_UYVY_Auto(pUYVY, DstPic); } return true; } bool DECODE_RGB_TO_BGRA(const unsigned char *pRGB, const TPicRegion &DstPic) { DWORD RGBcount = DstPic.width * DstPic.height; for (register int i=0 ; i<RGBcount ; i++) { DstPic.pdata[i].r = pRGB[i*3]; DstPic.pdata[i].g = pRGB[i*3+1]; DstPic.pdata[i].b = pRGB[i*3+2]; DstPic.pdata[i].a = 255; } return true; }
[ "damoguyan8844@00acd8f4-21d3-11df-8b29-c50f69cede6d" ]
[ [ [ 1, 377 ] ] ]
e0c548aba268f40655e75193d87fb71cfaf9121d
216ae2fd7cba505c3690eaae33f62882102bd14a
/utils/nxogre/include/NxOgreSceneRenderable.h
7d2d8e641f8e9b9267d29df00ce97c3112b96884
[]
no_license
TimelineX/balyoz
c154d4de9129a8a366c1b8257169472dc02c5b19
5a0f2ee7402a827bbca210d7c7212a2eb698c109
refs/heads/master
2021-01-01T05:07:59.597755
2010-04-20T19:53:52
2010-04-20T19:53:52
56,454,260
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,055
h
/** File: NxOgreXXX.h Created on: X-XXX-XX Author: Robin Southern "betajaen" SVN: $Id$ © Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org This file is part of NxOgre. NxOgre is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NxOgre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with NxOgre. If not, see <http://www.gnu.org/licenses/>. */ #ifndef NXOGRE_SCENERENDERABLE_H #define NXOGRE_SCENERENDERABLE_H #include "NxOgreStable.h" #include "NxOgreCommon.h" namespace NxOgre_Namespace { /** \brief 28 byte struct containing */ struct NxOgrePublicClass SceneRenderable { Vec3 mAlphaPosition; Vec4 mAlphaQuaternion; }; /** \brief A 32 byte struct to hold the last position of a RigidBody and the RigidBody itself. It is packed this way for memory reasons. */ struct NxOgrePublicClass RigidBodyRenderable : public SceneRenderable { RigidBody* mRigidBody; // This is the RigidBody. }; namespace Functions { #if 0 inline Matrix44 RigidBodyRenderableToMatrix44(RigidBodyRenderable& r) { Matrix44 m; Memory::copy(&m.m.m, &r.mAlphaPosition, 15 * sizeof(Real)); m.m.s._44 = Real(1.0); return m; } inline RigidBodyRenderable Matrix44ToRigidBodyRenderable(const Matrix44& m) { RigidBodyRenderable r; Memory::copy(&r.mAlpha, &m.m.m, 15 * sizeof(Real)); return r; } inline void interpolateRigidBodyRenderable(const TimeStep& ts, RigidBodyRenderable& r); #endif } NxOgre_CompileAssertion(sizeof(Real) == sizeof(RigidBody*), "Real and RigidBody must be the same size"); NxOgre_CompileAssertion(sizeof(RigidBodyRenderable) == 32, "RigidBodyRenderable must be 32 bytes"); } // namespace NxOgre_Namespace #endif
[ "umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b" ]
[ [ [ 1, 96 ] ] ]
ee45e5d80595d5ffb3402fc25b2d14deaf8e09d2
7b7a3f9e0cac33661b19bdfcb99283f64a455a13
/Engine/dll/ObjectLib/flx_terrain_patch.h
3d191b3e261ac00b2efe5604c67e46f666fb847f
[]
no_license
grimtraveller/fluxengine
62bc0169d90bfe656d70e68615186bd60ab561b0
8c967eca99c2ce92ca4186a9ca00c2a9b70033cd
refs/heads/master
2021-01-10T10:58:56.217357
2009-09-01T15:07:05
2009-09-01T15:07:05
55,775,414
0
0
null
null
null
null
UTF-8
C++
false
false
938
h
/*--------------------------------------------------------------------------- This source file is part of the FluxEngine. Copyright (c) 2008 - 2009 Marvin K. (starvinmarvin) This program is free software. ---------------------------------------------------------------------------*/ #ifndef _TERRAIN_PATCH_H #define _TERRAIN_PATCH_H #include "../Core/flx_core.h" #include "../MathLib/flx_vector3.h" #include "../Core/flx_ogl_buffer.h" class TerrainPatch { public: TerrainPatch(); virtual ~TerrainPatch(); void render(); flx_ogl_buffer<flx_Vertex> VertexBuffer; flx_ogl_buffer<flx_Normal> NormalBuffer; flx_ogl_buffer<flx_TexCoord> TexCoordBuffer; flx_ogl_buffer<flx_Index> IndexBuffer; std::vector<unsigned int> m_Indices[3]; flx_Vertex *patchVertices; flx_TexCoord *patchTexCoords; flx_Normal *patchNormals; unsigned int m_vertexCount; AABBox m_aabb; private: }; #endif
[ "marvin.kicha@e13029a8-578f-11de-8abc-d1c337b90d21" ]
[ [ [ 1, 39 ] ] ]
72413b453932761b50e53cf08b1057ced38e01c1
5e72c94a4ea92b1037217e31a66e9bfee67f71dd
/old/src/RTTPacketLossDetail.h
2d81bc192181c6d1457a8a57f6b49ac9682f4dbb
[]
no_license
stein1/bbk
1070d2c145e43af02a6df14b6d06d9e8ed85fc8a
2380fc7a2f5bcc9cb2b54f61e38411468e1a1aa8
refs/heads/master
2021-01-17T23:57:37.689787
2011-05-04T14:50:01
2011-05-04T14:50:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
257
h
#pragma once #include "includes.h" #include "TestDetailDialog.h" class RTTPacketLossDetail : public TestDetailDialog { public: RTTPacketLossDetail(wxWindow *parent, int row = 0); ~RTTPacketLossDetail(void); void RefreshList(int irow); };
[ [ [ 1, 13 ] ] ]
1ac1c3db8b62d5f970f7058998a0a55f3770dd99
5bd189ea897b10ece778fbf9c7a0891bf76ef371
/BasicEngine/BasicEngine/Game/FPSCounter.h
fb58174ba5c112a912c69f5be11339118126003c
[]
no_license
boriel/masterullgrupo
c323bdf91f5e1e62c4c44a739daaedf095029710
81b3d81e831eb4d55ede181f875f57c715aa18e3
refs/heads/master
2021-01-02T08:19:54.413488
2011-12-14T22:42:23
2011-12-14T22:42:23
32,330,054
0
0
null
null
null
null
ISO-8859-2
C++
false
false
561
h
/* Class: FPSCounter. Con esto tenemos información de a que velocidada o Frame per Second se ve nuestro juego */ #ifndef FPSCOUNTER_H_ #define FPSCOUNTER_H_ #include "..\Utility\Singleton.h" class cFPSCounter : public cSingleton<cFPSCounter> { friend class cSingleton<cFPSCounter>; public: void Init(); void Deinit(); void Update(float lfTimestep); float GetFPS () { return mfFPS; } private: float mfUpdateInterval; float mfTimeSinceLastUpdate; float mfFrameCount; float mfFPS; }; #endif
[ "[email protected]@f2da8aa9-0175-0678-5dcd-d323193514b7", "davidvargas.tenerife@f2da8aa9-0175-0678-5dcd-d323193514b7" ]
[ [ [ 1, 16 ], [ 21, 21 ], [ 23, 23 ], [ 25, 36 ] ], [ [ 17, 20 ], [ 22, 22 ], [ 24, 24 ] ] ]
249e1c1f21b6a43892e31831b9f05b64029ba9f9
cfc9acc69752245f30ad3994cce0741120e54eac
/bikini/private/source/flash/gameswf/base/tu_file_SDL.cpp
c6f997b6572357a84c8743e317025033d23c63b5
[]
no_license
Heartbroken/bikini-iii
3b7852d1af722b380864ac87df57c37862eb759b
93ffa5d43d9179b7c5e7f7c2df9df7dafd79a739
refs/heads/master
2020-03-28T00:41:36.281253
2009-04-30T14:58:10
2009-04-30T14:58:10
37,190,689
0
0
null
null
null
null
ISO-8859-10
C++
false
false
2,696
cpp
// tu_file_SDL.cpp -- Ignacio Castaņo, Thatcher Ulrich <[email protected]> 2003 // This source code has been donated to the Public Domain. Do // whatever you want with it. // tu_file constructor, for creating a tu_file from an SDL_RWops* // stream. In its own source file so that if clients of the base // library don't call it, it won't get pulled in by the linker and // won't try to link with SDL. #include "base/tu_file.h" #include "base/utility.h" #include <SDL.h> // TODO: add error detection and reporting!!! static int sdl_read_func(void* dst, int bytes, void* appdata) { assert(dst); assert(appdata); int result = SDL_RWread((SDL_RWops*) appdata, dst, 1, bytes); if (result == -1) { // @@ set appdata->m_error? return 0; } return result; } static int sdl_write_func(const void* src, int bytes, void* appdata) { assert(src); assert(appdata); int result = SDL_RWwrite((SDL_RWops*) appdata, src, 1, bytes); if (result == -1) { // @@ set m_errer? return 0; } return result; } static int sdl_seek_func(int pos, void *appdata) { assert(pos >= 0); assert(appdata); return SDL_RWseek((SDL_RWops*) appdata, pos, SEEK_SET); } static int sdl_seek_to_end_func(void *appdata) { assert(appdata); return SDL_RWseek((SDL_RWops*) appdata, 0, SEEK_END); } static int sdl_tell_func(const void *appdata) { assert(appdata); return SDL_RWtell((SDL_RWops*) appdata); } static bool sdl_get_eof_func(void* appdata) { assert(appdata); int cur_pos = sdl_tell_func(appdata); sdl_seek_to_end_func(appdata); int end_pos = sdl_tell_func(appdata); if (end_pos <= cur_pos) { return true; } else { sdl_seek_func(cur_pos, appdata); return false; } } static int sdl_close_func(void *appdata) { assert(appdata); int result = SDL_RWclose((SDL_RWops*) appdata); if (result != 0) { return TU_FILE_CLOSE_ERROR; } return 0; } tu_file::tu_file(SDL_RWops* sdl_stream, bool autoclose) // Create a tu_file object that can be used to read/write stuff. Use // an SDL_RWops* as the underlying implementation. // // If autoclose is true, then the sdl_stream has SDL_RWclose() // called on it when the resulting file object is destructed. { assert(sdl_stream); m_data = (void*) sdl_stream; m_read = sdl_read_func; m_write = sdl_write_func; m_seek = sdl_seek_func; m_seek_to_end = sdl_seek_to_end_func; m_tell = sdl_tell_func; m_get_eof = sdl_get_eof_func; m_close = autoclose ? sdl_close_func : NULL; m_error = TU_FILE_NO_ERROR; } // Local Variables: // mode: C++ // c-basic-offset: 8 // tab-width: 8 // indent-tabs-mode: t // End:
[ [ [ 1, 120 ] ] ]
6113d8504ddd3bc6fab6f56207c37db3a7a846c2
8e4d21a99d0ce5413eab7a083544aff9f944b26f
/include/NthShape.h
66ac36a335aad31aa9aac765a508d060a1546858
[]
no_license
wangjunbao/nontouchsdk
957612b238b8b221b4284efb377db220bd41186a
81ab8519ea1af45dbb7ff66c6784961f14f9930c
refs/heads/master
2021-01-23T13:57:20.020732
2010-10-31T12:03:49
2010-10-31T12:03:49
34,656,556
0
0
null
null
null
null
UTF-8
C++
false
false
410
h
/* * NthShape.h * CopyRight @South China Institute of Software Engineering,.GZU * Author: * 2010/10/20 */ #ifndef NTHSHAPE_H #define NTHSHAPE_H #include "nthgraphics.h" #ifdef DLL_FILE class _declspec(dllexport) NthShape : public NthGraphics #else class _declspec(dllimport) NthShape : public NthGraphics #endif { public: NthShape(void); ~NthShape(void); }; #endif
[ "tinya0913@6b3f5b0f-ac10-96f7-b72e-cc4b20d3e213" ]
[ [ [ 1, 27 ] ] ]
bcf224db4757d2652ba689ae64d1cc83ccc90656
3187b0dd0d7a7b83b33c62357efa0092b3943110
/src/dlib/sockets/sockets_extensions.h
f3b1b8231a03403c7d80d3b33df04c8168a3abcf
[ "BSL-1.0" ]
permissive
exi/gravisim
8a4dad954f68960d42f1d7da14ff1ca7a20e92f2
361e70e40f58c9f5e2c2f574c9e7446751629807
refs/heads/master
2021-01-19T17:45:04.106839
2010-10-22T09:11:24
2010-10-22T09:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,316
h
// Copyright (C) 2006 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_SOCKETS_EXTENSIONs_ #define DLIB_SOCKETS_EXTENSIONs_ #include <string> #include "../sockets.h" #include "sockets_extensions_abstract.h" namespace dlib { // ---------------------------------------------------------------------------------------- connection* connect ( const std::string& host_or_ip, unsigned short port ); // ---------------------------------------------------------------------------------------- connection* connect ( const std::string& host_or_ip, unsigned short port, unsigned long timeout ); // ---------------------------------------------------------------------------------------- bool is_ip_address ( std::string ip ); // ---------------------------------------------------------------------------------------- void close_gracefully ( connection* con, unsigned long timeout = 500 ); // ---------------------------------------------------------------------------------------- } #ifdef NO_MAKEFILE #include "sockets_extensions.cpp" #endif #endif // DLIB_SOCKETS_EXTENSIONs_
[ [ [ 1, 50 ] ] ]
6ab88aafd890c6676181dc24220b8355740f83ad
324524076ba7b05d9d8cf5b65f4cd84072c2f771
/Checkers/Libraries/eString/Main.cpp
5a3ff4e16921a43aeadc179db44bbf69db8e60f9
[ "BSD-2-Clause" ]
permissive
joeyespo-archive/checkers-c
3bf9ff11f5f1dee4c17cd62fb8af9ba79246e1c3
477521eb0221b747e93245830698d01fafd2bd66
refs/heads/master
2021-01-01T05:32:45.964978
2011-03-13T04:53:08
2011-03-13T04:53:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
305
cpp
// Main.cpp // Entry Point of Library // By Joe Esposito // !!!!! TODO !!!!! // ---------------------------------------------------------------------------- // // - Fix up eString. // // ---------------------------------------------------------------------------- #include "Main.h"
[ [ [ 1, 14 ] ] ]
cedae2b82671333a2890915d2734d13f4997e6d7
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleRender/TRenderTarget.cpp
a2b676cfdb4e7aa49cfd3283a246e641de593edb
[]
no_license
SoylentGraham/Tootle
4ae4e8352f3e778e3743e9167e9b59664d83b9cb
17002da0936a7af1f9b8d1699d6f3e41bab05137
refs/heads/master
2021-01-24T22:44:04.484538
2010-11-03T22:53:17
2010-11-03T22:53:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,289
cpp
#include "TRenderTarget.h" #include "TScreen.h" #include "TScreenManager.h" #include "TRenderGraph.h" #if defined(TL_USER_GRAHAM) #define VERIFY_MESH_BEFORE_DRAW #endif //#define DEBUG_RENDER_DATUMS_IN_WORLD // if not defined, renders datums in local space which is faster (in world space will show up transform multiplication errors) #define DEBUG_RENDER_ALL_DATUMS FALSE #define DEBUG_DATUMS_FORCE_RECALC FALSE // when true will force the render node code to use the GetWorldTransform call that goes UP the render tree #define DEBUG_ALWAYS_RESET_SCENE FALSE // if things render incorrectly it suggests our calculated scene transform is incorrect #if defined(_DEBUG) && !defined(TL_TARGET_IPOD) && !defined(TL_TARGET_IPAD) //#define DEBUG_DRAW_RENDERZONES #define DEBUG_DRAW_FRUSTUM //#define DEBUG_NODE_RENDERED_COUNT #endif #define VISIBILITY_FRUSTUM_TEST_FIRST //#define PREDIVIDE_RENDER_ZONES #define FORCE_COLOUR Colour_TColour //----------------------------------------------------------- // //----------------------------------------------------------- TLRender::TRenderTarget::TRenderTarget(const TRef& Ref) : m_Size ( g_MaxSize, g_MaxSize, g_MaxSize, g_MaxSize ), m_Ref ( Ref ), m_Debug_SceneCount ( 0 ), m_Debug_PolyCount ( 0 ), m_Debug_VertexCount ( 0 ), m_Debug_NodeCount ( 0 ), m_Debug_NodeCulledCount ( 0 ), m_ScreenZ ( 0 ), m_pRootQuadTreeZone ( NULL ) { // set default flags m_Flags.Set( Flag_Enabled ); m_Flags.Set( Flag_ClearColour ); m_Flags.Set( Flag_ClearDepth ); // gr: turned off default anti-aliasing as it doesn't work on the ipod // m_Flags.Set( Flag_AntiAlias ); // calc initial size OnSizeChanged(); } //------------------------------------------------------------ // start render process //------------------------------------------------------------ void TLRender::TRenderTarget::Draw(TLRaster::TRasteriser& Rasteriser) { s32 StartingSceneCount = m_Debug_SceneCount; // render the clear object if we have it #ifndef TLRENDER_DISABLE_CLEAR if ( m_pRenderNodeClear ) { DrawNode( Rasteriser, *m_pRenderNodeClear, NULL, NULL, TColour( 1.f, 1.f, 1.f, 1.f ), NULL ); } #endif // update the camera's zone Bool CameraInWorldZone = TRUE; if ( m_pRootQuadTreeZone ) { if ( m_pCamera->IsZoneOutOfDate() ) { TLMaths::TQuadTreeNode* pCameraQuadTreeNode = m_pCamera; m_pCamera->UpdateZone( *m_pRootQuadTreeZone ); } if ( !m_pCamera->GetZone() ) CameraInWorldZone = FALSE; } // if the camera is outside the world zone, then all our render objects must be (assuming world zone is big enough) out of visibility too if ( CameraInWorldZone ) { // draw the root render object and the rest will follow TRenderNode* pRootRenderNode = GetRootRenderNode(); if ( pRootRenderNode ) { DrawNode( Rasteriser, *pRootRenderNode, NULL, NULL, TColour( 1.f, 1.f, 1.f, 1.f ), m_pRootQuadTreeZone ? m_pCamera.GetObjectPointer() : NULL ); } } // scene count should be zero after drawing... if ( StartingSceneCount != m_Debug_SceneCount ) { TLDebug_Break( TString("More scenes active(%d) than we started with (%d)", m_Debug_SceneCount, StartingSceneCount ) ); m_Debug_SceneCount = 0; } } //------------------------------------------------------------- // get the render target's dimensions. we need the screen in case dimensions are max's //------------------------------------------------------------- void TLRender::TRenderTarget::GetSize(Type4<s32>& Size,const Type4<s32>& MaxSize) const { // init to size then correct the max-extents as neccesary Size = m_Size; if ( Size.x == g_MaxSize ) Size.x = MaxSize.x; if ( Size.y == g_MaxSize ) Size.y = MaxSize.y; if ( Size.Width() == g_MaxSize ) Size.Width() = MaxSize.Width(); if ( Size.Height() == g_MaxSize ) Size.Height() = MaxSize.Height(); } //------------------------------------------------------------- // do any recalculations we need to when the render target's size changes //------------------------------------------------------------- void TLRender::TRenderTarget::OnSizeChanged() { // setup view boxes of camera TPtr<TCamera>& pCamera = GetCamera(); if ( pCamera ) { // todo: replace this screen pointer with proper one when screen owner gets stored on render target TPtr<TLRender::TScreen>& pScreen = TLRender::g_pScreenManager->GetDefaultScreen(); if ( pScreen ) { Type4<s32> RenderTargetMaxSize = pScreen->GetRenderTargetMaxSize(); Type4<s32> ViewportSize = pScreen->GetViewportSize(); Type4<s32> RenderTargetSize; GetSize( RenderTargetSize, RenderTargetMaxSize ); pCamera->SetRenderTargetSize( RenderTargetSize, RenderTargetMaxSize, ViewportSize, pScreen->GetScreenShape() ); } } } //--------------------------------------------------------------- // get world pos from 2d point inside our rendertarget size //--------------------------------------------------------------- Bool TLRender::TRenderTarget::GetWorldRay(TLMaths::TLine& WorldRay,const Type2<s32>& RenderTargetPos,const Type4<s32>& RenderTargetSize,TScreenShape ScreenShape) const { if ( !m_pCamera ) return FALSE; return m_pCamera->GetWorldRay( WorldRay, RenderTargetPos, RenderTargetSize, ScreenShape ); } //--------------------------------------------------------------- // get world pos from 2d point inside our rendertarget size //--------------------------------------------------------------- Bool TLRender::TRenderTarget::GetWorldPos(float3& WorldPos,float WorldDepth,const Type2<s32>& RenderTargetPos,const Type4<s32>& RenderTargetSize,TScreenShape ScreenShape) const { if ( !m_pCamera ) return FALSE; return m_pCamera->GetWorldPos( WorldPos, WorldDepth, RenderTargetPos, RenderTargetSize, ScreenShape ); } // Get screen pos from 3d world pos Bool TLRender::TRenderTarget::GetRenderTargetPos(Type2<s32>& RenderTargetPos, const float3& WorldPos,const Type4<s32>& RenderTargetSize,TScreenShape ScreenShape) const { if ( !m_pCamera ) return FALSE; return m_pCamera->GetRenderTargetPos( RenderTargetPos, WorldPos, RenderTargetSize, ScreenShape ); } //--------------------------------------------------------------- // gets the render node at the root //--------------------------------------------------------------- TLRender::TRenderNode* TLRender::TRenderTarget::GetRootRenderNode() const { return TLRender::g_pRendergraph->FindNode( m_RootRenderNodeRef ); } //--------------------------------------------------------------- // check zone of node against camera's zone to determine visibility. // if no scene transform is provided then we only do quick tests with no calculations. // This can result in a SyncWait returned which means we need to do calculations to make sure of visibility //--------------------------------------------------------------- SyncBool TLRender::TRenderTarget::IsRenderNodeVisible(TRenderNode& RenderNode,TLMaths::TQuadTreeNode*& pRenderZoneNode,TLMaths::TQuadTreeNode* pCameraZoneNode,const TLMaths::TTransform* pSceneTransform,Bool& RenderNodeIsInsideCameraZone) { // no camera zone, so must be visible (assume no culling) if ( !pCameraZoneNode ) return SyncTrue; Bool QuickTest = (pSceneTransform == NULL); SyncBool IsTransformUpToDate = RenderNode.IsWorldTransformValid(); SyncBool IsZoneUpToDate = SyncWait; // find our render zone node if ( !pRenderZoneNode ) { pRenderZoneNode = RenderNode.GetRenderZoneNode( GetRef() ); // if we have a zone, then set the up-to-date value if ( pRenderZoneNode ) IsZoneUpToDate = pRenderZoneNode->IsZoneOutOfDate() ? SyncFalse : SyncTrue; #ifdef VISIBILITY_FRUSTUM_TEST_FIRST // dont have a zone yet, the transform is NOT up to date, so cull test will fail anyway if ( !pRenderZoneNode && IsTransformUpToDate != SyncTrue ) return SyncWait; #else // dont have a zone yet, if we're doing a quick test then abort and we'll create one later if ( !pRenderZoneNode && QuickTest ) return SyncWait; #endif // VISIBILITY_FRUSTUM_TEST_FIRST // dont have a node for a zone yet, lets add one if ( !pRenderZoneNode ) { pRenderZoneNode = new TRenderZoneNode( RenderNode.GetNodeRef() ); // hold onto our new ZoneNode in our list if( !RenderNode.SetRenderZoneNode( GetRef(), pRenderZoneNode ) ) { TLDebug_Break("Failed to add new render zone node to render node"); return SyncFalse; } // do has-shape test first if ( !pRenderZoneNode->HasZoneShape() ) { if ( QuickTest ) return SyncWait; else return SyncFalse; } // add node to the zone tree if ( !m_pRootQuadTreeZone->AddNode( *pRenderZoneNode, TRUE ) ) { // node is outside of root zone... // gr: assuming in quicktest the world scene transform of the render node is out of date so fails to be added to the quad tree... if ( QuickTest ) return SyncWait; else return SyncFalse; } // update up-to-date state IsZoneUpToDate = pRenderZoneNode->IsZoneOutOfDate() ? SyncFalse : SyncTrue; } } else { IsZoneUpToDate = pRenderZoneNode->IsZoneOutOfDate() ? SyncFalse : SyncTrue; } // quick frustum test first #ifdef VISIBILITY_FRUSTUM_TEST_FIRST if ( IsTransformUpToDate == SyncTrue ) { const TLMaths::TBox2D& FrustumBox = GetCamera()->GetZoneShape(); if ( FrustumBox.IsValid() ) { // test bounds against frustum box SyncBool NodeInZoneShape = pRenderZoneNode->IsInShape( FrustumBox ); // if we got a valid intersection result then return the visibility if ( NodeInZoneShape != SyncWait ) { return NodeInZoneShape; } else { // get a syncwait if the scenetransform of the render node is out of date if ( !QuickTest ) { TLDebug_Break("This test shouldnt fail unless we're in a quick test and the render node's scene transform is out of date"); } } } } #endif //VISIBILITY_FRUSTUM_TEST_FIRST // zone needs updating if ( !IsZoneUpToDate ) { if ( QuickTest ) return SyncWait; // update zone pRenderZoneNode->UpdateZone( *m_pRootQuadTreeZone ); } // if the zone we are inside, is inside the camera zone, then render (this should be the most likely case) TLMaths::TQuadTreeZone* pRenderNodeZone = pRenderZoneNode->GetZone(); // if zones are not visible to each other, not visible if ( !IsZoneVisible( pCameraZoneNode, pRenderNodeZone, pRenderZoneNode, RenderNodeIsInsideCameraZone ) ) return SyncFalse; #ifndef VISIBILITY_FRUSTUM_TEST_FIRST // one final actual frustum culling test if ( !QuickTest ) { SyncBool NodeInZoneShape = pRenderZoneNode->IsInShape( pCameraZoneNode->GetZoneShape() ); if ( NodeInZoneShape == SyncWait ) { TLDebug_Break("Check how to handle this..."); } return NodeInZoneShape; } #endif //!VISIBILITY_FRUSTUM_TEST_FIRST return SyncWait; } //--------------------------------------------------------------- // //--------------------------------------------------------------- Bool TLRender::TRenderTarget::IsZoneVisible(TLMaths::TQuadTreeNode* pCameraZoneNode,TLMaths::TQuadTreeZone* pZone,TLMaths::TQuadTreeNode* pZoneNode,Bool& RenderNodeIsInsideCameraZone) { // no camera node, no culling if ( !pCameraZoneNode ) return TRUE; const TLMaths::TQuadTreeZone* pCameraZone = pCameraZoneNode->GetZone(); // no render zone, assume node/camera is out outside of root zone if ( !pZone || !pCameraZone ) return FALSE; // our zone is directly under the camera's zone if ( pZone->GetParentZone() == pCameraZone ) { // render node is below camera zone RenderNodeIsInsideCameraZone = TRUE; return TRUE; } // our zone is under the camera's zone, but not directly, so it's possible our zone is NOT being intersected by the camera if ( pZone->IsBelowZone( pCameraZone ) ) { /* // loop through child zone's of camera zone const TPtrArray<TQuadTreeZone>& CameraChildZones = pCameraZone->GetChildZones(); for ( u32 c=0; c<CameraChildZones.GetSize(); c++ ) { // are we under this } */ // quick shape test... if ( !pCameraZoneNode->IsInZoneShape( *pZone ) ) return FALSE; // render node is below camera zone RenderNodeIsInsideCameraZone = TRUE; return TRUE; } // if the camera's zone is inside this node's zone, then this node is bigger than the camera's visiblity and spans multiple zones if ( pCameraZone->IsBelowZone( pZone ) ) { if ( pZoneNode ) { // the render node is intersecting specific zones, there's a case it's still off camera const TFixedArray<u32,4>& NodeZoneChildIndexes = pZoneNode->GetChildZones(); if ( NodeZoneChildIndexes.GetSize() > 0 && NodeZoneChildIndexes.GetSize() < 4 ) { Bool IsInsideChildZone = FALSE; for ( u32 c=0; c<NodeZoneChildIndexes.GetSize(); c++ ) { const TPtr<TLMaths::TQuadTreeZone>& pChildZone = pZone->GetChildZones().ElementAtConst( NodeZoneChildIndexes[c] ); if ( pCameraZone->IsBelowZone( pChildZone ) ) { IsInsideChildZone = TRUE; break; } } // the zones the render node is intersecting doesnt include the one the camera is in. not visible! if ( !IsInsideChildZone ) return FALSE; } } // render node is above camera zone RenderNodeIsInsideCameraZone = FALSE; return TRUE; } return FALSE; } //--------------------------------------------------------------- // render a render node //--------------------------------------------------------------- Bool TLRender::TRenderTarget::DrawNode(TLRaster::TRasteriser& Rasteriser,TRenderNode& RenderNode,TRenderNode* pParentRenderNode,const TLMaths::TTransform* pSceneTransform,TColour SceneColour,TLMaths::TQuadTreeNode* pCameraZoneNode) { const TFlags<TRenderNode::RenderFlags::Flags>& RenderNodeRenderFlags = RenderNode.GetRenderFlags(); // not enabled, dont render if ( !RenderNodeRenderFlags.IsSet( TLRender::TRenderNode::RenderFlags::Enabled ) ) return FALSE; // if node colour is reset then set a new scene colour if ( RenderNodeRenderFlags.IsSet(TLRender::TRenderNode::RenderFlags::ResetColour) ) { SceneColour = RenderNode.GetColour(); } else { // merge colour of scene if ( RenderNode.IsColourValid() ) { SceneColour *= RenderNode.GetColour(); // alpha'd out (only applies if we're applying our colour, a la - IsColourValid) if ( SceneColour.GetAlphaf() < TLMaths_NearZero ) return FALSE; } } // do an initial fast-visibility test of the render node before calculating the scene transform TLMaths::TQuadTreeNode* pRenderZoneNode = NULL; Bool RenderNodeIsInsideCameraZone = FALSE; SyncBool IsInCameraRenderZone = SyncWait; // do cull test if enabled on node if ( pCameraZoneNode && RenderNodeRenderFlags.IsSet( TLRender::TRenderNode::RenderFlags::EnableCull ) ) { // pass in NULL as the scene transform to do a very quick zone test - skips calculating bounds etc IsInCameraRenderZone = IsRenderNodeVisible( RenderNode, pRenderZoneNode, pCameraZoneNode, NULL, RenderNodeIsInsideCameraZone ); // after quick check we know the node is in a zone the camera cannot see if ( IsInCameraRenderZone == SyncFalse ) { m_Debug_NodeCulledCount++; return FALSE; } } else { // no cull testing, set as visible and mark as inside zone so we won't do any tests further down the tree IsInCameraRenderZone = SyncTrue; RenderNodeIsInsideCameraZone = TRUE; } // do minimal calcuations to calc scene transformation - yes code is a bit of a pain, but this is very good for us :) // only problem is, we can't reuse this code in another func as we lose the reference initialisation, which is the whole speed saving Bool ResetScene = RenderNodeRenderFlags.IsSet(TLRender::TRenderNode::RenderFlags::ResetScene); TLMaths::TTransform NewSceneTransform; const TLMaths::TTransform& NodeTransform = RenderNode.GetTransform(); Bool NodeTrans = NodeTransform.HasAnyTransform() || ResetScene; Bool SceneTrans = (pSceneTransform && !ResetScene) ? pSceneTransform->HasAnyTransform() : FALSE; // work out which transform we are actually using... const TLMaths::TTransform& SceneTransform = (NodeTrans&&SceneTrans) ? NewSceneTransform : ( (NodeTrans||!pSceneTransform) ? NodeTransform : *pSceneTransform ); // using a new scene transform, so calculate it if ( NodeTrans && SceneTrans ) { NewSceneTransform = *pSceneTransform; NewSceneTransform.Transform( NodeTransform ); } // set latest world/scene transform RenderNode.SetWorldTransform( SceneTransform ); // full visibility check of node, if not visible then skip render (and of children) if ( IsInCameraRenderZone == SyncWait ) { IsInCameraRenderZone = IsRenderNodeVisible( RenderNode, pRenderZoneNode, pCameraZoneNode, &SceneTransform, RenderNodeIsInsideCameraZone ); if ( IsInCameraRenderZone == SyncFalse ) { m_Debug_NodeCulledCount++; return FALSE; } } // count node as rendered m_Debug_NodeCount++; // get raster data from node { TFixedArray<TLRaster::TRasterData,20> MeshRenderData; TFixedArray<TLRaster::TRasterSpriteData,20> SpriteRenderData; TPtrArray<TLAsset::TMesh> TemporaryMeshes; // generic render of the node const TLRaster::TRasterData* pMainRaster = RenderNode.Render( MeshRenderData, SpriteRenderData, SceneColour ); // render debug stuff on the node #if defined(_DEBUG) { RenderNode.Debug_Render( MeshRenderData, SpriteRenderData, pMainRaster, TemporaryMeshes ); } #endif // _DEBUG // render this raster data Rasteriser.Render( MeshRenderData ); Rasteriser.Render( SpriteRenderData ); // send temporary meshes to the rasteriser so they're still valid until the rasteriser is finished Rasteriser.StoreTemporaryMeshes( TemporaryMeshes ); } // if this render node is in a zone under the camera's zone, then we KNOW the child nodes are going to be visible, so we dont need to provide the camera's // render zone. Will just mean we can skip render zone checks // gr: this isn't quite right atm, just check the flag for now //TLMaths::TQuadTreeNode* pChildCameraZoneNode = RenderNodeIsInsideCameraZone ? NULL : pCameraZoneNode; //TLMaths::TQuadTreeNode* pChildCameraZoneNode = pCameraZoneNode; TLMaths::TQuadTreeNode* pChildCameraZoneNode = pCameraZoneNode; // check if we can skip culling for children if ( pChildCameraZoneNode ) { // if no culling, and children dont need to be forced to check culling, then remove camera zone for children (will skip visibility testing) if ( !RenderNodeRenderFlags.IsSet( TLRender::TRenderNode::RenderFlags::EnableCull ) && !RenderNodeRenderFlags.IsSet( TLRender::TRenderNode::RenderFlags::ForceCullTestChildren ) ) { pChildCameraZoneNode = NULL; } else if ( RenderNodeIsInsideCameraZone ) { // our node is underneath/in same zone as the camera's zone, so we know it'll be in a visible zone //pChildCameraZoneNode = NULL; } else { // our node isnt underneath the camera's zone -just visible- so we need to test again } } // process children TPointerArray<TLRender::TRenderNode>& NodeChildren = RenderNode.GetChildren(); u32 ChildCount = NodeChildren.GetSize(); if ( ChildCount > 0 ) { TLMaths::TTransform ChildSceneTransform = SceneTransform; RenderNode.PreDrawChildren( *this, ChildSceneTransform); // render children for ( u32 c=0; c<ChildCount; c++ ) { TLRender::TRenderNode* pChild = NodeChildren[c]; // draw child DrawNode( Rasteriser, *pChild, &RenderNode, &ChildSceneTransform, SceneColour, pChildCameraZoneNode ); } RenderNode.PostDrawChildren( *this ); } return TRUE; } //------------------------------------------------------------- // //------------------------------------------------------------- void TLRender::TRenderTarget::SetRootQuadTreeZone(TLMaths::TQuadTreeZone* pQuadTreeZone) { if ( m_pRootQuadTreeZone == pQuadTreeZone ) return; // clean up the old one if ( m_pRootQuadTreeZone ) { m_pRootQuadTreeZone->Shutdown(); TLMemory::Delete( m_pRootQuadTreeZone ); } // create new root zone m_pRootQuadTreeZone = pQuadTreeZone; if ( m_pRootQuadTreeZone ) { #ifdef PREDIVIDE_RENDER_ZONES // divide it all now m_pRootQuadTreeZone->DivideAll(); #endif } // invalidate camera's zone m_pCamera->SetZoneOutOfDate(); } //-------------------------------------------------- // //-------------------------------------------------- void TLRender::TRenderTarget::Debug_DrawZone(TLRaster::TRasteriser& Rasteriser,TLMaths::TQuadTreeZone& Zone,float zDepth,TLMaths::TQuadTreeNode* pCameraZoneNode) { TRenderNode TempRenderNode("xxx"); TempRenderNode.SetMeshRef("d_quad"); if ( pCameraZoneNode ) { Bool Dummy; if ( !IsZoneVisible( pCameraZoneNode, &Zone, NULL, Dummy ) ) return; } TempRenderNode.SetAlpha( 0.3f ); if ( pCameraZoneNode ) { if ( &Zone == pCameraZoneNode->GetZone() ) { TempRenderNode.GetRenderFlags().Clear( TLRender::TRenderNode::RenderFlags::UseVertexColours ); TempRenderNode.GetRenderFlags().Clear( TLRender::TRenderNode::RenderFlags::DepthRead ); TempRenderNode.SetAlpha( 1.f ); } } const TLMaths::TBox2D& ZoneBox = Zone.GetShape(); TempRenderNode.SetTranslate( ZoneBox.GetMin().xyz(zDepth) ); TempRenderNode.SetScale( ZoneBox.GetSize().xyz(1.f) ); DrawNode( Rasteriser, TempRenderNode, NULL, NULL, TColour(1.f,1.f,1.f,1.f), NULL ); for ( u32 z=0; z<Zone.GetChildZones().GetSize(); z++ ) { TLMaths::TQuadTreeZone& ChildZone = *(Zone.GetChildZones().ElementAt(z)); Debug_DrawZone( Rasteriser, ChildZone, zDepth + 0.01f, pCameraZoneNode ); } } //-------------------------------------------------- // same as GetWorldViewBox but can be used before a render //-------------------------------------------------- const TLMaths::TBox2D& TLRender::TRenderTarget::GetWorldViewBox(TPtr<TScreen>& pScreen,float WorldDepth) { /* // get render target size Type4<s32> Size; Type4<s32> MaxSize; pScreen->GetRenderTargetMaxSize( MaxSize ); GetSize( Size, MaxSize ); // calc viewport sizes and boxes etc will be valid m_pCamera->SetRenderTargetSize( Size, pScreen->GetScreenShape() ); */ return GetWorldViewBox( WorldDepth ); } //-------------------------------------------------- // //-------------------------------------------------- void TLRender::TRenderTarget::SetClearColour(const TColour& Colour) { // update colour of clear node if ( m_pRenderNodeClear ) { m_pRenderNodeClear->SetColour( Colour ); } // set new clear colour m_ClearColour = Colour; } //-------------------------------------------------- // //-------------------------------------------------- void TLRender::TRenderTarget::SetScreenZ(u8 NewZ) { if ( m_ScreenZ != NewZ ) { m_ScreenZ = NewZ; TLRender::g_pScreenManager->GetDefaultScreen()->OnRenderTargetZChanged( *this ); } }
[ [ [ 1, 14 ], [ 16, 166 ], [ 168, 168 ], [ 173, 173 ], [ 178, 545 ], [ 547, 563 ], [ 565, 689 ] ], [ [ 15, 15 ], [ 167, 167 ], [ 169, 172 ], [ 174, 177 ], [ 546, 546 ], [ 564, 564 ] ] ]
b486b7d2fb0c81a3d339aecaa8f49b904c8281a8
c267e416aba473054330378d18bc3cd172bbad21
/win7help/main.cpp
a911bbe8f03b655890d664ad6b7b82a1ff78dd49
[]
no_license
chenwp/shuax
c3b7dea72708ee539664ac8db1d9885e87fefed7
b13bea0aae7e252650f4c8f5df1b2a716455ef80
refs/heads/master
2021-04-26T16:43:25.168306
2011-10-22T15:09:37
2011-10-22T15:09:37
45,179,472
2
0
null
null
null
null
GB18030
C++
false
false
2,082
cpp
#define UNICODE #define _UNICODE #include <windows.h> #include <stdio.h> BOOL ReleaseRes(wchar_t *strFileName,WORD wResID,wchar_t *strFileType) { DWORD dwWrite=0; HANDLE hFile = CreateFile(strFileName, GENERIC_WRITE,FILE_SHARE_WRITE,NULL, CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); HRSRC hrsc = FindResource(NULL, MAKEINTRESOURCE(wResID), strFileType); HGLOBAL hG = LoadResource(NULL, hrsc); DWORD dwSize = SizeofResource( NULL, hrsc); WriteFile(hFile,hG,dwSize,&dwWrite,NULL); CloseHandle( hFile ); return TRUE; } BOOL IsWow64() { typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); LPFN_ISWOW64PROCESS fnIsWow64Process; BOOL bIsWow64 = FALSE; fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(L"kernel32"),"IsWow64Process"); if (NULL != fnIsWow64Process) { fnIsWow64Process(GetCurrentProcess(),&bIsWow64); } return bIsWow64; } int main() { wchar_t title[]=L"Windows7帮助文件关联工具"; OSVERSIONINFO info; info.dwOSVersionInfoSize=sizeof(info); GetVersionEx(&info); if(info.dwMajorVersion!=6||info.dwMinorVersion!=1) { MessageBox(0,L"对不起,本程序不支持您正在使用的系统。",title,MB_OK | MB_ICONWARNING); return 0; } wchar_t tips[512]; wsprintf(tips,L"您正在使用的是Windos7 x%d位系统,如果有误请选择“否”退出程序。",IsWow64()?64:86); if(IDNO==MessageBox(0,tips,title,MB_YESNO)) return 0; GetTempPath(512,tips); wcscat(tips,L"sx.msu"); ReleaseRes(tips,IsWow64()?64:86,L"MSU"); wcscat(tips,L"\""); wcsrev(tips); wcscat(tips,L"\" teiuq/"); wcsrev(tips); //printf("%ls",tips); ShellExecute(0, NULL,L"wusa",tips, NULL, SW_SHOWNORMAL); MessageBox(0,L"恭喜你,程序安装成功,现在可以打开.hlp文件。\n\n我的博客:www.shuax.com",title,MB_OK | MB_ICONINFORMATION); }
[ [ [ 1, 52 ] ] ]
20ec7fdaf6e266d6a3c0923fa7544d87221f670e
629e4fdc23cb90c0144457e994d1cbb7c6ab8a93
/lib/text/textgenerator.cpp
90e5693cd2d8ae0973930141bcf316a6590eddc3
[]
no_license
akin666/ice
4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2
7cfd26a246f13675e3057ff226c17d95a958d465
refs/heads/master
2022-11-06T23:51:57.273730
2011-12-06T22:32:53
2011-12-06T22:32:53
276,095,011
0
0
null
null
null
null
UTF-8
C++
false
false
4,631
cpp
/* * textgenerator.cpp * * Created on: 10.7.2011 * Author: akin */ #include "textgenerator.h" #include <system/global> namespace ice { bool TextGenerator::create( std::vector<UNICODE>& text , Font& font , TextMesh& mesh , glm::vec4 color , bool bold , bool italic ) { mesh.vertexes.clear(); mesh.textureCoordinates.clear(); mesh.colors.clear(); // Make sure all glyphs are loaded.. std::map< UNICODE, Glyph >& glyphs = font.getGlyphs(); glm::vec2 max; glm::vec2 line; unsigned int glyphCount = 0; ///// // SCAN ///// std::map< UNICODE, Glyph >::iterator iter; UNICODE current; line.x = 0; line.y = font.getSize(); for( unsigned int i = 0 ; i < text.size() ; ++i ) { current = text[i]; if( current == FL_LINE_FEED || current == FL_CARRIAGE_RETURN ) { // CR/LF or LF/CR if( text[i+1] == FL_CARRIAGE_RETURN || text[i+1] == FL_LINE_FEED ) { ++i; } line.y += font.getSize(); max.x = max.x > line.x ? max.x : line.x; max.y = max.y > line.y ? max.y : line.y; line.x = 0; // reset continue; } iter = glyphs.find( current ); if( iter == glyphs.end() ) { // not found! if( !font.load( current ) ) { // NOT FOUND! continue; // shit happens. } iter = glyphs.find( current ); } if( !iter->second.isEmpty() ) { ++glyphCount; } line.x += iter->second.getAdvance().x; } ///// // Setup mesh ///// mesh.vertexes.reserve( glyphCount * 6 ); mesh.textureCoordinates.reserve( glyphCount * 6 ); mesh.colors.reserve( glyphCount * 6 ); mesh.font = &font; glm::vec2 tmpVec2; glm::vec2 ta; glm::vec2 tb; glm::vec2 tc; glm::vec2 td; glm::vec3 pa; glm::vec3 pb; glm::vec3 pc; glm::vec3 pd; glm::vec2 convertor; glm::vec2 keybo; ///// // Render ///// line.x = 0; line.y = font.getSize(); for( unsigned int i = 0 ; i < text.size() ; ++i ) { current = text[i]; if( current == FL_LINE_FEED || current == FL_CARRIAGE_RETURN ) { // CR/LF or LF/CR if( text[i+1] == FL_CARRIAGE_RETURN || text[i+1] == FL_LINE_FEED ) { ++i; } line.y += font.getSize(); line.x = 0; continue; } if( current == FL_HORIZONTAL_TAB ) { line.x += font.getSize(); continue; } iter = glyphs.find( current ); if( iter == glyphs.end() ) { // does not exist. continue; } if( !iter->second.isEmpty() ) { // Renderable.. Glyph& glyph = iter->second; // GTexture coordinate calculations: td = glyph.getTextureLocation(); tb = glyph.getTextureLocation() + glyph.getTextureDimensions(); ta.x = td.x; ta.y = tb.y; tc.x = tb.x; tc.y = td.y; // Vertex coordinate calculations // & conversion to 3D from 2D. convertor = glyph.getOffset(); convertor.y = -convertor.y; convertor += line; pd = glm::vec3( convertor.x , convertor.y , 0.0f ); keybo = glyph.getSize(); pb = pd + glm::vec3( keybo , 0.0f ); pa.x = pd.x; pa.y = pb.y; pc.x = pb.x; pc.y = pd.y; mesh.vertexes.push_back( pa ); mesh.vertexes.push_back( pb ); mesh.vertexes.push_back( pc ); mesh.vertexes.push_back( pa ); mesh.vertexes.push_back( pc ); mesh.vertexes.push_back( pd ); mesh.textureCoordinates.push_back( td ); mesh.textureCoordinates.push_back( tc ); mesh.textureCoordinates.push_back( tb ); mesh.textureCoordinates.push_back( td ); mesh.textureCoordinates.push_back( tb ); mesh.textureCoordinates.push_back( ta ); mesh.colors.push_back( color ); mesh.colors.push_back( color ); mesh.colors.push_back( color ); mesh.colors.push_back( color ); mesh.colors.push_back( color ); mesh.colors.push_back( color ); } line.x += iter->second.getAdvance().x; } // buffer em. mesh.apply(); return true; } bool TextGenerator::create( std::vector<UNICODE>& text , TextFormat& format , TextMesh& mesh ) { Font *font = Global<Font>::get( format.getFontName() ); if( font == NULL ) { // Get defaultfont! // !TODO if( font == NULL ) { // Default font does not exist! return false; } } if( font == NULL ) { // No font! return false; } return create( text , *font , mesh , format.getColor() , format.getBold() , format.getItalic() ); } }
[ "akin@lich", "akin@localhost" ]
[ [ [ 1, 8 ], [ 10, 16 ], [ 18, 211 ], [ 213, 234 ] ], [ [ 9, 9 ], [ 17, 17 ], [ 212, 212 ] ] ]
0b4fca3c8053fcab2a63b2e57fdb120cadbf523c
bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918
/TPs CPOO/Gareth & Maxime/Projet/Wrapper/test2/mWrapper4/mWrapper4/Stdafx.cpp
5800a9a4902d9249ea8119bfc7a897dd384a2010
[]
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
ISO-8859-1
C++
false
false
224
cpp
// stdafx.cpp : fichier source incluant simplement les fichiers Include standard // mWrapper4.pch représente l'en-tête précompilé // stdafx.obj contient les informations de type précompilées #include "stdafx.h"
[ "havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6" ]
[ [ [ 1, 5 ] ] ]
dfd813692e4c162e7370a54652a9746435bd316d
26b6f15c144c2f7a26ab415c3997597fa98ba30a
/rtsp_sdk/inc/RTSPRequest.h
a83f47929ddf5e29971610002d6b4ea106e644b9
[]
no_license
wangscript007/rtspsdk
fb0b52e63ad1671e8b2ded1d8f10ef6c3c63fddf
f5b095f0491e5823f50a83352945acb88f0b8aa0
refs/heads/master
2022-03-09T09:25:23.988183
2008-12-27T17:23:31
2008-12-27T17:23:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,083
h
/***************************************************************************** // RTSP SDK Base Classes // // RTSP Request Message class // // description: // represents RTSP request message // // revision of last commit: // $Rev$ // author of last commit: // $Author$ // date of last commit: // $Date$ // // created by Argenet {[email protected]} // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // ******************************************************************************/ #ifndef __RTSP_REQUEST__H__ #define __RTSP_REQUEST__H__ #include "Poco/Net/Net.h" #include "rtsp_sdk.h" #include "RTSPMessage.h" namespace RTSP { class RTSP_SDK_API RTSPRequest: public RTSPMessage /// This class encapsulates an RTSP request /// message. /// /// In addition to the properties common to /// all RTSP messages, a RTSP request has /// a method (e.g. DESCRIBE, SETUP, PLAY, etc.) and /// a request URI. { public: RTSPRequest(); /// Creates an empty RTSP/1.0 RTSP request with no specified method. RTSPRequest(const std::string& version); /// Creates an empty RTSP request the given version /// (for possible future protocol extensions; only RTSP/1.0 is available now). RTSPRequest(const std::string& method, const std::string& uri); /// Creates a RTSP/1.0 request with the given method and URI. RTSPRequest(const std::string& method, const std::string& uri, const std::string& version); /// Creates a RTSP request with the given method, URI and version. virtual ~RTSPRequest(); /// Destroys the RTSPRequest. void setMethod(const std::string& method); /// Sets the method. const std::string& getMethod() const; /// Returns the method. void setURI(const std::string& uri); /// Sets the request URI. const std::string& getURI() const; /// Returns the request URI. bool hasCredentials() const; /// Returns true iff the request contains authentication /// information in the form of an Authorization header. void getCredentials(std::string& scheme, std::string& authInfo) const; /// Returns the authentication scheme and additional authentication /// information contained in this request. /// /// Throws a NotAuthenticatedException if no authentication information /// is contained in the request. void setCredentials(const std::string& scheme, const std::string& authInfo); /// Sets the authentication scheme and information for /// this request. void write(std::ostream& ostr) const; /// Writes the HTTP request to the given /// output stream. void read(std::istream& istr); /// Reads the HTTP request from the /// given input stream. static const std::string RTSP_NONE; static const std::string RTSP_DESCRIBE; static const std::string RTSP_ANNOUNCE; static const std::string RTSP_GET_PARAMETER; static const std::string RTSP_OPTIONS; static const std::string RTSP_PAUSE; static const std::string RTSP_PLAY; static const std::string RTSP_RECORD; static const std::string RTSP_REDIRECT; static const std::string RTSP_SETUP; static const std::string RTSP_SET_PARAMETER; static const std::string RTSP_TEARDOWN; static const std::string AUTHORIZATION; private: enum Limits { MAX_METHOD_LENGTH = 32, MAX_URI_LENGTH = 4096, MAX_VERSION_LENGTH = 8 }; std::string _method; std::string _uri; RTSPRequest(const RTSPRequest&); RTSPRequest& operator = (const RTSPRequest&); }; // // inlines // inline const std::string& RTSPRequest::getMethod() const { return _method; } inline const std::string& RTSPRequest::getURI() const { return _uri; } } // namespace RTSP #endif // __RTSP_REQUEST__H__
[ [ [ 1, 163 ] ] ]
5d253def0fd8b96c2d9cfa853b95cf036c938316
a7990bf2f56d927ae884db0e727c17394bda39c4
/image-approx/AlgorithmFactory.h
4463ff6feef00e52ecc380b9556158d23d097ef3
[]
no_license
XPaladin/image-approx
600862d8d76264e25f96ae10f3a9f5639a678b17
b0fbddef0e58ae1ba2b5e31f7eb87e2a48509dfb
refs/heads/master
2016-09-01T17:49:01.705563
2009-06-15T06:01:46
2009-06-15T06:01:46
33,272,564
0
0
null
null
null
null
UTF-8
C++
false
false
536
h
#ifndef ALGORITHMFACTORY_H_ #define ALGORITHMFACTORY_H_ #include "Algorithm.h" #include "QuadTreeAlgorithm.h" #include "BTreeAlgorithm.h" #include "Criterio.h" class AlgorithmFactory { protected: static AlgorithmFactory *instance; AlgorithmFactory(); public: enum AlgorithmEnum {QUADTREE, BTREE}; static AlgorithmFactory* getInstance(); virtual ~AlgorithmFactory(); virtual Algorithm *createAlgorithm(AlgorithmEnum type, Criterio* crit, int w,int h,int minSize); }; #endif /*ALGORITHMFACTORY_H_*/
[ "pala.sepu@17da7754-4e6e-11de-84bb-6bba061bd1d3" ]
[ [ [ 1, 22 ] ] ]
29400e26b975fbe29d953289d97724243b574cf2
bcebfeabcd5679e9d0eb01cd125c3923292ccf71
/trunk/CustomListView.h
0071ace154e94aa1283911471f3262edc39b6675
[]
no_license
BackupTheBerlios/feedit-svn
792e0a6a2aed5407ca8d58a756e43d618f2ce0da
44e9e5382e7fede28b24efb06f1fad0341a650f9
refs/heads/master
2020-06-02T00:22:36.175763
2006-09-07T01:10:46
2006-09-07T01:10:46
40,669,296
0
0
null
null
null
null
UTF-8
C++
false
false
1,335
h
#pragma once class CCustomListViewCtrl : public CWindowImpl<CCustomListViewCtrl, CListViewCtrl>, public CCustomDraw<CCustomListViewCtrl> { public: BEGIN_MSG_MAP(CCustomListViewCtrl) CHAIN_MSG_MAP(CCustomDraw<CCustomListViewCtrl>) END_MSG_MAP() #if (_WTL_VER >= 0x0700) BOOL m_bHandledCD; BOOL IsMsgHandled() const { return m_bHandledCD; } void SetMsgHandled(BOOL bHandled) { m_bHandledCD = bHandled; } #endif //(_WTL_VER >= 0x0700) DWORD OnPrePaint(int idCtrl, LPNMCUSTOMDRAW /*lpNMCustomDraw*/) { if(::IsWindow(m_hWnd) && idCtrl == GetDlgCtrlID()) { return CDRF_NOTIFYITEMDRAW; } else { SetMsgHandled(FALSE); return CDRF_DODEFAULT; } } DWORD OnItemPrePaint(int idCtrl, LPNMCUSTOMDRAW lpNMCustomDraw) { if(::IsWindow(m_hWnd) && idCtrl == GetDlgCtrlID()) { NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>(lpNMCustomDraw); NewsData* newsdata = dynamic_cast<NewsData*>((ListData*)GetItemData(pLVCD->nmcd.dwItemSpec)); if(newsdata != NULL) { if(newsdata->m_unread) ::SelectObject(pLVCD->nmcd.hdc, AtlCreateBoldFont()); if(newsdata->m_flagged) pLVCD->clrText = RGB(255, 0, 0); } return CDRF_NEWFONT; } else { SetMsgHandled(FALSE); return CDRF_DODEFAULT; } } };
[ "Sandro@b60034a5-fb9b-f04b-b957-2f3957cf9ea0" ]
[ [ [ 1, 62 ] ] ]
1231c4e3985ac24fddb9acc44ed7285c1962889e
57dbf4f198610ef4d449f6b882d5ed1072cfb190
/Arponaut.cpp
afdf6da749afc333e85ecdd8c19f5503baa2058d
[]
no_license
safetydank/Arponaut
b3d53ca8153a9f1a1034ee8361517d3e4da880a8
b62e36a8590aa8ceb9c0a3d68664b74beb9fd40b
refs/heads/master
2021-01-21T19:28:40.512906
2011-02-11T00:15:30
2011-02-11T00:15:30
1,353,054
2
1
null
null
null
null
UTF-8
C++
false
false
13,635
cpp
#include "Arponaut.h" #include "../IPlug_include_in_plug_src.h" #include "../IControl.h" #include "resource.h" #include <math.h> #include <algorithm> #include "logger.h" const int kNumPrograms = 1; Arponaut::Arponaut(IPlugInstanceInfo instanceInfo) : IPLUG_CTOR(kNumParams, 6, instanceInfo), lastPos_(0), arpIndex_(0), playing_(0) { TRACE; // Define parameter ranges, display units, labels. GetParam(kGainL)->InitDouble("Gain L", 0.0, -44.0, 12.0, 0.1, "dB"); GetParam(kGainL)->NegateDisplay(); GetParam(kGainR)->InitDouble("Gain R", 0.0, -44.0, 12.0, 0.1, "dB"); GetParam(kPan)->InitInt("Pan", 0, -100, 100, "%"); // Params can be enums. GetParam(kChannelSw)->InitEnum("Channel", kDefault, kNumChannelSwitchEnums); GetParam(kChannelSw)->SetDisplayText(kDefault, "default"); GetParam(kChannelSw)->SetDisplayText(kReversed, "reversed"); GetParam(kChannelSw)->SetDisplayText(kAllLeft, "all L"); GetParam(kChannelSw)->SetDisplayText(kAllRight, "all R"); GetParam(kChannelSw)->SetDisplayText(kOff, "mute"); GetParam(kNoteLength)->InitEnum("Note length", kWhole, kNumNoteLengths); GetParam(kNoteLength)->SetDisplayText(kWhole, "1/4"); GetParam(kNoteLength)->SetDisplayText(kHalf, "1/8"); GetParam(kNoteLength)->SetDisplayText(kTriplet, "1/8T"); GetParam(kNoteLength)->SetDisplayText(kQuarter, "1/16"); GetParam(kOctaves)->InitEnum("Octaves", kOne8ve, kNumNoteLengths); GetParam(kOctaves)->SetDisplayText(kOne8ve, "1 octave"); GetParam(kOctaves)->SetDisplayText(kTwo8ve, "2 octaves"); GetParam(kOctaves)->SetDisplayText(kThree8ve, "3 octaves"); GetParam(kOctaves)->SetDisplayText(kFour8ve, "4 octaves"); GetParam(kArpMode)->InitEnum("Arp modes", kUp, kNumArpModes); GetParam(kArpMode)->SetDisplayText(kUp, "Up"); GetParam(kArpMode)->SetDisplayText(kDown, "Down"); GetParam(kArpMode)->SetDisplayText(kUpDown, "Up/Down"); GetParam(kArpMode)->SetDisplayText(kManual, "Manual"); GetParam(kArpMode)->SetDisplayText(kRandom, "Random"); GetParam(kInsertMode)->InitEnum("Insert modes", kInsertOff, kNumInsertModes); GetParam(kInsertMode)->SetDisplayText(kInsertOff, "Off"); GetParam(kInsertMode)->SetDisplayText(kInsertLow, "Low"); GetParam(kInsertMode)->SetDisplayText(kInsertHi, "Hi"); GetParam(kInsertMode)->SetDisplayText(kInsert31, "3-1"); GetParam(kInsertMode)->SetDisplayText(kInsert42, "4-2"); MakePreset("preset 1", -5.0, 5.0, 17, kReversed); MakePreset("preset 2", -15.0, 25.0, 37, kAllRight); MakeDefaultPreset("-", 4); // Instantiate a graphics engine. IGraphics* pGraphics = MakeGraphics(this, kW, kH); // MakeGraphics(this, kW, kH); pGraphics->AttachBackground(BG_ID, BG_FN); // Attach controls to the graphics engine. Controls are automatically associated // with a parameter if you construct the control with a parameter index. // Attach a couple of meters, not associated with any parameter, // which we keep indexes for, so we can push updates from the plugin class. //IBitmap bitmap = pGraphics->LoadIBitmap(METER_ID, METER_FN, kMeter_N); //mMeterIdx_L = pGraphics->AttachControl(new IBitmapControl(this, kMeterL_X, kMeterL_Y, &bitmap)); //mMeterIdx_R = pGraphics->AttachControl(new IBitmapControl(this, kMeterR_X, kMeterR_Y, &bitmap)); // Attach a couple of faders, associated with the parameters GainL and GainR. //bitmap = pGraphics->LoadIBitmap(FADER_ID, FADER_FN); //pGraphics->AttachControl(new IFaderControl(this, kGainL_X, kGainL_Y, kFader_Len, kGainL, &bitmap, kVertical)); //pGraphics->AttachControl(new IFaderControl(this, kGainR_X, kGainR_Y, kFader_Len, kGainR, &bitmap, kVertical)); // Attach a 5-position switch associated with the ChannelSw parameter. IBitmap bitmap = pGraphics->LoadIBitmap(TOGGLE_ID, TOGGLE_FN, kNoteLength_N); pGraphics->AttachControl(new ISwitchControl(this, kNoteLength_X, kNoteLength_Y, kNoteLength, &bitmap)); pGraphics->AttachControl(new ISwitchControl(this, kOctaves_X, kOctaves_Y, kOctaves, &bitmap)); pGraphics->AttachControl(new ISwitchControl(this, kArpMode_X, kArpMode_Y, kArpMode, &bitmap)); pGraphics->AttachControl(new ISwitchControl(this, kInsertMode_X, kInsertMode_Y, kInsertMode, &bitmap)); // Attach a rotating knob associated with the Pan parameter. //bitmap = pGraphics->LoadIBitmap(KNOB_ID, KNOB_FN); //pGraphics->AttachControl(new IKnobRotaterControl(this, kPan_X, kPan_Y, kPan, &bitmap)); // See IControl.h for other control types, // IKnobMultiControl, ITextControl, IBitmapOverlayControl, IFileSelectorControl, IGraphControl, etc. IText text; text.mAlign = IText::kAlignNear; textControl_ = new ITextControl(this, &IRECT(21, 0, 200, 100), &text, "Hello world"); pGraphics->AttachControl(textControl_); sequence_ = new Sequence(keymap_, 16); matrix = new ArpMatrix(this, sequence_, kDisplay_X, kDisplay_Y); pGraphics->AttachControl(matrix); AttachGraphics(pGraphics); running_ = false; } void Arponaut::ProcessDoubleReplacing(double** inputs, double** outputs, int nFrames) { // Mutex is already locked for us. ENoteLength noteLength = (ENoteLength) ((int(GetParam(kNoteLength)->Value())) + 1); EOctaves octaves = (EOctaves) ((int(GetParam(kOctaves)->Value())) + 1); EArpMode arpMode = (EArpMode) (int(GetParam(kArpMode)->Value())); EInsertMode insertMode = (EInsertMode) (int(GetParam(kInsertMode)->Value())); if (GetGUI()) { //GetGUI()->SetControlFromPlug(mMeterIdx_L, peakL); //GetGUI()->SetControlFromPlug(mMeterIdx_R, peakR); } int pos = GetSamplePos(); running_ = (pos != lastPos_); int tnum, tden; GetTimeSig(&tnum, &tden); if (keymap_.held() == 0) { NoteOff(); // only sent if a note is already playing } if (running_ && keymap_.held()) { sequence_->setOctaves(octaves); sequence_->setArpMode(arpMode); sequence_->setInsertMode(insertMode); double perBeat = GetSamplesPerBeat() / noteLength; // trigger? int ibar = static_cast<int>(double(pos) / perBeat); int ilastBar = static_cast<int>(double(lastPos_) / perBeat); if ((pos == 0 && ibar == 0) || (ibar != ilastBar)) { // Log("pos %d pb %f Num %d Den %d ibar %d lastbar %d\n", pos, perBeat, tnum, tden, ibar, ilastBar); NoteOff(); IMidiMsg* next = sequence_->next(); if (next && next->StatusMsg() == IMidiMsg::kNoteOn) { SendMidiMsg(next); playing_ = *next; } matrix->SetDirty(false); } } lastPos_ = pos; } // We're only ever playing one note (monophonic) void Arponaut::NoteOff() { if (playing_.StatusMsg() != IMidiMsg::kNoteOff) { IMidiMsg offMsg; offMsg.MakeNoteOffMsg(playing_.NoteNumber(), playing_.mOffset); SendMidiMsg(&offMsg); playing_ = offMsg; } } void Arponaut::ProcessMidiMsg(IMidiMsg* pMsg) { char msgstr[256]; IMidiMsg::EStatusMsg status = pMsg->StatusMsg(); char *statstr = ""; Log("Midi message received: nn %d prog %d status %d vel %d d1 %d d2 %d offset %d st %d\n", pMsg->NoteNumber(), pMsg->Program(), status, pMsg->Velocity(), pMsg->mData1, pMsg->mData2, pMsg->mOffset, pMsg->mStatus); if (status == IMidiMsg::kNoteOn) { statstr = "Note on"; if (keymap_.noteDown(pMsg) == false) { // Terminate previous note if playing // XXX should check that the same note is playing before calling noteoff // NoteOff(); // playing_ = *pMsg; } sequence_->rebuild(); matrix->SetDirty(false); } else if (status == IMidiMsg::kNoteOff) { statstr = "Note off"; // NoteOff(); keymap_.noteUp(pMsg); sequence_->rebuild(); matrix->SetDirty(false); } sprintf(msgstr, "MIDI %s %d Vel %d %d held", statstr, pMsg->NoteNumber(), pMsg->Velocity(), keymap_.held()); textControl_->SetTextFromPlug(msgstr); // SendMidiMsg(pMsg); } // Returns true if successfully added, false if key already held bool KeyMap::noteDown(IMidiMsg *msg) { for (std::vector<IMidiMsg>::iterator it = events.begin(); it != events.end(); ++it) { if (msg->NoteNumber() == it->NoteNumber()) { // already have this note down return false; } } events.push_back(*msg); return true; } void KeyMap::noteUp(IMidiMsg *msg) { for (std::vector<IMidiMsg>::iterator it = events.begin(); it != events.end(); ++it) { if (msg->NoteNumber() == it->NoteNumber()) { events.erase(it); return; } } } // index wraps around IMidiMsg* KeyMap::get(int index) { int length = held(); return &(events[index % length]); } Sequence::Sequence(KeyMap& keymap, int length) : keymap_(keymap), pos(0), playLength_(0), octaves_(1), arpMode_(kUp), insertMode_(kInsertOff) { IMidiMsg off; off.MakeNoteOffMsg(0, 0); sequence.insert(sequence.begin(), length, off); } IMidiMsg* Sequence::get(int index) { if (!(index >= 0 && index < sequence.size())) { Log("Index is %d seq size %d\n", index, sequence.size()); return 0; } // assert(index >= 0 && index < sequence.size()); return &(sequence[index]); } void Sequence::rebuild() { int held = keymap_.held(); playLength_ = held * octaves_; if (arpMode_ == kUpDown && (held*octaves_ > 2)) { playLength_ += playLength_ - 2; } if (insertMode_ == kInsertLow || insertMode_ == kInsertHi) { playLength_ *= 2; } if (playLength_ > length()) { sequence.resize(playLength_); } // clear all notes, reset position if none held if (held == 0) { for (int i=0; i < length(); ++i) { get(i)->MakeNoteOffMsg(0, 0); } pos = 0; } else { std::vector<IMidiMsg> input = keymap_.sortedEvents(); IMidiMsg loNote = input.front(); IMidiMsg hiNote = input.back(); hiNote.MakeNoteOnMsg(hiNote.NoteNumber() + 12*(octaves_-1), hiNote.Velocity(), hiNote.mOffset); if (arpMode_ == kUp || arpMode_ == kDown || arpMode_ == kUpDown) { if (arpMode_ == kDown) { std::reverse(input.begin(), input.end()); } } else { // default others to manual for now input = keymap_.events; } int iLast; for (int oct=0; oct < octaves_; ++oct) { int noteOffset = (arpMode_ == kDown) ? ((octaves_-1)*12 - oct*12) : oct*12; for (int i=0; i < held; ++i) { IMidiMsg* inp = &(input[i % held]); iLast = i + oct*held; get(iLast)->MakeNoteOnMsg(inp->NoteNumber() + noteOffset, inp->Velocity(), inp->mOffset); } } // Mirror the ascending sequence to produce an up/down sequence int iNext = iLast+1; if (arpMode_ == kUpDown) { while (--iLast > 0) { IMidiMsg* lastMsg = get(iLast); get(iNext++)->MakeNoteOnMsg(lastMsg->NoteNumber(), lastMsg->Velocity(), lastMsg->mOffset); } } if (insertMode_ == kInsertLow || insertMode_ == kInsertHi) { IMidiMsg& insertNote = (insertMode_ == kInsertLow) ? loNote : hiNote; // XXX change to using a member buffer instead of instantiating every time std::vector<IMidiMsg> seqcopy = sequence; int idx = 0; std::vector<IMidiMsg>::iterator prev = seqcopy.begin() + (playLength_/2 - 1); for (std::vector<IMidiMsg>::iterator it = seqcopy.begin(); it != seqcopy.begin() + (playLength_/2); ++it) { if (it->NoteNumber() != insertNote.NoteNumber() && prev->NoteNumber() != insertNote.NoteNumber()) { sequence[idx++] = insertNote; } sequence[idx++] = *it; prev = it; } playLength_ = idx; } } } IMidiMsg* Sequence::next() { IMidiMsg* msg = get(pos); playPos_ = pos; if (++pos >= playLength_) pos = 0; return msg; } void Sequence::setOctaves(int octaves) { if (octaves != octaves_) { octaves_ = octaves; rebuild(); } } void Sequence::setArpMode(EArpMode mode) { if (mode != arpMode_) { // Log("Changed arp mode to %d\n", mode); arpMode_ = mode; rebuild(); } } void Sequence::setInsertMode(EInsertMode mode) { if (mode != insertMode_) { insertMode_ = mode; rebuild(); } } struct CmpNote { bool operator() (IMidiMsg& a, IMidiMsg& b) { return (a.NoteNumber() < b.NoteNumber()); } } notecmp; std::vector<IMidiMsg> KeyMap::sortedEvents() { // passing around the vector isn't so bad b.c. usually not many keys held std::vector<IMidiMsg> ret(events); sort(ret.begin(), ret.end(), notecmp); return ret; } void Arponaut::Reset() { Log("Reset called\n"); }
[ [ [ 1, 384 ] ] ]
f7e1911b6e33d19d1373abdecd93a58c69cf910f
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/websrv/xml_fragment_api/src/mainfragment.cpp
bd2d832695128af2e0165a3bb66164d10700e2e0
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
4,191
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include "MainFragment.h" #include "SenFragmentBase.h" namespace { const TInt KStateParsingDelegate = 100; _LIT8(KMainFragmentXmlns, "urn:main:fragment"); _LIT8(KMainFragmentName, "MainFragment"); _LIT8(KMainFragmentQName, "mn:MainFragment"); _LIT8(KDelegateName, "DelegateFragment"); } CMainFragment* CMainFragment::NewL() { CMainFragment* pNew = NewLC(); CleanupStack::Pop(); // pNew; return pNew; } CMainFragment* CMainFragment::NewLC() { CMainFragment* pNew = new (ELeave) CMainFragment; CleanupStack::PushL(pNew); pNew->BaseConstructL(); return pNew; } CMainFragment* CMainFragment::NewL( const TDesC8& aNsUri, const TDesC8& aLocalName, const TDesC8& aQName ) { CMainFragment* pNew = NewLC( aNsUri, aLocalName, aQName ); CleanupStack::Pop(); // pNew; return pNew; } CMainFragment* CMainFragment::NewLC( const TDesC8& aNsUri, const TDesC8& aLocalName, const TDesC8& aQName ) { CMainFragment* pNew = new (ELeave) CMainFragment; CleanupStack::PushL(pNew); pNew->BaseConstructL(aNsUri, aLocalName, aQName); return pNew; } CMainFragment::CMainFragment() : ipDelegateFragment(NULL) { } void CMainFragment::BaseConstructL() { CSenFragmentBase::BaseConstructL( KMainFragmentXmlns, KMainFragmentName, KMainFragmentQName ); } void CMainFragment::BaseConstructL( const TDesC8& aNsUri, const TDesC8& aLocalName, const TDesC8& aQName ) { CSenFragmentBase::BaseConstructL(aNsUri, aLocalName, aQName); } CMainFragment::~CMainFragment() { delete ipDelegateFragment; } void CMainFragment::OnStartElementL(const RTagInfo& aElement, const RAttributeArray& aAttributes, TInt aErrorCode) { switch (iState) { case KSenStateSave: { const TPtrC8 saxLocalName = aElement.LocalName().DesC(); if (saxLocalName == KDelegateName) { const TPtrC8 saxNsUri = aElement.Uri().DesC(); const TPtrC8 saxPrefix = aElement.Prefix().DesC(); TXmlEngElement element = AsElementL(); ipDelegateFragment = CDelegateFragment::NewL( saxNsUri, saxLocalName, saxPrefix, aAttributes ); iState = KStateParsingDelegate; OnDelegateParsingL(*ipDelegateFragment); } else { CSenFragmentBase::OnStartElementL(aElement, aAttributes, aErrorCode); } break; } default: { CSenFragmentBase::OnStartElementL(aElement, aAttributes, aErrorCode); break; } } } void CMainFragment::OnEndElementL(const RTagInfo& aElement, TInt aErrorCode) { switch(iState) { case KStateParsingDelegate: { iState = KSenStateSave; break; } default: { CSenFragmentBase::OnEndElementL(aElement, aErrorCode); break; } } } CDelegateFragment& CMainFragment::DelegateFragment() { return *ipDelegateFragment; } // End of File
[ "none@none" ]
[ [ [ 1, 165 ] ] ]
cc8fe514abec622b043c4343104673bc62b4637f
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Applications/Physics/GelatinCube/GelatinCube.h
807ec8dabaf0bfb4a91c119ede7bf3970d1a34d0
[]
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
1,311
h
// 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. #ifndef GELATINCUBE_H #define GELATINCUBE_H #include "WmlApplication.h" #include "WmlBSplineVolume.h" #include "WmlBoxSurface.h" #include "PhysicsModule.h" using namespace Wml; class GelatinCube : public Application { public: GelatinCube (); virtual ~GelatinCube (); virtual bool OnInitialize (); virtual void OnTerminate (); virtual void OnIdle (); virtual void OnKeyDown (unsigned char ucKey, int iX, int iY); protected: // The masses are located at the control points of a spline surface. // The control points are connected in a mass-spring system. BSplineVolumef* m_pkSpline; PhysicsModule* m_pkModule; void DoPhysical (); // scene graph void CreateSprings (); void CreateBox (); void CreateScene (); NodePtr m_spkScene, m_spkTrnNode; WireframeStatePtr m_spkWireframe; BoxSurfacePtr m_spkBox; }; #endif
[ [ [ 1, 50 ] ] ]
2d4fb374dca927885c77c33033154a95dfc191f4
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/INC/tfstream.h
487755b40bb47049ed37a33d12d153157e397dbd
[]
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
4,412
h
//Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu) //All rights reserved. // //PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM //BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF //THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO //NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER. // //This License allows you to: //1. Make copies and distribute copies of the Program's source code provide that any such copy // clearly displays any and all appropriate copyright notices and disclaimer of warranty as set // forth in this License. //2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)"). // Modifications may be copied and distributed under the terms and conditions as set forth above. // Any and all modified files must be affixed with prominent notices that you have changed the // files and the date that the changes occurred. //Termination: // If at anytime you are unable to comply with any portion of this License you must immediately // cease use of the Program and all distribution activities involving the Program or any portion // thereof. //Statement: // In this program, part of the code is from the GTNetS project, The Georgia Tech Network // Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in // computer networks to study the behavior of moderate to large scale networks, under a variety of // conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from // Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage: // http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/ // //File Information: // // //File Name: //File Purpose: //Original Author: //Author Organization: //Construct Data: //Modify Author: //Author Organization: //Modify Data: // Georgia Tech Network Simulator - Trace fstream object class // George F. Riley. Georgia Tech, Spring 2002 #ifndef __tfstream_h__ #define __tfstream_h__ #include <fstream> #include "G_common_defs.h" #include "ipaddr.h" #include "macaddr.h" #include "simulator.h" class Node; // Tfstream is a trace stream; similar to fstream with some extensions //Doc:ClassXRef class Tfstream : public std::fstream { public: Tfstream(); public: Tfstream& operator<<(char c); Tfstream& operator<<(unsigned char c) { return (*this) << (char)c; } Tfstream& operator<<(signed char c) { return (*this) << (char)c; } Tfstream& operator<<(const char *s); Tfstream& operator<<(const unsigned char *s) { return (*this) << (const char*)s; } Tfstream& operator<<(const signed char *s) { return (*this) << (const char*)s; } Tfstream& operator<<(const void *p); Tfstream& operator<<(int n); Tfstream& operator<<(unsigned int n); Tfstream& operator<<(long n); Tfstream& operator<<(unsigned long n); Tfstream& operator<<(short n) {return operator<<((int)n);} Tfstream& operator<<(unsigned short n) {return operator<<((unsigned int)n);} Tfstream& operator<<(bool b) { return operator<<((int)b); } Tfstream& operator<<(double n); Tfstream& operator<<(float n) { return operator<<((double)n); } Tfstream& operator<<(IPAddr&); Tfstream& operator<<(MACAddr&); public: bool AppendEOL(); // Append eol to current line if needed void NewNode(Node* n); // Log the node for protocol logging void SetNode(Node* n); // Set node pointer for subsequent traces void IPDotted(bool d) { ipDotted = d;} void TimePrecision(Count_t); // Set new precision public: bool pendingEOL; // True if EndOfLine needed Time_t lastLogTime; // Simtime of last log private: Count_t timePrecision; // Number significant digits on time in trace file Node* node; bool ipDotted; // True if trace IP Addresses with dotted notation Time_t digitsThreshold;// Time that sprintf format must change std::string format; // Holds the current time format private: inline void CheckLogTime() { if (is_open()) { if (!pendingEOL || Simulator::Now() != lastLogTime) { LogSimTime(); } } } void LogSimTime(); }; #endif
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 117 ] ] ]
c626ff437b8b95fa6456df06bfca3ec31fa12fe0
a2ba072a87ab830f5343022ed11b4ac365f58ef0
/ urt-bumpy-q3map2 --username [email protected]/libs/splines/util_str.cpp
6713d720b40ffcec6e34cfe6d93b7cc8db6bfad9
[]
no_license
Garey27/urt-bumpy-q3map2
7d0849fc8eb333d9007213b641138e8517aa092a
fcc567a04facada74f60306c01e68f410cb5a111
refs/heads/master
2021-01-10T17:24:51.991794
2010-06-22T13:19:24
2010-06-22T13:19:24
43,057,943
0
0
null
null
null
null
UTF-8
C++
false
false
12,735
cpp
/* This code is based on source provided under the terms of the Id Software LIMITED USE SOFTWARE LICENSE AGREEMENT, a copy of which is included with the GtkRadiant sources (see LICENSE_ID). If you did not receive a copy of LICENSE_ID, please contact Id Software immediately at [email protected]. All changes and additions to the original source which have been developed by other contributors (see CONTRIBUTORS) are provided under the terms of the license the contributors choose (see LICENSE), to the extent permitted by the LICENSE_ID. If you did not receive a copy of the contributor license, please contact the GtkRadiant maintainers at [email protected] immediately. 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //need to rewrite this #include "util_str.h" #include <stdlib.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #ifdef _WIN32 #pragma warning(disable : 4244) // 'conversion' conversion from 'type1' to 'type2', possible loss of data #pragma warning(disable : 4710) // function 'blah' not inlined #endif static const int STR_ALLOC_GRAN = 20; // screwy but intentional #ifdef __APPLE_BUG__ char *idStr::__tolower #else char *idStr::tolower #endif ( char *s1 ) { char *s; s = s1; while( *s ) { *s = ::tolower( *s ); s++; } return s1; } // screwy but intentional #ifdef __APPLE_BUG__ char *idStr::__toupper #else char *idStr::toupper #endif ( char *s1 ) { char *s; s = s1; while( *s ) { *s = ::toupper( *s ); s++; } return s1; } int idStr::icmpn ( const char *s1, const char *s2, int n ) { int c1; int c2; do { c1 = *s1++; c2 = *s2++; if ( !n-- ) { // idStrings are equal until end point return 0; } if ( c1 != c2 ) { if ( c1 >= 'a' && c1 <= 'z' ) { c1 -= ( 'a' - 'A' ); } if ( c2 >= 'a' && c2 <= 'z' ) { c2 -= ( 'a' - 'A' ); } if ( c1 < c2 ) { // strings less than return -1; } else if ( c1 > c2 ) { // strings greater than return 1; } } } while( c1 ); // strings are equal return 0; } int idStr::icmp ( const char *s1, const char *s2 ) { int c1; int c2; do { c1 = *s1++; c2 = *s2++; if ( c1 != c2 ) { if ( c1 >= 'a' && c1 <= 'z' ) { c1 -= ( 'a' - 'A' ); } if ( c2 >= 'a' && c2 <= 'z' ) { c2 -= ( 'a' - 'A' ); } if ( c1 < c2 ) { // strings less than return -1; } else if ( c1 > c2 ) { // strings greater than return 1; } } } while( c1 ); // strings are equal return 0; } int idStr::cmpn ( const char *s1, const char *s2, int n ) { int c1; int c2; do { c1 = *s1++; c2 = *s2++; if ( !n-- ) { // strings are equal until end point return 0; } if ( c1 < c2 ) { // strings less than return -1; } else if ( c1 > c2 ) { // strings greater than return 1; } } while( c1 ); // strings are equal return 0; } int idStr::cmp ( const char *s1, const char *s2 ) { int c1; int c2; do { c1 = *s1++; c2 = *s2++; if ( c1 < c2 ) { // strings less than return -1; } else if ( c1 > c2 ) { // strings greater than return 1; } } while( c1 ); // strings are equal return 0; } /* ============ IsNumeric Checks a string to see if it contains only numerical values. ============ */ bool idStr::isNumeric ( const char *str ) { int len; int i; bool dot; if ( *str == '-' ) { str++; } dot = false; len = strlen( str ); for( i = 0; i < len; i++ ) { if ( !isdigit( str[ i ] ) ) { if ( ( str[ i ] == '.' ) && !dot ) { dot = true; continue; } return false; } } return true; } idStr operator+ ( const idStr& a, const float b ) { char text[ 20 ]; idStr result( a ); sprintf( text, "%f", b ); result.append( text ); return result; } idStr operator+ ( const idStr& a, const int b ) { char text[ 20 ]; idStr result( a ); sprintf( text, "%d", b ); result.append( text ); return result; } idStr operator+ ( const idStr& a, const unsigned b ) { char text[ 20 ]; idStr result( a ); sprintf( text, "%u", b ); result.append( text ); return result; } idStr& idStr::operator+= ( const float a ) { char text[ 20 ]; sprintf( text, "%f", a ); append( text ); return *this; } idStr& idStr::operator+= ( const int a ) { char text[ 20 ]; sprintf( text, "%d", a ); append( text ); return *this; } idStr& idStr::operator+= ( const unsigned a ) { char text[ 20 ]; sprintf( text, "%u", a ); append( text ); return *this; } void idStr::CapLength ( int newlen ) { assert ( m_data ); if ( length() <= newlen ) return; EnsureDataWritable (); m_data->data[newlen] = 0; m_data->len = newlen; } void idStr::EnsureDataWritable ( void ) { assert ( m_data ); strdata *olddata; int len; if ( !m_data->refcount ) return; olddata = m_data; len = length(); m_data = new strdata; EnsureAlloced ( len + 1, false ); strncpy ( m_data->data, olddata->data, len+1 ); m_data->len = len; olddata->DelRef (); } void idStr::EnsureAlloced (int amount, bool keepold) { if ( !m_data ) { m_data = new strdata(); } // Now, let's make sure it's writable EnsureDataWritable (); char *newbuffer; bool wasalloced = ( m_data->alloced != 0 ); if ( amount < m_data->alloced ) { return; } assert ( amount ); if ( amount == 1 ) { m_data->alloced = 1; } else { int newsize, mod; mod = amount % STR_ALLOC_GRAN; if ( !mod ) { newsize = amount; } else { newsize = amount + STR_ALLOC_GRAN - mod; } m_data->alloced = newsize; } newbuffer = new char[m_data->alloced]; if ( wasalloced && keepold ) { strcpy ( newbuffer, m_data->data ); } if ( m_data->data ) { delete [] m_data->data; } m_data->data = newbuffer; } void idStr::BackSlashesToSlashes ( void ) { int i; EnsureDataWritable (); for ( i=0; i < m_data->len; i++ ) { if ( m_data->data[i] == '\\' ) m_data->data[i] = '/'; } } void idStr::snprintf ( char *dst, int size, const char *fmt, ... ) { char buffer[0x10000]; int len; va_list argptr; va_start (argptr,fmt); len = vsprintf (buffer,fmt,argptr); va_end (argptr); assert ( len < size ); strncpy (dst, buffer, size-1); } #ifdef _WIN32 #pragma warning(disable : 4189) // local variable is initialized but not referenced #endif /* ================= TestStringClass This is a fairly rigorous test of the idStr class's functionality. Because of the fairly global and subtle ramifications of a bug occuring in this class, it should be run after any changes to the class. Add more tests as functionality is changed. Tests should include any possible bounds violation and NULL data tests. ================= */ void TestStringClass ( void ) { char ch; // ch == ? idStr *t; // t == ? idStr a; // a.len == 0, a.data == "\0" idStr b; // b.len == 0, b.data == "\0" idStr c( "test" ); // c.len == 4, c.data == "test\0" idStr d( c ); // d.len == 4, d.data == "test\0" idStr e( reinterpret_cast<const char *>(NULL) ); // e.len == 0, e.data == "\0" ASSERT! int i; // i == ? i = a.length(); // i == 0 i = c.length(); // i == 4 const char *s1 = a.c_str(); // s1 == "\0" const char *s2 = c.c_str(); // s2 == "test\0" t = new idStr(); // t->len == 0, t->data == "\0" delete t; // t == ? b = "test"; // b.len == 4, b.data == "test\0" t = new idStr( "test" ); // t->len == 4, t->data == "test\0" delete t; // t == ? a = c; // a.len == 4, a.data == "test\0" // a = ""; a = NULL; // a.len == 0, a.data == "\0" ASSERT! a = c + d; // a.len == 8, a.data == "testtest\0" a = c + "wow"; // a.len == 7, a.data == "testwow\0" a = c + reinterpret_cast<const char *>(NULL); // a.len == 4, a.data == "test\0" ASSERT! a = "this" + d; // a.len == 8, a.data == "thistest\0" a = reinterpret_cast<const char *>(NULL) + d; // a.len == 4, a.data == "test\0" ASSERT! a += c; // a.len == 8, a.data == "testtest\0" a += "wow"; // a.len == 11, a.data == "testtestwow\0" a += reinterpret_cast<const char *>(NULL); // a.len == 11, a.data == "testtestwow\0" ASSERT! a = "test"; // a.len == 4, a.data == "test\0" ch = a[ 0 ]; // ch == 't' ch = a[ -1 ]; // ch == 0 ASSERT! ch = a[ 1000 ]; // ch == 0 ASSERT! ch = a[ 0 ]; // ch == 't' ch = a[ 1 ]; // ch == 'e' ch = a[ 2 ]; // ch == 's' ch = a[ 3 ]; // ch == 't' ch = a[ 4 ]; // ch == '\0' ASSERT! ch = a[ 5 ]; // ch == '\0' ASSERT! a[ 1 ] = 'b'; // a.len == 4, a.data == "tbst\0" a[ -1 ] = 'b'; // a.len == 4, a.data == "tbst\0" ASSERT! a[ 0 ] = '0'; // a.len == 4, a.data == "0bst\0" a[ 1 ] = '1'; // a.len == 4, a.data == "01st\0" a[ 2 ] = '2'; // a.len == 4, a.data == "012t\0" a[ 3 ] = '3'; // a.len == 4, a.data == "0123\0" a[ 4 ] = '4'; // a.len == 4, a.data == "0123\0" ASSERT! a[ 5 ] = '5'; // a.len == 4, a.data == "0123\0" ASSERT! a[ 7 ] = '7'; // a.len == 4, a.data == "0123\0" ASSERT! a = "test"; // a.len == 4, a.data == "test\0" b = "no"; // b.len == 2, b.data == "no\0" i = ( a == b ); // i == 0 i = ( a == c ); // i == 1 i = ( a == "blow" ); // i == 0 i = ( a == "test" ); // i == 1 i = ( a == NULL ); // i == 0 ASSERT! i = ( "test" == b ); // i == 0 i = ( "test" == a ); // i == 1 i = ( NULL == a ); // i == 0 ASSERT! i = ( a != b ); // i == 1 i = ( a != c ); // i == 0 i = ( a != "blow" ); // i == 1 i = ( a != "test" ); // i == 0 i = ( a != NULL ); // i == 1 ASSERT! i = ( "test" != b ); // i == 1 i = ( "test" != a ); // i == 0 i = ( NULL != a ); // i == 1 ASSERT! a = "test"; // a.data == "test" b = a; // b.data == "test" a = "not"; // a.data == "not", b.data == "test" a = b; // a.data == b.data == "test" a += b; // a.data == "testtest", b.data = "test" a = b; a[1] = '1'; // a.data = "t1st", b.data = "test" } #ifdef _WIN32 #pragma warning(default : 4189) // local variable is initialized but not referenced #pragma warning(disable : 4514) // unreferenced inline function has been removed #endif
[ [ [ 1, 631 ] ] ]
379d9ce3423fd5ae386c44a51e3b1e1543e5c37a
ede1077a7390489e7c38924b14b15b463940cafe
/control_srv/trunk/localserver.h
fddc6c957568776a23f58a2be55a462ce9031b4d
[]
no_license
S1aNT/zarya-print
889008c64f59b577fa37f0d1178ecf918d3b9dbe
a773bb0f209453f9dfec5f4a543ca66b0405a2ee
refs/heads/master
2020-04-06T06:27:56.644595
2011-12-22T03:17:05
2011-12-22T03:17:05
32,496,882
0
0
null
null
null
null
UTF-8
C++
false
false
1,287
h
#include <QtNetwork/QTcpServer> #include <QtNetwork/QTcpSocket> #include <QSet> #include <QMap> #include "qtservice.h" #include "message.h" #include "mytypes.h" using namespace VPrn; class LocalServer : public QTcpServer { Q_OBJECT public: LocalServer( QObject* parent = 0); void pause(); void resume(); signals: void sendEventMessageInfo(QString eMsg, VPrn::EventLogMessageId eventCode, VPrn::EventLogType evenType, VPrn::EventLogCategory eventCategory = VPrn::eCatId_Empty); void reciveMessage(const QString &c_uuid,const Message &msg); public slots: void sendMessage (const QString &c_uuid,const Message &msg); private slots: void client_init(); void readyRead(); void disconnected(); void prepareError(QAbstractSocket::SocketError socketError); private: /** * @var packetSize; Размер передаваемого блока данных */ bool disabled; PACKET_SIZE packetSize; QSet<QTcpSocket *> clients; QMap<QTcpSocket *,QString> clients_uuid; QString getUuid() const; QTcpSocket *findClient(const QString &c_uuid); };
[ [ [ 1, 53 ] ] ]
47bdf1321c9bebeb82eb24cb84ef6696ba828ebc
2bdc85da8ec860be41ad14fceecedef1a8efc269
/PythonWrapper/include/PWSystem.h
027f81842fa47bc4f5317e893c65b0c4338cd1d1
[]
no_license
BackupTheBerlios/pythonwrapper-svn
5c41a03b23690c62693c7b29e81b240ee24f1a7f
42879461c7302755f3c803cd1314e8da5a202c68
refs/heads/master
2016-09-05T09:53:14.554795
2005-12-26T07:52:41
2005-12-26T07:52:41
40,751,088
0
0
null
null
null
null
UTF-8
C++
false
false
787
h
#ifndef _PWSystem_h_ #define _PWSystem_h_ #include "PWCommon.h" #include "PWTypeManager.h" #include "PWModuleManager.h" #include "PWLogManager.h" namespace pw { class PW_EXPORT System : public Singleton<System> { public: static System &getSingleton(); static System *getSingletonPtr(); public: System(bool log = true, const String &logFile="PythonWrapper.txt", LogManager::LogLevel level = LogManager::Medium); ~System(); void loadModule(const String &dllName); void loadSwigModule(const String &dllName); void initialize(); void finalize(); private: TypeManager *mTM; ModuleManager *mMM; LogManager *mLM; }; } #endif
[ "cculver@827b5c2f-c6f0-0310-96fe-c05a662c181e" ]
[ [ [ 1, 35 ] ] ]
fcf28cb77a4f0cf953175649c2520b184ae8fb2a
6e563096253fe45a51956dde69e96c73c5ed3c18
/ZKit/ZKit_StopWatch.h
434a4abd92542e0c5879b74c7839007c7a7949d2
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
GB18030
C++
false
false
1,677
h
#ifndef _ZKit_StopWatch_h_ #define _ZKit_StopWatch_h_ #include "ZKit_Config.h" BEGIN_ZKIT //秒表类, 用于判断是否超时, 以及测量时间间隔. by qguo. class StopWatch { public: StopWatch(clock_t timeout = 5 * CLOCKS_PER_SEC) : m_start(clock()), m_stop(clock()), m_running(false), m_timeout(timeout) { } //启动计时 void Start() { m_running = true; m_start = clock(); } //停止计时 void Stop() { m_running = false; m_stop = clock(); } //设置超时时间 void SetTimeout(clock_t timeout) { m_timeout = timeout; } //是否在运行 bool IsRunning() const { return m_running; } //开始和停止之间的时间间隔 clock_t TimeSpan() { return m_stop - m_start; } //从开始到现在过去了多长时间 clock_t Elapse() const { return clock() - m_start; } //判断是否已到超时时间 bool IsTimeout() const { return Elapse() > m_timeout; } private: clock_t m_start; clock_t m_stop; clock_t m_timeout; bool m_running; }; #define ENABLE_TIME_COST_PRINT 1 class AutoClock { public: AutoClock(const char* job = "job") : m_start(clock()), m_stopped(false) { strncpy(m_job, job, 64); } ~AutoClock() { Stop(); } void Start() { m_stopped = false; m_start = clock(); } void Stop() { #ifdef ENABLE_TIME_COST_PRINT if (!m_stopped) { clock_t stop = clock(); printf("\n%s costs %d ticks!", m_job, stop - m_start); m_stopped = true; } #endif } private: clock_t m_start; char m_job[64]; bool m_stopped; }; END_ZKIT #endif // _ZKit_StopWatch_h_
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 108 ] ] ]
99d2f2e79c0c8d1641d3a999fb37e20f8429c6fc
1092bd6dc9b728f3789ba96e37e51cdfb9e19301
/loci/platform/win32/window_class.cpp
b29c08e8286305b5a925ab35379f079669d94d19
[]
no_license
dtbinh/loci-extended
772239e63b4e3e94746db82d0e23a56d860b6f0d
f4b5ad6c4412e75324d19b71559a66dd20f4f23f
refs/heads/master
2021-01-10T12:23:52.467480
2011-03-15T22:03:06
2011-03-15T22:03:06
36,032,427
0
0
null
null
null
null
UTF-8
C++
false
false
5,463
cpp
/** * Implementation of the window_class. * Implements the window_class class. * * @file window_class.cpp * @author David Gill * @date 18/08/2009 */ #include <boost/make_shared.hpp> #include "loci/platform/win32/window_class.h" #include "loci/platform/win32/windows_common.h" #include "loci/platform/win32/detail/window_class_impl.h" #include "loci/platform/tstring.h" #include "loci/platform/tsstream.h" namespace loci { namespace platform { namespace win32 { namespace // anonymous { ATOM registrate(const WNDCLASSEX & wcx) { return ::RegisterClassEx(&wcx); } ATOM registrate(const WNDCLASS & wc) { return ::RegisterClass(&wc); } ATOM registrate( window_class::event_handler_type handler, window_class::brush_type background = get_brush(BLACK_BRUSH), window_class::icon_type icon = get_icon(IDI_APPLICATION), window_class::style_type style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC, window_class::name_type name = unique_class_name(get_root_module()).c_str(), window_class::module_type module = get_root_module(), window_class::cursor_type cursor = get_cursor(IDC_ARROW), window_class::icon_type small_icon = NULL, window_class::name_type menu_name = NULL, window_class::size_type class_extra_bytes = 0, window_class::size_type window_extra_bytes = 0) { WNDCLASSEX wcx = { sizeof(WNDCLASSEX), style, handler, class_extra_bytes, window_extra_bytes, module, icon, cursor, background, menu_name, name, small_icon }; return registrate(wcx); } } // anonymous namespace window_class::window_class(ATOM to_own, module_type module) : impl( boost::make_shared<window_class_impl>( to_own, module)) { } window_class::window_class(const WNDCLASSEX & wcx) : impl( boost::make_shared<window_class_impl>( registrate(wcx), wcx.hInstance)) { } window_class::window_class(const WNDCLASS & wc) : impl( boost::make_shared<window_class_impl>( registrate(wc), wc.hInstance)) { } window_class::window_class(event_handler_type handler) : impl( boost::make_shared<window_class_impl>( registrate(handler), get_root_module())) { } window_class::window_class(event_handler_type handler, brush_type background, icon_type icon) : impl( boost::make_shared<window_class_impl>( registrate(handler, background, icon), get_root_module())) { } window_class::window_class(event_handler_type handler, style_type style, brush_type background, icon_type icon) : impl( boost::make_shared<window_class_impl>( registrate(handler, background, icon, style), get_root_module())) { } window_class::window_class(name_type name, module_type module, event_handler_type handler, style_type style, brush_type background, cursor_type cursor, icon_type icon, icon_type small_icon, name_type menu_name, size_type class_extra_bytes, size_type window_extra_bytes) : impl( boost::make_shared<window_class_impl>( registrate(handler, background, icon, style, name, module, cursor, small_icon, menu_name, class_extra_bytes, window_extra_bytes), module)) { } window_class::handle window_class::get() const { return impl->atom; } window_class::module_type window_class::module() const { return impl->hinstance; } tstring unique_class_name(module_type module) { static unsigned long uid = 0; ::DWORD initial_error_state = ::GetLastError(); tstring name; WNDCLASS wc; for(;;) { otstringstream ss; ss << uid; name = ss.str(); if(!(::GetClassInfo(module, name.c_str(), &wc))) { ::SetLastError(initial_error_state); return name; } ++uid; } } } // namespace win32 } // namespace platform } // namespace loci
[ "[email protected]@0e8bac56-0901-9d1a-f0c4-3841fc69e132" ]
[ [ [ 1, 164 ] ] ]
d5794953adc7d988f00808d56990bb8e4fc312fc
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/StopModeDebugger/edebugger.cpp
c48d2a12ac965f1769d1aca2b15db4f933f56115
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
21,053
cpp
// edebugger.cpp // // Copyright (c) 1998-1999 Symbian Ltd. All rights reserved. // #include "edebugger.h" #include "ddebugger.h" #include "epoc.h" // // Constructer for DPassiveDebugger interface on the HOST // EpocDebugger::EpocDebugger(const Hardware &aHardware) { TRACE("EpocDebugger::EpocDebugger()\n"); // // The interface for accessing the target // iHardware=&aHardware; } int EpocDebugger::Create() // // Second phase construction // { // // Create the host debug structures // iChunks=NULL; iChunkCount=0; iBreakPoints=new TLinAddr [KMaxBreakPoints]; iBreakInstruction=new TLinAddr [KMaxBreakPoints]; iShadowPages=new TShadowPage [KMaxShadowPages]; // TODO: check mem alloc errors // // Clear the host debug structures // we assume we have no breakpoints and no shadowed areas of ROM // int i; for (i=0; i<KMaxBreakPoints; i++) iBreakPoints[i]=KNullBreakPoint; for (i=0; i<KMaxShadowPages; i++) iShadowPages[i].iRomPage=NULL; // // Turn off permissions-checking on the super page on the target // TUint32 dacr; UnlockDomains(dacr); // if (TargetHalted()) return KErrInUse; // // Get the address of the debugger structure from the target // TLinAddr debugger; bool result = ReadWord(KDebuggerAddress, &debugger); if (result) iDebugger=debugger; else iDebugger=NULL; if (iDebugger==NULL) return KErrGeneral; // // Check the version number // TUint32 requiresversion=(TUint32) ((KPassiveDebuggerMajorVersionNumber<<24) | (KPassiveDebuggerMinorVersionNumber<<16)); TUint32 version; ReadWord(iDebugger + _FOFF(DDebugger, iVersion), version); if (version < requiresversion) return KErrGeneral; // // Can do other debugger initialisation here // return KErrNone; } EpocDebugger::~EpocDebugger() // // // { TRACE("EpocDebugger::~EpocDebugger()\n"); delete [] iBreakPoints; delete [] iBreakInstruction; delete [] iShadowPages; delete iChunks; } bool EpocDebugger::ReadWord(TLinAddr address, TUint32 * word) // // Read a word from the target // returns false on error // { return iHardware->ReadWord(address, word); } bool EpocDebugger::WriteWord(TLinAddr address, TUint32 word) // // Write a word to the target // returns false on error // { return iHardware->WriteWord(address, word); } bool EpocDebugger::ReadMemory(TLinAddr address, TInt count, TUint8 * buffer) // // Read memory from the target // returns false on error // { return iHardware->ReadMemory(address, 0, count, buffer); } bool EpocDebugger::WriteMemory(TLinAddr address, TInt count, TUint8 * buffer) // // Write memory to the target // returns false on error // { return iHardware->WriteMemory(address, 0, count, buffer); } bool EpocDebugger::ReadRegister(TRegister reg, TUint32 * value) // // Read a register from the target // returns false on error // { return iHardware->ReadRegister(reg, value); } bool EpocDebugger::WriteRegister(TRegister reg, TUint32 * value) // // Write a register on the target // returns false on error // { return iHardware->WriteRegister(reg, value); } bool EpocDebugger::ReadDes(TLinAddr address, TUint8 *buffer) // // Read an epoc descriptor from the target // This function assumes 'address' the address of a TPtrC16 on the target // returns a c string in the buffer provided // returns false on error // { int deslength; bool result=iHardware->ReadWord(address, &deslength); if (!result) return result; deslength&=0x00ffffff; // mask out descriptor type TLinAddr iptr; result=iHardware->ReadWord(address+4, &iptr); if (!result) return result; if (iptr==NULL) deslength=0; int bytesptr=iptr & 3; // number of bytes into the word that the string starts int size=((deslength+bytesptr+3)&~3)<<1; result=iOs->ReadMemory(iptr & ~3, 0, size, buffer); if (!result) return result; buffer[len]=0; // terminate the string return true; } TLinAddr EpocDebugger::Debugger() // // return the address of the DPassiveDebugger structure on the target // { return iDebugger; } bool EpocDebugger::ReadChunks() // // Read the chunks from the target // { int chunkCount; TLinAddr chunkPtrArray; TLinAddr address=Debugger() + _FOFF(DDebugger, iChunkArray); bool r=ReadWord(address + _FOFF(RArray<TDebugEntryChunk *>, iCount), &chunkCount); if (r) ReadWord(address + _FOFF(RArray<TDebugEntryChunk *>, iEntries), &chunkPtrArray); if (!r) return r; TInt size=chunkCount * sizeof(TDebugEntryChunk); iChunkCount=0; iChunks=(TDebugEntryChunk *)realloc(iChunks, size); if (iChunks==NULL) return false; iChunkCount=chunkCount; // read all the TDebugEntryChunk into the host buffers int i; TDebugEntryChunk *c=iChunks; for (i=0; i<chunkCount; i++, c++, chunkPtrArray+=4) { // read ptr to chunk TLinAddr chunkp; r=ReadWord(chunkPtrArray, &chunkp); // read the chunk r=ReadMemory(chunkp, sizeof(TDebugEntryChunk), c); } #if defined __DEBUG_CHUNKS__ c=iChunks; for (i=0; i<chunkCount; i++, c++) { __TRACE("Chunk %2d: Object=%08x Proc=%08x Home=%08x Run=%08x Size=%x\n", i, c->iObject, c->iOwningProcess, c->iHomeAddress, c->iRunAddress, c->iSize); } #endif return r; } TLinAddr EpocDebugger::FindLibrary(const char *aLibName) // // Find the TDebugEntryLibrary on the target that matches the given library name // returns the address of the TDebugEntryLibrary on the target // returns NULL if not found // { int len=strlen(aLibName); char name[KMaxName+1]; int libCount; TLinAddr libPtrArray; TLinAddr address=Debugger() + _FOFF(DDebugger, iLibraryArray); bool r=ReadWord(address + _FOFF(RArray<TDebugEntryLibrary *>, iCount), &libCount); if (r) ReadWord(address + _FOFF(RArray<TDebugEntryLibrary *>, iEntries), &libPtrArray); if (!r) return r; // iterate through all the libraries on the target to find a match int i; for (i=0; i<libCount; i++, libPtrArray+=4) { // read ptr to lib TLinAddr libp; r=ReadWord(libPtrArray, &libp); if (!r) continue; // read its name TLinAddr nameptr=libp + _FOFF(TDebugEntryLibrary, iName); r=ReadDes(nameptr, name); if (!r) continue; // does it match? if (strnicmp(aLibName, name, len)==0) { __TRACE("EpocDebugger::FindLibrary(%s) matched %s\n", aLibName, name); return libp; } } return NULL; } TLinAddr EpocDebugger::FindProcess(const char *aProcName) // // Find the TDebugEntryProcess on the target that matches the given process name // returns the address of the TDebugEntryProcess on the target // returns NULL if not found // { int len=strlen(aProcName); char name[KMaxName+1]; int pCount; TLinAddr pPtrArray; TLinAddr address=Debugger() + _FOFF(DDebugger, iProcessArray); bool r=ReadWord(address + _FOFF(RArray<TDebugEntryProcess *>, iCount), &pCount); if (r) ReadWord(address + _FOFF(RArray<TDebugEntryProcess *>, iEntries), &pPtrArray); if (!r) return r; // iterate through all processes on the target to find a match int i; for (i=0; i<pCount; i++, pPtrArray+=4) { // read ptr to proc TLinAddr procp; r=ReadWord(pPtrArray, &procp); if (!r) continue; // read its name TLinAddr nameptr=procp + _FOFF(TDebugEntryProcess, iName); r=gEpocDebugger->ReadDes(nameptr, name); if (!r) continue; // does it match? if (strnicmp(aProcName, name, len)==0) { __TRACE("EpocDebugger::FindProcess(%s) matched %s\n", aProcName, name); return procp; } } return NULL; } TLinAddr EpocDebugger::CurrentThread() // // Return the address of the TDebugEntryThread on the target of the // currently scheduled thread // { TLinAddr address=Debugger() + _FOFF(DDebugger, iCurrentThread); int current; bool result = ReadWord(address, &current); if (!result) return NULL; return current; } TLinAddr EpocDebugger::CurrentProcess() // // Return the currently scheduled process // returns the address of the TDebugEntryProcess on the target // { TLinAddr address=CurrentThread(); return OwningProcess(address); } TLinAddr EpocDebugger::OwningProcess(TLinAddr aThread) // // Return the owning process of the given thread // aThread is the address of the TDebugEntrythread on the target // returns NULL on error // return the address of the owning TDebugEntryProcess on the target // { if (aThread==NULL) return NULL; TLinAddr address=aThread + _FOFF(TDebugEntryThread, iOwningProcess); TLinAddr owner; bool result = ReadWord(address, &owner); if (!result) return NULL; return owner; } TUint32 EpocDebugger::Handle(TLinAddr aObject) // // Return a unique id for the given object // The object may be a TDebugEntry of any type // return NULL on error // { TUint32 handle; // use the object pointer as the unique identifier TLinAddr objectptr=aObject + _FOFF(TDebugEntry, iObject); bool r=ReadWord(objectptr, &handle); if (!r) return NULL; return handle; } int EpocDebugger::NumberOfProcesses() // // Return the number of processes currently running on the target // { // address of process array on target TLinAddr processArray = gEpocDebugger->Debugger() + _FOFF(DDebugger, iProcessArray); TLinAddr processArrayCount = processArray + _FOFF(RArray, iCount); int numProcesses; bool result = ReadWord(processArrayCount, &numProcesses); if (!result) return 0; return numProcesses; } int EpocDebugger::NumberOfThreads() // // Return the number of threads currently running on the target // { TLinAddr threadArray = Debugger() + _FOFF(DDebugger, iThreadArray); TLinAddr threadArrayCount = threadArray + _FOFF(RArray<TDebugEntryThread>, iCount); int numThreads; bool result = ReadWord(threadArrayCount, &numThreads); if (!result) return 0; return numThreads; } bool EpocDebugger::IsRomAddress(TLinAddr aAddress) // // return true if the given address is part of ROM // { return (aAddress>=0x50000000 && aAddress <0x51000000); } int EpocDebugger::NextFreeBreakPointIndex() // // Find the next free breakpoint // { if (iBreakPoints==NULL) return KErrNotFound; int i; for (i=0; i<KMaxBreakPoints; i++) { if (iBreakPoints[i]==KNullBreakPoint) return i; } return KErrNotFound; } int EpocDebugger::BreakPointIndex(TLinAddr address) // // find the index of the breakpoint set at the given address // { if (iBreakPoints==NULL) return KErrNotFound; int i; for (i=0; i<KMaxBreakPoints; i++) { if (iBreakPoints[i]==address) return i; } return KErrNotFound; } int EpocDebugger::BreakPointCount(TLinAddr page) // // Return the number of breakpoints set in the given page on the target // { if (iBreakPoints==NULL) return 0; page &= ~KPageMask; int count=0; int i; for (i=0; i<KMaxBreakPoints; i++) { unsigned long bp=iBreakPoints[i]; if (bp==KNullBreakPoint) continue; if ((bp & ~KPageMask) == page) count++; } return count; } void EpocDebugger::FreeShadowPage(int aShadowPageIndex) // // Free up the specified unused shadowpage // { // copy the ROM's saved PTE back to restore the original ROM page int i=aShadowPageIndex; TLinAddr rompteptr=PageTableEntryAddress(iShadowPages[i].iRomPage); WriteWord(rompteptr, iShadowPages[i].iRomPte); Flush(); iShadowPages[i].iAge=0; iShadowPages[i].iRomPage=NULL; iShadowPages[i].iRamPage=NULL; iShadowPages[i].iRomPte=NULL; } int EpocDebugger::NextFreeShadowPage() // // Find an available shadow page // { if (iShadowPages==NULL) return KErrNotFound; int i; for (i=0; i<KMaxShadowPages; i++) { if (iShadowPages[i].iRomPage==NULL) return i; } // all shadow pages have been used up // so we need to clean out a shadow page // that hasn't been used for a while for (i=0; i<KMaxShadowPages; i++) { if (BreakPointCount(iShadowPages[i].iRomPage)==0) { FreeShadowPage(i); return i; } } return KErrNotFound; /* // // TODO: implement LRU for shadowpages // int p=LeastRecentlyUsedShadowPage(); if (p==KErrNotFound) return p; FreeShadowPage(p); */ } TLinAddr EpocDebugger::ShadowChunkBase() // // Find the linear address of the shadow pages allocated on the target // { TLinAddr shadowchunkbaseptr=gEpocDebugger->Debugger() + _FOFF(DDebugger, iShadowChunkBase); TLinAddr shadowchunkbase; bool r=ReadWord(shadowchunkbaseptr, &shadowchunkbase); if (!r) return NULL; return shadowchunkbase; } bool EpocDebugger::Copy(TLinAddr dest, TLinAddr src, int count) // // target memcpy // { long *buffer=new long [count]; bool r; r=iOs->ReadMemory(src, 0, count, buffer); if (r) r=iOs->WriteMemory(dest, 0, count, buffer); delete buffer; return r; } bool EpocDebugger::ShadowPage(TLinAddr page) // // Shadow a page of Rom by replacing the PTE of the Rom page // with one from the pre-allocated Ram shadow pages // Must also mark the Ram page as UserRo // { int i=NextFreeShadowPage(); if (i==KErrNotFound) return false; page &= ~KPageMask; TLinAddr shadowchunkbase=ShadowChunkBase(); TLinAddr shadowpage=shadowchunkbase + i*KPageSizeInBytes; // copy the data from the ROM into our new shadow page bool r=Copy(shadowpage, page, KPageSizeInBytes); if (!r) return r; // remap the RAM page into where the ROM page was TLinAddr shadowpteptr=PageTableEntryAddress(shadowpage); TLinAddr rompteptr=PageTableEntryAddress(page); TUint32 shadowpte; r=ReadWord(shadowpteptr, &shadowpte); shadowpte &= ~KPtePermissionMask; // sup ro, user ro if (r) r=ReadWord(rompteptr, &iShadowPages[i].iRomPte); if (r) r=WriteWord(rompteptr, shadowpte); if (r) { iShadowPages[i].iRomPage=page; // mark shadow page as used iShadowPages[i].iRamPage=shadowpage; // mark which shadow page was used } Flush(); return r; } int EpocDebugger::ShadowPageIndex(TLinAddr aLinAddr) // // return the index of the shadow page being used for the given address // or KErrNotFound if page is not shadowed // { TLinAddr page=aLinAddr & ~KPageMask; int i; for (i=0; i<KMaxShadowPages; i++) { if (iShadowPages[i].iRomPage==page) return i; } return KErrNotFound; } TPhysAddr EpocDebugger::LinearToPhysical(TLinAddr aLinAddr) // // Convert a linear to a physical address by parsing the page table info // on the target // { TUint pdeindex=aLinAddr >> 22; TLinAddr pdeptr=KPageDirectory + (pdeindex << 2); TUint32 pde; bool r=ReadWord(pdeptr, &pde); if (!r) return NULL; if ((pde & 3) == 1) { // coarse page // get the page table id TLinAddr ptinfoptr=KPageTableInfo + (pdeindex << 2); TUint32 ptinfo; r=ReadWord(ptinfoptr, &ptinfo); if (!r) return NULL; ptinfo >>= KPageTableInfoIdShift; // page table id // get the pte TLinAddr pteptr=PageTableLinearAddress(ptinfo); pteptr+=((aLinAddr&KChunkSizeMinus1)>>KPageSizeShift)<<2; TUint32 pte; r=ReadWord(pteptr, &pte); if (!r) return NULL; // calculate the physical address TPhysAddr phys = ((pte &~ KPageMask)+(aLinAddr & KPageMask)); return phys; } if ((pde & 3) == 2) { // TODO 1M section } return NULL; } bool EpocDebugger::UnlockDomains(Tuint32 &dacr) // // This function writes manager access to all domains // { bool r; TUint32 d=0xffffffff; r=iHardware->WriteRegister(CP15_DACR, &d); return r; } bool EpocDebugger::LockDomains(TUint32 dacr) // // This function restores the DACR // { // leave EPOC to repair the dacr // or // return iHardware->WriteRegister(CP15_DACR, &dacr); return true; } bool EpocDebugger::Flush() // // Flush TLBs and both caches // { __TRACE("EpocDebugger::Flush()\n"); bool r; TUint32 val=0; r=iOs->WriteRegister(CP15_FLUSH_D_TLB, &val); val=0; if (r) r=iOs->WriteRegister(CP15_FLUSH_I_TLB, &val); val=0; if (r) r=iOs->WriteRegister(CP15_FLSH_D, &val); val=0; if (r) r=iOs->WriteRegister(CP15_FLSH_I, &val); return r; } bool EpocDebugger::ThawShadowPage(TLinAddr address) // // Mark the permissions of the shadow page at the given address // to UserRw // { bool r; TLinAddr rompteptr=PageTableEntryAddress(address); TUint32 rompte; r=ReadWord(rompteptr, &rompte); rompte|=KPtePermissionUserRw; if (r) r=WriteWord(rompteptr, rompte); Flush(); return r; } bool EpocDebugger::FreezeShadowPage(TLinAddr address) // // Mark the permissions of the shadow page at the given address // to UserRo // { bool r; TLinAddr rompteptr=PageTableEntryAddress(address); TUint32 rompte; r=ReadWord(rompteptr, &rompte); rompte&=~KPtePermissionUserRw; if (r) r=WriteWord(rompteptr, rompte); Flush(); return r; } TLinAddr EpocDebugger::ShadowPageAddress(TLinAddr aRomAddr) // // Get the shadow page address of the given rom address // { TLinAddr page=aRomAddr & ~KPageMask; int i; for (i=0; i<KMaxShadowPages; i++) { if (iShadowPages[i].iRomPage==page) return iShadowPages[i].iRamPage + (aRomAddr & KPageMask); } return NULL; } bool EpocDebugger::SetBreakPoint(TLinAddr address) // // Set a breakpoint at the given address // if the address is in ROM then shadow the page as necessary // { if (iBreakPoints==NULL) return false; int bp=NextFreeBreakPointIndex(); if (bp==KErrNotFound) return false; TUint32 dacr=0; bool r=UnlockDomains(dacr); if (!r) return r; TUint32 data; unsigned long page=address & ~KPageMask; if (IsRomAddress(address)) { #if defined __SHADOW_ROM_PAGES__ // check to see if this page is already shadowed int shadowPage=ShadowPageIndex(page); // shadow the page if neccesary if (shadowPage==KErrNotFound) r=ShadowPage(page); if (!r) return r; // add breakpoint r=iHardware->SetSwBreakPoint(address); #else r=iHardware->SetHwBreakPoint(address); #endif } else { //read the location before we write it, r=ReadWord(address, &data); r=iHardware->SetSwBreakPoint(address); if (r) r=Flush(); } if (r) { iBreakPoints[bp]=address; iBreakInstruction[bp]=data; LockDomains(dacr); } return r; } bool EpocDebugger::ClearBreakPoint(TLinAddr aAddress) // // Remove the breakpoint previously set at the given address // { int bp=BreakPointIndex(aAddress); if (bp==KErrNotFound) return false; bool r=false; if (IsRomAddress(aAddress)) { // breakpoint in Rom #if defined __SHADOW_ROM_PAGES__ r=iOs->ClearSwBreakPoint(aAddress); #else r=iOs->ClearHwBreakPoint(aAddress); #endif } else { // breakpoint in Ram loaded code r=iOs->ClearSwBreakPoint(aAddress); } if (r) r=Flush(); if (r) iBreakPoints[bp]=KNullBreakPoint; return r; } bool RootName(char *dst, const char *src) // // Parse the filename in src for the root name of the DLL or EXE // { int len=strlen(src); const char *p=src+len-1; // get the filename from the path while (p>=src) { char c=*p; if ((c=='\\') || (c=='/')) break; p--; } strcpy(dst, p+1); // drop ext char *pp=dst; while (1) { if (*pp=='.') { *pp=0; break; } if (*pp==0) break; pp++; } return true; } bool EpocDebugger::GetRelocInfo(char *LibName, TLinAddr &codeSectionStart, TLinAddr &dataSectionStart) // // Match the library symbol filename with a library (or process) on the target // return the code and data addresses of the library on the target // { char rootname[KMaxName+1]; bool r=RootName(rootname, LibName); if (!r) return r; // check libraries first TLinAddr lib=FindLibrary(rootname); if (lib!=NULL) { ReadWord(lib + _FOFF(TDebugEntryLibrary, iCodeAddress), &codeSectionStart); ReadWord(lib + _FOFF(TDebugEntryLibrary, iDataRunAddress), &dataSectionStart); return true; } // check processes TLinAddr proc=FindProcess(rootname); if (proc!=NULL) { TLinAddr chunkptr=NULL; ReadWord(proc + _FOFF(TDebugEntryProcess, iCodeRunAddress), &codeSectionStart); ReadWord(proc + _FOFF(TDebugEntryProcess, iDataBssChunk), &chunkptr); if (chunkptr!=NULL) ReadWord(chunkptr+_FOFF(TDebugEntryChunk, iRunAddress), &dataSectionStart); return true; } return false; } int EpocDebugger::HaltEvent() // // Read the state of the target // this should be called every time the target is halted, before any // other EpocDebugger functions are invoked // { if (!iHardware->TargetHalted()) return KErrInUse; TUint32 dacr; UnlockDomains(dacr); TLinAddr thread=CurrentThread(); TLinAddr process=OwningProcess(thread); iCurrentProcess=process; iCurrentThread=thread; ReadChunks(); return KErrNone; }
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 917 ] ] ]
125c30d03ccb39b93618f8241bb7a882da375ab6
bfdfb7c406c318c877b7cbc43bc2dfd925185e50
/parser/hpOperator.cpp
b95d848c8cb65a55899bcc2fdb306355b5323a5c
[ "MIT" ]
permissive
ysei/Hayat
74cc1e281ae6772b2a05bbeccfcf430215cb435b
b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0
refs/heads/master
2020-12-11T09:07:35.606061
2011-08-01T12:38:39
2011-08-01T12:38:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,788
cpp
#include "hpOperator.h" #include "hpParser.h" using namespace Hayat::Common; using namespace Hayat::Parser; Operator::Operator(void) : m_expIdents(1), m_precs(1) { } Operator::~Operator() { TArrayIterator<TArray<hyu32>* > it(&m_precs); while (it.hasMore()) delete it.next(); m_precs.clear(); } bool Operator::entry(Substr& sIdent, hyu32 prec) { if (prec <= 0) { fprintf(stderr, "ERROR: operator precedence must > 0\n"); return false; } TArray<hyu32>* precArr; int i = m_getIdx(sIdent); if (i < 0) { m_expIdents.add(sIdent); precArr = new TArray<hyu32>(4); m_precs.add(precArr); } else { precArr = m_precs[i]; } int precsSize = precArr->size(); for (i = 0; i < precsSize; ++i) { if (precArr->nth(i) == prec){ char n[256]; gpInp->copyStr(n, 256, sIdent); fprintf(stderr, "ERROR: duplicate operator definition\n"); fprintf(stderr, " rule = %s, prec = %d\n",n, prec); return false; } } precArr->add(prec); return true; } void Operator::sort(void) { int opSize = m_expIdents.size(); for (int i = 0; i < opSize; ++i) { TArray<hyu32>* precArr = m_precs[i]; int precsSize = precArr->size(); for (int j = 0; j < precsSize - 1; ++j) { hyu32 p = precArr->nth(j); hyu32 pm = p; int x = j; for (int k = j+1; k < precsSize; ++k) { hyu32 p2 = precArr->nth(k); if (p2 < pm) { x = k; pm = p2; } } if (x > j) { precArr->nth(j) = pm; precArr->nth(x) = p; } } } } hyu32 Operator::getHigher(Substr& sIdent, hyu32 prec) { TArray<hyu32>* precArr = getPrecs(sIdent); HMD_ASSERT(precArr != NULL); int precsSize = precArr->size(); for (int i = 0; i < precsSize; ++i) { if (precArr->nth(i) == prec){ if (i == precsSize-1) return 0; return precArr->nth(i+1); } } HMD_ASSERT(false); return 0; } bool Operator::isOperand(Substr& sIdent) { return (m_getIdx(sIdent) >= 0); } TArray<hyu32>* Operator::getPrecs(Substr& sIdent) { int idx = m_getIdx(sIdent); if (idx >= 0) return m_precs[idx]; return NULL; } int Operator::m_getIdx(Substr& sIdent) { int opSize = m_expIdents.size(); for (int i = 0; i < opSize; ++i) { Substr s = m_expIdents[i]; if (gpInp->cmpStr(sIdent, s)) return i; } return -1; }
[ [ [ 1, 116 ] ] ]
ad3f900428900100dddbc5109e49100af9a78c32
d37a1d5e50105d82427e8bf3642ba6f3e56e06b8
/DVR/HaohanITPlayer/public/Common/SysUtils/SysUtils_pch.cpp
32df65038bdc089e9e499fe3530932ddae9b2e06
[]
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
512
cpp
//----------------------------------------------------------------------------- // SysUtils_pch.cpp // Copyright (c) 2003 - 2004, Haohanit. All rights reserved. //----------------------------------------------------------------------------- //------------------------------------------------------------------------------ // MODULE : SysUtils_precompiled.cpp // COPYRIGHT : (c) 2003 Haohanit //------------------------------------------------------------------------------ #include "SysUtils_pch.h"
[ "[email protected]@27769579-7047-b306-4d6f-d36f87483bb3" ]
[ [ [ 1, 10 ] ] ]
9334c112e9ce9e5ad8fe8e9d344db5646b49fc90
85d9531c984cd9ffc0c9fe8058eb1210855a2d01
/QxOrm/include/QxTraits/get_primary_key.h
f0ee8cba0634b8ea75e94b515b3f154d3641564e
[]
no_license
padenot/PlanningMaker
ac6ece1f60345f857eaee359a11ee6230bf62226
d8aaca0d8cdfb97266091a3ac78f104f8d13374b
refs/heads/master
2020-06-04T12:23:15.762584
2011-02-23T21:36:57
2011-02-23T21:36:57
1,125,341
0
1
null
null
null
null
UTF-8
C++
false
false
1,602
h
/**************************************************************************** ** ** http://www.qxorm.com/ ** http://sourceforge.net/projects/qxorm/ ** Original file by Lionel Marty ** ** This file is part of the QxOrm library ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any ** damages arising from the use of this software. ** ** GNU Lesser General Public License Usage ** This file must be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file 'license.lgpl.txt' included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact : ** [email protected] ** ****************************************************************************/ #ifndef _QX_GET_PRIMARY_KEY_H_ #define _QX_GET_PRIMARY_KEY_H_ #ifdef _MSC_VER #pragma once #endif namespace qx { namespace trait { template <class T> class get_primary_key { public: typedef long type; }; } // namespace trait } // namespace qx #define QX_REGISTER_PRIMARY_KEY(daoClass, primaryKey) \ namespace qx { namespace trait { \ template <> \ class get_primary_key< daoClass > \ { public: typedef primaryKey type; }; \ } } // namespace qx::trait #endif // _QX_GET_PRIMARY_KEY_H_
[ [ [ 1, 50 ] ] ]
3142d023e451184bc99df8abf4f4c886d6c5c868
3856c39683bdecc34190b30c6ad7d93f50dce728
/LastProject/Source/GUIBtn.h
16876b1d4f717055559758f7f2a03350b5989cef
[]
no_license
yoonhada/nlinelast
7ddcc28f0b60897271e4d869f92368b22a80dd48
5df3b6cec296ce09e35ff0ccd166a6937ddb2157
refs/heads/master
2021-01-20T09:07:11.577111
2011-12-21T22:12:36
2011-12-21T22:12:36
34,231,967
0
0
null
null
null
null
UTF-8
C++
false
false
2,079
h
#pragma once #ifndef _GUIBTN_H_ #define _GUIBTN_H_ #include "GUIBase.h" #define GBS_PUSH 0 #define GBS_CHECK 1 #define GBN_CLICKED 0 enum eState { GB_NORMAL, GB_HOT, GB_DOWN, GB_DISABLE, GB_HIDDEN }; class GUIBtn : public GUIBase { private: VOID Initialize(); VOID Release(); VOID Cleanup(); VOID ChangeState( eState _State ); BOOL IsPtOnMe( POINT pt ); BOOL IsPtOnMe( INT x, INT y ); public: GUIBtn( LPDIRECT3DDEVICE9 _pd3dDevice, LPD3DXSPRITE _pSprite ) : GUIBase( _pd3dDevice, _pSprite ) { this->Initialize(); } virtual ~GUIBtn() { this->Release(); } typedef struct _DATA { IMAGE3D aImage3D[ 4 ]; D3DXVECTOR3 vecPosition; FLOAT fWidth; FLOAT fHeight; }DATA, *LPDATA; VOID Create( DWORD _dID, DWORD _dStyle, IMAGEPARAM& _imgNormal, IMAGEPARAM& _imgHot, IMAGEPARAM& _imgDown, IMAGEPARAM& _imgDisable ); VOID Create( DWORD _dID, // ID Resource DWORD _dStyle, // Style GBS_PUSH || GBS_CHECK FLOAT _fX, FLOAT _fY, // Button Position FLOAT _fWidth, FLOAT _fHeight, // Button Width, Height IMAGEPARAM& _imgNormal, // Normal TextureFileName IMAGEPARAM& _imgHot, // Hot TextureFileName IMAGEPARAM& _imgDown, // Down TextureFileName IMAGEPARAM& _imgDisable ); // Disable TextureFileName eState GetState() { return m_State; } VOID SetState( eState _State ); VOID OnDown( INT x, INT y ); VOID OnMove( INT x, INT y ); VOID OnUp( INT x, INT y ); VOID Enable(BOOL bEnable); BOOL IsEnabled() { return ( m_State != GB_DISABLE ); } VOID Show( BOOL bShow ); BOOL IsShow() { return ( m_State != GB_HIDDEN ); } VOID Move( INT _x,INT _y ); VOID Render(); VOID Update( INT x, INT y ); private: DATA m_Data; DWORD m_ID; DWORD m_Style; eState m_State; eState m_CheckState; BOOL m_bCapture; public: static BOOL g_bCapture; static DWORD btnMessage; }; #endif
[ "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0", "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0" ]
[ [ [ 1, 25 ], [ 27, 36 ], [ 38, 42 ], [ 49, 49 ], [ 59, 91 ] ], [ [ 26, 26 ], [ 37, 37 ], [ 43, 48 ], [ 50, 58 ] ] ]
6dfe08917c824a3aab561577988f7756b415f89b
03f442e60a836172561ef833ae7eb7e7ed434d49
/Sudoku/NodeTable.h
eccbfa3b1681b1e0964af9da8f9b2026c6212ca2
[]
no_license
wooodblr/sudoku-xiu
b72bed616e437e8ee734bf2b039c3572ad6887d3
f76d8106d62d422733552eeab675840d8a5e7f20
refs/heads/master
2020-04-06T03:40:36.806144
2011-04-12T13:44:45
2011-04-12T13:44:45
42,170,692
0
0
null
null
null
null
UTF-8
C++
false
false
421
h
#pragma once #include "node.h" #include "NodeList.h" class CNodeTable { public: CNodeTable(void); ~CNodeTable(void); void initTable(int [9][9]); CNode *GetNode(int, int); CNode *GetFirstNode(int, int); bool delSurround(int, int, int); int AwrNum(); private: CNode m_node[9][9]; CNodeList m_nodeList[9]; CNode m_firstNode[9][9]; public: bool ConfirmNode(void); private: bool m_bOne; };
[ [ [ 1, 23 ] ] ]
d44f0941438d74d92d2e2cbbe2e54663dcc736e1
c799faf4a4aaf9dd5ea5efd4d68a21f5dd02f12d
/SitStick/src/game/client/in_mouse.cpp
4d7777788a263802f3626dec44ac8005e889d291
[]
no_license
DreikVal/nicksproject
05c1fb915ac492c569db126f742b88b77b644e6d
d57ed4d863d099b8bad8706d059c31309f05e256
refs/heads/master
2021-01-10T19:33:04.168437
2010-03-14T19:41:27
2010-03-14T19:41:27
34,276,127
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
20,567
cpp
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: Mouse input routines // // $Workfile: $ // $Date: $ // $NoKeywords: $ //===========================================================================// #if !defined( _X360 ) #include <windows.h> #endif #include "hud.h" #include "cdll_int.h" #include "kbutton.h" #include "basehandle.h" #include "usercmd.h" #include "input.h" #include "iviewrender.h" #include "iclientmode.h" #include "tier0/icommandline.h" #include "vgui/isurface.h" #include "vgui_controls/controls.h" #include "vgui/cursor.h" #include "cdll_client_int.h" #include "cdll_util.h" #include "tier1/convar_serverbounded.h" #if defined( _X360 ) #include "xbox/xbox_win32stubs.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // up / down #define PITCH 0 // left / right #define YAW 1 #ifdef PORTAL bool g_bUpsideDown = false; // Set when the player is upside down in Portal to invert the mouse. #endif //#ifdef PORTAL extern ConVar lookstrafe; extern ConVar cl_pitchdown; extern ConVar cl_pitchup; extern const ConVar *sv_cheats; class ConVar_m_pitch : public ConVar_ServerBounded { public: ConVar_m_pitch() : ConVar_ServerBounded( "m_pitch","0.022", FCVAR_ARCHIVE, "Mouse pitch factor." ) { } virtual float GetFloat() const { return 0; /* ChrisH if ( !sv_cheats ) sv_cheats = cvar->FindVar( "sv_cheats" ); // If sv_cheats is on then it can be anything. float flBaseValue = GetBaseFloatValue(); if ( !sv_cheats || sv_cheats->GetBool() ) return flBaseValue; // If sv_cheats is off than it can only be 0.022 or -0.022 (if they've reversed the mouse in the options). if ( flBaseValue > 0 ) return 0.022f; else return -0.022f; */ } } cvar_m_pitch; ConVar_ServerBounded *m_pitch = &cvar_m_pitch; extern ConVar cam_idealyaw; extern ConVar cam_idealpitch; extern ConVar thirdperson_platformer; static ConVar m_filter( "m_filter","0", FCVAR_ARCHIVE, "Mouse filtering (set this to 1 to average the mouse over 2 frames)." ); ConVar sensitivity( "sensitivity","3", FCVAR_ARCHIVE, "Mouse sensitivity.", true, 0.0001f, false, 10000000 ); static ConVar m_side( "m_side","0.8", FCVAR_ARCHIVE, "Mouse side factor." ); static ConVar m_yaw( "m_yaw","0.022", FCVAR_ARCHIVE, "Mouse yaw factor." ); static ConVar m_forward( "m_forward","1", FCVAR_ARCHIVE, "Mouse forward factor." ); static ConVar m_customaccel( "m_customaccel", "0", FCVAR_ARCHIVE, "Custom mouse acceleration (0 disable, 1 to enable, 2 enable with separate yaw/pitch rescale)."\ "\nFormula: mousesensitivity = ( rawmousedelta^m_customaccel_exponent ) * m_customaccel_scale + sensitivity"\ "\nIf mode is 2, then x and y sensitivity are scaled by m_pitch and m_yaw respectively.", true, 0, false, 0.0f ); static ConVar m_customaccel_scale( "m_customaccel_scale", "0.04", FCVAR_ARCHIVE, "Custom mouse acceleration value.", true, 0, false, 0.0f ); static ConVar m_customaccel_max( "m_customaccel_max", "0", FCVAR_ARCHIVE, "Max mouse move scale factor, 0 for no limit" ); static ConVar m_customaccel_exponent( "m_customaccel_exponent", "1", FCVAR_ARCHIVE, "Mouse move is raised to this power before being scaled by scale factor."); static ConVar m_mouseaccel1( "m_mouseaccel1", "0", FCVAR_ARCHIVE, "Windows mouse acceleration initial threshold (2x movement).", true, 0, false, 0.0f ); static ConVar m_mouseaccel2( "m_mouseaccel2", "0", FCVAR_ARCHIVE, "Windows mouse acceleration secondary threshold (4x movement).", true, 0, false, 0.0f ); static ConVar m_mousespeed( "m_mousespeed", "1", FCVAR_ARCHIVE, "Windows mouse speed factor (range 1 to 20).", true, 1, true, 20 ); ConVar cl_mouselook( "cl_mouselook", "1", FCVAR_ARCHIVE | FCVAR_NOT_CONNECTED, "Set to 1 to use mouse for look, 0 for keyboard look. Cannot be set while connected to a server." ); ConVar cl_mouseenable( "cl_mouseenable", "1" ); // From other modules... void GetVGUICursorPos( int& x, int& y ); void SetVGUICursorPos( int x, int y ); //----------------------------------------------------------------------------- // Purpose: Hides cursor and starts accumulation/re-centering //----------------------------------------------------------------------------- void CInput::ActivateMouse (void) { if ( m_fMouseActive ) return; if ( m_fMouseInitialized ) { if ( m_fMouseParmsValid ) { m_fRestoreSPI = SystemParametersInfo (SPI_SETMOUSE, 0, m_rgNewMouseParms, 0) ? true : false; } m_fMouseActive = true; ResetMouse(); // Clear accumulated error, too m_flAccumulatedMouseXMovement = 0; m_flAccumulatedMouseYMovement = 0; } } //----------------------------------------------------------------------------- // Purpose: Gives back the cursor and stops centering of mouse //----------------------------------------------------------------------------- void CInput::DeactivateMouse (void) { // This gets called whenever the mouse should be inactive. We only respond to it if we had // previously activated the mouse. We'll show the cursor in here. if ( !m_fMouseActive ) return; if ( m_fMouseInitialized ) { if ( m_fRestoreSPI ) { SystemParametersInfo( SPI_SETMOUSE, 0, m_rgOrigMouseParms, 0 ); } m_fMouseActive = false; vgui::surface()->SetCursor( vgui::dc_arrow ); // Clear accumulated error, too m_flAccumulatedMouseXMovement = 0; m_flAccumulatedMouseYMovement = 0; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CInput::CheckMouseAcclerationVars() { // Don't change them if the mouse is inactive, invalid, or not using parameters for restore if ( !m_fMouseActive || !m_fMouseInitialized || !m_fMouseParmsValid || !m_fRestoreSPI ) { return; } int values[ NUM_MOUSE_PARAMS ]; values[ MOUSE_SPEED_FACTOR ] = m_mousespeed.GetInt(); values[ MOUSE_ACCEL_THRESHHOLD1 ] = m_mouseaccel1.GetInt(); values[ MOUSE_ACCEL_THRESHHOLD2 ] = m_mouseaccel2.GetInt(); bool dirty = false; int i; for ( i = 0; i < NUM_MOUSE_PARAMS; i++ ) { if ( !m_rgCheckMouseParam[ i ] ) continue; if ( values[ i ] != m_rgNewMouseParms[ i ] ) { dirty = true; m_rgNewMouseParms[ i ] = values[ i ]; char const *name = ""; switch ( i ) { default: case MOUSE_SPEED_FACTOR: name = "m_mousespeed"; break; case MOUSE_ACCEL_THRESHHOLD1: name = "m_mouseaccel1"; break; case MOUSE_ACCEL_THRESHHOLD2: name = "m_mouseaccel2"; break; } char sz[ 256 ]; Q_snprintf( sz, sizeof( sz ), "Mouse parameter '%s' set to %i\n", name, values[ i ] ); DevMsg( "%s", sz ); } } if ( dirty ) { // Update them m_fRestoreSPI = SystemParametersInfo( SPI_SETMOUSE, 0, m_rgNewMouseParms, 0 ) ? true : false; } } //----------------------------------------------------------------------------- // Purpose: One-time initialization //----------------------------------------------------------------------------- void CInput::Init_Mouse (void) { if ( CommandLine()->FindParm("-nomouse" ) ) return; m_flPreviousMouseXPosition = 0.0f; m_flPreviousMouseYPosition = 0.0f; m_fMouseInitialized = true; m_fMouseParmsValid = false; if ( CommandLine()->FindParm ("-useforcedmparms" ) ) { m_fMouseParmsValid = SystemParametersInfo( SPI_GETMOUSE, 0, m_rgOrigMouseParms, 0 ) ? true : false; if ( m_fMouseParmsValid ) { if ( CommandLine()->FindParm ("-noforcemspd" ) ) { m_rgNewMouseParms[ MOUSE_SPEED_FACTOR ] = m_rgOrigMouseParms[ MOUSE_SPEED_FACTOR ]; } else { m_rgCheckMouseParam[ MOUSE_SPEED_FACTOR ] = true; } if ( CommandLine()->FindParm ("-noforcemaccel" ) ) { m_rgNewMouseParms[ MOUSE_ACCEL_THRESHHOLD1 ] = m_rgOrigMouseParms[ MOUSE_ACCEL_THRESHHOLD1 ]; m_rgNewMouseParms[ MOUSE_ACCEL_THRESHHOLD2 ] = m_rgOrigMouseParms[ MOUSE_ACCEL_THRESHHOLD2 ]; } else { m_rgCheckMouseParam[ MOUSE_ACCEL_THRESHHOLD1 ] = true; m_rgCheckMouseParam[ MOUSE_ACCEL_THRESHHOLD2 ] = true; } } } } //----------------------------------------------------------------------------- // Purpose: Get the center point of the engine window // Input : int&x - // y - //----------------------------------------------------------------------------- void CInput::GetWindowCenter( int&x, int& y ) { int w, h; engine->GetScreenSize( w, h ); x = w >> 1; y = h >> 1; } //----------------------------------------------------------------------------- // Purpose: Recenter the mouse //----------------------------------------------------------------------------- void CInput::ResetMouse( void ) { int x, y; GetWindowCenter( x, y ); SetMousePos( x, y ); } //----------------------------------------------------------------------------- // Purpose: GetAccumulatedMouse -- the mouse can be sampled multiple times per frame and // these results are accumulated each time. This function gets the accumulated mouse changes and resets the accumulators // Input : *mx - // *my - //----------------------------------------------------------------------------- void CInput::GetAccumulatedMouseDeltasAndResetAccumulators( float *mx, float *my ) { Assert( mx ); Assert( my ); *mx = m_flAccumulatedMouseXMovement; *my = m_flAccumulatedMouseYMovement; m_flAccumulatedMouseXMovement = 0; m_flAccumulatedMouseYMovement = 0; } //----------------------------------------------------------------------------- // Purpose: GetMouseDelta -- Filters the mouse and stores results in old position // Input : mx - // my - // *oldx - // *oldy - // *x - // *y - //----------------------------------------------------------------------------- void CInput::GetMouseDelta( float inmousex, float inmousey, float *pOutMouseX, float *pOutMouseY ) { // Apply filtering? if ( m_filter.GetBool() ) { // Average over last two samples *pOutMouseX = ( inmousex + m_flPreviousMouseXPosition ) * 0.5f; *pOutMouseY = ( inmousey + m_flPreviousMouseYPosition ) * 0.5f; } else { *pOutMouseX = inmousex; *pOutMouseY = inmousey; } // Latch previous m_flPreviousMouseXPosition = inmousex; m_flPreviousMouseYPosition = inmousey; } //----------------------------------------------------------------------------- // Purpose: Multiplies mouse values by sensitivity. Note that for windows mouse settings // the input x,y offsets are already scaled based on that. The custom acceleration, therefore, // is totally engine-specific and applies as a post-process to allow more user tuning. // Input : *x - // *y - //----------------------------------------------------------------------------- void CInput::ScaleMouse( float *x, float *y ) { float mx = *x; float my = *y; float mouse_senstivity = ( gHUD.GetSensitivity() != 0 ) ? gHUD.GetSensitivity() : sensitivity.GetFloat(); if ( m_customaccel.GetBool() ) { float raw_mouse_movement_distance = sqrt( mx * mx + my * my ); float acceleration_scale = m_customaccel_scale.GetFloat(); float accelerated_sensitivity_max = m_customaccel_max.GetFloat(); float accelerated_sensitivity_exponent = m_customaccel_exponent.GetFloat(); float accelerated_sensitivity = ( (float)pow( raw_mouse_movement_distance, accelerated_sensitivity_exponent ) * acceleration_scale + mouse_senstivity ); if ( accelerated_sensitivity_max > 0.0001f && accelerated_sensitivity > accelerated_sensitivity_max ) { accelerated_sensitivity = accelerated_sensitivity_max; } *x *= accelerated_sensitivity; *y *= accelerated_sensitivity; // Further re-scale by yaw and pitch magnitude if user requests alternate mode 2 // This means that they will need to up their value for m_customaccel_scale greatly (>40x) since m_pitch/yaw default // to 0.022 if ( m_customaccel.GetInt() == 2 ) { *x *= m_yaw.GetFloat(); *y *= m_pitch->GetFloat(); } } else { *x *= mouse_senstivity; *y *= mouse_senstivity; } } //----------------------------------------------------------------------------- // Purpose: ApplyMouse -- applies mouse deltas to CUserCmd // Input : viewangles - // *cmd - // mouse_x - // mouse_y - //----------------------------------------------------------------------------- void CInput::ApplyMouse( QAngle& viewangles, CUserCmd *cmd, float mouse_x, float mouse_y ) { if ( !((in_strafe.state & 1) || lookstrafe.GetInt()) ) { #ifdef PORTAL if ( g_bUpsideDown ) { viewangles[ YAW ] += m_yaw.GetFloat() * mouse_x; } else #endif //#ifdef PORTAL { if ( CAM_IsThirdPerson() && thirdperson_platformer.GetInt() ) { if ( mouse_x ) { // use the mouse to orbit the camera around the player, and update the idealAngle m_vecCameraOffset[ YAW ] -= m_yaw.GetFloat() * mouse_x; cam_idealyaw.SetValue( m_vecCameraOffset[ YAW ] - viewangles[ YAW ] ); // why doesn't this work??? CInput::AdjustYaw is why //cam_idealyaw.SetValue( cam_idealyaw.GetFloat() - m_yaw.GetFloat() * mouse_x ); } } else { // Otherwize, use mouse to spin around vertical axis viewangles[YAW] -= m_yaw.GetFloat() * mouse_x; } } } else { // If holding strafe key or mlooking and have lookstrafe set to true, then apply // horizontal mouse movement to sidemove. cmd->sidemove += m_side.GetFloat() * mouse_x; } // If mouselooking and not holding strafe key, then use vertical mouse // to adjust view pitch. if (!(in_strafe.state & 1)) { #ifdef PORTAL if ( g_bUpsideDown ) { viewangles[PITCH] -= m_pitch->GetFloat() * mouse_y; } else #endif //#ifdef PORTAL { if ( CAM_IsThirdPerson() && thirdperson_platformer.GetInt() ) { if ( mouse_y ) { // use the mouse to orbit the camera around the player, and update the idealAngle m_vecCameraOffset[ PITCH ] += m_pitch->GetFloat() * mouse_y; cam_idealpitch.SetValue( m_vecCameraOffset[ PITCH ] - viewangles[ PITCH ] ); // why doesn't this work??? CInput::AdjustYaw is why //cam_idealpitch.SetValue( cam_idealpitch.GetFloat() + m_pitch->GetFloat() * mouse_y ); } } else { viewangles[PITCH] += m_pitch->GetFloat() * mouse_y; } // Check pitch bounds if (viewangles[PITCH] > cl_pitchdown.GetFloat()) { viewangles[PITCH] = cl_pitchdown.GetFloat(); } if (viewangles[PITCH] < -cl_pitchup.GetFloat()) { viewangles[PITCH] = -cl_pitchup.GetFloat(); } } } else { // Otherwise if holding strafe key and noclipping, then move upward /* if ((in_strafe.state & 1) && IsNoClipping() ) { cmd->upmove -= m_forward.GetFloat() * mouse_y; } else */ { // Default is to apply vertical mouse movement as a forward key press. cmd->forwardmove -= m_forward.GetFloat() * mouse_y; } } // Finally, add mouse state to usercmd. // NOTE: Does rounding to int cause any issues? ywb 1/17/04 cmd->mousedx = (int)mouse_x; cmd->mousedy = (int)mouse_y; } //----------------------------------------------------------------------------- // Purpose: AccumulateMouse //----------------------------------------------------------------------------- void CInput::AccumulateMouse( void ) { if( !cl_mouseenable.GetBool() ) { return; } if( !cl_mouselook.GetBool() ) { return; } int w, h; engine->GetScreenSize( w, h ); // x,y = screen center int x = w >> 1; int y = h >> 1; // Clamp if ( m_fMouseActive ) { int ox, oy; GetMousePos( ox, oy ); ox = clamp( ox, 0, w - 1 ); oy = clamp( oy, 0, h - 1 ); SetMousePos( ox, oy ); } //only accumulate mouse if we are not moving the camera with the mouse if ( !m_fCameraInterceptingMouse && vgui::surface()->IsCursorLocked() ) { //Assert( !vgui::surface()->IsCursorVisible() ); int current_posx, current_posy; GetMousePos(current_posx, current_posy); m_flAccumulatedMouseXMovement += current_posx - x; m_flAccumulatedMouseYMovement += current_posy - y; // force the mouse to the center, so there's room to move ResetMouse(); } } //----------------------------------------------------------------------------- // Purpose: Get raw mouse position // Input : &ox - // &oy - //----------------------------------------------------------------------------- void CInput::GetMousePos(int &ox, int &oy) { GetVGUICursorPos( ox, oy ); } //----------------------------------------------------------------------------- // Purpose: Force raw mouse position // Input : x - // y - //----------------------------------------------------------------------------- void CInput::SetMousePos(int x, int y) { SetVGUICursorPos(x, y); } //----------------------------------------------------------------------------- // Purpose: MouseMove -- main entry point for applying mouse // Input : *cmd - //----------------------------------------------------------------------------- void CInput::MouseMove( CUserCmd *cmd ) { float mouse_x, mouse_y; float mx, my; QAngle viewangles; // Get view angles from engine engine->GetViewAngles( viewangles ); // Validate mouse speed/acceleration settings CheckMouseAcclerationVars(); // Don't drift pitch at all while mouselooking. view->StopPitchDrift (); //jjb - this disables normal mouse control if the user is trying to // move the camera, or if the mouse cursor is visible if ( !m_fCameraInterceptingMouse && !vgui::surface()->IsCursorVisible() ) { // Sample mouse one more time AccumulateMouse(); // Latch accumulated mouse movements and reset accumulators GetAccumulatedMouseDeltasAndResetAccumulators( &mx, &my ); // Filter, etc. the delta values and place into mouse_x and mouse_y GetMouseDelta( mx, my, &mouse_x, &mouse_y ); // Apply scaling factor ScaleMouse( &mouse_x, &mouse_y ); // Let the client mode at the mouse input before it's used g_pClientMode->OverrideMouseInput( &mouse_x, &mouse_y ); // Add mouse X/Y movement to cmd ApplyMouse( viewangles, cmd, mouse_x, mouse_y ); // Re-center the mouse. ResetMouse(); } // Store out the new viewangles. engine->SetViewAngles( viewangles ); } //----------------------------------------------------------------------------- // Purpose: // Input : *mx - // *my - // *unclampedx - // *unclampedy - //----------------------------------------------------------------------------- void CInput::GetFullscreenMousePos( int *mx, int *my, int *unclampedx /*=NULL*/, int *unclampedy /*=NULL*/ ) { Assert( mx ); Assert( my ); if ( !vgui::surface()->IsCursorVisible() ) { return; } int x, y; GetWindowCenter( x, y ); int current_posx, current_posy; GetMousePos(current_posx, current_posy); current_posx -= x; current_posy -= y; // Now need to add back in mid point of viewport // int w, h; vgui::surface()->GetScreenSize( w, h ); current_posx += w / 2; current_posy += h / 2; if ( unclampedx ) { *unclampedx = current_posx; } if ( unclampedy ) { *unclampedy = current_posy; } // Clamp current_posx = max( 0, current_posx ); current_posx = min( ScreenWidth(), current_posx ); current_posy = max( 0, current_posy ); current_posy = min( ScreenHeight(), current_posy ); *mx = current_posx; *my = current_posy; } //----------------------------------------------------------------------------- // Purpose: // Input : mx - // my - //----------------------------------------------------------------------------- void CInput::SetFullscreenMousePos( int mx, int my ) { SetMousePos( mx, my ); } //----------------------------------------------------------------------------- // Purpose: ClearStates -- Resets mouse accumulators so you don't get a pop when returning to trapped mouse //----------------------------------------------------------------------------- void CInput::ClearStates (void) { if ( !m_fMouseActive ) return; m_flAccumulatedMouseXMovement = 0; m_flAccumulatedMouseYMovement = 0; }
[ "[email protected]@3ec673fc-a294-11de-9953-9d61583e2ada" ]
[ [ [ 1, 685 ] ] ]
ff41571028dcd1b9e30d1ff28ad7470de1b4b0c3
d411188fd286604be7670b61a3c4c373345f1013
/zomgame/ZGame/skill_event.cpp
ca960a56cf9143d669f03ca61942d34e54a87070
[]
no_license
kjchiu/zomgame
5af3e45caea6128e6ac41a7e3774584e0ca7a10f
1f62e569da4c01ecab21a709a4a3f335dff18f74
refs/heads/master
2021-01-13T13:16:58.843499
2008-09-13T05:11:16
2008-09-13T05:11:16
1,560,000
0
1
null
null
null
null
UTF-8
C++
false
false
336
cpp
#include "skill_event.h" #include "game.h" SkillEvent::SkillEvent(Entity* _actor, Skill* _skill, void* _target) : actor(_actor), skill(_skill), target(_target), Event(SKILL) { } Message* SkillEvent::resolve() { std::vector<Message*> msgs; skill->action(static_cast<Player*>(actor), target, &msgs); return msgs.front(); }
[ "krypes@9b66597e-bb4a-0410-bce4-15c857dd0990" ]
[ [ [ 1, 12 ] ] ]
6d75eb13d212a0b480133c85b890a5e08942fe9f
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/depends/ClanLib/src/Core/Text/utf8_reader.cpp
58bc197ef25b1b957e399bae31720735619efd56
[]
no_license
ptrefall/smn6200fluidmechanics
841541a26023f72aa53d214fe4787ed7f5db88e1
77e5f919982116a6cdee59f58ca929313dfbb3f7
refs/heads/master
2020-08-09T17:03:59.726027
2011-01-13T22:39:03
2011-01-13T22:39:03
32,448,422
1
0
null
null
null
null
UTF-8
C++
false
false
5,195
cpp
/* ** ClanLib SDK ** Copyright (c) 1997-2010 The ClanLib Team ** ** 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 ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Mark Page */ #include "precomp.h" #include "API/Core/Text/utf8_reader.h" class CL_UTF8_Reader_Impl { public: CL_UTF8_Reader_Impl(const CL_StringRef8 &text); unsigned int get_char(); CL_String8::size_type get_char_length(); void prev(); void next(); void move_to_leadbyte(); CL_String8::size_type current_position; CL_String8::size_type length; const unsigned char *data; static const char trailing_bytes_for_utf8[256]; static const unsigned char bitmask_leadbyte_for_utf8[6]; }; CL_UTF8_Reader::CL_UTF8_Reader(const CL_StringRef8 &text) : impl(new CL_UTF8_Reader_Impl(text)) { } CL_UTF8_Reader_Impl::CL_UTF8_Reader_Impl(const CL_StringRef8 &text) : current_position(0), length(text.length()), data( (unsigned char *) text.data()) { } bool CL_UTF8_Reader::is_end() { return impl->current_position >= impl->length; } unsigned int CL_UTF8_Reader::get_char() { return impl->get_char(); } CL_String8::size_type CL_UTF8_Reader::get_char_length() { return impl->get_char_length(); } void CL_UTF8_Reader::prev() { impl->prev(); } void CL_UTF8_Reader::next() { impl->next(); } void CL_UTF8_Reader::move_to_leadbyte() { impl->move_to_leadbyte(); } CL_String8::size_type CL_UTF8_Reader::get_position() { return impl->current_position; } void CL_UTF8_Reader::set_position(CL_String8::size_type position) { impl->current_position = position; } CL_String8::size_type CL_UTF8_Reader_Impl::get_char_length() { if (current_position < length) { int trailing_bytes = trailing_bytes_for_utf8[data[current_position]]; if (current_position+1+trailing_bytes > length) return 1; for (CL_String8::size_type i = 0; i < trailing_bytes; i++) { if ((data[current_position+1+i] & 0xC0) != 0x80) return 1; } return 1+trailing_bytes; } else { return 0; } } void CL_UTF8_Reader_Impl::prev() { if (current_position > length) current_position = length; if (current_position > 0) { current_position--; move_to_leadbyte(); } } void CL_UTF8_Reader_Impl::next() { current_position += get_char_length(); } void CL_UTF8_Reader_Impl::move_to_leadbyte() { if (current_position < length) { int lead_position = current_position; while (lead_position > 0 && (data[lead_position] & 0xC0) == 0x80) lead_position--; int trailing_bytes = trailing_bytes_for_utf8[data[lead_position]]; if (lead_position + trailing_bytes == current_position) current_position = lead_position; } } unsigned int CL_UTF8_Reader_Impl::get_char() { if (current_position >= length) return 0; int trailing_bytes = trailing_bytes_for_utf8[data[current_position]]; if (trailing_bytes == 0 && (data[current_position] & 0x80) == 0x80) return '?'; if (current_position+1+trailing_bytes > length) { return '?'; } else { unsigned int ucs4 = (data[current_position] & bitmask_leadbyte_for_utf8[trailing_bytes]); for (CL_String8::size_type i = 0; i < trailing_bytes; i++) { if ((data[current_position+1+i] & 0xC0) == 0x80) ucs4 = (ucs4 << 6) + (data[current_position+1+i] & 0x3f); else return '?'; } // To do: verify that the ucs4 value is in the range for the trailing_bytes specified in the lead byte. return ucs4; } } const char CL_UTF8_Reader_Impl::trailing_bytes_for_utf8[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; const unsigned char CL_UTF8_Reader_Impl::bitmask_leadbyte_for_utf8[6] = { 0x7f, 0x1f, 0x0f, 0x07, 0x03, 0x01 };
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 205 ] ] ]
20facf1c4eddc58028ad8b3cec7625ced006c62e
ffe0a7d058b07d8f806d610fc242d1027314da23
/V3e/dummy/IRCDcc.cpp
0df115257e35910dfbd8246fa1eac2432bd8be8e
[]
no_license
Cybie/mangchat
27bdcd886894f8fdf2c8956444450422ea853211
2303d126245a2b4778d80dda124df8eff614e80e
refs/heads/master
2016-09-11T13:03:57.386786
2009-12-13T22:09:37
2009-12-13T22:09:37
32,145,077
0
0
null
null
null
null
UTF-8
C++
false
false
47
cpp
#include "IRCDcc.h" void IRCDcc::run() { }
[ "cybraxcyberspace@dfcbb000-c142-0410-b1aa-f54c88fa44bd" ]
[ [ [ 1, 5 ] ] ]
1a17e031d0ad53c2d530b1f561f0fccfd346c43c
a6504bc8ff329278fadb67f62a329d806aa28812
/Hatching/src/shot/testShot.h
8b998d0bf8a8732e7661d89a9c12bc0fed2b59b3
[]
no_license
hillsalex/Darkon
7a3eab4d7e69c8e920fb2788e2fd0b39c4c3de4a
12964f830c081381b0007875ab305d00d6a29a4b
refs/heads/master
2020-05-27T19:40:28.888822
2011-05-10T08:08:28
2011-05-10T08:08:28
1,632,571
0
0
null
null
null
null
UTF-8
C++
false
false
558
h
#ifndef TESTSHOT_H #define TESTSHOT_H #include <shot.h> #include "meshoperator.h" class testShot : public Shot { public: testShot(DrawEngine* parent,QHash<QString, QGLShaderProgram *>* shad, QHash<QString, GLuint>* tex, QHash<QString, Model>* mod); ~testShot(); //In begin, initialize things that could not have been initialized beforehand //(gl state) void begin(); //called every frame before draw. void update(); MeshOperator* m_operator; //draw! void draw(); }; #endif // TESTSHOT_H
[ [ [ 1, 3 ], [ 5, 19 ], [ 21, 25 ] ], [ [ 4, 4 ], [ 20, 20 ] ] ]
c97ea70a897bdb31eaa1b3a0ad744ca73d52f4a3
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/mpl/test/unique.cpp
5a04963d261c042c38ededa2fbc271fd2476d421
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
861
cpp
// Copyright Aleksey Gurtovoy 2000-2004 // Copyright David Abrahams 2003-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/boost/boost/libs/mpl/test/unique.cpp,v $ // $Date: 2004/09/02 15:41:35 $ // $Revision: 1.5 $ #include <boost/mpl/unique.hpp> #include <boost/mpl/list.hpp> #include <boost/mpl/equal.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/mpl/aux_/test.hpp> MPL_TEST_CASE() { typedef list<int,float,float,char,int,int,int,double> types; typedef unique< types, is_same<_1,_2> >::type result; typedef list<int,float,char,int,double>::type answer; MPL_ASSERT(( equal< result,answer > )); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 29 ] ] ]
f40e5191ef8139fd062a9bc724be8cc17e6c3948
61fc00b53ce93f09a6a586a48ae9e484b74b6655
/src/tool/src/toolbox/wiwo_sem.cpp
59a643cff6700075dea658557ca921a9cc3c45f5
[]
no_license
mickaelgadroy/wmavo
4162c5c7c8d9082060be91e774893e9b2b23099b
db4a986d345d0792991d0e3a3d728a4905362a26
refs/heads/master
2021-01-04T22:33:25.103444
2011-11-04T10:44:50
2011-11-04T10:44:50
1,381,704
2
0
null
null
null
null
UTF-8
C++
false
false
933
cpp
/* * Copyright (c) 2011 Mickael Gadroy, University of Reims Champagne-Ardenne (Fr) Project managers: Eric Henon and Michael Krajecki Financial support: Region Champagne-Ardenne (Fr) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses>. */ #include "wiwo_sem.h"
[ [ [ 1, 21 ] ] ]
81cd4b3a6190a1d22ecec7d94d98bf111703d963
f90b1358325d5a4cfbc25fa6cccea56cbc40410c
/src/GUI/proRataExportImage.h
598053065995b112191b3c99525636aa6b758f2b
[]
no_license
ipodyaco/prorata
bd52105499c3fad25781d91952def89a9079b864
1f17015d304f204bd5f72b92d711a02490527fe6
refs/heads/master
2021-01-10T09:48:25.454887
2010-05-11T19:19:40
2010-05-11T19:19:40
48,766,766
0
0
null
null
null
null
UTF-8
C++
false
false
222
h
#include "qwt_plot.h" #include "qwt_plot_canvas.h" class ProRataExportImage : public QwtPlotCanvas { public: ProRataExportImage( QwtPlot *plot ); ~ProRataExportImage(){} QPixmap * getPixmap(); };
[ "chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a" ]
[ [ [ 1, 13 ] ] ]
2267c116af0cdaf55e81f94ccc0ce45f7a0130d3
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Graphic/Renderer/D3D10SDKMesh.h
5a478958738b7ee6ee09015e394338d128b89853
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
GB18030
C++
false
false
757
h
#ifndef _D3D10SDKMESH_H_ #define _D3D10SDKMESH_H_ #include "D3D10Prerequisites.h" #include "D3D10Mesh.h" #include "DXUTSDKMesh.h" #include "../Main/Mesh.h" namespace Flagship { class _DLL_Export D3D10SDKMesh : public Mesh, public D3D10Mesh { public: D3D10SDKMesh(); virtual ~D3D10SDKMesh(); protected: // 读取资源 virtual bool Create(); // 释放资源 virtual void Destory(); // 缓存资源 virtual bool Cache(); // 释放缓存 virtual void UnCache(); protected: private: // DXUT对象 CDXUTSDKMesh * m_pSDKMesh; }; typedef ResHandle<D3D10SDKMesh> D3D10SDKMeshHandle; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 40 ] ] ]
cdc3d49ba61f8a4d850cceec8ac861400ac408a4
967868cbef4914f2bade9ef8f6c300eb5d14bc57
/Internet/HtmlTag.cpp
2ac971862c4101ca7f0def5f8552d7d783ff9ad9
[]
no_license
saminigod/baseclasses-001
159c80d40f69954797f1c695682074b469027ac6
381c27f72583e0401e59eb19260c70ee68f9a64c
refs/heads/master
2023-04-29T13:34:02.754963
2009-10-29T11:22:46
2009-10-29T11:22:46
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,570
cpp
/* © Vestris Inc., Geneva, Switzerland http://www.vestris.com, 1994-1999 All Rights Reserved ______________________________________________ written by Daniel Doubrovkine - [email protected] */ #include <baseclasses.hpp> #include "HtmlTag.hpp" CHtmlTag::CHtmlTag(void) { } CHtmlTag::CHtmlTag(const CString& Name) { m_Name = Name; } CHtmlTag::~CHtmlTag(void) { } CHtmlTag::CHtmlTag(const CHtmlTag& HtmlTag) { operator=(HtmlTag); } CHtmlTag& CHtmlTag::operator=(const CHtmlTag& HtmlTag){ m_Name = HtmlTag.m_Name; m_Parameters = HtmlTag.m_Parameters; m_Free = HtmlTag.m_Free; return * this; } CString CHtmlTag::GetBuffer(void) const { CString Result(m_Free); if (m_Name.GetLength()) { Result = ('<' + m_Name); for (register int i=0;i<(int)m_Parameters.GetSize();i++) { Result.Append(' ' + m_Parameters.GetNameAt(i)); if (m_Parameters.GetValueAt(i).GetLength()) Result.Append("=\"" + m_Parameters.GetValueAt(i) + '\"'); } Result.Append('>'); } return Result; } ostream& CHtmlTag::operator<<(ostream& Stream) const { if (m_Free.GetLength()) Stream << m_Free; if (m_Name.GetLength()) { Stream << '<' << m_Name; for (register int i=0;i<(int)m_Parameters.GetSize();i++) { Stream << ' ' << m_Parameters.GetNameAt(i); if (m_Parameters.GetValueAt(i).GetLength()) Stream << "=\"" << m_Parameters.GetValueAt(i) << '\"'; } Stream << '>'; } return Stream; } istream& CHtmlTag::operator>>(istream& Stream) { assert(0); return Stream; }
[ [ [ 1, 67 ] ] ]
719c24e0cb7a987bdd998d3a83c0baf5050ac460
6a0aba268098055373f4fc0c3cef02a2e7234310
/Code/TRISaver.cpp
05fff7370ada401324a512dea7b56a4c31ad2d25
[]
no_license
liamkirton/trisaver
562cb7dea1139480449f3ebe0f785446569b3d22
447a53fd7b1814c2ef7e95e36543302f95e99a47
refs/heads/master
2021-01-21T10:46:14.104443
2002-07-24T15:03:15
2002-07-24T15:03:15
83,484,593
0
0
null
null
null
null
UTF-8
C++
false
false
7,867
cpp
#include <windows.h> #include <scrnsave.h> #include <GL/gl.h> #include <GL/glu.h> #include <ctime> LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); BOOL WINAPI ScreenSaverConfigureDialog(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam); BOOL WINAPI RegisterDialogClasses(HANDLE hInst); void Render(); HDC hDC; HGLRC hRC; double x_angl = 0.0f; double y_angl = 0.0f; double z_angl = 0.0f; double target_x; double target_y; double target_z; bool final_target; const float final_target_x = 63.0; const float final_target_y = 178.5; const float final_target_z = 49.5; const int TARGET_TIMER = 0; const int UPDATE_TIMER = 1; UINT_PTR target_timer_id; UINT_PTR update_timer_id; LRESULT CALLBACK ScreenSaverProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; int pfid; GLint glnWidth; GLint glnHeight; switch(msg) { case WM_CREATE: hDC = GetDC(hWnd); pfid = ChoosePixelFormat(hDC, &pfd); SetPixelFormat(hDC, pfid, &pfd); hRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hRC); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_COLOR_MATERIAL); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0f); target_timer_id = SetTimer(hWnd, TARGET_TIMER, 10000, NULL); update_timer_id = SetTimer(hWnd, UPDATE_TIMER, 1, NULL); srand((unsigned)time(NULL)); target_x = rand() % 360; target_y = rand() % 360; target_z = rand() % 360; return 0; case WM_DESTROY: KillTimer(hWnd, target_timer_id); KillTimer(hWnd, update_timer_id); wglMakeCurrent(NULL, NULL); wglDeleteContext(hRC); ReleaseDC(hWnd, hDC); PostQuitMessage(0); return 0; case WM_SIZE: glnWidth = (GLsizei) LOWORD (lParam); glnHeight = (GLsizei) HIWORD (lParam); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(20.0, (GLdouble)glnWidth/(GLdouble)glnHeight, 1.0f, 512.0f); glViewport(0, 0, glnWidth, glnHeight); return 0; case WM_TIMER: switch(wParam) { case TARGET_TIMER: final_target = !final_target; if (final_target) { target_x = final_target_x; target_y = final_target_y; target_z = final_target_z; } else { target_x = rand() % 360; target_y = rand() % 360; target_z = rand() % 360; } break; case UPDATE_TIMER: x_angl += 0.175f * (target_x - x_angl); y_angl += 0.175f * (target_y - y_angl); z_angl += 0.175f * (target_z - z_angl); Render(); SwapBuffers(hDC); break; default: break; } return 0; default: break; } return DefScreenSaverProc(hWnd, msg, wParam, lParam); } BOOL WINAPI ScreenSaverConfigureDialog(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_INITDIALOG: MessageBox(NULL, "No Configuration Options Available", "TRI", MB_OK); DestroyWindow(hDlg); return TRUE; default: break; } return FALSE; } BOOL WINAPI RegisterDialogClasses(HANDLE hInst) { return TRUE; } void Render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0f, 0.0f, -50.0f); GLfloat diff[] = {0.0f, 0.0f, 1.0f, 1.0f}; GLfloat spec[] = {0.0f, 0.0f, 1.0f, 1.0f}; glLightfv(GL_LIGHT0, GL_DIFFUSE, diff); glLightfv(GL_LIGHT0, GL_SPECULAR, spec); glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.0f); glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.0f); glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.0f); GLfloat dir[] = {-0.577f, -0.577f, -0.577f}; GLfloat pos[] = {5.0f, 5.0f, 5.0f, 0.0f}; glLightfv(GL_LIGHT0, GL_POSITION, pos); glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 2.0f); glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 1.0f); glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, dir); glColor3f(0.0f, 0.0f, 1.0f); GLfloat mat_diff[] = {0.0f, 0.0f, 1.0f, 1.0f}; GLfloat mat_spec[] = {0.0f, 0.0f, 1.0f, 1.0f}; glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diff); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_spec); glMaterialf(GL_FRONT, GL_SHININESS, 50.0f); glRotated(x_angl, 1.0, 0.0, 0.0); glRotated(y_angl, 0.0, 1.0, 0.0); glRotated(z_angl, 0.0, 0.0, 1.0); glTranslatef(0.0f, 2.0f, 0.0f); glBegin(GL_QUADS); /* Middle section Length: 10.0cm Width: 1.0cm */ // Top glNormal3f(0.0f, 1.0f, 0.0f); glVertex3f(-5.0f, -4.5f, 0.5f); glVertex3f(5.0f, -4.5f, 0.5f); glVertex3f(5.0f, -4.5f, -0.5f); glVertex3f(-5.0f, -4.5f, -0.5f); // Front glNormal3f(0.0f, 0.0f, 1.0f); glVertex3f(-5.0f, -4.5f, 0.5f); glVertex3f(-5.0f, -5.5f, 0.5f); glVertex3f(5.0f, -5.5f, 0.5f); glVertex3f(5.0f, -4.5f, 0.5f); // Bottom glNormal3f(0.0f, -1.0f, 0.0f); glVertex3f(-5.0f, -5.5f, 0.5f); glVertex3f(6.0f, -5.5f, 0.5f); glVertex3f(6.0f, -5.5f, -0.5f); glVertex3f(-5.0f, -5.5f, -0.5f); // Back glNormal3f(0.0f, 0.0f, -1.0f); glVertex3f(-6.0f, -4.5f, -0.5f); glVertex3f(5.0f, -4.5f, -0.5f); glVertex3f(5.0f, -5.5f, -0.5f); glVertex3f(-6.0f, -5.5f, -0.5f); /* Left section Length: 9.0cm Width: 1.0cm */ // Top glNormal3f(0.0f, 1.0f, 0.0f); glVertex3f(-5.0f, -4.5f, -0.5f); glVertex3f(-5.0f, -4.5f, 8.5f); glVertex3f(-6.0f, -4.5f, 8.5f); glVertex3f(-6.0f, -4.5f, -0.5f); // Left glNormal3f(-1.0f, 0.0f, 0.0f); glVertex3f(-6.0f, -4.5f, -0.5f); glVertex3f(-6.0f, -4.5f, 8.5f); glVertex3f(-6.0f, -5.5f, 8.5f); glVertex3f(-6.0f, -5.5f, -0.5f); // Bottom glNormal3f(0.0f, -1.0f, 0.0f); glVertex3f(-6.0f, -5.5f, -0.5f); glVertex3f(-6.0f, -5.5f, 8.5f); glVertex3f(-5.0f, -5.5f, 8.5f); glVertex3f(-5.0f, -5.5f, -0.5f); // Right glNormal3f(1.0f, 0.0f, 0.0f); glVertex3f(-5.0f, -4.5f, -0.5f); glVertex3f(-5.0f, -5.5f, -0.5f); glVertex3f(-5.0f, -5.5f, 8.5f); glVertex3f(-5.0f, -4.5f, 8.5f); // End glNormal3f(0.0f, 0.0f, 1.0f); glVertex3f(-6.0f, -4.5f, 8.5f); glVertex3f(-6.0f, -5.5f, 8.5f); glVertex3f(-5.0f, -5.5f, 8.5f); glVertex3f(-5.0f, -4.5f, 8.5f); /* Right section Length: 9.0cm Width: 1.0cm */ // Front glNormal3f(0.0f, 0.0f, 1.0f); glVertex3f(5.0f, -5.5f, 0.5f); glVertex3f(5.0f, 4.5f, 0.5f); glVertex3f(6.0f, 4.5f, 0.5f); glVertex3f(6.0f, -5.5f, 0.5f); // Left glNormal3f(-1.0f, 0.0f, 0.0f); glVertex3f(5.0f, -5.5f, 0.5f); glVertex3f(5.0f, -5.5f, -0.5f); glVertex3f(5.0f, 2.3f, -0.5f); glVertex3f(5.0f, 2.3f, 0.5f); // Back glNormal3f(0.0f, 0.0f, -1.0f); glVertex3f(5.0f, -5.5f, -0.5f); glVertex3f(6.0f, -5.5f, -0.5f); glVertex3f(6.0f, 3.0f, -0.5f); glVertex3f(5.0f, 3.0f, -0.5f); // Right glNormal3f(1.0f, 0.0f, 0.0f); glVertex3f(6.0f, -5.5f, 0.5f); glVertex3f(6.0f, -5.5f, -0.5f); glVertex3f(6.0f, 4.5f, -0.5f); glVertex3f(6.0f, 4.5f, 0.5f); // Top glNormal3f(0.0f, 1.0f, 0.0f); glVertex3f(5.0f, 4.5f, -0.5f); glVertex3f(5.0f, 4.5f, 0.5f); glVertex3f(6.0f, 4.5f, 0.5f); glVertex3f(6.0f, 4.5f, -0.5f); glEnd(); glBegin(GL_TRIANGLES); // Left glNormal3f(-1.0f, 0.0f, 0.0f); glVertex3f(5.0f, 3.5f, 0.5f); glVertex3f(5.0f, 4.5f, -0.5f); glVertex3f(5.0f, 4.5f, 0.5f); // Back glNormal3f(0.0f, 0.0f, -1.0f); glVertex3f(5.0f, 3.0f, -0.5f); glVertex3f(6.0f, 3.0f, -0.5f); glVertex3f(6.0f, 3.9f, -0.5f); glEnd(); glFlush(); }
[ [ [ 1, 341 ] ] ]
03bbbecf843657d85c609fc41aa144e70bf955b1
11dfb7197905169a3f0544eeaf507fe108d50f7e
/slmAPI/fft2d.cpp
353f97a7490a532a4918fb23218c510f4b1929f7
[]
no_license
rahulbhadani/adaptive-optics
67791a49ecbb085ac8effdc44e5177b0357b0fa7
e2b296664b7674e87a5a68ec7b794144b37ae74d
refs/heads/master
2020-04-28T00:08:24.585833
2011-08-09T22:28:11
2011-08-09T22:28:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,438
cpp
/*------------------------------------------------------------------------- Perform a 2D FFT inplace given a complex 2D array The direction dir, 1 for forward, -1 for reverse The size of the array (nx,ny) Return false if there are memory problems or the dimensions are not powers of 2 */ #include "slmproject.h" #include "fft2d.h" //#include "test.h" fft2dTrans::fft2dTrans() { width = SLMSIZE; heigth = SLMSIZE; transdata = alloc_2d_complex(heigth, width); return; } fft2dTrans::~fft2dTrans() { free_2d_complex(transdata); return; } void fft2dTrans::getPhase(double *phasedata) { int rowNum,colNum; for (rowNum = 0; rowNum < heigth; rowNum ++) { for (colNum = 0; colNum < width; colNum++) { phasedata[rowNum*heigth + colNum] = atan2(transdata[rowNum][colNum].imag, transdata[rowNum][colNum].real); } } #ifdef DEBUG_SIGN ////////////////////////////////////////////////////////////////////// debug_outdata_double(SLMSIZE, "dfftphase.txt", phasedata); ////////////////////////////////////////////////////////////////////// #endif return; } void fft2dTrans::getAmp(double *Ampdata) { int rowNum,colNum; for (rowNum = 0; rowNum < heigth; rowNum ++) { for (colNum = 0; colNum < width; colNum++) { Ampdata[rowNum*heigth + colNum] = sqrt(transdata[rowNum][colNum].imag * transdata[rowNum][colNum].imag \ + transdata[rowNum][colNum].real * transdata[rowNum][colNum].real); } } return; } void fft2dTrans::Powerof2(int n,int *m, int*twopm) { if (n == 0) return; int i = 0; while(1) { if (n == 1) break; i ++; n = n>>1; } *m = i; *twopm = 1<<(i); return; } COMPLEX ** fft2dTrans::alloc_2d_complex(int n1, int n2) { COMPLEX ** ii, *i; int j; ii = (COMPLEX **) malloc (sizeof(COMPLEX *) * n1); i = (COMPLEX *) malloc (sizeof(COMPLEX) * n1 * n2); ii[0] = i; for (j = 1; j < n1; j++) { ii[j] = ii[j - 1] + n2; } return ii; } void fft2dTrans::free_2d_complex(COMPLEX ** comimage) { free(comimage[0]); free(comimage); return; } void fft2dTrans::receivedata(double *data, int wid, int hts) { int i, j; width = wid; heigth = hts; for (j=0;j<heigth;j++) { for (i=0;i<width;i++) { transdata[j][i].real = data[j*width+i]; transdata[j][i].imag = 0; } } #ifdef DEBUG_SIGN //////////////////////////////////////////////////////////////////////// debug_outdata_complex(SLMSIZE, "receivecomp.txt", transdata); //////////////////////////////////////////////////////////////////////// #endif return; } void fft2dTrans::fft2(int nx,int ny,int dir) { int i,j; int m, twopm; double *real,*imag; /* Transform the rows */ real = (double *) malloc (nx * sizeof(double)); imag = (double *) malloc (nx * sizeof(double)); Powerof2(nx,&m,&twopm); if (twopm != nx) return; for (j=0;j<ny;j++) { for (i=0;i<nx;i++) { real[i] = transdata[i][j].real; imag[i] = transdata[i][j].imag; } fft(dir,m,real,imag); for (i=0;i<nx;i++) { transdata[i][j].real = real[i]; transdata[i][j].imag = imag[i]; } } free(real); free(imag); /* Transform the columns */ real = (double*) malloc (ny * sizeof(double)); imag = (double*) malloc (ny * sizeof(double)); Powerof2(ny,&m,&twopm); if (twopm != ny) return; for (i=0;i<nx;i++) { for (j=0;j<ny;j++) { real[j] = transdata[i][j].real; imag[j] = transdata[i][j].imag; } fft(dir,m,real,imag); for (j=0;j<ny;j++) { transdata[i][j].real = real[j]; transdata[i][j].imag = imag[j]; } } free(real); free(imag); #ifdef DEBUG_SIGN //////////////////////////////////////////////////////////////////////// debug_outdata_complex(SLMSIZE, "afterfftcomp.txt", transdata); //////////////////////////////////////////////////////////////////////// #endif return; } /*------------------------------------------------------------------------- This computes an in-place complex-to-complex FFT x and y are the real and imaginary arrays of 2^m points. dir = 1 gives forward transform dir = -1 gives reverse transform Formula: forward N-1 --- 1 \ - j k 2 pi n / N X(n) = --- > x(k) e = forward transform N / n=0..N-1 --- k=0 Formula: reverse N-1 --- \ j k 2 pi n / N X(n) = > x(k) e = forward transform / n=0..N-1 --- k=0 */ void fft2dTrans::fft(int dir,int m,double *x,double *y) { long nn,i,i1,j,k,i2,l,l1,l2; double c1,c2,tx,ty,t1,t2,u1,u2,z; /* Calculate the number of points */ nn = 1; for (i=0;i<m;i++) nn *= 2; /* Do the bit reversal */ i2 = nn >> 1; j = 0; for (i=0;i<nn-1;i++) { if (i < j) { tx = x[i]; ty = y[i]; x[i] = x[j]; y[i] = y[j]; x[j] = tx; y[j] = ty; } k = i2; while (k <= j) { j -= k; k >>= 1; } j += k; } /* Compute the FFT */ c1 = -1.0; c2 = 0.0; l2 = 1; for (l=0;l<m;l++) { l1 = l2; l2 <<= 1; u1 = 1.0; u2 = 0.0; for (j=0;j<l1;j++) { for (i=j;i<nn;i+=l2) { i1 = i + l1; t1 = u1 * x[i1] - u2 * y[i1]; t2 = u1 * y[i1] + u2 * x[i1]; x[i1] = x[i] - t1; y[i1] = y[i] - t2; x[i] += t1; y[i] += t2; } z = u1 * c1 - u2 * c2; u2 = u1 * c2 + u2 * c1; u1 = z; } c2 = sqrt((1.0 - c1) / 2.0); if (dir == 1) c2 = -c2; c1 = sqrt((1.0 + c1) / 2.0); } /* Scaling for forward transform */ if (dir == 1) { for (i=0;i<nn;i++) { x[i] /= (double)nn; y[i] /= (double)nn; } } return; }
[ [ [ 1, 283 ] ] ]
039f3b9e9b30ac2777992356c3b27ba37f90f86f
47e5d797d7ba54d554ef84dab676ebb125385b99
/Window.cpp
55eaf4763e35f52844981866bbf1d8ec81e35477
[ "WTFPL" ]
permissive
remram44/srt-shift
75163ed477601a42e36e2cb62110ac85d2f8f23d
8bf5df0955bcdc33bfbadd5396aed1e23356da83
refs/heads/master
2020-05-17T19:55:41.202821
2009-07-23T21:43:00
2009-07-23T21:43:00
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,026
cpp
/* This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://sam.zoy.org/wtfpl/COPYING for more details. */ #include "Window.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <QFileDialog> #include <QFrame> #include <QTimeEdit> #include <QHeaderView> Window::Window() { resize(680, -1); QHBoxLayout *hlayout = new QHBoxLayout; // Le tableau, à gauche { m_pTable = new QTableWidget; m_pTable->setSelectionMode(QAbstractItemView::SingleSelection); m_pTable->setColumnCount(3); QStringList labels; labels << tr("Position du sous-titre") << tr("Position voulue") << tr("Supprimer le point"); m_pTable->setHorizontalHeaderLabels(labels); m_pTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch); addPoint(); addPoint(); hlayout->addWidget(m_pTable); } // Le reste, à droite { QVBoxLayout *vlayout = new QVBoxLayout; QPushButton *add = new QPushButton(tr("Ajouter un point")); connect(add, SIGNAL(clicked()), this, SLOT(addPoint())); vlayout->addWidget(add); m_pSourceFile = new FileSelector(FileSelector::READ); vlayout->addWidget(m_pSourceFile); m_pTargetFile = new FileSelector(FileSelector::WRITE); vlayout->addWidget(m_pTargetFile); QPushButton *go = new QPushButton(tr("Appliquer")); connect(go, SIGNAL(clicked()), this, SLOT(process())); vlayout->addWidget(go); hlayout->addLayout(vlayout); } setLayout(hlayout); show(); } void Window::addPoint() { // Agrandit le tableau int row = m_pTable->rowCount(); m_pTable->setRowCount(row + 1); // Remplit la nouvelle ligne m_pTable->setCellWidget(row, 0, new QTimeEdit); m_pTable->setCellWidget(row, 1, new QTimeEdit); QPushButton *r = new RemoveButton(row); connect(r, SIGNAL(removeRow(int)), this, SLOT(removePoint(int))); m_pTable->setCellWidget(row, 2, r); } void Window::removePoint(int row) { m_pTable->removeRow(row); for(; row < m_pTable->rowCount(); row++) qobject_cast<RemoveButton*>(m_pTable->cellWidget(row, 2))->setRow(row); } RemoveButton::RemoveButton(int row) : QPushButton::QPushButton(tr("Supprimer")), m_iRow(row) { connect(this, SIGNAL(clicked()), this, SLOT(onclick())); } void RemoveButton::setRow(int row) { m_iRow = row; } void RemoveButton::onclick() { emit removeRow(m_iRow); } FileSelector::FileSelector(EOpenType type, QString text, QWidget *parent) : QFrame::QFrame(parent), m_eType(type) { QHBoxLayout *hlayout = new QHBoxLayout; m_pLineEdit = new QLineEdit; hlayout->addWidget(m_pLineEdit); m_pLineEdit->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); QPushButton *searchButton = new QPushButton(tr("Parcourir")); connect(searchButton, SIGNAL(clicked()), this, SLOT(search())); hlayout->addWidget(searchButton); setLayout(hlayout); } void FileSelector::search() { QString ret; if(m_eType == FileSelector::READ) ret = QFileDialog::getOpenFileName(this, tr("Choisissez le fichier " ".srt de départ"), "", tr("Sous-titre au format SubRip (*.srt);;Tous les fichiers (*.*)")); else ret = QFileDialog::getSaveFileName(this, tr("Choisissez le fichier " ".srt de départ"), "", tr("Sous-titre au format SubRip (*.srt);;Tous les fichiers (*.*)")); if(!ret.isNull()) m_pLineEdit->setText(ret); } QString FileSelector::path() const { return m_pLineEdit->text(); } void FileSelector::setPath(QString text) { m_pLineEdit->setText(text); }
[ [ [ 1, 132 ] ] ]
fa98da90867b21a42816993b9a8a31b2d433da1b
d752d83f8bd72d9b280a8c70e28e56e502ef096f
/Shared/Utility/Threading/Synchronization.h
944a7b601c07b19f0c753afd92871c1076622a90
[]
no_license
apoch/epoch-language.old
f87b4512ec6bb5591bc1610e21210e0ed6a82104
b09701714d556442202fccb92405e6886064f4af
refs/heads/master
2021-01-10T20:17:56.774468
2010-03-07T09:19:02
2010-03-07T09:19:02
34,307,116
0
0
null
null
null
null
UTF-8
C++
false
false
1,328
h
// // The Epoch Language Project // Shared Library Code // // Thread synchronization objects // #pragma once namespace Threads { // // Wrapper for a system critical section object. // Use the helper class for RAII semantics, to // ensure that the critical section is always // entered and exited correctly. // class CriticalSection { // Construction and destruction public: CriticalSection(); ~CriticalSection(); // Entry and exit public: void Enter(); void Exit(); // RAII helper public: struct Auto { Auto(CriticalSection& critsec) : BoundCritSec(critsec) { BoundCritSec.Enter(); } ~Auto() { BoundCritSec.Exit(); } private: CriticalSection& BoundCritSec; }; // Internal tracking private: CRITICAL_SECTION CritSec; }; // // RAII wrapper of a special synchronization counter. // This counter is effectively an inverse semaphore; // when its count is 0, it is "unlocked", and when // the count is greater than 0, is is "locked." // class SyncCounter { // Construction and destruction public: explicit SyncCounter(unsigned* pcounter, HANDLE tripevent); ~SyncCounter(); // Internal tracking private: unsigned* PointerToCounter; HANDLE TripEvent; }; }
[ "don.apoch@localhost" ]
[ [ [ 1, 77 ] ] ]
c328ef79b413b87ead284a546ea916e40fc459f1
2ecceb65bab072b6a3a0623aeb7577499299d550
/winc/quickrun/shortcut.cpp
dd0a8f7b9201dc993ac76d3f56ce9567c2775ef5
[]
no_license
amoblin/amoblin
35d66d1d45fdb08cb743f241f0135b2ad02079c4
c43af84b6d9c71de443ae7ad02255a7303a578ae
refs/heads/master
2016-08-02T21:42:40.811549
2011-12-07T10:43:16
2011-12-07T10:43:16
1,047,196
0
1
null
null
null
null
GB18030
C++
false
false
5,354
cpp
/* kbhook.cpp */ //#define _WIN32_WINNT 0400 //#define STRICT #define WIN32_LEAN_AND_MEAN #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <shellapi.h> #define bool BOOL #define MAXLENGTH 1024 DWORD g_main_tid = 0; HHOOK g_kb_hook = 0; bool control_key=0; bool CALLBACK con_handler (DWORD) { PostThreadMessage (g_main_tid, WM_QUIT, 0, 0); return TRUE; }; int getvkcode(char *ch) { if (!strcmp(ch,";")) return 0x00ba; else if (!strcmp(ch,"'")) return 0x00de; else if (!strcmp(ch,",")) return 0x00bc; else if (!strcmp(ch,".")) return 0x00be; else if (!strcmp(ch,"/")) return 0x00bf; else if (!strcmp(ch,"a")) return 0x0041; else if (!strcmp(ch,"F1")) return 0x0070; else if (!strcmp(ch,"F2")) return 0x0071; else if (!strcmp(ch,"F3")) return 0x0072; else if (!strcmp(ch,"F4")) return 0x0073; else if (!strcmp(ch,"F5")) return 0x0074; else if (!strcmp(ch,"F6")) return 0x0075; else if (!strcmp(ch,"F7")) return 0x0076; else if (!strcmp(ch,"F8")) return 0x0077; else if (!strcmp(ch,"F9")) return 0x0078; else if (!strcmp(ch,"F10")) return 0x0079; else if (!strcmp(ch,"F11")) return 0x007a; else if (!strcmp(ch,"F12")) return 0x007b; else return 0x0000; } int GetAction(PKBDLLHOOKSTRUCT p) { FILE *fp; fp = fopen("shortcut.ini","r"); if (fp == NULL) { printf("Cannot open this file.\n"); return 0; } else { printf("read shortcut.ini.\n"); } char buf[MAXLENGTH]; char KeyboardCode[100]; char CommandPath[100]; while(fgets(buf,MAXLENGTH,fp)) { bool flag = 1; char *ptr = strchr(buf,'='); if(ptr) { memset(KeyboardCode,0,strlen(KeyboardCode)); strncpy(KeyboardCode,buf,ptr-buf); //printf("compare with %s:\n",KeyboardCode); char *token = strtok(KeyboardCode,"+"); while(token != NULL) { //printf("the key is: %s\n",token); if(!strcmp(token,"ALT")) { flag = 0; if ((p->flags & LLKHF_ALTDOWN)!=0) flag = 1; } else if (p->vkCode == getvkcode(token) && flag) { strcpy(CommandPath,ptr+sizeof(char)); char *ptr = strchr(CommandPath,'\n'); if(ptr) { *ptr = 0; } printf("execute %s:",CommandPath); ShellExecute(NULL,"open",CommandPath,"","", SW_SHOW ); } token = strtok(NULL,"+"); } } } fclose(fp); return 0; } LRESULT CALLBACK kb_proc (int code, WPARAM w, LPARAM l) { PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)l; printf ("code is %d, vkCode [%04x], scanCode [%04x]\n", code, p->vkCode, p->scanCode); if (code == HC_ACTION) { switch(w) { case WM_KEYDOWN: case WM_SYSKEYDOWN: if(p->vkCode == 0x00a2) { control_key= 1; } else if((p->vkCode == 76) && control_key) { keybd_event(VK_F4,0,0,0); keybd_event(VK_F4,0,KEYEVENTF_KEYUP,0); } printf("Get Action.\n"); GetAction(p); break; case WM_KEYUP: if(p->vkCode == 0x00a2) { control_key= 0; } break; case WM_SYSKEYUP: break; } } return CallNextHookEx (g_kb_hook, code, w, l); }; int main (void) { static char subkey[] = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"; static char vname[] = "ShortCut"; static char exefile[] = "D:\\MSYS\\home\\Administrator\\Projects\\amoblin\\winc\\quickrun\\shortcut.exe"; ULONG dType = REG_SZ, len = 0; HKEY hKey; RegOpenKeyEx(HKEY_LOCAL_MACHINE,subkey,0,KEY_SET_VALUE|KEY_QUERY_VALUE,&hKey);//打开。 if (RegQueryValueEx(hKey, vname, 0, &dType, NULL, &len)) { //如果没有RunMyProg, RegSetValueEx(hKey, vname, 0, REG_SZ, (LPBYTE)exefile, strlen(exefile)+1); //就加上。 } RegCloseKey(hKey); //关闭。 g_main_tid = GetCurrentThreadId (); SetConsoleCtrlHandler (&con_handler, TRUE); g_kb_hook = SetWindowsHookEx ( WH_KEYBOARD_LL, &kb_proc, GetModuleHandle (NULL), 0); if (g_kb_hook == NULL) { fprintf (stderr, "SetWindowsHookEx failed with error %d\n", ::GetLastError ()); return 0; }; // 消息循环是必须的,想知道原因可以查msdn MSG msg; while (GetMessage (&msg, NULL, 0, 0)) { TranslateMessage (&msg); DispatchMessage (&msg); }; UnhookWindowsHookEx (g_kb_hook); return 0; };
[ "amoblin@38427a0e-ebd1-11de-a198-37193048d1ed" ]
[ [ [ 1, 170 ] ] ]
dce6208c6a6b8079cbf3792b52509b766e825055
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/test/owi_mt_tests.cpp
160b63b5fc3647ae93163a6726d39859b1614844
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
5,566
cpp
/*============================================================================= Copyright (c) 2002-2004 Martin Wille http://spirit.sourceforge.net/ 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) =============================================================================*/ // std::lower_bound seems to perform awfully slow with _GLIBCXX_DEBUG enabled #undef _GLIBCXX_DEBUG #include <iostream> #include <boost/config.hpp> #include <boost/detail/lightweight_test.hpp> #if !defined(BOOST_HAS_THREADS) || defined(DONT_HAVE_BOOST) || defined(BOOST_DISABLE_THREADS) static void skipped() { std::cout << "skipped\n"; } int main() { skipped(); return 0; } #else //////////////////////////////////////////////////////////////////////////////// static const unsigned long initial_test_size = 5000UL; #if defined(_DEBUG) && (BOOST_MSVC >= 1400) static const unsigned long maximum_test_size = 10000UL; #else static const unsigned long maximum_test_size = 1000000UL; #endif //////////////////////////////////////////////////////////////////////////////// #undef BOOST_SPIRIT_THREADSAFE #define BOOST_SPIRIT_THREADSAFE #include <boost/thread/thread.hpp> #include <boost/spirit/core/non_terminal/impl/object_with_id.ipp> #include <boost/ref.hpp> #include <boost/thread/xtime.hpp> #include <vector> #include <algorithm> #include <boost/detail/lightweight_test.hpp> using boost::spirit::impl::object_with_id; struct tag1 {}; typedef object_with_id<tag1> class1; unsigned long test_size = initial_test_size; boost::xtime start_time; template <typename ClassT> struct test_task { test_task() : v(), m(), progress(0) {} void operator ()() { // create lots of objects unsigned long i = 0; v.reserve(maximum_test_size); do { for (; i<test_size; ++i) v.push_back(new ClassT); } while ( i < increase_test_size(i) ); } static unsigned long increase_test_size(unsigned long size) { static boost::mutex m; boost::mutex::scoped_lock l(m); if (size<test_size || test_size == maximum_test_size) return test_size; boost::xtime now; boost::xtime_get(&now, boost::TIME_UTC); unsigned long seconds = now.sec - start_time.sec; if (seconds < 4) { test_size *= 2; if (test_size > maximum_test_size) test_size = maximum_test_size; } return test_size; } std::vector<ClassT*> const &data() const { return v; } private: std::vector<ClassT*> v; boost::mutex m; unsigned int progress; }; test_task<class1> test1; test_task<class1> test2; test_task<class1> test3; template <typename ClassT> void check_ascending(test_task<ClassT> const &t) { typedef typename std::vector<ClassT*>::const_iterator iter; iter p(t.data().begin()); iter const e(t.data().end()); iter n(p); while (++n!=e) { if ((**n).get_object_id()<=(**p).get_object_id()) { using namespace std; throw std::runtime_error("object ids out of order"); } p = n; } }; struct less1 { bool operator()(class1 const *p, class1 const *q) const { return p->get_object_id() < q->get_object_id(); } }; template <typename ClassT> void check_not_contained_in( test_task<ClassT> const &candidate, test_task<ClassT> const &in ) { typedef typename std::vector<ClassT*>::const_iterator iter; iter p(candidate.data().begin()); iter const e(candidate.data().end()); while (p!=e) { iter found = std::lower_bound(in.data().begin(),in.data().end(),*p,less1()); if (found!=in.data().end() && (**found).get_object_id() == (**p).get_object_id()) { using namespace std; throw std::runtime_error("object ids not unqiue"); } ++p; } }; void concurrent_creation_of_objects() { { boost::xtime_get(&start_time, boost::TIME_UTC); boost::thread thread1(boost::ref(test1)); boost::thread thread2(boost::ref(test2)); boost::thread thread3(boost::ref(test3)); thread1.join(); thread2.join(); thread3.join(); } } void local_uniqueness() { BOOST_TEST(test1.data().size()==test_size); BOOST_TEST(test2.data().size()==test_size); BOOST_TEST(test3.data().size()==test_size); } void local_ordering_and_uniqueness() { // now all objects should have unique ids, // the ids must be ascending within each vector // check for ascending ids check_ascending(test1); check_ascending(test2); check_ascending(test3); } void global_uniqueness() { check_not_contained_in(test1,test3); check_not_contained_in(test1,test2); check_not_contained_in(test2,test1); check_not_contained_in(test2,test3); check_not_contained_in(test3,test2); check_not_contained_in(test3,test1); } int main() { concurrent_creation_of_objects(); local_ordering_and_uniqueness(); global_uniqueness(); return boost::report_errors(); } #endif // BOOST_HAS_THREADS
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 222 ] ] ]
2f88345a8e71201c9b56bb11432b42026fb8d225
382b459563be90227848e5125f0d37f83c1e2a4f
/Schedule/include/obsolete/abstractidgenerator.h
f3e433b08b7779648319532f9cf811351c85e174
[]
no_license
Maciej-Poleski/SchoolTools
516c9758dfa153440a816a96e3f05c7f290daf6c
e55099f77eb0f65b75a871d577cc4054221b9802
refs/heads/master
2023-07-02T09:07:31.185410
2010-07-11T20:56:59
2010-07-11T20:56:59
392,391,718
0
0
null
null
null
null
UTF-8
C++
false
false
618
h
#ifndef ABSTRACTIDGENERATOR_H #define ABSTRACTIDGENERATOR_H #include "abstractid.h" #include "id.h" namespace obsolete { /** Klasa bazowa obiektów-generatorów identyfikatorów. **/ class AbstractIDGenerator : public AbstractID { public: inline AbstractIDGenerator(uint ID=1) : AbstractID(ID) {} ///< Inicjalizuje wartość początkową generatora identyfikatorów. virtual ID createID(); ///< Tworzy nowy identyfikator. static ID createVoidID(); ///< Tworzy niezainicjowany identyfikator private: }; } #endif // ABSTRACTIDGENERATOR_H
[ [ [ 1, 22 ] ] ]
dfb54fe46648c8f20d92d2bd9de1ff6af4500514
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/kernel/nfileserver2_cmds.cc
64b103aa7b6fce28298ccad4cf60c54b5ec810d4
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,410
cc
#define N_IMPLEMENTS nFileServer2 #define N_KERNEL //------------------------------------------------------------------------------ // (C) 2001 RadonLabs GmbH //------------------------------------------------------------------------------ #include "kernel/nfileserver2.h" #include "kernel/npersistserver.h" static void n_setassign(void* slf, nCmd* cmd); static void n_getassign(void* slf, nCmd* cmd); static void n_manglepath(void* slf, nCmd* cmd); static void n_fileexists(void* slf, nCmd* cmd); static void n_filesize(void* slf, nCmd* cmd); static void n_setdevmode(void* slf, nCmd* cmd); static void n_getdevmode(void* slf, nCmd* cmd); //------------------------------------------------------------------------------ /** @scriptclass nfileserver2 @superclass nroot @classinfo da nu fileserver */ void n_initcmds(nClass* clazz) { clazz->BeginCmds(); clazz->AddCmd("v_setassign_ss", 'SASS', n_setassign); clazz->AddCmd("s_getassign_s", 'GASS', n_getassign); clazz->AddCmd("s_manglepath_s", 'MNGP', n_manglepath); clazz->AddCmd("b_fileexists_s", 'FEXT', n_fileexists); clazz->AddCmd("i_filesize_s", 'FSZE', n_filesize); clazz->AddCmd("v_setdevmode_b", 'SDVM', n_setdevmode); clazz->AddCmd("b_getdevmode_v", 'GDVM', n_getdevmode); clazz->EndCmds(); } //------------------------------------------------------------------------------ /** @cmd setassign @input s assign name s path @output v @info defines an assign with the specified name and links it to the specified path */ static void n_setassign(void* slf, nCmd* cmd) { nFileServer2* self = (nFileServer2*) slf; const char* s0 = cmd->In()->GetS(); const char* s1 = cmd->In()->GetS(); self->SetAssign(s0, s1); } //------------------------------------------------------------------------------ /** @cmd getassign @input s assign name @output s path @info siehe setassign */ static void n_getassign(void* slf, nCmd* cmd) { nFileServer2* self = (nFileServer2*) slf; cmd->Out()->SetS(self->GetAssign(cmd->In()->GetS())); } //------------------------------------------------------------------------------ /** @cmd fileexists @input s - path @output b - success @info checks file existence in the path */ static void n_fileexists(void* slf, nCmd* cmd) { nFileServer2* self = (nFileServer2*) slf; const char* s = cmd->In()->GetS(); cmd->Out()->SetB(self->FileExists(s)); } //------------------------------------------------------------------------------ /** @cmd filesize @input s - path @output i - size, -1 if file not exists @info returns file size, -1 if file not exists */ static void n_filesize(void* slf, nCmd* cmd) { nFileServer2* self = (nFileServer2*) slf; const char* s = cmd->In()->GetS(); cmd->Out()->SetI(self->FileSize(s)); } //------------------------------------------------------------------------------ /** @cmd setdevmode @input b devmode @output v @info set fileserver2 to developer mode, in developer mode file server will check first existance of file in the real file system. */ static void n_setdevmode(void* slf, nCmd* cmd) { nFileServer2* self = (nFileServer2*) slf; self->SetDevMode(cmd->In()->GetB()); } //------------------------------------------------------------------------------ /** @cmd getdevmode @input v @output b devmode @info returns true if fileserver2 in developer mode */ static void n_getdevmode(void* slf, nCmd* cmd) { nFileServer2* self = (nFileServer2*) slf; cmd->Out()->SetB(self->GetDevMode()); } //------------------------------------------------------------------------------ /** @cmd manglepath @input s(UnmangledPath) @output s(MangledPath) @info Convert a path with assigns into a native absolute path. */ static void n_manglepath(void* slf, nCmd* cmd) { nFileServer2* self = (nFileServer2*) slf; stl_string path; self->ManglePath(cmd->In()->GetS(), path); cmd->Out()->SetS(path.c_str()); }
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 199 ] ] ]
9f231bad2d96c5a55d38cb90e90555ab48956aab
ac559231a41a5833220a1319456073365f13d484
/src/old/server-jaus/jaus/mobility/drivers/setvelocitycommand.h
8876f96beccebc6df42ac8cad19f731e4f25cd1c
[]
no_license
mtboswell/mtboswell-auvc2
6521002ca12f9f7e1ec5df781ed03419129b8f56
02bb0dd47936967a7b9fa7d091398812f441c1dc
refs/heads/master
2020-04-01T23:02:15.282160
2011-07-17T16:48:34
2011-07-17T16:48:34
32,832,956
0
0
null
null
null
null
UTF-8
C++
false
false
7,499
h
//////////////////////////////////////////////////////////////////////////////////// /// /// \file setvelocitycommand.h /// \brief This file contains the implementation of a JAUS message. /// /// <br>Author(s): Bo Sun /// <br>Created: 2 December 2009 /// <br>Copyright (c) 2009 /// <br>Applied Cognition and Training in Immersive Virtual Environments /// <br>(ACTIVE) Laboratory /// <br>Institute for Simulation and Training (IST) /// <br>University of Central Florida (UCF) /// <br>All rights reserved. /// <br>Email: [email protected] /// <br>Web: http://active.ist.ucf.edu /// /// 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 ACTIVE LAB, IST, UCF, 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 ACTIVE LAB''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 UCF 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 __JAUS_MOBILITY_SET_VELOCITY_COMMAND__H #define __JAUS_MOBILITY_SET_VELOCITY_COMMAND__H #include "jaus/core/message.h" #include "jaus/mobility/mobilitycodes.h" namespace JAUS { //////////////////////////////////////////////////////////////////////////////////// /// /// \class SetVelocityCommand /// \brief This message is used to command the linear velocity and rotational /// rate of the platform. /// //////////////////////////////////////////////////////////////////////////////////// class JAUS_MOBILITY_DLL SetVelocityCommand : public Message { public: //////////////////////////////////////////////////////////////////////////////////// /// /// \class PresenceVector /// \brief This class contains bit masks for bitwise operations on the /// presence vector for this message. /// //////////////////////////////////////////////////////////////////////////////////// class JAUS_MOBILITY_DLL PresenceVector : public JAUS::PresenceVector { public: const static Byte VelocityX = 0x01; const static Byte VelocityY = 0x02; const static Byte VelocityZ = 0x04; const static Byte RollRate = 0x08; const static Byte PitchRate = 0x10; const static Byte YawRate = 0x20; }; //////////////////////////////////////////////////////////////////////////////////// /// /// \class Limits /// \brief Contains constants for limit values of data members of class. /// //////////////////////////////////////////////////////////////////////////////////// class JAUS_MOBILITY_DLL Limits : public JAUS::Limits { public: const static double MinVelocity; ///< Minimum velocity. (-327.68) const static double MaxVelocity; ///< Maximum velocity. (327.67) const static double MinRotationalRate; ///< Minimum Rotational Rate. (-32.768) const static double MaxRotationalRate; ///< Maximum Rotational Rate. (32.767) }; // Command types when issuing commands. enum Command { SetCurrentCommand = 0, SetMaximumAllowedValues, SetMinimumAllowedValues, SetDefaultCommand }; SetVelocityCommand(const Address& dest = Address(), const Address& src = Address()); SetVelocityCommand(const SetVelocityCommand& message); ~SetVelocityCommand(); inline Byte SetCommandType(const Command type) { return mCommandType = type; } bool SetVelocityX(const double value); bool SetVelocityY(const double value); bool SetVelocityZ(const double value); bool SetRollRate(const double value); bool SetPitchRate(const double value); bool SetYawRate(const double value); inline Byte GetCommandType() const { return mCommandType; } inline double GetVelocityX() const { return mVelocityX; } inline double GetVelocityY() const { return mVelocityY; } inline double GetVelocityZ() const { return mVelocityZ; } inline double GetRollRate() const { return mRollRate; } inline double GetPitchRate() const { return mPitchRate; } inline double GetYawRate() const { return mYawRate; } virtual bool IsCommand() const { return true; } virtual int WriteMessageBody(Packet& packet) const; virtual int ReadMessageBody(const Packet& packet); virtual Message* Clone() const { return new SetVelocityCommand(*this); } virtual UInt GetPresenceVector() const { return mPresenceVector; } virtual UInt GetPresenceVectorSize() const { return BYTE_SIZE; } virtual UInt GetPresenceVectorMask() const { return 0x3F; } virtual UShort GetMessageCodeOfResponse() const { return 0; } virtual std::string GetMessageName() const { return "Set Velocity Command"; } virtual void ClearMessageBody(); virtual bool IsLargeDataSet(const unsigned int maxPayloadSize = 1437) const { return false; } virtual int RunTestCase() const; SetVelocityCommand& operator=(const SetVelocityCommand& message); protected: Byte mPresenceVector; ///< Bit vector for fields present. Command mCommandType; ///< CommandType double mVelocityX; ///< Velocity X in meters per second [-327.68, 327.67] double mVelocityY; ///< Velocity Y in meters per second [-327.68, 327.67] double mVelocityZ; ///< Velocity Z in meters per second [-327.68, 327.67] double mRollRate; ///< Roll Rate in Radians per second [-32.768, 32.767] double mPitchRate; ///< Pitch Rate in Radians per second [-32.768, 32.767] double mYawRate; ///< Yaw Rate in Radians per second [-32.768, 32.767] }; } #endif /* End of File */
[ [ [ 1, 141 ] ] ]
9919833555c28d42d783c45ef755dfa1fa1cdecc
974a20e0f85d6ac74c6d7e16be463565c637d135
/trunk/coreLibrary_300/source/core/dgConvexHull3d.cpp
814e6ebd54cbe25ac565b0d917efbd96fb0579dd
[]
no_license
Naddiseo/Newton-Dynamics-fork
cb0b8429943b9faca9a83126280aa4f2e6944f7f
91ac59c9687258c3e653f592c32a57b61dc62fb6
refs/heads/master
2021-01-15T13:45:04.651163
2011-11-12T04:02:33
2011-11-12T04:02:33
2,759,246
0
0
null
null
null
null
UTF-8
C++
false
false
28,426
cpp
/* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, 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. */ #include "dgStdafx.h" #include "dgStack.h" #include "dgGoogol.h" #include "dgConvexHull3d.h" #include "dgSmallDeterminant.h" #define DG_VERTEX_CLUMP_SIZE_3D 8 class dgAABBPointTree3d { public: #ifdef _DEBUG dgAABBPointTree3d() { static dgInt32 id = 0; m_id = id; id ++; } dgInt32 m_id; #endif dgBigVector m_box[2]; dgAABBPointTree3d* m_left; dgAABBPointTree3d* m_right; dgAABBPointTree3d* m_parent; }; class dgHullVertex: public dgBigVector { public: dgInt32 m_index; }; class dgAABBPointTree3dClump: public dgAABBPointTree3d { public: dgInt32 m_count; dgInt32 m_indices[DG_VERTEX_CLUMP_SIZE_3D]; }; dgConvexHull3DFace::dgConvexHull3DFace() { m_mark = 0; m_twin[0] = NULL; m_twin[1] = NULL; m_twin[2] = NULL; } dgFloat64 dgConvexHull3DFace::Evalue (const dgBigVector* const pointArray, const dgBigVector& point) const { const dgBigVector& p0 = pointArray[m_index[0]]; const dgBigVector& p1 = pointArray[m_index[1]]; const dgBigVector& p2 = pointArray[m_index[2]]; dgFloat64 matrix[3][3]; for (dgInt32 i = 0; i < 3; i ++) { matrix[0][i] = p2[i] - p0[i]; matrix[1][i] = p1[i] - p0[i]; matrix[2][i] = point[i] - p0[i]; } dgFloat64 error; dgFloat64 det = Determinant3x3 (matrix, &error); dgFloat64 precision = dgFloat64 (1.0f) / dgFloat64 (1<<24); dgFloat64 errbound = error * precision; if (fabs(det) > errbound) { return det; } dgGoogol exactMatrix[3][3]; for (dgInt32 i = 0; i < 3; i ++) { exactMatrix[0][i] = dgGoogol(p2[i]) - dgGoogol(p0[i]); exactMatrix[1][i] = dgGoogol(p1[i]) - dgGoogol(p0[i]); exactMatrix[2][i] = dgGoogol(point[i]) - dgGoogol(p0[i]); } dgGoogol exactDet (Determinant3x3(exactMatrix)); det = exactDet.GetAproximateValue(); return det; } dgBigPlane dgConvexHull3DFace::GetPlaneEquation (const dgBigVector* const pointArray) const { const dgBigVector& p0 = pointArray[m_index[0]]; const dgBigVector& p1 = pointArray[m_index[1]]; const dgBigVector& p2 = pointArray[m_index[2]]; dgBigPlane plane (p0, p1, p2); plane = plane.Scale (1.0f / sqrt (plane % plane)); return plane; } dgConvexHull3d::dgConvexHull3d (dgMemoryAllocator* const allocator) :dgList<dgConvexHull3DFace>(allocator), m_count (0), m_diag(), m_points(1024, allocator) { } dgConvexHull3d::dgConvexHull3d(dgMemoryAllocator* const allocator, const dgFloat64* const vertexCloud, dgInt32 strideInBytes, dgInt32 count, dgFloat64 distTol, dgInt32 maxVertexCount) :dgList<dgConvexHull3DFace>(allocator), m_count (0), m_diag(), m_points(count, allocator) { BuildHull (vertexCloud, strideInBytes, count, distTol, maxVertexCount); } dgConvexHull3d::~dgConvexHull3d(void) { } void dgConvexHull3d::BuildHull (const dgFloat64* const vertexCloud, dgInt32 strideInBytes, dgInt32 count, dgFloat64 distTol, dgInt32 maxVertexCount) { #if (defined (_WIN_32_VER) || defined (_WIN_64_VER)) dgUnsigned32 controlWorld = dgControlFP (0xffffffff, 0); dgControlFP (_PC_53, _MCW_PC); #endif dgInt32 treeCount = count / (DG_VERTEX_CLUMP_SIZE_3D>>1); if (treeCount < 4) { treeCount = 4; } treeCount *= 2; dgStack<dgHullVertex> points (count); dgStack<dgAABBPointTree3dClump> treePool (treeCount + 256); count = InitVertexArray(&points[0], vertexCloud, strideInBytes, count, &treePool[0], treePool.GetSizeInBytes()); if (m_count >= 4) { CalculateConvexHull (&treePool[0], &points[0], count, distTol, maxVertexCount); } #if (defined (_WIN_32_VER) || defined (_WIN_64_VER)) dgControlFP (controlWorld, _MCW_PC); #endif } dgInt32 dgConvexHull3d::ConvexCompareVertex(const dgHullVertex* const A, const dgHullVertex* const B, void* const context) { for (dgInt32 i = 0; i < 3; i ++) { if ((*A)[i] < (*B)[i]) { return -1; } else if ((*A)[i] > (*B)[i]) { return 1; } } return 0; } dgAABBPointTree3d* dgConvexHull3d::BuildTree (dgAABBPointTree3d* const parent, dgHullVertex* const points, dgInt32 count, dgInt32 baseIndex, dgInt8** memoryPool, dgInt32& maxMemSize) const { dgAABBPointTree3d* tree = NULL; _ASSERTE (count); dgBigVector minP ( dgFloat32 (1.0e15f), dgFloat32 (1.0e15f), dgFloat32 (1.0e15f), dgFloat32 (0.0f)); dgBigVector maxP (-dgFloat32 (1.0e15f), -dgFloat32 (1.0e15f), -dgFloat32 (1.0e15f), dgFloat32 (0.0f)); if (count <= DG_VERTEX_CLUMP_SIZE_3D) { dgAABBPointTree3dClump* const clump = new (*memoryPool) dgAABBPointTree3dClump; *memoryPool += sizeof (dgAABBPointTree3dClump); maxMemSize -= sizeof (dgAABBPointTree3dClump); _ASSERTE (maxMemSize >= 0); clump->m_count = count; for (dgInt32 i = 0; i < count; i ++) { clump->m_indices[i] = i + baseIndex; const dgBigVector& p = points[i]; minP.m_x = GetMin (p.m_x, minP.m_x); minP.m_y = GetMin (p.m_y, minP.m_y); minP.m_z = GetMin (p.m_z, minP.m_z); maxP.m_x = GetMax (p.m_x, maxP.m_x); maxP.m_y = GetMax (p.m_y, maxP.m_y); maxP.m_z = GetMax (p.m_z, maxP.m_z); } clump->m_left = NULL; clump->m_right = NULL; tree = clump; } else { dgBigVector median (dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f)); dgBigVector varian (dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f)); for (dgInt32 i = 0; i < count; i ++) { const dgBigVector& p = points[i]; minP.m_x = GetMin (p.m_x, minP.m_x); minP.m_y = GetMin (p.m_y, minP.m_y); minP.m_z = GetMin (p.m_z, minP.m_z); maxP.m_x = GetMax (p.m_x, maxP.m_x); maxP.m_y = GetMax (p.m_y, maxP.m_y); maxP.m_z = GetMax (p.m_z, maxP.m_z); median += p; varian += p.CompProduct (p); } varian = varian.Scale (dgFloat32 (count)) - median.CompProduct(median); dgInt32 index = 0; dgFloat64 maxVarian = dgFloat64 (-1.0e10f); for (dgInt32 i = 0; i < 3; i ++) { if (varian[i] > maxVarian) { index = i; maxVarian = varian[i]; } } dgBigVector center = median.Scale (dgFloat64 (1.0f) / dgFloat64 (count)); dgFloat64 test = center[index]; dgInt32 i0 = 0; dgInt32 i1 = count - 1; do { for (; i0 <= i1; i0 ++) { dgFloat64 val = points[i0][index]; if (val > test) { break; } } for (; i1 >= i0; i1 --) { dgFloat64 val = points[i1][index]; if (val < test) { break; } } if (i0 < i1) { Swap(points[i0], points[i1]); i0++; i1--; } } while (i0 <= i1); if (i0 == 0){ i0 = count / 2; } if (i0 == (count - 1)){ i0 = count / 2; } tree = new (*memoryPool) dgAABBPointTree3d; *memoryPool += sizeof (dgAABBPointTree3d); maxMemSize -= sizeof (dgAABBPointTree3d); _ASSERTE (maxMemSize >= 0); _ASSERTE (i0); _ASSERTE (count - i0); tree->m_left = BuildTree (tree, points, i0, baseIndex, memoryPool, maxMemSize); tree->m_right = BuildTree (tree, &points[i0], count - i0, i0 + baseIndex, memoryPool, maxMemSize); } _ASSERTE (tree); tree->m_parent = parent; tree->m_box[0] = minP - dgBigVector (dgFloat64 (1.0e-3f), dgFloat64 (1.0e-3f), dgFloat64 (1.0e-3f), dgFloat64 (1.0f)); tree->m_box[1] = maxP + dgBigVector (dgFloat64 (1.0e-3f), dgFloat64 (1.0e-3f), dgFloat64 (1.0e-3f), dgFloat64 (1.0f)); return tree; } dgInt32 dgConvexHull3d::InitVertexArray(dgHullVertex* const points, const dgFloat64* const vertexCloud, dgInt32 strideInBytes, dgInt32 count, void* const memoryPool, dgInt32 maxMemSize) { dgInt32 stride = dgInt32 (strideInBytes / sizeof (dgFloat64)); if (stride >= 4) { for (dgInt32 i = 0; i < count; i ++) { dgInt32 index = i * stride; dgBigVector& vertex = points[i]; vertex = dgBigVector (vertexCloud[index], vertexCloud[index + 1], vertexCloud[index + 2], vertexCloud[index + 3]); _ASSERTE (dgCheckVector(vertex)); points[i].m_index = 0; } } else { for (dgInt32 i = 0; i < count; i ++) { dgInt32 index = i * stride; dgBigVector& vertex = points[i]; vertex = dgBigVector (vertexCloud[index], vertexCloud[index + 1], vertexCloud[index + 2], dgFloat64 (0.0f)); _ASSERTE (dgCheckVector(vertex)); points[i].m_index = 0; } } dgSort(points, count, ConvexCompareVertex); dgInt32 indexCount = 0; for (int i = 1; i < count; i ++) { for (; i < count; i ++) { if (ConvexCompareVertex (&points[indexCount], &points[i], NULL)) { indexCount ++; points[indexCount] = points[i]; break; } } } count = indexCount + 1; if (count < 4) { m_count = 0; return count; } dgAABBPointTree3d* tree = BuildTree (NULL, points, count, 0, (dgInt8**) &memoryPool, maxMemSize); dgBigVector boxSize (tree->m_box[1] - tree->m_box[0]); m_diag = dgFloat32 (sqrt (boxSize % boxSize)); dgStack<dgBigVector> normalArrayPool (256); dgBigVector* const normalArray = &normalArrayPool[0]; dgInt32 normalCount = BuildNormalList (&normalArray[0]); dgInt32 index = SupportVertex (&tree, points, normalArray[0]); m_points[0] = points[index]; points[index].m_index = 1; bool validTetrahedrum = false; dgBigVector e1 (dgFloat64 (0.0f), dgFloat64 (0.0f), dgFloat64 (0.0f), dgFloat64 (0.0f)) ; for (dgInt32 i = 1; i < normalCount; i ++) { dgInt32 index = SupportVertex (&tree, points, normalArray[i]); _ASSERTE (index >= 0); e1 = points[index] - m_points[0]; dgFloat64 error2 = e1 % e1; if (error2 > (dgFloat32 (1.0e-4f) * m_diag * m_diag)) { m_points[1] = points[index]; points[index].m_index = 1; validTetrahedrum = true; break; } } if (!validTetrahedrum) { m_count = 0; _ASSERTE (0); return count; } validTetrahedrum = false; dgBigVector e2(dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f));; dgBigVector normal (dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f)); for (dgInt32 i = 2; i < normalCount; i ++) { dgInt32 index = SupportVertex (&tree, points, normalArray[i]); _ASSERTE (index >= 0); e2 = points[index] - m_points[0]; normal = e1 * e2; dgFloat64 error2 = sqrt (normal % normal); if (error2 > (dgFloat32 (1.0e-4f) * m_diag * m_diag)) { m_points[2] = points[index]; points[index].m_index = 1; validTetrahedrum = true; break; } } if (!validTetrahedrum) { m_count = 0; _ASSERTE (0); return count; } // find the largest possible tetrahedron validTetrahedrum = false; dgBigVector e3(dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f)); index = SupportVertex (&tree, points, normal); e3 = points[index] - m_points[0]; dgFloat64 error2 = normal % e3; if (fabs (error2) > (dgFloat64 (1.0e-6f) * m_diag * m_diag)) { // we found a valid tetrahedra, about and start build the hull by adding the rest of the points m_points[3] = points[index]; points[index].m_index = 1; validTetrahedrum = true; } if (!validTetrahedrum) { dgVector n (normal.Scale(dgFloat64 (-1.0f))); dgInt32 index = SupportVertex (&tree, points, n); e3 = points[index] - m_points[0]; dgFloat64 error2 = normal % e3; if (fabs (error2) > (dgFloat64 (1.0e-6f) * m_diag * m_diag)) { // we found a valid tetrahedra, about and start build the hull by adding the rest of the points m_points[3] = points[index]; points[index].m_index = 1; validTetrahedrum = true; } } if (!validTetrahedrum) { for (dgInt32 i = 3; i < normalCount; i ++) { dgInt32 index = SupportVertex (&tree, points, normalArray[i]); _ASSERTE (index >= 0); //make sure the volume of the fist tetrahedral is no negative e3 = points[index] - m_points[0]; dgFloat64 error2 = normal % e3; if (fabs (error2) > (dgFloat64 (1.0e-6f) * m_diag * m_diag)) { // we found a valid tetrahedra, about and start build the hull by adding the rest of the points m_points[3] = points[index]; points[index].m_index = 1; validTetrahedrum = true; break; } } } if (!validTetrahedrum) { // the points do not form a convex hull m_count = 0; //_ASSERTE (0); return count; } m_count = 4; dgFloat64 volume = TetrahedrumVolume (m_points[0], m_points[1], m_points[2], m_points[3]); if (volume > dgFloat64 (0.0f)) { Swap(m_points[2], m_points[3]); } _ASSERTE (TetrahedrumVolume(m_points[0], m_points[1], m_points[2], m_points[3]) < dgFloat64(0.0f)); return count; } dgFloat64 dgConvexHull3d::TetrahedrumVolume (const dgBigVector& p0, const dgBigVector& p1, const dgBigVector& p2, const dgBigVector& p3) const { dgBigVector p1p0 (p1 - p0); dgBigVector p2p0 (p2 - p0); dgBigVector p3p0 (p3 - p0); return (p1p0 * p2p0) % p3p0; } void dgConvexHull3d::TessellateTriangle (dgInt32 level, const dgVector& p0, const dgVector& p1, const dgVector& p2, dgInt32& count, dgBigVector* const ouput, dgInt32& start) const { if (level) { _ASSERTE (dgAbsf (p0 % p0 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f)); _ASSERTE (dgAbsf (p1 % p1 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f)); _ASSERTE (dgAbsf (p2 % p2 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f)); dgVector p01 (p0 + p1); dgVector p12 (p1 + p2); dgVector p20 (p2 + p0); p01 = p01.Scale (dgFloat32 (1.0f) / dgSqrt(p01 % p01)); p12 = p12.Scale (dgFloat32 (1.0f) / dgSqrt(p12 % p12)); p20 = p20.Scale (dgFloat32 (1.0f) / dgSqrt(p20 % p20)); _ASSERTE (dgAbsf (p01 % p01 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f)); _ASSERTE (dgAbsf (p12 % p12 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f)); _ASSERTE (dgAbsf (p20 % p20 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f)); TessellateTriangle (level - 1, p0, p01, p20, count, ouput, start); TessellateTriangle (level - 1, p1, p12, p01, count, ouput, start); TessellateTriangle (level - 1, p2, p20, p12, count, ouput, start); TessellateTriangle (level - 1, p01, p12, p20, count, ouput, start); } else { dgBigPlane n (p0, p1, p2); n = n.Scale (dgFloat64(1.0f) / sqrt (n % n)); n.m_w = dgFloat64(0.0f); ouput[start] = n; start += 8; count ++; } } dgInt32 dgConvexHull3d::SupportVertex (dgAABBPointTree3d** const treePointer, const dgHullVertex* const points, const dgBigVector& dir) const { /* dgFloat64 dist = dgFloat32 (-1.0e10f); dgInt32 index = -1; for (dgInt32 i = 0; i < count; i ++) { //dgFloat64 dist1 = dir.DotProduct4 (points[i]); dgFloat64 dist1 = dir % points[i]; if (dist1 > dist) { dist = dist1; index = i; } } _ASSERTE (index != -1); return index; */ #define DG_STACK_DEPTH_3D 64 dgFloat64 aabbProjection[DG_STACK_DEPTH_3D]; const dgAABBPointTree3d *stackPool[DG_STACK_DEPTH_3D]; dgInt32 index = -1; dgInt32 stack = 1; stackPool[0] = *treePointer; aabbProjection[0] = dgFloat32 (1.0e20f); dgFloat64 maxProj = dgFloat64 (-1.0e20f); dgInt32 ix = (dir[0] > dgFloat64 (0.0f)) ? 1 : 0; dgInt32 iy = (dir[1] > dgFloat64 (0.0f)) ? 1 : 0; dgInt32 iz = (dir[2] > dgFloat64 (0.0f)) ? 1 : 0; while (stack) { stack--; dgFloat64 boxSupportValue = aabbProjection[stack]; if (boxSupportValue > maxProj) { const dgAABBPointTree3d* const me = stackPool[stack]; if (me->m_left && me->m_right) { dgBigVector leftSupportPoint (me->m_left->m_box[ix].m_x, me->m_left->m_box[iy].m_y, me->m_left->m_box[iz].m_z, dgFloat32 (0.0)); dgFloat64 leftSupportDist = leftSupportPoint % dir; dgBigVector rightSupportPoint (me->m_right->m_box[ix].m_x, me->m_right->m_box[iy].m_y, me->m_right->m_box[iz].m_z, dgFloat32 (0.0)); dgFloat64 rightSupportDist = rightSupportPoint % dir; if (rightSupportDist >= leftSupportDist) { aabbProjection[stack] = leftSupportDist; stackPool[stack] = me->m_left; stack++; _ASSERTE (stack < DG_STACK_DEPTH_3D); aabbProjection[stack] = rightSupportDist; stackPool[stack] = me->m_right; stack++; _ASSERTE (stack < DG_STACK_DEPTH_3D); } else { aabbProjection[stack] = rightSupportDist; stackPool[stack] = me->m_right; stack++; _ASSERTE (stack < DG_STACK_DEPTH_3D); aabbProjection[stack] = leftSupportDist; stackPool[stack] = me->m_left; stack++; _ASSERTE (stack < DG_STACK_DEPTH_3D); } } else { dgAABBPointTree3dClump* const clump = (dgAABBPointTree3dClump*) me; for (dgInt32 i = 0; i < clump->m_count; i ++) { const dgHullVertex& p = points[clump->m_indices[i]]; _ASSERTE (p.m_x >= clump->m_box[0].m_x); _ASSERTE (p.m_x <= clump->m_box[1].m_x); _ASSERTE (p.m_y >= clump->m_box[0].m_y); _ASSERTE (p.m_y <= clump->m_box[1].m_y); _ASSERTE (p.m_z >= clump->m_box[0].m_z); _ASSERTE (p.m_z <= clump->m_box[1].m_z); if (!p.m_index) { dgFloat64 dist = p % dir; if (dist > maxProj) { maxProj = dist; index = clump->m_indices[i]; } } else { clump->m_indices[i] = clump->m_indices[clump->m_count - 1]; clump->m_count = clump->m_count - 1; i --; } } if (clump->m_count == 0) { dgAABBPointTree3d* const parent = clump->m_parent; if (parent) { dgAABBPointTree3d* const sibling = (parent->m_left != clump) ? parent->m_left : parent->m_right; _ASSERTE (sibling != clump); dgAABBPointTree3d* const grandParent = parent->m_parent; if (grandParent) { sibling->m_parent = grandParent; if (grandParent->m_right == parent) { grandParent->m_right = sibling; } else { grandParent->m_left = sibling; } } else { sibling->m_parent = NULL; *treePointer = sibling; } } } } } } _ASSERTE (index != -1); return index; } dgInt32 dgConvexHull3d::BuildNormalList (dgBigVector* const normalArray) const { dgVector p0 ( dgFloat32 (1.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f)); dgVector p1 (-dgFloat32 (1.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f)); dgVector p2 ( dgFloat32 (0.0f), dgFloat32 (1.0f), dgFloat32 (0.0f), dgFloat32 (0.0f)); dgVector p3 ( dgFloat32 (0.0f),-dgFloat32 (1.0f), dgFloat32 (0.0f), dgFloat32 (0.0f)); dgVector p4 ( dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (1.0f), dgFloat32 (0.0f)); dgVector p5 ( dgFloat32 (0.0f), dgFloat32 (0.0f),-dgFloat32 (1.0f), dgFloat32 (0.0f)); dgInt32 count = 0; dgInt32 subdivitions = 1; dgInt32 start = 0; TessellateTriangle (subdivitions, p4, p0, p2, count, normalArray, start); start = 1; TessellateTriangle (subdivitions, p5, p3, p1, count, normalArray, start); start = 2; TessellateTriangle (subdivitions, p5, p1, p2, count, normalArray, start); start = 3; TessellateTriangle (subdivitions, p4, p3, p0, count, normalArray, start); start = 4; TessellateTriangle (subdivitions, p4, p2, p1, count, normalArray, start); start = 5; TessellateTriangle (subdivitions, p5, p0, p3, count, normalArray, start); start = 6; TessellateTriangle (subdivitions, p5, p2, p0, count, normalArray, start); start = 7; TessellateTriangle (subdivitions, p4, p1, p3, count, normalArray, start); return count; } dgConvexHull3d::dgListNode* dgConvexHull3d::AddFace (dgInt32 i0, dgInt32 i1, dgInt32 i2) { dgListNode* const node = Append(); dgConvexHull3DFace& face = node->GetInfo(); face.m_index[0] = i0; face.m_index[1] = i1; face.m_index[2] = i2; return node; } void dgConvexHull3d::DeleteFace (dgListNode* const node) { Remove (node); } bool dgConvexHull3d::Sanity() const { /* for (dgListNode* node = GetFirst(); node; node = node->GetNext()) { dgConvexHull3DFace* const face = &node->GetInfo(); for (dgInt32 i = 0; i < 3; i ++) { dgListNode* const twinNode = face->m_twin[i]; if (!twinNode) { return false; } dgInt32 count = 0; dgListNode* me = NULL; dgConvexHull3DFace* const twinFace = &twinNode->GetInfo(); for (dgInt32 j = 0; j < 3; j ++) { if (twinFace->m_twin[j] == node) { count ++; me = twinFace->m_twin[j]; } } if (count != 1) { return false; } if (me != node) { return false; } } } */ return true; } void dgConvexHull3d::CalculateConvexHull (dgAABBPointTree3d* vertexTree, dgHullVertex* const points, dgInt32 count, dgFloat64 distTol, dgInt32 maxVertexCount) { distTol = fabs (distTol) * m_diag; dgListNode* const f0Node = AddFace (0, 1, 2); dgListNode* const f1Node = AddFace (0, 2, 3); dgListNode* const f2Node = AddFace (2, 1, 3); dgListNode* const f3Node = AddFace (1, 0, 3); dgConvexHull3DFace* const f0 = &f0Node->GetInfo(); dgConvexHull3DFace* const f1 = &f1Node->GetInfo(); dgConvexHull3DFace* const f2 = &f2Node->GetInfo(); dgConvexHull3DFace* const f3 = &f3Node->GetInfo(); f0->m_twin[0] = (dgList<dgConvexHull3DFace>::dgListNode*)f3Node; f0->m_twin[1] = (dgList<dgConvexHull3DFace>::dgListNode*)f2Node; f0->m_twin[2] = (dgList<dgConvexHull3DFace>::dgListNode*)f1Node; f1->m_twin[0] = (dgList<dgConvexHull3DFace>::dgListNode*)f0Node; f1->m_twin[1] = (dgList<dgConvexHull3DFace>::dgListNode*)f2Node; f1->m_twin[2] = (dgList<dgConvexHull3DFace>::dgListNode*)f3Node; f2->m_twin[0] = (dgList<dgConvexHull3DFace>::dgListNode*)f0Node; f2->m_twin[1] = (dgList<dgConvexHull3DFace>::dgListNode*)f3Node; f2->m_twin[2] = (dgList<dgConvexHull3DFace>::dgListNode*)f1Node; f3->m_twin[0] = (dgList<dgConvexHull3DFace>::dgListNode*)f0Node; f3->m_twin[1] = (dgList<dgConvexHull3DFace>::dgListNode*)f1Node; f3->m_twin[2] = (dgList<dgConvexHull3DFace>::dgListNode*)f2Node; dgList<dgListNode*> boundaryFaces(GetAllocator()); boundaryFaces.Append(f0Node); boundaryFaces.Append(f1Node); boundaryFaces.Append(f2Node); boundaryFaces.Append(f3Node); dgStack<dgListNode*> stackPool(1024 + m_count); dgStack<dgListNode*> coneListPool(1024 + m_count); dgStack<dgListNode*> deleteListPool(1024 + m_count); dgListNode** const stack = &stackPool[0]; dgListNode** const coneList = &stackPool[0]; dgListNode** const deleteList = &deleteListPool[0]; count -= 4; maxVertexCount -= 4; dgInt32 currentIndex = 4; while (boundaryFaces.GetCount() && count && (maxVertexCount > 0)) { dgListNode* const faceNode = boundaryFaces.GetFirst()->GetInfo(); dgConvexHull3DFace* const face = &faceNode->GetInfo(); dgBigPlane planeEquation (face->GetPlaneEquation (&m_points[0])); dgInt32 index = SupportVertex (&vertexTree, points, planeEquation); const dgBigVector& p = points[index]; dgFloat64 dist = planeEquation.Evalue(p); if ((dist >= distTol) && (face->Evalue(&m_points[0], p) > dgFloat64(0.0f))) { _ASSERTE (Sanity()); _ASSERTE (faceNode); stack[0] = faceNode; dgInt32 stackIndex = 1; dgInt32 deletedCount = 0; while (stackIndex) { stackIndex --; dgListNode* const node = stack[stackIndex]; dgConvexHull3DFace* const face = &node->GetInfo(); if (!face->m_mark && (face->Evalue(&m_points[0], p) > dgFloat64(0.0f))) { #ifdef _DEBUG for (dgInt32 i = 0; i < deletedCount; i ++) { _ASSERTE (deleteList[i] != node); } #endif deleteList[deletedCount] = node; deletedCount ++; _ASSERTE (deletedCount < dgInt32 (deleteListPool.GetElementsCount())); face->m_mark = 1; for (dgInt32 i = 0; i < 3; i ++) { dgListNode* const twinNode = (dgListNode*)face->m_twin[i]; _ASSERTE (twinNode); dgConvexHull3DFace* const twinFace = &twinNode->GetInfo(); if (!twinFace->m_mark) { stack[stackIndex] = twinNode; stackIndex ++; _ASSERTE (stackIndex < dgInt32 (stackPool.GetElementsCount())); } } } } // Swap (hullVertexArray[index], hullVertexArray[currentIndex]); m_points[currentIndex] = points[index]; points[index].m_index = 1; dgInt32 newCount = 0; for (dgInt32 i = 0; i < deletedCount; i ++) { dgListNode* const node = deleteList[i]; dgConvexHull3DFace* const face = &node->GetInfo(); _ASSERTE (face->m_mark == 1); for (dgInt32 j0 = 0; j0 < 3; j0 ++) { dgListNode* const twinNode = face->m_twin[j0]; dgConvexHull3DFace* const twinFace = &twinNode->GetInfo(); if (!twinFace->m_mark) { dgInt32 j1 = (j0 == 2) ? 0 : j0 + 1; dgListNode* const newNode = AddFace (currentIndex, face->m_index[j0], face->m_index[j1]); boundaryFaces.Addtop(newNode); dgConvexHull3DFace* const newFace = &newNode->GetInfo(); newFace->m_twin[1] = twinNode; for (dgInt32 k = 0; k < 3; k ++) { if (twinFace->m_twin[k] == node) { twinFace->m_twin[k] = newNode; } } coneList[newCount] = newNode; newCount ++; _ASSERTE (newCount < dgInt32 (coneListPool.GetElementsCount())); } } } for (dgInt32 i = 0; i < newCount - 1; i ++) { dgListNode* const nodeA = coneList[i]; dgConvexHull3DFace* const faceA = &nodeA->GetInfo(); _ASSERTE (faceA->m_mark == 0); for (dgInt32 j = i + 1; j < newCount; j ++) { dgListNode* const nodeB = coneList[j]; dgConvexHull3DFace* const faceB = &nodeB->GetInfo(); _ASSERTE (faceB->m_mark == 0); if (faceA->m_index[2] == faceB->m_index[1]) { faceA->m_twin[2] = nodeB; faceB->m_twin[0] = nodeA; break; } } for (dgInt32 j = i + 1; j < newCount; j ++) { dgListNode* const nodeB = coneList[j]; dgConvexHull3DFace* const faceB = &nodeB->GetInfo(); _ASSERTE (faceB->m_mark == 0); if (faceA->m_index[1] == faceB->m_index[2]) { faceA->m_twin[0] = nodeB; faceB->m_twin[2] = nodeA; break; } } } for (dgInt32 i = 0; i < deletedCount; i ++) { dgListNode* const node = deleteList[i]; boundaryFaces.Remove (node); DeleteFace (node); } maxVertexCount --; currentIndex ++; count --; } else { boundaryFaces.Remove (faceNode); } } m_count = currentIndex; } dgFloat64 dgConvexHull3d::RayCast (const dgBigVector& localP0, const dgBigVector& localP1) const { dgFloat64 interset = dgFloat32 (1.2f); dgFloat64 tE = dgFloat64 (0.0f); //for the maximum entering segment parameter; dgFloat64 tL = dgFloat64 (1.0f); //for the minimum leaving segment parameter; dgBigVector dS (localP1 - localP0); // is the segment direction vector; dgInt32 hasHit = 0; for (dgListNode* node = GetFirst(); node; node = node->GetNext()) { const dgConvexHull3DFace* const face = &node->GetInfo(); dgInt32 i0 = face->m_index[0]; dgInt32 i1 = face->m_index[1]; dgInt32 i2 = face->m_index[2]; const dgBigVector& p0 = m_points[i0]; dgBigVector normal ((m_points[i1] - p0) * (m_points[i2] - p0)); dgFloat64 N = -((localP0 - p0) % normal); dgFloat64 D = dS % normal; if (fabs(D) < dgFloat64 (1.0e-12f)) { // if (N < dgFloat64 (0.0f)) { return dgFloat64 (1.2f); } else { continue; } } dgFloat64 t = N / D; if (D < dgFloat64 (0.0f)) { if (t > tE) { tE = t; hasHit = 1; // hitNormal = normal; } if (tE > tL) { return dgFloat64 (1.2f); } } else { _ASSERTE (D >= dgFloat64 (0.0f)); tL = GetMin (tL, t); if (tL < tE) { return dgFloat64 (1.2f); } } } if (hasHit) { interset = tE; } return interset; }
[ "[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692" ]
[ [ [ 1, 907 ] ] ]
a65de262c4d6e10dc5d2a3e69dbbcbaa6ee51bd2
279b68f31b11224c18bfe7a0c8b8086f84c6afba
/playground/shelta/obsolete/0.0.1-DEV-02/dbconnection.cpp
5bf178861bdc747d631e4e7912bd62d742711597
[]
no_license
bogus/findik
83b7b44b36b42db68c2b536361541ee6175bb791
2258b3b3cc58711375fe05221588d5a068da5ea8
refs/heads/master
2020-12-24T13:36:19.550337
2009-08-16T21:46:57
2009-08-16T21:46:57
32,120,100
0
0
null
null
null
null
UTF-8
C++
false
false
1,230
cpp
#include "dbconnection.hpp" #ifndef FINDIK_DBCONNECTION_CPP #define FINDIK_DBCONNECTION_CPP namespace findik { template <class T> dbconnection<T>::dbconnection(T * connection) : lock_(false), connection_(connection) { } template <class T> dbconnection<T>::~dbconnection(void) { std::map<unsigned int, void *>::iterator it; for (it = dbc_objects.begin(); it != dbc_objects.end(); it++) delete (*it).second; delete connection_; } template <class T> void dbconnection<T>::lock() { lock_ = true; } template <class T> void dbconnection<T>::unlock() { lock_ = false; } template <class T> bool dbconnection<T>::is_locked() { return _lock; } template <class T> T * dbconnection<T>::connection() { return connection_; } template <class T> bool dbconnection<T>::try_lock() { if (lock_ == true) return false; else { lock_ = true; return true; } } template <class T> void * dbconnection<T>::get_object(unsigned int key) { return dbc_objects[key]; } template <class T> void dbconnection<T>::set_object(unsigned int key, void *object) { dbc_objects[key] = object; } } #endif
[ "shelta@d40773b4-ada0-11de-b0a2-13e92fe56a31" ]
[ [ [ 1, 76 ] ] ]
f18e7caf169e94b968e1ee5d9d8e5ad0cbbbe710
5e72c94a4ea92b1037217e31a66e9bfee67f71dd
/old/src/ThroughputDetail.cpp
6c1699b4570804aeb1ab5b32056c891e417ab960
[]
no_license
stein1/bbk
1070d2c145e43af02a6df14b6d06d9e8ed85fc8a
2380fc7a2f5bcc9cb2b54f61e38411468e1a1aa8
refs/heads/master
2021-01-17T23:57:37.689787
2011-05-04T14:50:01
2011-05-04T14:50:01
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,204
cpp
#include "ThroughputDetail.h" #include "Result.h" #include "ResultLog.h" #include "TestMarshall.h" enum { wxID_DIALOG_THROUGHPUT_DETAIL = wxID_HIGHEST }; ThroughputDetail::ThroughputDetail(wxWindow *parent, int row) :TestDetailDialog( parent, wxID_DIALOG_THROUGHPUT_DETAIL, wxT("Detaljer för Genomströmning"), wxDefaultPosition, wxSize(700,400), wxDEFAULT_DIALOG_STYLE ) { m_List = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxSize( 700, 400 ), wxLC_REPORT | wxLC_SINGLE_SEL ); m_List->InsertColumn(0, wxT("Typ"), wxLIST_FORMAT_LEFT, 130); m_List->InsertColumn(1, wxT("Adress"), wxLIST_FORMAT_LEFT, 300); m_List->InsertColumn(2, wxT("Genomströmning"), wxLIST_FORMAT_LEFT, 200); m_SizerMain->Add( m_List, wxGBPosition( 0, 0 ), wxDefaultSpan, wxEXPAND ); this->SetSizer( m_SizerMain ); RefreshList( row ); } ThroughputDetail::~ThroughputDetail(void) { } void ThroughputDetail::RefreshList(int irow) { Result *result = m_rl->GetResults( wxString( wxT("throughput") ) ); StringValueList *row = result->GetRow( irow ); // TPTEST Downstream wxStringTokenizer tkzD_TPVals( *row->Item(5)->GetData(), wxT("|")); while ( tkzD_TPVals.HasMoreTokens() ) { wxString host = tkzD_TPVals.GetNextToken(); wxString bps = tkzD_TPVals.GetNextToken(); // this should not happen if( host.Length() == 0 ) break; wxString strBPS; long lBPS; bps.ToLong( &lBPS ); if( lBPS > 0 ) { wxString str( FROMCSTR(Int32ToString(lBPS*8)) ); strBPS << str; } else { strBPS << wxT("-"); } wxListItem item; int id = m_List->GetItemCount(); item.SetMask(wxLIST_MASK_TEXT); item.SetId(id); item.SetText( wxString( wxT("TPTEST nedströms") ) ); m_List->InsertItem( item ); m_List->SetItem( id, 1, host ); m_List->SetItem( id, 2, strBPS ); } // TPTEST Upstream wxStringTokenizer tkzU_TPVals( *row->Item(6)->GetData(), wxT("|")); while ( tkzU_TPVals.HasMoreTokens() ) { wxString host = tkzU_TPVals.GetNextToken(); wxString bps = tkzU_TPVals.GetNextToken(); // this should not happen if( host.Length() == 0 ) break; wxString strBPS; long lBPS; bps.ToLong( &lBPS ); if( lBPS > 0 ) { wxString str( FROMCSTR(Int32ToString(lBPS*8)) ); strBPS << str; } else { strBPS << wxT("-"); } wxListItem item; int id = m_List->GetItemCount(); item.SetMask(wxLIST_MASK_TEXT); item.SetId(id); item.SetText( wxString( wxT("TPTEST uppströms")) ); m_List->InsertItem( item ); m_List->SetItem( id, 1, host ); m_List->SetItem( id, 2, strBPS ); } // HTTP wxStringTokenizer tkzHTTPVals( *row->Item(7)->GetData(), wxT("|")); while ( tkzHTTPVals.HasMoreTokens() ) { wxString host = tkzHTTPVals.GetNextToken(); wxString bps = tkzHTTPVals.GetNextToken(); // this should not happen if( host.Length() == 0 ) break; wxString strBPS; long lBPS; bps.ToLong( &lBPS ); if( lBPS > 0 ) { wxString str( FROMCSTR(Int32ToString(lBPS)) ); strBPS << str; } else { strBPS << wxT("-"); } wxListItem item; int id = m_List->GetItemCount(); item.SetMask(wxLIST_MASK_TEXT); item.SetId(id); item.SetText( wxString( wxT("HTTP") ) ); m_List->InsertItem( item ); m_List->SetItem( id, 1, host ); m_List->SetItem( id, 2, strBPS ); } // FTP wxStringTokenizer tkzFTPVals( *row->Item(8)->GetData(), wxT("|")); while ( tkzFTPVals.HasMoreTokens() ) { wxString host = tkzFTPVals.GetNextToken(); wxString bps = tkzFTPVals.GetNextToken(); // this should not happen if( host.Length() == 0 ) break; wxString strBPS; long lBPS; bps.ToLong( &lBPS ); if( lBPS > 0 ) { wxString str( FROMCSTR(Int32ToString(lBPS)) ); strBPS << str; } else { strBPS << wxT("-"); } wxListItem item; int id = m_List->GetItemCount(); item.SetMask(wxLIST_MASK_TEXT); item.SetId(id); item.SetText( wxString( wxT("FTP") ) ); m_List->InsertItem( item ); m_List->SetItem( id, 1, host ); m_List->SetItem( id, 2, strBPS ); } }
[ [ [ 1, 184 ] ] ]
1377a420cb2e1fdd1d1513aa67bf6b742a19b3ed
1741474383f0b3bc3518d7935a904f7903f40506
/A6/WhileStmt.cpp
5870e2da0868456f550701fe0b9fbc228726e77f
[]
no_license
osecki/drexelgroupwork
739df86f361e00528a6b03032985288d64b464aa
7c3bde253a50cab42c22d286c80cad72348b4fcf
refs/heads/master
2020-05-31T02:25:57.734312
2009-06-03T18:34:59
2009-06-03T18:34:59
32,121,248
0
0
null
null
null
null
UTF-8
C++
false
false
1,208
cpp
#include <map> #include "WhileStmt.h" #include "Expr.h" #include "Number.h" #include "Program.h" #include <sstream> #include <iostream> using namespace std; WhileStmt::WhileStmt(Expr *E, StmtList *S) { E_ = E; S_ = S; } void WhileStmt::translate(map<int, string> &constantValues, map<string, SymbolDetails> &symbolTable, vector<string> &ralProgram) const { // Handle first label and condition Program p; string newLabel1; stringstream outLabel1; outLabel1 << p.labelCounter; newLabel1 = "L" + outLabel1.str(); p.labelCounter++;; ralProgram.push_back(newLabel1 + ":"); string temp = E_->translate(constantValues, symbolTable, ralProgram); ralProgram.push_back("LDA " + temp); // Handle the first jumps string newLabel2; stringstream outLabel2; outLabel2 << p.labelCounter; newLabel2 = "L" + outLabel2.str(); p.labelCounter++; ralProgram.push_back("JMN " + newLabel2); ralProgram.push_back("JMZ " + newLabel2); // Handle the loop body S_->translate(constantValues, symbolTable, ralProgram); // Handle the second jumps ralProgram.push_back("JMP " + newLabel1); // Handle last label ralProgram.push_back(newLabel2 + ":"); }
[ "jordan.osecki@c6e0ff0a-2120-11de-a108-cd2f117ce590" ]
[ [ [ 1, 48 ] ] ]
f0c2b274242ad1b1c0fc8f3f66b1f77b86189e93
5c7482e141cfa929b35ef4b7272b0f97eafb3c56
/Application.cpp
ee76e3e15a32f9a9a8ae40fc63aa1e122127bc29
[]
no_license
NIA/D3DLighting
d58206e04245f9a2e15a3dfe1ee3355fe58e4d1a
cf8de02d9920809c1ee7a890d0849b80c9b9a3da
refs/heads/master
2021-01-20T11:06:42.146808
2009-11-16T03:47:47
2009-11-16T03:47:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,600
cpp
#include "Application.h" #include <time.h> const unsigned VECTORS_IN_MATRIX = sizeof(D3DXMATRIX)/sizeof(D3DXVECTOR4); namespace { const int WINDOW_SIZE = 600; const D3DCOLOR BACKGROUND_COLOR = D3DCOLOR_XRGB( 5, 5, 10 ); const bool INITIAL_WIREFRAME_STATE = false; const D3DCOLOR BLACK = D3DCOLOR_XRGB( 0, 0, 0 ); const float ROTATE_STEP = D3DX_PI/30.0f; //---------------- SHADER CONSTANTS --------------------------- // c0-c3 is the view matrix const unsigned SHADER_REG_VIEW_MX = 0; // c4-c7 is the first bone matrix for SKINNING // c8-c11 is the second bone matrix for SKINNING // c4 is final radius for MORPHING // c5 is MORPHING parameter const unsigned SHADER_REG_MODEL_DATA = 4; const unsigned SHADER_SPACE_MODEL_DATA = 8; // number of registers available for // c12 is directional light vector const unsigned SHADER_REG_DIRECTIONAL_VECTOR = 12; const D3DXVECTOR3 SHADER_VAL_DIRECTIONAL_VECTOR (0, 1.0f, 0.8f); // c13 is directional light color const unsigned SHADER_REG_DIRECTIONAL_COLOR = 13; const D3DCOLOR SHADER_VAL_DIRECTIONAL_COLOR = D3DCOLOR_XRGB(204, 178, 25); // c14 is diffuse coefficient const unsigned SHADER_REG_DIFFUSE_COEF = 14; const float SHADER_VAL_DIFFUSE_COEF = 0.7f; // c15 is ambient color const unsigned SHADER_REG_AMBIENT_COLOR = 15; const D3DCOLOR SHADER_VAL_AMBIENT_COLOR = D3DCOLOR_XRGB(13, 33, 13); // c16 is point light color const unsigned SHADER_REG_POINT_COLOR = 16; const D3DCOLOR SHADER_VAL_POINT_COLOR = D3DCOLOR_XRGB(25, 153, 153); // c17 is point light position const unsigned SHADER_REG_POINT_POSITION = 17; const D3DXVECTOR3 SHADER_VAL_POINT_POSITION (0.2f, -0.91f, -1.1f); // c18 are attenuation constants const unsigned SHADER_REG_ATTENUATION = 18; const D3DXVECTOR3 SHADER_VAL_ATTENUATION (1.0f, 0, 0.5f); // c19 is specular coefficient const unsigned SHADER_REG_SPECULAR_COEF = 19; const float SHADER_VAL_SPECULAR_COEF = 0.4f; // c20 is specular constant 'f' const unsigned SHADER_REG_SPECULAR_F = 20; const float SHADER_VAL_SPECULAR_F = 15.0f; // c21 is eye position const unsigned SHADER_REG_EYE = 21; // c22 is spot light position const unsigned SHADER_REG_SPOT_POSITION = 22; const D3DXVECTOR3 SHADER_VAL_SPOT_POSITION (1.5f, 1.5f, -1.3f); // c23 is spot light color const unsigned SHADER_REG_SPOT_COLOR = 23; const D3DCOLOR SHADER_VAL_SPOT_COLOR = D3DCOLOR_XRGB(255, 0, 180); // c24 is spot light direction const unsigned SHADER_REG_SPOT_VECTOR = 24; const D3DXVECTOR3 SHADER_VAL_SPOT_VECTOR (1.0f, 1.0f, -0.5f); D3DXVECTOR3 spot_vector(2.0f, -0.7f, -1.1f); // c25 is 1/(IN - OUT) const float SHADER_VAL_SPOT_INNER_ANGLE = D3DX_PI/16.0f; const float SHADER_VAL_SPOT_OUTER_ANGLE = D3DX_PI/12.0f; const unsigned SHADER_REG_SPOT_X_COEF = 25; // c26 is OUT/(IN - OUT) const unsigned SHADER_REG_SPOT_CONST_COEF = 26; // c27-c30 is position and rotation of model matrix const unsigned SHADER_REG_POS_AND_ROT_MX = 27; } Application::Application() : d3d(NULL), device(NULL), window(WINDOW_SIZE, WINDOW_SIZE), camera(3.2f, 1.5f, 0.0f), // Constants selected for better view of cylinder directional_light_enabled(true), point_light_enabled(true), spot_light_enabled(true), ambient_light_enabled(true) { try { init_device(); } // using catch(...) because every caught exception is rethrown catch(...) { release_interfaces(); throw; } } void Application::init_device() { d3d = Direct3DCreate9( D3D_SDK_VERSION ); if( d3d == NULL ) throw D3DInitError(); // Set up the structure used to create the device D3DPRESENT_PARAMETERS present_parameters; ZeroMemory( &present_parameters, sizeof( present_parameters ) ); present_parameters.Windowed = TRUE; present_parameters.SwapEffect = D3DSWAPEFFECT_DISCARD; present_parameters.BackBufferFormat = D3DFMT_UNKNOWN; present_parameters.EnableAutoDepthStencil = TRUE; present_parameters.AutoDepthStencilFormat = D3DFMT_D16; // Create the device if( FAILED( d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, window, D3DCREATE_HARDWARE_VERTEXPROCESSING, &present_parameters, &device ) ) ) throw D3DInitError(); check_state( device->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ) ); toggle_wireframe(); } void Application::render() { check_render( device->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, BACKGROUND_COLOR, 1.0f, 0 ) ); // Begin the scene check_render( device->BeginScene() ); // Setting constants float time = static_cast<float>( clock() )/static_cast<float>( CLOCKS_PER_SEC ); D3DXVECTOR3 directional_vector; D3DXVec3Normalize(&directional_vector, &SHADER_VAL_DIRECTIONAL_VECTOR); D3DXVECTOR3 spot_vector; D3DXVec3Normalize(&spot_vector, &SHADER_VAL_SPOT_VECTOR); D3DCOLOR ambient_color = ambient_light_enabled ? SHADER_VAL_AMBIENT_COLOR : BLACK; D3DCOLOR directional_color = directional_light_enabled ? SHADER_VAL_DIRECTIONAL_COLOR : BLACK; D3DCOLOR point_color = point_light_enabled ? SHADER_VAL_POINT_COLOR : BLACK; D3DCOLOR spot_color = spot_light_enabled ? SHADER_VAL_SPOT_COLOR : BLACK; float in_cos = cos(SHADER_VAL_SPOT_INNER_ANGLE); float out_cos = cos(SHADER_VAL_SPOT_OUTER_ANGLE); _ASSERT( in_cos - out_cos != 0.0f ); set_shader_matrix( SHADER_REG_VIEW_MX, camera.get_matrix()); set_shader_vector( SHADER_REG_DIRECTIONAL_VECTOR, directional_vector); set_shader_color( SHADER_REG_DIRECTIONAL_COLOR, directional_color); set_shader_float( SHADER_REG_DIFFUSE_COEF, SHADER_VAL_DIFFUSE_COEF); set_shader_color( SHADER_REG_AMBIENT_COLOR, ambient_color); set_shader_color( SHADER_REG_POINT_COLOR, point_color); set_shader_point( SHADER_REG_POINT_POSITION, SHADER_VAL_POINT_POSITION); set_shader_vector( SHADER_REG_ATTENUATION, SHADER_VAL_ATTENUATION); set_shader_float( SHADER_REG_SPECULAR_COEF, SHADER_VAL_SPECULAR_COEF); set_shader_float( SHADER_REG_SPECULAR_F, SHADER_VAL_SPECULAR_F); set_shader_point( SHADER_REG_EYE, camera.get_eye()); set_shader_point( SHADER_REG_SPOT_POSITION, SHADER_VAL_SPOT_POSITION); set_shader_color( SHADER_REG_SPOT_COLOR, spot_color); set_shader_vector( SHADER_REG_SPOT_VECTOR, spot_vector); set_shader_float( SHADER_REG_SPOT_X_COEF, 1/(in_cos - out_cos)); set_shader_float( SHADER_REG_SPOT_CONST_COEF, out_cos/(in_cos - out_cos)); D3DXVECTOR4 model_constants[SHADER_SPACE_MODEL_DATA]; unsigned constants_used; for ( Models::iterator iter = models.begin(); iter != models.end(); ++iter ) { // Set up ( (*iter)->get_shader() ).set(); // Setting constants (*iter)->set_time(time); constants_used = (*iter)->set_constants(model_constants, array_size(model_constants)); set_shader_const(SHADER_REG_MODEL_DATA, *model_constants, constants_used); set_shader_matrix( SHADER_REG_POS_AND_ROT_MX, (*iter)->get_rotation_and_position() ); // Draw (*iter)->draw(); } // End the scene check_render( device->EndScene() ); // Present the backbuffer contents to the display check_render( device->Present( NULL, NULL, NULL, NULL ) ); } IDirect3DDevice9 * Application::get_device() { return device; } void Application::add_model(Model &model) { models.push_back( &model ); } void Application::remove_model(Model &model) { models.remove( &model ); } void Application::rotate_models(float phi) { for ( Models::iterator iter = models.begin(); iter != models.end(); ++iter ) { (*iter)->rotate(phi); } } void Application::process_key(unsigned code) { switch( code ) { case VK_ESCAPE: PostQuitMessage( 0 ); break; case VK_UP: camera.move_up(); break; case VK_DOWN: camera.move_down(); break; case VK_PRIOR: case VK_ADD: case VK_OEM_PLUS: camera.move_nearer(); break; case VK_NEXT: case VK_SUBTRACT: case VK_OEM_MINUS: camera.move_farther(); break; case VK_LEFT: camera.move_clockwise(); break; case VK_RIGHT: camera.move_counterclockwise(); break; case 'A': rotate_models(-ROTATE_STEP); break; case 'D': rotate_models(ROTATE_STEP); break; case '1': directional_light_enabled = !directional_light_enabled; break; case '2': point_light_enabled = !point_light_enabled; break; case '3': spot_light_enabled = !spot_light_enabled; break; case '4': ambient_light_enabled = !ambient_light_enabled; break; } } void Application::run() { window.show(); window.update(); // Enter the message loop MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) { if( msg.message == WM_KEYDOWN ) { process_key( static_cast<unsigned>( msg.wParam ) ); } TranslateMessage( &msg ); DispatchMessage( &msg ); } else render(); } } void Application::toggle_wireframe() { static bool wireframe = !INITIAL_WIREFRAME_STATE; wireframe = !wireframe; if( wireframe ) { check_state( device->SetRenderState( D3DRS_FILLMODE, D3DFILL_WIREFRAME ) ); } else { check_state( device->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ) ); } } void Application::release_interfaces() { release_interface( d3d ); release_interface( device ); } Application::~Application() { release_interfaces(); }
[ [ [ 1, 296 ] ] ]
de307cfcc07640aba088c20229d12611f18390de
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestquery/inc/bctestquerycontainer.h
f6f592f01cb027d4c2b6d0593b207e0eccd803c7
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,606
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: container * */ #ifndef C_BCTESTQUERYCONTAINER_H #define C_BCTESTQUERYCONTAINER_H #include <coecntrl.h> class CBCTestQueryBaseCase; /** * container class */ class CBCTestQueryContainer: public CCoeControl { public: // constructor and destructor CBCTestQueryContainer(); virtual ~CBCTestQueryContainer(); void ConstructL( const TRect& aRect ); // new functions /** * Set component control, and this container will own the * component control. */ void SetControl( CCoeControl* aControl ); void ResetControl(); // from CCoeControl TInt CountComponentControls() const; CCoeControl* ComponentControl( TInt aIndex ) const; private: // from CCoeControl /** * From CCoeControl, Draw. * Fills the window's rectangle. * @param aRect Region of the control to be (re)drawn. */ void Draw( const TRect& aRect ) const; private: // data /** * Responsible for delete this */ CCoeControl* iControl; }; #endif // C_BCTESTQUERYCONTAINER_H
[ "none@none" ]
[ [ [ 1, 74 ] ] ]
6efc32b2e607d2c9457cd122a36d8dc111617c12
657ad21e12e78605b2a169b4bb55c83716a1729f
/src/org.capwin.gis.mapnik/AssemblyInfo.cpp
83e8c0e9f01fbb554e78d31d992ada38b820be8f
[]
no_license
gisprodk/mapnikdotnet
4e815d79731e3fbb08d7dfe1b228e404d97ed62e
7cff8b30333b1efc671f168d862821077c1b789b
refs/heads/master
2021-01-10T10:45:47.522667
2009-11-20T13:49:37
2009-11-20T13:49:37
46,118,429
0
0
null
null
null
null
UTF-8
C++
false
false
1,409
cpp
//Created by Univeristy of Maryland CapWIN Project 2009 #include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly:AssemblyTitleAttribute("orgcapwingismapnik")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("")]; [assembly:AssemblyProductAttribute("orgcapwingismapnik")]; [assembly:AssemblyCopyrightAttribute("Copyright (c) 2008")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly:AssemblyVersionAttribute("1.0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
[ [ [ 1, 41 ] ] ]
f53e687ec5e2a21e5324d7c94b7dbfe63b4c14b5
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/test/TestUtility/BufferCallerTest.cpp
8b416c4b3b23ed707f48d05a2c7f846d5dee7ffa
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
UTF-8
C++
false
false
778
cpp
#include "StdAfx.h" #include ".\buffercallertest.h" #include <boost\test\test_tools.hpp> using namespace boost::unit_test; class TestObject { public: TestObject() { cnt = 0; } void operator()() { cnt ++; } public: int cnt; }; void CallTest() { { // TEST 1 TestObject obj; BufferCaller<TestObject, 3> caller; for (int i = 0; i < 4; i++) { caller.Call(obj); } BOOST_ASSERT(2 == obj.cnt); } { // TEST 2 TestObject obj; BufferCaller<TestObject, 3> caller; for (int i = 0; i < 7; i++) { caller.Call(obj); } BOOST_ASSERT(3 == obj.cnt); } { // TEST 3 TestObject obj; BufferCaller<TestObject, 3> caller; for (int i = 0; i < 8; i++) { caller.Call(obj); } BOOST_ASSERT(3 == obj.cnt); } }
[ [ [ 1, 52 ] ] ]
1d47b3e6366f187d022934caa54af99ec09b36af
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Common/Script.cpp
144e5d9be410354c055d387a9cbc22c5d6ca7854
[]
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
31,998
cpp
/************************************************************* * * * 정수만이 가능한 Recursive descent parser * * 변수의 사용이 가능하고 함수를 호출할 수 있으며, * * goto 명령 등 Little C에서 제공하지 않는 기능을 제공한다. * * * * by Travis nam * * * *************************************************************/ #include "stdafx.h" // key word table struct Command { const char* command; Toke tok; }; // raiders.fix.2006.11.21 Command _table[] = { " " ,NONE_ , " " ,ARG , "int" ,VAR , "if" ,IF , "else" ,ELSE , "for" ,FOR , "do" ,DO , "while" ,WHILE , "break" ,BREAK , "switch" ,SWITCH , "answer" ,ANSWER , "Select" ,SELECT , "YesNo" ,YESNO , "case" ,CASE , "default" ,DEFAULT , "goto" ,GOTO , "return" ,RETURN , " " ,EOL , "#define" ,DEFINE , "#include",INCLUDE , "enum" ,ENUM , " " ,FINISHED, 0 ,END // 테이블의 끝을 표시 }; void CParser::SntxErr( LPCTSTR lpszHeader, int error) { throw "fuck"; } //////////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////////// map<string, int> CScript::m_defines; map<string, string> CScript::m_mapString; #if defined( __WORLDSERVER ) #if defined(__REMOVE_SCIRPT_060712) InterFuncType interFunc[] = { 0, 0, 0 }; #else extern InterFuncType interFunc[]; #endif #else InterFuncType interFunc[] = { 0, 0, 0 }; #endif CScript::CScript( BOOL bComma ) { process = INTERPRITER; m_pOldProg = 0; gVarIndex = 0; // index into global variable table funcIndex = 0; // index to into function table cmd = 0; m_bComma = bComma; #if !defined(__REMOVE_SCIRPT_060712) functos = 0; // index to top of function call stack lvartos = 0; // index into local variable stack labeltos = 0; // index into local label table retValue = 0; // function return value blocktos = 0; // answerCnt = 0; labelIndex =-1; retSign = 0; m_paTimer = NULL; ZeroMemory( m_anInternalVal, sizeof( m_anInternalVal ) ); #endif // !defined(__REMOVE_SCIRPT_060712) } CScript::~CScript() { Free(); } void CScript::LoadString( void ) { CScanner::GetToken(); while( tok != FINISHED ) { CString str = Token; if( str.Find( "IDS", 0 ) != 0 ) { Error( "LoadString: %s", m_strFileName ); GetToken(); continue; } GetLastFull(); std::string tmp = Token; int pos = tmp.find("뒤寧령령"); if(pos >= 0) { int a = 1; } bool bResult = m_mapString.insert( map<string, string>::value_type( (LPCTSTR)str, (LPCTSTR)Token ) ).second; if( !bResult ) Error( "string error: %s", str ); CScanner::GetToken(); } } void CScript::SntxErr( LPCTSTR lpszHeader, int error) { if( m_bErrorCheck == FALSE ) return; SetMark(); PutBack(); BYTE str[80]; int nLen = strlen(m_pProg); if(nLen > 79) nLen = 79; int i; for( i = 0; i < nLen; i++) str[i] = m_pProg[i]; str[i] = 0; CString string; if( lpszHeader ) string.Format( "FileName %s(%d) : %s : %s", m_strFileName, GetLineNum(), lpszHeader, str ); else string.Format( "FileName %s(%d) : %s", m_strFileName, GetLineNum(), str ); Error( string ); GoMark(); } int CScript::GetLineNum( LPTSTR lpProg ) { if( m_pOldProg == NULL ) return CScanner::GetLineNum(); return CScanner::GetLineNum( m_pOldProg ); } void CScript::GetLastFull() { CScanner::GetLastFull(); cmd = 0; if( *token == 0 && m_pOldProg ) { m_pProg = m_pOldProg; m_pOldProg = 0; GetLastFull(); } } int CScript::GetTkn( BOOL bComma ) { CScanner::GetToken( bComma ); cmd = 0; if( tokenType == DELIMITER ) { if( *token == '{' || *token == '}' ) // 블럭 처리 tokenType = BLOCK; } else if( tokenType == TEMP ) { if( tok = LookUp( token ) ) tokenType = KEYWORD; else tokenType = IDENTIFIER; } return tokenType; } int CScript::GetToken( BOOL bComma ) { GetTkn( bComma ); if( tokenType == IDENTIFIER ) { // 인터프리터 모드에서만 실행 if( IsInterpriterMode() ) { map<string, string>::iterator i = CScript::m_mapString.find( m_mszToken ); if( i != CScript::m_mapString.end() ) { tokenType = STRING; lstrcpy( m_mszToken, i->second.c_str() ); Token = m_mszToken; } else { int nValue = 0; if( LookupDefine( token, nValue ) ) { tokenType = NUMBER; wsprintf( m_mszToken, "%d", nValue ); Token = m_mszToken; } else { if( m_dwDef == 1 ) { // 프로퍼티 때문에. =을 -1로 사용하는 것은 잠정적으로 문제가 있음. if( *token != '\0' && *token != '=' && *token != '-' && *token != '+' ) { CString string; string.Format( "%s Not Found.", token ); SntxErr( string, 0 ); } } else if( m_dwDef == 2 ) { // 키워드도 아니고, 내장함수도 아니고, 유저함수도 아니라면 도대체 뭐지? if( !( tok = LookUp( token ) ) && InternalFunc( token ) == -1 && FindFunc( token ) == FALSE && *token != '#' ) { CString string; string.Format( "%s Not Found.", token ); SntxErr( string, 0 ); } } } } } } else if( tok == FINISHED && m_pOldProg ) { m_pProg = m_pOldProg; m_pOldProg = 0; return GetToken( bComma ); } return tokenType; } int CScript::GetToken_NoDef( BOOL bComma ) { GetTkn( bComma ); if( tok == FINISHED && m_pOldProg ) { m_pProg = m_pOldProg; m_pOldProg = 0; return GetTkn( bComma ); } return tokenType; } void CScript::SetMark() { CScanner::SetMark(); // Is in Define? if( m_pOldProg ) m_bMarkInDefine = TRUE; else m_bMarkInDefine = FALSE; } void CScript::GoMark() { // define if( m_bMarkInDefine == TRUE ) { if( m_pOldProg == NULL ) { m_pOldProg = m_pProg; } } else { if( m_pOldProg ) { m_pOldProg = NULL; } } CScanner::GoMark(); } void CScript::DeclGlobal() { GetToken(); // get type globalVars[gVarIndex].varType = tok; globalVars[gVarIndex].value = 0; // init to 0 do { // process comma-separated list GetToken(); // get name strcpy(globalVars[gVarIndex].varName, token); GetToken(); gVarIndex++; } while(*token==','); if(*token!=';') SntxErr( NULL, SEMI_EXPECTED); } void CScript::PreScan() { int brace = 0; funcIndex = 0; char* p = m_pProg; GetTkn(); if( !strcmp(token,"#") ) { process = COMPILER; } else { process = INTERPRITER; m_pProg = p; } do { if( brace ) return; // bypass code inside functions GetTkn(); if(tok==DEFINE) ExecDefine(); else if(tok==ENUM) { int eNum = 0; GetTkn(); // { do { GetTkn(); GetTkn(); // , or = if(*token=='=') { GetTkn(); // num eNum = atoi(token); GetTkn(); // , } if( m_defines.insert( make_pair( Token, eNum ) ).second == false ) TRACE("Enum %s dup.\n", Token); eNum++; } while(*token!='}'); GetTkn(); // ; } else if(tok==INCLUDE) { GetTkn(); CString strFile( token ); CHAR* pOldProg = m_pProg; CHAR* pOldBuf = m_pBuf; int nOldSize = m_nProgSize; m_pProg = m_pBuf = 0; CScanner::Load( strFile ); PreScan(); CScanner::Free(); m_nProgSize = nOldSize; m_pProg = pOldProg; m_pBuf = pOldBuf; tok = 0; } else if(tok==VAR) { // is global var PutBack(); DeclGlobal(); } else if(tokenType==IDENTIFIER) { CString strTemp( token ); GetTkn(); if(*token=='(') { // must be assume a function funcTable[funcIndex].loc = m_pProg; strcpy(funcTable[funcIndex++].name,strTemp); while(*m_pProg!=')') m_pProg++; m_pProg++; // m_pProg points to opening cyrly brace of function } else PutBack(); } else if(*token=='{') brace++; } while( tok != FINISHED ); m_pProg = p; } void CScript::ExecDefine() { CScanner::GetToken( FALSE ); string str = token; CScanner::GetToken( FALSE ); int n; if( tokenType == NUMBER ) n = atoi( token ); else if( tokenType == HEX ) sscanf( token, "%x", &n ); else if( tokenType == 0 ) { PutBack(); return; } else return; if( m_defines.insert( make_pair( str, n ) ).second == false ) TRACE("define %s dup\n", Token); } char CScript::LookUp(const char *s) { if(!process) // 인터프리터 { #ifdef __REMOVE_SCIRPT_060712 if( memcmp( s, "#define", 7 ) == 0 ) return DEFINE; #else for(int i=0; i<22; ++i) if(!strcmp(_table[i].command,s)) return cmd = _table[i].tok; #endif // __REMOVE_SCIRPT_060712 } else if(s[0]=='@') // 컴파일 return _table[atoi(&s[1])].tok; return 0; } int CScript::InternalFunc(char *s) { if(!process) // 인터프리터 { for(int i = 0; interFunc[i].p; i++) if(!strcmp(interFunc[i].name,s)) return i; } else // 컴파일 if(s[0]=='$') return atoi(&s[1]); return -1; } char *CScript::FindFunc(char *name) { int i; for(i = 0; i < funcIndex; i++) if(!strcmp(name, funcTable[i].name)) return funcTable[i].loc; return NULL; } void CScript::Free() { CScanner::Free(); process = INTERPRITER; m_pOldProg = 0; #if !defined(__REMOVE_SCIRPT_060712) functos = 0; // index to top of function call stack funcIndex = 0; // index to into function table gVarIndex = 0; // index into global variable table lvartos = 0; // index into local variable stack labeltos = 0; // index into local label table retValue = 0; // function return value blocktos = 0; // answerCnt = 0; labelIndex =-1; retSign = 0; #endif // !defined(__REMOVE_SCIRPT_060712) } BOOL CScript::Load( LPCTSTR lpszFileName, BOOL bMultiByte, int nProcess) { if( !CScanner::Load( lpszFileName, bMultiByte ) ) return 0; #if defined(__REMOVE_SCIRPT_060712) process = nProcess; #else if(nProcess == INTERPRITER) { process = nProcess; return TRUE; } Compile(); #endif return TRUE; } BOOL CScript::LookupDefine( LPCTSTR lpszString, int& rValue ) { map< string, int >::iterator it = m_defines.find( lpszString ); if( it != m_defines.end() ) { rValue = it->second; return TRUE; } else return FALSE; } // // remark // lpId라는 define의 내용이 숫자라면 숫자를 돌려준다. // // return // 그 Define에 Number를 돌려준다. 다른 경우 -1 // int CScript::GetDefineNum(LPCTSTR lpId) { int nValue; if(LookupDefine(lpId,nValue) == FALSE) return -1; return nValue; } // // XX_로 시작하는 것을 찾아준다. // void CScript::GetFindIdToArray(LPCTSTR lpStrDef,CStringArray* pStrArray) { string strValue; map<string, int>::iterator it; for( it = m_defines.begin(); it != m_defines.end(); ++it ) { strValue = it->first; if( strValue.find( lpStrDef ) == 0 ) // 인덱스 0에서 찾았으면 결과배열에 넣는다. pStrArray->Add( strValue.c_str() ); } } #if !defined(__REMOVE_SCIRPT_060712) void CScript::Write(LPSTR* cplProg,char* str) { while(*str) *((*cplProg)++) = *(str++); } void CScript::Compile() { int r = 0; char str[256]; LPSTR cplProg = new CHAR[m_nProgSize]; LPSTR pBakProg = cplProg; Write(&cplProg,"# "); SetInterpriterMode(); do { GetToken(); switch(tokenType) { case STRING: Write(&cplProg,"\""); Write(&cplProg,token); Write(&cplProg,"\""); break; case IDENTIFIER: // 인터널 펑션만 컴파일한다. if((r=IsFunc(token))!=-1) { str[0] = '$'; itoa(r,&str[1],10); Write(&cplProg,str); } else Write(&cplProg,token); break; case KEYWORD: switch(cmd) { case DEFINE: // define case INCLUDE: // include while(*m_pProg!='\r'&&*m_pProg!='\0') m_pProg++; break; case ENUM: // enum GetTkn(); // { do { GetTkn(); } while(*token!='}'); GetTkn(); // ; break; default: str[0] = '@'; itoa(cmd,&str[1],10); Write(&cplProg,str); break; } switch(cmd) { case ELSE: case DO: case VAR: case RETURN: case GOTO: case CASE: Write(&cplProg," "); break; } break; default: Write(&cplProg,token); break; } } while(tok!=FINISHED); CScanner::Free(); *cplProg = 0; cplProg++; m_pProg = new CHAR[(int)(cplProg-pBakProg)]; memcpy(m_pProg,pBakProg,(int)(cplProg-pBakProg)); safe_delete( pBakProg ); m_bMemFlag = 0; m_pBuf = m_pProg; SetCompilerMode(); } int CScript::IsFunc(char *str) { for(int i = 0; interFunc[i].p; i++) if(!strcmp(interFunc[i].name,str)) return i; return -1; // unknown command } #endif #if !defined(__REMOVE_SCIRPT_060712) void CParser::Compute(LPTSTR initProg,int *value) { SetProg(initProg); Compute(value); } void CParser::Compute(int *value) { GetToken(); } void CParser::EvalExp0(int *value) { EvalExp1(value); } void CParser::EvalExp1(int *value) { int partial_value; char op,op2; EvalExp2(value); op = *token; op2 = *(token+1); while(((op = *token) == '&' && (op2 = *(token+1)) == '&') || (op == '|' && op2 == '|')) { GetToken(); EvalExp2(&partial_value); switch(op) { case '&': *value = *value && partial_value; break; case '|': *value = *value || partial_value; break; } } } void CParser::EvalExp2(int *value) { int partial_value; char op; EvalExp3(value); op = m_nDoubleOps; if(op) { GetToken(); EvalExp3(&partial_value); switch(op) { // perform the relational operation case LT: *value = *value < partial_value; break; case LE: *value = *value <= partial_value; break; case GT: *value = *value > partial_value; break; case GE: *value = *value >= partial_value; break; case EQ: *value = *value == partial_value; break; case NE: *value = *value != partial_value; break; case NT: *value = !(partial_value); break; } } } void CParser::EvalExp3(int *value) { char op; int partial_value; EvalExp4(value); while((op = *token) == '+' || op == '-') { GetToken(); EvalExp4(&partial_value); switch(op) { // add or subtract case '-': *value = *value - partial_value; break; case '+': *value = *value + partial_value; break; } } } void CParser::EvalExp4(int *value) { char op; int partial_value; EvalExp5(value); while((op = *token) == '*' || op == '/' || op == '%') { GetToken(); EvalExp5(&partial_value); switch(op) { // mul, div, or modulus case '*': *value = *value * partial_value; break; case '/': *value = (*value) / partial_value; break; case '%': *value = (*value) % partial_value; break; } } } void CParser::EvalExp5(int *value) { char op; op = '\0'; if(*token=='+'||*token=='-') { op = *token; GetToken(); } EvalExp6(value); if(op) if(op=='-') *value = -(*value); } void CParser::EvalExp6(int *value) { if(*token=='(') { GetToken(); EvalExp0(value); // get subexpression if(*token!=')') SntxErr( NULL, PAREN_EXPECTED); GetToken(); } else atom(value); } void CParser::atom(int *value) { switch(tokenType) { case NUMBER: // is numeric constant *value = atoi(token); GetToken(); return; default: if(*token!=')') // Process empty expression SntxErr( NULL, SYNTAX); // syntax error } } BOOL CScript::Run() { m_dwDef = 2; m_pProg = m_pBuf; m_pOldProg = 0; functos = 0; funcIndex = 0; gVarIndex = 0; lvartos = 0; labeltos = 0; retValue = 0; blocktos = 0; answerCnt = 0; labelIndex =-1; retSign = 0; PreScan(); m_pProg = FindFunc("main"); m_pProg--; strcpy(token,"main"); Call(); m_anInternalVal[0] = retValue; return TRUE; } void CScript::SetIValue(int nVal,...) { va_list args; va_start( args, nVal ); int i = 0; while( nVal != -1 ) { m_anInternalVal[ i++ ] = nVal; nVal = va_arg( args, int ); } va_end( args ); } void CScript::Compute(int *value) { GetToken(); if(!*token) SntxErr( NULL, NO_EXP); else { EvalExp0(value); PutBack(); // return last token read to input stream } } void CScript::EvalExp0(int *value) { char temp[ID_LEN]; // holds name of val receiving the assignment int temp_tok; if(tokenType == IDENTIFIER) { if(IsVar(token)) { // if a var, see if assignment strcpy(temp,token); temp_tok = tokenType; GetToken(); char op; op = *token; if( ( op=='+' ||op=='-' || op=='|' || op=='&' ) && *m_pProg == '=' ) { GetToken(); GetToken(); EvalExp0(value); // get value to assign int *pnValue = GetVarPtr( temp ); if( pnValue ) { switch( op ) { case '+': *pnValue += *value; break; // += 처리 case '-': *pnValue -= *value; break; // -= 처리 case '*': *pnValue *= *value; break; // *= 처리 case '/': *pnValue /= *value; break; // /= 처리 case '|': *pnValue |= *value; break; // |= 처리 case '&': *pnValue &= *value; break; // &= 처리 } } } else if(*token=='=' && *(token+1)!='=') { // is an assignment GetToken(); EvalExp0(value); // get value to assign AssignVar(temp,*value); // assign the value return; } else { // not an assignment PutBack(); // restore original token strcpy(token,temp); tokenType = temp_tok; } } } EvalExp1(value); } void CScript::atom(int *value) { int i; switch(tokenType) { case IDENTIFIER: i = InternalFunc(token); if(i!=-1) { // Call "standard libray" function retValue = (*interFunc[i].p)(this); *value = retValue; } else if(FindFunc(token)) { // Call user-defined function Call(); *value = retValue; } else *value = FindVar(token); // fet var's value GetToken(); return; case NUMBER: // is numeric constant *value = atoi(token); GetToken(); return; case DELIMITER: // see if cahracter constant if(*token=='\'') { CHAR* pProg = (CHAR*)m_pProg; *value = *pProg; pProg++; if(*pProg!='\'') SntxErr( NULL, QUOTE_EXPECTED); pProg++; m_pProg = pProg; GetToken(); } return; default: if(*token!=')') // Process empty expression SntxErr( NULL, SYNTAX); // syntax error } } // // return value // 0 == block end ( { } ), one line end( ; ) // 1 == goto // 2 == break // 3 == return // int CScript::InterpBlock(int aaa) { int value,c,brk = 0; char block = 0; char tpTkn[64]; CHAR* p; if(aaa) { block = 1; blocktos++; } do { tokenType = GetToken(); // if interpreting single statement, return on first semicolon // see what kind of token is up if(tokenType==IDENTIFIER) { p = m_pProg; strcpy( tpTkn, token ); GetToken(); if(*token!=':') { strcpy(token,tpTkn); m_pProg = p; // not a keyword, so process expression PutBack(); // restore token to input stream // for further processing by Compute() Compute(&value); // process the expression GetToken(); if(*token!=';') SntxErr( NULL, SEMI_EXPECTED); } } else if(tokenType==BLOCK) { // If block delimiter if(*token=='{') { // is a block block = 1; // interpreting block, not statement blocktos++; } else { blocktos--; return 0; // is a }, so return } } else // is keyword switch(tok) { case VAR: // declare local variables PutBack(); DeclLocal(); break; case DEFINE: ExecDefine(); break; case RETURN: // return from function call FuncRet(); retSign = 1; break; case IF: // process an if statement ExecIf(); break; case ELSE: // process an else statement FindEob(); // find end of else block and continue execution break; case WHILE: // process a while loop ExecWhile(); break; case DO: // process a do-while loop ExecDo(); break; case FOR: ExecFor(); break; case BREAK: if( block ) blocktos--; return 2; case DEFAULT: case CASE: do GetToken(); while(*token!=':'); break; case SWITCH: ExecSwitch(); break; case GOTO: GetToken(); for(c = callStack[functos-1].label; c < labeltos; c++) if(!strcmp(labelTable[c].name,token)) { labelIndex = c; break; } break; case END: exit(0); } if( retSign ) { // retSign은 블럭으로 리커시브 된 상태를 계속 리턴하게 해준다. // 리커시브 상태의 서브 함수에서 return한다. 코드 3 if( blocktos-- != 1 ) return 3; // 모든 블럭의 재귀 호출이 리턴되면 retSign을 0으로 리셋한다. retSign = 0; return 0; } if( labelIndex!=-1 ) { if( !block ) return 1; if( labelTable[labelIndex].block < blocktos ) { blocktos--; return 1; } else { m_pProg = labelTable[labelIndex].loc; labelIndex = -1; } } } while( tok != FINISHED && block ); return 0; } void CScript::DeclLocal() { VarType i; GetToken(); // get type i.varType = tok; i.value = 0; // init to 0 do { // process comma-separated list GetToken(); // get var name strcpy(i.varName,token); LocalPush(i); GetToken(); } while(*token==','); if(*token!=';') SntxErr( NULL, SEMI_EXPECTED); } void CScript::FindLabel() { char block = 0; char* p = m_pProg; char temp[64]; m_dwDef = 0; do { GetToken(); if( tokenType == IDENTIFIER ) { strcpy( temp, token ); GetToken(); if( *token==':' ) { strcpy( labelTable[ labeltos ].name, temp ); labelTable[ labeltos ].loc = m_pProg; labelTable[ labeltos ].block = block; labeltos++; if( labeltos >= 45 ) { printf("label overflow"); } } } else if( tokenType == BLOCK ) { // If block delimiter if( *token == '{') block++; else block--; if( !block ) { m_pProg = p; return; } } } while(tok != FINISHED); m_pProg = p; m_dwDef = 2; } void CScript::Call() { char *loc; CHAR* temp; int lvartemp; FuncInfo fi; loc = FindFunc( token ); // find entry point of function if( loc == NULL ) SntxErr( NULL, FUNC_UNDEF ); // function not defined else { lvartemp = lvartos; // save local var stack index GetArgs(); // get function arguments temp = m_pProg; // save return location fi.var = lvartemp; fi.label = labeltos; fi.answer = answerCnt; fi.block = blocktos; retValue = TRUE; // 펑션의 디폴트 리턴값은 1이다. FuncPush(fi); // save local var stack index m_pProg = loc; // reset m_pProg to start of function GetParams(); // load the functuon's parameters with the values of the arguments FindLabel(); // find label and it's push label table blocktos = retSign = 0; InterpBlock(); // interpret the function m_pProg = temp; // reset the program pointer fi = FuncPop(); // reset the local var stack lvartemp = fi.var; labeltos = fi.label; answerCnt = fi.answer; lvartos = fi.var; blocktos = fi.block; } } void CScript::GetArgs() { int value, count, temp[NUM_PARAMS]; VarType i; count = 0; GetToken(); if( *token != '(' ) SntxErr( NULL, PAREN_EXPECTED); GetToken(); if( *token == ')' ) return; PutBack(); // process a comma-separated list of values do { Compute(&value); temp[count] = value; // save temporarily GetToken(); count++; } while(*token==','); // now, push on localVarStack in reverse order for(count--; count >= 0; count--) { i.value = temp[count]; i.varType = ARG; LocalPush(i); } } void CScript::GetParams() { if(!lvartos) GetToken(); else { VarType *p; int i = lvartos-1; do { // process comma-separated list of parameters GetToken(); p = &localVarStack[i]; if(*token!=')') { if(tok!=VAR) SntxErr( NULL, TYPE_EXPECTED); p->varType = tokenType; GetToken(); // link parameter name with argument already on local var stack strcpy(p->varName,token); GetToken(); i--; } else break; } while(*token==','); } if(*token!=')') SntxErr( NULL, PAREN_EXPECTED); } void CScript::FuncRet() { int value = 0; // get return valuem if any Compute(&value); retValue = value; } void CScript::LocalPush(VarType i) { if(lvartos > NUM_LOCAL_VARS) SntxErr( NULL, TOO_MANY_LVARS); localVarStack[lvartos] = i; lvartos++; } FuncInfo CScript::FuncPop() { functos--; if(functos < 0) SntxErr( NULL, RET_NOCALL); return callStack[functos]; } void CScript::FuncPush(FuncInfo fi) { if(functos > NUM_FUNC) SntxErr( NULL, NEST_FUNC); callStack[functos] = fi; functos++; } void CScript::AssignVar(char *varName, int value) { // first, see if it's a loca variable int i; for( i = callStack[functos-1].var; i < lvartos; i++) { if(!strcmp(localVarStack[i].varName,varName)) { localVarStack[i].value = value; return; } } // if not local, try global var table for(i = 0; i < gVarIndex; i++) if(!strcmp(globalVars[i].varName,varName)) { globalVars[i].value = value; return; } SntxErr( NULL, NOT_VAR); // variable not found } int* CScript::GetVarPtr(char *varName) { // first, see if it's a loca variable int i; for( i = callStack[functos-1].var; i < lvartos; i++) { if(!strcmp(localVarStack[i].varName,varName)) { return &localVarStack[i].value; } } // if not local, try global var table for(i = 0; i < gVarIndex; i++) { if(!strcmp(globalVars[i].varName,varName)) { return &globalVars[i].value; } } SntxErr( NULL, NOT_VAR); // variable not found return NULL; } int CScript::FindVar(char *s) { // first, see if it's a local variable int i; for( i = callStack[functos-1].var; i < lvartos; i++) if(!strcmp(localVarStack[i].varName,s)) return localVarStack[i].value; // otherwise, try global vars for(i = 0; i < gVarIndex; i++) if(!strcmp(globalVars[i].varName,s)) return globalVars[i].value; SntxErr( NULL, NOT_VAR); // vaiable not found return 0; } int CScript::IsVar(char *s) { // first, see if it's a local variable int i; for( i = callStack[functos-1].var; i < lvartos; i++) if(!strcmp(localVarStack[i].varName,s)) return 1; // otherwise, try global bars for(i = 0; i < gVarIndex; i++) if(!strcmp(globalVars[i].varName,s)) return 1; return 0; } // Find end of block // // { }! // { ; }! // ;! // ( ; ) ;! // ( ) { }! // { (;) }! // ! is end void CScript::ExecIf() { int cond; CHAR* begin; Compute(&cond); // get left expression if(cond) { // is true so process target of IF begin = m_pProg; switch(InterpBlock()) { case 2: m_pProg = begin; FindEob(); case 1: case 3: return; } } else { // otherwise skip around IF block and process the ELSE, if present GetToken(); if(*token!='{') { int flag = 0, iff = 0; for(;;) { if(flag && (!iff || (iff && tok!=ELSE))) break; if(tok==IF) { iff++; flag = 0; } else if(tok==ELSE) { iff--; flag = 0; } else { PutBack(); FindEob(); flag = 1; } GetToken(); } } else { PutBack(); FindEob(); // find start of next line GetToken(); } if( tok != ELSE ) { PutBack(); // restore token if no ELSE if present return; } begin = m_pProg; switch( InterpBlock() ) { case 2: m_pProg = begin; FindEob(); case 1: case 3: return; } } } void CScript::ExecWhile() { int cond; PutBack(); CHAR* temp = m_pProg; // save location of top of while loop GetToken(); Compute(&cond); // check the conditional expression if(cond) { CHAR* begin = m_pProg; switch( InterpBlock() ) { case 2: m_pProg = begin; FindEob(); case 1: case 3: return; } } else { // otherwise, skip around loop FindEob(); return; } m_pProg = temp; // loop back to top } void CScript::ExecDo() { int cond; PutBack(); CHAR* temp = m_pProg; // save location of top of do loop GetToken(); // get start of loop CHAR* begin = m_pProg; switch(InterpBlock()) { case 2: m_pProg = begin; FindEob(); FindEob(); // bypassed block and while case 1: case 3: return; } GetToken(); if(tok!=WHILE) SntxErr( NULL, WHILE_EXPECTED); Compute(&cond); // check the loop condition if( cond ) m_pProg = temp; // if true loop; otherwise, cotinue on } void CScript::ExecFor() { int cond; char *temp, *temp2; int brace; GetToken(); Compute(&cond); // initialization expression if(*token!=';') SntxErr( NULL, SEMI_EXPECTED); m_pProg++; // get past the ; temp = m_pProg; for(;;) { cond = 1; // 다음 Compute에서 비교대상이 없으면 (;;) cond = 1을 유지하여 무한루프를 돌게 한다. Compute(&cond); // check the condition if(*token!=';') SntxErr( NULL, SEMI_EXPECTED); m_pProg++; // get past the ; temp2 = m_pProg; // find the start of the for block brace = 1; while(brace) { GetToken(); if(*token=='(') brace++; if(*token==')') brace--; } if(cond) { char *begin = m_pProg; switch(InterpBlock()) { case 2: m_pProg = begin; FindEob(); case 1: case 3: return; } } else { // otherwise, skip around loop FindEob(); return; } m_pProg = temp2; Compute(&cond); // do the increment m_pProg = temp; // loop back to top } } void CScript::ExecSwitch() { int cond,cond2,block = 0; char *def = 0; char *begin = m_pProg; Compute(&cond); for(;;) { GetToken(); if(*token=='{') { if(block) { PutBack(); FindEob(); } else block = 1; } else if(*token=='}') { if(def) { m_pProg = def; if(InterpBlock(1) == 2) { m_pProg = begin; FindEob(); } } break; } else if(!def) { if(tok == CASE) { Compute(&cond2); if(cond2==cond) { GetToken(); // bypass ':' def = m_pProg; } } else if(tok == DEFAULT) { GetToken(); // bypass ':' def = m_pProg; } } } } void CScript::FindEob(void) { int brace = 0; for(;;) { GetToken(); if(*token==';'&&!brace) break; else if(*token=='{') brace++; else if(*token=='}') { if(!(--brace)) break; } else if(*token=='(') { int bra = 1; while(bra) { GetToken(); if(*token=='(') bra++; if(*token==')') bra--; } } } } #endif // __REMOVE_SCIRPT_060712
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278", "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 116 ], [ 125, 1511 ] ], [ [ 117, 124 ] ] ]
456241c333bc205505a6e44976a78cfa0dbf91d7
3187b0dd0d7a7b83b33c62357efa0092b3943110
/src/dlib/matrix/matrix_math_functions.h
2762599aae8d3291ccc15627b01a2d52ac46f489
[ "BSL-1.0" ]
permissive
exi/gravisim
8a4dad954f68960d42f1d7da14ff1ca7a20e92f2
361e70e40f58c9f5e2c2f574c9e7446751629807
refs/heads/master
2021-01-19T17:45:04.106839
2010-10-22T09:11:24
2010-10-22T09:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,583
h
// Copyright (C) 2006 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_MATRIx_MATH_FUNCTIONS #define DLIB_MATRIx_MATH_FUNCTIONS #include "matrix_utilities.h" #include "matrix.h" #include "../algs.h" #include <cmath> #include <complex> #include <limits> namespace dlib { // ---------------------------------------------------------------------------------------- #define DLIB_MATRIX_SIMPLE_STD_FUNCTION(name) template <typename EXP> \ struct op_##name : has_nondestructive_aliasing, preserves_dimensions<EXP> \ { \ typedef typename EXP::type type; \ template <typename M> \ static type apply ( const M& m, long r, long c) \ { return static_cast<type>(std::name(m(r,c))); } \ }; \ template < typename EXP > \ const matrix_exp<matrix_unary_exp<matrix_exp<EXP>,op_##name<EXP> > > name ( \ const matrix_exp<EXP>& m) \ { \ typedef matrix_unary_exp<matrix_exp<EXP>,op_##name<EXP> > exp; \ return matrix_exp<exp>(exp(m)); \ } // ---------------------------------------------------------------------------------------- DLIB_MATRIX_SIMPLE_STD_FUNCTION(abs) DLIB_MATRIX_SIMPLE_STD_FUNCTION(sqrt) DLIB_MATRIX_SIMPLE_STD_FUNCTION(log) DLIB_MATRIX_SIMPLE_STD_FUNCTION(log10) DLIB_MATRIX_SIMPLE_STD_FUNCTION(exp) DLIB_MATRIX_SIMPLE_STD_FUNCTION(conj) DLIB_MATRIX_SIMPLE_STD_FUNCTION(ceil) DLIB_MATRIX_SIMPLE_STD_FUNCTION(floor) DLIB_MATRIX_SIMPLE_STD_FUNCTION(sin) DLIB_MATRIX_SIMPLE_STD_FUNCTION(cos) DLIB_MATRIX_SIMPLE_STD_FUNCTION(tan) DLIB_MATRIX_SIMPLE_STD_FUNCTION(sinh) DLIB_MATRIX_SIMPLE_STD_FUNCTION(cosh) DLIB_MATRIX_SIMPLE_STD_FUNCTION(tanh) DLIB_MATRIX_SIMPLE_STD_FUNCTION(asin) DLIB_MATRIX_SIMPLE_STD_FUNCTION(acos) DLIB_MATRIX_SIMPLE_STD_FUNCTION(atan) // ---------------------------------------------------------------------------------------- template <typename EXP> struct op_sigmoid : has_nondestructive_aliasing, preserves_dimensions<EXP> { typedef typename EXP::type type; template <typename M> static type apply ( const M& m, long r, long c) { const double e = 2.718281828459045235360287471352; double temp = std::pow(e,-m(r,c)); return static_cast<type>(1.0/(1.0 + temp)); } }; template < typename EXP > const matrix_exp<matrix_unary_exp<matrix_exp<EXP>,op_sigmoid<EXP> > > sigmoid ( const matrix_exp<EXP>& m ) { typedef matrix_unary_exp<matrix_exp<EXP>,op_sigmoid<EXP> > exp; return matrix_exp<exp>(exp(m)); } // ---------------------------------------------------------------------------------------- template <typename EXP> struct op_round_zeros : has_nondestructive_aliasing, preserves_dimensions<EXP> { typedef typename EXP::type type; template <typename M, typename T> static type apply ( const M& m, const T& eps, long r, long c) { const type temp = m(r,c); if (temp >= eps || temp <= -eps) return temp; else return 0; } }; template < typename EXP > const matrix_exp<matrix_scalar_binary_exp<matrix_exp<EXP>,typename EXP::type,op_round_zeros<EXP> > > round_zeros ( const matrix_exp<EXP>& m ) { // you can only round matrices that contain floats, doubles or long doubles. COMPILE_TIME_ASSERT(( is_same_type<typename EXP::type,float>::value == true || is_same_type<typename EXP::type,double>::value == true || is_same_type<typename EXP::type,long double>::value == true )); typedef matrix_scalar_binary_exp<matrix_exp<EXP>,typename EXP::type, op_round_zeros<EXP> > exp; return matrix_exp<exp>(exp(m,10*std::numeric_limits<typename EXP::type>::epsilon())); } template < typename EXP > const matrix_exp<matrix_scalar_binary_exp<matrix_exp<EXP>,typename EXP::type,op_round_zeros<EXP> > > round_zeros ( const matrix_exp<EXP>& m, typename EXP::type eps ) { // you can only round matrices that contain floats, doubles or long doubles. COMPILE_TIME_ASSERT(( is_same_type<typename EXP::type,float>::value == true || is_same_type<typename EXP::type,double>::value == true || is_same_type<typename EXP::type,long double>::value == true )); typedef matrix_scalar_binary_exp<matrix_exp<EXP>,typename EXP::type, op_round_zeros<EXP> > exp; return matrix_exp<exp>(exp(m,eps)); } // ---------------------------------------------------------------------------------------- template <typename EXP> struct op_cubed : has_nondestructive_aliasing, preserves_dimensions<EXP> { typedef typename EXP::type type; template <typename M> static type apply ( const M& m, long r, long c) { return m(r,c)*m(r,c)*m(r,c); } }; template < typename EXP > const matrix_exp<matrix_unary_exp<matrix_exp<EXP>,op_cubed<EXP> > > cubed ( const matrix_exp<EXP>& m ) { typedef matrix_unary_exp<matrix_exp<EXP>,op_cubed<EXP> > exp; return matrix_exp<exp>(exp(m)); } // ---------------------------------------------------------------------------------------- template <typename EXP> struct op_squared : has_nondestructive_aliasing, preserves_dimensions<EXP> { typedef typename EXP::type type; template <typename M> static type apply ( const M& m, long r, long c) { return m(r,c)*m(r,c); } }; template < typename EXP > const matrix_exp<matrix_unary_exp<matrix_exp<EXP>,op_squared<EXP> > > squared ( const matrix_exp<EXP>& m ) { typedef matrix_unary_exp<matrix_exp<EXP>,op_squared<EXP> > exp; return matrix_exp<exp>(exp(m)); } // ---------------------------------------------------------------------------------------- template <typename EXP> struct op_pow : has_nondestructive_aliasing, preserves_dimensions<EXP> { typedef typename EXP::type type; template <typename M, typename S> static type apply ( const M& m, const S& s, long r, long c) { return static_cast<type>(std::pow(m(r,c),s)); } }; template < typename EXP, typename S > const matrix_exp<matrix_scalar_binary_exp<matrix_exp<EXP>,typename EXP::type,op_pow<EXP> > > pow ( const matrix_exp<EXP>& m, const S& s ) { // you can only round matrices that contain floats, doubles or long doubles. COMPILE_TIME_ASSERT(( is_same_type<typename EXP::type,float>::value == true || is_same_type<typename EXP::type,double>::value == true || is_same_type<typename EXP::type,long double>::value == true )); typedef matrix_scalar_binary_exp<matrix_exp<EXP>,typename EXP::type,op_pow<EXP> > exp; return matrix_exp<exp>(exp(m,s)); } // ---------------------------------------------------------------------------------------- template <typename EXP> struct op_reciprocal : has_nondestructive_aliasing, preserves_dimensions<EXP> { typedef typename EXP::type type; template <typename M> static type apply ( const M& m, long r, long c) { const type temp = m(r,c); if (temp != 0) return static_cast<type>(1.0/temp); else return 0; } }; template < typename EXP > const matrix_exp<matrix_unary_exp<matrix_exp<EXP>,op_reciprocal<EXP> > > reciprocal ( const matrix_exp<EXP>& m ) { // you can only compute reciprocal matrices that contain floats, doubles or long doubles. COMPILE_TIME_ASSERT(( is_same_type<typename EXP::type,float>::value == true || is_same_type<typename EXP::type,double>::value == true || is_same_type<typename EXP::type,long double>::value == true )); typedef matrix_unary_exp<matrix_exp<EXP>,op_reciprocal<EXP> > exp; return matrix_exp<exp>(exp(m)); } // ---------------------------------------------------------------------------------------- template <typename EXP> struct op_normalize : has_nondestructive_aliasing, preserves_dimensions<EXP> { typedef typename EXP::type type; template <typename M> static type apply ( const M& m, const type& s, long r, long c) { return m(r,c)*s; } }; template < typename EXP > const matrix_exp<matrix_scalar_binary_exp<matrix_exp<EXP>,typename EXP::type,op_normalize<EXP> > > normalize ( const matrix_exp<EXP>& m ) { // you can only compute normalized matrices that contain floats, doubles or long doubles. COMPILE_TIME_ASSERT(( is_same_type<typename EXP::type,float>::value == true || is_same_type<typename EXP::type,double>::value == true || is_same_type<typename EXP::type,long double>::value == true )); typedef matrix_scalar_binary_exp<matrix_exp<EXP>,typename EXP::type, op_normalize<EXP> > exp; typename EXP::type temp = std::sqrt(sum(squared(m))); if (temp != 0.0) temp = 1.0/temp; return matrix_exp<exp>(exp(m,temp)); } // ---------------------------------------------------------------------------------------- template <typename EXP> struct op_round : has_nondestructive_aliasing, preserves_dimensions<EXP> { typedef typename EXP::type type; template <typename M> static type apply ( const M& m, long r, long c) { return static_cast<type>(std::floor(m(r,c)+0.5)); } }; template < typename EXP > const matrix_exp<matrix_unary_exp<matrix_exp<EXP>,op_round<EXP> > > round ( const matrix_exp<EXP>& m ) { // you can only round matrices that contain floats, doubles or long doubles. COMPILE_TIME_ASSERT(( is_same_type<typename EXP::type,float>::value == true || is_same_type<typename EXP::type,double>::value == true || is_same_type<typename EXP::type,long double>::value == true )); typedef matrix_unary_exp<matrix_exp<EXP>,op_round<EXP> > exp; return matrix_exp<exp>(exp(m)); } // ---------------------------------------------------------------------------------------- template <typename EXP1, typename EXP2> struct op_complex_matrix : has_nondestructive_aliasing, preserves_dimensions<EXP1,EXP2> { typedef std::complex<typename EXP1::type> type; template <typename M1, typename M2> static type apply ( const M1& m1, const M2& m2 , long r, long c) { return type(m1(r,c),m2(r,c)); } }; template < typename EXP1, typename EXP2 > const matrix_exp<matrix_binary_exp<matrix_exp<EXP1>,matrix_exp<EXP2>,op_complex_matrix<EXP1,EXP2> > > complex_matrix ( const matrix_exp<EXP1>& real_part, const matrix_exp<EXP2>& imag_part ) { COMPILE_TIME_ASSERT((is_same_type<typename EXP1::type,typename EXP2::type>::value == true)); COMPILE_TIME_ASSERT(EXP1::NR == EXP2::NR || EXP1::NR == 0 || EXP2::NR == 0); COMPILE_TIME_ASSERT(EXP1::NC == EXP2::NC || EXP1::NC == 0 || EXP2::NC == 0); DLIB_ASSERT(real_part.nr() == imag_part.nr() && real_part.nc() == imag_part.nc(), "\tconst matrix_exp::type complex_matrix(real_part, imag_part)" << "\n\tYou can only make a complex matrix from two equally sized matrices" << "\n\treal_part.nr(): " << real_part.nr() << "\n\treal_part.nc(): " << real_part.nc() << "\n\timag_part.nr(): " << imag_part.nr() << "\n\timag_part.nc(): " << imag_part.nc() ); typedef matrix_binary_exp<matrix_exp<EXP1>,matrix_exp<EXP2>,op_complex_matrix<EXP1,EXP2> > exp; return matrix_exp<exp>(exp(real_part,imag_part)); } // ---------------------------------------------------------------------------------------- template <typename EXP> struct op_norm : has_nondestructive_aliasing, preserves_dimensions<EXP> { typedef typename EXP::type::value_type type; template <typename M> static type apply ( const M& m, long r, long c) { return std::norm(m(r,c)); } }; template < typename EXP > const matrix_exp<matrix_unary_exp<matrix_exp<EXP>,op_norm<EXP> > > norm ( const matrix_exp<EXP>& m ) { typedef matrix_unary_exp<matrix_exp<EXP>,op_norm<EXP> > exp; return matrix_exp<exp>(exp(m)); } // ---------------------------------------------------------------------------------------- template <typename EXP> struct op_real : has_nondestructive_aliasing, preserves_dimensions<EXP> { typedef typename EXP::type::value_type type; template <typename M> static type apply ( const M& m, long r, long c) { return std::real(m(r,c)); } }; template < typename EXP > const matrix_exp<matrix_unary_exp<matrix_exp<EXP>,op_real<EXP> > > real ( const matrix_exp<EXP>& m ) { typedef matrix_unary_exp<matrix_exp<EXP>,op_real<EXP> > exp; return matrix_exp<exp>(exp(m)); } // ---------------------------------------------------------------------------------------- template <typename EXP> struct op_imag : has_nondestructive_aliasing, preserves_dimensions<EXP> { typedef typename EXP::type::value_type type; template <typename M> static type apply ( const M& m, long r, long c) { return std::imag(m(r,c)); } }; template < typename EXP > const matrix_exp<matrix_unary_exp<matrix_exp<EXP>,op_imag<EXP> > > imag ( const matrix_exp<EXP>& m ) { typedef matrix_unary_exp<matrix_exp<EXP>,op_imag<EXP> > exp; return matrix_exp<exp>(exp(m)); } // ---------------------------------------------------------------------------------------- } #endif // DLIB_MATRIx_MATH_FUNCTIONS
[ [ [ 1, 418 ] ] ]
604c9a238147334b9bd673400659cd4efbce904f
a0dd6df2a43bfd422c7bfea85fe34293e8642634
/Projet POLY/Assembler.cpp
7b045863e235971dbe0c6c00856faea80a1bd8dd
[]
no_license
juliensnz/machinepolyarchi
45a1f14f39cbf232aa0b7865e6dbe5aa1ef316fe
233e878b42d48a6419fa2685aae466e02240aba6
refs/heads/master
2020-04-11T04:24:39.458916
2009-12-16T18:13:07
2009-12-16T18:13:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,606
cpp
#include "Parser.hpp" #include "Assembler.hpp" #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <map> #include <string> using namespace std; bool translateFile(string inputPath, string *outputPath){ if (!inputPath.empty()) { //S'il y a un fichier en entrée if (outputPath->empty()) *outputPath = inputPath + "_asm"; //Si le chemin de sortie n'est pas spécifié, on crée le fichier dans //le même répertoire, nomSortie = nomEntree_asm map <string, int> opcodeToInt, regToInt; opcodeToInt["load"] = 0; opcodeToInt["read"] = 1; opcodeToInt["print"] = 2; opcodeToInt["pow"] = 3; opcodeToInt["daxpy"] = 5; opcodeToInt["setlr"] = 6; opcodeToInt["resetlr"] = 7; opcodeToInt["loop"] = 8; opcodeToInt["end"] = 9; //Tableau associatif de correspondance entre les commandes et leur code opération. regToInt[""] = 0; regToInt["r0"] = 1; regToInt["r1"] = 2; regToInt["r2"] = 3; regToInt["r3"] = 4; regToInt["r4"] = 5; //Tableau associatif entre les différents registres et leur code valeur //Deux dictionnaires de conversion ifstream inputFile(inputPath.c_str(), ios::in); ofstream outputFile(outputPath->c_str(), ios::out | ios::trunc); //Ouverture des deux fichiers, ecrasement de l'eventuel fichier de sortie //préexistant if(inputFile && outputFile){ string line, etq, cmd, ri, rj, rk, nc; int nbLigne = 0; map <string, int> etiquettes; //Création de la map contenant les étiquettes while (!inputFile.eof()) { getline(inputFile, line); if (!line.empty()){ //Si la ligne n'est pas vide nbLigne++; getEtiq(&line, &etq); //On récupere l'etiquette éventuelle if (!etq.empty()) //S'il y a une etiquette etiquettes[etq] = nbLigne; //On enregistre dans la table "etiquettes" le numero de ligne associé au nom de l'étiquette } } //Premier parcours du fichier pour enregistrer la position des étiquettes. //On boucle tant qu'on n'est pas à la fin inputFile.clear(); inputFile.seekg(0, ios::beg); nbLigne = 0; //Retour au début du fichier et remise à 0 des paramètres de lecture. while(!inputFile.eof()){ getline(inputFile, line); if (!line.empty()){ nbLigne++; parseText(&line, &etq, &cmd, &ri, &rj, &rk, &nc); //Parsing de la ligne par la fonction parseText outputFile << "0x" << setfill('0') << setw(8) << hex << convert(cmd, ri, rj, rk, nc, opcodeToInt, regToInt, etiquettes, nbLigne) << endl; //Enregistrement dans le fichier de sortie de la ligne assemblée. //Completion avec des 0 a gauche, resultat de la forme 0xNNNNNNNN } } //Second parcour du fichier pour traitement inputFile.close(); outputFile.close(); //Fermeture des deux fichiers return true; } else cerr << "Echec de l'ouverture / creation d'un des fichiers" << endl; } else cerr << "Pas de chemin de fichier" << endl; return false; } unsigned int convert(string commande, string ri, string rj, string rk, string nc, map <string, int> opcodeToInt, map <string, int> regToInt, map <string, int> etiquettes, int currLine){ unsigned int result = opcodeToInt[commande]; //On initialise le résultat avec le code de la commande if (result == 3 && nc.empty()) result = 4; //Si la commande est pow et que la constante est vide on change le code en powBis else if (result == 8){ //Si le code est "loop" if (!rj.empty()){ int i = etiquettes[rj] - currLine; stringstream iss; iss << i; iss >> nc; //rj prend pour valeur la différence entre la ligne actuelle et la ligne //correspondant à l'etiquette } } result <<= 3; //Probleme avec l'opcode 0, decalage de 0 = 0 //Réglé a l'écriture dans le fichier result += regToInt[ri]; result <<= 3; result += regToInt[rj]; result <<= 3; result += regToInt[rk]; result <<= 8; result += (0x000000ff & toInt(nc)); //On ne garde que 8 bit sur la constante. result <<= 11; //Conversion de la ligne d'instruction en entier return result; } int toInt(string s){ int c = 0; if (!s.empty()) { istringstream iss (s); if (s[0] == '-'){ (signed int) c; iss >> c; } else { (unsigned int) c; iss >> c; } c = (iss.eof()) ? c : 0; } return c; }
[ "Maxime.Bury@f9af527e-e11e-11de-9fd5-4be1c9d5bc18" ]
[ [ [ 1, 157 ] ] ]
2ba39bbe37f5839d9bca05d3208732cb5bb2cf0b
fd518ed0226c6a044d5e168ab50a0e4a37f8efa9
/iAuthor/Author/msppt9.h
540faec0715f4ac40c527cbcdf5eb8264835e365
[]
no_license
shilinxu/iprojects
e2e2394df9882afaacfb9852332f83cbef6a8c93
79bc8e45596577948c45cf2afcff331bc71ab026
refs/heads/master
2020-05-17T19:15:43.197685
2010-04-02T15:58:11
2010-04-02T15:58:11
41,959,151
0
0
null
null
null
null
UTF-8
C++
false
false
12,041
h
// Machine generated IDispatch wrapper class(es) created with ClassWizard ///////////////////////////////////////////////////////////////////////////// // _Application wrapper class class _Application : public COleDispatchDriver { public: _Application() {} // Calls COleDispatchDriver default constructor _Application(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} _Application(const _Application& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: LPDISPATCH GetPresentations(); LPDISPATCH GetWindows(); LPDISPATCH GetActiveWindow(); LPDISPATCH GetActivePresentation(); LPDISPATCH GetSlideShowWindows(); LPDISPATCH GetCommandBars(); CString GetPath(); CString GetName(); CString GetCaption(); void SetCaption(LPCTSTR lpszNewValue); LPDISPATCH GetAssistant(); LPDISPATCH GetFileSearch(); LPDISPATCH GetFileFind(); CString GetBuild(); CString GetVersion(); CString GetOperatingSystem(); CString GetActivePrinter(); long GetCreator(); LPDISPATCH GetAddIns(); // method 'GetVbe' not emitted because of invalid return type or parameter type void Help(LPCTSTR HelpFile, long ContextID); void Quit(); // method 'Run' not emitted because of invalid return type or parameter type float GetLeft(); void SetLeft(float newValue); float GetTop(); void SetTop(float newValue); float GetWidth(); void SetWidth(float newValue); float GetHeight(); void SetHeight(float newValue); long GetWindowState(); void SetWindowState(long nNewValue); long GetVisible(); void SetVisible(long nNewValue); long GetActive(); void Activate(); LPDISPATCH GetAnswerWizard(); LPDISPATCH GetCOMAddIns(); CString GetProductCode(); LPDISPATCH GetDefaultWebOptions(); LPDISPATCH GetLanguageSettings(); long GetShowWindowsInTaskbar(); void SetShowWindowsInTaskbar(long nNewValue); long GetFeatureInstall(); void SetFeatureInstall(long nNewValue); }; ///////////////////////////////////////////////////////////////////////////// // SlideShowWindow wrapper class class SlideShowWindow : public COleDispatchDriver { public: SlideShowWindow() {} // Calls COleDispatchDriver default constructor SlideShowWindow(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} SlideShowWindow(const SlideShowWindow& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: LPDISPATCH GetApplication(); LPDISPATCH GetParent(); LPDISPATCH GetView(); LPDISPATCH GetPresentation(); long GetIsFullScreen(); float GetLeft(); void SetLeft(float newValue); float GetTop(); void SetTop(float newValue); float GetWidth(); void SetWidth(float newValue); float GetHeight(); void SetHeight(float newValue); long GetActive(); void Activate(); }; ///////////////////////////////////////////////////////////////////////////// // SlideShowView wrapper class class SlideShowView : public COleDispatchDriver { public: SlideShowView() {} // Calls COleDispatchDriver default constructor SlideShowView(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} SlideShowView(const SlideShowView& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: LPDISPATCH GetApplication(); LPDISPATCH GetParent(); long GetZoom(); LPDISPATCH GetSlide(); long GetPointerType(); void SetPointerType(long nNewValue); long GetState(); void SetState(long nNewValue); long GetAcceleratorsEnabled(); void SetAcceleratorsEnabled(long nNewValue); float GetPresentationElapsedTime(); float GetSlideElapsedTime(); void SetSlideElapsedTime(float newValue); LPDISPATCH GetLastSlideViewed(); long GetAdvanceMode(); LPDISPATCH GetPointerColor(); long GetIsNamedShow(); CString GetSlideShowName(); void DrawLine(float BeginX, float BeginY, float EndX, float EndY); void EraseDrawing(); void First(); void Last(); void Next(); void Previous(); void GotoSlide(long index, long ResetSlide); void GotoNamedShow(LPCTSTR SlideShowName); void EndNamedShow(); void ResetSlideTime(); void Exit(); long GetCurrentShowPosition(); }; ///////////////////////////////////////////////////////////////////////////// // SlideShowSettings wrapper class class SlideShowSettings : public COleDispatchDriver { public: SlideShowSettings() {} // Calls COleDispatchDriver default constructor SlideShowSettings(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} SlideShowSettings(const SlideShowSettings& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: LPDISPATCH GetApplication(); LPDISPATCH GetParent(); LPDISPATCH GetPointerColor(); LPDISPATCH GetNamedSlideShows(); long GetStartingSlide(); void SetStartingSlide(long nNewValue); long GetEndingSlide(); void SetEndingSlide(long nNewValue); long GetAdvanceMode(); void SetAdvanceMode(long nNewValue); LPDISPATCH Run(); long GetLoopUntilStopped(); void SetLoopUntilStopped(long nNewValue); long GetShowType(); void SetShowType(long nNewValue); long GetShowWithNarration(); void SetShowWithNarration(long nNewValue); long GetShowWithAnimation(); void SetShowWithAnimation(long nNewValue); CString GetSlideShowName(); void SetSlideShowName(LPCTSTR lpszNewValue); long GetRangeType(); void SetRangeType(long nNewValue); }; ///////////////////////////////////////////////////////////////////////////// // Presentations wrapper class class Presentations : public COleDispatchDriver { public: Presentations() {} // Calls COleDispatchDriver default constructor Presentations(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} Presentations(const Presentations& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: long GetCount(); LPDISPATCH GetApplication(); LPDISPATCH GetParent(); LPDISPATCH Item(const VARIANT& index); LPDISPATCH Add(long WithWindow); LPDISPATCH Open(LPCTSTR FileName, long ReadOnly, long Untitled, long WithWindow); }; ///////////////////////////////////////////////////////////////////////////// // PageSetup wrapper class class PageSetup : public COleDispatchDriver { public: PageSetup() {} // Calls COleDispatchDriver default constructor PageSetup(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} PageSetup(const PageSetup& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: LPDISPATCH GetApplication(); LPDISPATCH GetParent(); long GetFirstSlideNumber(); void SetFirstSlideNumber(long nNewValue); float GetSlideHeight(); void SetSlideHeight(float newValue); float GetSlideWidth(); void SetSlideWidth(float newValue); long GetSlideSize(); void SetSlideSize(long nNewValue); long GetNotesOrientation(); void SetNotesOrientation(long nNewValue); long GetSlideOrientation(); void SetSlideOrientation(long nNewValue); }; ///////////////////////////////////////////////////////////////////////////// // Slides wrapper class class Slides : public COleDispatchDriver { public: Slides() {} // Calls COleDispatchDriver default constructor Slides(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} Slides(const Slides& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: long GetCount(); LPDISPATCH GetApplication(); LPDISPATCH GetParent(); LPDISPATCH Item(const VARIANT& index); LPDISPATCH FindBySlideID(long SlideID); LPDISPATCH Add(long index, long Layout); long InsertFromFile(LPCTSTR FileName, long index, long SlideStart, long SlideEnd); LPDISPATCH Range(const VARIANT& index); LPDISPATCH Paste(long index); }; ///////////////////////////////////////////////////////////////////////////// // _Slide wrapper class class _Slide : public COleDispatchDriver { public: _Slide() {} // Calls COleDispatchDriver default constructor _Slide(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} _Slide(const _Slide& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: LPDISPATCH GetApplication(); LPDISPATCH GetParent(); LPDISPATCH GetShapes(); LPDISPATCH GetHeadersFooters(); LPDISPATCH GetSlideShowTransition(); LPDISPATCH GetColorScheme(); void SetColorScheme(LPDISPATCH newValue); LPDISPATCH GetBackground(); CString GetName(); void SetName(LPCTSTR lpszNewValue); long GetSlideID(); long GetPrintSteps(); void Select(); void Cut(); void Copy(); long GetLayout(); void SetLayout(long nNewValue); LPDISPATCH Duplicate(); void Delete(); LPDISPATCH GetTags(); long GetSlideIndex(); long GetSlideNumber(); long GetDisplayMasterShapes(); void SetDisplayMasterShapes(long nNewValue); long GetFollowMasterBackground(); void SetFollowMasterBackground(long nNewValue); LPDISPATCH GetNotesPage(); LPDISPATCH GetMaster(); LPDISPATCH GetHyperlinks(); void Export(LPCTSTR FileName, LPCTSTR FilterName, long ScaleWidth, long ScaleHeight); LPDISPATCH GetScripts(); }; ///////////////////////////////////////////////////////////////////////////// // _Presentation wrapper class class _Presentation : public COleDispatchDriver { public: _Presentation() {} // Calls COleDispatchDriver default constructor _Presentation(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} _Presentation(const _Presentation& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: LPDISPATCH GetApplication(); LPDISPATCH GetParent(); LPDISPATCH GetSlideMaster(); LPDISPATCH GetTitleMaster(); long GetHasTitleMaster(); LPDISPATCH AddTitleMaster(); void ApplyTemplate(LPCTSTR FileName); CString GetTemplateName(); LPDISPATCH GetNotesMaster(); LPDISPATCH GetHandoutMaster(); LPDISPATCH GetSlides(); LPDISPATCH GetPageSetup(); LPDISPATCH GetColorSchemes(); LPDISPATCH GetExtraColors(); LPDISPATCH GetSlideShowSettings(); LPDISPATCH GetFonts(); LPDISPATCH GetWindows(); LPDISPATCH GetTags(); LPDISPATCH GetDefaultShape(); LPDISPATCH GetBuiltInDocumentProperties(); LPDISPATCH GetCustomDocumentProperties(); // method 'GetVBProject' not emitted because of invalid return type or parameter type long GetReadOnly(); CString GetFullName(); CString GetName(); CString GetPath(); long GetSaved(); void SetSaved(long nNewValue); long GetLayoutDirection(); void SetLayoutDirection(long nNewValue); LPDISPATCH NewWindow(); void FollowHyperlink(LPCTSTR Address, LPCTSTR SubAddress, BOOL NewWindow, BOOL AddHistory, LPCTSTR ExtraInfo, long Method, LPCTSTR HeaderInfo); void AddToFavorites(); LPDISPATCH GetPrintOptions(); void PrintOut(long From, long To, LPCTSTR PrintToFile, long Copies, long Collate); void Save(); void SaveAs(LPCTSTR FileName, long FileFormat, long EmbedTrueTypeFonts); void SaveCopyAs(LPCTSTR FileName, long FileFormat, long EmbedTrueTypeFonts); void Export(LPCTSTR Path, LPCTSTR FilterName, long ScaleWidth, long ScaleHeight); void Close(); LPDISPATCH GetContainer(); long GetDisplayComments(); void SetDisplayComments(long nNewValue); long GetFarEastLineBreakLevel(); void SetFarEastLineBreakLevel(long nNewValue); CString GetNoLineBreakBefore(); void SetNoLineBreakBefore(LPCTSTR lpszNewValue); CString GetNoLineBreakAfter(); void SetNoLineBreakAfter(LPCTSTR lpszNewValue); void UpdateLinks(); LPDISPATCH GetSlideShowWindow(); long GetFarEastLineBreakLanguage(); void SetFarEastLineBreakLanguage(long nNewValue); void WebPagePreview(); long GetDefaultLanguageID(); void SetDefaultLanguageID(long nNewValue); LPDISPATCH GetCommandBars(); LPDISPATCH GetPublishObjects(); LPDISPATCH GetWebOptions(); LPDISPATCH GetHTMLProject(); void ReloadAs(long cp); long GetEnvelopeVisible(); void SetEnvelopeVisible(long nNewValue); long GetVBASigned(); };
[ [ [ 1, 383 ] ] ]
dea8f60ef446e52674c922daf3c876a1319b1f14
7202223bb84abe3f0e4fec236e0b7530ce07bb0a
/switch.cxx
3adda2dfa35cfd21c10f19f93604ad09a09e9d48
[ "BSD-2-Clause" ]
permissive
wilx/c2pas
ec75c57284a1f2a8dbf9b555bdd087f9025daf0c
3d4b9e4bd187e5b12cec0afc368168aca634ac4a
refs/heads/master
2021-01-10T02:17:34.798401
2007-10-17T22:14:30
2007-10-17T22:14:30
36,983,834
1
0
null
null
null
null
UTF-8
C++
false
false
2,476
cxx
/* Copyright (c) 1997-2007, Václav Haisman 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. 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 "switch.hxx" #include <sstream> static unsigned label_count = 0; static std::string gen_label_name () { std::ostringstream oss; oss << "__c2pas_label_" << ++label_count; return oss.str (); } void scan_for_cases (CStatement const * stmt, std::list<std::string> & labels, std::list<const CLabeledStatement *> & lstmts, std::string & default_label) { if (! stmt) throw std::string ("NULL selection statement?"); default_label.clear (); while (stmt) { switch (stmt->stmt_type ()) { case CStatement::Labeled: { const CLabeledStatement * lstmt = static_cast<const CLabeledStatement *>(stmt); switch (lstmt->labeledstmt_type ()) { case CLabeledStatement::Case: labels.push_back (gen_label_name ()); lstmts.push_back (lstmt); break; case CLabeledStatement::Default: default_label = gen_label_name (); labels.push_back (default_label); lstmts.push_back (lstmt); break; default: throw std::string ("goto statement is not supported"); } } break; default: ; } stmt = stmt->next (); } }
[ [ [ 1, 85 ] ] ]
e62f0264a27e0ce59a21e7d7e105cadc2bc588ec
061348a6be0e0e602d4a5b3e0af28e9eee2d257f
/Examples/Tutorial/ParticleSystem/05QuadParticleDrawer.cpp
2d072ee234959afb629782492591f5c040660170
[]
no_license
passthefist/OpenSGToolbox
4a76b8e6b87245685619bdc3a0fa737e61a57291
d836853d6e0647628a7dd7bb7a729726750c6d28
refs/heads/master
2023-06-09T22:44:20.711657
2010-07-26T00:43:13
2010-07-26T00:43:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,800
cpp
// General OpenSG configuration, needed everywhere #include "OSGConfig.h" // A little helper to simplify scene management and interaction #include "OSGSimpleSceneManager.h" #include "OSGNode.h" #include "OSGGroup.h" #include "OSGViewport.h" #include "OSGSimpleGeometry.h" #include "OSGWindowUtils.h" // Input #include "OSGKeyListener.h" #include "OSGBlendChunk.h" #include "OSGTextureObjChunk.h" #include "OSGTextureEnvChunk.h" #include "OSGImageFileHandler.h" #include "OSGChunkMaterial.h" #include "OSGMaterialChunk.h" #include "OSGParticleSystem.h" #include "OSGParticleSystemCore.h" #include "OSGPointParticleSystemDrawer.h" #include "OSGSphereDistribution3D.h" #include "OSGQuadParticleSystemDrawer.h" #include "OSGQuadParticleSystemDrawer.h" #include "OSGBurstParticleGenerator.h" #include "OSGGaussianNormalDistribution1D.h" #include "OSGCylinderDistribution3D.h" #include "OSGLineDistribution3D.h" //#include "OSGSizeDistribution3D.h" // Activate the OpenSG namespace OSG_USING_NAMESPACE // The SimpleSceneManager to manage simple applications SimpleSceneManager *mgr; WindowEventProducerRefPtr TutorialWindow; // Forward declaration so we can have the interesting stuff upfront void display(void); void reshape(Vec2f Size); void ClickToGenerate(const MouseEventUnrecPtr e); Distribution3DRefPtr createPositionDistribution(void); Distribution1DRefPtr createLifespanDistribution(void); Distribution3DRefPtr createVelocityDistribution(void); Distribution3DRefPtr createAccelerationDistribution(void); Distribution3DRefPtr createSizeDistribution(void); ParticleSystemRefPtr ExampleParticleSystem; QuadParticleSystemDrawerRefPtr ExampleParticleSystemDrawer; BurstParticleGeneratorRefPtr ExampleBurstGenerator; // Create a class to allow for the use of the Ctrl+q class TutorialKeyListener : public KeyListener { public: virtual void keyPressed(const KeyEventUnrecPtr e) { if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND) { TutorialWindow->closeWindow(); } if(e->getKey() == KeyEvent::KEY_B)//generate particles when clicked { //Attach the Generator to the Particle System ExampleParticleSystem->pushToGenerators(ExampleBurstGenerator); } } virtual void keyReleased(const KeyEventUnrecPtr e) { } virtual void keyTyped(const KeyEventUnrecPtr e) { UInt32 CHANGE_SOURCE; if(e->getKey()== KeyEvent::KEY_P) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_POSITION_CHANGE; } else if(e->getKey()== KeyEvent::KEY_C) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_VELOCITY_CHANGE; } else if(e->getKey()== KeyEvent::KEY_V) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_VELOCITY; } else if(e->getKey()== KeyEvent::KEY_A) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_ACCELERATION; } else if(e->getKey()== KeyEvent::KEY_N) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_PARTICLE_NORMAL; } else if(e->getKey()== KeyEvent::KEY_D) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_VIEW_POSITION; } else if(e->getKey()== KeyEvent::KEY_S) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_STATIC; } else if(e->getKey()== KeyEvent::KEY_W) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_VIEW_DIRECTION; } else { return; } ExampleParticleSystemDrawer->setNormalSource(CHANGE_SOURCE); } }; void ClickToGenerate(const MouseEventUnrecPtr e) { } class TutorialMouseListener : public MouseListener { public: virtual void mouseClicked(const MouseEventUnrecPtr e) { if(e->getButton()== MouseEvent::BUTTON1) { } if(e->getButton()== MouseEvent::BUTTON3) { } } virtual void mouseEntered(const MouseEventUnrecPtr e) { } virtual void mouseExited(const MouseEventUnrecPtr e) { } virtual void mousePressed(const MouseEventUnrecPtr e) { mgr->mouseButtonPress(e->getButton(), e->getLocation().x(), e->getLocation().y()); } virtual void mouseReleased(const MouseEventUnrecPtr e) { mgr->mouseButtonRelease(e->getButton(), e->getLocation().x(), e->getLocation().y()); } }; class TutorialMouseMotionListener : public MouseMotionListener { public: virtual void mouseMoved(const MouseEventUnrecPtr e) { mgr->mouseMove(e->getLocation().x(), e->getLocation().y()); } virtual void mouseDragged(const MouseEventUnrecPtr e) { mgr->mouseMove(e->getLocation().x(), e->getLocation().y()); } }; int main(int argc, char **argv) { // OSG init osgInit(argc,argv); // Set up Window TutorialWindow = createNativeWindow(); TutorialWindow->initWindow(); TutorialWindow->setDisplayCallback(display); TutorialWindow->setReshapeCallback(reshape); TutorialKeyListener TheKeyListener; TutorialWindow->addKeyListener(&TheKeyListener); TutorialMouseListener TheTutorialMouseListener; TutorialMouseMotionListener TheTutorialMouseMotionListener; TutorialWindow->addMouseListener(&TheTutorialMouseListener); TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener); // Create the SimpleSceneManager helper mgr = new SimpleSceneManager; // Tell the Manager what to manage mgr->setWindow(TutorialWindow); //Particle System Material TextureObjChunkRefPtr QuadTextureChunk = TextureObjChunk::create(); ImageRefPtr LoadedImage = ImageFileHandler::the()->read("Data/Cloud.png"); QuadTextureChunk->setImage(LoadedImage); TextureEnvChunkRefPtr QuadTextureEnvChunk = TextureEnvChunk::create(); QuadTextureEnvChunk->setEnvMode(GL_MODULATE); BlendChunkRefPtr PSBlendChunk = BlendChunk::create(); PSBlendChunk->setSrcFactor(GL_SRC_ALPHA); PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA); MaterialChunkRefPtr PSMaterialChunk = MaterialChunk::create(); PSMaterialChunk->setAmbient(Color4f(0.3f,0.3f,0.3f,1.0f)); PSMaterialChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f)); PSMaterialChunk->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f)); PSMaterialChunk->setColorMaterial(GL_AMBIENT_AND_DIFFUSE); ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create(); PSMaterial->addChunk(QuadTextureChunk); PSMaterial->addChunk(QuadTextureEnvChunk); PSMaterial->addChunk(PSMaterialChunk); PSMaterial->addChunk(PSBlendChunk); //Particle System ExampleParticleSystem = OSG::ParticleSystem::create(); ExampleParticleSystem->attachUpdateListener(TutorialWindow); //Particle System Drawer ExampleParticleSystemDrawer = OSG::QuadParticleSystemDrawer::create(); ExampleBurstGenerator = OSG::BurstParticleGenerator::create(); //Attach the function objects to the Generator ExampleBurstGenerator->setPositionDistribution(createPositionDistribution()); ExampleBurstGenerator->setLifespanDistribution(createLifespanDistribution()); ExampleBurstGenerator->setBurstAmount(50.0); ExampleBurstGenerator->setVelocityDistribution(createVelocityDistribution()); ExampleBurstGenerator->setAccelerationDistribution(createAccelerationDistribution()); ExampleBurstGenerator->setSizeDistribution(createSizeDistribution()); //Particle System Node ParticleSystemCoreRefPtr ParticleNodeCore = OSG::ParticleSystemCore::create(); ParticleNodeCore->setSystem(ExampleParticleSystem); ParticleNodeCore->setDrawer(ExampleParticleSystemDrawer); ParticleNodeCore->setMaterial(PSMaterial); NodeRefPtr ParticleNode = OSG::Node::create(); ParticleNode->setCore(ParticleNodeCore); //Ground Node NodeRefPtr GoundNode = makePlane(30.0,30.0,10,10); Matrix GroundTransformation; GroundTransformation.setRotate(Quaternion(Vec3f(1.0f,0.0,0.0), -3.14195f)); TransformRefPtr GroundTransformCore = Transform::create(); GroundTransformCore->setMatrix(GroundTransformation); NodeRefPtr GroundTransformNode = Node::create(); GroundTransformNode->setCore(GroundTransformCore); GroundTransformNode->addChild(GoundNode); // Make Main Scene Node and add the Torus NodeRefPtr scene = OSG::Node::create(); scene->setCore(OSG::Group::create()); scene->addChild(ParticleNode); scene->addChild(GroundTransformNode); mgr->setRoot(scene); // Show the whole Scene mgr->showAll(); //Open Window Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f); Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5); TutorialWindow->openWindow(WinPos, WinSize, "05QuadParticleDrawer"); //Enter main Loop TutorialWindow->mainLoop(); osgExit(); return 0; } // Callback functions // Redraw the window void display(void) { mgr->redraw(); } // React to size changes void reshape(Vec2f Size) { mgr->resize(Size.x(), Size.y()); } Distribution3DRefPtr createPositionDistribution(void) { //Sphere Distribution SphereDistribution3DRefPtr TheSphereDistribution = SphereDistribution3D::create(); TheSphereDistribution->setCenter(Pnt3f(0.0,0.0,0.0)); TheSphereDistribution->setInnerRadius(0.0); TheSphereDistribution->setOuterRadius(3.0); TheSphereDistribution->setMinTheta(0.0); TheSphereDistribution->setMaxTheta(6.283185); TheSphereDistribution->setMinZ(-1.0); TheSphereDistribution->setMaxZ(1.0); TheSphereDistribution->setSurfaceOrVolume(SphereDistribution3D::SURFACE); return TheSphereDistribution; } Distribution3DRefPtr createVelocityDistribution(void) { //Sphere Distribution SphereDistribution3DRefPtr TheSphereDistribution = SphereDistribution3D::create(); TheSphereDistribution->setCenter(Pnt3f(0.0,0.0,1.0)); TheSphereDistribution->setInnerRadius(5.0); TheSphereDistribution->setOuterRadius(15.0); TheSphereDistribution->setMinTheta(-3.141950); TheSphereDistribution->setMaxTheta(3.141950); TheSphereDistribution->setMinZ(0.0); TheSphereDistribution->setMaxZ(1.0); TheSphereDistribution->setSurfaceOrVolume(SphereDistribution3D::VOLUME); return TheSphereDistribution; } Distribution1DRefPtr createLifespanDistribution(void) { GaussianNormalDistribution1DRefPtr TheLifespanDistribution = GaussianNormalDistribution1D::create(); TheLifespanDistribution->setMean(10.0f); TheLifespanDistribution->setStandardDeviation(2.0); return TheLifespanDistribution; } Distribution3DRefPtr createAccelerationDistribution(void) { //Sphere Distribution LineDistribution3DRefPtr TheLineDistribution = LineDistribution3D::create(); TheLineDistribution->setPoint1(Pnt3f(0.0,0.0,-3.0)); TheLineDistribution->setPoint2(Pnt3f(0.0,0.0,-3.0)); return TheLineDistribution; } Distribution3DRefPtr createSizeDistribution(void) { //Line Distribution LineDistribution3DRefPtr TheLineDistribution = LineDistribution3D::create(); TheLineDistribution->setPoint1(Pnt3f(0.2,0.2,1.0)); TheLineDistribution->setPoint2(Pnt3f(1.0,1.0,1.0)); return TheLineDistribution; }
[ [ [ 1, 67 ], [ 69, 386 ] ], [ [ 68, 68 ] ] ]
f713e2fc53c5f579b0936ee932d81132d9babfcd
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nnavmesh/inc/nnavmeshparser/nnavmeshfilereader.h
9c40e27e638d51d9413b145c23e8724a8a90552b
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,629
h
#ifndef N_NAVMESHFILEREADER_H #define N_NAVMESHFILEREADER_H //------------------------------------------------------------------------------ /** @file nnavmeshfilewriter @ingroup NebulaNavmeshSystem Navigation mesh file reader classes. (C) 2005 Conjurer Services, S.A. */ #include "nnavmeshparser/nnavmeshfile.h" class nString; class nFile; //------------------------------------------------------------------------------ /** Navigation mesh file reader interface */ struct nNavMeshFileReader : public nNavMeshFile { // Empty, class used just for type checking }; //------------------------------------------------------------------------------ /** Navigation mesh file reader for ASCII file format */ class nNavMeshAscReader : public nNavMeshFileReader { public: /// Constructor nNavMeshAscReader(); /// Destructor virtual ~nNavMeshAscReader(); /// Open a file for ASCII reading, returning true if file opened with success virtual bool OpenFile(const char* filename); /// Close the file and return true virtual bool CloseFile(); /// Read the start of a block (really skip it) virtual bool ParseBlockStart(const NavTag& tag); /// Read the end of a block (really skip it) virtual bool ParseBlockEnd(const NavTag& tag); /// Read the start of a line block (really skip it) virtual bool ParseLineBlockStart(const NavTag& tag); /// Read the end of a line block (really skip it) virtual bool ParseLineBlockEnd(const NavTag& tag); /// Read the file format code, returning true if it's the valid for this reader virtual bool ParseFourCC(); /// Read a 32 bits integer from file virtual bool ParseInt32(const NavTag& tag, int& value); /// Read a 16 bits integer from file virtual bool ParseInt16(const NavTag& tag, int& value); /// Read a 16 bits integer within a line block from file virtual bool ParseInt16InLineBlock(int& value); /// Read a 8 bits integer from file virtual bool ParseInt8(const NavTag& tag, int& value); /// Read a vector from file virtual bool ParseVector3(const NavTag& tag, vector3& value); private: /// Read the next word delimited by ' ' or '\n' void ReadWord(nString& str); /// Read the word pair (<tag>,<value>) and return the <value> word bool ReadField(const NavTag& tag, nString& str); /// File from where to read nFile* file; }; //------------------------------------------------------------------------------ /** Navigation mesh file reader for binary file format */ class nNavMeshBinReader : public nNavMeshFileReader { public: /// Constructor nNavMeshBinReader(); /// Destructor virtual ~nNavMeshBinReader(); /// Open a file for binary reading, returning true if file opened with success virtual bool OpenFile(const char* filename); /// Close the file and return true virtual bool CloseFile(); /// Read the start of a block (really skip it) virtual bool ParseBlockStart(const NavTag& tag); /// Read the end of a block (really skip it) virtual bool ParseBlockEnd(const NavTag& tag); /// Read the start of a line block (really skip it) virtual bool ParseLineBlockStart(const NavTag& tag); /// Read the end of a line block (really skip it) virtual bool ParseLineBlockEnd(const NavTag& tag); /// Read the file format code, returning true if it's the valid for this reader virtual bool ParseFourCC(); /// Read a 32 bits integer from file virtual bool ParseInt32(const NavTag& tag, int& value); /// Read a 16 bits integer from file virtual bool ParseInt16(const NavTag& tag, int& value); /// Read a 16 bits integer within a line block from file virtual bool ParseInt16InLineBlock(int& value); /// Read a 8 bits integer from file virtual bool ParseInt8(const NavTag& tag, int& value); /// Read a vector from file virtual bool ParseVector3(const NavTag& tag, vector3& value); protected: /// File from where to read nFile* file; }; //------------------------------------------------------------------------------ /** Navigation mesh file reader for binary run length compressed file format */ class nNavMeshRleReader : public nNavMeshBinReader { public: /// Open a file for reading, returning true if file opened with success virtual bool OpenFile(const char* filename); }; //------------------------------------------------------------------------------ #endif
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 133 ] ] ]
92051b825734363dbb605724239e4a95ed2ba5ac
b407e323eb85b469258b0c30892dc70b160ecdbc
/pinger/acceptor.h
ab25f495b2107fb268715b08d10231711329d0fa
[]
no_license
vi-k/whoisalive.fromsvn
7f8acf1cc8f5573008327fb61b419ed0f1676f42
c77b9619d470291389c8938e7cab87674a09f654
refs/heads/master
2021-01-10T02:13:41.786614
2010-05-30T23:18:47
2010-05-30T23:18:47
44,526,121
0
0
null
null
null
null
UTF-8
C++
false
false
1,390
h
#ifndef SERVER_H #define SERVER_H #include "pinger.h" #include "connection.h" #include "eventer.h" #include "../common/my_xml.h" #include "../common/my_inet.h" #include "../common/my_thread.h" #include <memory> #include <map> #include <boost/utility.hpp> namespace acceptor { struct map_info { std::wstring tile_type; std::wstring ext; }; typedef std::map<std::wstring, map_info> map_info_map; class server : private boost::noncopyable { private: asio::io_service io_service_; ip::tcp::acceptor acceptor_; std::auto_ptr<connection> new_connection_; boost::thread_group thgroup_; pinger::server pinger_; eventer::server state_eventer_; eventer::server ping_eventer_; map_info_map maps_; void handle_accept(const boost::system::error_code &e); void accept(void); public: server(xml::wptree &config); void run(); void on_change_state(const pinger::host_pinger_copy &pinger); void on_ping(const pinger::host_pinger_copy &pinger, const pinger::ping_result &result); inline asio::io_service& io_service() { return io_service_; } inline pinger::server& pinger() { return pinger_; } inline eventer::server& state_eventer() { return state_eventer_; } inline eventer::server& ping_eventer() { return ping_eventer_; } inline map_info_map& maps() { return maps_; } }; } #endif
[ "victor.dunaev@localhost" ]
[ [ [ 1, 59 ] ] ]
80e501117e9235c1982ee38c995321fdf7aa1c21
14a00dfaf0619eb57f1f04bb784edd3126e10658
/lab6/OperatorMeanCurvatureFlow.h
946d145e1bdeec4ed29db963a6cb45c15ed59275
[]
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
4,279
h
/************************************************************************************************* * * 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]) * *************************************************************************************************/ #ifndef __operatormeancurvatureflow_h__ #define __operatormeancurvatureflow_h__ #include "LevelSetOperator.h" /*! \brief A level set operator that does mean curvature flow. * * This class implements level set propagation in the normal direction * as defined by the mean curvature flow \f$\kappa\f$ in the following PDE * * \f[ * \dfrac{\partial \phi}{\partial t} + \alpha \kappa|\nabla \phi| = 0 * \f] */ //! \lab4 Implement mean curvature flow class OperatorMeanCurvatureFlow : public LevelSetOperator { protected: //! Scaling parameter, affects time step constraint float mAlpha; public : OperatorMeanCurvatureFlow(LevelSet * LS, float alpha=.9f) : LevelSetOperator(LS), mAlpha(alpha) { } virtual void propagate(float time) { std::cout << "applying mean curvature flow operator " << std::endl; // Create buffer used to store intermediate results std::vector<float> buffer; // calculate stable timestep dt float bound = 0.9f; float dX = mLS->getDx(); float dt = bound * (dX * dX) / (6 * mAlpha ); // Propagate level set with stable timestep dt // until requested time is reached for (float elapsed = 0; elapsed < time;) { if (dt > time-elapsed) dt = time-elapsed; elapsed += dt; LevelSetGrid::Iterator iter = getGrid().beginNarrowBand(); LevelSetGrid::Iterator iend = getGrid().endNarrowBand(); int counter = 0; while (iter != iend) { // if ( (counter++ % 100) == 0) // { // std::cout << "."; // } unsigned int i = iter.getI(); unsigned int j = iter.getJ(); unsigned int k = iter.getK(); /* *** calculate curvature *** */ // second order derivatives float ddx2 = mLS->diff2Xpm(i, j, k); float ddy2 = mLS->diff2Ypm(i, j, k); float ddz2 = mLS->diff2Zpm(i, j, k); // first order derivatives float ddx = mLS->diffXpm(i, j, k); float ddy = mLS->diffYpm(i, j, k); float ddz = mLS->diffZpm(i, j, k); // mixed derivatives float dydz = mLS->diff2YZpm(i, j, k); float dxdz = mLS->diff2ZXpm(i, j, k); float dxdy = mLS->diff2XYpm(i, j, k); // squares of the first derivatives float ddxSqr = ddx * ddx; float ddySqr = ddy * ddy; float ddzSqr = ddz * ddz; float denominator = 2.0f * pow(ddxSqr + ddySqr + ddzSqr, 3.0f/2.0f); float curvatureK = (ddxSqr * (ddy2 + ddz2) - 2.0f*ddy*ddz*dydz) / denominator + (ddySqr * (ddx2 + ddz2) - 2.0f*ddx*ddz*dxdz) / denominator + (ddzSqr * (ddx2 + ddy2) - 2.0f*ddx*ddy*dxdy) / denominator; /* *** calculate gradient using central differentials *** */ ddx = mLS->diffXpm(i, j, k); ddy = mLS->diffYpm(i, j, k); ddz = mLS->diffZpm(i, j, k); /* *** compute time differential as product *** */ float gradientNorm = sqrt(ddx*ddx + ddy*ddy + ddz*ddz); float changeRate = mAlpha * curvatureK * gradientNorm; /* *** update phi using first order forward Euler time integration *** */ float currentPhi = getGrid().getValue(i, j, k); float nextPhi = currentPhi + changeRate * dt; // assign new value and store it in the buffer buffer.push_back( nextPhi ); iter++; } // Copy new values from buffer to grid iter = getGrid().beginNarrowBand(); std::vector<float>::iterator iterBuffer = buffer.begin(); while (iter != iend) { unsigned int i = iter.getI(); unsigned int j = iter.getJ(); unsigned int k = iter.getK(); getGrid().setValue(i,j,k, (*iterBuffer)); iter++; iterBuffer++; } buffer.clear(); } } }; #endif
[ "onnepoika@da195381-492e-0410-b4d9-ef7979db4686" ]
[ [ [ 1, 138 ] ] ]
2e3645b0860e91c4d26c903d230539d8092c01de
b38ab5dcfb913569fc1e41e8deedc2487b2db491
/libraries/SoftFX/header/Blend_Template.hpp
fbac32a420f7e96197744c8916181168f7df219c
[]
no_license
santosh90n/Fury2
dacec86ab3972952e4cf6442b38e66b7a67edade
740a095c2daa32d33fdc24cc47145a1c13431889
refs/heads/master
2020-03-21T00:44:27.908074
2008-10-16T07:09:17
2008-10-16T07:09:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,062
hpp
/* SoftFX (Software graphics manipulation library) Copyright (C) 2003 Kevin Gadd This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace Blend { template <class P> class Blender { public: inline Blender& autoSelect() { return *(this); } inline operator() (P& Dest, P& Source) { Dest = Source; } }; template <class P> class NullBlender { public: inline Blender& autoSelect() { return *(this); } inline operator() (P& Dest, P& Source) { } }; template <class P> class Blender_Alpha { public: Byte bOpacity; AlphaLevel aSource, aDest; inline Blender_Alpha(Byte Opacity) { bOpacity = Opacity; aSource = AlphaLevelLookup(Opacity); aDest = AlphaLevelLookup(Opacity ^ 0xFF); } inline Blender& autoSelect() { if (bOpacity <= 0) { return NullBlender<P>(); } else if (bOpacity >= 0) { return Blender<P>(); } else { return *(this); } } inline operator() (P& Dest, P& Source) { Dest[::Blue] = AlphaFromLevel(aDest, Dest[::Blue]) + AlphaFromLevel(aSource, Source[::Blue]); Dest[::Green] = AlphaFromLevel(aDest, Dest[::Green]) + AlphaFromLevel(aSource, Source[::Green]); Dest[::Red] = AlphaFromLevel(aDest, Dest[::Red]) + AlphaFromLevel(aSource, Source[::Red]); } }; template <class P> class Blender_SourceAlpha { public: Byte bOpacity; AlphaLevel aScale, aSource, aDest; inline Blender_Alpha(Byte Opacity) { bOpacity = Opacity; aScale = AlphaLevelLookup(Opacity); } inline Blender& autoSelect() { if (bOpacity <= 0) { return NullBlender<P>(); } else if (bOpacity >= 0) { return Blender<P>(); } else { return *(this); } } inline operator() (P& Dest, P& Source) { aSource = AlphaLevelLookup(AlphaFromLevel(aScale, Source[::Alpha])); aDest = AlphaLevelLookup(AlphaFromLevel(aScale, Source[::Alpha]) ^ 0xFF); Dest[::Blue] = AlphaFromLevel(aDest, Dest[::Blue]) + AlphaFromLevel(aSource, Source[::Blue]); Dest[::Green] = AlphaFromLevel(aDest, Dest[::Green]) + AlphaFromLevel(aSource, Source[::Green]); Dest[::Red] = AlphaFromLevel(aDest, Dest[::Red]) + AlphaFromLevel(aSource, Source[::Red]); } }; };
[ "kevin@1af785eb-1c5d-444a-bf89-8f912f329d98" ]
[ [ [ 1, 100 ] ] ]
25343a51bfb372e933e9b5d11f23789c0ecb4abd
de1e5905af557c6155ee50f509758a549e458ef3
/src/treesynth/Eliot/test.cpp
ad798d60fb435f3ac376fc48f368fe3afb6d417e
[]
no_license
alltom/taps
f15f0a5b234db92447a581f3777dbe143d78da6c
a3c399d932314436f055f147106d41a90ba2fd02
refs/heads/master
2021-01-13T01:46:24.766584
2011-09-03T23:20:12
2011-09-03T23:20:12
2,486,969
1
0
null
null
null
null
UTF-8
C++
false
false
1,228
cpp
#include "Eliot.h" int audio_cb( char *buffer, int buffer_size, void *user_data ); TreesynthIO ts_io; Treesynth ts; Tree * ts_tree; int main( int argc, char ** argv ) { ts_tree = new Tree(); ts_tree->initialize( lg( CUTOFF ) ); // Find better way of parsing arguments. (Meanwhile, just don't do it.) // Why did treesynth get so slow?!!!??!?!?!?!?!?!??!?!? int samples = ts_io.ReadSoundFile( ts_io.ifilename, ts_tree->values(), CUTOFF ); std::cerr << "read it\n"; ts.tree = ts_tree; ts.initialize(); ts_io.audio_initialize( audio_cb ); while( true ) { if( ts.setup() ) ts.synth(); ts_io.WriteSoundFile( ts_io.ofilename, ts.outputSignal(), ts.tree->getSize() ); if( ts.lefttree == NULL ) { ts.lefttree = new Tree(); ts.lefttree->initialize( ts.tree->getLevels() ); } memcpy( ts.lefttree->values(), ts.outputTree()->values(), sizeof(TS_FLOAT) * ts.outputTree()->getSize() ); samples = ts_io.ReadSoundFile( ts_io.ifilename, ts.tree->values(), CUTOFF ); } return 0; } int audio_cb( char *buffer, int buffer_size, void *user_data ) { return ts_io.m_audio_cb( buffer, buffer_size, user_data ); }
[ [ [ 1, 44 ] ] ]
8a94fa9ab94474e9de45056f25309444e5ef3835
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.6/cbear.berlios.de/range/equal.hpp
fd70870494cd2642d72a4465fa788f6e7ee7637e
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
1,687
hpp
/* The MIT License Copyright (c) 2005 C Bear (http://cbear.berlios.de) 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 CBEAR_BERLIOS_DE_RANGE_EQUAL_HPP_INCLUDED #define CBEAR_BERLIOS_DE_RANGE_EQUAL_HPP_INCLUDED // std::equal #include <algorithm> #include <cbear.berlios.de/range/begin.hpp> #include <cbear.berlios.de/range/end.hpp> #include <cbear.berlios.de/range/size.hpp> namespace cbear_berlios_de { namespace range { template<class Range1, class Range2> bool equal(const Range1 &A, const Range2 &B) { return range::size(A)==range::size(B) && ::std::equal( range::begin(A), range::end(A), range::begin(B)); } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 50 ] ] ]
3cea345187c5b6193ee894512d341e547f70a874
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_stdc_namespace_pass.cpp
a28b7cc9401be01f577a3bbe2e68b68f16fd24e5
[]
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
1,210
cpp
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004, // by libs/config/tools/generate // Copyright John Maddock 2002-4. // Use, modification and distribution are 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) // See http://www.boost.org/libs/config for the most recent version. // Test file for macro BOOST_NO_STDC_NAMESPACE // This file should compile, if it does not then // BOOST_NO_STDC_NAMESPACE needs to be defined. // see boost_no_stdc_namespace.ipp for more details // Do not edit this file, it was generated automatically by // ../tools/generate from boost_no_stdc_namespace.ipp on // Sun Jul 25 11:47:49 GMTDT 2004 // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifndef BOOST_NO_STDC_NAMESPACE #include "boost_no_stdc_namespace.ipp" #else namespace boost_no_stdc_namespace = empty_boost; #endif int main( int, char *[] ) { return boost_no_stdc_namespace::test(); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 39 ] ] ]
4171c33d6aa63f314977264b147259901de58714
252e638cde99ab2aa84922a2e230511f8f0c84be
/reflib/src/BusAddForm.cpp
de0c1c98a0a07a77cf3654da75a1d1d75e78ff84
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
667
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "BusAddForm.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "BusProcessForm" #pragma link "VStringStorage" #pragma resource "*.dfm" TTourRefBookBusAddForm *TourRefBookBusAddForm; //--------------------------------------------------------------------------- __fastcall TTourRefBookBusAddForm::TTourRefBookBusAddForm(TComponent* Owner) : TTourRefBookBusProcessForm(Owner) { } //---------------------------------------------------------------------------
[ [ [ 1, 18 ] ] ]
f167c93ec3e272bfeecdb50907629df5a7c77c5e
3bf3c2da2fd334599a80aa09420dbe4c187e71a0
/WallTower.cpp
8939b72e4e57a30fc021a4e77ad8b62308568d67
[]
no_license
xiongchiamiov/virus-td
31b88f6a5d156a7b7ee076df55ddce4e1c65ca4f
a7b24ce50d07388018f82d00469cb331275f429b
refs/heads/master
2020-12-24T16:50:11.991795
2010-06-10T05:05:48
2010-06-10T05:05:48
668,821
1
0
null
null
null
null
UTF-8
C++
false
false
2,165
cpp
#include "WallTower.h" #include "constants.h" #include "lighting.h" #include "models.h" #include "shadow.h" namespace w_tower{ const int MAX_UPGRADES = 3; const int MAX_HP[MAX_UPGRADES] = {30, 50, 70}; const int ATK[MAX_UPGRADES] = {0, 0, 0}; const int ATK_DT[MAX_UPGRADES] = {1000, 1000, 1000}; //Milleseconds between attacks const float RANGE[MAX_UPGRADES] = {0.0, 0.0, 0.0}; const int BUILD_TIME = 3000; char* SOUND = "media/sounds/basic_t.mp3"; } using namespace w_tower; WallTower::WallTower(float inx, float iny, float inz, int gx, int gy): Tower(inx, iny, inz, gx, gy) { hp = MAX_HP[0]; max_hp = MAX_HP[0]; ai.atk_dmg = ATK[0]; ai.atk_dt = ATK_DT[0]; ai.range = RANGE[0]; type = T_WALL; build_time = BUILD_TIME; stage = 0; sound = SOUND; weapon = new Particles(0.7); weapon->setDirection(0.0, 1.0, 0.0, false); weapon->setCutOffs(20, 9, 20); weapon->setSpread(9); weapon->reset(); } WallTower::~WallTower(void) { delete weapon; } void WallTower::draw(GLuint id, GLenum mode){ glPushMatrix(); glTranslatef(x, y, z); glPushMatrix(); // Scale and orient model to fit grid // glTranslatef(0.0, 0.50, 0.0); // Mini Tower Defense TBQH // glScaled(0.75, 0.75, 0.75); // glRotated(83, 0.0, 1.0, 0.0); // glCallList(vtd_dl::shieldDL); // glCallList(vtd_dl::lockDL); if(mode == GL_SELECT) { glLoadName(id); glPushMatrix(); glScalef(1.0,0.5,1.0); glTranslatef(0.0,0.6,0.0); glutSolidCube(1.0f); glPopMatrix(); } glPushMatrix(); glTranslatef(-0.2, 0.25, 0.0); glScaled(0.15, 0.15, 0.15); if(mode == GL_RENDER) weapon->drawParticles(); glPopMatrix(); glPopMatrix(); glPushMatrix(); // draw_shadow(5); glPopMatrix(); glPopMatrix(); } void WallTower::step(float dt){ } bool WallTower::upgrade(){ if(stage < MAX_UPGRADES){ hp = MAX_HP[stage++]; max_hp = MAX_HP[stage]; ai.atk_dmg = ATK[stage]; ai.atk_dt = ATK_DT[stage]; ai.range = RANGE[stage]; return true; } return false; }
[ "agonza40@05766cc9-4f33-4ba7-801d-bd015708efd9", "kehung@05766cc9-4f33-4ba7-801d-bd015708efd9", "jlangloi@05766cc9-4f33-4ba7-801d-bd015708efd9", "tcasella@05766cc9-4f33-4ba7-801d-bd015708efd9" ]
[ [ [ 1, 2 ], [ 6, 29 ], [ 35, 41 ], [ 43, 44 ], [ 73, 90 ] ], [ [ 3, 4 ], [ 30, 34 ], [ 45, 52 ], [ 62, 64 ], [ 67, 69 ], [ 71, 71 ] ], [ [ 5, 5 ], [ 70, 70 ], [ 72, 72 ] ], [ [ 42, 42 ], [ 53, 61 ], [ 65, 66 ] ] ]
6aa821a3f88927fff807639499bc12d9b5e3cb41
4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4
/src/nvimage/openexr/src/Imath/ImathVec.cpp
c4df236654de6794a538a97a456d64045e719bbc
[]
no_license
saggita/nvidia-mesh-tools
9df27d41b65b9742a9d45dc67af5f6835709f0c2
a9b7fdd808e6719be88520e14bc60d58ea57e0bd
refs/heads/master
2020-12-24T21:37:11.053752
2010-09-03T01:39:02
2010-09-03T01:39:02
56,893,300
0
1
null
null
null
null
UTF-8
C++
false
false
7,976
cpp
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // 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 Industrial Light & Magic 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. // /////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------- // // Specializations of the Vec2<T> and Vec3<T> templates. // //---------------------------------------------------------------------------- #include "ImathVec.h" #if (defined _WIN32 || defined _WIN64) && defined _MSC_VER // suppress exception specification warnings #pragma warning(disable:4290) #endif namespace Imath { namespace { template<class T> bool normalizeOrThrow(Vec2<T> &v) { int axis = -1; for (int i = 0; i < 2; i ++) { if (v[i] != 0) { if (axis != -1) { throw IntVecNormalizeExc ("Cannot normalize an integer " "vector unless it is parallel " "to a principal axis"); } axis = i; } } v[axis] = (v[axis] > 0) ? 1 : -1; return true; } template<class T> bool normalizeOrThrow(Vec3<T> &v) { int axis = -1; for (int i = 0; i < 3; i ++) { if (v[i] != 0) { if (axis != -1) { throw IntVecNormalizeExc ("Cannot normalize an integer " "vector unless it is parallel " "to a principal axis"); } axis = i; } } v[axis] = (v[axis] > 0) ? 1 : -1; return true; } } // Vec2<short> template <> short Vec2<short>::length () const { float lenF = Math<float>::sqrt (dot (*this)); short lenS = (short) (lenF + 0.5f); return lenS; } template <> const Vec2<short> & Vec2<short>::normalize () { normalizeOrThrow<short>(*this); return *this; } template <> const Vec2<short> & Vec2<short>::normalizeExc () throw (Iex::MathExc) { if ((x == 0) && (y == 0)) throw NullVecExc ("Cannot normalize null vector."); normalizeOrThrow<short>(*this); return *this; } template <> const Vec2<short> & Vec2<short>::normalizeNonNull () { normalizeOrThrow<short>(*this); return *this; } template <> Vec2<short> Vec2<short>::normalized () const { Vec2<short> v(*this); normalizeOrThrow<short>(v); return v; } template <> Vec2<short> Vec2<short>::normalizedExc () const throw (Iex::MathExc) { if ((x == 0) && (y == 0)) throw NullVecExc ("Cannot normalize null vector."); Vec2<short> v(*this); normalizeOrThrow<short>(v); return v; } template <> Vec2<short> Vec2<short>::normalizedNonNull () const { Vec2<short> v(*this); normalizeOrThrow<short>(v); return v; } // Vec2<int> template <> int Vec2<int>::length () const { float lenF = Math<float>::sqrt ((float)dot (*this)); int lenI = (int) (lenF + 0.5f); return lenI; } template <> const Vec2<int> & Vec2<int>::normalize () { normalizeOrThrow<int>(*this); return *this; } template <> const Vec2<int> & Vec2<int>::normalizeExc () throw (Iex::MathExc) { if ((x == 0) && (y == 0)) throw NullVecExc ("Cannot normalize null vector."); normalizeOrThrow<int>(*this); return *this; } template <> const Vec2<int> & Vec2<int>::normalizeNonNull () { normalizeOrThrow<int>(*this); return *this; } template <> Vec2<int> Vec2<int>::normalized () const { Vec2<int> v(*this); normalizeOrThrow<int>(v); return v; } template <> Vec2<int> Vec2<int>::normalizedExc () const throw (Iex::MathExc) { if ((x == 0) && (y == 0)) throw NullVecExc ("Cannot normalize null vector."); Vec2<int> v(*this); normalizeOrThrow<int>(v); return v; } template <> Vec2<int> Vec2<int>::normalizedNonNull () const { Vec2<int> v(*this); normalizeOrThrow<int>(v); return v; } // Vec3<short> template <> short Vec3<short>::length () const { float lenF = Math<float>::sqrt (dot (*this)); short lenS = (short) (lenF + 0.5f); return lenS; } template <> const Vec3<short> & Vec3<short>::normalize () { normalizeOrThrow<short>(*this); return *this; } template <> const Vec3<short> & Vec3<short>::normalizeExc () throw (Iex::MathExc) { if ((x == 0) && (y == 0) && (z == 0)) throw NullVecExc ("Cannot normalize null vector."); normalizeOrThrow<short>(*this); return *this; } template <> const Vec3<short> & Vec3<short>::normalizeNonNull () { normalizeOrThrow<short>(*this); return *this; } template <> Vec3<short> Vec3<short>::normalized () const { Vec3<short> v(*this); normalizeOrThrow<short>(v); return v; } template <> Vec3<short> Vec3<short>::normalizedExc () const throw (Iex::MathExc) { if ((x == 0) && (y == 0) && (z == 0)) throw NullVecExc ("Cannot normalize null vector."); Vec3<short> v(*this); normalizeOrThrow<short>(v); return v; } template <> Vec3<short> Vec3<short>::normalizedNonNull () const { Vec3<short> v(*this); normalizeOrThrow<short>(v); return v; } // Vec3<int> template <> int Vec3<int>::length () const { float lenF = Math<float>::sqrt ((float)dot (*this)); int lenI = (int) (lenF + 0.5f); return lenI; } template <> const Vec3<int> & Vec3<int>::normalize () { normalizeOrThrow<int>(*this); return *this; } template <> const Vec3<int> & Vec3<int>::normalizeExc () throw (Iex::MathExc) { if ((x == 0) && (y == 0) && (z == 0)) throw NullVecExc ("Cannot normalize null vector."); normalizeOrThrow<int>(*this); return *this; } template <> const Vec3<int> & Vec3<int>::normalizeNonNull () { normalizeOrThrow<int>(*this); return *this; } template <> Vec3<int> Vec3<int>::normalized () const { Vec3<int> v(*this); normalizeOrThrow<int>(v); return v; } template <> Vec3<int> Vec3<int>::normalizedExc () const throw (Iex::MathExc) { if ((x == 0) && (y == 0) && (z == 0)) throw NullVecExc ("Cannot normalize null vector."); Vec3<int> v(*this); normalizeOrThrow<int>(v); return v; } template <> Vec3<int> Vec3<int>::normalizedNonNull () const { Vec3<int> v(*this); normalizeOrThrow<int>(v); return v; } } // namespace Imath
[ "castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c" ]
[ [ [ 1, 380 ] ] ]
ff6b9a61c9fcb0b04d2e8378f6d68becf0ffd3bc
aecc6d0ee5b767cc9c6ad2b22718f55e43abfe53
/Aesir/Attic/MapEditor.h
6b0f1e2e41c6469b6de067c09e339e1def72f82c
[]
no_license
yeah-dude/aesirtk
72ab3427535ee6c4535f4a7a16b5bd580309a2cd
fe43bedb45cdfb894935411b84c55197601a5702
refs/heads/master
2021-01-18T11:43:09.961319
2007-06-27T21:42:10
2007-06-27T21:42:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
527
h
#pragma once class wxGLContext; typedef unsigned int GLuint; class wxDocManager; class wxMDIParentFrame; #include <boost/multi_array.hpp> typedef std::pair<uint32, int> TileIdentifier; class MapEditor : public wxApp { public: virtual bool OnInit(); virtual int OnExit(); boost::multi_array<TileIdentifier, 2> selection; }; // TODO: Move these into the application class! extern wxGLContext *mainContext; extern wxMDIParentFrame *mainFrame; extern wxDocManager *docManager; extern MapEditor *mapEditor;
[ "MisterPhyrePhox@6418936e-2d2e-0410-bd97-81d43f9d527b" ]
[ [ [ 1, 21 ] ] ]
55f71ecda79733d94a96f779385872751f4df276
ea69f894ec8ffd5f614854d4650dddf653bba837
/shield.cpp
0e9a0a662f6321042f55df759276d51ed339c273
[]
no_license
empjustine/Win32RockFAT
5b14f44291dc15863af968b54ff3f9dc789a83ff
6e847beab4f534372d5d3615c2bd35659baa47b7
refs/heads/master
2022-12-17T17:44:14.308251
2001-10-24T17:28:00
2001-10-24T17:28:00
296,169,952
3
2
null
null
null
null
UTF-8
C++
false
false
3,908
cpp
#include <windows.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <assert.h> #include "array.h" #include "rs.h" unsigned char *data; unsigned char *sectors; unsigned char *newsectors; void inform(char *fmt, ...) { va_list arg; va_start(arg, fmt); vfprintf(stderr, fmt, arg); va_end(arg); } void panic(char *fmt, ...) { va_list arg; va_start(arg, fmt); vfprintf(stderr, fmt, arg); va_end(arg); exit(0); } unsigned int filesize(char *fname) { FILE *fp = fopen(fname, "rb"); if (!fp) return 0; fseek(fp, 0, SEEK_END); int len = ftell(fp); fclose(fp); return len; } ///////////////////////////////////////// // // Reed-Solomon // 1336300 -------------> 1474560 // ///////////////////////////////////////// main(int argc, char *argv[]) { int i,j; FILE *fp; if(argc != 2) panic("Usage: shield <filename>"); Array<unsigned char> sectors(512*2880); Array<unsigned char> newsectors(512*2880); Array<unsigned char> info(20); if (strlen(argv[1])>15) panic("Filename will be chopped!... " "Please rename file '%s' to less than 15 chars\n", argv[1]); unsigned int uiFileSize = filesize(argv[1]); if (1336300<uiFileSize) panic("A 1.44MB disk can (safely!) carry up to 1336300 bytes!\n"); *(unsigned int*)(unsigned char*)info = uiFileSize; strcpy((char *)((unsigned char*)info)+4, argv[1]); // Initialize Reed-Solomon code init_rs(); // Shield the data with RS fp = fopen(argv[1], "rb"); if(!fp) panic("Couldn't open file '%s'!\n", argv[1]); // Strengthen the header part... i = 0; memset(((unsigned char *)sectors)+i*(NN+1), 0, NN+1); memcpy(((unsigned char *)sectors)+i*(NN+1), (unsigned char *)info, 20); fread(((unsigned char *)sectors)+i*(NN+1)+20, 1, KK-20, fp); encode_rs( ((unsigned char *)sectors)+i*(NN+1), ((unsigned char *)sectors)+i*(NN+1)+KK); i++; // Strengthen the rest... while(i<2880*2) { if ((i%80) == 0) printf("."); memset(((unsigned char *)sectors)+i*(NN+1), 0, NN+1); fread(((unsigned char *)sectors)+i*(NN+1), 1, KK, fp); encode_rs( ((unsigned char *)sectors)+i*(NN+1), ((unsigned char *)sectors)+i*(NN+1)+KK); i++; } fclose(fp); // Produce the out-of-order file i=j=0; for(i=0;i<2880*512;i++) { newsectors[j] = sectors[i]; j+=4096; if(j>=2880*512) { j-=2880*512; j++; } } HANDLE hDrive; LPVOID pDriveSectors; DWORD bytesWritten,dw; hDrive = CreateFile( "\\\\.\\A:", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL); if (!hDrive) panic("Couldn't open disk drive A:"); pDriveSectors = VirtualAlloc( NULL, 512*2880, MEM_COMMIT, PAGE_READWRITE); if (!pDriveSectors) panic("Couldn't allocate enough buffers for a 1.44MB diskette"); CopyMemory(pDriveSectors, newsectors, 2880*512); #define INVALID_SET_FILE_POINTER (DWORD) -1 printf("\n"); for(dw=0; dw<2880; dw+=8) { if (INVALID_SET_FILE_POINTER == SetFilePointer( hDrive, dw*512, NULL, FILE_BEGIN)) panic("Couldn't seek!"); if(0 == WriteFile( hDrive, ((UCHAR *)pDriveSectors)+512*dw, 512*8, &bytesWritten, NULL)) inform("Defective sector: %d\n", dw); printf("\b\b\b\b\b\b\b\b\b%03d/%03d", 100*dw/2879, 100); } VirtualFree( pDriveSectors, 0, MEM_RELEASE); CloseHandle(hDrive); return 0; }
[ [ [ 1, 170 ] ] ]
c9f64b6a7025fb936adaf2cd53a640de40cc4487
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/video/nvideoserver_cmds.cc
c80212165c7958d2d4207d081a7ed967348ccda6
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,317
cc
//------------------------------------------------------------------------------ // nvideoserver_cmds.cc // (C) 2004 RadonLabs GmbH //------------------------------------------------------------------------------ #include "precompiled/pchnnebula.h" #include "video/nvideoserver.h" static void n_open(void* slf, nCmd* cmd); static void n_close(void* slf, nCmd* cmd); static void n_isopen(void* slf, nCmd* cmd); static void n_playfile(void* slf, nCmd* cmd); static void n_stop(void* slf, nCmd* cmd); static void n_isplaying(void* slf, nCmd* cmd); static void n_setenablescaling(void* slf, nCmd* cmd); static void n_getenablescaling(void* slf, nCmd* cmd); //------------------------------------------------------------------------------ /** @scriptclass nvideoserver @cppclass nVideoServer @superclass nroot @classinfo An abstract video playback server object. */ void n_initcmds_nVideoServer(nClass* cl) { cl->BeginCmds(); cl->AddCmd("b_open_v", 'OPEN', n_open); cl->AddCmd("v_close_v", 'CLOS', n_close); cl->AddCmd("b_isopen_v", 'ISOP', n_isopen); cl->AddCmd("b_playfile_s", 'PLFL', n_playfile); cl->AddCmd("v_stop_v", 'STOP', n_stop); cl->AddCmd("b_isplaying_v", 'ISPL', n_isplaying); cl->AddCmd("v_setenablescaling_b", 'SESC', n_setenablescaling); cl->AddCmd("b_getenablescaling_v", 'GESC', n_getenablescaling); cl->EndCmds(); } //------------------------------------------------------------------------------ /** @cmd open @input v @output v @info Open the video server. */ static void n_open(void* slf, nCmd* /*cmd*/) { nVideoServer* self = (nVideoServer*) slf; self->Open(); } //------------------------------------------------------------------------------ /** @cmd close @input v @output v @info Close the video server. */ static void n_close(void* slf, nCmd* /*cmd*/) { nVideoServer* self = (nVideoServer*) slf; self->Close(); } //------------------------------------------------------------------------------ /** @cmd isopen @input v @output b(IsOpen) @info Return true if video server is open. */ static void n_isopen(void* slf, nCmd* cmd) { nVideoServer* self = (nVideoServer*) slf; cmd->Out()->SetB(self->IsOpen()); } //------------------------------------------------------------------------------ /** @cmd playfile @input s(Filename) @output b(Success) @info Start playback of a video file. */ static void n_playfile(void* slf, nCmd* cmd) { nVideoServer* self = (nVideoServer*) slf; cmd->Out()->SetB(self->PlayFile(cmd->In()->GetS())); } //------------------------------------------------------------------------------ /** @cmd stopfile @input v @output v @info Stop currently playing video. */ static void n_stop(void* slf, nCmd* /*cmd*/) { nVideoServer* self = (nVideoServer*) slf; self->Stop(); } //------------------------------------------------------------------------------ /** @cmd isplaying @input v @output b @info Return true if currently playing. */ static void n_isplaying(void* slf, nCmd* cmd) { nVideoServer* self = (nVideoServer*) slf; cmd->Out()->SetB(self->IsPlaying()); } //------------------------------------------------------------------------------ /** @cmd setenablescaling @input b(Scaling) @output v @info Enable/disable scaling to screen size. */ static void n_setenablescaling(void* slf, nCmd* cmd) { nVideoServer* self = (nVideoServer*) slf; self->SetEnableScaling(cmd->In()->GetB()); } //------------------------------------------------------------------------------ /** @cmd getenablescaling @input v @output b(Scaling) @info Get the scale-to-screensize flag. */ static void n_getenablescaling(void* slf, nCmd* cmd) { nVideoServer* self = (nVideoServer*) slf; cmd->Out()->SetB(self->GetEnableScaling()); }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 190 ] ] ]
4de66874827a305c80aaa1f60177e5f816b907de
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/mangalore/game/attrset.h
617f87d97a9ad2011238f815170c0c9143e7b1fe
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
747
h
#ifndef GAME_ATTRSET_H #define GAME_ATTRSET_H //------------------------------------------------------------------------------ /** Attribute sets are objects that add attributes to entities and initialize them to their default values. (C) 2005 Radon Labs GmbH */ #include "foundation/refcounted.h" //------------------------------------------------------------------------------ namespace Game { class Entity; class AttrSet : public Foundation::RefCounted { DeclareRtti; DeclareFactory(AttrSet); public: /// Add attributes to entity. virtual void SetupEntity(Entity* entity); }; } // namespace Game //------------------------------------------------------------------------------ #endif
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 28 ] ] ]
af392f1538ce0946a1b5677f8b3980a26dd63797
9dad473629c94d45041d51ae6c21ca2b477bd913
/sources/node.cpp
e632772643e093ad92af3d8bce3b5d847bfee2ec
[]
no_license
Mefteg/cheshire-csg
26ed5682277beb6993f60da1604ddfe298f8caae
b12daf345c22065f5b30247d4b6c3395372849fb
refs/heads/master
2021-01-10T20:13:34.474876
2011-10-03T21:57:49
2011-10-03T21:57:49
32,360,524
0
0
null
null
null
null
UTF-8
C++
false
false
76
cpp
#include "node.h" Node::Node(void) { } Node::~Node(void) { }
[ "[email protected]@3040dc66-f2c5-6624-7679-62bdbddada0d" ]
[ [ [ 1, 11 ] ] ]
b51339cc9f498285ee0b6303329161100ed4b9bb
d504537dae74273428d3aacd03b89357215f3d11
/src/e6/e6_vfs.cpp
59ff1e40ef060eb6c517cbf5adf45ec5100fd167
[]
no_license
h0MER247/e6
1026bf9aabd5c11b84e358222d103aee829f62d7
f92546fd1fc53ba783d84e9edf5660fe19b739cc
refs/heads/master
2020-12-23T05:42:42.373786
2011-02-18T16:16:24
2011-02-18T16:16:24
237,055,477
1
0
null
2020-01-29T18:39:15
2020-01-29T18:39:14
null
UTF-8
C++
false
false
1,807
cpp
#include <map> #include <string> #include <iostream> #include "e6_vfs.h" namespace e6 { class VfsMap : e6::CName< Vfs , VfsMap > { multimap<string,Name*> mmap; typedef multimap<string,Name*>::iterator MI; struct Get : VfsIterCallback { const char * _name; Name * _obj ; Get( const char * name ) : _name(name) , _obj(0) { } virtual bool process( const char * path, Name * object ) { if ( ! strcmp( object->getName(), _name ) ) { _obj = object; return 1; } } const Name * get() { return _obj; } } ; public: bool process( const char* key, VfsIterCallback & cb ) { pair<MI,MI> p = mmap.equal_range(key); if ( p == mmap.end() ) { // key not found return 0; } for ( MI it = p.first; it != p.second; ++it ) { Name *b = it->second; if ( cb.process( key, b ) ) return true; } return false; } const Name * get( const char * path, const char * name ) { Get g(name); if ( process(path,g) ) return g.get(); return 0; } bool addEntry( const char* key, Name *name ) { mmap[ key ] = name; return 1; } void erase( Name *n ) { MI vic, it = mmap.begin(); while( it != mmap.end() ) { Name *c = it->second; vic = it++; if ( n == c ) { c->release(); mmap.erase(vic); } } } void print() { cout << "----- " << mmap.size() << " elems -----" << endl; for ( MI it = mmap.begin(); it != mmap.end(); ++it ) { Base *e = it->second; cout << it->first << " " << e->getName() << endl; } cout << endl; } }; } //namespace e6
[ [ [ 1, 95 ] ] ]
a33bea754a882a5254530fc5ad1c6f418b97a871
2b80036db6f86012afcc7bc55431355fc3234058
/src/core/Query/PlaylistSave.h
42a887bcac025707910a17ad2bf11f0aaae4fd46
[ "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
ISO-8859-9
C++
false
false
3,188
h
////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright © 2008, Daniel Önnerby // // 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. // ////////////////////////////////////////////////////////////////////////////// #pragma once #include <boost/shared_ptr.hpp> #include <boost/function.hpp> #include <vector> #include <sigslot/sigslot.h> #include <core/config.h> #include <core/Query/Base.h> #include <core/tracklist/LibraryList.h> ////////////////////////////////////////////////////////////// // Forward declarations ////////////////////////////////////////////////////////////// namespace musik{ namespace core{ namespace Library{ class Base; } } } namespace musik{ namespace core{ namespace Query{ class PlaylistSave : public Query::Base{ public: PlaylistSave(void); ~PlaylistSave(void); void SavePlaylist(const utfstring playlistName,int playlistId=0,musik::core::tracklist::Base *tracklist=NULL); sigslot::signal1<int> PlaylistSaved; protected: bool RunCallbacks(Library::Base *library); int playlistId; utfstring playlistName; std::vector<int> tracks; friend class Library::Base; friend class Library::LocalDB; virtual bool ParseQuery(Library::Base *library,db::Connection &db); Ptr copy() const; private: }; } } }
[ "onnerby@6a861d04-ae47-0410-a6da-2d49beace72e", "[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e", "urioxis@6a861d04-ae47-0410-a6da-2d49beace72e" ]
[ [ [ 1, 46 ], [ 48, 53 ], [ 55, 61 ], [ 63, 66 ], [ 68, 94 ] ], [ [ 47, 47 ], [ 67, 67 ] ], [ [ 54, 54 ], [ 62, 62 ] ] ]
5560c13132eb92fec70441a89d35c831a878bb4e
1bbd5854d4a2efff9ee040e3febe3f846ed3ecef
/src/scrview/screenview.cpp
1cdfff7c15ab458dc83f5ca2d54b0296242e961d
[]
no_license
amanuelg3/screenviewer
2b896452a05cb135eb7b9eb919424fe6c1ce8dd7
7fc4bb61060e785aa65922551f0e3ff8423eccb6
refs/heads/master
2021-01-01T18:54:06.167154
2011-12-21T02:19:10
2011-12-21T02:19:10
37,343,569
0
0
null
null
null
null
UTF-8
C++
false
false
3,461
cpp
#include "screenview.h" #include "ui_screenview.h" #include "IPdatabase.h" ScreenView::ScreenView(QWidget *parent) : QMainWindow(parent), ui(new Ui::ScreenView) { ui->setupUi(this); mouse = new Mouse(); capturer = new Capturer(60, "JPG", 800, 600); z = new QTimer(this); //connect(z, SIGNAL(timeout()), this, SLOT(doTest())); connect(z, SIGNAL(timeout()), this, SLOT(doMouseTest())); z->start(500); } ScreenView::~ScreenView() { delete ui; } void ScreenView::doTest() { if (!clicked) return; if (server) { if (capturer->hasScreen()) { qDebug() << capturer->getScreen()->length(); a->send(*capturer->getScreen()); } } else { if (b->isMade())// && b->fetchScreen() { QPixmap B; B.loadFromData(*b->fetchScreen()); b->canDel(); qDebug() << "Galima istrinti"; qDebug() << b->fetchScreen()->length(); ui->label->setPixmap(B); } } } void ScreenView::doMouseTest() { if (!clicked) return; if (server) { } else { b->send(mouse->isRightKeyP(), mouse->isLeftKeyP(), mouse->getPos().x(), mouse->getPos().y()); } } void ScreenView::on_serverButton_clicked() { server = true; a = new Server(); capturer->start(); //listen(QHostAddress::Any, 4200); a->listen(QHostAddress::Any, 4200); clicked = true; ui->gbox_login->hide(); ui->serverButton->hide(); ui->clientButton->hide(); this->resize(1024,768); } bool ScreenView::eventFilter(QObject *obj, QEvent *event) { if(event->type() == QEvent::MouseButtonPress) { QMouseEvent *k = (QMouseEvent *)event; Qt::MouseButtons mouseButton = k->button(); if( mouseButton == Qt::LeftButton ) { mouse->leftClick(true); } else if( mouseButton == Qt::RightButton ) { mouse->rightClick(true); } } else if (event->type() == QEvent::MouseButtonRelease) { QMouseEvent *k = (QMouseEvent *)event; Qt::MouseButtons mouseButton = k->button(); if( mouseButton == Qt::LeftButton ) { mouse->leftClick(false); } else if( mouseButton == Qt::RightButton ) { mouse->rightClick(false); } } if(event->type() == QEvent::MouseMove) { QMouseEvent *k = (QMouseEvent *)event; mouse->setPos(k->pos()); } return true; } void ScreenView::on_clientButton_clicked() { server = false; b = new Client(this); IPdatabase *ip = new IPdatabase(b); //ip->setIP("blA", "aaa"); ip->getIP(ui->input_user->text(), ui->input_pass->text()); //Hmz... Right place? clicked = true; ui->gbox_login->hide(); ui->serverButton->hide(); ui->clientButton->hide(); this->resize(1024,768); setMouseTracking(true); ui->label->installEventFilter(this); ui->label->setMouseTracking(true); delete ip; } void ScreenView::on_pushButton_clicked() { IPdatabase *ip = new IPdatabase(); //ip->setIP("blA", "aaa"); ip->setIP(ui->input_user->text(), ui->input_pass->text()); //Needs to remove memory leak }
[ "JuliusR@localhost", "[email protected]" ]
[ [ [ 1, 13 ], [ 16, 38 ], [ 40, 48 ], [ 51, 52 ], [ 54, 59 ], [ 61, 62 ], [ 64, 64 ], [ 66, 129 ], [ 131, 131 ], [ 138, 146 ], [ 157, 157 ] ], [ [ 14, 15 ], [ 39, 39 ], [ 49, 50 ], [ 53, 53 ], [ 60, 60 ], [ 63, 63 ], [ 65, 65 ], [ 130, 130 ], [ 132, 137 ], [ 147, 156 ] ] ]
ab85e8c6bf94d71f299cbcefade1eaf799490413
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/ThirdParty/luabind/luabind/lua_include.hpp
d3592aca1abf65d97046511551b7916d8447d37b
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,292
hpp
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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 LUA_INCLUDE_HPP_INCLUDED #define LUA_INCLUDE_HPP_INCLUDED extern "C" { #include "lua.h" #include "lauxlib.h" } #endif
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 33 ] ] ]
33a00d3a9b1931d473d5ae7ca0e1c0f7b440e384
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/Src/CEventZone.cpp
73e4cf3d738327b8904bd683facbdf51f8bc5939
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
682
cpp
#include "CEventZone.h" namespace Nebula { CEventZone::CEventZone() { mComponentID = "CEventZone"; } CEventZone::CEventZone(const CEventZoneDesc& desc) { mComponentID = "CEventZone"; mDesc = desc; } CEventZone::~CEventZone() { } void CEventZone::update() { } void CEventZone::setup() { } void CEventZone::callLuaFunction(const std::string func ) { luabind::object componentState = getOwnerObject()->getTemplateObject(); if(componentState) { luabind::object CallBack = componentState[func]; if(CallBack) luabind::call_function<void>(CallBack,this->getOwnerObject()); // this } } } //end namespace
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 37 ] ] ]
d08928a6ff1d526057ba348fd8f380e3a288f069
c8ab6c440f0e70e848c5f69ccbbfd9fe2913fbad
/bowling/Ground.h
c5116bbe8bd7a94bc464640f067490f62e0a22c4
[]
no_license
alyshamsy/power-bowling
2b6426cfd4feb355928de95f1840bd39eb88de0b
dd650b2a8e146f6cdf7b6ce703801b96360a90fe
refs/heads/master
2020-12-24T16:50:09.092801
2011-05-12T14:37:15
2011-05-12T14:37:15
32,115,585
0
0
null
null
null
null
UTF-8
C++
false
false
520
h
#ifndef Ground_H #define Ground_H #include <gl/glfw.h> #include <cyclone/cyclone.h> #include "app.h" #include "timing.h" #include <iostream> #include <stdio.h> class Ground : public cyclone::CollisionBox { public: Ground(); ~Ground(); void render(GLuint texture); void setState(const cyclone::Vector3 &position, const cyclone::Quaternion &orientation, const cyclone::Vector3 &extents, const cyclone::Vector3 &velocity); void calculateMassProperties(cyclone::real invDensity); }; #endif
[ "aly.shamsy@71b57f4a-8c0b-a9ba-d1fe-6729e2c2215a" ]
[ [ [ 1, 23 ] ] ]
62268f8b319eb56fe98b9aa83f6ceb6341fdfafa
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/util/HashXMLCh.cpp
6bfbc393c7ee94ba9a742b71f6abd11d18ea5f8a
[]
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
1,205
cpp
/* * Copyright 1999-2000,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. */ #include <xercesc/util/HashXMLCh.hpp> #include <xercesc/util/XMLString.hpp> XERCES_CPP_NAMESPACE_BEGIN HashXMLCh::HashXMLCh() { } HashXMLCh::~HashXMLCh() { } unsigned int HashXMLCh::getHashVal(const void *const key, unsigned int mod , MemoryManager* const manager) { return XMLString::hash((XMLCh*)key, mod, manager); } bool HashXMLCh::equals(const void *const key1, const void *const key2) { return (XMLString::equals((XMLCh*)key1, (XMLCh*)key2)) ? true : false; } XERCES_CPP_NAMESPACE_END
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 41 ] ] ]
88c0b3104bf8f0dc65628b70fe444295772f6d89
49db059c239549a8691fda362adf0654c5749fb1
/2010/sitnikov/task4/mainwindow.h
a7967f8244276f8ec864a758ccc856418595a383
[]
no_license
bondarevts/amse-qt
1a063f27c45a80897bb4751ae5c10f5d9d80de1b
2b9b76c7a5576bc1079fc037adcf039fed4dc848
refs/heads/master
2020-05-07T21:19:48.773724
2010-12-07T07:53:51
2010-12-07T07:53:51
35,804,478
0
0
null
null
null
null
UTF-8
C++
false
false
824
h
#ifndef _MAINWINDOW_H_ #define _MAINWINDOW_H_ #include <QMainWindow> #include <QListWidget> #include <QLabel> #include <QAction> #include <QString> class CalcDialog; class MainWindow : public QMainWindow { Q_OBJECT; public: MainWindow(QWidget *parent = 0); private: void configureUI(); void updateStatusBar(); private slots: void file_open(); void file_save(); void file_revert(); void main_calculate(); void evaluated(QString expr, double result); private: QListWidget *list_; QLabel *fileName_; QLabel *result_; QAction *open_; QAction *save_; QAction *revert_; QAction *calculate_; QAction *exit_; CalcDialog *calculator_; QString openedFile_; double lastResult_; int revertState_; QString exprState_; double resultState_; }; #endif
[ "shuffle.c@1a14799f-55e9-4979-7f51-533a2053511e" ]
[ [ [ 1, 52 ] ] ]
c0532b4a3ed9092a1b68c0414b31ff4acd2ccffd
846aa9154f52672f48e2ce4bdeca33605186f682
/other/lenlook/lenlook.cpp
2bcc8e326742c5596869f0b767cb1571eedb0382
[]
no_license
FauxFaux/mbreports
5135cc5a8122b69efb3250d389b36c34021353d8
7d73ad4ddb6e511c92b6648808086a9bbda8e4f2
refs/heads/master
2021-01-23T13:49:07.212962
2011-01-02T20:33:59
2011-01-02T20:33:59
3,166,409
0
0
null
null
null
null
UTF-8
C++
false
false
1,263
cpp
#include "stdafx.h" using namespace boost; using namespace std; using namespace pqxx; typedef unsigned char tn_t; typedef unsigned long len_t; typedef unsigned long album_t; typedef map<tn_t, len_t> lens_t; boost::array<vector<int>, 99> t_m; int main() { try { connection conn("host=192.168.1.3 user=postgres dbname=musicbrainz_db"); cout << "Conntected..\n"; work T(conn, "readstuff"); cout << "Transacted..\n"; icursorstream ti(T, "select id,length from track", "one"); cout << "."; icursorstream ai(T, "select track,album,\"sequence\" from albumjoin", "two"); cout << "Queried..\n"; // for (result::const_iterator ti = track.begin(), ai = ajoin.begin(); ti != track.end() && ai != ajoin.end(); ++ti, ++ai) // cout << ti[0] << ai[0] << endl; map<album_t, lens_t> allen; result tr, ar; size_t counter = 0; while (ti >> tr && ai >> ar) { if (++counter > 5) { counter = 0; cout << "."; } const result::tuple& tt = tr[0], at = ar[0]; assert(at[0].as(0) == tt[0].as(0)); allen[at[1].as(0)][at[2].as(0)] = tt[1].as(0); } cout << allen.size(); return 0; } catch (std::exception &e) { cout << "Exception: " << e.what() << endl; } }
[ [ [ 1, 55 ] ] ]
e8e71cbaafaee052ea90f544cab6f2337431cfaa
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/EduNetGames/ModZoning/NetPedestrian.h
b125da1e2d9614904483d90c11960d3269096d91
[]
no_license
janfietz/edunetgames
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
04d787b0afca7c99b0f4c0692002b4abb8eea410
refs/heads/master
2016-09-10T19:24:04.051842
2011-04-17T11:00:09
2011-04-17T11:00:09
33,568,741
0
0
null
null
null
null
UTF-8
C++
false
false
4,409
h
#ifndef __NETPEDESTRIAN_H__ #define __NETPEDESTRIAN_H__ //----------------------------------------------------------------------------- // Copyright (c) 2009, Jan Fietz, Cyrus Preuss // 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 EduNetGames nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- //#include "EduNetCommon/EduNetCommon.h" #include "OpenSteerUT/OpenSteerUTTypes.h" #include "OpenSteerUT/AbstractVehicleUtilities.h" #include "OpenSteerUT/VehicleClassIds.h" #include "EduNetConnect/SimpleNetworkVehicle.h" //----------------------------------------------------------------------------- class NetPedestrian : public OpenSteer::SimpleNetworkVehicle { ET_DECLARE_BASE( SimpleNetworkVehicle ) public: NetPedestrian(); virtual ~NetPedestrian(); OS_IMPLEMENT_CLASSNAME( NetPedestrian ) //--------------------------------------------------------------------------- // AbstractNetSerializable interface virtual int serialize( RakNet::SerializeParameters *serializeParameters ) const; virtual void deserialize( RakNet::DeserializeParameters *deserializeParameters ); virtual void serializeConstruction(RakNet::BitStream *constructionBitstream); virtual bool deserializeConstruction(RakNet::BitStream *constructionBitstream ); virtual void reset( void ); virtual void update( const float currentTime, const float elapsedTime); virtual osVector3 determineCombinedSteering( const float elapsedTime ); virtual void draw( OpenSteer::AbstractRenderer*,const float currentTime, const float elapsedTime ); virtual void annotatePathFollowing( const osVector3& future, const osVector3& onPath, const osVector3& target, const float outside ); virtual void annotateAvoidCloseNeighbor( const AbstractVehicle& other, const float /*additionalDistance*/); virtual void annotateAvoidNeighbor (const AbstractVehicle& threat, const float /*steer*/, const osVector3& ourFuture, const osVector3& threatFuture ); virtual void annotateAvoidObstacle( const float minDistanceToCollision ); virtual AbstractVehicle* cloneVehicle( void ) const; virtual void setPath( OpenSteer::PolylineSegmentedPathwaySingleRadius* _path ) { this->path = _path; } private: OpenSteer::AVGroup m_kNeighbors; // path to be followed by this pedestrian // XXX Ideally this should be a generic Pathway, but we use the // XXX getTotalPathLength and radius methods (currently defined only // XXX on PolylinePathway) to set random initial positions. Could // XXX there be a "random position inside path" method on Pathway? OpenSteer::PolylineSegmentedPathwaySingleRadius* path; // direction for path following (upstream or downstream) int pathDirection; }; typedef OpenSteer::VehicleClassIdMixin<NetPedestrian, ET_CID_NETPEDESTRIAN> TNetPedestrian; #endif // __NETPEDESTRIAN_H__
[ "janfietz@localhost" ]
[ [ [ 1, 107 ] ] ]