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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4ab4fbcca6862053ef739e4f47aed73660ce3ccb | 0466568120485fcabdba5aa22a4b0fea13068b8b | /opencv/modules/highgui/test/test_ffmpeg.cpp | 510d6bb753bb919865b5156b6df4624b943614e2 | [] | no_license | coapp-packages/opencv | be25a9aec58d9ac890fc764932ba67914add078d | c78981e0d8f602fde523a82c3a7e2c3fef1f39bc | refs/heads/master | 2020-05-17T12:11:25.406742 | 2011-07-14T17:13:01 | 2011-07-14T17:13:01 | 2,048,483 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,096 | cpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
using namespace std;
class CV_FFmpegWriteBigImageTest : public cvtest::BaseTest
{
public:
void run(int)
{
try
{
ts->printf(cvtest::TS::LOG, "start reading bit image\n");
Mat img = imread(string(ts->get_data_path()) + "readwrite/read.png");
ts->printf(cvtest::TS::LOG, "finish reading bit image\n");
if (img.empty()) ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);
ts->printf(cvtest::TS::LOG, "start writing bit image\n");
imwrite(string(ts->get_data_path()) + "readwrite/write.png", img);
ts->printf(cvtest::TS::LOG, "finish writing bit image\n");
}
catch(...)
{
ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION);
}
ts->set_failed_test_info(cvtest::TS::OK);
}
};
class CV_FFmpegWriteBigVideoTest : public cvtest::BaseTest
{
public:
void run(int)
{
const int img_r = 4096;
const int img_c = 4096;
Size frame_s = Size(img_c, img_r);
const double fps = 30;
const double time_sec = 2;
const int coeff = static_cast<int>(static_cast<double>(cv::min(img_c, img_r)) / (fps * time_sec));
Mat img(img_r, img_c, CV_8UC3, Scalar::all(0));
try
{
VideoWriter writer(string(ts->get_data_path()) + "video/output.avi", CV_FOURCC('X', 'V', 'I', 'D'), fps, frame_s);
if (writer.isOpened() == false) ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION);
for (int i = 0 ; i < static_cast<int>(fps * time_sec); i++ )
{
//circle(img, Point2i(img_c / 2, img_r / 2), cv::min(img_r, img_c) / 2 * (i + 1), Scalar(255, 0, 0, 0), 2);
rectangle(img, Point2i(coeff * i, coeff * i), Point2i(coeff * (i + 1), coeff * (i + 1)),
Scalar::all(255 * (1.0 - static_cast<double>(i) / (fps * time_sec * 2) )), -1);
writer << img;
}
}
catch(...)
{
ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION);
}
ts->set_failed_test_info(cvtest::TS::OK);
}
};
string ext_from_int(int ext)
{
if (ext == 0) return ".png";
if (ext == 1) return ".bmp";
if (ext == 2) return ".pgm";
if (ext == 3) return ".tiff";
return "";
}
class CV_FFmpegWriteSequenceImageTest : public cvtest::BaseTest
{
public:
void run(int)
{
try
{
const int img_r = 640;
const int img_c = 480;
Size frame_s = Size(img_c, img_r);
for (size_t k = 1; k <= 5; ++k)
{
for (size_t ext = 0; ext < 4; ++ext) // 0 - png, 1 - bmp, 2 - pgm, 3 - tiff
for (size_t num_channels = 1; num_channels <= 3; num_channels+=2)
{
ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U, num_channels, ext_from_int(ext).c_str());
Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0));
circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255));
ts->printf(ts->LOG, "writing image : %s\n", string(string(ts->get_data_path()) + "readwrite/test" + ext_from_int(ext)).c_str());
imwrite(string(ts->get_data_path()) + "readwrite/test" + ext_from_int(ext), img);
ts->printf(ts->LOG, "reading test image : %s\n", string(string(ts->get_data_path()) + "readwrite/test" + ext_from_int(ext)).c_str());
Mat img_test = imread(string(ts->get_data_path()) + "readwrite/test" + ext_from_int(ext), CV_LOAD_IMAGE_UNCHANGED);
if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH);
CV_Assert(img.size() == img_test.size());
CV_Assert(img.type() == img_test.type());
double n = norm(img, img_test);
if ( n > 1.0)
{
ts->printf(ts->LOG, "norm = %f \n", n);
ts->set_failed_test_info(ts->FAIL_MISMATCH);
}
}
for (size_t num_channels = 1; num_channels <= 3; num_channels+=2)
{
// jpeg
ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U, num_channels, ".jpg");
Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0));
circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255));
string filename = string(ts->get_data_path() + "readwrite/test_" + char(k + 48) + "_c" + char(num_channels + 48) + "_.jpg");
imwrite(filename, img);
img = imread(filename, CV_LOAD_IMAGE_UNCHANGED);
filename = string(ts->get_data_path() + "readwrite/test_" + char(k + 48) + "_c" + char(num_channels + 48) + ".jpg");
ts->printf(ts->LOG, "reading test image : %s\n", filename.c_str());
Mat img_test = imread(filename, CV_LOAD_IMAGE_UNCHANGED);
if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH);
CV_Assert(img.size() == img_test.size());
CV_Assert(img.type() == img_test.type());
double n = norm(img, img_test);
if ( n > 1.0)
{
ts->printf(ts->LOG, "norm = %f \n", n);
ts->set_failed_test_info(ts->FAIL_MISMATCH);
}
}
for (size_t num_channels = 1; num_channels <= 3; num_channels+=2)
{
// tiff
ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_16U, num_channels, ".tiff");
Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_16U, num_channels), Scalar::all(0));
circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255));
string filename = string(ts->get_data_path() + "readwrite/test.tiff");
imwrite(filename, img);
ts->printf(ts->LOG, "reading test image : %s\n", filename.c_str());
Mat img_test = imread(filename, CV_LOAD_IMAGE_UNCHANGED);
if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH);
CV_Assert(img.size() == img_test.size());
ts->printf(ts->LOG, "img : %d ; %d \n", img.channels(), img.depth());
ts->printf(ts->LOG, "img_test : %d ; %d \n", img_test.channels(), img_test.depth());
CV_Assert(img.type() == img_test.type());
double n = norm(img, img_test);
if ( n > 1.0)
{
ts->printf(ts->LOG, "norm = %f \n", n);
ts->set_failed_test_info(ts->FAIL_MISMATCH);
}
}
}
}
catch(const cv::Exception & e)
{
ts->printf(ts->LOG, "Exception: %s\n" , e.what());
ts->set_failed_test_info(ts->FAIL_MISMATCH);
}
}
};
TEST(Highgui_FFmpeg_WriteBigImage, regression) { CV_FFmpegWriteBigImageTest test; test.safe_run(); }
TEST(Highgui_FFmpeg_WriteBigVideo, regression) { CV_FFmpegWriteBigVideoTest test; test.safe_run(); }
TEST(Highgui_FFmpeg_WriteSequenceImage, regression) { CV_FFmpegWriteSequenceImageTest test; test.safe_run(); }
| [
"morozov.andrey@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08",
"alekcac@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08"
] | [
[
[
1,
55
],
[
57,
57
],
[
59,
59
],
[
61,
61
],
[
63,
220
]
],
[
[
56,
56
],
[
58,
58
],
[
60,
60
],
[
62,
62
],
[
221,
221
]
]
] |
df1e56298e98426e16df06068c8be5315931dc7b | fe122f81ca7d6dff899945987f69305ada995cd7 | /developlib/vc60include/myGdiPlus.h | c881987befd0eff91aa4577fc41a8898692ac044 | [] | no_license | myeverytime/chtdependstoreroom | ddb9f4f98a6a403521aaf403d0b5f2dc5213f346 | 64a4d1e2d32abffaab0376f6377e10448b3c5bc3 | refs/heads/master | 2021-01-10T06:53:35.455736 | 2010-06-23T10:21:44 | 2010-06-23T10:21:44 | 50,168,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,156 | h | #define ULONG_PTR DWORD
//#include "GdiPlus.h"
//// Ensure that GdiPlus header files work properly with MFC DEBUG_NEW and STL header files.
#define iterator _iterator
#ifdef _DEBUG
namespace Gdiplus
{
namespace DllExports
{
#include "GdiplusMem.h"
};
#ifndef _GDIPLUSBASE_H
#define _GDIPLUSBASE_H
class GdiplusBase
{
public:
void (operator delete)(void* in_pVoid)
{
DllExports::GdipFree(in_pVoid);
}
void* (operator new)(size_t in_size)
{
return DllExports::GdipAlloc(in_size);
}
void (operator delete[])(void* in_pVoid)
{
DllExports::GdipFree(in_pVoid);
}
void* (operator new[])(size_t in_size)
{
return DllExports::GdipAlloc(in_size);
}
void * (operator new)(size_t nSize, LPCSTR lpszFileName, int nLine)
{
return DllExports::GdipAlloc(nSize);
}
void operator delete(void* p, LPCSTR lpszFileName, int nLine)
{
DllExports::GdipFree(p);
}
};
#endif // #ifndef _GDIPLUSBASE_H
}
#endif // #ifdef _DEBUG
#include "GdiPlus.h"
#undef iterator
//// Ensure that Gdiplus.lib is linked.
#pragma comment(lib, "gdiplus.lib")
| [
"robustwell@bd7e636a-136b-06c9-ecb0-b59307166256"
] | [
[
[
1,
58
]
]
] |
02ed8f39b5c22b0e9e9e4aa20592e51f1a3b750b | 6996a66a1a3434203d0b9a6433902654c41309c8 | /Formation.h | d7c91257b90a1dde603939083e6996f2a22fc9a7 | [] | no_license | dtbinh/CATALST-Robot-Formations-Simulator | 83509eba833f20f56311078049038da866d0b5a5 | f389557358588dcdf60c058c5ac0b55a5d2a7ae5 | refs/heads/master | 2020-05-29T08:45:57.510135 | 2011-06-29T08:54:27 | 2011-06-29T08:54:27 | 69,551,189 | 1 | 0 | null | 2016-09-29T09:12:48 | 2016-09-29T09:12:47 | null | UTF-8 | C++ | false | false | 3,900 | h | //
// Filename: "Formation.h"
//
// Programmer: Ross Mead
// Last modified: 30Nov2009
//
// Description: This class describes a formation.
//
// preprocessor directives
#ifndef FORMATION_H
#define FORMATION_H
#include <vector>
#include "Relationship.h"
using namespace std;
// mathematical functional type redefinition
typedef GLfloat (*Function)(const GLfloat);
// global constants
static const Function DEFAULT_FORMATION_FUNCTION = NULL;
static const GLfloat DEFAULT_FORMATION_RADIUS = 1.0f;
static const GLdouble X_ROOT_THRESHOLD = 5E-7;
static const GLint X_N_ITERATIONS = 100;
// describes a formation
class Formation: protected vector<Function>
{
public:
// <constructors>
Formation(Function f = DEFAULT_FORMATION_FUNCTION,
const GLfloat r = DEFAULT_FORMATION_RADIUS,
const Vector sGrad = Vector(),
const GLint sID = ID_BROADCAST,
const GLint fID = -1,
const GLfloat theta = 0.0f);
Formation(vector<Function> f,
const GLfloat r = DEFAULT_FORMATION_RADIUS,
const Vector sGrad = Vector(),
const GLint sID = ID_BROADCAST,
const GLint fID = -1,
const GLfloat theta = 0.0f);
Formation(const Formation &f);
// <public mutator functions>
bool setFunction(const Function f = DEFAULT_FORMATION_FUNCTION);
bool setFunctions(const vector<Function> &f);
bool addFunction(const Function f = DEFAULT_FORMATION_FUNCTION);
bool addFunctions(const vector<Function> &f);
bool removeFunction(const GLint pos = 0);
bool removeFunctions();
bool setRadius(const GLfloat r = DEFAULT_FORMATION_RADIUS);
bool setSeedGradient(const Vector sGrad = Vector());
bool setSeedID(const GLint sID = ID_BROADCAST);
bool setFormationID(const GLint fID = -1);
bool setHeading(const GLfloat theta = 0.0f);
// <public accessor functions>
Function getFunction(const GLint pos = 0) const;
vector<Function> getFunctions() const;
GLfloat getRadius() const;
Vector getSeedGradient() const;
GLint getSeedID() const;
GLint getFormationID() const;
GLfloat getHeading() const;
// <public utility functions>
vector<Vector> getRelationships(const Vector c = Vector());
Vector getRelationship(const Function f = DEFAULT_FORMATION_FUNCTION,
const GLfloat r = DEFAULT_FORMATION_RADIUS,
const Vector c = Vector(),
const GLfloat theta = 0.0f);
Vector getRelationship(const GLint pos = 0,
const GLfloat r = DEFAULT_FORMATION_RADIUS,
const Vector c = Vector(),
const GLfloat theta = 0.0f);
// <virtual overloaded operators>
virtual Formation& operator =(const Formation &f);
// <protected data members>
GLfloat radius, heading;
protected:
Vector seedGradient;
GLint seedID, formationID;
// <protected utility functions>
GLfloat fIntersect(const Function f = DEFAULT_FORMATION_FUNCTION,
const GLfloat r = DEFAULT_FORMATION_RADIUS,
const Vector c = Vector(),
const GLfloat x = 0.0f);
}; // Formation
#endif
| [
"rossmead@larry.(none)",
"[email protected]"
] | [
[
[
1,
91
],
[
93,
103
]
],
[
[
92,
92
]
]
] |
2b08a8611815d1f4a7e9a041ef409fcfe8aba077 | 08fe7d2be6b5c933d5e3223f726c34d38e56d332 | /programas/diversos/matriz-vizinhanca/Grafo.h | fdb96c688aa0821a47a60d40dc40e9eb3d9517ec | [] | no_license | ivancrneto/fesc | 5adcfb7acb78ed7d2690fcaabb707bb93adcd52a | 9fd0dcc019374f65b835b6a5363ad65d4abca25d | refs/heads/master | 2020-04-06T06:43:30.803037 | 2009-10-06T04:56:58 | 2009-10-06T04:56:58 | 102,975 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,175 | h | #ifndef GRAFO_H_
#define GRAFO_H_
#include <vector>
#include <queue>
#include <stack>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::queue;
using std::stack;
class Grafo {
public:
Grafo();
Grafo( int );
void add_vertice( char );
void add_aresta( int, int );
int existe_vertice( char );
int v_adjacente( char, char );
int v_adjacente( int, int );
void operator =( Grafo );
void operator =(Grafo*);
char vertice( int );
void imprimir_m_adj();
void def_cintura();
virtual ~Grafo();
int* busca_largura( void (*funcao)(int,int*), int v );
int* busca_profundidade( void (*funcao)(int,int*), int v );
vector<int> cintura;
int tam_cintura;
void setN(int);
int getN();
int getM();
int** getArestas();
void removeAresta(int, int);
vector<char> getVertices();
private:
vector<char> vertices;
queue<int> fila_busca;
stack<int> pilha_busca;
int **arestas;
int N;
int M;
int inicio_cintura;
int* busca_largura( void (Grafo::*funcao)(int,int*), int v );
int* busca_profundidade( void (Grafo::*funcao)(int,int*), int v );
void def_cintura_f_bruta( int, int* );
};
#endif // GRAFO_H_
| [
"[email protected]"
] | [
[
[
1,
56
]
]
] |
4eea6dcd899b14f0145ca5883a9fc6d76446fe44 | 097718ad5b708ce1d628b3b1c21ddc08428a5555 | /mfct/main.cpp | 2ce4b954727c90e4b1b7299122a1051759ca1545 | [] | no_license | breakingthings/mfct | 49c1d0a29ba0a0ff06ef434bec50b29b80136260 | efe5cf0ccedad98f342cd4acbfda117189f80648 | refs/heads/master | 2021-01-01T16:40:24.011737 | 2011-09-12T21:35:53 | 2011-09-12T21:35:53 | 2,326,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 485 | cpp | #include "stdafx.h"
#include "maindialog.h"
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
class MyApp : public CWinApp
{
CWnd *m_pMainWnd;
public:
MyApp()
{
#ifdef _DEBUG
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
}
~MyApp()
{
}
BOOL InitInstance()
{
Session::InitDB();
MainDialog dlg;
m_pMainWnd = &dlg;
dlg.DoModal();
return TRUE;
}
};
MyApp app;
| [
"[email protected]"
] | [
[
[
1,
37
]
]
] |
2e47077d3806128728c780e76b1d9b3dd86668d9 | d7320c9c1f155e2499afa066d159bfa6aa94b432 | /ghostgproxy/ghostdb.cpp | 1f66029acfd0a0b63b0fb052059cdbddc39a8f84 | [] | no_license | HOST-PYLOS/ghostnordicleague | c44c804cb1b912584db3dc4bb811f29f3761a458 | 9cb262d8005dda0150b75d34b95961d664b1b100 | refs/heads/master | 2016-09-05T10:06:54.279724 | 2011-02-23T08:02:50 | 2011-02-23T08:02:50 | 32,241,503 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 22,656 | cpp | /*
Copyright [2008] [Trevor Hogan]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/
*/
#include "ghost.h"
#include "util.h"
#include "config.h"
#include "ghostdb.h"
#include "packed.h"
#include "replay.h"
#include "gameprotocol.h"
//
// CGHostDB
//
CGHostDB :: CGHostDB( CConfig *CFG )
{
m_HasError = false;
}
CGHostDB :: ~CGHostDB( )
{
}
void CGHostDB :: RecoverCallable( CBaseCallable *callable )
{
}
bool CGHostDB :: Begin( )
{
return true;
}
bool CGHostDB :: Commit( )
{
return true;
}
//
// nordicleague
//
uint32_t CGHostDB :: RegisterPlayerAdd( string name, string email, string ip )
{
return 0;
}
uint32_t CGHostDB :: DotAEventAdd( uint32_t gameid, string gamename, string killer, string victim, uint32_t kcolour, uint32_t vcolour )
{
return 0;
}
bool CGHostDB :: UpdateGameInfo( string name, uint32_t players, bool ispublic, vector<string> m_Slots )
{
return false;
}
bool CGHostDB :: SaveReplay( CReplay *replay )
{
return false;
}
CCallableDotAEventAdd *CGHostDB :: ThreadedDotAEventAdd( uint32_t gameid, string gamename, string killer, string victim, uint32_t kcolour, uint32_t vcolour )
{
return NULL;
}
CCallableUpdateGameInfo *CGHostDB :: ThreadedUpdateGameInfo( string name, uint32_t players, bool ispublic, vector<string> m_Slots)
{
return NULL;
}
CDBLastSeenPlayer *CGHostDB :: LastSeenPlayer( string name )
{
return NULL;
}
CCallableLastSeenPlayer *CGHostDB :: ThreadedLastSeenPlayer( string name )
{
return NULL;
}
CCallableSaveReplay *CGHostDB :: ThreadedSaveReplay( CReplay *replay )
{
return NULL;
}
set<string> CGHostDB :: CountrySkipList()
{
return set<string>( );
}
CCallableCountrySkipList *CGHostDB :: ThreadedCountrySkipList( )
{
return NULL;
}
set<VouchPair> CGHostDB :: VouchList( )
{
return set<VouchPair>( );
}
CCallableVouchList *CGHostDB :: ThreadedVouchList( )
{
return NULL;
}
CCallableRegisterPlayerAdd :: ~CCallableRegisterPlayerAdd( )
{
}
CCallableDotAEventAdd :: ~CCallableDotAEventAdd( )
{
}
CCallableUpdateGameInfo :: ~CCallableUpdateGameInfo( )
{
}
CCallableLastSeenPlayer :: ~CCallableLastSeenPlayer( )
{
}
CCallableSaveReplay :: ~CCallableSaveReplay( )
{
}
CCallableCountrySkipList :: ~CCallableCountrySkipList()
{
}
CCallableVouchList :: ~CCallableVouchList()
{
}
//
// end
//
uint32_t CGHostDB :: AdminCount( string server )
{
return 0;
}
bool CGHostDB :: AdminCheck( string server, string user )
{
return false;
}
bool CGHostDB :: AdminAdd( string server, string user )
{
return false;
}
bool CGHostDB :: AdminRemove( string server, string user )
{
return false;
}
vector<string> CGHostDB :: AdminList( string server )
{
return vector<string>( );
}
uint32_t CGHostDB :: BanCount( string server )
{
return 0;
}
CDBBan *CGHostDB :: BanCheck( string server, string user, string ip )
{
return NULL;
}
bool CGHostDB :: BanAdd( string server, string user, string ip, string gamename, string admin, string reason, uint32_t bantime, uint32_t ipban )
{
return false;
}
bool CGHostDB :: BanRemove( string server, string user, string admin, string reason )
{
return false;
}
bool CGHostDB :: BanRemove( string user, string admin, string reason )
{
return false;
}
vector<CDBBan *> CGHostDB :: BanList( string server )
{
return vector<CDBBan *>( );
}
uint32_t CGHostDB :: GameAdd( string server, string map, string gamename, string ownername, uint32_t duration, uint32_t gamestate, string creatorname, string creatorserver )
{
return 0;
}
uint32_t CGHostDB :: GamePlayerAdd( uint32_t gameid, string name, string ip, uint32_t spoofed, string spoofedrealm, uint32_t reserved, uint32_t loadingtime, uint32_t left, string leftreason, uint32_t team, uint32_t colour )
{
return 0;
}
uint32_t CGHostDB :: GamePlayerCount( string name )
{
return 0;
}
CDBGamePlayerSummary *CGHostDB :: GamePlayerSummaryCheck( string name )
{
return NULL;
}
uint32_t CGHostDB :: DotAGameAdd( uint32_t gameid, uint32_t winner, uint32_t min, uint32_t sec )
{
return 0;
}
uint32_t CGHostDB :: DotAPlayerAdd( uint32_t gameid, string name, uint32_t colour, uint32_t kills, uint32_t deaths, uint32_t creepkills, uint32_t creepdenies, uint32_t assists, uint32_t gold, uint32_t neutralkills, string item1, string item2, string item3, string item4, string item5, string item6, string hero, uint32_t newcolour, uint32_t towerkills, uint32_t raxkills, uint32_t courierkills, uint32_t outcome, uint32_t level, uint32_t apm )
{
return 0;
}
uint32_t CGHostDB :: DotAPlayerCount( string name )
{
return 0;
}
CDBDotAPlayerSummary *CGHostDB :: DotAPlayerSummaryCheck( string name )
{
return NULL;
}
string CGHostDB :: FromCheck( uint32_t ip )
{
return "??";
}
bool CGHostDB :: FromAdd( uint32_t ip1, uint32_t ip2, string country )
{
return false;
}
bool CGHostDB :: DownloadAdd( string map, uint32_t mapsize, string name, string ip, uint32_t spoofed, string spoofedrealm, uint32_t downloadtime )
{
return false;
}
uint32_t CGHostDB :: W3MMDPlayerAdd( string category, uint32_t gameid, uint32_t pid, string name, string flag, uint32_t leaver, uint32_t practicing )
{
return 0;
}
bool CGHostDB :: W3MMDVarAdd( uint32_t gameid, map<VarP,int32_t> var_ints )
{
return false;
}
bool CGHostDB :: W3MMDVarAdd( uint32_t gameid, map<VarP,double> var_reals )
{
return false;
}
bool CGHostDB :: W3MMDVarAdd( uint32_t gameid, map<VarP,string> var_strings )
{
return false;
}
void CGHostDB :: CreateThread( CBaseCallable *callable )
{
callable->SetReady( true );
}
CCallableAdminCount *CGHostDB :: ThreadedAdminCount( string server )
{
return NULL;
}
CCallableAdminCheck *CGHostDB :: ThreadedAdminCheck( string server, string user )
{
return NULL;
}
CCallableAdminAdd *CGHostDB :: ThreadedAdminAdd( string server, string user )
{
return NULL;
}
CCallableAdminRemove *CGHostDB :: ThreadedAdminRemove( string server, string user )
{
return NULL;
}
CCallableAdminList *CGHostDB :: ThreadedAdminList( string server )
{
return NULL;
}
CCallableBanCount *CGHostDB :: ThreadedBanCount( string server )
{
return NULL;
}
CCallableBanCheck *CGHostDB :: ThreadedBanCheck( string server, string user, string ip )
{
return NULL;
}
CCallableBanAdd *CGHostDB :: ThreadedBanAdd( string server, string user, string ip, string gamename, string admin, string reason, uint32_t bantime, uint32_t ipban )
{
return NULL;
}
CCallableBanRemove *CGHostDB :: ThreadedBanRemove( string server, string user, string admin, string reason )
{
return NULL;
}
CCallableBanRemove *CGHostDB :: ThreadedBanRemove( string user, string admin, string reason )
{
return NULL;
}
CCallableBanList *CGHostDB :: ThreadedBanList( string server )
{
return NULL;
}
CCallableGameAdd *CGHostDB :: ThreadedGameAdd( string server, string map, string gamename, string ownername, uint32_t duration, uint32_t gamestate, string creatorname, string creatorserver, vector<string> chatlog )
{
return NULL;
}
CCallableGamePlayerAdd *CGHostDB :: ThreadedGamePlayerAdd( uint32_t gameid, string name, string ip, uint32_t spoofed, string spoofedrealm, uint32_t reserved, uint32_t loadingtime, uint32_t left, string leftreason, uint32_t team, uint32_t colour )
{
return NULL;
}
CCallableGamePlayerSummaryCheck *CGHostDB :: ThreadedGamePlayerSummaryCheck( string name, uint32_t season )
{
return NULL;
}
CCallableDotAGameAdd *CGHostDB :: ThreadedDotAGameAdd( uint32_t gameid, uint32_t winner, uint32_t min, uint32_t sec )
{
return NULL;
}
CCallableDotAPlayerAdd *CGHostDB :: ThreadedDotAPlayerAdd( uint32_t gameid, string name, uint32_t colour, uint32_t kills, uint32_t deaths, uint32_t creepkills, uint32_t creepdenies, uint32_t assists, uint32_t gold, uint32_t neutralkills, string item1, string item2, string item3, string item4, string item5, string item6, string hero, uint32_t newcolour, uint32_t towerkills, uint32_t raxkills, uint32_t courierkills, uint32_t outcome, uint32_t level, uint32_t apm )
{
return NULL;
}
CCallableDotAPlayerSummaryCheck *CGHostDB :: ThreadedDotAPlayerSummaryCheck( string name, uint32_t season )
{
return NULL;
}
CCallableDownloadAdd *CGHostDB :: ThreadedDownloadAdd( string map, uint32_t mapsize, string name, string ip, uint32_t spoofed, string spoofedrealm, uint32_t downloadtime )
{
return NULL;
}
CCallableScoreCheck *CGHostDB :: ThreadedScoreCheck( string category, string name, string server, uint32_t season )
{
return NULL;
}
CCallableW3MMDPlayerAdd *CGHostDB :: ThreadedW3MMDPlayerAdd( string category, uint32_t gameid, uint32_t pid, string name, string flag, uint32_t leaver, uint32_t practicing )
{
return NULL;
}
CCallableW3MMDVarAdd *CGHostDB :: ThreadedW3MMDVarAdd( uint32_t gameid, map<VarP,int32_t> var_ints )
{
return NULL;
}
CCallableW3MMDVarAdd *CGHostDB :: ThreadedW3MMDVarAdd( uint32_t gameid, map<VarP,double> var_reals )
{
return NULL;
}
CCallableW3MMDVarAdd *CGHostDB :: ThreadedW3MMDVarAdd( uint32_t gameid, map<VarP,string> var_strings )
{
return NULL;
}
CCallableRegisterPlayerAdd *CGHostDB :: ThreadedRegisterPlayerAdd( string name, string email, string ip )
{
return NULL;
}
//
// Callables
//
void CBaseCallable :: Init( )
{
m_StartTicks = GetTicks( );
}
void CBaseCallable :: Close( )
{
m_EndTicks = GetTicks( );
m_Ready = true;
}
CCallableAdminCount :: ~CCallableAdminCount( )
{
}
CCallableAdminCheck :: ~CCallableAdminCheck( )
{
}
CCallableAdminAdd :: ~CCallableAdminAdd( )
{
}
CCallableAdminRemove :: ~CCallableAdminRemove( )
{
}
CCallableAdminList :: ~CCallableAdminList( )
{
}
CCallableBanCount :: ~CCallableBanCount( )
{
}
CCallableBanCheck :: ~CCallableBanCheck( )
{
delete m_Result;
}
CCallableBanAdd :: ~CCallableBanAdd( )
{
}
CCallableBanRemove :: ~CCallableBanRemove( )
{
}
CCallableBanList :: ~CCallableBanList( )
{
// don't delete anything in m_Result here, it's the caller's responsibility
}
CCallableGameAdd :: ~CCallableGameAdd( )
{
}
CCallableGamePlayerAdd :: ~CCallableGamePlayerAdd( )
{
}
CCallableGamePlayerSummaryCheck :: ~CCallableGamePlayerSummaryCheck( )
{
delete m_Result;
}
CCallableDotAGameAdd :: ~CCallableDotAGameAdd( )
{
}
CCallableDotAPlayerAdd :: ~CCallableDotAPlayerAdd( )
{
}
CCallableDotAPlayerSummaryCheck :: ~CCallableDotAPlayerSummaryCheck( )
{
delete m_Result;
}
CCallableDownloadAdd :: ~CCallableDownloadAdd( )
{
}
CCallableScoreCheck :: ~CCallableScoreCheck( )
{
}
CCallableW3MMDPlayerAdd :: ~CCallableW3MMDPlayerAdd( )
{
}
CCallableW3MMDVarAdd :: ~CCallableW3MMDVarAdd( )
{
}
//
// CDBBan
//
CDBBan :: CDBBan( string nServer, string nName, string nIP, string nDate, string nGameName, string nAdmin, string nReason )
{
m_Server = nServer;
m_Name = nName;
m_IP = nIP;
m_Date = nDate;
m_GameName = nGameName;
m_Admin = nAdmin;
m_Reason = nReason;
m_IPBan = false;
}
CDBBan :: CDBBan( string nServer, string nName, string nIP, string nDate, string nGameName, string nAdmin, string nReason, string nExpires )
{
m_Server = nServer;
m_Name = nName;
m_IP = nIP;
m_Date = nDate;
m_GameName = nGameName;
m_Admin = nAdmin;
m_Reason = nReason;
m_IPBan = false;
m_Expires = nExpires;
}
CDBBan :: CDBBan( string nServer, string nName, string nIP, string nDate, string nGameName, string nAdmin, string nReason, uint32_t nIPBan )
{
m_Server = nServer;
m_Name = nName;
m_IP = nIP;
m_Date = nDate;
m_GameName = nGameName;
m_Admin = nAdmin;
m_Reason = nReason;
if (nIPBan == 0)
m_IPBan = false;
else
m_IPBan = true;
}
CDBBan :: CDBBan( string nServer, string nName, string nIP, string nDate, string nGameName, string nAdmin, string nReason, uint32_t nIPBan, string nExpires )
{
m_Server = nServer;
m_Name = nName;
m_IP = nIP;
m_Date = nDate;
m_GameName = nGameName;
m_Admin = nAdmin;
m_Reason = nReason;
if (nIPBan == 0)
m_IPBan = false;
else
m_IPBan = true;
m_Expires = nExpires;
}
CDBBan :: ~CDBBan( )
{
}
//
// CDBGame
//
CDBGame :: CDBGame( uint32_t nID, string nServer, string nMap, string nDateTime, string nGameName, string nOwnerName, uint32_t nDuration )
{
m_ID = nID;
m_Server = nServer;
m_Map = nMap;
m_DateTime = nDateTime;
m_GameName = nGameName;
m_OwnerName = nOwnerName;
m_Duration = nDuration;
}
CDBGame :: ~CDBGame( )
{
}
//
// CDBGamePlayer
//
CDBGamePlayer :: CDBGamePlayer( uint32_t nID, uint32_t nGameID, string nName, string nIP, uint32_t nSpoofed, string nSpoofedRealm, uint32_t nReserved, uint32_t nLoadingTime, uint32_t nLeft, string nLeftReason, uint32_t nTeam, uint32_t nColour )
{
m_ID = nID;
m_GameID = nGameID;
m_Name = nName;
m_IP = nIP;
m_Spoofed = nSpoofed;
m_SpoofedRealm = nSpoofedRealm;
m_Reserved = nReserved;
m_LoadingTime = nLoadingTime;
m_Left = nLeft;
m_LeftReason = nLeftReason;
m_Team = nTeam;
m_Colour = nColour;
}
CDBGamePlayer :: ~CDBGamePlayer( )
{
}
//
// CDBGamePlayerSummary
//
CDBGamePlayerSummary :: CDBGamePlayerSummary( string nServer, string nName, string nFirstGameDateTime, string nLastGameDateTime, uint32_t nTotalGames, uint32_t nMinLoadingTime, uint32_t nAvgLoadingTime, uint32_t nMaxLoadingTime, uint32_t nMinLeftPercent, uint32_t nAvgLeftPercent, uint32_t nMaxLeftPercent, uint32_t nMinDuration, uint32_t nAvgDuration, uint32_t nMaxDuration )
{
m_Server = nServer;
m_Name = nName;
m_FirstGameDateTime = nFirstGameDateTime;
m_LastGameDateTime = nLastGameDateTime;
m_TotalGames = nTotalGames;
m_MinLoadingTime = nMinLoadingTime;
m_AvgLoadingTime = nAvgLoadingTime;
m_MaxLoadingTime = nMaxLoadingTime;
m_MinLeftPercent = nMinLeftPercent;
m_AvgLeftPercent = nAvgLeftPercent;
m_MaxLeftPercent = nMaxLeftPercent;
m_MinDuration = nMinDuration;
m_AvgDuration = nAvgDuration;
m_MaxDuration = nMaxDuration;
m_Vouched = false;
m_VouchedBy.clear();
m_AllTotalGames = 0;
}
CDBGamePlayerSummary :: CDBGamePlayerSummary( string nServer, string nName, string nFirstGameDateTime, string nLastGameDateTime, uint32_t nTotalGames, uint32_t nMinLoadingTime, uint32_t nAvgLoadingTime, uint32_t nMaxLoadingTime, uint32_t nMinLeftPercent, uint32_t nAvgLeftPercent, uint32_t nMaxLeftPercent, uint32_t nMinDuration, uint32_t nAvgDuration, uint32_t nMaxDuration, bool nVouched, string nVouchedBy )
{
m_Server = nServer;
m_Name = nName;
m_FirstGameDateTime = nFirstGameDateTime;
m_LastGameDateTime = nLastGameDateTime;
m_TotalGames = nTotalGames;
m_MinLoadingTime = nMinLoadingTime;
m_AvgLoadingTime = nAvgLoadingTime;
m_MaxLoadingTime = nMaxLoadingTime;
m_MinLeftPercent = nMinLeftPercent;
m_AvgLeftPercent = nAvgLeftPercent;
m_MaxLeftPercent = nMaxLeftPercent;
m_MinDuration = nMinDuration;
m_AvgDuration = nAvgDuration;
m_MaxDuration = nMaxDuration;
m_Vouched = nVouched;
m_VouchedBy = nVouchedBy;
m_AllTotalGames = 0;
}
CDBGamePlayerSummary :: ~CDBGamePlayerSummary( )
{
}
//
// CDBDotAGame
//
CDBDotAGame :: CDBDotAGame( uint32_t nID, uint32_t nGameID, uint32_t nWinner, uint32_t nMin, uint32_t nSec )
{
m_ID = nID;
m_GameID = nGameID;
m_Winner = nWinner;
m_Min = nMin;
m_Sec = nSec;
}
CDBDotAGame :: ~CDBDotAGame( )
{
}
//
// CDBDotAPlayer
//
CDBDotAPlayer :: CDBDotAPlayer( )
{
m_ID = 0;
m_GameID = 0;
m_Colour = 0;
m_Kills = 0;
m_Deaths = 0;
m_CreepKills = 0;
m_CreepDenies = 0;
m_Assists = 0;
m_Gold = 0;
m_NeutralKills = 0;
m_NewColour = 0;
m_TowerKills = 0;
m_RaxKills = 0;
m_CourierKills = 0;
m_Rank = 0;
m_Score = 1000;
m_Outcome = 0;
m_Level = 1;
m_Apm = 0;
}
CDBDotAPlayer :: CDBDotAPlayer( uint32_t nID, string nName, uint32_t nGameID, uint32_t nColour, uint32_t nKills, uint32_t nDeaths, uint32_t nCreepKills, uint32_t nCreepDenies, uint32_t nAssists, uint32_t nGold, uint32_t nNeutralKills, string nItem1, string nItem2, string nItem3, string nItem4, string nItem5, string nItem6, string nHero, uint32_t nNewColour, uint32_t nTowerKills, uint32_t nRaxKills, uint32_t nCourierKills, uint32_t nOutcome, uint32_t nLevel, uint32_t nApm )
{
m_ID = nID;
m_GameID = nGameID;
m_Colour = nColour;
m_Kills = nKills;
m_Deaths = nDeaths;
m_CreepKills = nCreepKills;
m_CreepDenies = nCreepDenies;
m_Assists = nAssists;
m_Gold = nGold;
m_NeutralKills = nNeutralKills;
m_Items[0] = nItem1;
m_Items[1] = nItem2;
m_Items[2] = nItem3;
m_Items[3] = nItem4;
m_Items[4] = nItem5;
m_Items[5] = nItem6;
m_Hero = nHero;
m_NewColour = nNewColour;
m_TowerKills = nTowerKills;
m_RaxKills = nRaxKills;
m_CourierKills = nCourierKills;
m_Outcome = 0;
m_Name = nName;
m_Level = nLevel;
m_Apm = nApm;
}
CDBDotAPlayer :: CDBDotAPlayer( uint32_t nID, string nName, uint32_t nGameID,uint32_t nColour, uint32_t nKills, uint32_t nDeaths, uint32_t nCreepKills, uint32_t nCreepDenies, uint32_t nAssists, uint32_t nGold, uint32_t nNeutralKills, string nItem1, string nItem2, string nItem3, string nItem4, string nItem5, string nItem6, string nHero, uint32_t nNewColour, uint32_t nTowerKills, uint32_t nRaxKills, uint32_t nCourierKills, uint32_t nRank, uint32_t nScore, uint32_t nOutcome, uint32_t nLevel, uint32_t nApm )
{
m_ID = nID;
m_GameID = nGameID;
m_Colour = nColour;
m_Kills = nKills;
m_Deaths = nDeaths;
m_CreepKills = nCreepKills;
m_CreepDenies = nCreepDenies;
m_Assists = nAssists;
m_Gold = nGold;
m_NeutralKills = nNeutralKills;
m_Items[0] = nItem1;
m_Items[1] = nItem2;
m_Items[2] = nItem3;
m_Items[3] = nItem4;
m_Items[4] = nItem5;
m_Items[5] = nItem6;
m_Hero = nHero;
m_NewColour = nNewColour;
m_TowerKills = nTowerKills;
m_RaxKills = nRaxKills;
m_CourierKills = nCourierKills;
m_Rank = nRank;
m_Score = nScore;
m_Outcome = nOutcome;
m_Name = nName;
m_Level = nLevel;
m_Apm = nApm;
}
CDBDotAPlayer :: ~CDBDotAPlayer( )
{
}
string CDBDotAPlayer :: GetItem( unsigned int i )
{
if( i < 6 )
return m_Items[i];
return string( );
}
void CDBDotAPlayer :: SetItem( unsigned int i, string item )
{
if( i < 6 )
m_Items[i] = item;
}
//
// CDBDotAPlayerSummary
//
CDBDotAPlayerSummary :: CDBDotAPlayerSummary( string nServer, string nName, uint32_t nTotalGames, uint32_t nTotalWins, uint32_t nTotalLosses, uint32_t nTotalKills, uint32_t nTotalDeaths, uint32_t nTotalCreepKills, uint32_t nTotalCreepDenies, uint32_t nTotalAssists, uint32_t nTotalNeutralKills, uint32_t nTotalTowerKills, uint32_t nTotalRaxKills, uint32_t nTotalCourierKills )
{
m_Server = nServer;
m_Name = nName;
m_TotalGames = nTotalGames;
m_TotalWins = nTotalWins;
m_TotalLosses = nTotalLosses;
m_TotalKills = nTotalKills;
m_TotalDeaths = nTotalDeaths;
m_TotalCreepKills = nTotalCreepKills;
m_TotalCreepDenies = nTotalCreepDenies;
m_TotalAssists = nTotalAssists;
m_TotalNeutralKills = nTotalNeutralKills;
m_TotalTowerKills = nTotalTowerKills;
m_TotalRaxKills = nTotalRaxKills;
m_TotalCourierKills = nTotalCourierKills;
m_Score = 0;
m_Rank = 0;
m_Streak = 0;
}
CDBDotAPlayerSummary :: CDBDotAPlayerSummary( string nServer, string nName, uint32_t nTotalGames, uint32_t nTotalWins, uint32_t nTotalLosses, uint32_t nTotalKills, uint32_t nTotalDeaths, uint32_t nTotalCreepKills, uint32_t nTotalCreepDenies, uint32_t nTotalAssists, uint32_t nTotalNeutralKills, uint32_t nTotalTowerKills, uint32_t nTotalRaxKills, uint32_t nTotalCourierKills, uint32_t nRank, double nScore)
{
m_Server = nServer;
m_Name = nName;
m_TotalGames = nTotalGames;
m_TotalWins = nTotalWins;
m_TotalLosses = nTotalLosses;
m_TotalKills = nTotalKills;
m_TotalDeaths = nTotalDeaths;
m_TotalCreepKills = nTotalCreepKills;
m_TotalCreepDenies = nTotalCreepDenies;
m_TotalAssists = nTotalAssists;
m_TotalNeutralKills = nTotalNeutralKills;
m_TotalTowerKills = nTotalTowerKills;
m_TotalRaxKills = nTotalRaxKills;
m_TotalCourierKills = nTotalCourierKills;
m_Rank = nRank;
m_Score = nScore;
m_Streak = 0;
}
CDBDotAPlayerSummary :: CDBDotAPlayerSummary( string nServer, string nName, uint32_t nTotalGames, uint32_t nTotalWins, uint32_t nTotalLosses, uint32_t nTotalKills, uint32_t nTotalDeaths, uint32_t nTotalCreepKills, uint32_t nTotalCreepDenies, uint32_t nTotalAssists, uint32_t nTotalNeutralKills, uint32_t nTotalTowerKills, uint32_t nTotalRaxKills, uint32_t nTotalCourierKills, uint32_t nRank, double nScore, uint32_t nStreak)
{
m_Server = nServer;
m_Name = nName;
m_TotalGames = nTotalGames;
m_TotalWins = nTotalWins;
m_TotalLosses = nTotalLosses;
m_TotalKills = nTotalKills;
m_TotalDeaths = nTotalDeaths;
m_TotalCreepKills = nTotalCreepKills;
m_TotalCreepDenies = nTotalCreepDenies;
m_TotalAssists = nTotalAssists;
m_TotalNeutralKills = nTotalNeutralKills;
m_TotalTowerKills = nTotalTowerKills;
m_TotalRaxKills = nTotalRaxKills;
m_TotalCourierKills = nTotalCourierKills;
m_Rank = nRank;
m_Score = nScore;
m_Streak = nStreak;
}
CDBDotAPlayerSummary :: ~CDBDotAPlayerSummary( )
{
}
CDBLastSeenPlayer :: CDBLastSeenPlayer( bool nSeen, string nName )
{
m_Seen = nSeen;
m_Name = nName;
}
CDBLastSeenPlayer :: CDBLastSeenPlayer( bool nSeen, string nName, string nDate, string nLastGame, string nLastHero, uint32_t nLastTeam, uint32_t nLastOutcome, double nLastGain, uint32_t nKills, uint32_t nDeaths, uint32_t nAssists )
{
m_Seen = nSeen;
m_Name = nName;
m_Date = nDate;
m_LastGame = nLastGame;
m_LastHero = nLastHero;
m_LastTeam = nLastTeam;
m_LastOutcome = nLastOutcome;
m_LastGain = nLastGain;
m_Kills = nKills;
m_Deaths = nDeaths;
m_Assists = nAssists;
}
CDBLastSeenPlayer :: ~CDBLastSeenPlayer( )
{
}
| [
"fredrik.sigillet@4a4c9648-eef2-11de-9456-cf00f3bddd4e",
"[email protected]@4a4c9648-eef2-11de-9456-cf00f3bddd4e"
] | [
[
[
1,
368
],
[
370,
383
],
[
385,
393
],
[
395,
673
],
[
675,
694
],
[
696,
923
]
],
[
[
369,
369
],
[
384,
384
],
[
394,
394
],
[
674,
674
],
[
695,
695
]
]
] |
8fa2e51f8073dd2cec322539bb5146ad45e9c8c0 | 88f4b257863d50044212e6036dd09a25ec65a1ff | /src/jingxian/logging/log4cpp.cpp | baa48b1f6b7e437a2d879cea0b1f99f748f8e524 | [] | no_license | mei-rune/jx-proxy | bb1ee92f6b76fb21fdf2f4d8a907823efd05e17b | d24117ab62b10410f2ad05769165130a9f591bfb | refs/heads/master | 2022-08-20T08:56:54.222821 | 2009-11-14T07:01:08 | 2009-11-14T07:01:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,091 | cpp | # include "pro_config.h"
# include "log4cpp.h"
# include "jingxian/directory.h"
_jingxian_begin
namespace logging
{
namespace log4cppAdaptor
{
Logger::Logger(const tchar* nm)
: logger_(::log4cpp::Category::getInstance(toNarrowString(nm)))
{
}
Logger::~Logger(void)
{
}
void Logger::assertLog(bool assertion, const LogStream& msg, const char* file, int line)
{
}
bool Logger::isCritEnabled() const
{
return logger_.isCritEnabled();
}
void Logger::crit(const LogStream& message, const char* file, int line)
{
logger_.crit(toNarrowString(message.str()));
}
bool Logger::isFatalEnabled() const
{
return logger_.isErrorEnabled();
}
void Logger::fatal(const LogStream& message, const char* file, int line)
{
logger_.fatal(toNarrowString(message.str()));
}
bool Logger::isErrorEnabled() const
{
return logger_.isErrorEnabled();
}
void Logger::error(const LogStream& message, const char* file, int line)
{
logger_.error(toNarrowString(message.str()));
}
bool Logger::isInfoEnabled() const
{
return logger_.isCritEnabled();
}
void Logger::info(const LogStream& message, const char* file, int line)
{
logger_.crit(toNarrowString(message.str()));
}
bool Logger::isDebugEnabled() const
{
return logger_.isDebugEnabled();
}
void Logger::debug(const LogStream& message, const char* file, int line)
{
logger_.debug(toNarrowString(message.str()));
}
bool Logger::isWarnEnabled() const
{
return logger_.isWarnEnabled();
}
void Logger::warn(const LogStream& message, const char* file, int line)
{
logger_.warn(toNarrowString(message.str()));
}
bool Logger::isTraceEnabled() const
{
return logger_.isDebugEnabled();
}
void Logger::trace(const LogStream& message, const char* file, int line)
{
logger_.debug(toNarrowString(message.str()));
}
bool Logger::isEnabledFor(const logging::LevelPtr& level) const
{
return logger_.isPriorityEnabled(level);
}
void Logger::log(const logging::LevelPtr& level, const LogStream& message,
const char* file, int line)
{
logger_.log(level, toNarrowString(message.str()));
}
logging::LevelPtr Logger::getLevel() const
{
return logger_.getPriority();
}
void Logger::pushNDC(const tchar* str)
{
}
void Logger::popNDC()
{
}
void Logger::clearNDC()
{
}
const char* TRANSPORT_MODE[] = { "", "Receive", "Send", "Both" };
Tracer::Tracer(const tchar* nm, const tstring& thost, const tstring& tpeer, const tstring& sessionId)
: logger_(toNarrowString(nm), "")
, name_(null_ptr)
{
std::string host = toNarrowString(thost);
std::string peer = toNarrowString(tpeer);
size_t len = host.size() + peer.size() + 20;
name_ = (char*)my_malloc(len);
memset(name_, 0, len);
name_[0] = '[';
memcpy(name_ + 1, host.c_str(), host.size());
memcpy(name_ + 1 + host.size(), " - ", 3);
memcpy(name_ + 4 + host.size(), peer.c_str(), peer.size());
memcpy(name_ + 4 + host.size() + peer.size(), "]", 1);
logger_.setContext(name_);
host = trim_all(host, "tcp://");
host = trim_all(host, "tcp6://");
host = trim_all(host, "tcpv6://");
peer = trim_all(peer, "tcp://");
peer = trim_all(peer, "tcp6://");
peer = trim_all(peer, "tcpv6://");
host = replace_all(host, ":", "[");
peer = replace_all(peer, ":", "[");
std::string name = host + "]_" + peer + "]_" + toNarrowString(sessionId);
tstring dir = simplify(combinePath(getApplicationDirectory(), _T("log")));
if (!existDirectory(dir))
createDirectory(dir);
dir = combinePath(dir, _T("connection"));
if (!existDirectory(dir))
createDirectory(dir);
appender = toNarrowString(combinePath(dir, toTstring(name) + _T(".txt")));
logger_.addAppender(new log4cpp::FileAppender(name, appender));
}
Tracer::~Tracer(void)
{
::my_free(name_);
name_ = null_ptr;
logger_.removeAllAppenders();
DeleteFileA(appender.c_str());
}
bool Tracer::isDebugEnabled() const
{
return logger_.isDebugEnabled();
}
void Tracer::debug(transport_mode::type way, const LogStream& message, const char* file, int line)
{
std::string str = toNarrowString(message.str());
logger_.debug("%s %s", TRANSPORT_MODE[way], str.c_str(), file, line);
}
bool Tracer::isErrorEnabled() const
{
return logger_.isErrorEnabled();
}
void Tracer::error(transport_mode::type way, const LogStream& message, const char* file, int line)
{
std::string str = toNarrowString(message.str());
logger_.error("%s %s", TRANSPORT_MODE[way], str.c_str(), file, line);
}
bool Tracer::isFatalEnabled() const
{
return logger_.isFatalEnabled();
}
void Tracer::fatal(transport_mode::type way, const LogStream& message, const char* file, int line)
{
std::string str = toNarrowString(message.str());
logger_.fatal("%s %s", TRANSPORT_MODE[way], str.c_str(), file, line);
}
bool Tracer::isInfoEnabled() const
{
return logger_.isCritEnabled();
}
void Tracer::info(transport_mode::type way, const LogStream& message, const char* file, int line)
{
std::string str = toNarrowString(message.str());
logger_.crit("%s %s", TRANSPORT_MODE[way], str.c_str(), file, line);
}
bool Tracer::isWarnEnabled() const
{
return logger_.isWarnEnabled();
}
void Tracer::warn(transport_mode::type way, const LogStream& message, const char* file, int line)
{
std::string str = toNarrowString(message.str());
logger_.warn("%s %s", TRANSPORT_MODE[way], str.c_str(), file, line);
}
bool Tracer::isTraceEnabled() const
{
return logger_.isDebugEnabled();
}
void Tracer::trace(transport_mode::type way, const LogStream& message, const char* file, int line)
{
std::string str = toNarrowString(message.str());
logger_.debug("%s %s", TRANSPORT_MODE[way], str.c_str(), file, line);
}
bool Tracer::isCritEnabled() const
{
return logger_.isCritEnabled();
}
void Tracer::crit(transport_mode::type way, const LogStream& message, const char* file, int line)
{
std::string str = toNarrowString(message.str());
logger_.crit("%s %s", TRANSPORT_MODE[way], str.c_str(), file, line);
}
ContextCategory::ContextCategory(const std::string& name
, const std::string& context)
: log4cpp::Category(name, &log4cpp::Category::getInstance(name), log4cpp::Priority::DEBUG)
, context_(context)
{
this->setPriority(this->getParent()->getPriority());
}
void ContextCategory::setContext(const std::string& context)
{
context_ = context;
}
const std::string& ContextCategory::getContext() const
{
return context_;
}
void ContextCategory::_logUnconditionally2(log4cpp::Priority::Value priority,
const std::string& message) throw()
{
log4cpp::LoggingEvent evt(getName(), message, context_, priority);
callAppenders(evt);
}
}
}
_jingxian_end | [
"[email protected]@53e742d2-d0ea-11de-97bf-6350044336de"
] | [
[
[
1,
287
]
]
] |
81b15219162f058dfcae8d9c757a191393216ac5 | 335783c9e5837a1b626073d1288b492f9f6b057f | /source/fbxcmd/ViewScene/dds/Stream.cpp | 7e85954099bc40d7dcbf226ebe214b56c2fd5233 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | code-google-com/fbx4eclipse | 110766ee9760029d5017536847e9f3dc09e6ebd2 | cc494db4261d7d636f8c4d0313db3953b781e295 | refs/heads/master | 2016-09-08T01:55:57.195874 | 2009-12-03T20:35:48 | 2009-12-03T20:35:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,225 | cpp | /***** BEGIN LICENSE BLOCK *****
BSD License
Copyright (c) 2005-2009, NIF File Format Library and Tools
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the NIF File Format Library and Tools projectmay not be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR 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.
***** END LICENCE BLOCK *****/
#include "Stream.h"
#include <stdio.h> // printf
#include <string.h> // memcpy
unsigned int Stream::seek(unsigned int p)
{
if (p > size) {
printf("DDS: trying to seek beyond end of stream (corrupt file?)");
}
else {
pos = p;
}
return pos;
}
unsigned int mem_read(Stream & mem, unsigned long long & i)
{
if (mem.pos + 8 > mem.size) {
printf("DDS: trying to read beyond end of stream (corrupt file?)");
return(0);
};
memcpy(&i, mem.mem + mem.pos, 8); // @@ todo: make sure little endian
mem.pos += 8;
return(8);
}
unsigned int mem_read(Stream & mem, unsigned int & i)
{
if (mem.pos + 4 > mem.size) {
printf("DDS: trying to read beyond end of stream (corrupt file?)");
return(0);
};
memcpy(&i, mem.mem + mem.pos, 4); // @@ todo: make sure little endian
mem.pos += 4;
return(4);
}
unsigned int mem_read(Stream & mem, unsigned short & i)
{
if (mem.pos + 2 > mem.size) {
printf("DDS: trying to read beyond end of stream (corrupt file?)");
return(0);
};
memcpy(&i, mem.mem + mem.pos, 2); // @@ todo: make sure little endian
mem.pos += 2;
return(2);
}
unsigned int mem_read(Stream & mem, unsigned char & i)
{
if (mem.pos + 1 > mem.size) {
printf("DDS: trying to read beyond end of stream (corrupt file?)");
return(0);
};
i = (mem.mem + mem.pos)[0];
mem.pos += 1;
return(1);
}
unsigned int mem_read(Stream & mem, unsigned char *i, unsigned int cnt)
{
if (mem.pos + cnt > mem.size) {
printf("DDS: trying to read beyond end of stream (corrupt file?)");
return(0);
};
memcpy(i, mem.mem + mem.pos, cnt);
mem.pos += cnt;
return(cnt);
}
| [
"tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792"
] | [
[
[
1,
104
]
]
] |
5b3c2f084ceb5d6fa1c4b56fc9afc8d76d681fee | b8fe0ddfa6869de08ba9cd434e3cf11e57d59085 | /ouan-tests/EventTest/Event.cpp | 9706cfb6205825ef9a083c18edca80fc9867cf55 | [] | no_license | juanjmostazo/ouan-tests | c89933891ed4f6ad48f48d03df1f22ba0f3ff392 | eaa73fb482b264d555071f3726510ed73bef22ea | refs/heads/master | 2021-01-10T20:18:35.918470 | 2010-06-20T15:45:00 | 2010-06-20T15:45:00 | 38,101,212 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,429 | cpp | #include "Event.h"
using namespace OUAN;
bool EventComparator::operator() (EventPtr& evt1, EventPtr& evt2)
{
if (!evt1.get()) return true;
if (!evt2.get()) return false;
// The more or less standard definition for a priority queue
// assigns more priority to values with lower numbers.
// However, the STL implementation does the opposite.
// To stick with the more familiar convention, the comparison operator
// used for this method is > instead of <, so that the queue ordering
// gets reversed.
return evt1->getPriority()>evt2->getPriority();
}
//-------------------------
Event::Event(int priority, TEventType eventType)
:mEventType(eventType)
,mPriority(priority)
{
}
Event::~Event()
{
}
TEventType Event::getEventType() const
{
return mEventType;
}
int Event::getPriority() const
{
return mPriority;
}
//----------------------
ChangeWorldEvent::ChangeWorldEvent(bool dreamWorld)
:Event(EVT_PRIORITY_CHANGEWORLD,EVENT_TYPE_CHANGEWORLD)
,mDreamWorld(dreamWorld)
{
};
bool ChangeWorldEvent::isDreamWorld() const
{
return mDreamWorld;
}
//----------------------
EnemyHitEvent::EnemyHitEvent(std::string enemyName, int damage)
:Event(EVT_PRIORITY_GAME_OVER,EVENT_TYPE_GAMEOVER)
,mEnemyName(enemyName)
,mDamage(damage)
{
}
std::string EnemyHitEvent::getEnemyName() const
{
return mEnemyName;
}
int EnemyHitEvent::getDamage() const
{
return mDamage;
} | [
"ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde"
] | [
[
[
1,
60
]
]
] |
c190c28517b3d674bb13f7838320faaa87bcb043 | b73f27ba54ad98fa4314a79f2afbaee638cf13f0 | /libproject/Setting/WebsitesList.cpp | 3e314bdabe71a9e60c10e2d8737e5297bebadd3e | [] | 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 | GB18030 | C++ | false | false | 2,172 | cpp | #include "stdafx.h"
#include "WebsiteList.h"
#include <utility\dns.h>
WebsiteList::WebsiteList(void) {
}
WebsiteList::~WebsiteList(void) {
}
// 获取DNS列表
int WebsiteList::get_first_website(std::string * website) {
assert(NULL != website);
if (websites_set_.size() == 0) {
return 1;
} else {
*website = websites_set_.begin()->second;
return 0;
}
}
int WebsiteList::get_next_website(const std::string &name, std::string *next_item) {
assert(NULL != next_item);
assert (name.length() != 0);
if (name.length() == 0) {
return -1;
} else {
WEBSITES_SET::iterator iter = websites_set_.upper_bound(name);
if (iter == websites_set_.end()) {
return -1;
} else {
*next_item = iter->second;
return 0;
}
}
}
//==================================
// 测试DNS是否在黑白名单当中
bool WebsiteList::is_in_set(const std::string &dns_name) const {
TCHAR buffer[1024];
get_main_dns_name(buffer, 1024, dns_name.c_str());
// 表明不在此名单内
if (websites_set_.end() != websites_set_.find(buffer)) {
return true;
} else {
return false;
}
}
//=====================================
// 从DNS中移除
int WebsiteList::remote_website(const std::string &dns_name) {
TCHAR buffer[1024];
get_main_dns_name(buffer, 1024, dns_name.c_str());
WEBSITES_SET::iterator iter = websites_set_.find(buffer);
if (websites_set_.end() != iter) {
websites_set_.erase(iter);
return 0;
} else {
return 1;
}
}
int WebsiteList::add_website(const std::string &dns_name) {
// 去除DNS MAIN name
const int buf_size = 256;
TCHAR main_dns[buf_size], main_host_name[buf_size];
get_main_dns_name(main_dns, buf_size, dns_name.c_str());
get_main_serv_name(main_host_name, buf_size, dns_name.c_str());
websites_set_.insert(std::make_pair(main_dns, main_host_name));
return 0;
}
void WebsiteList::enum_webistes(boost::function<int (const char *)> enum_fun) {
WEBSITES_SET::const_iterator iter = websites_set_.begin();
for (; iter != websites_set_.end(); ++iter) {
enum_fun(iter->second.c_str());
}
}
| [
"[email protected]"
] | [
[
[
1,
85
]
]
] |
78172336e85e7f8ea269fcdbd49e3107664a86f9 | 6be72227405ee9fa245ea9f9896df3f2668ed81b | /src/TILFileStreamStd.cpp | cf751f09ef9473eccb8941134d9b722883ac9589 | [
"MIT"
] | permissive | lilieming/tinyimageloader | 9ab74ec20070ceff40a9e14de344d073da4655a4 | 9513947b61aa93ec7dd8f16e14fbc14becdcd86e | refs/heads/master | 2020-05-20T06:11:52.414776 | 2011-07-10T12:45:58 | 2011-07-10T12:45:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,331 | cpp | /*
TinyImageLoader - load images, just like that
Copyright (C) 2010 - 2011 by Quinten Lansu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "TILFileStreamStd.h"
#include "TILInternal.h"
namespace til
{
FileStreamStd::FileStreamStd() : FileStream()
{
}
FileStreamStd::~FileStreamStd()
{
}
bool FileStreamStd::Open(const char* a_File, uint32 a_Options)
{
char path[TIL_MAX_PATH] = { 0 };
size_t length = strlen(a_File);
if (a_Options == TIL_FILE_ABSOLUTEPATH)
{
strcpy(path, a_File);
}
else if (a_Options == TIL_FILE_ADDWORKINGDIR)
{
TIL_AddWorkingDirectory(path, TIL_MAX_PATH, a_File);
TIL_PRINT_DEBUG("Final path: %s", path);
}
length = strlen(path);
m_FilePath = new char[length + 1];
strcpy(m_FilePath, path);
m_Handle = fopen(m_FilePath, "rb");
if (!m_Handle)
{
TIL_ERROR_EXPLAIN("Could not open '%s'.", path);
delete m_FilePath;
return false;
}
return true;
}
bool FileStreamStd::Read(void* a_Dst, uint32 a_Size, uint32 a_Count)
{
size_t result = fread(a_Dst, a_Size, a_Count, m_Handle);
return (result == a_Count * a_Size);
}
bool FileStreamStd::ReadByte(byte* a_Dst, uint32 a_Count)
{
size_t result = fread(a_Dst, sizeof(byte), a_Count, m_Handle);
return (result == a_Count * sizeof(byte));
}
bool FileStreamStd::ReadWord(word* a_Dst, uint32 a_Count)
{
size_t result = fread(a_Dst, sizeof(word), a_Count, m_Handle);
return (result == a_Count * sizeof(word));
}
bool FileStreamStd::ReadDWord(dword* a_Dst, uint32 a_Count)
{
size_t result = fread(a_Dst, sizeof(dword), a_Count, m_Handle);
return (result == a_Count * sizeof(dword));
}
bool FileStreamStd::Seek(uint32 a_Bytes, uint32 a_Options)
{
if (a_Options & TIL_FILE_SEEK_START)
{
fseek(m_Handle, a_Bytes, SEEK_SET);
}
else if (a_Options & TIL_FILE_SEEK_CURR)
{
fseek(m_Handle, a_Bytes, SEEK_CUR);
}
else if (a_Options & TIL_FILE_SEEK_END)
{
fseek(m_Handle, a_Bytes, SEEK_END);
}
return true;
}
bool FileStreamStd::EndOfFile()
{
return false;
}
bool FileStreamStd::Close()
{
if (m_Handle)
{
fclose(m_Handle);
delete m_FilePath;
return true;
}
return false;
}
} | [
"knight666@ae7ae854-2bc2-de67-b11e-81cc9cd7c224"
] | [
[
[
1,
131
]
]
] |
623b18f125c6bf3d032c41ad22c111a866970014 | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/Modules/BehaviorControl/BH2009BehaviorControl/Symbols/BH2009SoccerSymbols.cpp | f7bd0780eb7b1994988733772af1957f5e74eb03 | [
"BSD-2-Clause"
] | permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,183 | cpp | /**
* \file BH2009SoccerSymbols.cpp
* Implementation of symbols for our 4 roles.
* \author Colin Graf
* \author <a href="mailto:[email protected]">André Schreck</a>
* \author Katharina Gillmann
*/
#include <limits>
#include "Tools/Debugging/Modify.h"
#include "BH2009SoccerSymbols.h"
#include "BH2009TeamSymbols.h"
#include "BH2009LocatorSymbols.h"
#include "BH2009BallSymbols.h"
#include "Tools/Team.h"
PROCESS_WIDE_STORAGE BH2009SoccerSymbols* BH2009SoccerSymbols::theInstance = 0;
void BH2009SoccerSymbols::registerSymbols(xabsl::Engine& engine)
{
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.unknown", BehaviorData::unknown);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.dribble", BehaviorData::dribble);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.go_to_ball", BehaviorData::goToBall);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.search_for_ball", BehaviorData::searchForBall);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.go_to_target", BehaviorData::goToTarget);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.prepare_kick", BehaviorData::prepareKick);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.kick", BehaviorData::kick);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.kick_sidewards", BehaviorData::kickSidewards);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.pass", BehaviorData::pass);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.block", BehaviorData::block);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.hold", BehaviorData::hold);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.stand_up", BehaviorData::standUp);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.patrol", BehaviorData::patrol);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.pass_before_goal", BehaviorData::passBeforeGoal);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.kickoff", BehaviorData::kickoff);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.wait_for_pass", BehaviorData::waitForPass);
engine.registerEnumElement("soccer.behavior_action", "soccer.behavior_action.prepare_pass", BehaviorData::preparePass);
engine.registerEnumeratedOutputSymbol("soccer.behavior_action", "soccer.behavior_action", (int*)&behaviorData.action);
engine.registerBooleanInputSymbol("soccer.disable_pre_initial", &disablePreInitialState);
engine.registerDecimalInputSymbol("soccer.opponent_goal_angle", &staticSoccerOpponentGoalAngle);
engine.registerDecimalInputSymbol("soccer.position_next_to_ball.x", &staticSoccerPositionNextBallX);
engine.registerDecimalInputSymbolBooleanParameter("soccer.position_next_to_ball.x", "soccer.position_next_to_ball.x.side", &sideLeft);
engine.registerDecimalInputSymbol("soccer.position_next_to_ball.y",&staticSoccerPositionNextBallY);
engine.registerDecimalInputSymbolBooleanParameter("soccer.position_next_to_ball.y", "soccer.position_next_to_ball.y.side", &sideLeft);
engine.registerDecimalInputSymbol("soccer.position_next_to_ball.angle", &staticSoccerAngleNextToBall);
engine.registerDecimalInputSymbolBooleanParameter("soccer.position_next_to_ball.angle", "soccer.position_next_to_ball.angle.side", &sideLeft);
engine.registerDecimalInputSymbol("soccer.position_behind_ball.x", &staticSoccerPositionBehindBallX);
engine.registerDecimalInputSymbol("soccer.position_behind_ball.y", &staticSoccerPositionBehindBallY);
engine.registerDecimalInputSymbol("soccer.position_behind_ball.angle", &staticSoccerPositionBehindBallAngle);
}
void BH2009SoccerSymbols::init()
{
#ifdef TARGET_SIM
disablePreInitialState = true;
#else
disablePreInitialState = Global::getSettings().recover;
#endif
}
void BH2009SoccerSymbols::update()
{
}
double BH2009SoccerSymbols::soccerOpponentGoalAngle()
{
if(frameInfo.getTimeSince(goalPercept.timeWhenOppGoalLastSeen) < 4000)
{
double angleLeft = toDegrees(goalPercept.posts[GoalPercept::LEFT_OPPONENT].positionOnField.angle());
double angleRight = toDegrees(goalPercept.posts[GoalPercept::RIGHT_OPPONENT].positionOnField.angle());
return (angleLeft + angleRight) / 2;
}
else
{
return toDegrees(Geometry::angleTo(robotPose, Vector2<double>(fieldDimensions.xPosOpponentGroundline, 0)));
}
}
double BH2009SoccerSymbols::computePositionNextBallX()
{
return computePosition().x;
}
double BH2009SoccerSymbols::computePositionNextBallY()
{
return computePosition().y;
}
double BH2009SoccerSymbols::computeAngleNextBall()
{
return toDegrees(Geometry::angleTo(theInstance->robotPose,computePosition()));
}
Vector2<double> BH2009SoccerSymbols::computePosition()
{
Vector2<double> ballPosition = ballModel.estimate.getPositionInFieldCoordinates(theInstance->robotPose);
Vector2<double> temp = ballPosition - Vector2<double>(fieldDimensions.xPosOpponentGroundline, 0);
if(sideLeft) temp.rotateLeft();
else temp.rotateRight();
temp.normalize(300);
return (temp + ballPosition);
}
double BH2009SoccerSymbols::computePositionBehindBallX()
{
return computePositionBehindBall().x;
}
double BH2009SoccerSymbols::computePositionBehindBallY()
{
return computePositionBehindBall().y;
}
double BH2009SoccerSymbols::computePositionBehindBallAngle()
{
return toDegrees(Geometry::angleTo(theInstance->robotPose,computePositionBehindBall()));
}
Vector2<double> BH2009SoccerSymbols::computePositionBehindBall()
{
Vector2<double> ballPosition = ballModel.estimate.getPositionInFieldCoordinates(theInstance->robotPose);
Vector2<double> temp = ballPosition - Vector2<double>(fieldDimensions.xPosOpponentGroundline, 0);
temp.normalize(250);
return (temp + ballPosition);
}
| [
"alon@rogue.(none)"
] | [
[
[
1,
135
]
]
] |
f91a7fa53c750e226056e328e2b7e0cd13126dd4 | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/Collection.cpp | 93081f106b460f00131273999239d7dbbd706143 | [] | no_license | mikezhoubill/emule-gifc | e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60 | 46979cf32a313ad6d58603b275ec0b2150562166 | refs/heads/master | 2021-01-10T20:37:07.581465 | 2011-08-13T13:58:37 | 2011-08-13T13:58:37 | 32,465,033 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 12,539 | cpp | //this file is part of eMule
//Copyright (C)2002-2005 Merkur ( [email protected] / 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 "collection.h"
#include "KnownFile.h"
#include "CollectionFile.h"
#include "SafeFile.h"
#include "Packets.h"
#include "Preferences.h"
#include "SharedFilelist.h"
#include "emule.h"
#include "Log.h"
#include "md5sum.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define COLLECTION_FILE_VERSION1_INITIAL 0x01
#define COLLECTION_FILE_VERSION2_LARGEFILES 0x02
CCollection::CCollection(void)
: m_sCollectionName(_T(""))
, m_sCollectionAuthorName(_T(""))
, m_bTextFormat(false)
{
m_CollectionFilesMap.InitHashTable(1031);
m_sCollectionName.Format(_T("New Collection-%u"), ::GetTickCount());
m_pabyCollectionAuthorKey = NULL;
m_nKeySize = 0;
}
CCollection::CCollection(const CCollection* pCollection)
{
//leuk_he CB Mod : Fix : Collection double extension
//see http://forum.emule-project.net/index.php?showtopic=107054
/*
m_sCollectionName = pCollection->m_sCollectionName;
*/
CString collectionName = pCollection->m_sCollectionName;
collectionName.Left(collectionName.ReverseFind('.')); // no extension should be handled correctly as well
m_sCollectionName = collectionName;
//leuk_he CB Mod : Fix : Collection double extension
if (pCollection->m_pabyCollectionAuthorKey != NULL){
m_nKeySize = pCollection->m_nKeySize;
m_pabyCollectionAuthorKey = new BYTE[m_nKeySize];
memcpy(m_pabyCollectionAuthorKey, pCollection->m_pabyCollectionAuthorKey, m_nKeySize);
m_sCollectionAuthorName = pCollection->m_sCollectionAuthorName;
}
else{
m_nKeySize = 0;
m_pabyCollectionAuthorKey = NULL;
}
m_bTextFormat = pCollection->m_bTextFormat;
m_CollectionFilesMap.InitHashTable(1031);
POSITION pos = pCollection->m_CollectionFilesMap.GetStartPosition();
CCollectionFile* pCollectionFile;
CSKey key;
while( pos != NULL )
{
pCollection->m_CollectionFilesMap.GetNextAssoc( pos, key, pCollectionFile );
AddFileToCollection(pCollectionFile, true);
}
}
CCollection::~CCollection(void)
{
delete[] m_pabyCollectionAuthorKey;
POSITION pos = m_CollectionFilesMap.GetStartPosition();
CCollectionFile* pCollectionFile;
CSKey key;
while( pos != NULL )
{
m_CollectionFilesMap.GetNextAssoc( pos, key, pCollectionFile );
delete pCollectionFile;
}
m_CollectionFilesMap.RemoveAll();
}
CCollectionFile* CCollection::AddFileToCollection(CAbstractFile* pAbstractFile, bool bCreateClone)
{
CSKey key(pAbstractFile->GetFileHash());
CCollectionFile* pCollectionFile;
if (m_CollectionFilesMap.Lookup(key, pCollectionFile))
{
ASSERT(0);
return pCollectionFile;
}
pCollectionFile = NULL;
if(bCreateClone)
pCollectionFile = new CCollectionFile(pAbstractFile);
else if(pAbstractFile->IsKindOf(RUNTIME_CLASS(CCollectionFile)))
pCollectionFile = (CCollectionFile*)pAbstractFile;
if(pCollectionFile)
m_CollectionFilesMap.SetAt(key, pCollectionFile);
return pCollectionFile;
}
void CCollection::RemoveFileFromCollection(CAbstractFile* pAbstractFile)
{
CSKey key(pAbstractFile->GetFileHash());
CCollectionFile* pCollectionFile;
if (m_CollectionFilesMap.Lookup(key, pCollectionFile))
{
m_CollectionFilesMap.RemoveKey(key);
delete pCollectionFile;
}
else
ASSERT(0);
}
void CCollection::SetCollectionAuthorKey(const byte* abyCollectionAuthorKey, uint32 nSize)
{
delete[] m_pabyCollectionAuthorKey;
m_pabyCollectionAuthorKey = NULL;
m_nKeySize = 0;
if (abyCollectionAuthorKey != NULL){
m_pabyCollectionAuthorKey = new BYTE[nSize];
memcpy(m_pabyCollectionAuthorKey, abyCollectionAuthorKey, nSize);
m_nKeySize = nSize;
}
}
bool CCollection::InitCollectionFromFile(const CString& sFilePath, CString sFileName)
{
DEBUG_ONLY( sFileName.Replace(COLLECTION_FILEEXTENSION, _T("")) );
bool bCollectionLoaded = false;
CSafeFile data;
if(data.Open(sFilePath, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary))
{
try
{
uint32 nVersion = data.ReadUInt32();
if(nVersion == COLLECTION_FILE_VERSION1_INITIAL || nVersion == COLLECTION_FILE_VERSION2_LARGEFILES)
{
uint32 headerTagCount = data.ReadUInt32();
while(headerTagCount)
{
CTag tag(&data, true);
switch(tag.GetNameID())
{
case FT_FILENAME:
{
if(tag.IsStr())
m_sCollectionName = tag.GetStr();
break;
}
case FT_COLLECTIONAUTHOR:
{
if(tag.IsStr())
m_sCollectionAuthorName = tag.GetStr();
break;
}
case FT_COLLECTIONAUTHORKEY:
{
if(tag.IsBlob())
{
SetCollectionAuthorKey(tag.GetBlob(), tag.GetBlobSize());
}
break;
}
}
headerTagCount--;
}
uint32 fileCount = data.ReadUInt32();
while(fileCount)
{
CCollectionFile* pCollectionFile = new CCollectionFile(&data);
if(pCollectionFile)
AddFileToCollection(pCollectionFile, false);
fileCount--;
}
bCollectionLoaded = true;
}
if (m_pabyCollectionAuthorKey != NULL){
bool bResult = false;
if (data.GetLength() > data.GetPosition()){
using namespace CryptoPP;
uint32 nPos = (uint32)data.GetPosition();
data.SeekToBegin();
BYTE* pMessage = new BYTE[nPos];
VERIFY( data.Read(pMessage, nPos) == nPos);
StringSource ss_Pubkey(m_pabyCollectionAuthorKey, m_nKeySize, true, 0);
RSASSA_PKCS1v15_SHA_Verifier pubkey(ss_Pubkey);
int nSignLen = (int)(data.GetLength() - data.GetPosition());
BYTE* pSignature = new BYTE[nSignLen ];
VERIFY( data.Read(pSignature, nSignLen) == (UINT)nSignLen);
bResult = pubkey.VerifyMessage(pMessage, nPos, pSignature, nSignLen);
delete[] pMessage;
delete[] pSignature;
}
if (!bResult){
DebugLogWarning(_T("Collection %s: Verifying of public key failed!"), m_sCollectionName);
delete[] m_pabyCollectionAuthorKey;
m_pabyCollectionAuthorKey = NULL;
m_nKeySize = 0;
m_sCollectionAuthorName = _T("");
}
else
DebugLog(_T("Collection %s: Public key verified"), m_sCollectionName);
}
else
m_sCollectionAuthorName = _T("");
data.Close();
}
catch(CFileException* error)
{
error->Delete();
return false;
}
catch(...)
{
ASSERT( false );
data.Close();
return false;
}
}
else
return false;
if(!bCollectionLoaded)
{
CStdioFile data;
if(data.Open(sFilePath, CFile::modeRead | CFile::shareDenyWrite | CFile::typeText))
{
try
{
CString sLink;
while(data.ReadString(sLink))
{
//Ignore all lines that start with #.
//These lines can be used for future features..
if(sLink.Find(_T("#")) != 0)
{
try
{
CCollectionFile* pCollectionFile = new CCollectionFile();
if (pCollectionFile->InitFromLink(sLink))
AddFileToCollection(pCollectionFile, false);
else
delete pCollectionFile;
}
catch(...)
{
ASSERT( false );
data.Close();
return false;
}
}
}
data.Close();
m_sCollectionName = sFileName;
bCollectionLoaded = true;
m_bTextFormat = true;
}
catch(CFileException* error)
{
error->Delete();
return false;
}
catch(...)
{
ASSERT( false );
data.Close();
return false;
}
}
}
return bCollectionLoaded;
}
void CCollection::WriteToFileAddShared(CryptoPP::RSASSA_PKCS1v15_SHA_Signer* pSignKey)
{
using namespace CryptoPP;
CString sFileName;
sFileName.Format(_T("%s%s"), m_sCollectionName, COLLECTION_FILEEXTENSION);
CString sFilePath;
sFilePath.Format(_T("%s\\%s"), thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR), sFileName);
if(m_bTextFormat)
{
CStdioFile data;
if(data.Open(sFilePath, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite | CFile::typeText))
{
try
{
POSITION pos = m_CollectionFilesMap.GetStartPosition();
CCollectionFile* pCollectionFile;
CSKey key;
while( pos != NULL )
{
m_CollectionFilesMap.GetNextAssoc( pos, key, pCollectionFile );
CString sLink;
sLink.Format(_T("%s\n"), pCollectionFile->GetED2kLink());
data.WriteString(sLink);
}
data.Close();
}
catch(CFileException* error)
{
error->Delete();
return;
}
catch(...)
{
ASSERT( false );
data.Close();
return;
}
}
}
else
{
CSafeFile data;
if(data.Open(sFilePath, CFile::modeCreate | CFile::modeReadWrite | CFile::shareDenyWrite | CFile::typeBinary))
{
try
{
//Version
// check first if we have any large files in the map - write use lowest version possible
uint32 dwVersion = COLLECTION_FILE_VERSION1_INITIAL;
POSITION pos = m_CollectionFilesMap.GetStartPosition();
CCollectionFile* pCollectionFile;
CSKey key;
while( pos != NULL ) {
m_CollectionFilesMap.GetNextAssoc( pos, key, pCollectionFile );
if (pCollectionFile->IsLargeFile()){
dwVersion = COLLECTION_FILE_VERSION2_LARGEFILES;
break;
}
}
data.WriteUInt32(dwVersion);
uint32 uTagCount = 1;
//NumberHeaderTags
if(m_pabyCollectionAuthorKey != NULL)
uTagCount += 2;
data.WriteUInt32(uTagCount);
CTag collectionName(FT_FILENAME, m_sCollectionName);
collectionName.WriteTagToFile(&data, utf8strRaw);
if(m_pabyCollectionAuthorKey != NULL){
CTag collectionAuthor(FT_COLLECTIONAUTHOR, m_sCollectionAuthorName);
collectionAuthor.WriteTagToFile(&data, utf8strRaw);
CTag collectionAuthorKey(FT_COLLECTIONAUTHORKEY, m_nKeySize, m_pabyCollectionAuthorKey);
collectionAuthorKey.WriteTagToFile(&data, utf8strRaw);
}
//Total Files
data.WriteUInt32(m_CollectionFilesMap.GetSize());
pos = m_CollectionFilesMap.GetStartPosition();
while( pos != NULL ) {
m_CollectionFilesMap.GetNextAssoc( pos, key, pCollectionFile );
pCollectionFile->WriteCollectionInfo(&data);
}
if (pSignKey != NULL){
uint32 nPos = (uint32)data.GetPosition();
data.SeekToBegin();
BYTE* pBuffer = new BYTE[nPos];
VERIFY( data.Read(pBuffer, nPos) == nPos);
SecByteBlock sbbSignature(pSignKey->SignatureLength());
AutoSeededRandomPool rng;
pSignKey->SignMessage(rng, pBuffer ,nPos , sbbSignature.begin());
BYTE abyBuffer2[500];
ArraySink asink(abyBuffer2, 500);
asink.Put(sbbSignature.begin(), sbbSignature.size());
int nResult = (uint8)asink.TotalPutLength();
data.Write(abyBuffer2, nResult);
delete[] pBuffer;
}
data.Close();
}
catch(CFileException* error)
{
error->Delete();
return;
}
catch(...)
{
ASSERT( false );
data.Close();
return;
}
}
}
theApp.sharedfiles->AddFileFromNewlyCreatedCollection(sFilePath);
}
bool CCollection::HasCollectionExtention(const CString& sFileName)
{
if(sFileName.Find(COLLECTION_FILEEXTENSION) == -1)
return false;
return true;
}
CString CCollection::GetCollectionAuthorKeyString(){
if (m_pabyCollectionAuthorKey != NULL)
return EncodeBase16(m_pabyCollectionAuthorKey, m_nKeySize);
else
return CString(_T(""));
}
CString CCollection::GetAuthorKeyHashString(){
if (m_pabyCollectionAuthorKey != NULL){
MD5Sum md5(m_pabyCollectionAuthorKey, m_nKeySize);
CString strResult = md5.GetHash();
strResult.MakeUpper();
return strResult;
}
return CString(_T(""));
}
| [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b",
"[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b"
] | [
[
[
1,
51
],
[
55,
55
],
[
61,
326
],
[
328,
454
]
],
[
[
52,
54
],
[
56,
60
],
[
327,
327
]
]
] |
0064cb72f6b35db7e3ba7d2c18616a88f71e4940 | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Base/ThreadsAndProcesses/TLS1/TLS1dll.h | 3961db3990a67c6ba7ccc448fb1010be66ac67a7 | [] | 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 | 699 | h | // TLS1dll.h
//
// Copyright (C) Symbian Software Ltd 2000-2005. All rights reserved.
// DLL example program (1) to demonstrate the use of Thread local storage.
#include <e32test.h>
class CSetter : public CBase
{
public:
IMPORT_C CSetter(CConsoleBase& aConsole);
~CSetter();
IMPORT_C void SetStaticTextL(const TDesC& aString);
IMPORT_C void ShowStaticText() const;
private:
CConsoleBase& iConsole; // Use the console (not owned)
};
class CGeneral : public CBase
{
public:
IMPORT_C CGeneral(CConsoleBase& aConsole);
IMPORT_C void ShowStaticText() const;
private:
CConsoleBase& iConsole; // Use the console (not owned)
};
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
] | [
[
[
1,
31
]
]
] |
72940e26b06626293795e6cd2832d025f4fded5f | 36bf908bb8423598bda91bd63c4bcbc02db67a9d | /Include/CZoomView.h | 67a0db4567f59c4be5b8bde72942d07c43c9400b | [] | no_license | code4bones/crawlpaper | edbae18a8b099814a1eed5453607a2d66142b496 | f218be1947a9791b2438b438362bc66c0a505f99 | refs/heads/master | 2021-01-10T13:11:23.176481 | 2011-04-14T11:04:17 | 2011-04-14T11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,918 | h | /*
CZoomView.h
Classe per la vista scroll/zoom (MFC).
Ripresa e modificata dall'originale:
Written by Brad Pirtle, CS:72450,1156, Internet:[email protected]
Copyright 1994, QuickLogic Corp., all rights reserved.
Luca Piergentili, 05/09/00
[email protected]
*/
#ifndef _CZOOMVIEW_H
#define _CZOOMVIEW_H 1
#include "window.h"
/*
CZoomView
*/
class CZoomView : public CScrollView
{
DECLARE_DYNCREATE(CZoomView)
protected:
// protected constructor used by dynamic creation
CZoomView();
virtual ~CZoomView();
#ifdef _DEBUG
// deve evitare il controllo sulla modalita' MM_ANISOTROPIC
virtual void AssertValid (void) const;
#endif
public:
// mapping mode
inline void SetMapMode (int nMode) {m_nMapMode = nMode;}
inline int GetMapMode (void) const {return(m_nMapMode);}
inline void SetCenterMode (BOOL bCenter) {m_bCenter = bCenter;}
inline BOOL GetCenterMode (void) const {return(m_bCenter);}
// zooming functions
typedef enum {
MODE_ZOOMOFF,
MODE_ZOOMIN,
MODE_ZOOMOUT
} ZOOMMODE;
typedef enum {
CURSOR_MODE_BYCLICK,
CURSOR_MODE_BYMODE,
CURSOR_MODE_NONE
} CURSORZOOMMODE;
// overridden CScrollView member functions
void CenterOnLogicalPoint (CPoint ptCenter);
CPoint GetLogicalCenterPoint (void);
void SetZoomSizes (SIZE sizeTotal,const SIZE& sizePage = sizeDefault,const SIZE& sizeLine = sizeDefault,BOOL bInvalidate = TRUE);
// zooming mode
void SetZoomMode (ZOOMMODE zoomMode);
inline ZOOMMODE GetZoomMode (void) const {return(m_zoomMode);}
// related cursors
BOOL SetZoomCursor (UINT);
inline void SetCursorZoomMode (CURSORZOOMMODE mode) {m_cursorZoomMode = mode;}
inline CURSORZOOMMODE GetCursorZoomMode (void) const {return(m_cursorZoomMode);}
// to implement zooming functionality
void DoZoomIn (CRect &rect);
void DoZoomIn (CPoint *point = NULL,double delta = 1.25);
void DoZoomIn (double factor);
void DoZoomOut (double factor);
void DoZoomOut (CPoint *point = NULL,double delta = 1.25);
void DoZoomOut (CRect &rect);
void DoZoomFull (void);
// bdelmee code change
inline double GetZoomRatio (void) const {return(m_zoomScale);}
inline void SetZoomRatio (double r) {m_zoomScale = r;}
// override this to get notified of zoom scale change
virtual void OnNotifyZoom (void) {};
// utility functions
void ViewDPtoLP (LPPOINT lpPoints,int nCount = 1);
void ViewLPtoDP (LPPOINT lpPoints,int nCount = 1);
void ViewLPtoDst (LPRECT rcDst);
void ViewLPtoSrc (LPRECT rcSrc);
void ViewLPtoSrc (LPPOINT lpPoint,int nCount=1);
void ClientToDevice (CPoint &point);
void NormalizeRect (CRect &rect);
void DrawBox (CDC &dc,CRect &rect,BOOL xor = TRUE);
void DrawLine (CDC &dc,const int &x1,const int &y1,const int &x2,const int &y2,BOOL xor = TRUE);
// handlers
void OnLButtonDown (UINT nFlags,CPoint point);
void OnLButtonUp (UINT nFlags,CPoint point);
void OnRButtonDown (UINT nFlags,CPoint point);
void OnMouseMove (UINT nFlags,CPoint point);
BOOL OnSetCursor (CWnd* pWnd,UINT nHitTest,UINT message);
protected:
virtual void OnDraw (CDC* pDC) {/*CZoomView::OnDraw(pDC);*/}
virtual void OnPrepareDC (CDC* pDC,CPrintInfo* pInfo = NULL);
private:
void PersistRatio (const CSize &orig,CSize &dest,CPoint &remainder);
void CalcBars (BOOL bInvalidate = TRUE);
ZOOMMODE m_zoomMode;
CURSORZOOMMODE m_cursorZoomMode;
BOOL m_bCaptured;
CRect m_ptDragRect;
CSize m_origTotalDev;// original total size in device units
CSize m_origPageDev; // original per page scroll size in device units
CSize m_origLineDev; // original per line scroll size in device units
double m_zoomScale;
HCURSOR m_hZoomCursor;
DECLARE_MESSAGE_MAP()
};
#endif // _CZOOMVIEW_H
| [
"[email protected]"
] | [
[
[
1,
121
]
]
] |
0e7b6e5f07337669a9a2e9ccd474789e42649d10 | 9566086d262936000a914c5dc31cb4e8aa8c461c | /EnigmaProtocol/Messages/MessageContainer.cpp | 97413d9d4120e6751fd0df8c85ce8d779f24167d | [] | no_license | pazuzu156/Enigma | 9a0aaf0cd426607bb981eb46f5baa7f05b66c21f | b8a4dfbd0df206e48072259dbbfcc85845caad76 | refs/heads/master | 2020-06-06T07:33:46.385396 | 2011-12-19T03:14:15 | 2011-12-19T03:14:15 | 3,023,618 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 13,520 | cpp | /*
Copyright © 2009 Christopher Joseph Dean Schaefer (disks86)
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 "MessageContainer.hpp"
namespace Enigma
{
MessageContainer::MessageContainer()
{
this->mMessage.signed32BitIntegerPointer=NULL;
this->mReliable=true;
this->mOwnsUnion=false;
this->mOwnsMessageString=false;
this->mIsDirty=false;
this->mChannel=CHANNEL_NONE; //this should always be changed.
}
MessageContainer::MessageContainer(Message message)
{
this->mMessage=message;
this->mReliable=true;
this->mOwnsUnion=false;
this->mOwnsMessageString=false;
this->mIsDirty=false;
this->mChannel=CHANNEL_NONE; //this should always be changed.
}
MessageContainer::MessageContainer(Enigma::c8* message)
{
this->mMessage.signed32BitIntegerPointer=NULL;
this->mReliable=true;
this->mOwnsUnion=false;
this->mOwnsMessageString=false;
this->mIsDirty=false;
this->mChannel=CHANNEL_NONE; //this should always be changed.
this->SetInnerMessage(message);
}
MessageContainer::MessageContainer(std::string& message)
{
this->mMessage.signed32BitIntegerPointer=NULL;
this->mReliable=true;
this->mOwnsUnion=false;
this->mOwnsMessageString=false;
this->mIsDirty=false;
this->mChannel=CHANNEL_NONE; //this should always be changed.
this->SetInnerMessage(message);
}
MessageContainer::~MessageContainer()
{
this->Clear("MessageContainer::~MessageContainer()");
}
void MessageContainer::PrintMessage()
{
std::cout << "Message: " << this->GetMessageUnion().unsigned8BitIntegerPointer << std::endl;
}
Message& MessageContainer::GetMessageUnion()
{
return this->mMessage;
}
void MessageContainer::SetMessageUnion(Message message)
{
this->Clear("MessageContainer::SetMessageUnion(Message&)");
this->mMessage=message;
this->mOwnsUnion=false;
this->mOwnsMessageString=false;
}
Enigma::s32 MessageContainer::GetType()
{
if(this->mMessage.signed32BitIntegerPointer!=NULL)
{
return this->mMessage.signed32BitIntegerPointer[MESSAGE_TYPE];
}
else
{
return 0;
}
}
void MessageContainer::SetType(Enigma::s32 value)
{
if(this->mMessage.signed32BitIntegerPointer!=NULL)
{
this->mMessage.signed32BitIntegerPointer[MESSAGE_TYPE]=value;
}
else
{
std::cout << "Message is NULL: MessageContainer::SetType" << std::endl;
}
}
Enigma::s32 MessageContainer::GetLength()
{
if(this->mMessage.signed32BitIntegerPointer!=NULL)
{
return this->mMessage.signed32BitIntegerPointer[MESSAGE_LENGTH];
}
else
{
return 0;
}
}
void MessageContainer::SetLength(Enigma::s32 value)
{
if(this->mMessage.signed32BitIntegerPointer!=NULL)
{
this->mMessage.signed32BitIntegerPointer[MESSAGE_LENGTH]=value;
}
else
{
std::cout << "Message is NULL: MessageContainer::SetLength" << std::endl;
}
}
Enigma::s32 MessageContainer::GetStatus()
{
if(this->mMessage.signed32BitIntegerPointer!=NULL)
{
return this->mMessage.signed32BitIntegerPointer[MESSAGE_STATUS];
}
else
{
return STATUS_UNKNOWN_FAIL;
}
}
void MessageContainer::SetStatus(Enigma::s32 value)
{
if(this->mMessage.signed32BitIntegerPointer!=NULL)
{
this->mMessage.signed32BitIntegerPointer[MESSAGE_STATUS]=value;
}
else
{
std::cout << "Message is NULL: MessageContainer::SetStatus" << std::endl;
}
}
bool MessageContainer::GetReliable() const
{
return this->mReliable;
}
void MessageContainer::SetReliable(bool value)
{
this->mReliable=value;
}
size_t MessageContainer::GetChannel() const
{
if(this->mChannel==CHANNEL_NONE)
{
throw new EnigmaException("Message channel not valid!"); //this should make it easier to detect failure to assign channels on derived classes.
}
return this->mChannel;
}
void MessageContainer::SetChannel(size_t value)
{
if(value==CHANNEL_NONE)
{
throw new EnigmaException("Message channel not valid!");
}
this->mChannel=value;
}
//Return message minus the length & type.
Enigma::c8* MessageContainer::GetInnerMessage()
{
if(this->mMessage.signed8BitIntegerPointer!=NULL)
{
return (Enigma::c8*)this->mMessage.signed8BitIntegerPointer+(sizeof(Enigma::s32)*MessageContainer::GetMessageLength());
}
else
{
return "";
}
}
//Set a new inner message.
void MessageContainer::SetInnerMessage(const std::string& message)
{
this->SetInnerMessage(message.size(),message.c_str());
}
//Set a new inner message.
void MessageContainer::SetInnerMessage(const Enigma::c8* message)
{
this->SetInnerMessage(strlen(message),message);
}
//Set a new inner message.
void MessageContainer::SetInnerMessage(size_t size,const Enigma::c8* message)
{
this->ResizeMessage(size/2,0);
strcpy(this->GetInnerMessage(),message);
this->mOwnsMessageString=true; //because this is a copy.
}
//Resize message.
void MessageContainer::ResizeMessage(size_t size,int type)
{
try
{
int newSize=0;
int newType=0;
int charSize=0;
int paddingSize=1;
newSize = MessageContainer::GetMessageLength()+paddingSize+size;
charSize=sizeof(Enigma::s32)/sizeof(Enigma::c8)*newSize;
if(this->mMessage.signed32BitIntegerPointer!=NULL)
{
newType = this->GetType();
delete[] this->mMessage.signed32BitIntegerPointer;
this->mMessage.signed32BitIntegerPointer=NULL;
}
//Added () which as of C++03 initializes the allocated memory.
this->mMessage.signed32BitIntegerPointer = new Enigma::s32[newSize]();
//This may no longer be required but I'll leave it just in case \0 isn't really 0.
this->mMessage.unsigned8BitIntegerPointer[charSize-1]='\0';
this->mOwnsMessageString=true;
this->SetType(newType);
this->SetLength(charSize);
this->SetStatus(STATUS_OK);
this->mIsDirty=true;
}
catch(Enigma::EnigmaException& e)
{
std::cout << "Enigma Exception: " << e.what() << std::endl;
}
catch (Enigma::HardwareException&)
{
throw;
}
catch (std::overflow_error&)
{
throw; //may need to pop some calls off the stack.
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
}
void MessageContainer::Clear(const Enigma::c8* callerName)
{
if(this->mIsDirty && this->mMessage.signed32BitIntegerPointer!=NULL)
{
this->mIsDirty=false;
if(this->mOwnsMessageString)
{
delete[] this->mMessage.signed32BitIntegerPointer;
this->mMessage.signed32BitIntegerPointer=NULL;
this->mOwnsMessageString=false;
}
else
{
std::cout << "Message String not owned by container string not deallocated." << std::endl;
}
}
else
{
//spams the console. even though calls are from destructor.
//std::cout << "Extra call to MessageContainer::Clear() from " << callerName << "." << std::endl;
}
}
void MessageContainer::SkipAutomaticCleanup()
{
this->mIsDirty=false;
}
u64 MessageContainer::GetSimpleChecksum(Enigma::u8* data,size_t length)
{
u64 total=0;
for(size_t i=0;i<length;i++)
{
total+=(u64)data[i];
}
return total;
}
Enigma::u32 MessageContainer::GetFletcherChecksum(Enigma::u16* data,size_t length)
{
Enigma::u32 a=0xffff;
Enigma::u32 b=0xffff;
Enigma::u32 tlength=0;
while(length)
{
tlength = length > 360 ? 360 : length;
length -= tlength;
do
{
a += *data++;
b += a;
}
while(--tlength);
a = (a & 0xffff) + (a >> 16);
b = (b & 0xffff) + (b >> 16);
}
a = (a & 0xffff) + (a >> 16);
b = (b & 0xffff) + (b >> 16);
return b << 16 | a;
}
Enigma::u32 MessageContainer::GetAdlerChecksum(Enigma::u8* data,size_t length)
{
Enigma::u32 a=0;
Enigma::u32 b=0;
const size_t MOD_ADLER=65521;
for(size_t i=0;i<length;i++)
{
a = (a+data[i]) % MOD_ADLER;
b = (b+a) % MOD_ADLER;
}
return (b << 16) | a;
}
Enigma::f32 MessageContainer::GetFloat(size_t index)
{
index+=MessageContainer::GetMessageLength();
return this->mMessage.signed32BitFloatPointer[index];
}
void MessageContainer::SetFloat(size_t index,Enigma::f32 value)
{
index+=MessageContainer::GetMessageLength();
this->mMessage.signed32BitFloatPointer[index]=value;
}
Enigma::s32 MessageContainer::GetInt(size_t index)
{
index+=MessageContainer::GetMessageLength();
return this->mMessage.signed32BitIntegerPointer[index];
}
void MessageContainer::SetInt(size_t index,Enigma::s32 value)
{
index+=MessageContainer::GetMessageLength();
this->mMessage.signed32BitIntegerPointer[index]=value;
}
Enigma::c8* MessageContainer::GetString(size_t index)
{
index+=MessageContainer::GetMessageLength();
return (Enigma::c8*)this->mMessage.signed8BitIntegerPointer+index*sizeof(Enigma::s32);
}
void MessageContainer::SetString(size_t index,std::string& value)
{
this->SetString(index,value.c_str());
}
void MessageContainer::SetString(size_t index,const std::string& value)
{
this->SetString(index,value.c_str());
}
void MessageContainer::SetString(size_t index,const Enigma::c8* value)
{
Enigma::c8* target=NULL;
target = this->GetString(index); //grab pointer to correct spot in message.
strcpy(target,value);
}
Enigma::u8* MessageContainer::GetBytes(size_t index,size_t& size)
{
size_t byteOffset = (index+MessageContainer::GetMessageLength())*sizeof(Enigma::s32);
Enigma::u8* result = this->mMessage.unsigned8BitIntegerPointer+byteOffset;
//total length minus fixed length equals variable length.
size = ( this->GetLength() - (index+MessageContainer::GetMessageLength()+1)*sizeof(Enigma::s32) );
return result;
}
void MessageContainer::SetBytes(size_t index,size_t length,const Enigma::u8* value)
{
size_t byteOffset = (index+MessageContainer::GetMessageLength())*sizeof(Enigma::s32);
size_t newSize = index+(length/sizeof(Enigma::s32));
//convert byte length to int length and add index then resize message to that size.
this->ResizeMessage(newSize,this->GetType());
Enigma::u8* target = this->mMessage.unsigned8BitIntegerPointer+byteOffset;
//copy byte data to message.
memcpy(target,value,length);
//diagnostic
/*std::cout << "Samples: ";
Enigma::u16* samples = (Enigma::u16*)target;
for(size_t i=0;i<(length/sizeof(Enigma::u16));i++)
{
std::cout << samples[i];
}
std::cout << std::endl;*/
}
u64 MessageContainer::GetChecksum()
{
return MessageContainer::GetSimpleChecksum(this->mMessage.unsigned8BitIntegerPointer,this->GetLength());
}
std::ostream& operator<< (std::ostream& os,const MessageContainer& value)
{
MessageContainer messageContainer=const_cast<MessageContainer&>(value);
return os << messageContainer.GetMessageUnion().unsigned8BitIntegerPointer << std::endl;
}
};
| [
"[email protected]"
] | [
[
[
1,
449
]
]
] |
91f93d1c80d11acef87f40069e06fa356022d4eb | cfa667b1f83649600e78ea53363ee71dfb684d81 | /code/editor/app/editorapplication.cc | 30c6caa00abfedaf535aae3ae04d505e78feb85e | [] | no_license | zhouxh1023/nebuladevice3 | c5f98a9e2c02828d04fb0e1033f4fce4119e1b9f | 3a888a7c6e6d1a2c91b7ebd28646054e4c9fc241 | refs/heads/master | 2021-01-23T08:56:15.823698 | 2011-08-26T02:22:25 | 2011-08-26T02:22:25 | 32,018,644 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,791 | cc | //------------------------------------------------------------------------------
// editorapplication.cc
// (C) 2011 xiongyouyi
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "editorapplication.h"
#include "basegamefeature/statehandlers/gamestatehandler.h"
#include "basegamefeature/basegamefeatureunit.h"
#include "graphicsfeature/graphicsfeatureunit.h"
#include "appgame/statehandler.h"
#include "game/entity.h"
#include "attr/attribute.h"
#include "properties/mayacameraproperty.h"
#include "debugrender/debugrender.h"
namespace Editor
{
using namespace BaseGameFeature;
using namespace Graphics;
using namespace Math;
using namespace Util;
using namespace Resources;
using namespace Timing;
using namespace GraphicsFeature;
__ImplementSingleton(EditorApplication);
//------------------------------------------------------------------------------
/**
*/
EditorApplication::EditorApplication()
: graphicsFeature(0)
, baseGameFeature(0)
, windowMsgHandler(0)
, activeEditTool(0)
{
__ConstructSingleton;
}
//------------------------------------------------------------------------------
/**
*/
EditorApplication::~EditorApplication()
{
if (this->IsOpen())
{
this->Close();
}
__DestructSingleton;
}
//------------------------------------------------------------------------------
/**
*/
void
EditorApplication::SetupStateHandlers()
{
// create our standard gamestatehandler
Ptr<GameStateHandler> gameState = GameStateHandler::Create();
gameState->SetSetupMode(GameStateHandler::NewGame);
gameState->SetName("GameState");
gameState->SetLevelName("testlevel");
this->AddStateHandler(gameState.get());
this->SetState("GameState");
}
//------------------------------------------------------------------------------
/**
*/
void
EditorApplication::SetupGameFeatures()
{
GameApplication::SetupGameFeatures();
// create and attach default graphic features
this->graphicsFeature = GraphicsFeature::GraphicsFeatureUnit::Create();
this->graphicsFeature->SetCmdLineArgs(this->GetCmdLineArgs());
this->graphicsFeature->SetRenderDebug(true);
this->gameServer->AttachGameFeature(this->graphicsFeature.cast<Game::FeatureUnit>());
// game features
this->baseGameFeature = BaseGameFeature::BaseGameFeatureUnit::Create();
this->baseGameFeature->SetRenderDebug(true);
this->gameServer->AttachGameFeature(this->baseGameFeature.upcast<Game::FeatureUnit>());
#if __USE_PHYSICS__
// create and attach core features
this->physicsFeature = PhysicsFeature::PhysicsFeatureUnit::Create();
this->gameServer->AttachGameFeature(this->physicsFeature.upcast<Game::FeatureUnit>());
#endif
}
//------------------------------------------------------------------------------
/**
Cleanup all added game features
*/
void
EditorApplication::CleanupGameFeatures()
{
this->gameServer->RemoveGameFeature(this->baseGameFeature.upcast<Game::FeatureUnit>());
this->baseGameFeature = 0;
this->gameServer->RemoveGameFeature(this->graphicsFeature.upcast<Game::FeatureUnit>());
this->graphicsFeature = 0;
#if __USE_PHYSICS__
this->gameServer->RemoveGameFeature(this->physicsFeature.upcast<Game::FeatureUnit>());
this->physicsFeature = 0;
#endif
GameApplication::CleanupGameFeatures();
}
//------------------------------------------------------------------------------
/**
*/
bool
EditorApplication::Open()
{
n_assert(this->GetCmdLineArgs().HasArg("-externalwindow"));
bool ret = App::GameApplication::Open();
HWND hwnd = (HWND)(this->GetCmdLineArgs().GetInt("-externalwindow"));
this->windowMsgHandler = new WindowMessageHandler(hwnd);
return ret;
}
//------------------------------------------------------------------------------
/**
*/
void
EditorApplication::Close()
{
App::GameApplication::Close();
}
//------------------------------------------------------------------------------
/**
begin update
*/
void
EditorApplication::BeginUpdate()
{
GraphicsInterface::Instance()->EnterLockStepMode();
}
//------------------------------------------------------------------------------
/**
update one frame
*/
void
EditorApplication::UpdateOneFrame()
{
if (this->GetCurrentState() != "Exit")
{
_start_timer(GameApplicationFrameTimeAll);
#if __NEBULA3_HTTP__
this->httpServerProxy->HandlePendingRequests();
this->remoteControlProxy->HandlePendingCommands();
#endif
this->coreServer->Trigger();
if (this->activeEditTool != NULL)
{
this->activeEditTool->OnUpdate();
}
// first trigger our game server, which triggers all game features
this->gameServer->OnFrame();
String curState = this->GetCurrentState();
Ptr<App::StateHandler> curStateHandler;
String newState;
if (curState.IsValid())
{
// call the current state handler
curStateHandler = this->FindStateHandlerByName(curState);
n_assert(curStateHandler);
newState = curStateHandler->OnFrame();
}
// call the app's Run() method
Application::Run();
// a requested state always overrides the returned state
if (this->requestedState.IsValid())
{
this->SetState(this->requestedState);
}
else if (newState.IsValid() && newState != curStateHandler->GetName())
{
// a normal state transition
this->SetState(newState);
}
_stop_timer(GameApplicationFrameTimeAll);
}
}
//------------------------------------------------------------------------------
/**
end update
*/
void
EditorApplication::EndUpdate()
{
GraphicsInterface::Instance()->LeaveLockStepMode();
this->SetState("Exit");
}
//------------------------------------------------------------------------------
/**
*/
Ptr<EditTool>
EditorApplication::GetEditTool(const Util::String& className)
{
Ptr<EditTool> tool = NULL;
String name(className);
if (className.FindStringIndex("Editor::", 0) == InvalidIndex)
{
name = "Editor::" + name;
}
if (Core::Factory::Instance()->ClassExists(name))
{
tool = (EditTool*)Core::Factory::Instance()->Create(name);
}
return tool;
}
//------------------------------------------------------------------------------
/**
*/
void
EditorApplication::SetActiveTool(const Ptr<EditTool>& tool)
{
if (this->activeEditTool == tool)
{
return;
}
if (this->activeEditTool != NULL)
{
this->activeEditTool->OnDeactivate();
}
this->activeEditTool = tool;
if (this->activeEditTool != NULL)
{
this->activeEditTool->OnActivate();
}
}
} // namespace Tools
| [
"[email protected]"
] | [
[
[
1,
264
]
]
] |
fad2360b272add4674be86b700c75d508692a76c | b369aabb8792359175aedfa50e949848ece03180 | /src/glWin/ViewGL.cpp | 57751b686399d5424f619038e2cdf704a473ecea | [] | no_license | LibreGamesArchive/magiccarpet | 6d49246817ab913f693f172fcfc53bf4cc153842 | 39210d57096d5c412de0f33289fbd4d08c20899b | refs/heads/master | 2021-05-08T02:00:46.182694 | 2009-01-06T20:25:36 | 2009-01-06T20:25:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,401 | cpp | ///////////////////////////////////////////////////////////////////////////////
// ViewGL.cpp
// ==========
// View component of OpenGL window
//
// AUTHORL Song Ho Ahn ([email protected])
// CREATED: 2006-07-10
// UPDATED: 2006-07-10
///////////////////////////////////////////////////////////////////////////////
#include "ViewGL.h"
#include "resource.h"
using namespace Win;
///////////////////////////////////////////////////////////////////////////////
// default ctor
///////////////////////////////////////////////////////////////////////////////
ViewGL::ViewGL() : hdc(0), hglrc(0)
{
}
///////////////////////////////////////////////////////////////////////////////
// default dtor
///////////////////////////////////////////////////////////////////////////////
ViewGL::~ViewGL()
{
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void ViewGL::closeContext(HWND handle)
{
if(!hdc || !hglrc)
return;
// delete DC and RC
::wglMakeCurrent(0, 0);
::wglDeleteContext(hglrc);
::ReleaseDC(handle, hdc);
hdc = 0;
hglrc = 0;
}
///////////////////////////////////////////////////////////////////////////////
// create OpenGL rendering context
///////////////////////////////////////////////////////////////////////////////
bool ViewGL::createContext(HWND handle, int colorBits, int depthBits, int stencilBits)
{
// retrieve a handle to a display device context
hdc = ::GetDC(handle);
// set pixel format
if(!setPixelFormat(hdc, colorBits, depthBits, stencilBits))
{
::MessageBox(0, L"Cannot set a suitable pixel format.", L"Error", MB_ICONEXCLAMATION | MB_OK);
//::MessageBox(0, "Cannot set a suitable pixel format.", "Error", MB_ICONEXCLAMATION | MB_OK);
::ReleaseDC(handle, hdc); // remove device context
return false;
}
// create a new OpenGL rendering context
hglrc = ::wglCreateContext(hdc);
//::wglMakeCurrent(hdc, hglrc);
::ReleaseDC(handle, hdc);
return true;
}
///////////////////////////////////////////////////////////////////////////////
// choose pixel format
// By default, pdf.dwFlags is set PFD_DRAW_TO_WINDOW, PFD_DOUBLEBUFFER and PFD_SUPPORT_OPENGL.
///////////////////////////////////////////////////////////////////////////////
bool ViewGL::setPixelFormat(HDC hdc, int colorBits, int depthBits, int stencilBits)
{
PIXELFORMATDESCRIPTOR pfd;
// find out the best matched pixel format
int pixelFormat = findPixelFormat(hdc, colorBits, depthBits, stencilBits);
if(pixelFormat == 0)
return false;
// set members of PIXELFORMATDESCRIPTOR with given mode ID
::DescribePixelFormat(hdc, pixelFormat, sizeof(pfd), &pfd);
// set the fixel format
if(!::SetPixelFormat(hdc, pixelFormat, &pfd))
return false;
return true;
}
///////////////////////////////////////////////////////////////////////////////
// find the best pixel format
///////////////////////////////////////////////////////////////////////////////
int ViewGL::findPixelFormat(HDC hdc, int colorBits, int depthBits, int stencilBits)
{
int currMode; // pixel format mode ID
int bestMode = 0; // return value, best pixel format
int currScore = 0; // points of current mode
int bestScore = 0; // points of best candidate
PIXELFORMATDESCRIPTOR pfd;
// search the available formats for the best mode
bestMode = 0;
bestScore = 0;
for(currMode = 1; ::DescribePixelFormat(hdc, currMode, sizeof(pfd), &pfd) > 0; ++currMode)
{
// ignore if cannot support opengl
if(!(pfd.dwFlags & PFD_SUPPORT_OPENGL))
continue;
// ignore if cannot render into a window
if(!(pfd.dwFlags & PFD_DRAW_TO_WINDOW))
continue;
// ignore if cannot support rgba mode
if((pfd.iPixelType != PFD_TYPE_RGBA) || (pfd.dwFlags & PFD_NEED_PALETTE))
continue;
// ignore if not double buffer
if(!(pfd.dwFlags & PFD_DOUBLEBUFFER))
continue;
// try to find best candidate
currScore = 0;
// colour bits
if(pfd.cColorBits >= colorBits) ++currScore;
if(pfd.cColorBits == colorBits) ++currScore;
// depth bits
if(pfd.cDepthBits >= depthBits) ++currScore;
if(pfd.cDepthBits == depthBits) ++currScore;
// stencil bits
if(pfd.cStencilBits >= stencilBits) ++currScore;
if(pfd.cStencilBits == stencilBits) ++currScore;
// alpha bits
if(pfd.cAlphaBits > 0) ++currScore;
// check if it is best mode so far
if(currScore > bestScore)
{
bestScore = currScore;
bestMode = currMode;
}
}
return bestMode;
}
///////////////////////////////////////////////////////////////////////////////
// swap OpenGL frame buffers
///////////////////////////////////////////////////////////////////////////////
void ViewGL::swapBuffers()
{
::SwapBuffers(hdc);
}
| [
"[email protected]"
] | [
[
[
1,
175
]
]
] |
92a3571cd81f1370154ab7c1d9b48c6983c22732 | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/MapRenderer/include/loaders/GroundTextures.h | 70145dfac27edfdae950c4e539e806349e3c97c2 | [] | no_license | bravesoftdz/iris-svn | 8f30b28773cf55ecf8951b982370854536d78870 | c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4 | refs/heads/master | 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,479 | h | //
// File: GroundTextures.h
// Created by: Alexander Oster - [email protected]
//
/*****
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*****/
#ifndef _GROUNDTEXTURES_H_
#define _GROUNDTEXTURES_H_
#ifdef WIN32
#include <windows.h>
#endif
#include <iostream>
#include <fstream>
#include <cstring>
#include "include.h"
#include "../renderer/Texture.h"
class cGroundTextureLoader
{
private:
std::ifstream * texmapsfile;
std::ifstream * texmapsindex;
unsigned int groundtex_count;
public:
cGroundTextureLoader (std::string filename, std::string indexname);
~cGroundTextureLoader ();
Texture * LoadTexture(int index);
protected:
};
extern cGroundTextureLoader * pGroundTextureLoader;
#endif //_GROUNDTEXTURES_H_
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
] | [
[
[
1,
55
]
]
] |
04a3f66f33ef80675deb832fdd2098afa9a37b19 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/src/sem_destroy.cpp | 55093b580639d5b03a43f7f1bf483963ef1bcc87 | [] | 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,975 | cpp | /*
* Copyright (c) 2005-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: sem_destroy call is implemented.
*
*
*
*/
#include <e32def.h>
#include <errno.h>
#include "semaphore.h"
#include "semaphoretypes.h"
#include "pthread.h"
EXPORT_C int sem_destroy (sem_t * sem)
{
if (!sem || !(*sem))
{
errno = EINVAL;
return -1;
}
_sem_t* lsem = *sem;
if (_findAndFreeSem(lsem) == _SEM_NOT_FOUND_IN_LIST)
{
errno = EINVAL;
return -1;
}
if(lsem->iState != _sem_t::EInitialized)
{
errno = EINVAL;
return -1;
}
if(lsem->iCount <0)
{
// Add sem to sem-list
_addToSemList(lsem);
errno = EBUSY;
return -1;
}
#ifndef NOUSE_INTERNALS
void* tlsPtr;
// Get the TLS pointer
tlsPtr = _pthread_getTls();
if(NULL == tlsPtr)
{
User::Panic(_L("pthread lib could not initailize"),0);
errno = EBUSY;
return -1;
}
_pthread_atomicMutexLock(tlsPtr);
#endif
if(lsem->iState == _sem_t::EDestroyed)
{
#ifndef NOUSE_INTERNALS
_pthread_atomicMutexUnlock(tlsPtr);
#endif
return 0;
}
lsem->iMutex.Wait();
lsem->iState = _sem_t::EDestroyed;
lsem->iSemaphore.Close();
lsem->iMutex.Signal();
lsem->iMutex.Close();
delete lsem;
*sem = NULL;
#ifndef NOUSE_INTERNALS
_pthread_atomicMutexUnlock(tlsPtr);
#endif
return 0;
}//sem_destroy()
//End of File
| [
"none@none"
] | [
[
[
1,
97
]
]
] |
77303ca33b67107646f3d84b369801c9b140456f | 40e58042e635ea2a61a6216dc3e143fd3e14709c | /paradebot10/pneumatics.h | b6c2058fcd6e534fce22d5ee95ccd526c6622230 | [] | no_license | chopshop-166/frc-2011 | 005bb7f0d02050a19bdb2eb33af145d5d2916a4d | 7ef98f84e544a17855197f491fc9f80247698dd3 | refs/heads/master | 2016-09-05T10:59:54.976527 | 2011-10-20T22:50:17 | 2011-10-20T22:50:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,625 | h | /*******************************************************************************
* Project : chopshop10 - 2010 Chopshop Robot Controller Code
* File Name : TaskTemplate.h
* Owner : Software Group (FIRST Chopshop Team 166)
* Creation Date : January 18, 2010
* Revision History : From Explorer with TortoiseSVN, Use "Show log" menu item
* File Description : Pneumatics header file for tasks, with template functions
*******************************************************************************/
/*----------------------------------------------------------------------------*/
/* Copyright (c) MHS Chopshop Team 166, 2010. All Rights Reserved. */
/*----------------------------------------------------------------------------*/
#if !defined(PNEUMATICS_H)
#define PNEUMATICS_H
#include "WPILib.h"
#include "Robot.h"
//
// This constant defines how often we want this task to run in the form
// of miliseconds. Max allowed time is 999 miliseconds.
// You should rename this when you copy it into a new file
#define PNEUMATICS_CYCLE_TIME (10) // 10ms
// Rename this, too, or you'll run into collisions
class Pneumatics166 : public Team166Task
{
public:
// task constructor
Pneumatics166(void);
// task destructor
virtual ~Pneumatics166(void);
// Main function of the task
virtual int Main(int a2, int a3, int a4, int a5,
int a6, int a7, int a8, int a9, int a10);
private:
// Any variables that the task has as members go here
Compressor compressor;
Solenoid cylinder_open;
Relay fans;
};
#endif // !defined(PNEUMATICS_H)
| [
"[email protected]"
] | [
[
[
1,
47
]
]
] |
f8b2d6c211a4286055c160c0364ffe92a1138e25 | a84b013cd995870071589cefe0ab060ff3105f35 | /webdriver/branches/chrome/chrome/src/cpp/include/v8/src/token.h | 48ffda33c818f844487ab3900925deff8115e051 | [
"Apache-2.0"
] | permissive | vdt/selenium | 137bcad58b7184690b8785859d77da0cd9f745a0 | 30e5e122b068aadf31bcd010d00a58afd8075217 | refs/heads/master | 2020-12-27T21:35:06.461381 | 2009-08-18T15:56:32 | 2009-08-18T15:56:32 | 13,650,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,743 | h | // Copyright 2006-2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef V8_TOKEN_H_
#define V8_TOKEN_H_
namespace v8 { namespace internal {
// TOKEN_LIST takes a list of 3 macros M, all of which satisfy the
// same signature M(name, string, precedence), where name is the
// symbolic token name, string is the corresponding syntactic symbol
// (or NULL, for literals), and precedence is the precedence (or 0).
// The parameters are invoked for token categories as follows:
//
// T: Non-keyword tokens
// K: Keyword tokens
// F: Future (reserved) keyword tokens
// IGNORE_TOKEN is a convenience macro that can be supplied as
// an argument (at any position) for a TOKEN_LIST call. It does
// nothing with tokens belonging to the respective category.
#define IGNORE_TOKEN(name, string, precedence)
#define TOKEN_LIST(T, K, F) \
/* End of source indicator. */ \
T(EOS, "EOS", 0) \
\
/* Punctuators (ECMA-262, section 7.7, page 15). */ \
T(LPAREN, "(", 0) \
T(RPAREN, ")", 0) \
T(LBRACK, "[", 0) \
T(RBRACK, "]", 0) \
T(LBRACE, "{", 0) \
T(RBRACE, "}", 0) \
T(COLON, ":", 0) \
T(SEMICOLON, ";", 0) \
T(PERIOD, ".", 0) \
T(CONDITIONAL, "?", 3) \
T(INC, "++", 0) \
T(DEC, "--", 0) \
\
/* Assignment operators. */ \
/* IsAssignmentOp() relies on this block of enum values */ \
/* being contiguous and sorted in the same order! */ \
T(INIT_VAR, "=init_var", 2) /* AST-use only. */ \
T(INIT_CONST, "=init_const", 2) /* AST-use only. */ \
T(ASSIGN, "=", 2) \
T(ASSIGN_BIT_OR, "|=", 2) \
T(ASSIGN_BIT_XOR, "^=", 2) \
T(ASSIGN_BIT_AND, "&=", 2) \
T(ASSIGN_SHL, "<<=", 2) \
T(ASSIGN_SAR, ">>=", 2) \
T(ASSIGN_SHR, ">>>=", 2) \
T(ASSIGN_ADD, "+=", 2) \
T(ASSIGN_SUB, "-=", 2) \
T(ASSIGN_MUL, "*=", 2) \
T(ASSIGN_DIV, "/=", 2) \
T(ASSIGN_MOD, "%=", 2) \
\
/* Binary operators sorted by precedence. */ \
/* IsBinaryOp() relies on this block of enum values */ \
/* being contiguous and sorted in the same order! */ \
T(COMMA, ",", 1) \
T(OR, "||", 4) \
T(AND, "&&", 5) \
T(BIT_OR, "|", 6) \
T(BIT_XOR, "^", 7) \
T(BIT_AND, "&", 8) \
T(SHL, "<<", 11) \
T(SAR, ">>", 11) \
T(SHR, ">>>", 11) \
T(ADD, "+", 12) \
T(SUB, "-", 12) \
T(MUL, "*", 13) \
T(DIV, "/", 13) \
T(MOD, "%", 13) \
\
/* Compare operators sorted by precedence. */ \
/* IsCompareOp() relies on this block of enum values */ \
/* being contiguous and sorted in the same order! */ \
T(EQ, "==", 9) \
T(NE, "!=", 9) \
T(EQ_STRICT, "===", 9) \
T(NE_STRICT, "!==", 9) \
T(LT, "<", 10) \
T(GT, ">", 10) \
T(LTE, "<=", 10) \
T(GTE, ">=", 10) \
K(INSTANCEOF, "instanceof", 10) \
K(IN, "in", 10) \
\
/* Unary operators. */ \
/* IsUnaryOp() relies on this block of enum values */ \
/* being contiguous and sorted in the same order! */ \
T(NOT, "!", 0) \
T(BIT_NOT, "~", 0) \
K(DELETE, "delete", 0) \
K(TYPEOF, "typeof", 0) \
K(VOID, "void", 0) \
\
/* Keywords (ECMA-262, section 7.5.2, page 13). */ \
K(BREAK, "break", 0) \
K(CASE, "case", 0) \
K(CATCH, "catch", 0) \
K(CONTINUE, "continue", 0) \
K(DEBUGGER, "debugger", 0) \
K(DEFAULT, "default", 0) \
/* DELETE */ \
K(DO, "do", 0) \
K(ELSE, "else", 0) \
K(FINALLY, "finally", 0) \
K(FOR, "for", 0) \
K(FUNCTION, "function", 0) \
K(IF, "if", 0) \
/* IN */ \
/* INSTANCEOF */ \
K(NEW, "new", 0) \
K(RETURN, "return", 0) \
K(SWITCH, "switch", 0) \
K(THIS, "this", 0) \
K(THROW, "throw", 0) \
K(TRY, "try", 0) \
/* TYPEOF */ \
K(VAR, "var", 0) \
/* VOID */ \
K(WHILE, "while", 0) \
K(WITH, "with", 0) \
\
/* Future reserved words (ECMA-262, section 7.5.3, page 14). */ \
F(ABSTRACT, "abstract", 0) \
F(BOOLEAN, "boolean", 0) \
F(BYTE, "byte", 0) \
F(CHAR, "char", 0) \
F(CLASS, "class", 0) \
K(CONST, "const", 0) \
F(DOUBLE, "double", 0) \
F(ENUM, "enum", 0) \
F(EXPORT, "export", 0) \
F(EXTENDS, "extends", 0) \
F(FINAL, "final", 0) \
F(FLOAT, "float", 0) \
F(GOTO, "goto", 0) \
F(IMPLEMENTS, "implements", 0) \
F(IMPORT, "import", 0) \
F(INT, "int", 0) \
F(INTERFACE, "interface", 0) \
F(LONG, "long", 0) \
K(NATIVE, "native", 0) \
F(PACKAGE, "package", 0) \
F(PRIVATE, "private", 0) \
F(PROTECTED, "protected", 0) \
F(PUBLIC, "public", 0) \
F(SHORT, "short", 0) \
F(STATIC, "static", 0) \
F(SUPER, "super", 0) \
F(SYNCHRONIZED, "synchronized", 0) \
F(THROWS, "throws", 0) \
F(TRANSIENT, "transient", 0) \
F(VOLATILE, "volatile", 0) \
\
/* Literals (ECMA-262, section 7.8, page 16). */ \
K(NULL_LITERAL, "null", 0) \
K(TRUE_LITERAL, "true", 0) \
K(FALSE_LITERAL, "false", 0) \
T(NUMBER, NULL, 0) \
T(STRING, NULL, 0) \
\
/* Identifiers (not keywords or future reserved words). */ \
T(IDENTIFIER, NULL, 0) \
\
/* Illegal token - not able to scan. */ \
T(ILLEGAL, "ILLEGAL", 0) \
\
/* Scanner-internal use only. */ \
T(COMMENT, NULL, 0)
class Token {
public:
// All token values.
#define T(name, string, precedence) name,
enum Value {
TOKEN_LIST(T, T, IGNORE_TOKEN)
NUM_TOKENS
};
#undef T
#ifdef DEBUG
// Returns a string corresponding to the C++ token name
// (e.g. "LT" for the token LT).
static const char* Name(Value tok) {
ASSERT(0 <= tok && tok < NUM_TOKENS);
return name_[tok];
}
#endif
// Predicates
static bool IsAssignmentOp(Value tok) {
return INIT_VAR <= tok && tok <= ASSIGN_MOD;
}
static bool IsBinaryOp(Value op) {
return COMMA <= op && op <= MOD;
}
static bool IsCompareOp(Value op) {
return EQ <= op && op <= IN;
}
static bool IsBitOp(Value op) {
return (BIT_OR <= op && op <= SHR) || op == BIT_NOT;
}
static bool IsUnaryOp(Value op) {
return (NOT <= op && op <= VOID) || op == ADD || op == SUB;
}
static bool IsCountOp(Value op) {
return op == INC || op == DEC;
}
// Returns a string corresponding to the JS token string
// (.e., "<" for the token LT) or NULL if the token doesn't
// have a (unique) string (e.g. an IDENTIFIER).
static const char* String(Value tok) {
ASSERT(0 <= tok && tok < NUM_TOKENS);
return string_[tok];
}
// Returns the precedence > 0 for binary and compare
// operators; returns 0 otherwise.
static int Precedence(Value tok) {
ASSERT(0 <= tok && tok < NUM_TOKENS);
return precedence_[tok];
}
// Returns the keyword value if str is a keyword;
// returns IDENTIFIER otherwise. The class must
// have been initialized.
static Value Lookup(const char* str);
// Must be called once to initialize the class.
// Multiple calls are ignored.
static void Initialize();
private:
#ifdef DEBUG
static const char* name_[NUM_TOKENS];
#endif
static const char* string_[NUM_TOKENS];
static int8_t precedence_[NUM_TOKENS];
};
} } // namespace v8::internal
#endif // V8_TOKEN_H_
| [
"noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9"
] | [
[
[
1,
281
]
]
] |
dd74ec3ddebb2b0a3d1033689b92863690cb5342 | bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2 | /Open GL Basic Engine/source/glutFramework/glutFramework/basicObject.cpp | a48c5730445bf83cb31af9a49b29c53e069cd780 | [] | no_license | CorwinJV/rvbgame | 0f2723ed3a4c1a368fc3bac69052091d2d87de77 | a4fc13ed95bd3e5a03e3c6ecff633fe37718314b | refs/heads/master | 2021-01-01T06:49:33.445550 | 2009-11-03T23:14:39 | 2009-11-03T23:14:39 | 32,131,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | cpp |
//private:
// double strength;
// double health;
// int movementSpeed;
// int jumpDistance;
// int climbHeight;
// direction facing;
basicObject::basicObject()
{
}
basicObject::~basicObject();
bool basicObject::moveForward()
bool turnLeft();
bool turnRight();
bool crouch();
bool jump();
bool punch();
bool activate();
bool wait();
| [
"corwin.j@5457d560-9b84-11de-b17c-2fd642447241"
] | [
[
[
1,
24
]
]
] |
0ff4da0f72a35e6aa3dca03cc2b8cfe5eac570a7 | ba193aec31ea43e0b4b231df6da8e152e77d42f8 | /raytrace/def.h | 746777d5ff258ba3b69f2b75bb4d75a456e7e8c2 | [] | no_license | normlguy/Raytracer | d36aedd84d733de329effb193579e487204f46ea | ab548d68c82c4012af3be1dee3d9a8f239830f7b | refs/heads/master | 2021-01-25T07:35:23.943729 | 2010-02-21T06:54:39 | 2010-02-21T06:54:39 | 249,102 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,398 | h | #ifndef _INC_DEF_H_
#define _INC_DEF_H_
#define SCRW 928
#define SCRH 672
#define PRIM_ARRAY_SIZE 20
#define HIT 1
#define MISS 0
#define INPRIM -1
#define VIEW_WINDOW_X1 -4
#define VIEW_WINDOW_Y1 3
#define VIEW_WINDOW_X2 4
#define VIEW_WINDOW_Y2 -3
#define CAM_X 0
#define CAM_Y 0
#define CAM_Z -1
#define WINDOW_TITLE "raytracer"
#define WINDOW_UPDATE_DELAY 0
#define MAX_RAY_DEPTH 6
#define EPSILON 0.0001f
#define RENDER_TILE_SIZE 16
#define ENABLE_SPEC_LIGHTING 1
#define ENABLE_REFLECTIONS 1
#define ENABLE_DIFFUSE_LIGHTING 1
#define ENABLE_HARD_SHADOWS 1
#define CLAMP( x, min, max ) (x < min) ? x = min : ( (x > max) ? x = max : );
#define __RGB( r, g, b ) int( r * 255 ), int( g * 255 ), int( b * 255 )
#define DOT(A,B) ( A["x"] * B["x"]+ A["y"] * B["y"] + A["z"] * B["z"] )
#define NORMALIZE(A) { float l = 1 / sqrtf( A["x"] * A["x"] + A["y"] * A["y"] + A["z"] * A["z"] ); A["x"] *= l; A["y"] *= l; A["z"] *= l; }
#define LENGTH(A) ( sqrtf( A["x"] * A["x"] + A["y"] * A["y"] + A["z"] * A["z"] ) )
#define SQRLENGTH(A) ( A["x"] * A["x"] + A["y"] * A["y"] + A["z"] * A["z"] )
#define SQRDISTANCE(A,B) ( ( A["x"] - B["x"] ) * ( A["x"] - ["x"] ) + ( A["y"] - B["y"] ) * ( A["y"] - B["y"] ) + ( A["z"] - B["z"] ) * ( A["z"] - B["z"] ) )
#define DEBUG 1
#define _OUT( x ) if( DEBUG ){ std::cout << x << "\n"; }
#endif // _INC_DEF_H_
| [
"[email protected]"
] | [
[
[
1,
47
]
]
] |
900a85b810cdadf4ebbe95dda2732253b781a890 | 9df2486e5d0489f83cc7dcfb3ccc43374ab2500c | /src/overworld/world_sprite_manager.h | c824ad4454d1a02c486529933c2f9470e75a32eb | [] | no_license | renardchien/Eta-Chronicles | 27ad4ffb68385ecaafae4f12b0db67c096f62ad1 | d77d54184ec916baeb1ab7cc00ac44005d4f5624 | refs/heads/master | 2021-01-10T19:28:28.394781 | 2011-09-05T14:40:38 | 2011-09-05T14:40:38 | 1,914,623 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,365 | h | /***************************************************************************
* world_sprite_manager.h - header for the corresponding cpp file
*
* Copyright (C) 2008 - 2009 Florian Richter
***************************************************************************/
/*
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SMC_WORLD_SPRITE_MANAGER_H
#define SMC_WORLD_SPRITE_MANAGER_H
#include "../core/globals.h"
#include "../core/sprite_manager.h"
#include "../overworld/overworld.h"
namespace SMC
{
/* *** *** *** *** *** cWorld_Sprite_Manager *** *** *** *** *** *** *** *** *** *** *** *** */
class cWorld_Sprite_Manager : public cSprite_Manager
{
public:
cWorld_Sprite_Manager( cOverworld *origin );
virtual ~cWorld_Sprite_Manager( void );
// Add a sprite
virtual void Add( cSprite *sprite );
// origin overworld
cOverworld *n_origin;
};
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
} // namespace SMC
#endif
| [
"[email protected]"
] | [
[
[
1,
45
]
]
] |
89fd58b472063f4507429866e2fb578029cf29a8 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/snk6502.h | 77df618fada2e55f82dbfade5c83d74cc0790e19 | [] | no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,466 | h | /*************************************************************************
rokola hardware
*************************************************************************/
#include "devlegcy.h"
#include "sound/discrete.h"
#include "sound/samples.h"
#include "sound/sn76477.h"
class snk6502_state : public driver_device
{
public:
snk6502_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
UINT8 m_sasuke_counter;
UINT8 *m_videoram;
UINT8 *m_colorram;
UINT8 *m_videoram2;
UINT8 *m_charram;
int m_charbank;
int m_backcolor;
tilemap_t *m_bg_tilemap;
tilemap_t *m_fg_tilemap;
rgb_t m_palette[64];
};
/*----------- defined in audio/snk6502.c -----------*/
extern const samples_interface sasuke_samples_interface;
extern const samples_interface vanguard_samples_interface;
extern const samples_interface fantasy_samples_interface;
extern const sn76477_interface sasuke_sn76477_intf_1;
extern const sn76477_interface sasuke_sn76477_intf_2;
extern const sn76477_interface sasuke_sn76477_intf_3;
extern const sn76477_interface satansat_sn76477_intf;
extern const sn76477_interface vanguard_sn76477_intf_1;
extern const sn76477_interface vanguard_sn76477_intf_2;
extern const sn76477_interface fantasy_sn76477_intf;
extern WRITE8_HANDLER( sasuke_sound_w );
extern WRITE8_HANDLER( satansat_sound_w );
extern WRITE8_HANDLER( vanguard_sound_w );
extern WRITE8_HANDLER( vanguard_speech_w );
extern WRITE8_HANDLER( fantasy_sound_w );
extern WRITE8_HANDLER( fantasy_speech_w );
DECLARE_LEGACY_SOUND_DEVICE(SNK6502, snk6502_sound);
void snk6502_set_music_clock(running_machine &machine, double clock_time);
void snk6502_set_music_freq(running_machine &machine, int freq);
int snk6502_music0_playing(running_machine &machine);
DISCRETE_SOUND_EXTERN( fantasy );
/*----------- defined in video/snk6502.c -----------*/
WRITE8_HANDLER( snk6502_videoram_w );
WRITE8_HANDLER( snk6502_videoram2_w );
WRITE8_HANDLER( snk6502_colorram_w );
WRITE8_HANDLER( snk6502_charram_w );
WRITE8_HANDLER( snk6502_flipscreen_w );
WRITE8_HANDLER( snk6502_scrollx_w );
WRITE8_HANDLER( snk6502_scrolly_w );
PALETTE_INIT( snk6502 );
VIDEO_START( snk6502 );
SCREEN_UPDATE( snk6502 );
VIDEO_START( pballoon );
WRITE8_HANDLER( satansat_b002_w );
WRITE8_HANDLER( satansat_backcolor_w );
PALETTE_INIT( satansat );
VIDEO_START( satansat );
| [
"Mike@localhost"
] | [
[
[
1,
84
]
]
] |
d884b399a8318cc883b20746da408b572a671ad0 | dd5c8920aa0ea96607f2498701c81bb1af2b3c96 | /stlplus/source/debug.cpp | 1ad7f0dd8d1516c95c87f1b13fa0e16ab9dfeb0e | [] | no_license | BackupTheBerlios/multicrew-svn | 913279401e9cf886476a3c912ecd3d2b8d28344c | 5087f07a100f82c37d2b85134ccc9125342c58d1 | refs/heads/master | 2021-01-23T13:36:03.990862 | 2005-06-10T16:52:32 | 2005-06-10T16:52:32 | 40,747,367 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,718 | cpp | /*------------------------------------------------------------------------------
Author: Andy Rushton
Copyright: (c) Andy Rushton, 2004
License: BSD License, see ../docs/license.html
------------------------------------------------------------------------------*/
#include "debug.hpp"
#include "string_utilities.hpp"
#include "file_system.hpp"
#include <stdlib.h>
////////////////////////////////////////////////////////////////////////////////
static const char* unknown_function = "";
////////////////////////////////////////////////////////////////////////////////
assert_failed::assert_failed(const char* file, int line, const char* function, const std::string& message) throw() :
std::logic_error(std::string(file) + std::string(":") + to_string(line) + std::string(":") +
std::string(function ? function : unknown_function) + std::string(": assertion failed: ") + message)
{
}
assert_failed::~assert_failed(void) throw()
{
}
////////////////////////////////////////////////////////////////////////////////
static unsigned debug_trace_depth = 0;
static bool debug_global = false;
static bool debug_set = false;
static bool debug_recurse = false;
static bool debug_read = false;
static char* debug_match = 0;
static const _debug_trace* debug_last = 0;
void _debug_global(const char* file, int line, const char* function, bool state)
{
debug_global = state;
fprintf(stderr, "%s:%i:[%i]%s ", filename_part(file).c_str(), line, debug_trace_depth, function ? function : unknown_function);
fprintf(stderr, "debug global : %s\n", debug_global ? "on" : "off");
}
void _debug_assert_fail(const char* file, int line, const char* function, const char* test) throw(assert_failed)
{
fprintf(stderr, "%s:%i:[%i]%s: assertion failed: %s\n",
filename_part(file).c_str(), line, debug_trace_depth, function ? function : unknown_function, test);
if (debug_last) debug_last->stackdump();
throw assert_failed (file, line, function, std::string(test));
}
////////////////////////////////////////////////////////////////////////////////
_debug_trace::_debug_trace(const char* f, int l, const char* fn) :
m_file(f), m_line(l), m_function(fn ? fn : unknown_function), m_last(debug_last), m_dbg(false), m_old(false)
{
if (!debug_read)
{
debug_read = true;
debug_match = getenv("DEBUG");
debug_recurse = getenv("DEBUG_LOCAL") == 0;
}
m_dbg = debug_set || (debug_match && (!debug_match[0] || match_wildcard(debug_match, filename_part(m_file))));
m_old = debug_set;
if (m_dbg && debug_recurse)
debug_set = true;
m_depth = ++debug_trace_depth;
debug_last = this;
report(std::string("entering ") + (m_function ? m_function : unknown_function));
}
_debug_trace::~_debug_trace(void)
{
report("leaving");
--debug_trace_depth;
debug_set = m_old;
debug_last = m_last;
}
const char* _debug_trace::file(void) const
{
return m_file;
}
int _debug_trace::line(void) const
{
return m_line;
}
bool _debug_trace::debug(void) const
{
return m_dbg || debug_global;
}
void _debug_trace::debug_on(int l, bool recurse)
{
m_dbg = true;
m_old = debug_set;
if (recurse)
debug_set = true;
report(l, std::string("debug on") + (recurse ? " recursive" : ""));
}
void _debug_trace::debug_off(int l)
{
report(l, std::string("debug off"));
m_dbg = false;
debug_set = m_old;
}
void _debug_trace::prefix(int l) const
{
fprintf(stderr, "%s:%i:[%i]%s ", filename_part(m_file).c_str(), l, m_depth, m_function ? m_function : unknown_function);
}
void _debug_trace::do_report(int l, const std::string& message) const
{
prefix(l);
fprintf(stderr, "%s\n", message.c_str());
fflush(stderr);
}
void _debug_trace::do_report(const std::string& message) const
{
do_report(m_line, message);
}
void _debug_trace::report(int l, const std::string& message) const
{
if (debug()) do_report(l, message);
}
void _debug_trace::report(const std::string& message) const
{
report(m_line, message);
}
void _debug_trace::error(int l, const std::string& message) const
{
do_report(l, "ERROR: " + message);
}
void _debug_trace::error(const std::string& message) const
{
error(m_line, message);
}
void _debug_trace::stackdump(int l, const std::string& message) const
{
do_report(l, message);
stackdump();
}
void _debug_trace::stackdump(const std::string& message) const
{
stackdump(m_line, message);
}
void _debug_trace::stackdump(void) const
{
for (const _debug_trace* item = this; item; item = item->m_last)
item->do_report("...called from here");
}
| [
"schimmi@cb9ff89a-abed-0310-8fc6-a4cabe7d48c9"
] | [
[
[
1,
165
]
]
] |
f6da552be83e35e905b221304fa3fea840d3137c | 0f457762985248f4f6f06e29429955b3fd2c969a | /physics/trunk/sdk/ggfsdk/irr_utill.h | 2765f42277c0736cedfddb1b609dc4d7024f3db8 | [] | no_license | tk8812/ukgtut | f19e14449c7e75a0aca89d194caedb9a6769bb2e | 3146ac405794777e779c2bbb0b735b0acd9a3f1e | refs/heads/master | 2021-01-01T16:55:07.417628 | 2010-11-15T16:02:53 | 2010-11-15T16:02:53 | 37,515,002 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 13,275 | h | #pragma once
/***********************************************************************
원본 출처 : http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=19725
복합선택자 도우미 함수모음
- 2007 7.4. 일리히트 1.3.1버전에서 정상 작동확인
- 2008 6.26. 일리히트 1.4.1버전에서 정상 작동확인(수정)
- 2008 8.20. DrawDebugBox 추가
- 2008 8.26. ReverseMeshSurface 추가
************************************************************************/
namespace ggf
{
namespace irr_util
{
//주어진 노드에 삼각선택자 등록시키기
inline void ISceneNode_assignTriangleSelector(irr::scene::ISceneNode* node, irr::scene::ISceneManager* smgr, irr::io::IFileSystem* ifs)
{
if (!node || !smgr || !ifs)
return;
if (node->getType() == irr::scene::ESNT_OCT_TREE)
{
irr::io::IAttributes* attribs = ifs->createEmptyAttributes();
if (attribs)
{
node->serializeAttributes(attribs);
// get the mesh name out
irr::core::stringc name = attribs->getAttributeAsString("Mesh");
attribs->drop();
// get the animated mesh for the object
irr::scene::IAnimatedMesh* mesh = smgr->getMesh(name.c_str());
if (mesh)
{
irr::scene::ITriangleSelector* selector =
smgr->createOctTreeTriangleSelector(mesh->getMesh(0), node, 128);
node->setTriangleSelector(selector);
selector->drop();
}
}
}
else if (node->getType() == irr::scene::ESNT_MESH)
{
irr::scene::IMeshSceneNode* msn = (irr::scene::IMeshSceneNode*)node;
if (msn->getMesh())
{
irr::scene::ITriangleSelector* selector =
smgr->createTriangleSelector(msn->getMesh(), msn);
msn->setTriangleSelector(selector);
selector->drop();
}
}
else if (node->getType() == irr::scene::ESNT_ANIMATED_MESH)
{
irr::scene::IAnimatedMeshSceneNode* msn = (irr::scene::IAnimatedMeshSceneNode*)node;
irr::scene::IAnimatedMesh* am = msn->getMesh();
if (am)
{
irr::scene::ITriangleSelector* selector =
smgr->createTriangleSelector(am->getMesh(0), msn);
msn->setTriangleSelector(selector);
selector->drop();
}
}
else if (node->getType() == irr::scene::ESNT_TERRAIN)
{
irr::scene::ITerrainSceneNode* tsn = (irr::scene::ITerrainSceneNode*)node;
irr::scene::ITriangleSelector* selector =
smgr->createTerrainTriangleSelector(tsn, 0); // probably don't want lod 0 all the time...
tsn->setTriangleSelector(selector);
selector->drop();
}
else if (node->getType() == irr::scene::ESNT_CUBE)
{
irr::scene::ITriangleSelector* selector =
smgr->createTriangleSelectorFromBoundingBox(node);
node->setTriangleSelector(selector);
selector->drop();
}
else
{
// not something we want to collide with
}
}
//자식노드까지 모두 순회해서 삼각선택자 등록시키기
inline void ISceneNode_assignTriangleSelectors(irr::scene::ISceneNode* node, irr::scene::ISceneManager* smgr, irr::io::IFileSystem* ifs)
{
// assign a selector for this node
ISceneNode_assignTriangleSelector(node, smgr, ifs);
// now recurse on children...
irr::core::list<irr::scene::ISceneNode*>::ConstIterator begin = node->getChildren().begin();
irr::core::list<irr::scene::ISceneNode*>::ConstIterator end = node->getChildren().end();
for (/**/; begin != end; ++begin)
ISceneNode_assignTriangleSelectors(*begin, smgr, ifs);
}
//씬관리자내의 모든 노드에 삼각선택자 등록하기
inline void ISceneManager_assignTriangleSelectors(irr::scene::ISceneManager* smgr, irr::io::IFileSystem* ifs)
{
ISceneNode_assignTriangleSelectors(smgr->getRootSceneNode(), smgr, ifs);
}
//주어진 노드의 자식노드를 모두 순회하며 삼각선택자를 한데 모으기
inline void ISceneNode_gatherTriangleSelectors(irr::scene::ISceneNode* node, irr::scene::IMetaTriangleSelector* meta)
{
irr::scene::ITriangleSelector* selector = node->getTriangleSelector();
if (selector)
meta->addTriangleSelector(selector);
// now recurse on children...
irr::core::list<irr::scene::ISceneNode*>::ConstIterator begin = node->getChildren().begin();
irr::core::list<irr::scene::ISceneNode*>::ConstIterator end = node->getChildren().end();
for (/**/; begin != end; ++begin)
ISceneNode_gatherTriangleSelectors(*begin, meta);
}
//씬매니져내의 모든 삼각선택자를 한데 모으기
inline void ISceneManager_gatherTriangleSelectors(irr::scene::ISceneManager* smgr, irr::scene::IMetaTriangleSelector* meta)
{
ISceneNode_gatherTriangleSelectors(smgr->getRootSceneNode(), meta);
}
inline void ISceneNode_RecursiveUpdateAbsoutePosition(irr::scene::ISceneNode* pNode)
{
if (!pNode )
return;
// Do something with the node here.
pNode->updateAbsolutePosition();
// recursive call to children
const irr::core::list<irr::scene::ISceneNode*> & children = pNode->getChildren();
irr::core::list<irr::scene::ISceneNode*>::ConstIterator it = children.begin();
for (; it != children.end(); ++it)
{
ISceneNode_RecursiveUpdateAbsoutePosition(*it);
}
}
inline void IAnimatedMeshSceneNode_RecursiveSetFrame(irr::scene::ISceneNode* pNode,irr::s32 nFrame)
{
if (!pNode )
return;
if(pNode->getType() == irr::scene::ESNT_ANIMATED_MESH)
{
((irr::scene::IAnimatedMeshSceneNode*)pNode)->setCurrentFrame((irr::f32)nFrame);
}
// recursive call to children
const irr::core::list<irr::scene::ISceneNode*> & children = pNode->getChildren();
irr::core::list<irr::scene::ISceneNode*>::ConstIterator it = children.begin();
for (; it != children.end(); ++it)
{
IAnimatedMeshSceneNode_RecursiveSetFrame(*it,nFrame);
}
}
/***********************************************************************
etc 아직정리안됨...
************************************************************************/
/*
메쉬 감는 모양 뒤집기
용도는...
카드의 뒷면..
망또앞뒤를 서로 다른 텍스춰로 표현할때..
사용예..
irr::scene::ISceneNode* pNode = 0;
irr::scene::IAnimatedMesh* pMesh;
pMesh = pSmgr->addHillPlaneMesh("myHill",
irr::core::dimension2d<irr::f32>(32,32),
irr::core::dimension2d<irr::u32>(8,8),
0,0
);
pMesh = pSmgr->addHillPlaneMesh("myHill_back",
irr::core::dimension2d<irr::f32>(32,32),
irr::core::dimension2d<irr::u32>(8,8),
0,0
);
ReverseMeshSurface(pMesh->getMeshBuffer(0));
*/
inline void ReverseMeshSurface(irr::scene::IMeshBuffer *pmb)
{
irr::u16 *pIb = pmb->getIndices();
irr::video::S3DVertex *pVb = (irr::video::S3DVertex *)pmb->getVertices();
{
irr::u32 i;
for(i=0;i<pmb->getIndexCount();i)
{
int nTemp = pIb[i+1];
pIb[i+1] = pIb[i+2];
pIb[i+2] = nTemp;
i+=3;
}
}
}
inline irr::core::vector3df GetWorldPosition(irr::scene::ISceneNode* pNode)
{
irr::scene::ISceneNode *par = pNode->getParent();
if(par)
{
irr::core::vector3df pos;
irr::core::matrix4 mat = par->getRelativeTransformation();
par = par->getParent();
while(par)
{
mat = par->getRelativeTransformation() * mat;
par = par->getParent();
}
mat.transformVect(pos,pNode->getPosition());
return pos;
}
else
return pNode->getPosition();
}
//디버깅정보표시용 점은 너무 안보여서 위치파악할때 박스가 편함
inline void DrawDebugBox(irr::video::IVideoDriver *pVideo,irr::core::vector3df pos,irr::f32 scale,irr::video::SColor color)
{
irr::core::vector3df ptscale(scale,scale,scale);
pVideo->draw3DBox(irr::core::aabbox3df(pos - ptscale,pos + ptscale),color);
}
//위치 뿐만아니라 방향도 알고싶을때
inline void DrawDebugAxies(irr::video::IVideoDriver *pVideo,irr::core::vector3df pos,irr::f32 scale,irr::core::quaternion Rot)
{
irr::core::vector3df AxiesX(1,0,0);
irr::core::vector3df AxiesY(0,1,0);
irr::core::vector3df AxiesZ(0,0,1);
AxiesX = Rot * AxiesX;
AxiesY = Rot * AxiesY;
AxiesZ = Rot * AxiesZ;
pVideo->draw3DLine(pos,pos+AxiesX*scale,irr::video::SColor(255,255,0,0));
pVideo->draw3DLine(pos,pos+AxiesY*scale,irr::video::SColor(255,0,255,0));
pVideo->draw3DLine(pos,pos+AxiesZ*scale,irr::video::SColor(255,0,0,255));
}
//씬파일로 로딩된 옥트리에서 메쉬 얻어내기
inline irr::scene::IMesh* ExtractMeshFromOctree(irr::IrrlichtDevice *pDevice,
irr::scene::ISceneNode *pOctNode,
irr::core::stringc &meshName)
{
//irr::scene::ISceneNode *pRoadRoot = CBycleApp::Get().m_System.m_pSmgr->getSceneNodeFromName(stageRes.m_strRoad.c_str());
irr::scene::ISceneManager *pSmgr = pDevice->getSceneManager();
irr::io::IFileSystem* ifs = pDevice->getFileSystem();
//irr::core::list<irr::scene::ISceneNode*>::ConstIterator it = pRoadRoot->getChildren().begin();
//for (; it != pRoadRoot->getChildren().end(); ++it)
{
//if((*it)->getType() == irr::scene::ESNT_OCT_TREE)
{
irr::scene::ISceneNode *pNode = pOctNode;
{
irr::io::IAttributes* attribs = ifs->createEmptyAttributes();
if (attribs)
{
pNode->serializeAttributes(attribs);
// get the mesh name out
meshName = attribs->getAttributeAsString("Mesh");
attribs->drop();
// get the animated mesh for the object
irr::scene::IAnimatedMesh* mesh = pSmgr->getMesh(meshName.c_str());
return mesh->getMesh(0);
//irr::scene::CBulletObjectAnimatorGeometry geom;
//irr::scene::CBulletObjectAnimatorParams physicsParams;
////pNode->setMaterialFlag(irr::video::EMF_WIREFRAME,true);
//// add level static mesh
//geom.type = scene::CBPAGT_CONCAVE_MESH;
//geom.mesh.irrMesh = NULL;//pNode->getMesh();////pMesh->getMesh(0);
//geom.meshFile = name;
//physicsParams.mass = 0.0f;
//scene::CBulletObjectAnimator* levelAnim =
// m_pBulletPhysicsFactory->createBulletObjectAnimator(
// pSmgr,
// pNode,
// m_pWorldAnimator->getID(),
// &geom,
// &physicsParams
// );
//pNode->addAnimator(levelAnim);
//levelAnim->drop();
}
}
}
}
meshName = "";
return NULL;
}
/*
샐랙터없이 피킹된 삼각형,위치,면인덱스 얻기
*/
inline bool Mesh_RayHitNodeTriangles (irr::scene::IAnimatedMeshSceneNode* Node,
irr::core::line3df Ray,
irr::core::vector3df &intersection,
irr::core::triangle3df &triangle,
irr::u32 &FaceIndex)
{
irr::u32 nMeshBuffer = 0;
int v_index[3] = {0,0,0};
//irr::core::triangle3df triangle;
irr::scene::IMeshBuffer *mesh_buffer = NULL;
irr::scene::IAnimatedMesh* mesh = Node->getMesh();
if (Node->getTransformedBoundingBox().intersectsWithLine(Ray))
{
int frame=(int)Node->getFrameNr();
irr::scene::IMesh* irr_mesh=mesh->getMesh(frame);
for( nMeshBuffer=0 ; nMeshBuffer < irr_mesh->getMeshBufferCount() ; nMeshBuffer++ )
{
mesh_buffer = irr_mesh->getMeshBuffer(nMeshBuffer);
irr::video::S3DVertex *vertices = (irr::video::S3DVertex*)mesh_buffer->getVertices();
irr::u16 *indices = mesh_buffer->getIndices();
irr::u32 i;
for(i=0; i<mesh_buffer->getIndexCount()/3; i++)
{
v_index[0] = indices[i*3 ];
v_index[1] = indices[i*3+1];
v_index[2] = indices[i*3+2];
triangle.pointA=vertices[ v_index[0] ].Pos;
triangle.pointB=vertices[ v_index[1] ].Pos;
triangle.pointC=vertices[ v_index[2] ].Pos;
Node->getAbsoluteTransformation().transformVect(triangle.pointA);
Node->getAbsoluteTransformation().transformVect(triangle.pointB);
Node->getAbsoluteTransformation().transformVect(triangle.pointC);
if (triangle.getIntersectionWithLine(Ray.start,Ray.end,intersection))
{
/*driver->setTransform(irr::video::ETS_WORLD, irr::core::matrix4());
material.Lighting=false;
material.setTexture(0,0);
driver->setMaterial(material);
driver->draw3DTriangle(triangle, irr::video::SColor(255,255,0,0)); */
FaceIndex = i;
return true;
}
}
}
}
return false;
}
/*
디버깅 로그 함수
pirrDevice : 널값일경우에는 윈도우 출력함수 바로출력
나머진 printf와 같음
*/
inline void DebugOutputFmt(irr::IrrlichtDevice *pirrDevice, const char *format,...)
{
#ifdef _DEBUG
va_list ap;
va_start(ap,format);
static char szBuf[256];
//sprintf_s(szBuf,format,ap);
_vsnprintf_s(szBuf, 256, format, ap );
if(pirrDevice)
{
pirrDevice->getLogger()->log(szBuf);
}
else
OutputDebugStringA(szBuf);
va_end(ap);
#endif
}
//inline void Octree2Bullet(irr::IrrlichtDevice *pDevice
// irr::scene::CBulletAnimatorManager *pBamgr,
// irr::scene::CBulletWorldAnimator*pWorldAnimator,
// irr::scene::ISceneNode *pRootNode)
//{
//
//}
//
//
}
}
| [
"gbox3d@58f0f68e-7603-11de-abb5-1d1887d8974b"
] | [
[
[
1,
431
]
]
] |
07a5dcc65e619224f557a42deb90c57ba52e2527 | 9101b1a05ce585937e9fcd89145115093ab1309b | /tcNetwork/tcNetwork.cpp | f68dbb73c58bd0d1f66ad9344f44fa3abfd1cab7 | [] | no_license | PiraZhao/C-Socket-API | beda5914cc2a6e2ee2a730b9859720248967f842 | f2d75091796815f8b53bc4e9d5a3977df8ffa9f7 | refs/heads/master | 2021-01-25T12:02:07.481982 | 2011-12-28T16:31:52 | 2011-12-28T16:31:52 | 3,038,844 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,061 | cpp | #include "tcNetwork.h"
#include <conio.h>
#define PRE_NUM 10
typedef enum {
CHESSMAN_SELECT_EVENT,
CHESSMAN_MOVE_EVENT,
CHESSMAN_CHANGE_EVENT,
CHESSMAN_ENLARGE_EVENT,
PROP_SHOW_EVENT,
CHANGE_TURN_EVENT,
ADJUST_CHESSMAN_EVENT,
} packetCodes;
typedef struct {
int chessman_id;
float x;
float y;
}ChessmanInfoStruct;
void sendMessage(ClientOpt *session, packetCodes packetID, void *data, int length);
void createConnection(ClientOpt *session) {
ConnectUser(session, "2008", "2009");
}
void sendChessmanSelectEvent(ClientOpt *session, int chessman_id) {
sendMessage(session, CHESSMAN_SELECT_EVENT, &chessman_id, sizeof(int));
}
void sendChessmanMoveEvent(ClientOpt *session, int chessman_id, float x, float y) {
ChessmanInfoStruct cis;
cis.chessman_id = chessman_id;
cis.x = x;
cis.y = y;
sendMessage(session, CHESSMAN_MOVE_EVENT, &cis, sizeof(ChessmanInfoStruct));
}
void sendChessmanChangeEvent(ClientOpt *session, int chessman_id) {
sendMessage(session, CHESSMAN_CHANGE_EVENT, &chessman_id, sizeof(int));
}
void sendChessmanEnlargeEvent(ClientOpt *session, int chessman_id) {
sendMessage(session, CHESSMAN_ENLARGE_EVENT, &chessman_id, sizeof(int));
}
void sendPropShowEvent(ClientOpt *session, int prop_id) {
sendMessage(session, PROP_SHOW_EVENT, &prop_id, sizeof(int));
}
void sendChangeTurnEvent(ClientOpt *session) {
sendMessage(session, CHANGE_TURN_EVENT, NULL, 0);
}
void sendAdjustChessmanEvent(ClientOpt *session) {
}
void sendMessage(ClientOpt *session, packetCodes packetID, void *data, int length) {
static char networkPacket[1024];
const unsigned int packetHeaderSize = sizeof(stPacketHeader);
if(length <= (int)(1024 - packetHeaderSize)) { // our networkPacket buffer size minus the size of the header info
stPacketHeader* pPacketHeader = (stPacketHeader*)networkPacket;
// header info
pPacketHeader->packetID = packetID;
// copy data in after the header
memcpy( &networkPacket[packetHeaderSize], data, length );
SendData(session, NULL, networkPacket);
}
}
char* fgetstr(FILE *in)//在文件中读取任意长度的字符串(读到回车或空格或括弧或逗号停止)
{
char* str;
char c;
int len = 0,temp_len = 0,times = sizeof(char);
if((str = (char*)calloc(PRE_NUM,times)) == NULL)
exit(1);
while(((c = fgetc(in)) != '\n')&&(c != ',')&&(c != EOF))
{
if(PRE_NUM == temp_len)
{
times *= 2;
if((str = (char*)realloc(str,PRE_NUM*times)) == NULL)
exit(1);
temp_len = 0;
}
*(str+len) = c;
len++;
temp_len++;
}
if((str = (char*)realloc(str,(len+1)*sizeof(char))) == NULL)
exit(1);
if(len == 0)
{
if(c == EOF)
{
*str = c;
return(str);
}
free(str);
str = NULL;
}
else
{
*(str+len) = '\0';
}
return(str);
}
void receivePackage(char *data, int length) {
//stPacketHeader* pPacketHeader = (stPacketHeader*)&incomingPacket[0];
//receiveMessage(pPacketHeader->packetID, (char *)(data + sizeof(stPacketHeader)), length - sizeof(stPacketHeader));
}
ClientOpt *login(char *user_name) {
FILE *network_config;
char *server_ip, *server_port, *client_port;
if((network_config = fopen("network.config", "r")) == NULL) {
printf("can not open network.config file");
return NULL;
}
else {
server_ip = fgetstr(network_config);
server_port = fgetstr(network_config);
client_port = fgetstr(network_config);
}
printf("server_ip:%s, server_port:%s, client_port:%s", server_ip, server_port, client_port);
ClientOpt *copt = (ClientOpt *)calloc(1, sizeof(ClientOpt));
copt->buffer_len = 1024;
copt->remote_port = atoi(server_port);
strcpy(copt->server_name, server_ip);
copt->SocketProc = receivePackage;
copt->user_name = user_name;
copt->local_port = client_port;
HANDLE * h = StartClient(copt);
Login(copt);
return copt;
}
void receiveMessage(packetCodes tag, char *data, int length) {
}
int main() {
ClientOpt *session = login("bluebitch");
getch();
return 0;
} | [
"[email protected]"
] | [
[
[
1,
156
]
]
] |
9cf46d3006744bd881a21925436e3d39348abef6 | 34a68e61a469b94063bc98465557072897a9aa88 | /script/ScriptEngine.h | dfe938ba2e292db4c1cc057cdff7e413338450a2 | [] | no_license | CneoC/shinzui | f83bfc9cbd9a05480d5323a21339d83e4d403dd9 | 5a2b79b430b207500766849bd58538e6a4aff2f8 | refs/heads/master | 2020-05-03T11:00:52.671613 | 2010-01-25T00:05:55 | 2010-01-25T00:05:55 | 377,430 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,823 | h | //////////////////////////////////////////////////////////////////////////
//
// This file is part of Shinzui.
//
// Shinzui 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.
//
// Shinzui 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 Shinzui. If not, see <http://www.gnu.org/licenses/>.
//
//////////////////////////////////////////////////////////////////////////
//
// ScriptEngine.h
// Copyright (c) 2009 Coen Campman
//
//////////////////////////////////////////////////////////////////////////
#pragma once
#ifndef __SCRIPT_SCRIPTENGINE_H__
#define __SCRIPT_SCRIPTENGINE_H__
#include "core/Process.h"
#include "ScriptObject.h"
namespace script
{
class Script;
/**
* Script engine class which manages and runs a group of scripts.
*/
class ScriptEngine
: public core::Process
{
public:
enum ExecFlags
{
EXEC_QUEUE = 0x0001, //!< Queue the command for execution (for multithreading).
};
/**
* Constructs a script engine.
* @param pCore Core class.
* @param id Process identifier for lookups.
*/
ScriptEngine(core::Core *pCore, u32 id = 0)
: core::Process(pCore, id)
{
}
/**
* @see core::Process::onStart
*/
virtual void onStart() {}
// TODO: generalize more of the script based logic?
protected:
};
}
#endif // __SCRIPT_SCRIPTENGINE_H__ | [
"[email protected]"
] | [
[
[
1,
71
]
]
] |
b28427d02a9027a1f2b92b7896830a2f96ae71d2 | 14a00dfaf0619eb57f1f04bb784edd3126e10658 | /Lab3/SupportCode/GLMenu.cpp | 77abb62c6a37d276112450a8076c64b30178240e | [] | 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 | 1,489 | cpp | #include "GLMenu.h"
#include "GL/glut.h"
#include "Vector3.h"
#define DEFAULT_WINDOW_HEIGHT 768
#define DEFAULT_WINDOW_WIDTH 1024
GLMenu::GLMenu(void)
{
}
GLMenu::~GLMenu(void)
{
std::vector<char*>::iterator linesIt = lines.begin();
std::vector<char*>::iterator end = lines.end();
for(; linesIt != end; ++linesIt)
{
//delete (*linesIt);
}
}
void GLMenu::addMenuLine(string line)
{
const char* original = line.c_str();
char* str = new char[ strlen(original) ];
strcpy(str, original);
this->lines.push_back( str );
}
void GLMenu::draw()
{
float startPos = 48;
const float pixelsPerLine = 48.0;
float pixelsizeH = 1.0/DEFAULT_WINDOW_HEIGHT;
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
{
glColor3f(0, 0, 0);
glOrtho(0, DEFAULT_WINDOW_WIDTH, 0, DEFAULT_WINDOW_HEIGHT, -1, 1);
std::vector<char*>::const_iterator linesIt = lines.begin();
std::vector<char*>::const_iterator end = lines.end();
for(; linesIt != end; ++linesIt, startPos+= 16)
{
//glRasterPos2f(-1,1.0-1*pixelsPerLine*pixelsizeH);
glRasterPos2f(0, DEFAULT_WINDOW_HEIGHT - startPos);
int len = strlen( *linesIt );
for (unsigned int i = 0; i < len; i++){
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12,(*linesIt)[i]);
}
}
}
glPopMatrix();
}
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
} | [
"jpjorge@da195381-492e-0410-b4d9-ef7979db4686"
] | [
[
[
1,
70
]
]
] |
44321db57f705b8df86dd7c18a458a959557614d | 5b2b0e9131a27043573107bf42d8ca7641ba511a | /PropsSounds.cpp | a6f68d7aff3491b6738c6cd38c8c245fc4073625 | [
"MIT"
] | permissive | acastroy/pumpkin | 0b1932e9c1fe7672a707cc04f092d98cfcecbd4e | 6e7e413ca364d79673e523c09767c18e7cff1bec | refs/heads/master | 2023-03-15T20:43:59.544227 | 2011-04-27T16:24:42 | 2011-04-27T16:24:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,720 | cpp | // PropsSounds.cpp : implementation file
//
#include "stdafx.h"
#include "PumpKIN.h"
#include "PropsSounds.h"
#include "PumpKINDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CPropsSounds property page
IMPLEMENT_DYNCREATE(CPropsSounds, CPropertyPage)
CPropsSounds::CPropsSounds() : CPropertyPage(CPropsSounds::IDD)
{
//{{AFX_DATA_INIT(CPropsSounds)
m_Abort = _T("");
m_Success = _T("");
m_Request = _T("");
//}}AFX_DATA_INIT
}
CPropsSounds::~CPropsSounds()
{
}
void CPropsSounds::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CPropsSounds)
DDX_Control(pDX, IDC_RING_PLAY, m_RequestPlayCtl);
DDX_Control(pDX, IDC_RING_BROWSE, m_RequestBrowseCtl);
DDX_Control(pDX, IDC_RING, m_RequestCtl);
DDX_Control(pDX, IDC_FINISHED_PLAY, m_SuccessPlayCtl);
DDX_Control(pDX, IDC_FINISHED_BROWSE, m_SuccessBrowseCtl);
DDX_Control(pDX, IDC_FINISHED, m_SuccessCtl);
DDX_Control(pDX, IDC_ABORTED_PLAY, m_AbortPlayCtl);
DDX_Control(pDX, IDC_ABORTED_BROWSE, m_AbortBrowseCtl);
DDX_Control(pDX, IDC_ABORTED, m_AbortCtl);
DDX_CBString(pDX, IDC_ABORTED, m_Abort);
DDX_CBString(pDX, IDC_FINISHED, m_Success);
DDX_CBString(pDX, IDC_RING, m_Request);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CPropsSounds, CPropertyPage)
//{{AFX_MSG_MAP(CPropsSounds)
ON_BN_CLICKED(IDC_ABORTED_BROWSE, OnAbortedBrowse)
ON_BN_CLICKED(IDC_FINISHED_BROWSE, OnFinishedBrowse)
ON_BN_CLICKED(IDC_RING_BROWSE, OnRingBrowse)
ON_BN_CLICKED(IDC_ABORTED_PLAY, OnAbortedPlay)
ON_BN_CLICKED(IDC_FINISHED_PLAY, OnFinishedPlay)
ON_BN_CLICKED(IDC_RING_PLAY, OnRingPlay)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CPropsSounds message handlers
BOOL CPropsSounds::OnInitDialog()
{
CPropertyPage::OnInitDialog();
HICON hP = AfxGetApp()->LoadIcon(IDI_PLAY);
HICON hB = AfxGetApp()->LoadIcon(IDI_BROWSE);
m_RequestPlayCtl.SetIcon(hP);
m_SuccessPlayCtl.SetIcon(hP);
m_AbortPlayCtl.SetIcon(hP);
m_RequestBrowseCtl.SetIcon(hB);
m_SuccessBrowseCtl.SetIcon(hB);
m_AbortBrowseCtl.SetIcon(hB);
CPumpKINDlg* pd = (CPumpKINDlg*)AfxGetMainWnd();
// ASSERT_KINDOF(CPumpKINDlg,pd);
m_bnw=&pd->m_bnw;
m_bnw->FillInCombo(&m_RequestCtl);
m_bnw->FillInCombo(&m_SuccessCtl);
m_bnw->FillInCombo(&m_AbortCtl);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CPropsSounds::OnAbortedBrowse()
{
Browse(m_AbortCtl);
}
void CPropsSounds::OnFinishedBrowse()
{
Browse(m_SuccessCtl);
}
void CPropsSounds::OnRingBrowse()
{
Browse(m_RequestCtl);
}
void CPropsSounds::OnAbortedPlay()
{
Play(m_AbortCtl);
}
void CPropsSounds::OnFinishedPlay()
{
Play(m_SuccessCtl);
}
void CPropsSounds::OnRingPlay()
{
Play(m_RequestCtl);
}
void CPropsSounds::Browse(CComboBox& ctl)
{
CString f;
ctl.GetWindowText(f);
CString filter;
filter.LoadString(IDS_FILTER_WAV);
CFileDialog fd(TRUE,NULL,(LPCTSTR)f,
OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_HIDEREADONLY
|OFN_LONGNAMES|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST,
filter,this);
CString title;
title.LoadString(IDS_TITLE_WAV);
fd.m_ofn.lpstrTitle=(LPCTSTR)title;
if(fd.DoModal()==IDOK)
ctl.SetWindowText(fd.GetPathName());
}
void CPropsSounds::Play(CComboBox& ctl)
{
CString s;
ctl.GetWindowText(s);
CBellsNWhistles::Whistling w = m_bnw->StartSound(s);
if(w){
Sleep(5000);
m_bnw->StopSound(w);
}
}
| [
"[email protected]"
] | [
[
[
1,
146
]
]
] |
1db01c9c35cb64374315b456f6c55e2905b77215 | 826479e30cfe9f7b9a1b7262211423d8208ffb68 | /RayTracer/CCamera.h | db1b61975bef6e4e66093a256276d6514a668d9b | [] | no_license | whztt07/real-time-raytracer | 5d1961c545e4703a3811fd7eabdff96017030abd | f54a75aed811b8ab6a509c70f879739896428fff | refs/heads/master | 2021-01-17T05:33:13.305151 | 2008-12-19T20:17:30 | 2008-12-19T20:17:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 257 | h | // Author : Jean-Rene Bedard ([email protected])
#pragma once
#include "CVector.h"
class CCamera
{
public:
CCamera();
virtual ~CCamera();
CVector p, up, dir, right;
float fov;
void lookAt(CVector target, float roll);
};
| [
"[email protected]"
] | [
[
[
1,
21
]
]
] |
d5273530caa4111b468a7bbf5940bc508462d96e | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/iptv_kernel/src/Poll.cpp | deae62331e372223fe3f9a4574fa2dab5009c93e | [] | no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,283 | cpp | #include "iptv_kernel/Poll.h"
#include "iptv_kernel/PollNotificationParameters.h"
#include "chat/nOpCodes.h"
#include <list>
using namespace std;
using namespace br::com::sbVB::VBLib;
Poll::Poll()
{
}
void Poll::OnIrmMessage(IrmMessage &msg, IrmUser &user, IrmConnection &conn)
{
switch (msg.m_irmMessageCode)
{
//---------------------------------------------------------------------------------------------
// Private message events
//---------------------------------------------------------------------------------------------
case PRIVMSG:
OnUserPrivateMessage(msg.m_strSource, msg.m_strData);
break;
//---------------------------------------------------------------------------------------------
case PRIVMSG_CHANNEL:
OnChannelPrivateMessage(msg.m_strSource, msg.m_strTarget, msg.m_strData);
break;
//---------------------------------------------------------------------------------------------
}
}
bool Poll::PollSend(const PollData &pollData)
{
// Preparing messages.
PollCtcpMessage begin;
begin.SetPollMessageCode(POLL_MESSAGE_CODE_BEGIN);
VBString beginMessage = begin.GetPollCtcpMessage();
PollCtcpMessage question;
question.SetPollMessageCode(POLL_MESSAGE_CODE_QUESTION);
question.SetText(pollData.question);
VBString questionMessage = question.GetPollCtcpMessage();
list<VBString> optionMessageList;
list<PollAnswer>::const_iterator it;
for(it = pollData.answerList.begin(); it != pollData.answerList.end(); it++)
{
PollCtcpMessage option;
option.SetPollMessageCode(POLL_MESSAGE_CODE_OPTION);
option.SetOptionIndex(it->index);
option.SetText(it->text);
VBString optionMessage = option.GetPollCtcpMessage();
optionMessageList.push_back(optionMessage);
}
PollCtcpMessage end;
end.SetPollMessageCode(POLL_MESSAGE_CODE_END);
VBString endMessage = end.GetPollCtcpMessage();
// Validating messages.
if(beginMessage.IsEmpty())
return false;
if(questionMessage.IsEmpty())
return false;
list<VBString>::iterator it2;
for(it2 = optionMessageList.begin(); it2 != optionMessageList.end(); it2++)
if((*it2).IsEmpty())
return false;
if(endMessage.IsEmpty())
return false;
// Sending messages.
SendChannelPrivateMessage(pollData.channel, beginMessage);
SendChannelPrivateMessage(pollData.channel, questionMessage);
for(it2 = optionMessageList.begin(); it2 != optionMessageList.end(); it2++)
SendChannelPrivateMessage(pollData.channel, *it2);
SendChannelPrivateMessage(pollData.channel, endMessage);
return true;
}
bool Poll::PollSendAnswer(VBString recipient, int optionIndex)
{
PollCtcpMessage msg;
msg.SetPollMessageCode(POLL_MESSAGE_CODE_ANSWER);
msg.SetOptionIndex(optionIndex);
VBString message = msg.GetPollCtcpMessage();
if(!message.IsEmpty())
{
SendPrivateMessage(recipient, message);
return true;
}
return false;
}
bool Poll::PollSendStats(const PollData &pollData)
{
// Preparing messages.
PollCtcpMessage begin;
begin.SetPollMessageCode(POLL_MESSAGE_CODE_STATS_BEGIN);
VBString beginMessage = begin.GetPollCtcpMessage();
PollCtcpMessage question;
question.SetPollMessageCode(POLL_MESSAGE_CODE_STATS_QUESTION);
question.SetText(pollData.question);
VBString questionMessage = question.GetPollCtcpMessage();
list<VBString> optionMessageList;
list<PollAnswer>::const_iterator it;
for(it = pollData.answerList.begin(); it != pollData.answerList.end(); it++)
{
PollCtcpMessage option;
option.SetPollMessageCode(POLL_MESSAGE_CODE_STATS_OPTION);
option.SetOptionIndex(it->index);
option.SetAnswerCount(it->answerCount);
option.SetText(it->text);
VBString optionMessage = option.GetPollCtcpMessage();
optionMessageList.push_back(optionMessage);
}
PollCtcpMessage end;
end.SetPollMessageCode(POLL_MESSAGE_CODE_STATS_END);
VBString endMessage = end.GetPollCtcpMessage();
// Validating messages.
if(beginMessage.IsEmpty())
return false;
if(questionMessage.IsEmpty())
return false;
list<VBString>::iterator it2;
for(it2 = optionMessageList.begin(); it2 != optionMessageList.end(); it2++)
if((*it2).IsEmpty())
return false;
if(endMessage.IsEmpty())
return false;
// Sending messages.
SendChannelPrivateMessage(pollData.channel, beginMessage);
SendChannelPrivateMessage(pollData.channel, questionMessage);
for(it2 = optionMessageList.begin(); it2 != optionMessageList.end(); it2++)
SendChannelPrivateMessage(pollData.channel, *it2);
SendChannelPrivateMessage(pollData.channel, endMessage);
return true;
}
void ShowPollData(PollCtcpMessage &msg)
{
if(msg.IsPollBegin())
cout << "Poll Begin" << endl;
if(msg.IsPollQuestion())
cout << "Poll Question|text=" << msg.GetText()<< endl;
if(msg.IsPollOption())
cout << "Poll Option|index=" << msg.GetOptionIndex() << "|text=" << msg.GetText() <<endl;
if(msg.IsPollEnd())
cout << "Poll End" << endl;
if(msg.IsPollAnswer())
cout << "Poll Answer|index=" << msg.GetOptionIndex() << endl;
if(msg.IsPollStatsBegin())
cout << "Poll Stats Begin" << endl;
if(msg.IsPollStatsQuestion())
cout << "Poll Stats Question|text=" << msg.GetText()<< endl;
if(msg.IsPollStatsOption())
cout << "Poll Stats Option|index=" << msg.GetOptionIndex() << "|count=" << msg.GetAnswerCount() << "|text=" << msg.GetText() <<endl;
if(msg.IsPollStatsEnd())
cout << "Poll Stats End" << endl;
}
void Poll::OnUserPrivateMessage(VBString sender, VBString message)
{
PollCtcpMessage msg(message);
if(msg.IsPollCtcpMessage())
{
//ShowPollData(msg);
if(msg.IsPollAnswer())
{
PollParameter p;
p.m_code = IMNC_MODULE_SPECIFIC;
p.m_moduleId = IPTV_MODULE_ID_POLL;
p.m_pollCode = POLLNC_ANSWER;
p.m_index = msg.GetOptionIndex();
p.m_user = sender;
Notify(p);
}
}
}
void Poll::OnChannelPrivateMessage(VBString sender, VBString channel, VBString message)
{
PollCtcpMessage msg(message);
if(msg.IsPollCtcpMessage())
{
//ShowPollData(msg);
if(msg.IsPollBegin())
{
PollParameter p;
p.m_code = IMNC_MODULE_SPECIFIC;
p.m_moduleId = IPTV_MODULE_ID_POLL;
p.m_pollCode = POLLNC_BEGIN;
p.m_user = sender;
p.m_channel = channel;
Notify(p);
}
else if(msg.IsPollQuestion())
{
PollParameter p;
p.m_code = IMNC_MODULE_SPECIFIC;
p.m_moduleId = IPTV_MODULE_ID_POLL;
p.m_pollCode = POLLNC_QUESTION;
p.m_text = msg.GetText();
p.m_user = sender;
p.m_channel = channel;
Notify(p);
}
else if(msg.IsPollOption())
{
PollParameter p;
p.m_code = IMNC_MODULE_SPECIFIC;
p.m_moduleId = IPTV_MODULE_ID_POLL;
p.m_pollCode = POLLNC_OPTION;
p.m_index = msg.GetOptionIndex();
p.m_text = msg.GetText();
p.m_user = sender;
p.m_channel = channel;
Notify(p);
}
else if(msg.IsPollEnd())
{
PollParameter p;
p.m_code = IMNC_MODULE_SPECIFIC;
p.m_moduleId = IPTV_MODULE_ID_POLL;
p.m_pollCode = POLLNC_END;
p.m_user = sender;
p.m_channel = channel;
Notify(p);
}
if(msg.IsPollStatsBegin())
{
PollParameter p;
p.m_code = IMNC_MODULE_SPECIFIC;
p.m_moduleId = IPTV_MODULE_ID_POLL;
p.m_pollCode = POLLNC_STATS_BEGIN;
p.m_user = sender;
p.m_channel = channel;
Notify(p);
}
else if(msg.IsPollStatsQuestion())
{
PollParameter p;
p.m_code = IMNC_MODULE_SPECIFIC;
p.m_moduleId = IPTV_MODULE_ID_POLL;
p.m_pollCode = POLLNC_STATS_QUESTION;
p.m_text = msg.GetText();
p.m_user = sender;
p.m_channel = channel;
Notify(p);
}
else if(msg.IsPollStatsOption())
{
PollParameter p;
p.m_code = IMNC_MODULE_SPECIFIC;
p.m_moduleId = IPTV_MODULE_ID_POLL;
p.m_pollCode = POLLNC_STATS_OPTION;
p.m_index = msg.GetOptionIndex();
p.m_answerCount = msg.GetAnswerCount();
p.m_text = msg.GetText();
p.m_user = sender;
p.m_channel = channel;
Notify(p);
}
else if(msg.IsPollStatsEnd())
{
PollParameter p;
p.m_code = IMNC_MODULE_SPECIFIC;
p.m_moduleId = IPTV_MODULE_ID_POLL;
p.m_pollCode = POLLNC_STATS_END;
p.m_user = sender;
p.m_channel = channel;
Notify(p);
}
}
}
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
] | [
[
[
1,
307
]
]
] |
47ff5c1e0a145275d03295a18b82722ecc38ad87 | 975d45994f670a7f284b0dc88d3a0ebe44458a82 | /servidor/Testes/Comunicação/Comunicação/Comunicação/includes/dreamClient.cpp | 0b6dd4fb66b422f49f06c172c771e9500fde6a4a | [] | no_license | phabh/warbugs | 2b616be17a54fbf46c78b576f17e702f6ddda1e6 | bf1def2f8b7d4267fb7af42df104e9cdbe0378f8 | refs/heads/master | 2020-12-25T08:51:02.308060 | 2010-11-15T00:37:38 | 2010-11-15T00:37:38 | 60,636,297 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,034 | cpp | /*************************************************************************************************
Funções da Classe dreamClient
**************************************************************************************************/
#include "dreamClient.h"
#include "dreamSock.h"
#include "dreamMessage.h"
dreamClient::dreamClient()
{
_connectionState = DREAMSOCK_DISCONNECTED;
_outgoingSequence = 1;
_incomingSequence = 0;
_incomingAcknowledged = 0;
_droppedPackets = 0;
_init = false;
_serverPort = 0;
_pingSent = 0;
_ping = 0;
_lastMessageTime = 0;
_next = NULL;
}
dreamClient::~dreamClient()
{
dreamSock_CloseSocket(_socket);
}
int dreamClient::initialize(char *localIP, char *remoteIP, int port)
{
// Initialize dreamSock if it is not already initialized
dreamSock_Initialize();
// Save server's address information for later use
_serverPort = port;
strcpy(_serverIP, remoteIP);
//LogString("Server's information: IP address: %s, port: %d", _serverIP, _serverPort);
// Create client socket
_socket = dreamSock_OpenUDPSocket(localIP, 0);
// Check that the address is not empty
u_long inetAddr = inet_addr(_serverIP);
if(inetAddr == INADDR_NONE)
{
return DREAMSOCK_CLIENT_ERROR;
}
if(_socket == DREAMSOCK_INVALID_SOCKET)
{
return DREAMSOCK_CLIENT_ERROR;
}
_init = true;
return 0;
}
void dreamClient::uninitialize(void)
{
dreamSock_CloseSocket(_socket);
reset();
_init = false;
}
void dreamClient::reset(void)
{
_connectionState = DREAMSOCK_DISCONNECTED;
_outgoingSequence = 1;
_incomingSequence = 0;
_incomingAcknowledged = 0;
_droppedPackets = 0;
_pingSent = 0;
_ping = 0;
_lastMessageTime = 0;
_next = NULL;
}
void dreamClient::dumpBuffer(void)
{
char data[1400];
int ret;
while((ret = dreamSock_GetPacket(_socket, data, NULL)) > 0)
{
}
}
void dreamClient::sendConnect(char *name)
{
// Dump buffer so there won't be any old packets to process
dumpBuffer();
_connectionState = DREAMSOCK_CONNECTING;
_message.init(_message._outgoingData, sizeof(_message._outgoingData));
//-101 = DREAMSOCK_MES_CONNECT
_message.writeByte(-101);
_message.writeString(name);
sendPacket(&_message);
}
void dreamClient::sendDisconnect(void)
{
_message.init(_message._outgoingData, sizeof(_message._outgoingData));
//-102 = DREAMSOCK_MES_DISCONNECT
_message.writeByte(-102);
sendPacket(&_message);
reset();
_connectionState = DREAMSOCK_DISCONNECTING;
}
void dreamClient::sendPing(void)
{
_pingSent = dreamSock_GetCurrentSystemTime();
_message.init(_message._outgoingData, sizeof(_message._outgoingData));
//-105 = DREAMSOCK_MES_PING
_message.writeByte(-105);
sendPacket(&_message);
}
void dreamClient::parsePacket(dreamMessage *mes)
{
mes->beginReading();
int type = mes->readByte();
// Check if the type is a positive number = is the packet sequenced
if(type > 0)
{
unsigned short sequence = mes->readShort();
unsigned short sequenceAck = mes->readShort();
if(sequence <= _incomingSequence)
{
// LogString("Client: (sequence: %d <= incoming seq: %d)", sequence, _incomingSequence);
// LogString("Client: Sequence mismatch");
}
_droppedPackets = (sequence - _incomingSequence) + 1;
_incomingSequence = sequence;
_incomingAcknowledged = sequenceAck;
}
// Parse through the system messages
switch(type)
{
//-101 = DREAMSOCK_MES_CONNECT
case -101:
_connectionState = DREAMSOCK_CONNECTED;
// LogString("LIBRARY: Client: got connect confirmation");
break;
//-102 = DREAMSOCK_MES_DISCONNECT
case -102:
_connectionState = DREAMSOCK_DISCONNECTED;
//LogString("LIBRARY: Client: got disconnect confirmation");
break;
//-103 = DREAMSOCK_MES_ADDCLIENT
case -103:
//LogString("LIBRARY: Client: adding a client");
break;
//-104 = DREAMSOCK_MES_REMOVECLIENT
case -104:
//LogString("LIBRARY: Client: removing a client");
break;
//-105 = DREAMSOCK_MES_PING
case -105:
sendPing();
break;
}
}
int dreamClient::getPacket(char *data, struct sockaddr *from)
{
// Check if the client is set up or if it is disconnecting
if(!_socket)
return 0;
int ret;
dreamMessage mes;
mes.init(data, sizeof(data));
ret = dreamSock_GetPacket(_socket, mes._data, from);
if(ret <= 0)
return 0;
mes.setSize(ret);
// Parse system messages
parsePacket(&mes);
return ret;
}
void dreamClient::sendPacket(void)
{
// Check that everything is set up
if(!_socket || _connectionState == DREAMSOCK_DISCONNECTED)
{
// LogString("SendPacket error: Could not send because the client is disconnected");
return;
}
// If the message overflowed, do not send it
if(_message.getOverFlow())
{
//LogString("SendPacket error: Could not send because the buffer overflowed");
return;
}
// Check if serverPort is set. If it is, we are a client sending to
// the server. Otherwise we are a server sending to a client.
if(_serverPort)
{
struct sockaddr_in sendToAddress;
memset((char *) &sendToAddress, 0, sizeof(sendToAddress));
u_long inetAddr = inet_addr(_serverIP);
sendToAddress.sin_port = htons((u_short) _serverPort);
sendToAddress.sin_family = AF_INET;
sendToAddress.sin_addr.s_addr = inetAddr;
dreamSock_SendPacket(_socket, _message.getSize(), _message._data, *(struct sockaddr *) &sendToAddress);
}
else
{
dreamSock_SendPacket(_socket, _message.getSize(), _message._data, _myaddress);
}
// Check if the packet is sequenced
_message.beginReading();
int type = _message.readByte();
if(type > 0)
{
_outgoingSequence++;
}
}
void dreamClient::sendPacket(dreamMessage *theMes)
{
// Check that everything is set up
if(!_socket || _connectionState == DREAMSOCK_DISCONNECTED)
{
//LogString("SendPacket error: Could not send because the client is disconnected");
return;
}
// If the message overflowed, do not send it
if(theMes->getOverFlow())
{
//LogString("SendPacket error: Could not send because the buffer overflowed");
return;
}
// Check if serverPort is set. If it is, we are a client sending to
// the server. Otherwise we are a server sending to a client.
if(_serverPort)
{
struct sockaddr_in sendToAddress;
memset((char *) &sendToAddress, 0, sizeof(sendToAddress));
u_long inetAddr = inet_addr(_serverIP);
sendToAddress.sin_port = htons((u_short) _serverPort);
sendToAddress.sin_family = AF_INET;
sendToAddress.sin_addr.s_addr = inetAddr;
dreamSock_SendPacket(_socket, theMes->getSize(), theMes->_data, *(struct sockaddr *) &sendToAddress);
}
else
{
dreamSock_SendPacket(_socket, theMes->getSize(), theMes->_data, _myaddress);
}
// Check if the packet is sequenced
theMes->beginReading();
int type = theMes->readByte();
if(type > 0)
{
_outgoingSequence++;
}
} | [
"[email protected]"
] | [
[
[
1,
293
]
]
] |
e02031b53209d25fdb94abadb6fb799a8c629f11 | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Include/Nuclex/Support/ThreadPool.h | 87f9a9bd7f9e814ef6ff3032c85ac8df1e7c498f | [] | no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,899 | h | // //
// # # ### # # -= Nuclex Library =- //
// ## # # # ## ## ThreadPool.h - Thread pool //
// ### # # ### //
// # ### # ### A pool of worker threads for parallel processing //
// # ## # # ## ## //
// # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt //
// //
#ifndef NUCLEX_SUPPORT_THREADPOOL_H
#define NUCLEX_SUPPORT_THREADPOOL_H
#include "Nuclex/Nuclex.h"
#include "Nuclex/Support/String.h"
#include "Nuclex/Support/Thread.h"
#include "Nuclex/Support/Synchronization.h"
#include "Nuclex/Support/Invocation.h"
#include <vector>
#include <deque>
namespace Nuclex { namespace Support {
// //
// Nuclex::Support::ThreadPool //
// //
/// Thread pool
class ThreadPool {
public:
NUCLEX_API ThreadPool(size_t NumThreads);
NUCLEX_API ~ThreadPool();
//
// ThreadPool implementation
//
public:
/// Enqueue a task to be executed
NUCLEX_API void enqueue(std::auto_ptr<Thread::Function> spTask);
private:
/// A worker thread
struct WorkerThread :
public Thread::Function {
/// Constructor
WorkerThread(ThreadPool &Owner) :
m_Owner(Owner),
m_Signal(false),
m_bStopRequested(false),
m_bWorking(false) {}
/// The threaded method
void operator()();
/// Request the thread to stop
void requestStop() { m_bStopRequested = true; }
/// Access signal for suspending idle threads
Signal &getSignal() { return m_Signal; }
/// Check whether the thread is currently working
bool isWorking() const { return m_bWorking; }
private:
ThreadPool &m_Owner; ///< The worker thread's owner
Signal m_Signal; ///< Signal to suspend thread
bool m_bStopRequested; ///< Whether a stop was requested
bool m_bWorking; ///< Whether the thread is working
};
typedef std::vector<std::pair<shared_ptr<Thread>, WorkerThread *> > WorkerThreadVector;
typedef std::deque<shared_ptr<Thread::Function> > TaskDeque;
WorkerThreadVector m_WorkerThreads;
Mutex m_TasksMutex;
TaskDeque m_Tasks;
};
}} // namespace Nuclex::Support
#endif // NUCLEX_SUPPORT_THREADPOOL_H
| [
"ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38"
] | [
[
[
1,
75
]
]
] |
15ddf7d0510e5bc8bed3fb9ada1d45371358195a | 3ea9ea4da0819d1cdf99cac9225c5b34e48430b1 | /assign2-cpp/Parse.cpp | cdb5211e1453810b1ebdaa450ed13e9d6a37cc5a | [] | no_license | keithfancher/Programming-Languages | b32697a233253dacd679cc120d698f552af02a93 | f84ccf9beb4a56022c1ad0dae1400cab5b39fb5d | refs/heads/master | 2016-09-10T08:05:41.992568 | 2011-07-23T23:16:34 | 2011-07-23T23:16:34 | 2,304,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,612 | cpp | //****************************************************************************
// File : Parse.cpp
// Author: Keith T. Fancher
// Date : 02/09/04
// Class : CS3490
//
// Purpose: The implementation for the Parse class, which handles the (gasp!)
// parsing for our crazy little assembler.
//****************************************************************************
using namespace std;
#include <string.h>
#include <fstream>
#include "Instruction.h"
#include "Parse.h"
Instruction * Parse::parse(ifstream & f)
{
const int MAXLEN = Instruction::INSTR_LEN; // the max length of a field
Instruction * return_instr = NULL; // the return value
char instring[MAXLEN] = {0}; // necessary temp string
bool hasLabel = false; // makes things easier down below
char label[MAXLEN] = {0};
char opcode[MAXLEN] = {0};
char field0[MAXLEN] = {0};
char field1[MAXLEN] = {0};
f >> instring;
if(!isOpcode(instring)) // must be a label
{
strncpy(label, instring, MAXLEN);
f >> instring; // done w/ label, read next field (opcode)
hasLabel = true;
}
strncpy(opcode, instring, MAXLEN); // put opcode into the string
// A, B, and D types all use field0
if(isAType(opcode) || isBType(opcode) || isDType(opcode))
f >> field0;
if(isAType(opcode))
{
if(isAdd(opcode))
return_instr = new Add( (hasLabel ? label : NULL), opcode, field0);
if(isLoad(opcode))
return_instr = new Load( (hasLabel ? label : NULL), opcode, field0);
if(isStore(opcode))
return_instr = new Store( (hasLabel ? label : NULL), opcode, field0);
}
if(isBType(opcode))
{
f >> field1; // only B types need field1
if(isBeq(opcode))
return_instr = new Beq( (hasLabel ? label : NULL), opcode, field0, field1);
if(isBne(opcode))
return_instr = new Bne( (hasLabel ? label : NULL), opcode, field0, field1);
}
if(isCType(opcode))
{
if(isHalt(opcode))
return_instr = new Halt( (hasLabel ? label: NULL), opcode);
}
if(isDType(opcode))
{
if(isFill(opcode))
return_instr = new Fill( (hasLabel ? label: NULL), opcode, field0);
}
return return_instr;
}
bool Parse::isOpcode(char * field)
{
if(isAType(field) || isBType(field) || isCType(field) || isDType(field))
return true;
return false;
}
bool Parse::isAType(char * opcode)
{
if(isAdd(opcode) || isLoad(opcode) || isStore(opcode))
return true;
return false;
}
bool Parse::isBType(char * opcode)
{
if(isBeq(opcode) || isBne(opcode))
return true;
return false;
}
bool Parse::isCType(char * opcode)
{
return isHalt(opcode); // halt is the only CType
}
bool Parse::isDType(char * opcode)
{
return isFill(opcode); // fill is the only DType
}
bool Parse::isAdd(char * opcode)
{
if(!strcmp(opcode, "add"))
return true;
return false;
}
bool Parse::isLoad(char * opcode)
{
if(!strcmp(opcode, "load"))
return true;
return false;
}
bool Parse::isStore(char * opcode)
{
if(!strcmp(opcode, "store"))
return true;
return false;
}
bool Parse::isBeq(char * opcode)
{
if(!strcmp(opcode, "beq"))
return true;
return false;
}
bool Parse::isBne(char * opcode)
{
if(!strcmp(opcode, "bne"))
return true;
return false;
}
bool Parse::isHalt(char * opcode)
{
if(!strcmp(opcode, "halt"))
return true;
return false;
}
bool Parse::isFill(char * opcode)
{
if(!strcmp(opcode, ".fill"))
return true;
return false;
}
| [
"[email protected]"
] | [
[
[
1,
152
]
]
] |
5031291e46f255652dd32ce36b6a1ec62e3096ab | 0da7fec56f63012180d848b1e72bada9f6984ef3 | /PocketDjVu_root/libdjvu/GString.cpp | 040bd944271a88bb05be75274dddb8ab9e9d8f68 | [] | no_license | UIKit0/pocketdjvu | a34fb2b8ac724d25fab7a0298942db1755098b25 | 4c0c761e6a3d3628440fb4fb0a9c54e5594807d9 | refs/heads/master | 2021-01-20T12:01:16.947853 | 2010-05-03T12:29:44 | 2010-05-03T12:29:44 | 32,293,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 66,770 | cpp | //C- -*- C++ -*-
//C- -------------------------------------------------------------------
//C- DjVuLibre-3.5
//C- Copyright (c) 2002 Leon Bottou and Yann Le Cun.
//C- Copyright (c) 2001 AT&T
//C-
//C- This software is subject to, and may be distributed under, the
//C- GNU General Public License, Version 2. The license should have
//C- accompanied the software or you may obtain a copy of the license
//C- from the Free Software Foundation at http://www.fsf.org .
//C-
//C- This program is distributed in the hope that it will be useful,
//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//C- GNU General Public License for more details.
//C-
//C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library
//C- distributed by Lizardtech Software. On July 19th 2002, Lizardtech
//C- Software authorized us to replace the original DjVu(r) Reference
//C- Library notice by the following text (see doc/lizard2002.djvu):
//C-
//C- ------------------------------------------------------------------
//C- | DjVu (r) Reference Library (v. 3.5)
//C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved.
//C- | The DjVu Reference Library is protected by U.S. Pat. No.
//C- | 6,058,214 and patents pending.
//C- |
//C- | This software is subject to, and may be distributed under, the
//C- | GNU General Public License, Version 2. The license should have
//C- | accompanied the software or you may obtain a copy of the license
//C- | from the Free Software Foundation at http://www.fsf.org .
//C- |
//C- | The computer code originally released by LizardTech under this
//C- | license and unmodified by other parties is deemed "the LIZARDTECH
//C- | ORIGINAL CODE." Subject to any third party intellectual property
//C- | claims, LizardTech grants recipient a worldwide, royalty-free,
//C- | non-exclusive license to make, use, sell, or otherwise dispose of
//C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the
//C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU
//C- | General Public License. This grant only confers the right to
//C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to
//C- | the extent such infringement is reasonably necessary to enable
//C- | recipient to make, have made, practice, sell, or otherwise dispose
//C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to
//C- | any greater extent that may be necessary to utilize further
//C- | modifications or combinations.
//C- |
//C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY
//C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF
//C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//C- +------------------------------------------------------------------
//
// $Id: GString.cpp,v 1.23 2005/12/23 15:14:16 leonb Exp $
// $Name: release_3_5_17 $
// From: Leon Bottou, 1/31/2002
// This file has very little to do with my initial implementation.
// It has been practically rewritten by Lizardtech for i18n changes.
// My original implementation was very small in comparison
// <http://prdownloads.sourceforge.net/djvu/DjVu2_2b-src.tgz>.
// In my opinion, the duplication of the string classes is a failed
// attempt to use the type system to enforce coding policies.
// This could be fixed. But there are better things to do in djvulibre.
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#if NEED_GNUG_PRAGMAS
# pragma implementation
#endif
#include "GString.h"
#include "GThreads.h"
#include "debug.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#if HAS_WCHAR
# include <locale.h>
# if !defined(AUTOCONF) || HAVE_WCHAR_H
# include <wchar.h>
# endif
# if HAS_WCTYPE
# include <wctype.h>
# endif
#endif
#include <ctype.h>
#ifdef UNDER_CE
#include <windows.h>
#include <wchar.h>
#undef WIN32
#define DO_CHANGELOCALE 0
#endif
#ifndef DO_CHANGELOCALE
#define DO_CHANGELOCALE 1
#ifdef UNIX
#if THREADMODEL != COTHREADS
#if THREADMODEL != NOTHREADS
#undef DO_CHANGELOCALE
#define DO_CHANGELOCALE 0
#endif
#endif
#endif
#endif
#ifdef HAVE_NAMESPACES
namespace DJVU {
# ifdef NOT_DEFINED // Just to fool emacs c++ mode
}
#endif
#endif
GBaseString::~GBaseString() {}
GNativeString::~GNativeString() {}
GUTF8String::~GUTF8String() {}
GUTF8String::GUTF8String(const char *str)
{ init(GStringRep::UTF8::create(str)); }
/*#ifdef UNDER_CE
static inline int
wcrtomb(char *bytes,wchar_t w,mbstate_t *)
{
wchar_t inp[2]={w,0};
char buf[10];
WideCharToMultiByte(CP_UTF8,0,inp,-1,buf,10,0,0);
int n = strlen(buf);
memcpy(bytes,buf,n);
return n;
}
static inline int
mbrtowc(wchar_t *w,const char *source, size_t n, mbstate_t *)
{
return mbtowc(w,source,n);
}
static inline size_t
mbrlen(const char *s, size_t n, mbstate_t *)
{
return mblen(s,n);
}
#endif*/
#if !HAS_MBSTATE && HAS_WCHAR
// Under some systems, wctomb() and mbtowc() are not thread
// safe. In those cases, wcrtomb and mbrtowc are preferred.
// For Solaris, wctomb() and mbtowc() are thread safe, and
// wcrtomb() and mbrtowc() don't exist.
#define wcrtomb MYwcrtomb
#define mbrtowc MYmbrtowc
#define mbrlen MYmbrlen
static inline int
wcrtomb(char *bytes,wchar_t w,mbstate_t *)
{
return wctomb(bytes,w);
}
static inline int
mbrtowc(wchar_t *w,const char *source, size_t n, mbstate_t *)
{
return mbtowc(w,source,n);
}
static inline size_t
mbrlen(const char *s, size_t n, mbstate_t *)
{
return mblen(s,n);
}
#endif // !HAS_MBSTATE || HAS_WCHAR
GP<GStringRep>
GStringRep::upcase(void) const
{ return tocase(giswupper,gtowupper); }
GP<GStringRep>
GStringRep::downcase(void) const
{ return tocase(giswlower,gtowlower); }
GP<GStringRep>
GStringRep::UTF8::create(const unsigned int sz)
{
return GStringRep::create(sz,(GStringRep::UTF8 *)0);
}
GP<GStringRep>
GStringRep::UTF8::create(const char *s)
{
GStringRep::UTF8 dummy;
return dummy.strdup(s);
}
GP<GStringRep>
GStringRep::UTF8::create(const GP<GStringRep> &s1,const GP<GStringRep> &s2)
{
GStringRep::UTF8 dummy;
return dummy.concat(s1,s2);
}
GP<GStringRep>
GStringRep::UTF8::create( const GP<GStringRep> &s1,const char *s2)
{
GStringRep::UTF8 dummy;
return dummy.concat(s1,s2);
}
GP<GStringRep>
GStringRep::UTF8::create( const char *s1, const GP<GStringRep> &s2)
{
GStringRep::UTF8 dummy;
return dummy.concat(s1,s2);
}
GP<GStringRep>
GStringRep::UTF8::create( const char *s1,const char *s2)
{
GStringRep::UTF8 dummy;
return dummy.concat(s1,s2);
}
GP<GStringRep>
GStringRep::UTF8::create(const char *s,const int start,const int length)
{
GStringRep::UTF8 dummy;
return dummy.substr(s,start,length);
}
GP<GStringRep>
GStringRep::UTF8::create(
const unsigned short *s,const int start,const int length)
{
GStringRep::UTF8 dummy;
return dummy.substr(s,start,length);
}
GP<GStringRep>
GStringRep::UTF8::create(
const unsigned long *s,const int start,const int length)
{
GStringRep::UTF8 dummy;
return dummy.substr(s,start,length);
}
GP<GStringRep>
GStringRep::UTF8::blank(const unsigned int sz) const
{
return GStringRep::create(sz,(GStringRep::UTF8 *)0);
}
bool
GStringRep::UTF8::isUTF8(void) const
{
return true;
}
GP<GStringRep>
GStringRep::UTF8::toThis(
const GP<GStringRep> &rep,const GP<GStringRep> &) const
{
return rep?(rep->toUTF8(true)):rep;
}
GP<GStringRep>
GStringRep::UTF8::create(const char fmt[],va_list& args)
{
const GP<GStringRep> s(create(fmt));
return (s?(s->vformat(args)):s);
}
#if !HAS_WCHAR
#define NATIVE_CREATE(x) UTF8::create( x );
#ifdef LC_ALL
#undef LC_ALL
#endif
#define LC_ALL 0
#ifdef UNDER_CE
#ifndef LC_NUMERIC
#define LC_NUMERIC 0
#endif
#endif
class GStringRep::ChangeLocale
{
public:
ChangeLocale(const int,const char *) {}
~ChangeLocale() {};
};
GP<GStringRep>
GStringRep::NativeToUTF8( const char *s )
{
return GStringRep::UTF8::create(s);
}
#else
#define NATIVE_CREATE(x) Native::create( x );
// The declaration and implementation of GStringRep::ChangeLocale
// Not used in WinCE
class GStringRep::ChangeLocale
{
public:
ChangeLocale(const int category,const char locale[]);
~ChangeLocale();
private:
GUTF8String locale;
int category;
};
class GStringRep::Native : public GStringRep
{
public:
// default constructor
Native(void);
// virtual destructor
virtual ~Native();
// Other virtual methods.
// Create an empty string.
virtual GP<GStringRep> blank(const unsigned int sz = 0) const;
// Append a string.
virtual GP<GStringRep> append(const GP<GStringRep> &s2) const;
// Test if Native.
virtual bool isNative(void) const;
// Convert to Native.
virtual GP<GStringRep> toNative(
const EscapeMode escape=UNKNOWN_ESCAPED) const;
// Convert to UTF8.
virtual GP<GStringRep> toUTF8(const bool nothrow=false) const;
// Convert to UTF8.
virtual GP<GStringRep> toThis(
const GP<GStringRep> &rep,const GP<GStringRep> &) const;
// Compare with #s2#.
virtual int cmp(const GP<GStringRep> &s2, const int len=(-1)) const;
// Convert strings to numbers.
virtual int toInt(void) const;
virtual long toLong(
const int pos, int &endpos, const int base=10) const;
virtual unsigned long toULong(
const int pos, int &endpos, const int base=10) const;
virtual double toDouble(
const int pos, int &endpos) const;
// Create an empty string
static GP<GStringRep> create(const unsigned int sz = 0);
// Create a strdup string.
static GP<GStringRep> create(const char *s);
// Creates by appending to the current string
// Creates with a concat operation.
static GP<GStringRep> create(
const GP<GStringRep> &s1,const GP<GStringRep> &s2);
static GP<GStringRep> create( const GP<GStringRep> &s1,const char *s2);
static GP<GStringRep> create( const char *s1, const GP<GStringRep> &s2);
static GP<GStringRep> create(const char *s1,const char *s2);
// Create with a strdup and substr operation.
static GP<GStringRep> create(
const char *s,const int start,const int length=(-1));
static GP<GStringRep> create(
const unsigned short *s,const int start,const int length=(-1));
static GP<GStringRep> create(
const unsigned long *s,const int start,const int length=(-1));
// Create with an sprintf()
static GP<GStringRep> create_format(const char fmt[],...);
static GP<GStringRep> create(const char fmt[],va_list &args);
virtual unsigned char *UCS4toString(
const unsigned long w,unsigned char *ptr, mbstate_t *ps=0) const;
// Tests if a string is legally encoded in the current character set.
virtual bool is_valid(void) const;
virtual int ncopy(wchar_t * const buf, const int buflen) const;
friend class GBaseString;
protected:
// Return the next character and increment the source pointer.
virtual unsigned long getValidUCS4(const char *&source) const;
};
GP<GStringRep>
GStringRep::Native::create(const unsigned int sz)
{
return GStringRep::create(sz,(GStringRep::Native *)0);
}
// Create a strdup string.
GP<GStringRep>
GStringRep::Native::create(const char *s)
{
GStringRep::Native dummy;
return dummy.strdup(s);
}
GP<GStringRep>
GStringRep::Native::create(const GP<GStringRep> &s1,const GP<GStringRep> &s2)
{
GStringRep::Native dummy;
return dummy.concat(s1,s2);
}
GP<GStringRep>
GStringRep::Native::create( const GP<GStringRep> &s1,const char *s2)
{
GStringRep::Native dummy;
return dummy.concat(s1,s2);
}
GP<GStringRep>
GStringRep::Native::create( const char *s1, const GP<GStringRep> &s2)
{
GStringRep::Native dummy;
return dummy.concat(s1,s2);
}
GP<GStringRep>
GStringRep::Native::create(const char *s1,const char *s2)
{
GStringRep::Native dummy;
return dummy.concat(s1,s2);
}
GP<GStringRep>
GStringRep::Native::create(
const char *s,const int start,const int length)
{
GStringRep::Native dummy;
return dummy.substr(s,start,length);
}
GP<GStringRep>
GStringRep::Native::create(
const unsigned short *s,const int start,const int length)
{
GStringRep::Native dummy;
return dummy.substr(s,start,length);
}
GP<GStringRep>
GStringRep::Native::create(
const unsigned long *s,const int start,const int length)
{
GStringRep::Native dummy;
return dummy.substr(s,start,length);
}
GP<GStringRep>
GStringRep::Native::blank(const unsigned int sz) const
{
return GStringRep::create(sz,(GStringRep::Native *)0);
}
bool
GStringRep::Native::isNative(void) const
{
return true;
}
GP<GStringRep>
GStringRep::Native::toThis(
const GP<GStringRep> &rep,const GP<GStringRep> &) const
{
return rep?(rep->toNative(NOT_ESCAPED)):rep;
}
GP<GStringRep>
GStringRep::Native::create(const char fmt[],va_list &args)
{
const GP<GStringRep> s(create(fmt));
return (s?(s->vformat(args)):s);
}
int
GStringRep::Native::ncopy(
wchar_t * const buf, const int buflen ) const
{
return toUTF8()->ncopy(buf,buflen);
}
GStringRep::ChangeLocale::ChangeLocale(const int xcategory, const char xlocale[] )
: category(xcategory)
{
#if DO_CHANGELOCALE
// This is disabled under UNIX because
// it does not play nice with MT.
if(xlocale)
{
locale=setlocale(xcategory,0);
if(locale.length() &&(locale!=xlocale))
{
if(locale == setlocale(category,xlocale))
{
locale.empty();
}
}
else
{
locale.empty();
}
}
#endif
}
GStringRep::ChangeLocale::~ChangeLocale()
{
#if DO_CHANGELOCALE
if(locale.length())
{
setlocale(category,(const char *)locale);
}
#endif
}
GNativeString &
GNativeString::format(const char fmt[], ... )
{
va_list args;
va_start(args, fmt);
return init(GStringRep::Native::create(fmt,args));
}
// Gather the native implementations here. Not used in WinCE.
GStringRep::Native::Native(void) {}
GStringRep::Native::~Native() {}
GP<GStringRep>
GStringRep::Native::append(const GP<GStringRep> &s2) const
{
GP<GStringRep> retval;
if(s2)
{
if(s2->isUTF8())
{
G_THROW( ERR_MSG("GStringRep.appendUTF8toNative") );
}
retval=concat(data,s2->data);
}else
{
retval=const_cast<GStringRep::Native *>(this);
}
return retval;
}
GP<GStringRep>
GStringRep::Native::create_format(const char fmt[],...)
{
va_list args;
va_start(args, fmt);
return create(fmt,args);
}
unsigned char *
GStringRep::Native::UCS4toString(
const unsigned long w0,unsigned char *ptr, mbstate_t *ps) const
{
return UCS4toNative(w0,ptr,ps);
}
// Convert a UCS4 to a multibyte string in the value bytes.
// The data pointed to by ptr should be long enough to contain
// the results with a nill termination. (Normally 7 characters
// is enough.)
unsigned char *
GStringRep::UCS4toNative(
const unsigned long w0,unsigned char *ptr, mbstate_t *ps)
{
unsigned short w1;
unsigned short w2=1;
for(int count=(sizeof(wchar_t)==sizeof(w1)) ? UCS4toUTF16(w0,w1,w2) : 1;
count;
--count,w1=w2)
{
// wchar_t can be either UCS4 or UCS2
const wchar_t w=(sizeof(wchar_t) == sizeof(w1))?(wchar_t)w1:(wchar_t)w0;
wchar_t wbuf[2]={w,0};
char buf[10]={0};
if (WideCharToMultiByte(CP_UTF8,0,wbuf,1,buf,10,0,0)==0)
break;
int i = strlen(buf);
strcpy(reinterpret_cast<char*>(ptr),buf);
/*int i=wcrtomb((char *)ptr,w,ps);
if(i<0)
{
break;
}*/
ptr[i]=0;
ptr += i;
}
ptr[0]=0;
return ptr;
}
GP<GStringRep>
GStringRep::Native::toNative(const EscapeMode escape) const
{
if(escape == UNKNOWN_ESCAPED)
G_THROW( ERR_MSG("GStringRep.NativeToNative") );
return const_cast<GStringRep::Native *>(this);
}
GP<GStringRep>
GStringRep::Native::toUTF8(const bool) const
{
#ifdef UNDER_CE
return GStringRep::UTF8::create((const char *)data);
#else
unsigned char *buf;
GPBuffer<unsigned char> gbuf(buf,size*6+1);
buf[0]=0;
if(data && size)
{
size_t n=size;
const char *source=data;
mbstate_t ps;
unsigned char *ptr=buf;
//(void)mbrlen(source, n, &ps);
memset(&ps,0,sizeof(mbstate_t));
int i=0;
if(sizeof(wchar_t) == sizeof(unsigned long))
{
wchar_t w = 0;
for(;(n>0)&&((i=mbrtowc(&w,source,n,&ps))>=0); n-=i,source+=i)
{
ptr=UCS4toUTF8(w,ptr);
}
}
else
{
wchar_t w = 0;
for(;(n>0)&&((i=mbrtowc(&w,source,n,&ps))>=0);n-=i,source+=i)
{
unsigned short s[2];
s[0]=w;
unsigned long w0;
if(UTF16toUCS4(w0,s,s+1)<=0)
{
source+=i;
n-=i;
if((n>0)&&((i=mbrtowc(&w,source,n,&ps))>=0))
{
s[1]=w;
if(UTF16toUCS4(w0,s,s+2)<=0)
{
i=(-1);
break;
}
}
else
{
i=(-1);
break;
}
}
ptr=UCS4toUTF8(w0,ptr);
}
}
if(i<0)
{
gbuf.resize(0);
}
else
{
ptr[0]=0;
}
}
return GStringRep::UTF8::create((const char *)buf);
#endif
}
GNativeString
GBaseString::UTF8ToNative(
const bool currentlocale,const EscapeMode escape) const
{
const char *source=(*this);
GP<GStringRep> retval;
if(source && source[0])
{
#if DO_CHANGELOCALE
GUTF8String lc_ctype(setlocale(LC_CTYPE,0));
#endif
bool repeat;
for(repeat=!currentlocale;;repeat=false)
{
retval=(*this)->toNative((GStringRep::EscapeMode)escape);
#if DO_CHANGELOCALE
if (!repeat || retval || (lc_ctype == setlocale(LC_CTYPE,"")))
#endif
break;
}
#if DO_CHANGELOCALE
if(!repeat)
{
setlocale(LC_CTYPE,(const char *)lc_ctype);
}
#endif
}
return GNativeString(retval);
}
/*MBCS*/
GNativeString
GBaseString::getUTF82Native( EscapeMode escape ) const
{ //MBCS cvt
GNativeString retval;
// We don't want to convert this if it
// already is known to be native...
// if (isNative()) return *this;
const size_t slen=length()+1;
if(slen>1)
{
retval=UTF8ToNative(false,escape) ;
if(!retval.length())
{
retval=(const char*)*this;
}
}
return retval;
}
GUTF8String
GBaseString::NativeToUTF8(void) const
{
GP<GStringRep> retval;
if(length())
{
const char *source=(*this);
#if DO_CHANGELOCALE
GUTF8String lc_ctype=setlocale(LC_CTYPE,0);
#endif
bool repeat;
for(repeat=true;;repeat=false)
{
if( (retval=GStringRep::NativeToUTF8(source)) )
{
if(GStringRep::cmp(retval->toNative(),source))
{
retval=GStringRep::UTF8::create((unsigned int)0);
}
}
#if DO_CHANGELOCALE
if(!repeat || retval || (lc_ctype == setlocale(LC_CTYPE,"")))
#endif
break;
}
#if DO_CHANGELOCALE
if(!repeat)
{
setlocale(LC_CTYPE,(const char *)lc_ctype);
}
#endif
}
return GUTF8String(retval);
}
GUTF8String
GBaseString::getNative2UTF8(void) const
{ //MBCS cvt
// We don't want to do a transform this
// if we already are in the given type.
// if (isUTF8()) return *this;
const size_t slen=length()+1;
GUTF8String retval;
if(slen > 1)
{
retval=NativeToUTF8();
if(!retval.length())
{
retval=(const char *)(*this);
}
}
return retval;
} /*MBCS*/
int
GStringRep::Native::cmp(const GP<GStringRep> &s2,const int len) const
{
int retval;
if(s2)
{
if(s2->isUTF8())
{
const GP<GStringRep> r(toUTF8(true));
if(r)
{
retval=GStringRep::cmp(r->data,s2->data,len);
}else
{
retval=cmp(s2->toNative(NOT_ESCAPED),len);
}
}else
{
retval=GStringRep::cmp(data,s2->data,len);
}
}else
{
retval=GStringRep::cmp(data,0,len);
}
return retval;
}
int
GStringRep::Native::toInt() const
{
return atoi(data);
}
long
GStringRep::Native::toLong(
const int pos, int &endpos, const int base) const
{
char *edata=0;
const long retval=strtol(data+pos, &edata, base);
if(edata)
{
endpos=(int)((size_t)edata-(size_t)data);
}else
{
endpos=(-1);
}
return retval;
}
unsigned long
GStringRep::Native::toULong(
const int pos, int &endpos, const int base) const
{
char *edata=0;
const unsigned long retval=strtoul(data+pos, &edata, base);
if(edata)
{
endpos=(int)((size_t)edata-(size_t)data);
}else
{
endpos=(-1);
}
return retval;
}
double
GStringRep::Native::toDouble(
const int pos, int &endpos) const
{
char *edata=0;
const double retval=strtod(data+pos, &edata);
if(edata)
{
endpos=(int)((size_t)edata-(size_t)data);
}else
{
endpos=(-1);
}
return retval;
}
static unsigned int to_ucs4(const char *pt, int * length)
{
const unsigned char* p = reinterpret_cast<const unsigned char*>(pt);
unsigned char b0 = *p++;
if ((b0 & ~0x7F) == 0) {
if (length)
*length = 1;
return static_cast<unsigned int>(b0);
}
int n;
for (n = 7; n >= 0; --n) {
if ((b0 & (1<<n)) == 0)
break;
}
if (n < 2 || n > 5) {
return -1;//invalid utf-8 sequence
}
int cb = 6-n;//count of bytes (excluding b0) that form utf-8 sequence for a single char
int rv = 0;
int sh = 6*cb;
rv |= (b0 & ((1<<n)-1))<<sh;;
//int sh = n;
for (int i = 0; i < cb; ++i) {
unsigned char b = *p++;
unsigned char mask_seq_mark = (1 << 7) | (1 << 6);
unsigned char expected_seq_mark = (1 << 7);
if ((b & mask_seq_mark ) != expected_seq_mark)
return -1;//invalid utf-8 sequnce;
unsigned char mask_value = (1 << 6)-1;
unsigned int val = b & mask_value;
sh -= 6;
rv |= (val << sh);
//sh -= 6;
}
if (length)
*length = cb+1;
return rv;
}
unsigned long
GStringRep::Native::getValidUCS4(const char *&source) const
{
#ifdef UNDER_CE
int length;
unsigned int ucs4char;
ucs4char = to_ucs4(source,&length);
source += length;
return static_cast<unsigned long>(ucs4char);
#else
unsigned long retval=0;
int n=(int)((size_t)size+(size_t)data-(size_t)source);
if(source && (n > 0))
{
mbstate_t ps;
//(void)mbrlen(source, n, &ps);
memset(&ps,0,sizeof(mbstate_t));
wchar_t wt;
const int len=mbrtowc(&wt,source,n,&ps);
if(len>=0)
{
if(sizeof(wchar_t) == sizeof(unsigned short))
{
source+=len;
unsigned short s[2];
s[0]=(unsigned short)wt;
if(UTF16toUCS4(retval,s,s+1)<=0)
{
if((n-=len)>0)
{
const int len=mbrtowc(&wt,source,n,&ps);
if(len>=0)
{
s[1]=(unsigned short)wt;
unsigned long w;
if(UTF16toUCS4(w,s,s+2)>0)
{
source+=len;
retval=w;
}
}
}
}
}else
{
retval=(unsigned long)wt;
source++;
}
}else
{
source++;
}
}
return retval;
#endif
}
// Tests if a string is legally encoded in the current character set.
bool
GStringRep::Native::is_valid(void) const
{
bool retval=true;
#ifndef UNDER_CE
if(data && size)
{
size_t n=size;
const char *s=data;
mbstate_t ps;
//(void)mbrlen(s, n, &ps);
memset(&ps,0,sizeof(mbstate_t));
do
{
size_t m=mbrlen(s,n,&ps);
if(m > n)
{
retval=false;
break;
}else if(m)
{
s+=m;
n-=m;
}else
{
break;
}
} while(n);
}
#endif
return retval;
}
// These are dummy functions.
void
GStringRep::set_remainder(void const * const, const unsigned int,
const EncodeType) {}
void
GStringRep::set_remainder(void const * const, const unsigned int,
const GP<GStringRep> &encoding) {}
void
GStringRep::set_remainder( const GP<GStringRep::Unicode> &) {}
GP<GStringRep::Unicode>
GStringRep::get_remainder( void ) const
{
return 0;
}
GNativeString::GNativeString(const char dat)
{
init(GStringRep::Native::create(&dat,0,1));
}
GNativeString::GNativeString(const char *str)
{
init(GStringRep::Native::create(str));
}
GNativeString::GNativeString(const unsigned char *str)
{
init(GStringRep::Native::create((const char *)str));
}
GNativeString::GNativeString(const unsigned short *str)
{
init(GStringRep::Native::create(str,0,-1));
}
GNativeString::GNativeString(const unsigned long *str)
{
init(GStringRep::Native::create(str,0,-1));
}
GNativeString::GNativeString(const char *dat, unsigned int len)
{
init(
GStringRep::Native::create(dat,0,((int)len<0)?(-1):(int)len));
}
GNativeString::GNativeString(const unsigned short *dat, unsigned int len)
{
init(
GStringRep::Native::create(dat,0,((int)len<0)?(-1):(int)len));
}
GNativeString::GNativeString(const unsigned long *dat, unsigned int len)
{
init(
GStringRep::Native::create(dat,0,((int)len<0)?(-1):(int)len));
}
GNativeString::GNativeString(const GNativeString &str)
{
init(str);
}
GNativeString::GNativeString(const GBaseString &gs, int from, int len)
{
init(
GStringRep::Native::create(gs,from,((int)len<0)?(-1):(int)len));
}
GNativeString::GNativeString(const int number)
{
init(GStringRep::Native::create_format("%d",number));
}
GNativeString::GNativeString(const double number)
{
init(GStringRep::Native::create_format("%f",number));
}
GNativeString&
GNativeString::operator= (const char str)
{ return init(GStringRep::Native::create(&str,0,1)); }
GNativeString&
GNativeString::operator= (const char *str)
{ return init(GStringRep::Native::create(str)); }
GNativeString
GBaseString::operator+(const GNativeString &s2) const
{
return GStringRep::Native::create(*this,s2);
}
GP<GStringRep>
GStringRep::NativeToUTF8( const char *s )
{
return GStringRep::Native::create(s)->toUTF8();
}
#endif // HAS_WCHAR
template <class TYPE>
GP<GStringRep>
GStringRep::create(const unsigned int sz, TYPE *)
{
GP<GStringRep> gaddr;
if (sz > 0)
{
GStringRep *addr;
gaddr=(addr=new TYPE);
addr->data=(char *)(::operator new(sz+1));
addr->size = sz;
addr->data[sz] = 0;
}
return gaddr;
}
GP<GStringRep>
GStringRep::strdup(const char *s) const
{
GP<GStringRep> retval;
const int length=s?strlen(s):0;
if(length>0)
{
retval=blank(length);
char const * const end=s+length;
char *ptr=retval->data;
for(;*s&&(s!=end);ptr++)
{
ptr[0]=s++[0];
}
ptr[0]=0;
}
return retval;
}
GP<GStringRep>
GStringRep::substr(const char *s,const int start,const int len) const
{
GP<GStringRep> retval;
if(s && s[0])
{
const unsigned int length=(start<0 || len<0)?(unsigned int)strlen(s):(unsigned int)(-1);
const char *startptr, *endptr;
if(start<0)
{
startptr=s+length+start;
if(startptr<s)
startptr=s;
}else
{
startptr=s;
for(const char * const ptr=s+start;(startptr<ptr)&&*startptr;++startptr)
EMPTY_LOOP;
}
if(len<0)
{
if(s+length+1 < startptr+len)
{
endptr=startptr;
}else
{
endptr=s+length+1+len;
}
}else
{
endptr=startptr;
for(const char * const ptr=startptr+len;(endptr<ptr)&&*endptr;++endptr)
EMPTY_LOOP;
}
if(endptr>startptr)
{
retval=blank((size_t)(endptr-startptr));
char *data=retval->data;
for(; (startptr<endptr) && *startptr; ++startptr,++data)
{
data[0]=startptr[0];
}
data[0]=0;
}
}
return retval;
}
GP<GStringRep>
GStringRep::substr(const unsigned short *s,const int start,const int len) const
{
GP<GStringRep> retval;
if(s && s[0])
{
unsigned short const *eptr;
if(len<0)
{
for(eptr=s;eptr[0];++eptr)
EMPTY_LOOP;
}else
{
eptr=&(s[len]);
}
s=&s[start];
if((size_t)s<(size_t)eptr)
{
mbstate_t ps;
memset(&ps,0,sizeof(mbstate_t));
unsigned char *buf,*ptr;
GPBuffer<unsigned char> gbuf(buf,(((size_t)eptr-(size_t)s)/2)*3+7);
for(ptr=buf;s[0];)
{
unsigned long w;
int i=UTF16toUCS4(w,s,eptr);
if(i<=0)
break;
s+=i;
ptr=UCS4toString(w,ptr,&ps);
}
ptr[0]=0;
retval = strdup( (const char *)buf );
}
}
return retval;
}
GP<GStringRep>
GStringRep::substr(const unsigned long *s,const int start,const int len) const
{
GP<GStringRep> retval;
if(s && s[0])
{
unsigned long const *eptr;
if(len<0)
{
for(eptr=s;eptr[0];++eptr)
EMPTY_LOOP;
}else
{
eptr=&(s[len]);
}
s=&s[start];
if((size_t)s<(size_t)eptr)
{
mbstate_t ps;
memset(&ps,0,sizeof(mbstate_t));
unsigned char *buf,*ptr;
GPBuffer<unsigned char> gbuf(buf,((((size_t)eptr-(size_t)s))/4)*6+7);
for(ptr=buf;s[0];++s)
{
ptr=UCS4toString(s[0],ptr,&ps);
}
ptr[0]=0;
retval = strdup( (const char *)buf );
}
}
return retval;
}
GP<GStringRep>
GStringRep::append(const char *s2) const
{
GP<GStringRep> retval;
if(s2)
{
retval=concat(data,s2);
}else
{
retval=const_cast<GStringRep *>(this);
}
return retval;
}
GP<GStringRep>
GStringRep::UTF8::append(const GP<GStringRep> &s2) const
{
GP<GStringRep> retval;
if(s2)
{
if(s2->isNative())
{
G_THROW( ERR_MSG("GStringRep.appendNativeToUTF8") );
}
retval=concat(data,s2->data);
}else
{
retval=const_cast<GStringRep::UTF8 *>(this);
}
return retval;
}
GP<GStringRep>
GStringRep::concat(const char *s1,const char *s2) const
{
const int length1=(s1?strlen(s1):0);
const int length2=(s2?strlen(s2):0);
const int length=length1+length2;
GP<GStringRep> retval;
if(length>0)
{
retval=blank(length);
GStringRep &r=*retval;
if(length1)
{
strcpy(r.data,s1);
if(length2)
strcat(r.data,s2);
}else
{
strcpy(r.data,s2);
}
}
return retval;
}
const char *GBaseString::nullstr = "";
void
GBaseString::empty( void )
{
init(0);
}
GP<GStringRep>
GStringRep::getbuf(int n) const
{
GP<GStringRep> retval;
if(n< 0)
n=strlen(data);
if(n>0)
{
retval=blank(n);
char *ndata=retval->data;
strncpy(ndata,data,n);
ndata[n]=0;
}
return retval;
}
const char *
GStringRep::isCharType(
bool (*xiswtest)(const unsigned long wc), const char *ptr, const bool reverse) const
{
char const * xptr=ptr;
const unsigned long w=getValidUCS4(xptr);
if((ptr != xptr)
&&(((sizeof(wchar_t) == 2)&&(w&~0xffff))
||(reverse?(!xiswtest(w)):xiswtest(w))))
{
ptr=xptr;
}
return ptr;
}
int
GStringRep::nextCharType(
bool (*xiswtest)(const unsigned long wc), const int from, const int len,
const bool reverse) const
{
// We want to return the position of the next
// non white space starting from the #from#
// location. isspace should work in any locale
// so we should only need to do this for the non-
// native locales (UTF8)
int retval;
if(from<size)
{
retval=from;
const char * ptr = data+from;
for( const char * const eptr=ptr+((len<0)?(size-from):len);
(ptr<eptr) && *ptr;)
{
// Skip characters that fail the isCharType test
char const * const xptr=isCharType(xiswtest,ptr,!reverse);
if(xptr == ptr)
break;
ptr=xptr;
}
retval=(int)((size_t)ptr-(size_t)data);
}else
{
retval=size;
}
return retval;
}
bool
GStringRep::giswspace(const unsigned long w)
{
#if HAS_WCTYPE
return
((sizeof(wchar_t) == 2)&&(w&~0xffff))
||((unsigned long)iswspace((wchar_t)w))
||((w == '\r')||(w == '\n'));
#else
return
(w&~0xff)?(true):(((unsigned long)isspace((char)w))||((w == '\r')||(w == '\n')));
#endif
}
bool
GStringRep::giswupper(const unsigned long w)
{
#if HAS_WCTYPE
return ((sizeof(wchar_t) == 2)&&(w&~0xffff))
?(true):((unsigned long)iswupper((wchar_t)w)?true:false);
#else
return (w&~0xff)?(true):((unsigned long)isupper((char)w)?true:false);
#endif
}
bool
GStringRep::giswlower(const unsigned long w)
{
#if HAS_WCTYPE
return ((sizeof(wchar_t) == 2)&&(w&~0xffff))
?(true):((unsigned long)iswlower((wchar_t)w)?true:false);
#else
return (w&~0xff)?(true):((unsigned long)islower((char)w)?true:false);
#endif
}
unsigned long
GStringRep::gtowupper(const unsigned long w)
{
#if HAS_WCTYPE
return ((sizeof(wchar_t) == 2)&&(w&~0xffff))
?w:((unsigned long)towupper((wchar_t)w));
#else
return (w&~0xff)?w:((unsigned long)toupper((char)w));
#endif
}
unsigned long
GStringRep::gtowlower(const unsigned long w)
{
#if HAS_WCTYPE
return ((sizeof(wchar_t) == 2)&&(w&~0xffff))
?w:((unsigned long)towlower((wchar_t)w));
#else
return (w&~0xff)?w:((unsigned long)tolower((char)w));
#endif
}
GP<GStringRep>
GStringRep::tocase(
bool (*xiswcase)(const unsigned long wc),
unsigned long (*xtowcase)(const unsigned long wc)) const
{
GP<GStringRep> retval;
char const * const eptr=data+size;
char const *ptr=data;
while(ptr<eptr)
{
char const * const xptr=isCharType(xiswcase,ptr,false);
if(ptr == xptr)
break;
ptr=xptr;
}
if(ptr<eptr)
{
const int n=(int)((size_t)ptr-(size_t)data);
unsigned char *buf;
GPBuffer<unsigned char> gbuf(buf,n+(1+size-n)*6);
if(n>0)
{
strncpy((char *)buf,data,n);
}
unsigned char *buf_ptr=buf+n;
for(char const *ptr=data+n;ptr<eptr;)
{
char const * const xptr=ptr;
const unsigned long w=getValidUCS4(ptr);
if(ptr == xptr)
break;
if(xiswcase(w))
{
const int len=(int)((size_t)ptr-(size_t)xptr);
strncpy((char *)buf_ptr,xptr,len);
buf_ptr+=len;
}else
{
mbstate_t ps;
memset(&ps,0,sizeof(mbstate_t));
buf_ptr=UCS4toString(xtowcase(w),buf_ptr,&ps);
}
}
buf_ptr[0]=0;
retval=substr((const char *)buf,0,(int)((size_t)buf_ptr-(size_t)buf));
}else
{
retval=const_cast<GStringRep *>(this);
}
return retval;
}
// Returns a copy of this string with characters used in XML escaped as follows:
// '<' --> "<"
// '>' --> ">"
// '&' --> "&"
// '\'' --> "'"
// '\"' --> """
// Also escapes characters 0x00 through 0x1f and 0x7e through 0x7f.
GP<GStringRep>
GStringRep::toEscaped( const bool tosevenbit ) const
{
bool modified=false;
char *ret;
GPBuffer<char> gret(ret,size*7);
ret[0]=0;
char *retptr=ret;
char const *start=data;
char const *s=start;
char const *last=s;
GP<GStringRep> special;
for(unsigned long w;(w=getValidUCS4(s));last=s)
{
char const *ss=0;
switch(w)
{
case '<':
ss="<";
break;
case '>':
ss=">";
break;
case '&':
ss="&";
break;
case '\47':
ss="'";
break;
case '\42':
ss=""";
break;
default:
if((w<' ')||(w>=0x7e && (tosevenbit || (w < 0x80))))
{
special=toThis(UTF8::create_format("&#%lu;",w));
ss=special->data;
}
break;
}
if(ss)
{
modified=true;
if(s!=start)
{
size_t len=(size_t)last-(size_t)start;
strncpy(retptr,start,len);
retptr+=len;
start=s;
}
if(ss[0])
{
size_t len=strlen(ss);
strcpy(retptr,ss);
retptr+=len;
}
}
}
GP<GStringRep> retval;
if(modified)
{
strcpy(retptr,start);
retval=strdup( ret );
}else
{
retval=const_cast<GStringRep *>(this);
}
// DEBUG_MSG( "Escaped string is '" << ret << "'\n" );
return retval;
}
static const GMap<GUTF8String,GUTF8String> &
BasicMap( void )
{
static GMap<GUTF8String,GUTF8String> Basic;
if (! Basic.size())
{
Basic["lt"] = GUTF8String('<');
Basic["gt"] = GUTF8String('>');
Basic["amp"] = GUTF8String('&');
Basic["apos"] = GUTF8String('\47');
Basic["quot"] = GUTF8String('\42');
}
return Basic;
}
GUTF8String
GUTF8String::fromEscaped( const GMap<GUTF8String,GUTF8String> ConvMap ) const
{
GUTF8String ret; // Build output string here
int start_locn = 0; // Beginning of substring to skip
int amp_locn; // Location of a found ampersand
while( (amp_locn = search( '&', start_locn )) > -1 )
{
// Found the next apostrophe
// Locate the closing semicolon
const int semi_locn = search( ';', amp_locn );
// No closing semicolon, exit and copy
// the rest of the string.
if( semi_locn < 0 )
break;
ret += substr( start_locn, amp_locn - start_locn );
int const len = semi_locn - amp_locn - 1;
if(len)
{
GUTF8String key = substr( amp_locn+1, len);
//DEBUG_MSG( "key = '" << key << "'\n" );
char const * s=key;
if( s[0] == '#')
{
unsigned long value;
char *ptr=0;
if(s[1] == 'x' || s[1] == 'X')
{
value=strtoul((char const *)(s+2),&ptr,16);
}else
{
value=strtoul((char const *)(s+1),&ptr,10);
}
if(ptr)
{
unsigned char utf8char[7];
unsigned char const * const end=GStringRep::UCS4toUTF8(value,utf8char);
ret+=GUTF8String((char const *)utf8char,(size_t)end-(size_t)utf8char);
}else
{
ret += substr( amp_locn, semi_locn - amp_locn + 1 );
}
}else
{
GPosition map_entry = ConvMap.contains( key );
if( map_entry )
{ // Found in the conversion map, substitute
ret += ConvMap[map_entry];
} else
{
static const GMap<GUTF8String,GUTF8String> &Basic = BasicMap();
GPosition map_entry = Basic.contains( key );
if ( map_entry )
{
ret += Basic[map_entry];
}else
{
ret += substr( amp_locn, len+2 );
}
}
}
}else
{
ret += substr( amp_locn, len+2 );
}
start_locn = semi_locn + 1;
// DEBUG_MSG( "ret = '" << ret << "'\n" );
}
// Copy the end of the string to the output
ret += substr( start_locn, length()-start_locn );
// DEBUG_MSG( "Unescaped string is '" << ret << "'\n" );
return (ret == *this)?(*this):ret;
}
GUTF8String
GUTF8String::fromEscaped(void) const
{
const GMap<GUTF8String,GUTF8String> nill;
return fromEscaped(nill);
}
GP<GStringRep>
GStringRep::setat(int n, char ch) const
{
GP<GStringRep> retval;
if(n<0)
n+=size;
if (n < 0 || n>size)
GBaseString::throw_illegal_subscript();
if(ch == data[n])
{
retval=const_cast<GStringRep *>(this);
}else if(!ch)
{
retval=getbuf(n);
}else
{
retval=getbuf((n<size)?size:n);
retval->data[n]=ch;
if(n == size)
retval->data[n+1]=0;
}
return retval;
}
#ifdef WIN32
#define USE_VSNPRINTF _vsnprintf
#endif
#ifdef AUTOCONF
# ifdef HAVE_VSNPRINTF
# define USE_VSNPRINTF vsnprintf
# endif
#else
# ifdef linux
# define USE_VSNPRINTF vsnprintf
# endif
#endif
GUTF8String &
GUTF8String::format(const char fmt[], ... )
{
va_list args;
va_start(args, fmt);
return init(GStringRep::UTF8::create(fmt,args));
}
GP<GStringRep>
GStringRep::UTF8::create_format(const char fmt[],...)
{
va_list args;
va_start(args, fmt);
return create(fmt,args);
}
GP<GStringRep>
GStringRep::vformat(va_list args) const
{
GP<GStringRep> retval;
if(size)
{
#ifndef WIN32
char *nfmt;
GPBuffer<char> gnfmt(nfmt,size+1);
nfmt[0]=0;
int start=0;
#endif
int from=0;
while((from=search('%',from)) >= 0)
{
if(data[++from] != '%')
{
int m,n=0;
sscanf(data+from,"%d!%n",&m,&n);
if(n)
{
#ifdef WIN32
char *lpszFormat=data;
LPTSTR lpszTemp;
if((!::FormatMessage(
FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,
lpszFormat, 0, 0, (LPTSTR)&lpszTemp,0,&args))
|| !lpszTemp)
{
G_THROW(GException::outofmemory);
}
va_end(args);
retval=strdup((const char *)lpszTemp);
LocalFree(lpszTemp);
break;
#else
from+=n;
const int end=search('!',from);
if(end>=0)
{
strncat(nfmt,data+start,(int)(end-start));
strncat(nfmt,"$",1);
start=from=end+1;
}else
{
gnfmt.resize(0);
from=(-1);
break;
}
#endif
}else
{
#ifndef WIN32
gnfmt.resize(0);
#endif
from=(-1);
break;
}
}
}
if(from < 0)
{
#ifndef WIN32
char const * const fmt=(nfmt&&nfmt[0])?nfmt:data;
#else
char const * const fmt=data;
#endif
int buflen=32768;
char *buffer;
GPBuffer<char> gbuffer(buffer,buflen);
ChangeLocale locale(LC_NUMERIC,(isNative()?0:"C"));
// Format string
#ifdef USE_VSNPRINTF
while(USE_VSNPRINTF(buffer, buflen, fmt, args)<0)
{
gbuffer.resize(0);
gbuffer.resize(buflen+32768);
}
va_end(args);
#else
buffer[buflen-1] = 0;
vsprintf(buffer, fmt, args);
va_end(args);
if (buffer[buflen-1])
{
// This isn't as fatal since it is on the stack, but we
// definitely should stop the current operation.
G_THROW( ERR_MSG("GString.overwrite") );
}
#endif
retval=strdup((const char *)buffer);
}
}
// Go altering the string
return retval;
}
int
GStringRep::search(char c, int from) const
{
if (from<0)
from += size;
int retval=(-1);
if (from>=0 && from<size)
{
char const *const s = strchr(data+from,c);
if(s)
retval=(int)((size_t)s-(size_t)data);
}
return retval;
}
int
GStringRep::search(char const *ptr, int from) const
{
if(from<0)
{
from+=size;
if(from<0)
G_THROW( ERR_MSG("GString.bad_subscript") );
}
int retval=(-1);
if (from>=0 && from<size)
{
char const *const s = strstr(data+from,ptr);
if(s)
retval=(int)((size_t)s-(size_t)data);
}
return retval;
}
int
GStringRep::rsearch(char c, int from) const
{
if(from<0)
{
from+=size;
if(from<0)
G_THROW( ERR_MSG("GString.bad_subscript") );
}
int retval=(-1);
if ((from>=0) && (from<size))
{
char const *const s = strrchr(data+from,c);
if(s)
retval=(int)((size_t)s-(size_t)data);
}
return retval;
}
int
GStringRep::rsearch(char const *ptr, int from) const
{
if(from<0)
{
from+=size;
if(from<0)
G_THROW( ERR_MSG("GString.bad_subscript") );
}
int retval=(-1);
for(int loc=from;(loc=search(ptr,loc)) >= 0;++loc)
retval=loc;
return retval;
}
int
GStringRep::contains(const char accept[],int from) const
{
if(from<0)
{
from+=size;
if(from<0)
G_THROW( ERR_MSG("GString.bad_subscript") );
}
int retval=(-1);
if (accept && accept[0] && from>=0 && from<size)
{
char const * const src = data+from;
char const *ptr=strpbrk(src,accept);
if(ptr)
{
retval=(int)(ptr-src)+from;
}
}
return retval;
}
int
GStringRep::rcontains(const char accept[],int from) const
{
int retval=(-1);
while((from=contains(accept,from)) >= 0)
{
retval=from++;
}
return retval;
}
bool
GBaseString::is_int(void) const
{
bool isLong=!!ptr;
if(isLong)
{
int endpos;
(*this)->toLong(0,endpos);
if(endpos>=0)
{
isLong=((*this)->nextNonSpace(endpos) == (int)length());
}
}
return isLong;
}
bool
GBaseString::is_float(void) const
{
bool isDouble=!!ptr;
if(isDouble)
{
int endpos;
(*this)->toDouble(0,endpos);
if(endpos>=0)
{
isDouble=((*this)->nextNonSpace(endpos) == (int)length());
}
}
return isDouble;
}
unsigned int
hash(const GBaseString &str)
{
unsigned int x = 0;
const char *s = (const char*)str;
while (*s)
x = x ^ (x<<6) ^ (unsigned char)(*s++);
return x;
}
void
GBaseString::throw_illegal_subscript()
{
G_THROW( ERR_MSG("GString.bad_subscript") );
}
unsigned char *
GStringRep::UTF8::UCS4toString(
const unsigned long w0,unsigned char *ptr, mbstate_t *) const
{
return UCS4toUTF8(w0,ptr);
}
int
GStringRep::UTF8::ncopy(
wchar_t * const buf, const int buflen ) const
{
int retval=(-1);
if(buf && buflen)
{
buf[0]=0;
if(data[0])
{
const size_t length=strlen(data);
const unsigned char * const eptr=(const unsigned char *)(data+length);
wchar_t *r=buf;
wchar_t const * const rend=buf+buflen;
for(const unsigned char *s=(const unsigned char *)data;(r<rend)&&(s<eptr)&&*s;)
{
const unsigned long w0=UTF8toUCS4(s,eptr);
unsigned short w1;
unsigned short w2=1;
for(int count=(sizeof(wchar_t) == sizeof(w1))?UCS4toUTF16(w0,w1,w2):1;
count&&(r<rend);
--count,w1=w2,++r)
{
r[0]=(sizeof(wchar_t) == sizeof(w1))?(wchar_t)w1:(wchar_t)w0;
}
}
if(r<rend)
{
r[0]=0;
retval=((size_t)r-(size_t)buf)/sizeof(wchar_t);
}
}else
{
retval=0;
}
}
return retval;
}
GP<GStringRep>
GStringRep::UTF8::toNative(const EscapeMode escape) const
{
GP<GStringRep> retval;
if(data[0])
{
const size_t length=strlen(data);
const unsigned char * const eptr=(const unsigned char *)(data+length);
unsigned char *buf;
GPBuffer<unsigned char> gbuf(buf,12*length+12);
unsigned char *r=buf;
mbstate_t ps;
memset(&ps,0,sizeof(mbstate_t));
for(const unsigned char *s=(const unsigned char *)data;(s<eptr)&& *s;)
{
const unsigned long w0=UTF8toUCS4(s,eptr);
const unsigned char * const r0=r;
r=UCS4toNative(w0,r,&ps);
if(r == r0)
{
if(escape == IS_ESCAPED)
{
sprintf((char *)r,"&#%lu;",w0);
r+=strlen((char *)r);
}else
{
r=buf;
break;
}
}
}
r[0]=0;
retval = NATIVE_CREATE( (const char *)buf );
} else
{
retval = NATIVE_CREATE( (unsigned int)0 );
}
return retval;
}
GP<GStringRep>
GStringRep::UTF8::toUTF8(const bool nothrow) const
{
if(!nothrow)
G_THROW( ERR_MSG("GStringRep.UTF8ToUTF8") );
return const_cast<GStringRep::UTF8 *>(this);
}
// Tests if a string is legally encoded in the current character set.
bool
GStringRep::UTF8::is_valid(void) const
{
bool retval=true;
if(data && size)
{
const unsigned char * const eptr=(const unsigned char *)(data+size);
for(const unsigned char *s=(const unsigned char *)data;(s<eptr)&& *s;)
{
const unsigned char * const r=s;
(void)UTF8toUCS4(s,eptr);
if(r == s)
{
retval=false;
break;
}
}
}
return retval;
}
static inline unsigned long
add_char(unsigned long const U, unsigned char const * const r)
{
unsigned long const C=r[0];
return ((C|0x3f) == 0xbf)?((U<<6)|(C&0x3f)):0;
}
unsigned long
GStringRep::UTF8toUCS4(
unsigned char const *&s,void const * const eptr)
{
unsigned long U=0;
unsigned char const *r=s;
if(r < eptr)
{
unsigned long const C1=r++[0];
if(C1&0x80)
{
if(r < eptr)
{
U=C1;
if((U=((C1&0x40)?add_char(U,r++):0)))
{
if(C1&0x20)
{
if(r < eptr)
{
if((U=add_char(U,r++)))
{
if(C1&0x10)
{
if(r < eptr)
{
if((U=add_char(U,r++)))
{
if(C1&0x8)
{
if(r < eptr)
{
if((U=add_char(U,r++)))
{
if(C1&0x4)
{
if(r < eptr)
{
if((U=((!(C1&0x2))?(add_char(U,r++)&0x7fffffff):0)))
{
s=r;
}else
{
U=(unsigned int)(-1)-s++[0];
}
}else
{
U=0;
}
}else if((U=((U&0x4000000)?0:(U&0x3ffffff))))
{
s=r;
}
}else
{
U=(unsigned int)(-1)-s++[0];
}
}else
{
U=0;
}
}else if((U=((U&0x200000)?0:(U&0x1fffff))))
{
s=r;
}
}else
{
U=(unsigned int)(-1)-s++[0];
}
}else
{
U=0;
}
}else if((U=((U&0x10000)?0:(U&0xffff))))
{
s=r;
}
}else
{
U=(unsigned int)(-1)-s++[0];
}
}else
{
U=0;
}
}else if((U=((U&0x800)?0:(U&0x7ff))))
{
s=r;
}
}else
{
U=(unsigned int)(-1)-s++[0];
}
}else
{
U=0;
}
}else if((U=C1))
{
s=r;
}
}
return U;
}
unsigned char *
GStringRep::UCS4toUTF8(const unsigned long w,unsigned char *ptr)
{
if(w <= 0x7f)
{
*ptr++ = (unsigned char)w;
}
else if(w <= 0x7ff)
{
*ptr++ = (unsigned char)((w>>6)|0xC0);
*ptr++ = (unsigned char)((w|0x80)&0xBF);
}
else if(w <= 0xFFFF)
{
*ptr++ = (unsigned char)((w>>12)|0xE0);
*ptr++ = (unsigned char)(((w>>6)|0x80)&0xBF);
*ptr++ = (unsigned char)((w|0x80)&0xBF);
}
else if(w <= 0x1FFFFF)
{
*ptr++ = (unsigned char)((w>>18)|0xF0);
*ptr++ = (unsigned char)(((w>>12)|0x80)&0xBF);
*ptr++ = (unsigned char)(((w>>6)|0x80)&0xBF);
*ptr++ = (unsigned char)((w|0x80)&0xBF);
}
else if(w <= 0x3FFFFFF)
{
*ptr++ = (unsigned char)((w>>24)|0xF8);
*ptr++ = (unsigned char)(((w>>18)|0x80)&0xBF);
*ptr++ = (unsigned char)(((w>>12)|0x80)&0xBF);
*ptr++ = (unsigned char)(((w>>6)|0x80)&0xBF);
*ptr++ = (unsigned char)((w|0x80)&0xBF);
}
else if(w <= 0x7FFFFFFF)
{
*ptr++ = (unsigned char)((w>>30)|0xFC);
*ptr++ = (unsigned char)(((w>>24)|0x80)&0xBF);
*ptr++ = (unsigned char)(((w>>18)|0x80)&0xBF);
*ptr++ = (unsigned char)(((w>>12)|0x80)&0xBF);
*ptr++ = (unsigned char)(((w>>6)|0x80)&0xBF);
*ptr++ = (unsigned char)((w|0x80)&0xBF);
}
else
{
*ptr++ = '?';
}
return ptr;
}
// Creates with a concat operation.
GP<GStringRep>
GStringRep::concat( const char *s1, const GP<GStringRep> &s2) const
{
GP<GStringRep> retval;
if(s2)
{
retval=toThis(s2);
if(s1 && s1[0])
{
if(retval)
{
retval=concat(s1,retval->data);
}else
{
retval=strdup(s1);
}
}
}else if(s1 && s1[0])
{
retval=strdup(s1);
}
return retval;
}
// Creates with a concat operation.
GP<GStringRep>
GStringRep::concat( const GP<GStringRep> &s1,const char *s2) const
{
GP<GStringRep> retval;
if(s1)
{
retval=toThis(s1);
if(s2 && s2[0])
{
if(retval)
{
retval=retval->append(s2);
}else
{
retval=strdup(s2);
}
}
}else if(s2 && s2[0])
{
retval=strdup(s2);
}
return retval;
}
GP<GStringRep>
GStringRep::concat(const GP<GStringRep> &s1,const GP<GStringRep> &s2) const
{
GP<GStringRep> retval;
if(s1)
{
retval=toThis(s1,s2);
if(retval && s2)
{
retval=retval->append(toThis(s2));
}
}else if(s2)
{
retval=toThis(s2);
}
return retval;
}
#ifdef WIN32
static const char *setlocale_win32(void)
{
static const char *locale=setlocale(LC_ALL,0);
if(! locale || (locale[0] == 'C' && !locale[1]))
{
locale=setlocale(LC_ALL,"");
}
return locale;
}
#endif
GStringRep::GStringRep(void)
{
#ifdef WIN32
static const char *locale=setlocale_win32();
#endif
size=0;
data=0;
}
GStringRep::~GStringRep()
{
if(data)
{
data[0]=0;
::operator delete(data);
}
data=0;
}
GStringRep::UTF8::UTF8(void) {}
GStringRep::UTF8::~UTF8() {}
int
GStringRep::cmp(const char *s1,const int len) const
{
return cmp(data,s1,len);
}
int
GStringRep::cmp(const char *s1, const char *s2,const int len)
{
return (len
?((s1&&s1[0])
?((s2&&s2[0])
?((len>0)
?strncmp(s1,s2,len)
:strcmp(s1,s2))
:1)
:((s2&&s2[0])?(-1):0))
:0);
}
int
GStringRep::cmp(const GP<GStringRep> &s1, const GP<GStringRep> &s2,
const int len )
{
return (s1?(s1->cmp(s2,len)):cmp(0,(s2?(s2->data):0),len));
}
int
GStringRep::cmp(const GP<GStringRep> &s1, const char *s2,
const int len )
{
return cmp((s1?s1->data:0),s2,len);
}
int
GStringRep::cmp(const char *s1, const GP<GStringRep> &s2,
const int len )
{
return cmp(s1,(s2?(s2->data):0),len);
}
int
GStringRep::UTF8::cmp(const GP<GStringRep> &s2,const int len) const
{
int retval;
if(s2)
{
if(s2->isNative())
{
GP<GStringRep> r(s2->toUTF8(true));
if(r)
{
retval=GStringRep::cmp(data,r->data,len);
}else
{
retval=-(s2->cmp(toNative(NOT_ESCAPED),len));
}
}else
{
retval=GStringRep::cmp(data,s2->data,len);
}
}else
{
retval=GStringRep::cmp(data,0,len);
}
return retval;
}
int
GStringRep::UTF8::toInt() const
{
int endpos;
return (int)toLong(0,endpos);
}
static inline long
Cstrtol(char *data,char **edata, const int base)
{
GStringRep::ChangeLocale locale(LC_NUMERIC,"C");
while (data && *data==' ') data++;
return strtol(data,edata,base);
}
long
GStringRep::UTF8::toLong(
const int pos, int &endpos, const int base) const
{
char *edata=0;
long retval=Cstrtol(data+pos,&edata, base);
if(edata)
{
endpos=edata-data;
}else
{
endpos=(-1);
GP<GStringRep> ptr=ptr->strdup(data+pos);
if(ptr)
ptr=ptr->toNative(NOT_ESCAPED);
if(ptr)
{
int xendpos;
retval=ptr->toLong(0,xendpos,base);
if(xendpos> 0)
{
endpos=(int)size;
ptr=ptr->strdup(data+xendpos);
if(ptr)
{
ptr=ptr->toUTF8(true);
if(ptr)
{
endpos-=(int)(ptr->size);
}
}
}
}
}
return retval;
}
static inline unsigned long
Cstrtoul(char *data,char **edata, const int base)
{
GStringRep::ChangeLocale locale(LC_NUMERIC,"C");
while (data && *data==' ') data++;
return strtoul(data,edata,base);
}
unsigned long
GStringRep::UTF8::toULong(
const int pos, int &endpos, const int base) const
{
char *edata=0;
unsigned long retval=Cstrtoul(data+pos,&edata, base);
if(edata)
{
endpos=edata-data;
}else
{
endpos=(-1);
GP<GStringRep> ptr=ptr->strdup(data+pos);
if(ptr)
ptr=ptr->toNative(NOT_ESCAPED);
if(ptr)
{
int xendpos;
retval=ptr->toULong(0,xendpos,base);
if(xendpos> 0)
{
endpos=(int)size;
ptr=ptr->strdup(data+xendpos);
if(ptr)
{
ptr=ptr->toUTF8(true);
if(ptr)
{
endpos-=(int)(ptr->size);
}
}
}
}
}
return retval;
}
static inline double
Cstrtod(char *data,char **edata)
{
GStringRep::ChangeLocale locale(LC_NUMERIC,"C");
while (data && *data==' ') data++;
return strtod(data,edata);
}
double
GStringRep::UTF8::toDouble(const int pos, int &endpos) const
{
char *edata=0;
double retval=Cstrtod(data+pos,&edata);
if(edata)
{
endpos=edata-data;
}else
{
endpos=(-1);
GP<GStringRep> ptr=ptr->strdup(data+pos);
if(ptr)
ptr=ptr->toNative(NOT_ESCAPED);
if(ptr)
{
int xendpos;
retval=ptr->toDouble(0,xendpos);
if(xendpos >= 0)
{
endpos=(int)size;
ptr=ptr->strdup(data+xendpos);
if(ptr)
{
ptr=ptr->toUTF8(true);
if(ptr)
{
endpos-=(int)(ptr->size);
}
}
}
}
}
return retval;
}
int
GStringRep::getUCS4(unsigned long &w, const int from) const
{
int retval;
if(from>=size)
{
w=0;
retval=size;
}else if(from<0)
{
w=(unsigned int)(-1);
retval=(-1);
}else
{
const char *source=data+from;
w=getValidUCS4(source);
retval=(int)((size_t)source-(size_t)data);
}
return retval;
}
unsigned long
GStringRep::UTF8::getValidUCS4(const char *&source) const
{
return GStringRep::UTF8toUCS4((const unsigned char *&)source,data+size);
}
int
GStringRep::nextNonSpace(const int from,const int len) const
{
return nextCharType(giswspace,from,len,true);
}
int
GStringRep::nextSpace(const int from,const int len) const
{
return nextCharType(giswspace,from,len,false);
}
int
GStringRep::nextChar(const int from) const
{
char const * xptr=data+from;
(void)getValidUCS4(xptr);
return (int)((size_t)xptr-(size_t)data);
}
int
GStringRep::firstEndSpace(int from,const int len) const
{
const int xsize=(len<0)?size:(from+len);
const int ysize=(size<xsize)?size:xsize;
int retval=ysize;
while(from<ysize)
{
from=nextNonSpace(from,ysize-from);
if(from < size)
{
const int r=nextSpace(from,ysize-from);
// If a character isn't legal, then it will return
// tru for both nextSpace and nextNonSpace.
if(r == from)
{
from++;
}else
{
from=retval=r;
}
}
}
return retval;
}
int
GStringRep::UCS4toUTF16(
const unsigned long w,unsigned short &w1, unsigned short &w2)
{
int retval;
if(w<0x10000)
{
w1=(unsigned short)w;
w2=0;
retval=1;
}else
{
w1=(unsigned short)((((w-0x10000)>>10)&0x3ff)+0xD800);
w2=(unsigned short)((w&0x3ff)+0xDC00);
retval=2;
}
return retval;
}
int
GStringRep::UTF16toUCS4(
unsigned long &U,unsigned short const * const s,void const * const eptr)
{
int retval=0;
U=0;
unsigned short const * const r=s+1;
if(r <= eptr)
{
unsigned long const W1=s[0];
if((W1<0xD800)||(W1>0xDFFF))
{
if((U=W1))
{
retval=1;
}
}else if(W1<=0xDBFF)
{
unsigned short const * const rr=r+1;
if(rr <= eptr)
{
unsigned long const W2=s[1];
if(((W2>=0xDC00)||(W2<=0xDFFF))&&((U=(0x10000+((W1&0x3ff)<<10))|(W2&0x3ff))))
{
retval=2;
}else
{
retval=(-1);
}
}
}
}
return retval;
}
//bcr
GUTF8String&
GUTF8String::operator+= (char ch)
{
return init(
GStringRep::UTF8::create((const char*)*this,
GStringRep::UTF8::create(&ch,0,1)));
}
GUTF8String&
GUTF8String::operator+= (const char *str)
{
return init(GStringRep::UTF8::create(*this,str));
}
GUTF8String&
GUTF8String::operator+= (const GBaseString &str)
{
return init(GStringRep::UTF8::create(*this,str));
}
GUTF8String
GUTF8String::substr(int from, int len) const
{ return GUTF8String(*this, from, len); }
GUTF8String
GUTF8String::operator+(const GBaseString &s2) const
{ return GStringRep::UTF8::create(*this,s2); }
GUTF8String
GUTF8String::operator+(const GUTF8String &s2) const
{ return GStringRep::UTF8::create(*this,s2); }
GUTF8String
GUTF8String::operator+(const char *s2) const
{ return GStringRep::UTF8::create(*this,s2); }
char *
GUTF8String::getbuf(int n)
{
if(ptr)
init((*this)->getbuf(n));
else if(n>0)
init(GStringRep::UTF8::create(n));
else
init(0);
return ptr?((*this)->data):0;
}
void
GUTF8String::setat(const int n, const char ch)
{
if((!n)&&(!ptr))
{
init(GStringRep::UTF8::create(&ch,0,1));
}else
{
init((*this)->setat(CheckSubscript(n),ch));
}
}
GP<GStringRep>
GStringRep::UTF8ToNative( const char *s, const EscapeMode escape )
{
return GStringRep::UTF8::create(s)->toNative(escape);
}
GUTF8String::GUTF8String(const char dat)
{ init(GStringRep::UTF8::create(&dat,0,1)); }
GUTF8String::GUTF8String(const GUTF8String &fmt, va_list &args)
{
if (fmt.ptr)
init(fmt->vformat(args));
else
init(fmt);
}
GUTF8String::GUTF8String(const unsigned char *str)
{ init(GStringRep::UTF8::create((const char *)str)); }
GUTF8String::GUTF8String(const unsigned short *str)
{ init(GStringRep::UTF8::create(str,0,-1)); }
GUTF8String::GUTF8String(const unsigned long *str)
{ init(GStringRep::UTF8::create(str,0,-1)); }
GUTF8String::GUTF8String(const char *dat, unsigned int len)
{ init(GStringRep::UTF8::create(dat,0,((int)len<0)?(-1):(int)len)); }
GUTF8String::GUTF8String(const unsigned short *dat, unsigned int len)
{ init(GStringRep::UTF8::create(dat,0,((int)len<0)?(-1):(int)len)); }
GUTF8String::GUTF8String(const unsigned long *dat, unsigned int len)
{ init(GStringRep::UTF8::create(dat,0,((int)len<0)?(-1):(int)len)); }
GUTF8String::GUTF8String(const GBaseString &gs, int from, int len)
{ init(GStringRep::UTF8::create(gs,from,((int)len<0)?(-1):(int)len)); }
GUTF8String::GUTF8String(const int number)
{ init(GStringRep::UTF8::create_format("%d",number)); }
GUTF8String::GUTF8String(const double number)
{ init(GStringRep::UTF8::create_format("%f",number)); }
GUTF8String& GUTF8String::operator= (const char str)
{ return init(GStringRep::UTF8::create(&str,0,1)); }
GUTF8String& GUTF8String::operator= (const char *str)
{ return init(GStringRep::UTF8::create(str)); }
GUTF8String GBaseString::operator+(const GUTF8String &s2) const
{ return GStringRep::UTF8::create(*this,s2); }
#if HAS_WCHAR
GUTF8String
GNativeString::operator+(const GUTF8String &s2) const
{
if (ptr)
return GStringRep::UTF8::create((*this)->toUTF8(true),s2);
else
return GStringRep::UTF8::create((*this),s2);
}
#endif
GUTF8String
GUTF8String::operator+(const GNativeString &s2) const
{
GP<GStringRep> g = s2;
if (s2.ptr)
g = s2->toUTF8(true);
return GStringRep::UTF8::create(*this,g);
}
GUTF8String
operator+(const char *s1, const GUTF8String &s2)
{ return GStringRep::UTF8::create(s1,s2); }
#if HAS_WCHAR
GNativeString
operator+(const char *s1, const GNativeString &s2)
{ return GStringRep::Native::create(s1,s2); }
GNativeString&
GNativeString::operator+= (char ch)
{
char s[2]; s[0]=ch; s[1]=0;
return init(GStringRep::Native::create((const char*)*this, s));
}
GNativeString&
GNativeString::operator+= (const char *str)
{
return init(GStringRep::Native::create(*this,str));
}
GNativeString&
GNativeString::operator+= (const GBaseString &str)
{
return init(GStringRep::Native::create(*this,str));
}
GNativeString
GNativeString::operator+(const GBaseString &s2) const
{ return GStringRep::Native::create(*this,s2); }
GNativeString
GNativeString::operator+(const GNativeString &s2) const
{ return GStringRep::Native::create(*this,s2); }
GNativeString
GNativeString::operator+(const char *s2) const
{ return GStringRep::Native::create(*this,s2); }
char *
GNativeString::getbuf(int n)
{
if(ptr)
init((*this)->getbuf(n));
else if(n>0)
init(GStringRep::Native::create(n));
else
init(0);
return ptr?((*this)->data):0;
}
void
GNativeString::setat(const int n, const char ch)
{
if((!n)&&(!ptr))
{
init(GStringRep::Native::create(&ch,0,1));
}else
{
init((*this)->setat(CheckSubscript(n),ch));
}
}
#endif
#ifdef HAVE_NAMESPACES
}
# ifndef NOT_USING_DJVU_NAMESPACE
using namespace DJVU;
# endif
#endif
| [
"Igor.Solovyov@84cd470b-3125-0410-acc3-039690e87181"
] | [
[
[
1,
2909
]
]
] |
cdeb567f4bd6af36f78472db236de5ba6d9c8b4e | 04fec4cbb69789d44717aace6c8c5490f2cdfa47 | /include/wx/msw/glcanvas.h | 2396360adfc3d9bef185b6343900c7d13532d2c6 | [] | no_license | aaryanapps/whiteTiger | 04f39b00946376c273bcbd323414f0a0b675d49d | 65ed8ffd530f20198280b8a9ea79cb22a6a47acd | refs/heads/master | 2021-01-17T12:07:15.264788 | 2010-10-11T20:20:26 | 2010-10-11T20:20:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,974 | h | /////////////////////////////////////////////////////////////////////////////
// Name: wx/msw/glcanvas.h
// Purpose: wxGLCanvas, for using OpenGL with wxWidgets under Windows
// Author: Julian Smart
// Modified by:
// Created: 04/01/98
// RCS-ID: $Id: glcanvas.h 43097 2006-11-06 00:57:46Z VZ $
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_GLCANVAS_H_
#define _WX_GLCANVAS_H_
#include "wx/palette.h"
#include "wx/scrolwin.h"
#include "wx/msw/wrapwin.h"
#include <GL/gl.h>
class WXDLLIMPEXP_GL wxGLCanvas; /* forward reference */
class WXDLLIMPEXP_GL wxGLContext: public wxObject
{
public:
wxGLContext(wxGLCanvas *win, const wxGLContext* other=NULL /* for sharing display lists */ );
virtual ~wxGLContext();
void SetCurrent(const wxGLCanvas& win) const;
inline HGLRC GetGLRC() const { return m_glContext; }
protected:
HGLRC m_glContext;
private:
DECLARE_CLASS(wxGLContext)
};
class WXDLLIMPEXP_GL wxGLCanvas: public wxWindow
{
public:
// This ctor is identical to the next, except for the fact that it
// doesn't create an implicit wxGLContext.
// The attribList parameter has been moved to avoid overload clashes.
wxGLCanvas(wxWindow *parent, wxWindowID id = wxID_ANY,
int* attribList = 0,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize, long style = 0,
const wxString& name = wxGLCanvasName,
const wxPalette& palette = wxNullPalette);
wxGLCanvas(wxWindow *parent, wxWindowID id = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize, long style = 0,
const wxString& name = wxGLCanvasName, int *attribList = 0,
const wxPalette& palette = wxNullPalette);
wxGLCanvas(wxWindow *parent,
const wxGLContext *shared,
wxWindowID id = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0,
const wxString& name = wxGLCanvasName,
int *attribList = (int *) NULL,
const wxPalette& palette = wxNullPalette);
wxGLCanvas(wxWindow *parent,
const wxGLCanvas *shared,
wxWindowID id = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0,
const wxString& name = wxGLCanvasName,
int *attribList = 0,
const wxPalette& palette = wxNullPalette);
virtual ~wxGLCanvas();
// Replaces wxWindow::Create functionality, since
// we need to use a different window class
bool Create(wxWindow *parent, wxWindowID id,
const wxPoint& pos, const wxSize& size,
long style, const wxString& name);
void SetCurrent(const wxGLContext& RC) const;
void SetCurrent();
#ifdef __WXUNIVERSAL__
virtual bool SetCurrent(bool doit) { return wxWindow::SetCurrent(doit); };
#endif
void SetColour(const wxChar *colour);
void SwapBuffers();
void OnSize(wxSizeEvent& event);
void OnQueryNewPalette(wxQueryNewPaletteEvent& event);
void OnPaletteChanged(wxPaletteChangedEvent& event);
inline wxGLContext* GetContext() const { return m_glContext; }
inline WXHDC GetHDC() const { return m_hDC; }
void SetupPixelFormat(int *attribList = (int *) NULL);
void SetupPalette(const wxPalette& palette);
wxPalette CreateDefaultPalette();
inline wxPalette* GetPalette() const { return (wxPalette *) &m_palette; }
protected:
wxGLContext* m_glContext; // this is typedef-ed ptr, in fact
wxPalette m_palette;
WXHDC m_hDC;
private:
DECLARE_EVENT_TABLE()
DECLARE_CLASS(wxGLCanvas)
};
#endif
// _WX_GLCANVAS_H_
| [
"[email protected]"
] | [
[
[
1,
128
]
]
] |
2234917a85e6869ee456e6124b99e98965503c67 | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /Sockets/HttpResponse.h | a17eedd0b2b9f924effc9eec229646f81e968856 | [] | no_license | 15831944/phoebemail | 0931b76a5c52324669f902176c8477e3bd69f9b1 | e10140c36153aa00d0251f94bde576c16cab61bd | refs/heads/master | 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,762 | h | /**
** \file HttpResponse.h
** \date 2007-10-05
** \author [email protected]
**/
/*
Copyright (C) 2007-2009 Anders Hedstrom
This library is made available under the terms of the GNU GPL, with
the additional exemption that compiling, linking, and/or using OpenSSL
is allowed.
If you would like to use this library in a closed-source application,
a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
email [email protected].
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _SOCKETS_HttpResponse_H
#define _SOCKETS_HttpResponse_H
#include "HttpTransaction.h"
#include <list>
#ifdef SOCKETS_NAMESPACE
namespace SOCKETS_NAMESPACE {
#endif
class IFile;
class HttpResponse : public HttpTransaction
{
public:
HttpResponse(const std::string& version = "HTTP/1.0");
HttpResponse(const HttpResponse& src);
~HttpResponse();
HttpResponse& operator=(const HttpResponse& src);
/** HTTP/1.x */
void SetHttpVersion(const std::string& value);
const std::string& HttpVersion() const;
void SetHttpStatusCode(int value);
int HttpStatusCode() const;
void SetHttpStatusMsg(const std::string& value);
const std::string& HttpStatusMsg() const;
void SetCookie(const std::string& value);
const std::string Cookie(const std::string& name) const;
std::list<std::string> CookieNames() const;
void Write( const std::string& str );
void Write( const char *buf, size_t sz );
void Writef( const char *format, ... );
const IFile& GetFile() const { return *m_file; }
/** Replace memfile with file on disk, opened for read. */
void SetFile( const std::string& path );
void Reset();
private:
std::string m_http_version;
int m_http_status_code;
std::string m_http_status_msg;
Utility::ncmap<std::string> m_cookie;
mutable std::auto_ptr<IFile> m_file;
}; // end of class
#ifdef SOCKETS_NAMESPACE
} // namespace SOCKETS_NAMESPACE {
#endif
#endif // _SOCKETS_HttpResponse_H
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
] | [
[
[
1,
95
]
]
] |
74a5db913b784de70371bb4508e54405d2be4b91 | ea2786bfb29ab1522074aa865524600f719b5d60 | /MultimodalSpaceShooter/src/core/Game.cpp | 152ac1a4eee3a2219e7f2176b7b2b524bf9b90c4 | [] | no_license | jeremysingy/multimodal-space-shooter | 90ffda254246d0e3a1e25558aae5a15fed39137f | ca6e28944cdda97285a2caf90e635a73c9e4e5cd | refs/heads/master | 2021-01-19T08:52:52.393679 | 2011-04-12T08:37:03 | 2011-04-12T08:37:03 | 1,467,691 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,205 | cpp | #include "core/Game.h"
#include "entities/Spaceship.h"
#include "entities/Planet.h"
#include "utils/AnimatedSprite.h"
Game& Game::instance()
{
static Game game;
return game;
}
Game::Game() :
myScreenSize(1024, 768),
myWindow(sf::VideoMode(myScreenSize.x, myScreenSize.y, 32), "Multimodal Space Shooter - By SBB"),
myEventManager(myWindow.GetInput()),
myImageManager("./images/"),
mySoundManager("./sounds/")
{
myWindow.ShowMouseCursor(false);
myWindow.EnableKeyRepeat(false);
}
const sf::Vector2i& Game::getScreenSize()
{
return myScreenSize;
}
void Game::run()
{
while(myWindow.IsOpened())
{
// Dispatch events to the event manager
myEventManager.update(myWindow);
// Update the multimodal events (gesture and voice)
myMultimodalManager.update();
// Update the current scene
mySceneManager.updateScene(myWindow.GetFrameTime());
// Clear screen
myWindow.Clear();
// Draw the current scene
mySceneManager.drawScene(myWindow);
// Display content
myWindow.Display();
}
}
void Game::quit()
{
myWindow.Close();
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
12
],
[
14,
55
]
],
[
[
13,
13
]
]
] |
f8f352094e3eee82e224229e463e3c301edae262 | 62e5e66246617ec5f030ce9711b855979d8fcb19 | /Microprocessadores II/Projeto elevador/RS-232/CommThread_Unit.cpp | bb044268b8290b689d31a8df52e2c618be59fd84 | [] | no_license | JaconsMorais/repcomputaria | 67fbdd4ceab7868a2bfac8f6a8b1ff969b41ca90 | eb53f788e885f93e6e2665f2e588ca16475b30ef | refs/heads/master | 2021-01-10T16:31:16.433608 | 2011-07-12T01:00:05 | 2011-07-12T01:00:05 | 51,807,319 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,390 | cpp | //---------------------------------------------------------------------------
//TCommThread version 6.0 - 30/11/2005
//Luciano Vieira Koenigkan - e-mail: [email protected]
#include <vcl.h>
#pragma hdrstop
#include "CommThread_Unit.h"
#pragma package(smart_init)
//---------------------------------------------------------------------------
// Important: Methods and properties of objects in VCL can only be
// used in a method called using Synchronize, for example:
//
// Synchronize(UpdateCaption);
//
// where UpdateCaption could look like:
//
// void __fastcall Unit2::UpdateCaption()
// {
// Form1->Caption = "Updated in a thread";
// }
//---------------------------------------------------------------------------
__fastcall TCommThread::TCommThread()
: TThread(true),ReturnMethod(NULL)
{
//Inicializando os atributos
Connected=false;
FreeOnTerminate = false;
DeviceName="COM1";
MyDCB.DCBlength=sizeof(DCB);
MyDCB.BaudRate=9600;
MyDCB.ByteSize=8;
MyDCB.Parity=NOPARITY;
MyDCB.StopBits=ONESTOPBIT;
MyTimeouts.ReadIntervalTimeout=15;
MyTimeouts.ReadTotalTimeoutMultiplier=1;
MyTimeouts.ReadTotalTimeoutConstant=250;
MyTimeouts.WriteTotalTimeoutMultiplier=1;
MyTimeouts.WriteTotalTimeoutConstant=250;
ReceiveQueue=32;
TransmitQueue=9;
MaxFails=100000;
ReceiveInterval=1;
}
//---------------------------------------------------------------------------
__fastcall TCommThread::TCommThread(void(__closure *NewReturnMethod)(AnsiString))
: TThread(true),ReturnMethod(NewReturnMethod)
{
//Inicializando os atributos
Connected=false;
DeviceName="COM1";
MyDCB.DCBlength=sizeof(DCB);
MyDCB.BaudRate=9600;
MyDCB.ByteSize=8;
MyDCB.Parity=NOPARITY;
MyDCB.StopBits=ONESTOPBIT;
MyTimeouts.ReadIntervalTimeout=15;
MyTimeouts.ReadTotalTimeoutMultiplier=1;
MyTimeouts.ReadTotalTimeoutConstant=250;
MyTimeouts.WriteTotalTimeoutMultiplier=1;
MyTimeouts.WriteTotalTimeoutConstant=250;
ReceiveQueue=32;
TransmitQueue=9;
MaxFails=100000;
ReceiveInterval=1;
}
//---------------------------------------------------------------------------
void __fastcall TCommThread::Execute()
{
unsigned long AvailableBytes;
unsigned long ReadBytes;
while(Terminated==false)
{
Sleep(ReceiveInterval);
AvailableBytes=BytesAvailable();
if(AvailableBytes>0)
{
ReceivedData.SetLength(AvailableBytes);
if(ReadFile(DeviceHandle,(void*)ReceivedData.data(),AvailableBytes,&ReadBytes,NULL)==true)
{
if(ReadBytes>0)
{
Synchronize(AfterReceiveData);
ReceivedData="";
}//if
}//if
}//if
}
}
//---------------------------------------------------------------------------
bool TCommThread::Connect(void)
{
Synchronize(Open);
return(Connected);
}
//---------------------------------------------------------------------------
bool TCommThread::Disconnect(void)
{
Synchronize(Close);
return(!Connected);
}
//---------------------------------------------------------------------------
bool TCommThread::GetConnected(void)
{
return(Connected);
}
//---------------------------------------------------------------------------
void __fastcall TCommThread::AfterReceiveData()
{
ReturnMethod(ReceivedData);
}
//---------------------------------------------------------------------------
bool TCommThread::TransmitChar(char c)
{
unsigned long CEnviados;
CEnviados=0;
if(Connected==true)
{
if(WriteFile(DeviceHandle,&c,1,&CEnviados,NULL)!=0)
return(true);
else
return(false);
}//if
else
return(false);
}
//---------------------------------------------------------------------------
int TCommThread::BytesAvailable(void)
{
if(Connected==true)
{
COMSTAT TempStat;
DWORD TempDword;
if(ClearCommError(DeviceHandle,&TempDword,&TempStat)==true)
{
return(TempStat.cbInQue);
}//if
else
return(0);
}//if
else
return(0);
}
//---------------------------------------------------------------------------
bool TCommThread::TransmitData(AnsiString Data)
{
int i;
int Fails;
i=1;
Fails=0;
while((i<=Data.Length())&&(Data.Length()>0)&&(Fails<MaxFails))
{
if(TransmitChar(Data[i])==true)
{
i++;
Fails=0;
}
else
{
Fails++;
}
}
if(Fails<MaxFails)
return(true);
else
return(false);
}
//---------------------------------------------------------------------------
void __fastcall TCommThread::Close()
{
if(Connected==true)
{
//back to original setings
SetCommState(DeviceHandle,&OriginalDCB);
SetCommTimeouts(DeviceHandle,&OriginalTimeouts);
if(CloseHandle(DeviceHandle)!=0)
{
Connected=false;
}//if
else
{
SetCommState(DeviceHandle,&MyDCB);
SetCommTimeouts(DeviceHandle,&MyTimeouts);
}
}//if
}
//---------------------------------------------------------------------------
void __fastcall TCommThread::Open()
{
if(Connected==false)
{
//Open device
DeviceHandle=CreateFile( DeviceName.c_str(),
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,
NULL
);
if(DeviceHandle!=INVALID_HANDLE_VALUE)
{
//Make backup and set DCB of open device
GetCommState(DeviceHandle,&OriginalDCB);
SetCommState(DeviceHandle,&MyDCB);
//Make backup and set COMMTIMEOUTS of open device
GetCommTimeouts(DeviceHandle,&OriginalTimeouts);
SetCommTimeouts(DeviceHandle,&MyTimeouts);
SetupComm(DeviceHandle,1024*ReceiveQueue,1024*TransmitQueue);
//Resume Thread
if(this->Suspended)
Resume();
Connected=true;
}//if
}//if
}
//---------------------------------------------------------------------------
void TCommThread::SetDeviceName(AnsiString NewDeviceName)
{
if(Connected==true)
{
Disconnect();
DeviceName=NewDeviceName;
Connect();
}
else
DeviceName=NewDeviceName;
}
//---------------------------------------------------------------------------
AnsiString TCommThread::GetDeviceName(void)
{
return(DeviceName);
}
//---------------------------------------------------------------------------
HANDLE TCommThread::GetDeviceHandle(void)
{
return(DeviceHandle);
}
//---------------------------------------------------------------------------
int TCommThread::GetReceiveQueue(void)
{
return(ReceiveQueue);
}
//---------------------------------------------------------------------------
void TCommThread::SetReceiveQueue(int NewReceiveQueue)
{
if(Connected==true)
{
Disconnect();
ReceiveQueue=NewReceiveQueue;
Connect();
}
else
ReceiveQueue=NewReceiveQueue;
}
//---------------------------------------------------------------------------
void TCommThread::SetReturnMethod(void(__closure *NewReturnMethod)(AnsiString))
{
if(Connected==true)
{
Disconnect();
ReturnMethod=NewReturnMethod;
Connect();
}
else
ReturnMethod=NewReturnMethod;
}
//---------------------------------------------------------------------------
int TCommThread::GetTransmitQueue(void)
{
return(TransmitQueue);
}
//---------------------------------------------------------------------------
void TCommThread::SetTransmitQueue(int NewTransmitQueue)
{
if(Connected==true)
{
Disconnect();
TransmitQueue=NewTransmitQueue;
Connect();
}
else
TransmitQueue=NewTransmitQueue;
}
//---------------------------------------------------------------------------
void TCommThread::SetMaxFails(int NewMaxFails)
{
if(Connected==true)
{
Disconnect();
MaxFails=NewMaxFails;
Connect();
}
else
MaxFails=NewMaxFails;
}
//---------------------------------------------------------------------------
int TCommThread::GetMaxFails(void)
{
return(MaxFails);
}
//---------------------------------------------------------------------------
int TCommThread::GetBaudRate(void)
{
return(MyDCB.BaudRate);
}
//---------------------------------------------------------------------------
void TCommThread::SetBaudRate(int NewBaudRate)
{
if(Connected==true)
{
Disconnect();
MyDCB.BaudRate=NewBaudRate;
Connect();
}
else
MyDCB.BaudRate=NewBaudRate;
}
//---------------------------------------------------------------------------
int TCommThread::GetByteSize(void)
{
return(MyDCB.ByteSize);
}
//---------------------------------------------------------------------------
void TCommThread::SetByteSize(int NewByteSize)
{
if(Connected==true)
{
Disconnect();
MyDCB.ByteSize=NewByteSize;
Connect();
}
else
MyDCB.ByteSize=NewByteSize;
}
//---------------------------------------------------------------------------
int TCommThread::GetParity(void)
{
return(MyDCB.Parity);
}
//---------------------------------------------------------------------------
void TCommThread::SetParity(int NewParity)
{
if(Connected==true)
{
Disconnect();
MyDCB.Parity=NewParity;
Connect();
}
else
MyDCB.Parity=NewParity;
}
//---------------------------------------------------------------------------
int TCommThread::GetStopBits(void)
{
return(MyDCB.StopBits);
}
//---------------------------------------------------------------------------
void TCommThread::SetStopBits(int NewStopBits)
{
if(Connected==true)
{
Disconnect();
MyDCB.StopBits=NewStopBits;
Connect();
}
else
MyDCB.StopBits=NewStopBits;
}
//---------------------------------------------------------------------------
int TCommThread::GetReadIntervalTimeout(void)
{
return(MyTimeouts.ReadIntervalTimeout);
}
//---------------------------------------------------------------------------
void TCommThread::SetReadIntervalTimeout(int NewReadIntervalTimeout)
{
if(Connected==true)
{
Disconnect();
MyTimeouts.ReadIntervalTimeout=NewReadIntervalTimeout;
Connect();
}
else
MyTimeouts.ReadIntervalTimeout=NewReadIntervalTimeout;
}
//---------------------------------------------------------------------------
int TCommThread::GetReadTotalTimeoutMultiplier(void)
{
return(MyTimeouts.ReadTotalTimeoutMultiplier);
}
//---------------------------------------------------------------------------
void TCommThread::SetReadTotalTimeoutMultiplier(int NewReadTotalTimeoutMultiplier)
{
if(Connected==true)
{
Disconnect();
MyTimeouts.ReadTotalTimeoutMultiplier=NewReadTotalTimeoutMultiplier;
Connect();
}
else
MyTimeouts.ReadTotalTimeoutMultiplier=NewReadTotalTimeoutMultiplier;
}
//---------------------------------------------------------------------------
int TCommThread::GetReadTotalTimeoutConstant(void)
{
return(MyTimeouts.ReadTotalTimeoutConstant);
}
//---------------------------------------------------------------------------
void TCommThread::SetReadTotalTimeoutConstant(int NewReadTotalTimeoutConstant)
{
if(Connected==true)
{
Disconnect();
MyTimeouts.ReadTotalTimeoutConstant=NewReadTotalTimeoutConstant;
Connect();
}
else
MyTimeouts.ReadTotalTimeoutConstant=NewReadTotalTimeoutConstant;
}
//---------------------------------------------------------------------------
int TCommThread::GetWriteTotalTimeoutMultiplier(void)
{
return(MyTimeouts.WriteTotalTimeoutMultiplier);
}
//---------------------------------------------------------------------------
void TCommThread::SetWriteTotalTimeoutMultiplier(int NewWriteTotalTimeoutMultiplier)
{
if(Connected==true)
{
Disconnect();
MyTimeouts.WriteTotalTimeoutMultiplier=NewWriteTotalTimeoutMultiplier;
Connect();
}
else
MyTimeouts.WriteTotalTimeoutMultiplier=NewWriteTotalTimeoutMultiplier;
}
//---------------------------------------------------------------------------
int TCommThread::GetWriteTotalTimeoutConstant(void)
{
return(MyTimeouts.WriteTotalTimeoutConstant);
}
//---------------------------------------------------------------------------
void TCommThread::SetWriteTotalTimeoutConstant(int NewWriteTotalTimeoutConstant)
{
if(Connected==true)
{
Disconnect();
MyTimeouts.WriteTotalTimeoutConstant=NewWriteTotalTimeoutConstant;
Connect();
}
else
MyTimeouts.WriteTotalTimeoutConstant=NewWriteTotalTimeoutConstant;
}
//---------------------------------------------------------------------------
AnsiString TCommThread::GetAvailableData(void)
{
unsigned long AvailableBytes;
unsigned long ReadBytes;
ReceivedData="";
AvailableBytes=BytesAvailable();
if(AvailableBytes>0)
{
ReceivedData.SetLength(AvailableBytes);
if(ReadFile(DeviceHandle,(void*)ReceivedData.data(),AvailableBytes,&ReadBytes,NULL)==true)
{
if(ReadBytes>0)
{
return(ReceivedData);
}//if
}//if
}
return("");
}
//---------------------------------------------------------------------------
void TCommThread::SetReceiveInterval(int NewReceiveInterval)
{
ReceiveInterval=NewReceiveInterval;
}
//---------------------------------------------------------------------------
int TCommThread::GetReceiveInterval(void)
{
return ReceiveInterval;
}
//---------------------------------------------------------------------------
TStringList* TCommThread::GetAvailableDevicesNames(bool IncludeSerial, bool IncludeParallel, TStringList * AvaiableDevicesNames)
{
TRegistry *Registro = new TRegistry();
TStringList *StringsTemp = new TStringList();
int Indice;
if (AvaiableDevicesNames!=NULL)
AvaiableDevicesNames->Clear();
else
AvaiableDevicesNames = new TStringList();
Registro->RootKey=HKEY_LOCAL_MACHINE;
if(IncludeSerial==true)
{
StringsTemp->Clear();
Registro->OpenKey("hardware\\devicemap\\serialcomm",false);
Registro->GetValueNames(StringsTemp);
for (Indice=0;Indice<StringsTemp->Count;Indice++)
AvaiableDevicesNames->Add(Registro->ReadString(StringsTemp->Strings[Indice]));
Registro->CloseKey();
}
if(IncludeParallel==true)
{
StringsTemp->Clear();
Registro->OpenKey("hardware\\devicemap\\parallel ports",false);
Registro->GetValueNames(StringsTemp);
for (Indice=0;Indice<StringsTemp->Count;Indice++)
AvaiableDevicesNames->Add(ExtractFileName(Registro->ReadString(StringsTemp->Strings[Indice])));
Registro->CloseKey();
}
AvaiableDevicesNames->Sort();
delete Registro;
delete StringsTemp;
return AvaiableDevicesNames;
}
//---------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
587
]
]
] |
79b71e8005fbe05d907f70ce36bebe30f9474f3d | c1c3866586c56ec921cd8c9a690e88ac471adfc8 | /MeizuM8/01.HelloWorld/01.HelloWorld.cpp | 0a1e4295802ff0409f2f7db7b13b83cb25de4d33 | [] | no_license | rtmpnewbie/lai3d | 0802dbb5ebe67be2b28d9e8a4d1cc83b4f36b14f | b44c9edfb81fde2b40e180a651793fec7d0e617d | refs/heads/master | 2021-01-10T04:29:07.463289 | 2011-03-22T17:51:24 | 2011-03-22T17:51:24 | 36,842,700 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,808 | cpp | #include "stdafx.h"
/************************************************************************/
/*
* Copyright (C) Meizu Technology Corporation Zhuhai China
* All rights reserved.
* 中国珠海, 魅族科技有限公司, 版权所有.
*
* This file is a part of the Meizu Foundation Classes library.
* Author: Michael
* Create on: 2008-12-1
*/
/************************************************************************/
// The steps for running this sample code:
// Use Visual Studio 2005/2008 to create a smart device project,
// Choose M8SDK,
// Choose empty project,
// Add a sample.cpp file to the project,
// Copy this peace of code into the sample.cpp,
// Now, you can build the project and try to run it in M8 emulator or device.
// include the MZFC library header file
#include <mzfc_inc.h>
// This sample shows in a MZFC application:
// application's creation & initialization,
// window's creation & initialization,
// using button control, and process its command.
// ID of the button in the window
#define MZ_IDC_TESTBTN1 101
// Main window derived from CMzWndEx
class CSample1MainWnd: public CMzWndEx
{
MZ_DECLARE_DYNAMIC(CSample1MainWnd);
public:
// A button control in the window
UiButton m_btn;
protected:
// Initialization of the window (dialog)
virtual BOOL OnInitDialog()
{
// Must all the Init of parent class first!
if (!CMzWndEx::OnInitDialog())
{
return FALSE;
}
// Then init the controls & other things in the window
m_btn.SetButtonType(MZC_BUTTON_GREEN);
m_btn.SetPos(100,250,280,100);
m_btn.SetID(MZ_IDC_TESTBTN1);
m_btn.SetText(L"草泥马之歌");
m_btn.SetTextColor(RGB(255,255,255));
// Add the control into the window.
AddUiWin(&m_btn);
return TRUE;
}
// override the MZFC command handler
virtual void OnMzCommand(WPARAM wParam, LPARAM lParam)
{
UINT_PTR id = LOWORD(wParam);
switch(id)
{
case MZ_IDC_TESTBTN1:
{
if(1 == MzMessageBoxEx(m_hWnd, L"You have pressed Exit button, Really want exit?", L"Exit", MB_YESNO, false))
PostQuitMessage(0);
}
break;
}
}
};
MZ_IMPLEMENT_DYNAMIC(CSample1MainWnd)
// Application class derived from CMzApp
class CSample1App: public CMzApp
{
public:
// The main window of the app.
CSample1MainWnd m_MainWnd;
// Initialization of the application
virtual BOOL Init()
{
// Init the COM relative library.
CoInitializeEx(0, COINIT_MULTITHREADED);
// Create the main window
RECT rcWork = MzGetWorkArea();
m_MainWnd.Create(rcWork.left,rcWork.top,RECT_WIDTH(rcWork),RECT_HEIGHT(rcWork), 0, 0, 0);
m_MainWnd.Show();
// return TRUE means init success.
return TRUE;
}
};
// The global variable of the application.
CSample1App theApp;
| [
"laiyanlin@27d9c402-1b7e-11de-9433-ad2e3fad96c5"
] | [
[
[
1,
108
]
]
] |
d14ebcd6c22bc947ecf1b8c7cfa0822082f812ce | 5218c2a5173e3137f341f99aa0495879b189042a | /Stokes/Core/Exception.cpp | fce6f246f8f3426d2f7e21454a4bc8e560ddef97 | [] | no_license | bungnoid/stokes | cd00ba5d5aeb36da69fb38db69b1d2394853dada | 553abca00a626379ea7fb9f51c206d15ae32d2da | refs/heads/master | 2021-01-10T12:57:12.718405 | 2011-08-15T09:44:30 | 2011-08-15T09:44:30 | 51,467,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 90 | cpp | #include <Stokes/Core/Exception.hpp>
ENTER_NAMESPACE_STOKES
LEAVE_NAMESPACE_STOKES
| [
"[email protected]"
] | [
[
[
1,
5
]
]
] |
15f741ca3a6f2e5a203359a4a8658ba20a57929b | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/PageEditDlg.cpp | c851210fd091bcd8911d0a0461bff5272dad09f5 | [] | no_license | 15831944/AiPI-1 | 2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4 | 9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8 | refs/heads/master | 2021-12-02T20:34:03.136125 | 2011-10-27T00:07:54 | 2011-10-27T00:07:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,755 | cpp | // PageEditDlg.cpp : implementation file
//
#include "stdafx.h"
#include "AIPI.h"
#include "PageEditDlg.h"
#include "InductionTabView.h"
#include "AIPITabView.h"
#include ".\GridCtrl\GridCtrl.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CPageEditDlg dialog
CPageEditDlg::CPageEditDlg(CWnd* pParent /*=NULL*/)
: CDialog(CPageEditDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CPageEditDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CPageEditDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CPageEditDlg)
DDX_Control(pDX, IDC_STATIC_SEPARATOR, m_stcSeparator);
DDX_Control(pDX, IDC_STATIC_MODE, m_stcMode);
DDX_Control(pDX, IDC_BTN_SELECTALL, m_btnSelectAll);
DDX_Control(pDX, IDC_BTN_PASTE, m_btnPaste);
DDX_Control(pDX, IDC_BTN_CUT, m_btnCut);
DDX_Control(pDX, IDC_BTN_COPY, m_btnCopy);
DDX_Control(pDX, IDC_RADIO_READ, m_radioRead);
DDX_Control(pDX, IDC_RADIO_WRITE, m_radioWrite);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CPageEditDlg, CDialog)
//{{AFX_MSG_MAP(CPageEditDlg)
ON_BN_CLICKED(IDC_BTN_COPY, OnBtnCopy)
ON_BN_CLICKED(IDC_BTN_CUT, OnBtnCut)
ON_BN_CLICKED(IDC_BTN_PASTE, OnBtnPaste)
ON_BN_CLICKED(IDC_BTN_SELECTALL, OnBtnSelectAll)
ON_BN_CLICKED(IDC_RADIO_READ, OnRadioRead)
ON_BN_CLICKED(IDC_RADIO_WRITE, OnRadioWrite)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CPageEditDlg message handlers
BOOL CPageEditDlg::OnInitDialog()
{
CDialog::OnInitDialog();
m_radioRead.SetCheck(TRUE);
//m_radioRead.EnableWindow(FALSE);
//m_radioWrite.EnableWindow(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
/*
void CPageEditDlg::SelectGrid()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
switch(pMainFrame->m_CurrentGrid)
{
case GRID_INDUCTION:
m_pGrid = &pMainFrame->m_GridInduction;
break;
case GRID_PM:
m_pGrid = &pMainFrame->m_GridPM;
break;
case GRID_WM:
m_pGrid = &pMainFrame->m_GridWM;
break;
case GRID_AGENDA:
m_pGrid = &pMainFrame->m_GridAgenda;
break;
case GRID_AM:
m_pGrid = &pMainFrame->m_GridAM;
break;
case GRID_BM:
m_pGrid = &pMainFrame->m_GridBM;
break;
case GRID_RETE:
m_pGrid = &pMainFrame->m_GridRETE;
break;
}
}
*/
#ifndef GRIDCONTROL_NO_CLIPBOARD
void CPageEditDlg::OnBtnCopy()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->SelectGrid();
m_pGrid->OnEditCopy();
}
void CPageEditDlg::OnBtnCut()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->SelectGrid();
m_pGrid->OnEditCut();
}
void CPageEditDlg::OnBtnPaste()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->SelectGrid();
m_pGrid->OnEditPaste();
}
void CPageEditDlg::OnUpdateEditCopyOrCut(CCmdUI* pCmdUI)
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->SelectGrid();
pCmdUI->Enable(m_pGrid->GetSelectedCount() > 0);
m_btnCopy.EnableWindow(m_pGrid->GetSelectedCount() > 0);
m_btnCut.EnableWindow(m_pGrid->GetSelectedCount() > 0);
}
void CPageEditDlg::OnUpdateEditPaste(CCmdUI* pCmdUI)
{
// Attach a COleDataObject to the clipboard see if there is any data
COleDataObject obj;
pCmdUI->Enable(obj.AttachClipboard() && obj.IsDataAvailable(CF_TEXT));
m_btnPaste.EnableWindow(obj.AttachClipboard() && obj.IsDataAvailable(CF_TEXT));
}
#endif
void CPageEditDlg::OnBtnSelectAll()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->SelectGrid();
m_pGrid->OnEditSelectAll();
}
void CPageEditDlg::OnRadioRead()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
COLORREF clr = RGB(255, 255, 220);
int currentGrid= pMainFrame->SelectGrid();
m_pGrid->SetEditable(FALSE);
switch(currentGrid)
{
case GRID_PM:
pMainFrame->ChangeGridVarState(_T("EditablePM"), false);
break;
case GRID_WM:
pMainFrame->ChangeGridVarState(_T("EditableWM"), false);
break;
case GRID_AGENDA:
pMainFrame->ChangeGridVarState(_T("EditableAgenda"), false);
break;
case GRID_AM:
pMainFrame->ChangeGridVarState(_T("EditableAM"), false);
break;
case GRID_BM:
pMainFrame->ChangeGridVarState(_T("EditableBM"), false);
break;
case GRID_BM_TK:
pMainFrame->ChangeGridVarState(_T("EditableBM_TK"), false);
break;
case GRID_RETE:
pMainFrame->ChangeGridVarState(_T("EditableRETE"), false);
break;
case GRID_INDUCTION:
pMainFrame->ChangeGridVarState(_T("EditableInduction"), false);
break;
}//end switch
for (int row = m_pGrid->GetFixedRowCount(); row < m_pGrid->GetRowCount(); row++)
{
for (int col = m_pGrid->GetFixedColumnCount(); col < m_pGrid->GetColumnCount(); col++)
{
m_pGrid->SetItemBkColour(row, col, clr);
//m_pGrid->SetItemFgColour(row, col, RGB(0,0,0));
}
}
m_pGrid->Invalidate();
}
void CPageEditDlg::OnRadioWrite()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
COLORREF clr = RGB(255, 255, 255);
int f = NOT_FOUND;
int currentGrid = pMainFrame->SelectGrid();
m_pGrid->SetEditable(TRUE);
switch(currentGrid)
{
case GRID_PM:
pMainFrame->ChangeGridVarState(_T("EditablePM"), true);
break;
case GRID_WM:
pMainFrame->ChangeGridVarState(_T("EditableWM"), true);
break;
case GRID_AGENDA:
pMainFrame->ChangeGridVarState(_T("EditableAgenda"), true);
break;
case GRID_AM:
pMainFrame->ChangeGridVarState(_T("EditableAM"), true);
break;
case GRID_BM:
pMainFrame->ChangeGridVarState(_T("EditableBM"), true);
break;
case GRID_BM_TK:
pMainFrame->ChangeGridVarState(_T("EditableBM_TK"), true);
break;
case GRID_RETE:
pMainFrame->ChangeGridVarState(_T("EditableRETE"), true);
break;
case GRID_INDUCTION:
pMainFrame->ChangeGridVarState(_T("EditableInduction"), true);
break;
}//end switch
for (int row = m_pGrid->GetFixedRowCount(); row < m_pGrid->GetRowCount(); row++)
{
for (int col = m_pGrid->GetFixedColumnCount(); col < m_pGrid->GetColumnCount(); col++)
{
m_pGrid->SetItemBkColour(row, col, clr);
//m_pGrid->SetItemFgColour(row, col, RGB(0,0,0));
}
}
m_pGrid->Invalidate();
}
| [
"[email protected]"
] | [
[
[
1,
274
]
]
] |
08e2549340c10ccc1ffbda4e35dd5a802c0bf05a | 1960e1ee431d2cfd2f8ed5715a1112f665b258e3 | /src/writeread.cpp | 92fd457fc22a01b3f1c8b1e554e78f7a79c93b20 | [] | no_license | BackupTheBerlios/bvr20983 | c26a1379b0a62e1c09d1428525f3b4940d5bb1a7 | b32e92c866c294637785862e0ff9c491705c62a5 | refs/heads/master | 2021-01-01T16:12:42.021350 | 2009-11-01T22:38:40 | 2009-11-01T22:38:40 | 39,518,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,817 | cpp | //+===================================================================
//
// To build:
// cl /GX WriteRead.cpp
//
//+===================================================================
#define WIN32_LEAN_AND_MEAN
#define UNICODE
#define _UNICODE
#include <stdio.h>
#include <windows.h>
#include <ole2.h>
// Implicitly link ole32.dll
#pragma comment( lib, "ole32.lib" )
// From uuidgen.exe:
const FMTID fmtid = { /* d170df2e-1117-11d2-aa01-00805ffe11b8 */
0xd170df2e,
0x1117,
0x11d2,
{0xaa, 0x01, 0x00, 0x80, 0x5f, 0xfe, 0x11, 0xb8}
};
EXTERN_C void wmain()
{
HRESULT hr = S_OK;
IPropertySetStorage *pPropSetStg = NULL;
IPropertyStorage *pPropStg = NULL;
WCHAR *pwszError = L"";
PROPSPEC propspec;
PROPVARIANT propvarWrite;
PROPVARIANT propvarRead;
try
{
// Create a file and a property set within it.
hr = StgCreateStorageEx( L"WriteRead.stg",
STGM_CREATE|STGM_SHARE_EXCLUSIVE|STGM_READWRITE,
STGFMT_STORAGE,
// STGFMT_STORAGE => Structured Storage
// property sets
// STGFMT_FILE => NTFS file system
// property sets
0, NULL, NULL,
IID_IPropertySetStorage,
reinterpret_cast<void**>(&pPropSetStg) );
if( FAILED(hr) ) throw L"Failed StgCreateStorageEx";
hr = pPropSetStg->Create( fmtid, NULL, PROPSETFLAG_DEFAULT,
STGM_CREATE|STGM_READWRITE|STGM_SHARE_EXCLUSIVE,
&pPropStg );
if( FAILED(hr) ) throw L"Failed IPropertySetStorage::Create";
// Write a Unicode string property to the property set
propspec.ulKind = PRSPEC_LPWSTR;
propspec.lpwstr = L"Property Name";
propvarWrite.vt = VT_LPWSTR;
propvarWrite.pwszVal = L"Property Value";
hr = pPropStg->WriteMultiple( 1, &propspec, &propvarWrite,
PID_FIRST_USABLE );
if( FAILED(hr) )
throw L"Failed IPropertyStorage::WriteMultiple";
// Not required, but give the property set a friendly
// name.
PROPID propidDictionary = PID_DICTIONARY;
WCHAR *pwszFriendlyName =
L"Write/Read Properties Sample Property Set";
hr = pPropStg->WritePropertyNames( 1, &propidDictionary,
&pwszFriendlyName );
if( FAILED(hr) )
throw L"Failed IPropertyStorage::WritePropertyNames";
// Commit changes to the property set.
hr = pPropStg->Commit(STGC_DEFAULT);
if( FAILED(hr) )
throw L"Failed IPropertyStorage::Commit";
// Close and reopen everything.
// By using the STGFMT_ANY flag in the StgOpenStorageEx call,
// it does not matter if this is a Structured Storage
// property set or an NTFS file system property set
// (for more information see the StgCreateStorageEx
// call above).
pPropStg->Release(); pPropStg = NULL;
pPropSetStg->Release(); pPropSetStg = NULL;
hr = StgOpenStorageEx( L"WriteRead.stg",
STGM_READ|STGM_SHARE_DENY_WRITE,
STGFMT_ANY,
0, NULL, NULL,
IID_IPropertySetStorage,
reinterpret_cast<void**>(&pPropSetStg) );
if( FAILED(hr) )
throw L"Failed StgOpenStorageEx";
hr = pPropSetStg->Open( fmtid, STGM_READ|STGM_SHARE_EXCLUSIVE,
&pPropStg );
if( FAILED(hr) )
throw L"Failed IPropertySetStorage::Open";
// Read the property back and validate it
hr = pPropStg->ReadMultiple( 1, &propspec, &propvarRead );
if( FAILED(hr) )
throw L"Failed IPropertyStorage::ReadMultiple";
if( S_FALSE == hr )
throw L"Property didn't exist after reopening the property set";
else if( propvarWrite.vt != propvarRead.vt )
throw L"Property types didn't match after reopening the property set";
else if( 0 != wcscmp( propvarWrite.pwszVal, propvarRead.pwszVal ))
throw L"Property values didn't match after reopening the property set";
else
wprintf( L"Success\n" );
}
catch( const WCHAR *pwszError )
{
wprintf( L"Error: %s (hr=%08x)\n", pwszError, hr );
}
PropVariantClear( &propvarRead );
if( pPropStg ) pPropStg->Release();
if( pPropSetStg ) pPropSetStg->Release();
} | [
"dwachmann@01137330-e44e-0410-aa50-acf51430b3d2"
] | [
[
[
1,
141
]
]
] |
6fa6c42a16d48ffaab26bd6ddf6ba3b346f6ae6e | 0ee189afe953dc99825f55232cd52b94d2884a85 | /mstd/access.hpp | 89ebff7d4dbb8170b1ea7892c0d10773114a88ac | [] | no_license | spolitov/lib | fed99fa046b84b575acc61919d4ef301daeed857 | 7dee91505a37a739c8568fdc597eebf1b3796cf9 | refs/heads/master | 2016-09-11T02:04:49.852151 | 2011-08-11T18:00:44 | 2011-08-11T18:00:44 | 2,192,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,793 | hpp | #pragma once
#include <boost/noncopyable.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>
namespace mstd {
namespace detail {
template<class Mutex>
class nolock {
public:
explicit nolock(Mutex & mutex) {}
bool owns_lock() const { return true; }
};
}
template<class T, template<class M> class Lock, class Ret>
class access_base;
template<class T>
class access_source : public boost::noncopyable {
public:
explicit access_source(T & t, boost::shared_mutex & mutex)
: t_(&t), mutex_(mutex) {}
private:
T * t_;
boost::shared_mutex & mutex_;
template<class T, template<class M> class Lock, class Ret>
friend class access_base;
};
template<class T, bool writable>
class access_source_ref {
public:
explicit access_source_ref(const access_source<T> & source)
: source_(&source) {}
access_source_ref(const access_source_ref<T, true> & ref)
: source_(&ref.source()) {}
const access_source<T> & source() const
{
return *source_;
}
private:
const access_source<T> * source_;
};
template<class T, template<class M> class Lock, class Ret>
class access_base {
public:
template<bool w>
explicit access_base(const access_source_ref<T, w> & ref)
: lock_(ref.source().mutex_), t_(ref.source().t_) {}
Ret & get() const
{
BOOST_ASSERT(lock_.owns_lock());
return *t_;
}
Ret * operator->() const
{
BOOST_ASSERT(lock_.owns_lock());
return t_;
}
void unlock()
{
lock_.unlock();
}
private:
Lock<boost::shared_mutex> lock_;
Ret * t_;
};
template<class T>
class access_nolock : public access_base<T, detail::nolock, const T> {
public:
template<bool w>
explicit access_nolock(const access_source_ref<T, w> & ref)
: access_base(ref)
{
}
};
template<class T>
class access_read : public access_base<T, boost::shared_lock, const T> {
public:
template<bool w>
explicit access_read(const access_source_ref<T, w> & ref)
: access_base(ref)
{
}
};
template<class T>
class access_write : public access_base<T, boost::unique_lock, T> {
public:
explicit access_write(const access_source_ref<T, true> & ref)
: access_base(ref)
{
}
};
template<class T, bool w>
access_nolock<T> nolock(const access_source_ref<T, w> & ref)
{
return access_nolock<T>(ref);
}
template<class T, bool w>
access_read<T> read(const access_source_ref<T, w> & ref)
{
return access_read<T>(ref);
}
template<class T>
access_write<T> write(const access_source_ref<T, true> & ref)
{
return access_write<T>(ref);
}
}
| [
"[email protected]"
] | [
[
[
1,
128
]
]
] |
d6be23a2fdf3d6d090fbf11041dbd6bf80c5843b | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/Plugins/Plugin_AwesomiumWidget/KeyboardHook.cpp | dfef3d60ad185ec0bd66b543f11c7a49a058ea52 | [] | no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,559 | cpp | /*
This file is part of NaviLibrary, a library that allows developers to create and
interact with web-content as an overlay or material in Ogre3D applications.
Copyright (C) 2009 Adam J. Simmons
http://princeofcode.com/navilibrary.php
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "KeyboardHook.h"
//using namespace NaviLibrary::Impl;
LRESULT CALLBACK GetMessageProc(int nCode, WPARAM wParam, LPARAM lParam);
KeyboardHook* KeyboardHook::instance = 0;
KeyboardHook::KeyboardHook(HookListener* listener) : listener(listener)
{
instance = this;
HINSTANCE hInstance = GetModuleHandle(0);
getMsgHook = SetWindowsHookEx(WH_GETMESSAGE, GetMessageProc, hInstance, GetCurrentThreadId());
}
KeyboardHook::~KeyboardHook()
{
UnhookWindowsHookEx(getMsgHook);
instance = 0;
}
void KeyboardHook::handleHook(UINT msg, HWND hwnd, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_KEYDOWN:
case WM_KEYUP:
case WM_CHAR:
case WM_DEADCHAR:
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
case WM_SYSDEADCHAR:
case WM_SYSCHAR:
case WM_IME_CHAR:
case WM_IME_COMPOSITION:
case WM_IME_COMPOSITIONFULL:
case WM_IME_CONTROL:
case WM_IME_ENDCOMPOSITION:
case WM_IME_KEYDOWN:
case WM_IME_KEYUP:
case WM_IME_NOTIFY:
case WM_IME_REQUEST:
case WM_IME_SELECT:
case WM_IME_SETCONTEXT:
case WM_IME_STARTCOMPOSITION:
case WM_HELP:
case WM_CANCELMODE:
{
if (listener)
listener->handleKeyMessage(hwnd, msg, wParam, lParam);
break;
}
}
}
LRESULT CALLBACK GetMessageProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode == HC_ACTION)
{
MSG* msg = (MSG*)lParam;
if (wParam & PM_REMOVE)
KeyboardHook::instance->handleHook(msg->message, msg->hwnd, msg->wParam, msg->lParam);
}
return CallNextHookEx(KeyboardHook::instance->getMsgHook, nCode, wParam, lParam);
}
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
] | [
[
[
1,
92
]
]
] |
39f3c0ac8068d62b675a92319a36cc508bdf0ad4 | 81a3611bfa4e9022e1194295a8f314bafa744f69 | /grass-20100203/src/DLGLexer.h | 2bda95ef58ab1f6ff03633b846fcdff620a94dda | [] | no_license | ominux/sjtuedaacgrass | 65c02f6a1db52e8194157fd1622b73124220a27c | 463b1926b1eddcc06ff2253b3077aad1bca7e37b | refs/heads/master | 2016-09-15T16:14:00.747072 | 2010-05-18T13:20:08 | 2010-05-18T13:20:08 | 32,243,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,932 | h | #ifndef DLGLexer_h
#define DLGLexer_h
/*
* D L G L e x e r C l a s s D e f i n i t i o n
*
* Generated from: parser.dlg
*
* 1989-2001 by Will Cohen, Terence Parr, and Hank Dietz
* Purdue University Electrical Engineering
* DLG Version 1.33MR33
*/
#include "DLexerBase.h"
class DLGLexer : public DLGLexerBase {
public:
public:
static const int MAX_MODE;
static const int DfaStates;
static const int START;
static const int PAR_STATE;
static const int NORMAL;
typedef unsigned short DfaState;
DLGLexer(DLGInputStream *in,
unsigned bufsize=2000)
: DLGLexerBase(in, bufsize, 1)
{
;
}
void mode(int);
ANTLRTokenType nextTokenType(void);
void advance(void);
protected:
ANTLRTokenType act1();
ANTLRTokenType act2();
ANTLRTokenType act3();
ANTLRTokenType act4();
ANTLRTokenType act5();
ANTLRTokenType act6();
ANTLRTokenType act7();
ANTLRTokenType act8();
ANTLRTokenType act9();
ANTLRTokenType act10();
ANTLRTokenType act11();
ANTLRTokenType act12();
ANTLRTokenType act13();
ANTLRTokenType act14();
ANTLRTokenType act15();
ANTLRTokenType act16();
ANTLRTokenType act17();
ANTLRTokenType act18();
ANTLRTokenType act19();
ANTLRTokenType act20();
ANTLRTokenType act21();
ANTLRTokenType act22();
ANTLRTokenType act23();
ANTLRTokenType act24();
ANTLRTokenType act25();
ANTLRTokenType act26();
ANTLRTokenType act27();
ANTLRTokenType act28();
ANTLRTokenType act29();
ANTLRTokenType act30();
ANTLRTokenType act31();
ANTLRTokenType act32();
ANTLRTokenType act33();
ANTLRTokenType act34();
ANTLRTokenType act35();
ANTLRTokenType act36();
ANTLRTokenType act37();
ANTLRTokenType act38();
ANTLRTokenType act39();
ANTLRTokenType act40();
ANTLRTokenType act41();
ANTLRTokenType act42();
ANTLRTokenType act43();
ANTLRTokenType act44();
ANTLRTokenType act45();
ANTLRTokenType act46();
ANTLRTokenType act47();
ANTLRTokenType act48();
ANTLRTokenType act49();
ANTLRTokenType act50();
ANTLRTokenType act51();
ANTLRTokenType act52();
ANTLRTokenType act53();
ANTLRTokenType act54();
ANTLRTokenType act55();
ANTLRTokenType act56();
ANTLRTokenType act57();
ANTLRTokenType act58();
ANTLRTokenType act59();
ANTLRTokenType act60();
ANTLRTokenType act61();
ANTLRTokenType act62();
ANTLRTokenType act63();
ANTLRTokenType act64();
ANTLRTokenType act65();
ANTLRTokenType act66();
ANTLRTokenType act67();
ANTLRTokenType act68();
ANTLRTokenType act69();
ANTLRTokenType act70();
ANTLRTokenType act71();
ANTLRTokenType act72();
ANTLRTokenType act73();
ANTLRTokenType act74();
ANTLRTokenType act75();
ANTLRTokenType act76();
ANTLRTokenType act77();
ANTLRTokenType act78();
ANTLRTokenType act79();
static DfaState st0[3];
static DfaState st1[3];
static DfaState st2[3];
static DfaState st3[34];
static DfaState st4[34];
static DfaState st5[34];
static DfaState st6[34];
static DfaState st7[34];
static DfaState st8[34];
static DfaState st9[34];
static DfaState st10[34];
static DfaState st11[34];
static DfaState st12[34];
static DfaState st13[34];
static DfaState st14[34];
static DfaState st15[34];
static DfaState st16[34];
static DfaState st17[34];
static DfaState st18[34];
static DfaState st19[34];
static DfaState st20[34];
static DfaState st21[34];
static DfaState st22[34];
static DfaState st23[34];
static DfaState st24[34];
static DfaState st25[34];
static DfaState st26[34];
static DfaState st27[34];
static DfaState st28[34];
static DfaState st29[34];
static DfaState st30[34];
static DfaState st31[34];
static DfaState st32[34];
static DfaState st33[34];
static DfaState st34[34];
static DfaState st35[34];
static DfaState st36[34];
static DfaState st37[34];
static DfaState st38[34];
static DfaState st39[34];
static DfaState st40[34];
static DfaState st41[34];
static DfaState st42[34];
static DfaState st43[34];
static DfaState st44[34];
static DfaState st45[34];
static DfaState st46[34];
static DfaState st47[34];
static DfaState st48[34];
static DfaState st49[34];
static DfaState st50[34];
static DfaState st51[34];
static DfaState st52[34];
static DfaState st53[34];
static DfaState st54[34];
static DfaState st55[34];
static DfaState st56[34];
static DfaState st57[34];
static DfaState st58[34];
static DfaState st59[34];
static DfaState st60[34];
static DfaState st61[34];
static DfaState st62[57];
static DfaState st63[57];
static DfaState st64[57];
static DfaState st65[57];
static DfaState st66[57];
static DfaState st67[57];
static DfaState st68[57];
static DfaState st69[57];
static DfaState st70[57];
static DfaState st71[57];
static DfaState st72[57];
static DfaState st73[57];
static DfaState st74[57];
static DfaState st75[57];
static DfaState st76[57];
static DfaState st77[57];
static DfaState st78[57];
static DfaState st79[57];
static DfaState st80[57];
static DfaState st81[57];
static DfaState st82[57];
static DfaState st83[57];
static DfaState st84[57];
static DfaState st85[57];
static DfaState st86[57];
static DfaState st87[57];
static DfaState st88[57];
static DfaState st89[57];
static DfaState st90[57];
static DfaState st91[57];
static DfaState st92[57];
static DfaState st93[57];
static DfaState st94[57];
static DfaState st95[57];
static DfaState st96[57];
static DfaState st97[57];
static DfaState st98[57];
static DfaState st99[57];
static DfaState st100[57];
static DfaState st101[57];
static DfaState st102[57];
static DfaState st103[57];
static DfaState st104[57];
static DfaState st105[57];
static DfaState st106[57];
static DfaState st107[57];
static DfaState st108[57];
static DfaState st109[57];
static DfaState st110[57];
static DfaState st111[57];
static DfaState st112[57];
static DfaState st113[57];
static DfaState st114[57];
static DfaState st115[57];
static DfaState st116[57];
static DfaState st117[57];
static DfaState st118[57];
static DfaState st119[57];
static DfaState st120[57];
static DfaState st121[57];
static DfaState st122[57];
static DfaState st123[57];
static DfaState st124[57];
static DfaState st125[57];
static DfaState st126[57];
static DfaState st127[57];
static DfaState st128[57];
static DfaState st129[57];
static DfaState st130[57];
static DfaState st131[57];
static DfaState st132[57];
static DfaState st133[57];
static DfaState st134[57];
static DfaState st135[57];
static DfaState st136[57];
static DfaState st137[57];
static DfaState st138[57];
static DfaState st139[57];
static DfaState st140[57];
static DfaState st141[57];
static DfaState st142[57];
static DfaState st143[57];
static DfaState st144[57];
static DfaState st145[57];
static DfaState st146[57];
static DfaState st147[57];
static DfaState st148[57];
static DfaState st149[57];
static DfaState st150[57];
static DfaState st151[57];
static DfaState st152[57];
static DfaState st153[57];
static DfaState st154[57];
static DfaState st155[57];
static DfaState st156[57];
static DfaState st157[57];
static DfaState st158[57];
static DfaState st159[57];
static DfaState st160[57];
static DfaState st161[57];
static DfaState st162[57];
static DfaState st163[57];
static DfaState st164[57];
static DfaState st165[57];
static DfaState st166[57];
static DfaState st167[57];
static DfaState st168[57];
static DfaState st169[57];
static DfaState st170[57];
static DfaState st171[57];
static DfaState st172[57];
static DfaState st173[57];
static DfaState st174[57];
static DfaState st175[57];
static DfaState st176[57];
static DfaState st177[57];
static DfaState st178[57];
static DfaState st179[57];
static DfaState st180[57];
static DfaState st181[57];
static DfaState st182[57];
static DfaState st183[57];
static DfaState st184[57];
static DfaState st185[57];
static DfaState st186[57];
static DfaState st187[57];
static DfaState st188[57];
static DfaState st189[57];
static DfaState st190[57];
static DfaState st191[57];
static DfaState st192[57];
static DfaState st193[57];
static DfaState st194[57];
static DfaState st195[57];
static DfaState st196[57];
static DfaState st197[57];
static DfaState st198[57];
static DfaState st199[57];
static DfaState st200[57];
static DfaState st201[57];
static DfaState st202[57];
static DfaState st203[57];
static DfaState st204[57];
static DfaState st205[57];
static DfaState st206[57];
static DfaState st207[57];
static DfaState st208[57];
static DfaState st209[57];
static DfaState st210[57];
static DfaState st211[57];
static DfaState st212[57];
static DfaState st213[57];
static DfaState st214[57];
static DfaState st215[57];
static DfaState st216[57];
static DfaState st217[57];
static DfaState st218[57];
static DfaState st219[57];
static DfaState st220[57];
static DfaState st221[57];
static DfaState st222[57];
static DfaState st223[57];
static DfaState st224[57];
static DfaState st225[57];
static DfaState st226[57];
static DfaState st227[57];
static DfaState st228[57];
static DfaState *dfa[229];
static DfaState dfa_base[];
static unsigned char *b_class_no[];
static DfaState accepts[230];
static DLGChar alternatives[230];
static ANTLRTokenType (DLGLexer::*actions[80])();
static unsigned char shift0[257];
static unsigned char shift1[257];
static unsigned char shift2[257];
int ZZSHIFT(int c) { return b_class_no[automaton][1+c]; }
//
// 133MR1 Deprecated feature to allow inclusion of user-defined code in DLG class header
//
#ifdef DLGLexerIncludeFile
#include DLGLexerIncludeFile
#endif
};
typedef ANTLRTokenType (DLGLexer::*PtrDLGLexerMemberFunc)();
#endif
| [
"wontian@ecd5914e-0e2d-11df-9afa-8babb764c599"
] | [
[
[
1,
362
]
]
] |
6a6e55fa0c7f2c786601e67e2d790157eede0cb5 | 03d1f3dd8c9284b93890648d65a1589276ef505f | /VisualSPH/Render/gMetaballs.h | d8da71f45f374970bc1b975aec7d3162b7db495e | [] | no_license | shadercoder/photonray | 18271358ca7f20a3c4a6326164d292774bfc3f53 | e0bbad33bc9c03e094036748f965100023aa0287 | refs/heads/master | 2021-01-10T04:20:14.592834 | 2011-05-07T21:09:43 | 2011-05-07T21:09:43 | 45,577,179 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,957 | h | #pragma once
#include <vector>
#include "GObject.h"
#include "gQuad.h"
#include "DenseField.h"
#include "Particle.h"
#include <algorithm>
#include "tbb/tbb.h"
#include "tbb/parallel_for.h"
#include "tbb/blocked_range.h"
using namespace tbb;
using namespace std;
class CalcField
{
private:
DenseField* field;
const Particle* particles;
float metaballsSize;
float scale;
const float threadshold;
inline static float calcMetaball(const D3DXVECTOR3& centerBall, const D3DXVECTOR3& cell, const float threadshold)
{
D3DXVECTOR3 tmp = centerBall - cell;
//float len = pow(tmp.x, 2) + pow(tmp.y, 2) + pow(tmp.z, 2);
float len = D3DXVec3Dot(&tmp, &tmp);
if (len > threadshold) {
return 0.0f;
}
float res = powf(threadshold / (len + 1e-5f), 4.0f);
return res;
}
public:
CalcField(DenseField* field, const Particle* particles, float metaballsSize, float scale)
:threadshold(metaballsSize * metaballsSize)
{
this->field = field;
this->particles = particles;
this->metaballsSize = metaballsSize;
this->scale = scale;
}
void operator()(const blocked_range<size_t>& r) const
{
float* fieldData = (float*) field->getData();
for (size_t i = r.begin(); i != r.end(); ++i)
{
int x = (int) floor(particles[i].position.x * scale);
int y = (int) floor(particles[i].position.y * scale);
int z = (int) floor(particles[i].position.z * scale);
for (int dz = (int) -metaballsSize; dz <= (int) metaballsSize; ++dz)
{
for (int dx = (int) -metaballsSize; dx <= (int) metaballsSize; ++dx)
{
for (int dy = (int) -metaballsSize; dy <= (int) metaballsSize; ++dy)
{
D3DXVECTOR3 cell((float) (x + dx), (float) (y + dy), (float) (z + dz));
if(field->isInside(x + dx, y + dy, z + dz))
{
//field->lvalue(x + dx, y + dy, z + dz) += calcMetaball(particles[i].position * scale, cell, threadshold);
fieldData[field->arrayIndexFromCoordinate(x + dx, y + dy, z + dz)] += calcMetaball(particles[i].position * scale, cell, threadshold);
}
}
}
}
}
}
};
struct VS_CONSTANT_BUFFER
{
D3DXMATRIX mWorldViewProj; //mWorldViewProj will probably be global to all shaders in a project.
};
class gMetaballs : public GObject
{
private:
ID3D10VertexShader* pVertexShader;
ID3D10InputLayout* pVertexLayout;
ID3D10PixelShader* pPixelShader;
ID3D10Buffer* mCB;
ID3D10BlendState* pBlendState;
ID3D10RasterizerState* pRasterizerStateBack;
ID3D10RasterizerState* pRasterizerStateFront;
ID3D10DepthStencilState* pDepthStencilState;
ID3D10Texture2D* pBackGroundS;
ID3D10RenderTargetView* pBackGroundSView;
ID3D10ShaderResourceView* pBackGroundSRV;
ID3D10Texture2D* pFrontS;
ID3D10RenderTargetView* pFrontSView;
ID3D10Texture2D* pBackS;
ID3D10RenderTargetView* pBackSView;
ID3D10ShaderResourceView* pFrontSRV;
ID3D10ShaderResourceView* pBackSRV;
ID3D10Texture3D* pVolume;
ID3D10ShaderResourceView* volumeSRV;
ID3D10Texture2D* pNoise;
ID3D10ShaderResourceView* pNoiseSRV;
ID3D10RenderTargetView* pRenderTargetView;
ID3D10Texture2D* pDepthStencilBuffer;
ID3D10DepthStencilView* pDepthStencilView;
UINT screenWidth;
UINT screenHeight;
UINT volumeResolution;
gQuad quad;
DenseField field;
float scale;
float metaballsSize;
HRESULT onCreate();
HRESULT createTexture2D();
HRESULT createTexture3D();
void drawBox();
float calcMetaball(D3DXVECTOR3 centerBall, D3DXVECTOR3 cell);
public:
UINT mNumMetaballs;
void updateVolume(const vector<Particle>& particles, int numParticles, float scale, float metaballsSize);
void draw();
void onFrameMove(D3DXMATRIX& mWorldViewProj);
void onFrameResize(int width, int height);
void init(ID3D10Device* device, int _screenWidth, int _screenHeight, int _volumeResolution);
gMetaballs(void);
~gMetaballs(void);
};
| [
"ilyakrukov@f2d442f5-4fb6-3e1e-f2a6-32ff9b5dcf3a",
"IlyaKrukov@f2d442f5-4fb6-3e1e-f2a6-32ff9b5dcf3a"
] | [
[
[
1,
23
],
[
25,
58
],
[
60,
90
],
[
95,
137
]
],
[
[
24,
24
],
[
59,
59
],
[
91,
94
]
]
] |
711d4d60a8808fbbff69d586ae30445afa5cf8de | da49fe5fb9fc91dba1f0236411de3021e1e25348 | /BaczekKPAI.cpp | 37bdceea68087231d38f13a03c08df09d1345339 | [] | no_license | imbaczek/baczek-kpai | 7f84d83ba395c2e5b5d85c10c14072049b4830ab | 4291ec37f49fc8cb4a643133ed5f3024264e1e27 | refs/heads/master | 2020-03-28T19:13:42.841144 | 2009-10-29T21:39:02 | 2009-10-29T21:39:02 | 151,447 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,412 | cpp | // BaczekKPAI.cpp: implementation of the BaczekKPAI class.
//
////////////////////////////////////////////////////////////////////////////////
// system includes
#include <fstream>
#include <stdlib.h>
#include <cassert>
#include <iterator>
#include <sstream>
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
#include <boost/timer.hpp>
#include <boost/shared_ptr.hpp>
// AI interface/Spring includes
#include "AIExport.h"
#include "ExternalAI/IGlobalAICallback.h"
#include "ExternalAI/IAICheats.h"
#include "Sim/MoveTypes/MoveInfo.h"
#include "Sim/Units/UnitDef.h"
#include "Sim/Features/FeatureDef.h"
#include "CUtils/Util.h" // we only use the defines
// project includes
#include "BaczekKPAI.h"
#include "Unit.h"
#include "GUI/StatusFrame.h"
#include "Log.h"
#include "InfluenceMap.h"
#include "PythonScripting.h"
#include "RNG.h"
namespace fs = boost::filesystem;
////////////////////////////////////////////////////////////////////////////////
// Version, globals and static members
////////////////////////////////////////////////////////////////////////////////
boost::shared_ptr<Log> ailog;
const char BaczekKPAI::AI_NAME[] = "Baczek's KP AI";
const char BaczekKPAI::AI_VERSION[] = "1.2";
////////////////////////////////////////////////////////////////////////////////
// Construction/Destruction
////////////////////////////////////////////////////////////////////////////////
BaczekKPAI::BaczekKPAI()
{
statusName = 0;
influence = 0;
python = 0;
toplevel = 0;
for (int i = 0; i<MAX_UNITS; ++i)
unitTable[i] = 0;
debugLines = false;
debugMsgs = false;
}
BaczekKPAI::~BaczekKPAI()
{
ailog->info() << "Shutting down." << endl;
ailog->close();
// order of deletion matters
delete toplevel; toplevel = 0; // <- this should delete all child groups
delete python; python = 0;
delete influence; influence = 0;
free((void*)statusName); statusName = 0;
}
////////////////////////////////////////////////////////////////////////////////
// AI Event functions
////////////////////////////////////////////////////////////////////////////////
void BaczekKPAI::InitAI(IGlobalAICallback* callback, int team)
{
init_rng();
this->callback=callback;
cb = callback->GetAICallback();
cheatcb = callback->GetCheatInterface();
cheatcb->EnableCheatEvents(true);
datadir = aiexport_getDataDir(true, "");
std::string dd(datadir);
cb->SendTextMsg(AI_NAME, 0);
cb->SendTextMsg(AI_VERSION, 0);
cb->SendTextMsg("AI data directory:", 0);
cb->SendTextMsg(datadir, 0);
if (!ailog) {
ailog.reset(new Log(callback));
std::stringstream ss;
ss << dd << "/log.txt";
std::string logname = ss.str();
ailog->open(logname.c_str());
ailog->info() << "Logging initialized.\n";
ailog->info() << "Baczek KP AI compiled on " __TIMESTAMP__ "\n";
ailog->info() << AI_NAME << " " << AI_VERSION << std::endl;
ss.clear();
}
InitializeUnitDefs();
std::stringstream ss;
ss << dd << "status" << team << ".txt";
std::string logname = ss.str();
statusName = strdup(logname.c_str());
map.h = cb->GetMapHeight();
map.w = cb->GetMapWidth();
map.squareSize = SQUARE_SIZE;
float3::maxxpos = map.w * SQUARE_SIZE;
float3::maxzpos = map.h * SQUARE_SIZE;
ailog->info() << "Map size: " << float3::maxxpos << "x" << float3::maxzpos << std::endl;
FindGeovents();
std::string influence_conf = dd+"influence.json";
if (!fs::is_regular_file(fs::path(influence_conf))) {
InfluenceMap::WriteDefaultJSONConfig(influence_conf);
}
influence = new InfluenceMap(this, influence_conf);
PythonScripting::RegisterAI(team, this);
python = new PythonScripting(team, datadir);
debugLines = python->GetIntValue("debugDrawLines", false);
debugMsgs = python->GetIntValue("debugMessages", false);
toplevel = new TopLevelAI(this);
assert(randfloat() != randfloat() || randfloat() != randfloat());
#ifdef USE_STATUS_WINDOW
int argc = 1;
static char *argv[] = {"SkirmishAI.dll"};
wxEntry(argc, argv);
// Create the main application window
frame = new MyFrame(_T("Drawing sample"),
wxPoint(50, 50), wxSize(550, 340));
// Show it and tell the application that it's our main window
frame->Show(true);
#endif
}
void BaczekKPAI::UnitCreated(int unit, int builder)
{
ailog->info() << "unit created: " << unit << " by " << builder << std::endl;
SendTextMsg("unit created", 0);
myUnits.insert(unit);
assert(!unitTable[unit]);
unitTable[unit] = new Unit(this, unit);
// TODO chain builder and goal
if (unitTable[unit]->is_expansion)
toplevel->HandleExpansionCommands(unitTable[unit]);
else if (unitTable[unit]->is_base)
toplevel->HandleBaseStartCommands(unitTable[unit]);
}
void BaczekKPAI::UnitFinished(int unit)
{
ailog->info() << "unit finished: " << unit << std::endl;
assert(unitTable[unit]);
unitTable[unit]->complete();
toplevel->UnitFinished(unitTable[unit]);
toplevel->AssignUnitToGroup(unitTable[unit]);
}
void BaczekKPAI::UnitDestroyed(int unit,int attacker)
{
float3 pos = cb->GetUnitPos(unit);
ailog->info() << "unit destroyed: " << unit << " at " << pos << std::endl;
myUnits.erase(unit);
assert(unitTable[unit]);
Unit* tmp = unitTable[unit];
unitTable[unit] = 0;
tmp->destroy(attacker);
delete tmp;
}
void BaczekKPAI::EnemyEnterLOS(int enemy)
{
losEnemies.insert(enemy);
}
void BaczekKPAI::EnemyLeaveLOS(int enemy)
{
losEnemies.erase(enemy);
}
void BaczekKPAI::EnemyEnterRadar(int enemy)
{
}
void BaczekKPAI::EnemyLeaveRadar(int enemy)
{
}
void BaczekKPAI::EnemyDamaged(int damaged, int attacker, float damage,
float3 dir)
{
}
void BaczekKPAI::EnemyDestroyed(int enemy,int attacker)
{
SendTextMsg("enemy destroyed", 0);
losEnemies.erase(enemy);
allEnemies.erase(find(allEnemies.begin(), allEnemies.end(), enemy));
Unit* unit = GetUnit(attacker);
toplevel->EnemyDestroyed(enemy, unit);
}
void BaczekKPAI::UnitIdle(int unit)
{
Unit* u = GetUnit(unit);
assert(u);
ailog->info() << "unit idle " << unit << std::endl;
u->last_idle_frame = cb->GetCurrentFrame();
toplevel->UnitIdle(u);
}
void BaczekKPAI::GotChatMsg(const char* msg,int player)
{
}
void BaczekKPAI::UnitDamaged(int damaged,int attacker,float damage,float3 dir)
{
toplevel->UnitDamaged(GetUnit(damaged), attacker, damage, dir);
}
void BaczekKPAI::UnitMoveFailed(int unit)
{
}
int BaczekKPAI::HandleEvent(int msg,const void* data)
{
ailog->info() << "event " << msg << std::endl;
return 0; // signaling: OK
}
void BaczekKPAI::Update()
{
boost::timer total;
int frame=cb->GetCurrentFrame();
int unitids[MAX_UNITS];
int num = cb->GetFriendlyUnits(unitids);
friends.clear();
std::copy(unitids, unitids+num, inserter(friends, friends.begin()));
num = cheatcb->GetEnemyUnits(unitids);
oldEnemies.clear();
oldEnemies.resize(allEnemies.size());
std::copy(allEnemies.begin(), allEnemies.end(), oldEnemies.begin());
allEnemies.clear();
allEnemies.resize(num);
std::copy(unitids, unitids+num, allEnemies.begin());
if (frame == 1) {
// XXX this will fail if used with prespawned units, e.g. missions
std::copy(unitids, unitids+num, std::inserter(enemyBases, enemyBases.end()));
}
if ((frame % 30) == 0) {
DumpStatus();
}
influence->Update(friends, allEnemies);
python->GameFrame(frame);
// enable dynamic switching of debug info
debugLines = python->GetIntValue("debugDrawLines", false);
debugMsgs = python->GetIntValue("debugMessages", false);
toplevel->Update();
ailog->info() << "frame " << frame << " in " << total.elapsed() << std::endl;
}
///////////////////
// helper methods
void BaczekKPAI::FindGeovents()
{
int features[MAX_UNITS];
int num = cheatcb->GetFeatures(features, MAX_UNITS);
ailog->info() << "found " << num << " features" << endl;
for (int i = 0; i<num; ++i) {
int featId = features[i];
const FeatureDef* fd = cb->GetFeatureDef(featId);
assert(fd);
ailog->info() << "found feature " << fd->myName << "\n";
if (fd->myName != "geovent")
continue;
float3 fpos = cb->GetFeaturePos(featId);
ailog->info() << "found geovent at " << fpos.x << " " << fpos.z << "\n";
// check if there isn't a geovent in close proximity (there are maps
// with duplicate geovents)
BOOST_FOREACH(float3 oldpos, geovents) {
if (oldpos.SqDistance2D(fpos) <= 64*64)
goto bad_geo;
}
ailog->info() << "adding geovent" << endl;
geovents.push_back(fpos);
bad_geo: ;
}
}
void BaczekKPAI::DumpStatus()
{
std::string tmpName = std::string(statusName)+".tmp";
ofstream statusFile(tmpName.c_str());
// dump map size, frame number, etc
int frame = cb->GetCurrentFrame();
statusFile << "frame " << frame << "\n"
<< "map " << map.w << " " << map.h << "\n";
// dump known geovents
statusFile << "geovents\n";
BOOST_FOREACH(float3 geo, geovents) {
statusFile << "\t" << geo.x << " " << geo.z << "\n";
}
// dump units
int unitids[MAX_UNITS];
// dump known friendly units
statusFile << "units friendly\n";
int num = cb->GetFriendlyUnits(unitids);
std::vector<float3> friends;
friends.reserve(num);
for (int i = 0; i<num; ++i) {
int id = unitids[i];
float3 pos = cb->GetUnitPos(id);
const UnitDef* ud = cb->GetUnitDef(id);
assert(ud);
// print owner
char *ownerstr;
if (cb->GetUnitTeam(id)
== cb->GetMyTeam()) {
ownerstr = "mine";
} else {
ownerstr = "allied";
}
statusFile << "\t" << ud->name << " " << id << " "
<< pos.x << " " << pos.y << " " << pos.z
<< " " << ownerstr << "\n";
friends.push_back(pos);
}
// dump known enemy units
statusFile << "units enemy\n";
num = cheatcb->GetEnemyUnits(unitids);
std::vector<float3> enemies;
enemies.reserve(num);
for (int i = 0; i<num; ++i) {
int id = unitids[i];
float3 pos = cheatcb->GetUnitPos(id);
const UnitDef* ud = cheatcb->GetUnitDef(id);
assert(ud);
statusFile << "\t" << ud->name << " " << id << " " <<
pos.x << " " << pos.y << " " << pos.z << "\n";
enemies.push_back(pos);
}
// dump influence map
statusFile << "influence map\n";
statusFile << influence->mapw << " " << influence->maph << "\n";
for (int y=0; y<influence->maph; ++y) {
for (int x=0; x<influence->mapw; ++x) {
statusFile << influence->map[x][y] << " ";
}
statusFile << "\n";
}
// dump other stuff
statusFile.close();
unlink(statusName);
rename(tmpName.c_str(), statusName);
//python->DumpStatus(frame, geovents, friends, enemies);
}
///////////////////
// spatial queries
/// union three queries
void BaczekKPAI::GetAllUnitsInRadius(std::vector<int>& vec, float3 pos, float radius)
{
int friends[MAX_UNITS];
int friend_cnt;
int enemies[MAX_UNITS];
int enemy_cnt;
int neutrals[MAX_UNITS];
int neutral_cnt;
vec.clear();
friend_cnt = cb->GetFriendlyUnits(friends, pos, radius);
enemy_cnt = cheatcb->GetEnemyUnits(enemies, pos, radius);
neutral_cnt = cheatcb->GetNeutralUnits(neutrals, pos, radius);
vec.reserve(friend_cnt + enemy_cnt + neutral_cnt);
std::copy(friends, friends+friend_cnt, std::back_inserter(vec));
std::copy(enemies, enemies+enemy_cnt, std::back_inserter(vec));
std::copy(neutrals, neutrals+neutral_cnt, std::back_inserter(vec));
}
///////////////
// pathfinder
//
// should just use GetPathLength, but it's not implemented yet!
inline float BaczekKPAI::EstimateSqDistancePF(int unitID, const float3& start, const float3& end)
{
const UnitDef* ud = cb->GetUnitDef(unitID);
return EstimateSqDistancePF(ud, start, end);
}
float BaczekKPAI::EstimateSqDistancePF(const UnitDef* unitdef, const float3& start, const float3& end)
{
int pathId = cb->InitPath(start, end, unitdef->movedata->pathType);
float sqdist = 0;
float3 prev = start;
while(true) {
float3 cur;
do {
cur = cb->GetNextWaypoint(pathId);
} while (cur.y == -2); // y == -2 means "try again"
if (prev == cur) // end of path
break;
// y == -1 means no path or end of path
if (cur.y < 0) {
if (cur.x < 0 || cur.z < 0) { // error
cb->FreePath(pathId);
return -1;
}
else {
// last waypoint reached
sqdist += cur.SqDistance2D(end);
// end here!
break;
}
} else {
sqdist += cur.SqDistance2D(prev);
prev = cur;
}
}
cb->FreePath(pathId);
return sqdist;
}
inline float BaczekKPAI::EstimateDistancePF(int unitID, const float3& start, const float3& end)
{
const UnitDef* ud = cb->GetUnitDef(unitID);
return EstimateDistancePF(ud, start, end);
}
float BaczekKPAI::EstimateDistancePF(const UnitDef* unitdef, const float3& start, const float3& end)
{
int pathId = cb->InitPath(start, end, unitdef->movedata->pathType);
float dist = 0;
float3 prev = start;
while(true) {
float3 cur;
do {
cur = cb->GetNextWaypoint(pathId);
} while (cur.y == -2); // y == -2 means "try again"
if (prev == cur) // end of path
break;
// y == -1 means no path or end of path
if (cur.y < 0) {
if (cur.x < 0 || cur.z < 0) // error
return -1;
else {
// last waypoint reached
dist += cur.distance2D(end);
// end here!
break;
}
} else {
dist += cur.distance2D(prev);
prev = cur;
}
}
cb->FreePath(pathId);
return dist;
}
//////////////////////////////////////////////////////////////////
float BaczekKPAI::GetGroundHeight(float x, float y)
{
int xsquare = int(x) / SQUARE_SIZE;
int ysquare = int(y) / SQUARE_SIZE;
if (xsquare < 0)
xsquare = 0;
else if (xsquare > map.w - 1)
xsquare = map.w - 1;
if (ysquare < 0)
ysquare = 0;
else if (ysquare > map.h - 1)
ysquare = map.h - 1;
return cb->GetHeightMap()[xsquare + ysquare * map.h];
}
//////////////////////////////////////////////////////////////////
void BaczekKPAI::InitializeUnitDefs()
{
int num = cb->GetNumUnitDefs();
const UnitDef** ar = (const UnitDef **)malloc(num*sizeof(void*));
cb->GetUnitDefList(ar);
unitDefById.reserve(num);
std::copy(ar, ar+num, std::back_inserter(unitDefById));
ailog->info() << "loaded " << num << " unitdefs" << std::endl;
free(ar);
}
| [
"[email protected]"
] | [
[
[
1,
556
]
]
] |
9a806b5998d18e6df9b38382022857de613f8314 | de98f880e307627d5ce93dcad1397bd4813751dd | /3libs/ut/include/OXInteger.inl | 32257fe7716c0beff0e39821dd675bf547aa8a03 | [] | no_license | weimingtom/sls | 7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8 | d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd | refs/heads/master | 2021-01-10T22:20:55.638757 | 2011-03-19T06:23:49 | 2011-03-19T06:23:49 | 44,464,621 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,220 | inl | // ==========================================================================
// Inline Implementation : COXInteger
// ==========================================================================
// Header file : OXInteger.inl
// Version: 9.3
// Source : R.Mortelmans
// Creation Date : 12th February 1997
// Last Modification : 12th February 1997
// //////////////////////////////////////////////////////////////////////////
inline COXInteger::COXInteger(LONGLONG nNumber /* = 0 */)
:
m_nDecimal(nNumber)
{
}
inline COXInteger::COXInteger(LPCTSTR pszNumber, int nRadix /* = 10 */)
:
m_nDecimal(0)
{
SetStringNumber(pszNumber, nRadix);
}
inline LONGLONG COXInteger::GetNumber() const
{
return m_nDecimal;
}
inline void COXInteger::SetNumber(LONGLONG nNumber)
{
m_nDecimal = nNumber;
}
inline void COXInteger::Empty()
{
m_nDecimal = 0;
}
inline BOOL COXInteger::IsEmpty() const
{
return (m_nDecimal == 0);
}
inline COXInteger::operator LONGLONG() const
{
return GetNumber();
}
inline COXInteger::~COXInteger()
{
}
// ==========================================================================
| [
"[email protected]"
] | [
[
[
1,
57
]
]
] |
e87781330a1b850a32db912b156fdb20730b433a | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/blackberry/WebKitSupport/TileIndexHash.h | 6f860a6d2238a62dd537cafeee9a4b16e62b6683 | [
"BSD-2-Clause"
] | permissive | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,494 | h | /*
* Copyright (C) Research In Motion Limited 2009. All rights reserved.
*/
#ifndef TileIndexHash_h
#define TileIndexHash_h
#include "TileIndex.h"
#include <limits>
#include <wtf/HashMap.h>
#include <wtf/HashSet.h>
using Olympia::WebKit::TileIndex;
namespace WTF {
template<> struct IntHash<TileIndex> {
static unsigned hash(const TileIndex& key) { return intHash((static_cast<uint64_t>(key.i()) << 32 | key.j())); }
static bool equal(const TileIndex& a, const TileIndex& b) { return a == b; }
static const bool safeToCompareToEmptyOrDeleted = true;
};
template<> struct DefaultHash<TileIndex> { typedef IntHash<TileIndex> Hash; };
template<> struct HashTraits<TileIndex> : GenericHashTraits<TileIndex> {
static const bool emptyValueIsZero = false;
static const bool needsDestruction = false;
static TileIndex emptyValue() { return TileIndex(); }
static void constructDeletedValue(TileIndex& slot)
{
new (&slot) TileIndex(std::numeric_limits<unsigned int>::max() - 1,
std::numeric_limits<unsigned int>::max() - 1);
}
static bool isDeletedValue(const TileIndex& value)
{
return value.i() == (std::numeric_limits<unsigned int>::max() - 1)
&& value.j() == (std::numeric_limits<unsigned int>::max() - 1);
}
};
} // namespace WTF
#endif // TileIndexHash_h
| [
"[email protected]"
] | [
[
[
1,
41
]
]
] |
0d3e6f0e8d64a62a0cdb22eaada4a5a9cba68bdd | 74e7667ad65cbdaa869c6e384fdd8dc7e94aca34 | /MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/corlib_native_System_GC.h | 4a221bbe4cc6f8e1c3842923292eff62f7cbe1bc | [
"BSD-3-Clause",
"OpenSSL",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | gezidan/NETMF-LPC | 5093ab223eb9d7f42396344ea316cbe50a2f784b | db1880a03108db6c7f611e6de6dbc45ce9b9adce | refs/heads/master | 2021-01-18T10:59:42.467549 | 2011-06-28T08:11:24 | 2011-06-28T08:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | h | //-----------------------------------------------------------------------------
//
// ** WARNING! **
// This file was generated automatically by a tool.
// Re-running the tool will overwrite this file.
// You should copy this file to a custom location
// before adding any customization in the copy to
// prevent loss of your changes when the tool is
// re-run.
//
//-----------------------------------------------------------------------------
#ifndef _CORLIB_NATIVE_SYSTEM_GC_H_
#define _CORLIB_NATIVE_SYSTEM_GC_H_
namespace System
{
struct GC
{
// Helper Functions to access fields of managed object
// Declaration of stubs. These functions are implemented by Interop code developers
static INT8 AnyPendingFinalizers( HRESULT &hr );
static void SuppressFinalize( UNSUPPORTED_TYPE param0, HRESULT &hr );
static void ReRegisterForFinalize( UNSUPPORTED_TYPE param0, HRESULT &hr );
};
}
#endif //_CORLIB_NATIVE_SYSTEM_GC_H_
| [
"[email protected]"
] | [
[
[
1,
28
]
]
] |
13ce4ebbf1c00dfd81110f684f44449360028257 | d76a67033e3abf492ff2f22d38fb80de804c4269 | /lov8/generated/v8_system.cpp | 4119c56be441ecba607edde4c02f90bf76ac84ca | [
"Zlib"
] | permissive | truthwzl/lov8 | 869a6be317b7d963600f2f88edaefdf9b5996f2d | 579163941593bae481212148041e0db78270c21d | refs/heads/master | 2021-01-10T01:58:59.103256 | 2009-12-16T16:00:09 | 2009-12-16T16:00:09 | 36,340,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,688 | cpp | #include <v8.h>
#include "../v8Object.h"
#include "../../src/system/love_system.h"
// extern
// forward declaractions
void JSlove_systemSetupClass(v8::Handle<v8::ObjectTemplate> js_obj);
v8::Handle<v8::ObjectTemplate> JSlove_systemCreateClass();
/**
* love_system::getVersion
*/
v8::Handle<v8::Value> JSlove_systemGetVersion(const v8::Arguments& args) {
if (args.Length() == 0) {
v8::HandleScope handle_scope;
char* ret = (char*)love_system::getVersion();
return v8::String::New(ret);
}
return v8::Undefined();
}
/**
* love_system::getCodename
*/
v8::Handle<v8::Value> JSlove_systemGetCodename(const v8::Arguments& args) {
if (args.Length() == 0) {
v8::HandleScope handle_scope;
char* ret = (char*)love_system::getCodename();
return v8::String::New(ret);
}
return v8::Undefined();
}
/**
* love_system::getPlatform
*/
v8::Handle<v8::Value> JSlove_systemGetPlatform(const v8::Arguments& args) {
if (args.Length() == 0) {
v8::HandleScope handle_scope;
char* ret = (char*)love_system::getPlatform();
return v8::String::New(ret);
}
return v8::Undefined();
}
/**
* love_system::exit
*/
v8::Handle<v8::Value> JSlove_systemExit(const v8::Arguments& args) {
if (args.Length() == 0) {
v8::HandleScope handle_scope;
love_system::exit();
}
return v8::Undefined();
}
/**
* love_system::restart
*/
v8::Handle<v8::Value> JSlove_systemRestart(const v8::Arguments& args) {
if (args.Length() == 0) {
v8::HandleScope handle_scope;
love_system::restart();
}
return v8::Undefined();
}
/**
* love_system::suspend
*/
v8::Handle<v8::Value> JSlove_systemSuspend(const v8::Arguments& args) {
if (args.Length() == 0) {
v8::HandleScope handle_scope;
love_system::suspend();
}
return v8::Undefined();
}
/**
* love_system::resume
*/
v8::Handle<v8::Value> JSlove_systemResume(const v8::Arguments& args) {
if (args.Length() == 0) {
v8::HandleScope handle_scope;
love_system::resume();
}
return v8::Undefined();
}
/**
* love_system::grabInput
*/
v8::Handle<v8::Value> JSlove_systemGrabInput(const v8::Arguments& args) {
if (args.Length() == 1) {
v8::HandleScope handle_scope;
bool grab = args[0]->BooleanValue();
love_system::grabInput(grab);
}
return v8::Undefined();
}
/**
* SetupClass
* Attach methods and properties
*/
void JSlove_systemSetupClass(v8::Handle<v8::ObjectTemplate> js_obj) {
js_obj->Set(v8::String::New("getVersion"), v8::FunctionTemplate::New(JSlove_systemGetVersion));
js_obj->Set(v8::String::New("getCodename"), v8::FunctionTemplate::New(JSlove_systemGetCodename));
js_obj->Set(v8::String::New("getPlatform"), v8::FunctionTemplate::New(JSlove_systemGetPlatform));
js_obj->Set(v8::String::New("exit"), v8::FunctionTemplate::New(JSlove_systemExit));
js_obj->Set(v8::String::New("restart"), v8::FunctionTemplate::New(JSlove_systemRestart));
js_obj->Set(v8::String::New("suspend"), v8::FunctionTemplate::New(JSlove_systemSuspend));
js_obj->Set(v8::String::New("resume"), v8::FunctionTemplate::New(JSlove_systemResume));
js_obj->Set(v8::String::New("grabInput"), v8::FunctionTemplate::New(JSlove_systemGrabInput));
}
/**
* CreateClass
* Creates a JS object
*/
v8::Handle<v8::ObjectTemplate> JSlove_systemCreateClass() {
v8::Handle<v8::FunctionTemplate> js_func = v8::FunctionTemplate::New();
js_func->SetClassName(v8::String::New("system"));
v8::Handle<v8::ObjectTemplate> js_obj = js_func->InstanceTemplate();
JSlove_systemSetupClass(js_obj);
return js_obj;
}
| [
"m4rvin2005@8b5f54a0-8722-11de-9e21-49812d2d8162"
] | [
[
[
1,
157
]
]
] |
9da0442c10ea95130096ae6cd3011d20e101664d | 1eb0e6d7119d33fa76bdad32363483d0c9ace9b2 | /PointCloud/trunk/PointCloud/ANN/kd_search.cpp | 7058e57d9cf0a4c7a9dd48f5e7ae991590ebed66 | [] | no_license | kbdacaa/point-clouds-mesh | 90f174a534eddb373a1ac6f5481ee7a80b05f806 | 73b6bc17aa5c597192ace1a3356bff4880ca062f | refs/heads/master | 2016-09-08T00:22:30.593144 | 2011-06-04T01:54:24 | 2011-06-04T01:54:24 | 41,203,780 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 8,893 | cpp | #include "stdafx.h"
//----------------------------------------------------------------------
// File: kd_search.cpp
// Programmer: Sunil Arya and David Mount
// Description: Standard kd-tree search
// Last modified: 01/04/05 (Version 1.0)
//----------------------------------------------------------------------
// Copyright (c) 1997-2005 University of Maryland and Sunil Arya and
// David Mount. All Rights Reserved.
//
// This software and related documentation is part of the Approximate
// Nearest Neighbor Library (ANN). This software is provided under
// the provisions of the Lesser GNU Public License (LGPL). See the
// file ../ReadMe.txt for further information.
//
// The University of Maryland (U.M.) and the authors make no
// representations about the suitability or fitness of this software for
// any purpose. It is provided "as is" without express or implied
// warranty.
//----------------------------------------------------------------------
// History:
// Revision 0.1 03/04/98
// Initial release
// Revision 1.0 04/01/05
// Changed names LO, HI to ANN_LO, ANN_HI
//----------------------------------------------------------------------
#include "kd_search.h" // kd-search declarations
//----------------------------------------------------------------------
// Approximate nearest neighbor searching by kd-tree search
// The kd-tree is searched for an approximate nearest neighbor.
// The point is returned through one of the arguments, and the
// distance returned is the squared distance to this point.
//
// The method used for searching the kd-tree is an approximate
// adaptation of the search algorithm described by Friedman,
// Bentley, and Finkel, ``An algorithm for finding best matches
// in logarithmic expected time,'' ACM Transactions on Mathematical
// Software, 3(3):209-226, 1977).
//
// The algorithm operates recursively. When first encountering a
// node of the kd-tree we first visit the child which is closest to
// the query point. On return, we decide whether we want to visit
// the other child. If the box containing the other child exceeds
// 1/(1+eps) times the current best distance, then we skip it (since
// any point found in this child cannot be closer to the query point
// by more than this factor.) Otherwise, we visit it recursively.
// The distance between a box and the query point is computed exactly
// (not approximated as is often done in kd-tree), using incremental
// distance updates, as described by Arya and Mount in ``Algorithms
// for fast vector quantization,'' Proc. of DCC '93: Data Compression
// Conference, eds. J. A. Storer and M. Cohn, IEEE Press, 1993,
// 381-390.
//
// The main entry points is annkSearch() which sets things up and
// then call the recursive routine ann_search(). This is a recursive
// routine which performs the processing for one node in the kd-tree.
// There are two versions of this virtual procedure, one for splitting
// nodes and one for leaves. When a splitting node is visited, we
// determine which child to visit first (the closer one), and visit
// the other child on return. When a leaf is visited, we compute
// the distances to the points in the buckets, and update information
// on the closest points.
//
// Some trickery is used to incrementally update the distance from
// a kd-tree rectangle to the query point. This comes about from
// the fact that which each successive split, only one component
// (along the dimension that is split) of the squared distance to
// the child rectangle is different from the squared distance to
// the parent rectangle.
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// To keep argument lists short, a number of global variables
// are maintained which are common to all the recursive calls.
// These are given below.
//----------------------------------------------------------------------
int ANNkdDim; // dimension of space
ANNpoint ANNkdQ; // query point
double ANNkdMaxErr; // max tolerable squared error
ANNpointArray ANNkdPts; // the points
ANNmin_k *ANNkdPointMK; // set of k closest points
//----------------------------------------------------------------------
// annkSearch - search for the k nearest neighbors
//----------------------------------------------------------------------
void ANNkd_tree::annkSearch(
ANNpoint q, // the query point
int k, // number of near neighbors to return
ANNidxArray nn_idx, // nearest neighbor indices (returned)
ANNdistArray dd, // the approximate nearest neighbor
double eps) // the error bound
{
ANNkdDim = dim; // copy arguments to static equivs
ANNkdQ = q;
ANNkdPts = pts;
ANNptsVisited = 0; // initialize count of points visited
if (k > n_pts) { // too many near neighbors?
annError("Requesting more near neighbors than data points", ANNabort);
}
ANNkdMaxErr = ANN_POW(1.0 + eps);
ANN_FLOP(2) // increment floating op count
ANNkdPointMK = new ANNmin_k(k); // create set for closest k points
// search starting at the root
root->ann_search(annBoxDistance(q, bnd_box_lo, bnd_box_hi, dim));
for (int i = 0; i < k; i++) { // extract the k-th closest points
dd[i] = ANNkdPointMK->ith_smallest_key(i);
nn_idx[i] = ANNkdPointMK->ith_smallest_info(i);
}
delete ANNkdPointMK; // deallocate closest point set
}
//----------------------------------------------------------------------
// kd_split::ann_search - search a splitting node
//----------------------------------------------------------------------
void ANNkd_split::ann_search(ANNdist box_dist)
{
// check dist calc term condition
if (ANNmaxPtsVisited != 0 && ANNptsVisited > ANNmaxPtsVisited) return;
// distance to cutting plane
ANNcoord cut_diff = ANNkdQ[cut_dim] - cut_val;
if (cut_diff < 0) { // left of cutting plane
child[ANN_LO]->ann_search(box_dist);// visit closer child first
ANNcoord box_diff = cd_bnds[ANN_LO] - ANNkdQ[cut_dim];
if (box_diff < 0) // within bounds - ignore
box_diff = 0;
// distance to further box
box_dist = (ANNdist) ANN_SUM(box_dist,
ANN_DIFF(ANN_POW(box_diff), ANN_POW(cut_diff)));
// visit further child if close enough
if (box_dist * ANNkdMaxErr < ANNkdPointMK->max_key())
child[ANN_HI]->ann_search(box_dist);
}
else { // right of cutting plane
child[ANN_HI]->ann_search(box_dist);// visit closer child first
ANNcoord box_diff = ANNkdQ[cut_dim] - cd_bnds[ANN_HI];
if (box_diff < 0) // within bounds - ignore
box_diff = 0;
// distance to further box
box_dist = (ANNdist) ANN_SUM(box_dist,
ANN_DIFF(ANN_POW(box_diff), ANN_POW(cut_diff)));
// visit further child if close enough
if (box_dist * ANNkdMaxErr < ANNkdPointMK->max_key())
child[ANN_LO]->ann_search(box_dist);
}
ANN_FLOP(10) // increment floating ops
ANN_SPL(1) // one more splitting node visited
}
//----------------------------------------------------------------------
// kd_leaf::ann_search - search points in a leaf node
// Note: The unreadability of this code is the result of
// some fine tuning to replace indexing by pointer operations.
//----------------------------------------------------------------------
void ANNkd_leaf::ann_search(ANNdist box_dist)
{
register ANNdist dist; // distance to data point
register ANNcoord* pp; // data coordinate pointer
register ANNcoord* qq; // query coordinate pointer
register ANNdist min_dist; // distance to k-th closest point
register ANNcoord t;
register int d;
min_dist = ANNkdPointMK->max_key(); // k-th smallest distance so far
for (int i = 0; i < n_pts; i++) { // check points in bucket
pp = ANNkdPts[bkt[i]]; // first coord of next data point
qq = ANNkdQ; // first coord of query point
dist = 0;
for(d = 0; d < ANNkdDim; d++) {
ANN_COORD(1) // one more coordinate hit
ANN_FLOP(4) // increment floating ops
t = *(qq++) - *(pp++); // compute length and adv coordinate
// exceeds dist to k-th smallest?
if( (dist = ANN_SUM(dist, ANN_POW(t))) > min_dist) {
break;
}
}
if (d >= ANNkdDim && // among the k best?
(ANN_ALLOW_SELF_MATCH || dist!=0)) { // and no self-match problem
// add it to the list
ANNkdPointMK->insert(dist, bkt[i]);
min_dist = ANNkdPointMK->max_key();
}
}
ANN_LEAF(1) // one more leaf node visited
ANN_PTS(n_pts) // increment points visited
ANNptsVisited += n_pts; // increment number of points visited
}
| [
"huangchunkuangke@e87e5053-baee-b2b1-302d-3646b6e6cf75"
] | [
[
[
1,
211
]
]
] |
540386e064a5eb6460e437fce4d885a6ccb65e05 | be78c6c17e74febd81d3f89e88347a0d009f4c99 | /src/GoIO_cpp/GTextUtils.h | ab7310c2ed588be5513f4af6539c654b560a4130 | [] | no_license | concord-consortium/goio_sdk | 87b3f816199e0bc3bd03cf754e0daf2b6a10f792 | e371fd14b8962748e853f76a3a1b472063d12284 | refs/heads/master | 2021-01-22T09:41:53.246014 | 2011-07-14T21:33:34 | 2011-07-14T21:33:34 | 851,663 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,353 | h | // GTextUtils.h
//
// Common text/string-related utilities, including
// text-format data importing facilities and types.
// NOTE CHANGE IN-PROGRESS: Many text-related methods
// currently in GUtils.h will be moved here in the near
// future.
#ifndef _GTEXTUTILS_H_
#define _GTEXTUTILS_H_
#include "GTypes.h" // for cppsstream
#ifndef USE_WIDE_CHARS
typedef int gint;
#else
typedef wint_t gint;
#endif
class GTextUtils
{
public:
static void OSInitResourceStrings(void);
static bool ReadStringsFromFile(cppstring sPath);
static void FreeResourceStrings(void);
static int GetStringIndexByKey(const char * sKey);
static cppstring GetStringByKey(const char * sKey);
static std::string GetNarrowStringByKey(const char * sKey);
static bool OSGetOSStringByKey(const char * sKey, OSStringPtr pOSString);
static cppstring GetStringByIndex(int nIndex);
static std::string GetNarrowStringByIndex(int nIndex);
static bool OSGetOSStringByIndex(int nIndex, OSStringPtr pOSString);
static StringVector GetRangeOfStrings(int nStartIndex, int nEndIndex);
static bool OSTextDataToClipboard(const cppstring & sText, bool bClearClipboard=true);
static bool OSIsTextClipDataAvailable(long * pOutLength = NULL);
static bool OSGetTextClipData(cppstring * pOutString);
// static GDeviceRect GetBestRectForText(cppstring sText, const GDeviceRect &maxRect, int kFontHeight, int nMinWidth = 450);
static bool OSPrintPlainText(const cppstring & sText, bool bShowJobDialog=false);
static cppstring RealToCPPString(real rNum, int nPrecision = 3, EFloatStyle eFloatStyle = kFloatStyle_default);
static cppstring RealToCPPString(real rNum, int nPrecision, bool bPrecisionDecimal);
static cppstring RealToDisplayCPPString(real rNum, int nDigits);
static cppstring RealToCPPStringRoundedToSigDigits(real rNum, int nSigDigits);
static cppstring LongToCPPString(long nNum);
static std::string LongToString(long nNum);
static real CPPStringToReal(const cppstring &sNumber);
static real StringToReal(const narrowstring &sNumber);
static long CPPStringToLong(const cppstring &sInteger);
static long StringToLong(const narrowstring &sInteger);
static bool IsStringRealNumber(cppstring sNumber, real *pfValue = NULL); // RETURN true if number is a real
static bool IsStringLong(const cppstring & sNumber, long *pnValue = NULL); // RETURN true if number is a long
static bool IsNarrowStringLong(const narrowstring & sNumber, long *pnValue = NULL); // RETURN true if number is a long
static cppstring StringReplace(cppstring sBase, const cppstring &sSearchFor, const cppstring &sReplaceWith);
static std::string AsciiStringReplace(std::string sBase, const std::string &sSearchFor, const std::string &sReplaceWith);
static bool StringIsAllDigits(const cppstring & sNumber);
static cppstring ExtractBaseName(const cppstring & sFullName, int * p_nOutNumberSuffix);
// For a name like "Run 3", ExtractBaseName will return "Run' and p_nOutNumberSuffix will be set to "3"
static real GetVersionFromBaseName(cppstring sFilename, cppstring sBaseName);
static cppstring MatchSubString(const cppstring & sFullName, const cppstring & sMatchName, const cppstring & sSubName);
static cppstring ParenthesizeString(const cppstring &sInString);
static narrowstring ParenthesizeNarrowString(const narrowstring &sInString);
static cppstring FilterOutChars(const cppstring &sInString, const cppstring &sFilterChars);
static cppstring ConvertToUppercase(const cppstring &sInString);
static bool StringsEqualIgnoringCase(const cppstring &s1, const cppstring &s2);
static EImportTextFormat ParseImportFormat(std::ifstream * pInStream);
static int GetWordsPerLine(std::stringstream * pInStream);
static cppstring StripPathAndExtension(const cppstring &sFileAndPath);
static cppstring StripPath(const cppstring &sFileAndPath);
static cppstring GetExtension(const cppstring &sFileName);
static cppstring GetPath(const cppstring &sFileName);
static cppstring OSGetPathSeparator(void);
static bool InvalidDataWorldName(const cppstring &sName);
// standard c string library functions with wide versions
static gchar * Gstrcpy(gchar *strDestination,const gchar * strSource );
static gchar * Gstrncpy(gchar *strDestination,const gchar * strSource, size_t nCount);
static int Gstrcmp(const gchar *str1,const gchar *str2);
static int Gstrncmp(const gchar *str1,const gchar *str2, size_t nCount);
static long Gstrtol(const gchar *nptr, gchar **endptr, int base);
static double Gstrtod(const gchar *nptr, gchar **endptr);
static size_t Gstrlen(const gchar * str );
static int Gisspace(const gint c);
static int Gisalpha (const gint c);
static int Gisprint(const gint c);
static gint GEOF();
static bool IsEOF(int i);
static cppstring ConvertNarrowStringToWide(const std::string sNarrow);
static std::string ConvertWideStringToNarrow(const cppstring sWide);
static unsigned short GetValueFromCharacterEscape(cppstring sCharEscape);
// sCharEscape should be a standard XML/HTML escape sequence in one of two formats:
// &#N; or &#xN;
// In the first case, nnn is a base-10 integer; in the second case, a hexadecimal integer.
// The method simply converts the value to an integer correctly according to base (presence of the "x"
// indicated hexadecimal).
static cppstring EncodeCharacterEscape(unsigned short nUTF8Char);
static cppstring OSGetNativeCharCodeForUTF8(unsigned short nUTF8Char);
// Typically a Windows-charset or MacRoman character equivalent to a UTF-8 char code.
// NOTE that if controls & text displays have UTF-8 support this OS method should
// not do anything, assuming we're also using wide strings.
static unsigned short OSGetUTF8CharCodeForNative(unsigned short nNativeChar);
// REVISIT - the methods below use a narrow decimal-string-escape method of character conversion
// which should be abandoned in favor of the methods above
static cppstring ConvertToOSSpecialChars(cppstring s); // go through s and convert "&SpecialCharxx" to the xx'th special OS character
static cppstring ConvertFromOSSpecialChars(cppstring s); // go through s and convert any OS special chars to "&SpecialCharxx"
static StringVector * GetOSSpecialChars(void); // list of all possible web entities (#&###;) to map from incoming text
static StringVector * GetOSSpecialCharCodes(void); // list of Local char map chars/strings to map web entities TO
static StringVector * GetOSOutgoingSpecialChars(void); // list of chars to map to web entities for outgoing text
static StringVector * GetOSOutgoingSpecialCharCodes(void); // list of web entities to map chars to
static const cppstring kSpecialCharFlag;
static cppstring OSConvertReturnLineFeed(cppstring sText); // do OS-Specific new line conversion
static bool OSGetLine(cppsstream * pInStream, cppstring * pOutString);
static int OSGetTextLength(cppstring sText);
static short AdjustTextSizeByAppPref(short nOrigSize, bool bApplyNewSize=true, void * pOSData=NULL);
// Routine to nudge text sizes up if user preferences
// so dictate. The return value is the new font pt. size.
// If bApplyNewSize is true (default) this routine actually
// applies the larger text size for immediate drawing; pOSData
// can be used as needed for draw-releated data (e.g. a draw context).
static short OSApplyTextSize(short nNewSize, void * pOSData=NULL);
// Apply new text size for text drawing. pOSData can be
// used for a draw context etc.
static narrowstring RemoveSameRoot(AsciiStringVector *pvStrings); // if all strings have the same root (i.e. text before the last '\') then remove it (and return it)
static EFloatStyle GetFloatStyle(bool bPrecisionDecimal); // return a float style based on bPrecisionDecimal
static cppstring TranslatePathToFile(cppstring sPath); // Convert all separator characters to the proper OS
static cppstring TranslatePathFromFile(cppstring sPath); // Convert all separator characters from the proper OS
static int kSmallestFontSize; // used in font size controls
static int kLargestFontSize;
private:
static StringVector kvSpecialChar;
static StringVector kvSpecialCharCode;
static StringVector kvOutgoingSpecialChar;
static StringVector kvOutgoingSpecialCharCode;
static std::map<narrowstring, int> m_mStringIndices;
static std::vector<cppstring> m_vStringData;
};
#define GSTD_STRING(x) GTextUtils::GetStringByKey(#x)
#define GSTD_INDEX(x) GTextUtils::GetStringIndexByKey(#x)
#define GSTD_INDEXSTRING(x) GTextUtils::GetStringByIndex(x)
#define GSTD_OSSTRING(x, p) GTextUtils::OSGetOSStringByKey(#x, p)
#define GSTD_NARROWSTRING(x) GTextUtils::GetNarrowStringByKey(#x)
#endif // _GTEXTUTILS_H_
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
77
],
[
79,
174
]
],
[
[
78,
78
]
]
] |
66e4b3a395d9e408b05ada16e2bf132881f20566 | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osgManipulator/Translate1DDragger | bc3fd109c49c6def0394bcde6011fe7f4fb8d2b1 | [] | no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,529 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V.
#ifndef OSGMANIPULATOR_TRANSLATE1DDRAGGER
#define OSGMANIPULATOR_TRANSLATE1DDRAGGER 1
#include <osgManipulator/Dragger>
#include <osgManipulator/Projector>
namespace osgManipulator {
/**
* Dragger for performing 1D translation.
*/
class OSGMANIPULATOR_EXPORT Translate1DDragger : public Dragger
{
public:
Translate1DDragger();
META_OSGMANIPULATOR_Object(osgManipulator,Translate1DDragger)
Translate1DDragger(const osg::Vec3d& s, const osg::Vec3d& e);
/** Handle pick events on dragger and generate TranslateInLine commands. */
virtual bool handle(const PointerInfo& pi, const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us);
/** Setup default geometry for dragger. */
void setupDefaultGeometry();
/** Set/Get color for dragger. */
inline void setColor(const osg::Vec4& color) { _color = color; setMaterialColor(_color,*this); }
inline const osg::Vec4 getColor() const { return _color; }
/** Set/Get pick color for dragger. Pick color is color of the dragger when picked.
It gives a visual feedback to show that the dragger has been picked. */
inline void setPickColor(const osg::Vec4& color) { _pickColor = color; }
inline const osg::Vec4 getPickColor() const { return _pickColor; }
inline void setCheckForNodeInNodePath(bool onOff) { _checkForNodeInNodePath = onOff; }
protected:
virtual ~Translate1DDragger();
osg::ref_ptr< LineProjector > _projector;
osg::Vec3d _startProjectedPoint;
osg::Vec4 _color;
osg::Vec4 _pickColor;
bool _checkForNodeInNodePath;
};
}
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
] | [
[
[
1,
70
]
]
] |
|
9f4cd950c24f0f6ea278df1d0f53d6294c3433b3 | 01acea32aaabe631ce84ff37340c6f20da3065a6 | /ship.cpp | e15af7e8dc9d9514452cf9098780f473dfecc0fc | [] | no_license | olooney/pattern-space | db2804d75249fe42427c15260ecb665bc489e012 | dcf07e63a6cb7644452924212ed087d45c301e78 | refs/heads/master | 2021-01-20T09:38:41.065323 | 2011-04-20T01:25:58 | 2011-04-20T01:25:58 | 1,638,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,760 | cpp | /*
Implementation for Ship class.
Note that the Controls class, also defined in ship.h, is basically a struct
and has no implementation here.
All we're doing is keeping track of the state of the relevant control keys,
and applying forces to the Ship based on which combination of keys is being
held down.
TODO: The missle firing code here seems out of place and should be moved
somewhere more appropriate.
*/
#include "ship.h"
#include "factories.h"
namespace PatternSpace {
/********************* Ship *********************/
const double Ship::ENGINE_THRUST = .1;
const double Ship::ENGINE_REVERSE_THRUST = .03;
const double Ship::TURN_THRUST = 10;
void Ship::step(double deltaTime)
{
// apply the forces from the user controls
if (upState) {
Vector2d thrust = ENGINE_THRUST * Vector2d( angle() );
push(thrust);
}
if (downState) {
Vector2d thrust = - ENGINE_REVERSE_THRUST * Vector2d( angle() );
push(thrust);
}
if (leftState) {
torque( - TURN_THRUST );
}
if (rightState) {
torque( TURN_THRUST );
}
// then let the base class take care of the rest.
this->NormalSolid::step(deltaTime);
}
// these functions inform the Ship about changes in the state of the
// user controls. Here, we simply record the current state.
void Ship::up(bool state) { upState = state; }
void Ship::down(bool state) { downState = state; }
void Ship::left(bool state) { leftState = state; }
void Ship::right(bool state) { rightState = state; }
// when the primary key is depressed, fire a single missle.
void Ship::primary(bool state)
{
if (state == true) {
fireMissle = true;
}
primaryState = state;
}
// the next two functions form a kind of iterator: hasSpawn will be true
// as long as there is a missle to fire, and nextSpawn will keep being
// called until hasSpawn becomes false. In this case, we set the internal
// flag fireMissle when the user presses the fire key, and clear it after
// firing a single missle.
bool Ship::hasSpawn() const {
return fireMissle;
}
boost::shared_ptr<Solid> Ship::nextSpawn() {
fireMissle = false;
Vector2d forward = Vector2d( angle() );
Vector2d misslePosition = position() + ( (radius()+6) * forward );
Vector2d missleVelocity = velocity() + ( .8 * forward );
return newMissle( misslePosition, missleVelocity );
}
} // end namespace PatternSpace
| [
"[email protected]"
] | [
[
[
1,
81
]
]
] |
6c3f4b5f4eb7b9e9c9275aa5978692fa8072b0e2 | 63937d06f9f4083609200cb743ec0122c6da9f40 | /tests/test_2.cpp | 11bb920b7f63cf8b76f18798a1cf0bf9f20a615e | [] | no_license | funkjunky/slogic | 924704b192f102390e1fde1402aedfcb13d3af40 | 4795a9f7aa626faa215012d94686b1769af4f2c7 | refs/heads/master | 2021-01-22T09:46:51.990756 | 2011-02-10T08:51:27 | 2011-02-10T08:51:27 | 1,341,519 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,066 | cpp | /**
* \todo Do inherited members show up in initializer lists???
*/
#include "subj_logic.hpp"
#include <iostream>
#include <set>
using namespace std;
using namespace Subj_logic;
template <typename T>
T reduce(T data) { return data; }
int main()
{
// Example D: Reliability Analusis
Opinion x(Real(41, 100), Real(24, 100), Real(30, 100));
Opinion y(Real(23, 100), Real(56, 100), Real(11, 100));
// test out the & operator
Opinion z = x & y;
// test out the | operator
Opinion z2 = x | y;
// test out the + operator
Opinion z3 = x + y;
// test out the - operator
Opinion z4 = x - y;
// now lets see if it gives the correct numbers.
// these numbers are correct, we tested them using the program on josangs website.
cout << "x:" << endl
<< "belief: " << reduce(x.get_belief()) << endl
<< "disbelief: " << reduce(x.get_disbelief()) << endl
<< "uncertainty: " << reduce(x.get_uncertainty()) << endl
<< "Atomicity: " << reduce(x.get_base_rate()) << endl
<< "x probability: " << reduce(x.get_probability_expectation()) << endl
<< "---" << endl;
cout << "y:" << endl
<< "belief: " << reduce(y.get_belief()) << endl
<< "disbelief: " << reduce(y.get_disbelief()) << endl
<< "uncertainty: " << reduce(y.get_uncertainty()) << endl
<< "Atomicity: " << reduce(y.get_base_rate()) << endl
<< "y probability: " << reduce(y.get_probability_expectation()) << endl
<< "---" << endl;
cout << "x & y:" << endl
<< "belief: " << reduce(z.get_belief()) << endl
<< "disbelief: " << reduce(z.get_disbelief()) << endl
<< "uncertainty: " << reduce(z.get_uncertainty()) << endl
<< "Atomicity: " << reduce(z.get_base_rate()) << endl
<< "z probability: " << reduce(z.get_probability_expectation()) << endl
<< "---" << endl;
cout << "x | y:" << endl
<< "belief: " << reduce(z2.get_belief()) << endl
<< "disbelief: " << reduce(z2.get_disbelief()) << endl
<< "uncertainty: " << reduce(z2.get_uncertainty()) << endl
<< "Atomicity: " << reduce(z2.get_base_rate()) << endl
<< "z probability: " << reduce(z2.get_probability_expectation()) << endl
<< "---" << endl;
cout << "x + y:" << endl
<< "belief: " << reduce(z3.get_belief()) << endl
<< "disbelief: " << reduce(z3.get_disbelief()) << endl
<< "uncertainty: " << reduce(z3.get_uncertainty()) << endl
<< "Atomicity: " << reduce(z3.get_base_rate()) << endl
<< "z probability: " << reduce(z3.get_probability_expectation()) << endl
<< "---" << endl;
cout << "x - y:" << endl
<< "belief: " << reduce(z4.get_belief()) << endl
<< "disbelief: " << reduce(z4.get_disbelief()) << endl
<< "uncertainty: " << reduce(z4.get_uncertainty()) << endl
<< "Atomicity: " << reduce(z4.get_base_rate()) << endl
<< "z probability: " << reduce(z4.get_probability_expectation()) << endl
<< "---" << endl;
}
| [
"[email protected]"
] | [
[
[
1,
80
]
]
] |
58db100579f9adb13e3babcd341c9f784a733d03 | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /Shared/ComponentInterface2/CMPScienceAPI.h | e455ce48cce1a1d7c22dff758fb5430059d6f2ab | [] | no_license | sativa/apsim_development | efc2b584459b43c89e841abf93830db8d523b07a | a90ffef3b4ed8a7d0cce1c169c65364be6e93797 | refs/heads/master | 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,743 | h | #ifndef CMPScienceAPIH
#define CMPScienceAPIH
#include <general/platform.h>
#include <ComponentInterface2/ScienceAPI.h>
class CMPComponentInterface;
// ------------------------------------------------------------------
// CMP Implementation for interacting with simulation
// NB: Autogenerated. Do not modify manually.
// ------------------------------------------------------------------
class EXPORT CMPScienceAPI : public ScienceAPI
{
private:
CMPComponentInterface& componentInterface;
public:
CMPScienceAPI(CMPComponentInterface& componentinterface);
virtual ~CMPScienceAPI() {};
virtual void write(const std::string& msg);
virtual std::string name();
virtual std::string FQName();
virtual void setSearchOrder(const std::vector<std::string> &list);
virtual void getSearchOrder(std::vector<std::string> &list);
virtual void query(const std::string& pattern, std::vector<QueryMatch>& matches);
// Methods for reading raw strings
virtual bool readFiltered(const std::string& filterName, std::vector<std::string> &values);
virtual bool readAll(std::vector<std::string>& names, std::vector<std::string> &values);
virtual void notifyFutureEvent(const std::string& name);
// null
virtual void subscribe(const std::string& name, boost::function0<void> handler);
virtual void publish(const std::string& name);
// bool
virtual bool read(const std::string& name, const std::string& units, bool optional, bool& data);
virtual bool get(const std::string& name, const std::string& units, bool optional, bool& data);
virtual void set(const std::string& name, const std::string& units, bool& data);
virtual void expose(const std::string& name, const std::string& units, const std::string& description, bool writable, bool& variable);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description, boost::function1<void, bool&> method);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description,
boost::function1<void, bool&> getter,
boost::function1<void, bool&> setter);
virtual void subscribe(const std::string& name, boost::function1<void, bool&> handler);
virtual void publish(const std::string& name, bool& data);
// int
virtual bool read(const std::string& name, const std::string& units, bool optional, int& data);
virtual bool read(const std::string& name, const std::string& units, bool optional, int& data, int lower, int upper);
virtual bool get(const std::string& name, const std::string& units, bool optional, int& data);
virtual bool get(const std::string& name, const std::string& units, bool optional, int& data, int lower, int upper);
virtual void set(const std::string& name, const std::string& units, int& data);
virtual void expose(const std::string& name, const std::string& units, const std::string& description, bool writable, int& variable);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description, boost::function1<void, int&> method);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description,
boost::function1<void, int&> getter,
boost::function1<void, int&> setter);
virtual void subscribe(const std::string& name, boost::function1<void, int&> handler);
virtual void publish(const std::string& name, int& data);
// float
virtual bool read(const std::string& name, const std::string& units, bool optional, float& data);
virtual bool read(const std::string& name, const std::string& units, bool optional, float& data, float lower, float upper);
virtual bool get(const std::string& name, const std::string& units, bool optional, float& data);
virtual bool get(const std::string& name, const std::string& units, bool optional, float& data, float lower, float upper);
virtual void set(const std::string& name, const std::string& units, float& data);
virtual void expose(const std::string& name, const std::string& units, const std::string& description, bool writable, float& variable);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description, boost::function1<void, float&> method);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description,
boost::function1<void, float&> getter,
boost::function1<void, float&> setter);
virtual void subscribe(const std::string& name, boost::function1<void, float&> handler);
virtual void publish(const std::string& name, float& data);
// double
virtual bool read(const std::string& name, const std::string& units, bool optional, double& data);
virtual bool read(const std::string& name, const std::string& units, bool optional, double& data, double lower, double upper);
virtual bool get(const std::string& name, const std::string& units, bool optional, double& data);
virtual bool get(const std::string& name, const std::string& units, bool optional, double& data, double lower, double upper);
virtual void set(const std::string& name, const std::string& units, double& data);
virtual void expose(const std::string& name, const std::string& units, const std::string& description, bool writable, double& variable);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description, boost::function1<void, double&> method);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description,
boost::function1<void, double&> getter,
boost::function1<void, double&> setter);
virtual void subscribe(const std::string& name, boost::function1<void, double&> handler);
virtual void publish(const std::string& name, double& data);
// std::string
virtual bool read(const std::string& name, const std::string& units, bool optional, std::string& data);
virtual bool get(const std::string& name, const std::string& units, bool optional, std::string& data);
virtual void set(const std::string& name, const std::string& units, std::string& data);
virtual void expose(const std::string& name, const std::string& units, const std::string& description, bool writable, std::string& variable);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description, boost::function1<void, std::string&> method);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description,
boost::function1<void, std::string&> getter,
boost::function1<void, std::string&> setter);
virtual void subscribe(const std::string& name, boost::function1<void, std::string&> handler);
virtual void publish(const std::string& name, std::string& data);
// std::vector<bool>
virtual bool read(const std::string& name, const std::string& units, bool optional, std::vector<bool>& data);
virtual bool get(const std::string& name, const std::string& units, bool optional, std::vector<bool>& data);
virtual void set(const std::string& name, const std::string& units, std::vector<bool>& data);
virtual void expose(const std::string& name, const std::string& units, const std::string& description, bool writable, std::vector<bool>& variable);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description, boost::function1<void, std::vector<bool>&> method);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description,
boost::function1<void, std::vector<bool>&> getter,
boost::function1<void, std::vector<bool>&> setter);
virtual void subscribe(const std::string& name, boost::function1<void, std::vector<bool>&> handler);
virtual void publish(const std::string& name, std::vector<bool>& data);
// std::vector<int>
virtual bool read(const std::string& name, const std::string& units, bool optional, std::vector<int>& data);
virtual bool read(const std::string& name, const std::string& units, bool optional, std::vector<int>& data, int lower, int upper);
virtual bool get(const std::string& name, const std::string& units, bool optional, std::vector<int>& data);
virtual bool get(const std::string& name, const std::string& units, bool optional, std::vector<int>& data, int lower, int upper);
virtual void set(const std::string& name, const std::string& units, std::vector<int>& data);
virtual void expose(const std::string& name, const std::string& units, const std::string& description, bool writable, std::vector<int>& variable);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description, boost::function1<void, std::vector<int>&> method);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description,
boost::function1<void, std::vector<int>&> getter,
boost::function1<void, std::vector<int>&> setter);
virtual void subscribe(const std::string& name, boost::function1<void, std::vector<int>&> handler);
virtual void publish(const std::string& name, std::vector<int>& data);
// std::vector<float>
virtual bool read(const std::string& name, const std::string& units, bool optional, std::vector<float>& data);
virtual bool read(const std::string& name, const std::string& units, bool optional, std::vector<float>& data, float lower, float upper);
virtual bool get(const std::string& name, const std::string& units, bool optional, std::vector<float>& data);
virtual bool get(const std::string& name, const std::string& units, bool optional, std::vector<float>& data, float lower, float upper);
virtual void set(const std::string& name, const std::string& units, std::vector<float>& data);
virtual void expose(const std::string& name, const std::string& units, const std::string& description, bool writable, std::vector<float>& variable);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description, boost::function1<void, std::vector<float>&> method);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description,
boost::function1<void, std::vector<float>&> getter,
boost::function1<void, std::vector<float>&> setter);
virtual void subscribe(const std::string& name, boost::function1<void, std::vector<float>&> handler);
virtual void publish(const std::string& name, std::vector<float>& data);
// std::vector<double>
virtual bool read(const std::string& name, const std::string& units, bool optional, std::vector<double>& data);
virtual bool read(const std::string& name, const std::string& units, bool optional, std::vector<double>& data, double lower, double upper);
virtual bool get(const std::string& name, const std::string& units, bool optional, std::vector<double>& data);
virtual bool get(const std::string& name, const std::string& units, bool optional, std::vector<double>& data, double lower, double upper);
virtual void set(const std::string& name, const std::string& units, std::vector<double>& data);
virtual void expose(const std::string& name, const std::string& units, const std::string& description, bool writable, std::vector<double>& variable);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description, boost::function1<void, std::vector<double>&> method);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description,
boost::function1<void, std::vector<double>&> getter,
boost::function1<void, std::vector<double>&> setter);
virtual void subscribe(const std::string& name, boost::function1<void, std::vector<double>&> handler);
virtual void publish(const std::string& name, std::vector<double>& data);
// std::vector<std::string>
virtual bool read(const std::string& name, const std::string& units, bool optional, std::vector<std::string>& data);
virtual bool get(const std::string& name, const std::string& units, bool optional, std::vector<std::string>& data);
virtual void set(const std::string& name, const std::string& units, std::vector<std::string>& data);
virtual void expose(const std::string& name, const std::string& units, const std::string& description, bool writable, std::vector<std::string>& variable);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description, boost::function1<void, std::vector<std::string>&> method);
virtual void exposeFunction(const std::string& name, const std::string& units, const std::string& description,
boost::function1<void, std::vector<std::string>&> getter,
boost::function1<void, std::vector<std::string>&> setter);
virtual void subscribe(const std::string& name, boost::function1<void, std::vector<std::string>&> handler);
virtual void publish(const std::string& name, std::vector<std::string>& data);
virtual void subscribe(const std::string& name, boost::function1<void, CompleteType&> handler);
virtual void publish(const std::string& name, CompleteType& data);
virtual void subscribe(const std::string& name, boost::function1<void, ErrorType&> handler);
virtual void publish(const std::string& name, ErrorType& data);
virtual void subscribe(const std::string& name, boost::function1<void, EventType&> handler);
virtual void publish(const std::string& name, EventType& data);
virtual void subscribe(const std::string& name, boost::function1<void, GetValueType&> handler);
virtual void publish(const std::string& name, GetValueType& data);
virtual void subscribe(const std::string& name, boost::function1<void, Init1Type&> handler);
virtual void publish(const std::string& name, Init1Type& data);
virtual void subscribe(const std::string& name, boost::function1<void, NotifySetValueSuccessType&> handler);
virtual void publish(const std::string& name, NotifySetValueSuccessType& data);
virtual void subscribe(const std::string& name, boost::function1<void, PublishEventType&> handler);
virtual void publish(const std::string& name, PublishEventType& data);
virtual void subscribe(const std::string& name, boost::function1<void, QueryInfoType&> handler);
virtual void publish(const std::string& name, QueryInfoType& data);
virtual void subscribe(const std::string& name, boost::function1<void, RegisterType&> handler);
virtual void publish(const std::string& name, RegisterType& data);
virtual void subscribe(const std::string& name, boost::function1<void, ReplyValueType&> handler);
virtual void publish(const std::string& name, ReplyValueType& data);
virtual void subscribe(const std::string& name, boost::function1<void, RequestSetValueType&> handler);
virtual void publish(const std::string& name, RequestSetValueType& data);
virtual void subscribe(const std::string& name, boost::function1<void, ReturnInfoType&> handler);
virtual void publish(const std::string& name, ReturnInfoType& data);
virtual void subscribe(const std::string& name, boost::function1<void, ReturnValueType&> handler);
virtual void publish(const std::string& name, ReturnValueType& data);
virtual void subscribe(const std::string& name, boost::function1<void, QueryValueType&> handler);
virtual void publish(const std::string& name, QueryValueType& data);
virtual void subscribe(const std::string& name, boost::function1<void, QuerySetValueType&> handler);
virtual void publish(const std::string& name, QuerySetValueType& data);
virtual void subscribe(const std::string& name, boost::function1<void, ApsimVariantType&> handler);
virtual void publish(const std::string& name, ApsimVariantType& data);
virtual void subscribe(const std::string& name, boost::function1<void, LayeredType&> handler);
virtual void publish(const std::string& name, LayeredType& data);
virtual void subscribe(const std::string& name, boost::function1<void, TimeType&> handler);
virtual void publish(const std::string& name, TimeType& data);
virtual void subscribe(const std::string& name, boost::function1<void, NewMetType&> handler);
virtual void publish(const std::string& name, NewMetType& data);
virtual void subscribe(const std::string& name, boost::function1<void, NewSoluteType&> handler);
virtual void publish(const std::string& name, NewSoluteType& data);
virtual void subscribe(const std::string& name, boost::function1<void, IrrigatedType&> handler);
virtual void publish(const std::string& name, IrrigatedType& data);
virtual void subscribe(const std::string& name, boost::function1<void, KillCropType&> handler);
virtual void publish(const std::string& name, KillCropType& data);
virtual void subscribe(const std::string& name, boost::function1<void, layerType&> handler);
virtual void publish(const std::string& name, layerType& data);
virtual void subscribe(const std::string& name, boost::function1<void, InterceptionType&> handler);
virtual void publish(const std::string& name, InterceptionType& data);
virtual void subscribe(const std::string& name, boost::function1<void, LightProfileType&> handler);
virtual void publish(const std::string& name, LightProfileType& data);
virtual void subscribe(const std::string& name, boost::function1<void, CanopyType&> handler);
virtual void publish(const std::string& name, CanopyType& data);
virtual void subscribe(const std::string& name, boost::function1<void, CanopyWaterBalanceType&> handler);
virtual void publish(const std::string& name, CanopyWaterBalanceType& data);
virtual void subscribe(const std::string& name, boost::function1<void, OrganicMatterFractionType&> handler);
virtual void publish(const std::string& name, OrganicMatterFractionType& data);
virtual void subscribe(const std::string& name, boost::function1<void, ResidueType&> handler);
virtual void publish(const std::string& name, ResidueType& data);
virtual void subscribe(const std::string& name, boost::function1<void, FPoolType&> handler);
virtual void publish(const std::string& name, FPoolType& data);
virtual void subscribe(const std::string& name, boost::function1<void, FPoolProfileLayerType&> handler);
virtual void publish(const std::string& name, FPoolProfileLayerType& data);
virtual void subscribe(const std::string& name, boost::function1<void, StandingFractionType&> handler);
virtual void publish(const std::string& name, StandingFractionType& data);
virtual void subscribe(const std::string& name, boost::function1<void, LyingFractionType&> handler);
virtual void publish(const std::string& name, LyingFractionType& data);
virtual void subscribe(const std::string& name, boost::function1<void, SurfaceOrganicMatterType&> handler);
virtual void publish(const std::string& name, SurfaceOrganicMatterType& data);
virtual void subscribe(const std::string& name, boost::function1<void, SurfaceOrganicMatterDecompType&> handler);
virtual void publish(const std::string& name, SurfaceOrganicMatterDecompType& data);
virtual void subscribe(const std::string& name, boost::function1<void, NBalanceType&> handler);
virtual void publish(const std::string& name, NBalanceType& data);
virtual void subscribe(const std::string& name, boost::function1<void, CBalanceType&> handler);
virtual void publish(const std::string& name, CBalanceType& data);
virtual void subscribe(const std::string& name, boost::function1<void, IncorpFomType&> handler);
virtual void publish(const std::string& name, IncorpFomType& data);
virtual void subscribe(const std::string& name, boost::function1<void, SoilOrganicMatterType&> handler);
virtual void publish(const std::string& name, SoilOrganicMatterType& data);
virtual void subscribe(const std::string& name, boost::function1<void, CropChoppedType&> handler);
virtual void publish(const std::string& name, CropChoppedType& data);
virtual void subscribe(const std::string& name, boost::function1<void, NewProfileType&> handler);
virtual void publish(const std::string& name, NewProfileType& data);
virtual void subscribe(const std::string& name, boost::function1<void, NewPotentialGrowthType&> handler);
virtual void publish(const std::string& name, NewPotentialGrowthType& data);
virtual void subscribe(const std::string& name, boost::function1<void, NewCanopyType&> handler);
virtual void publish(const std::string& name, NewCanopyType& data);
virtual void subscribe(const std::string& name, boost::function1<void, NewCropType&> handler);
virtual void publish(const std::string& name, NewCropType& data);
virtual void subscribe(const std::string& name, boost::function1<void, fomType&> handler);
virtual void publish(const std::string& name, fomType& data);
virtual void subscribe(const std::string& name, boost::function1<void, FomAddedType&> handler);
virtual void publish(const std::string& name, FomAddedType& data);
virtual void subscribe(const std::string& name, boost::function1<void, PastureSowType&> handler);
virtual void publish(const std::string& name, PastureSowType& data);
virtual void subscribe(const std::string& name, boost::function1<void, PastureKillType&> handler);
virtual void publish(const std::string& name, PastureKillType& data);
virtual void subscribe(const std::string& name, boost::function1<void, PastureCultivateType&> handler);
virtual void publish(const std::string& name, PastureCultivateType& data);
virtual void subscribe(const std::string& name, boost::function1<void, PastureCutType&> handler);
virtual void publish(const std::string& name, PastureCutType& data);
virtual void subscribe(const std::string& name, boost::function1<void, PastureBurnType&> handler);
virtual void publish(const std::string& name, PastureBurnType& data);
virtual void subscribe(const std::string& name, boost::function1<void, PastureOnCutType&> handler);
virtual void publish(const std::string& name, PastureOnCutType& data);
virtual void subscribe(const std::string& name, boost::function1<void, FaecesType&> handler);
virtual void publish(const std::string& name, FaecesType& data);
virtual void subscribe(const std::string& name, boost::function1<void, FaecesInorgType&> handler);
virtual void publish(const std::string& name, FaecesInorgType& data);
virtual void subscribe(const std::string& name, boost::function1<void, IntakeType&> handler);
virtual void publish(const std::string& name, IntakeType& data);
virtual void subscribe(const std::string& name, boost::function1<void, PastIntakeType&> handler);
virtual void publish(const std::string& name, PastIntakeType& data);
virtual void subscribe(const std::string& name, boost::function1<void, SuppIntakeType&> handler);
virtual void publish(const std::string& name, SuppIntakeType& data);
virtual void subscribe(const std::string& name, boost::function1<void, faeces_omType&> handler);
virtual void publish(const std::string& name, faeces_omType& data);
virtual void subscribe(const std::string& name, boost::function1<void, faeces_inorgType&> handler);
virtual void publish(const std::string& name, faeces_inorgType& data);
virtual void subscribe(const std::string& name, boost::function1<void, urineType&> handler);
virtual void publish(const std::string& name, urineType& data);
virtual void subscribe(const std::string& name, boost::function1<void, AddExcretaType&> handler);
virtual void publish(const std::string& name, AddExcretaType& data);
virtual void subscribe(const std::string& name, boost::function1<void, RemoveHerbageType&> handler);
virtual void publish(const std::string& name, RemoveHerbageType& data);
virtual void subscribe(const std::string& name, boost::function1<void, SuppEatenType&> handler);
virtual void publish(const std::string& name, SuppEatenType& data);
virtual void subscribe(const std::string& name, boost::function1<void, herbageType&> handler);
virtual void publish(const std::string& name, herbageType& data);
virtual void subscribe(const std::string& name, boost::function1<void, seedType&> handler);
virtual void publish(const std::string& name, seedType& data);
virtual void subscribe(const std::string& name, boost::function1<void, Plant2StockType&> handler);
virtual void publish(const std::string& name, Plant2StockType& data);
virtual void subscribe(const std::string& name, boost::function1<void, BuyStockType&> handler);
virtual void publish(const std::string& name, BuyStockType& data);
virtual void subscribe(const std::string& name, boost::function1<void, SellStockType&> handler);
virtual void publish(const std::string& name, SellStockType& data);
virtual void subscribe(const std::string& name, boost::function1<void, CastrateStockType&> handler);
virtual void publish(const std::string& name, CastrateStockType& data);
virtual void subscribe(const std::string& name, boost::function1<void, DryOffStockType&> handler);
virtual void publish(const std::string& name, DryOffStockType& data);
virtual void subscribe(const std::string& name, boost::function1<void, JoinStockType&> handler);
virtual void publish(const std::string& name, JoinStockType& data);
virtual void subscribe(const std::string& name, boost::function1<void, MoveStockType&> handler);
virtual void publish(const std::string& name, MoveStockType& data);
virtual void subscribe(const std::string& name, boost::function1<void, ShearStockType&> handler);
virtual void publish(const std::string& name, ShearStockType& data);
virtual void subscribe(const std::string& name, boost::function1<void, SplitStockType&> handler);
virtual void publish(const std::string& name, SplitStockType& data);
virtual void subscribe(const std::string& name, boost::function1<void, TagStockType&> handler);
virtual void publish(const std::string& name, TagStockType& data);
virtual void subscribe(const std::string& name, boost::function1<void, WeanStockType&> handler);
virtual void publish(const std::string& name, WeanStockType& data);
virtual void subscribe(const std::string& name, boost::function1<void, dmType&> handler);
virtual void publish(const std::string& name, dmType& data);
virtual void subscribe(const std::string& name, boost::function1<void, RemoveCropDmType&> handler);
virtual void publish(const std::string& name, RemoveCropDmType& data);
virtual void subscribe(const std::string& name, boost::function1<void, RemoveResidueDmType&> handler);
virtual void publish(const std::string& name, RemoveResidueDmType& data);
virtual void subscribe(const std::string& name, boost::function1<void, SupplementBuyType&> handler);
virtual void publish(const std::string& name, SupplementBuyType& data);
virtual void subscribe(const std::string& name, boost::function1<void, SupplementFeedType&> handler);
virtual void publish(const std::string& name, SupplementFeedType& data);
virtual void subscribe(const std::string& name, boost::function1<void, SupplementMixType&> handler);
virtual void publish(const std::string& name, SupplementMixType& data);
virtual void subscribe(const std::string& name, boost::function1<void, ExternalMassFlowType&> handler);
virtual void publish(const std::string& name, ExternalMassFlowType& data);
virtual void subscribe(const std::string& name, boost::function1<void, Variant&> handler);
virtual void publish(const std::string& name, Variant& data);
};
#endif
| [
"devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8",
"hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8"
] | [
[
[
1,
6
],
[
8,
30
],
[
33,
216
],
[
220,
237
],
[
241,
426
]
],
[
[
7,
7
],
[
31,
32
],
[
217,
219
],
[
238,
240
]
]
] |
ae69d794cf7d9aa0ac932a5493fef214b8671c31 | df070aa6eb5225412ebf0c3916b41449edfa16ac | /AVS_Transcoder_SDK/kernel/video/tavs/avs_enc/src/configfile.cpp | f9634512c2ed1abddc328c3825667edb32b92357 | [] | no_license | numericalBoy/avs-transcoder | 659b584cc5bbc4598a3ec9beb6e28801d3d33f8d | 56a3238b34ec4e0bf3a810cedc31284ac65361c5 | refs/heads/master | 2020-04-28T21:08:55.048442 | 2010-03-10T13:28:18 | 2010-03-10T13:28:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,616 | cpp | /*
*****************************************************************************
* COPYRIGHT AND WARRANTY INFORMATION
*
* Copyright 2003, Advanced Audio Video Coding Standard, Part II
*
* DISCLAIMER OF WARRANTY
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations under
* the License.
*
* THIS IS NOT A GRANT OF PATENT RIGHTS - SEE THE AVS PATENT POLICY.
* The AVS Working Group doesn't represent or warrant that the programs
* furnished here under are free of infringement of any third-party patents.
* Commercial implementations of AVS, including shareware, may be
* subject to royalty fees to patent holders. Information regarding
* the AVS patent policy for standardization procedure is available at
* AVS Web site http://www.avs.org.cn. Patent Licensing is outside
* of AVS Working Group.
*
* THIS IS NOT A GRANT OF PATENT RIGHTS - SEE THE AVS PATENT POLICY.
************************************************************************
*/
/*
*************************************************************************************
* File name:
* Function:
*
*************************************************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "global.h"
TLS InputParameters configinput;
typedef struct tag_mapping
{
char *TokenName;
void *Place;
int_32_t Type;
} Mapping;
TLS Mapping Map[39];
/*
*************************************************************************
* Function:Parse the command line parameters and read the config files.
* Input: ac
number of command line parameters
av
command line parameters
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::Configure (char *av)
{
char *content;
Map[0].TokenName = "GOPLength";
Map[1].TokenName = "FramesToBeEncoded";
Map[2].TokenName = "QPFirstFrame";
Map[3].TokenName = "QPRemainingFrame";
Map[4].TokenName = "UseHadamard";
Map[5].TokenName = "SearchRange";
Map[6].TokenName = "NumberReferenceFrames";
Map[7].TokenName = "SourceWidth";
Map[8].TokenName = "SourceHeight";
Map[9].TokenName = "InputFile";
Map[10].TokenName = "InputHeaderLength";
Map[11].TokenName = "OutputFile";
Map[12].TokenName = "ReconFile";
Map[13].TokenName = "TraceFile";
Map[14].TokenName = "NumberBFrames";
Map[15].TokenName = "QPBPicture";
Map[16].TokenName = "InterSearch16x16";
Map[17].TokenName = "InterSearch16x8";
Map[18].TokenName = "InterSearch8x16";
Map[19].TokenName = "InterSearch8x8";
Map[20].TokenName = "RDOptimization";
Map[21].TokenName = "InterlaceCodingOption";
Map[22].TokenName = "LoopFilterDisable";
Map[23].TokenName = "LoopFilterParameter";
Map[24].TokenName = "LoopFilterAlphaOffset";
Map[25].TokenName = "LoopFilterBetaOffset";
Map[26].TokenName = "Progressive_frame";
Map[27].TokenName = "Dct_Adaptive_Flag";
Map[28].TokenName = "NumberOfRowsInSlice";
Map[29].TokenName = "SliceParameter";
Map[30].TokenName = "WeightEnable";
Map[31].TokenName = "FrameRate";
Map[32].TokenName = "ChromaFormat";
Map[33].TokenName = "RateControlEnable";
Map[34].TokenName = "Bitrate";
Map[35].TokenName = "InitialQP";
Map[36].TokenName = "BasicUnit";
Map[37].TokenName = "ChannelType";
Map[38].TokenName = NULL;
Map[0].Place = &configinput.GopLength;
Map[1].Place = &configinput.no_frames;
Map[2].Place = &configinput.qp0;
Map[3].Place = &configinput.qpN;
Map[4].Place = &configinput.hadamard;
Map[5].Place = &configinput.search_range;
Map[6].Place = &configinput.no_multpred;
Map[7].Place = &configinput.img_width;
Map[8].Place = &configinput.img_height;
Map[9].Place = &configinput.infile;
Map[10].Place = &configinput.infile_header;
Map[11].Place = &configinput.outfile;
Map[12].Place = &configinput.ReconFile;
Map[13].Place = &configinput.TraceFile;
Map[14].Place = &configinput.successive_Bframe;
Map[15].Place = &configinput.qpB;
Map[16].Place = &configinput.InterSearch16x16;
Map[17].Place = &configinput.InterSearch16x8 ;
Map[18].Place = &configinput.InterSearch8x16;
Map[19].Place = &configinput.InterSearch8x8 ;
Map[20].Place = &configinput.rdopt;
Map[21].Place = &configinput.InterlaceCodingOption;
Map[22].Place = &configinput.loop_filter_disable;
Map[23].Place = &configinput.loop_filter_parameter_flag;
Map[24].Place = &configinput.alpha_c_offset;
Map[25].Place = &configinput.beta_offset;
Map[26].Place = &configinput.progressive_frame;
Map[27].Place = &configinput.dct_adaptive_flag;
Map[28].Place = &configinput.slice_row_nr;
Map[29].Place = &configinput.slice_parameter;
Map[30].Place = &configinput.picture_weighting_flag;
Map[31].Place = &configinput.frame_rate_code;
Map[32].Place = &configinput.chroma_format;
Map[33].Place = &configinput.RCEnable;
Map[34].Place = &configinput.bit_rate;
Map[35].Place = &configinput.SeinitialQP;
Map[36].Place = &configinput.basicunit;
Map[37].Place = &configinput.channel_type;
Map[38].Place = NULL;
Map[0].Type = 0;
Map[1].Type = 0;
Map[2].Type = 0;
Map[3].Type = 0;
Map[4].Type = 0;
Map[5].Type = 0;
Map[6].Type = 0;
Map[7].Type = 0;
Map[8].Type = 0;
Map[9].Type = 1;
Map[10].Type = 0;
Map[11].Type = 1;
Map[12].Type = 1;
Map[13].Type = 1;
Map[14].Type = 0;
Map[15].Type = 0;
Map[16].Type = 0;
Map[17].Type = 0;
Map[18].Type = 0;
Map[19].Type = 0;
Map[20].Type = 0;
Map[21].Type = 0;
Map[22].Type = 0;
Map[23].Type = 0;
Map[24].Type = 0;
Map[25].Type = 0;
Map[26].Type = 0;
Map[27].Type = 0;
Map[28].Type = 0;
Map[29].Type = 0;
Map[30].Type = 0;
Map[31].Type = 0;
Map[32].Type = 0;
Map[33].Type = 0;
Map[34].Type = 0;
Map[35].Type = 0;
Map[36].Type = 0;
Map[37].Type = 0;
Map[38].Type = -1;
memset (&configinput, 0, sizeof (InputParameters));
// Process default config file
// Parse the command line
content = GetConfigFileContent (av);
printf ("Parsing Configfile %s", av);
ParseContent (content, (int_32_t)strlen (content));
printf ("\n");
free (content);
printf ("\n");
}
/*
*************************************************************************
* Function: Alocate memory buf, opens file Filename in f, reads contents into
buf and returns buf
* Input:name of config file
* Output:
* Return:
* Attention:
*************************************************************************
*/
char* c_avs_enc::GetConfigFileContent (char *Filename)
{
unsigned FileSize;
FILE *f;
char *buf;
if (NULL == (f = fopen (Filename, "r")))
{
snprintf (errortext, ET_SIZE, "Cannot open configuration file %s.\n", Filename);
error (errortext, 300);
}
if (0 != fseek (f, 0, SEEK_END))
{
snprintf (errortext, ET_SIZE, "Cannot fseek in configuration file %s.\n", Filename);
error (errortext, 300);
}
FileSize = ftell (f);
if (FileSize < 0 || FileSize > 60000)
{
snprintf (errortext, ET_SIZE, "Unreasonable Filesize %d reported by ftell for configuration file %s.\n", FileSize, Filename);
error (errortext, 300);
}
if (0 != fseek (f, 0, SEEK_SET))
{
snprintf (errortext, ET_SIZE, "Cannot fseek in configuration file %s.\n", Filename);
error (errortext, 300);
}
if ((buf = (char*) malloc (FileSize + 1))==NULL)
no_mem_exit("GetConfigFileContent: buf");
// Note that ftell() gives us the file size as the file system sees it. The actual file size,
// as reported by fread() below will be often smaller due to CR/LF to CR conversion and/or
// control characters after the dos EOF marker in the file.
FileSize = (unsigned int)fread (buf, 1, FileSize, f);
buf[FileSize] = '\0';
fclose (f);
return buf;
}
/*
*************************************************************************
* Function: Parses the character array buf and writes global variable input, which is defined in
configfile.h. This hack will continue to be necessary to facilitate the addition of
new parameters through the Map[] mechanism (Need compiler-generated addresses in map[]).
* Input: buf
buffer to be parsed
bufsize
buffer size of buffer
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::ParseContent (char *buf, int_32_t bufsize)
{
char *items[MAX_ITEMS_TO_PARSE];
int_32_t MapIdx;
int_32_t item = 0;
int_32_t InString = 0;
int_32_t InItem = 0;
char *p = buf;
char *bufend = &buf[bufsize];
int_32_t IntContent;
int_32_t i;
// Stage one: Generate an argc/argv-type list in items[], without comments and whitespace.
// This is context insensitive and could be done most easily with lex(1).
while (p < bufend)
{
switch (*p)
{
case 13:
p++;
break;
case '#': // Found comment
*p = '\0'; // Replace '#' with '\0' in case of comment immediately following integer or string
while (*p != '\n' && p < bufend) // Skip till EOL or EOF, whichever comes first
p++;
InString = 0;
InItem = 0;
break;
case '\n':
InItem = 0;
InString = 0;
*p++='\0';
break;
case ' ':
case '\t': // Skip whitespace, leave state unchanged
if (InString)
p++;
else
{ // Terminate non-strings once whitespace is found
*p++ = '\0';
InItem = 0;
}
break;
case '"': // Begin/End of String
*p++ = '\0';
if (!InString)
{
items[item++] = p;
InItem = ~InItem;
}
else
InItem = 0;
InString = ~InString; // Toggle
break;
default:
if (!InItem)
{
items[item++] = p;
InItem = ~InItem;
}
p++;
}
}
item--;
for (i=0; i<item; i+= 3)
{
if (0 > (MapIdx = ParameterNameToMapIndex (items[i])))
{
snprintf (errortext, ET_SIZE, " Parsing error in config file: Parameter Name '%s' not recognized.", items[i]);
error (errortext, 300);
}
if (strcmp ("=", items[i+1]))
{
snprintf (errortext, ET_SIZE, " Parsing error in config file: '=' expected as the second token in each line.");
error (errortext, 300);
}
// Now interprete the Value, context sensitive...
switch (Map[MapIdx].Type)
{
case 0: // Numerical
if (1 != sscanf (items[i+2], "%d", &IntContent))
{
snprintf (errortext, ET_SIZE, " Parsing error: Expected numerical value for Parameter of %s, found '%s'.", items[i], items[i+2]);
error (errortext, 300);
}
* (int_32_t *) (Map[MapIdx].Place) = IntContent;
printf (".");
break;
case 1:
strcpy ((char *) Map[MapIdx].Place, items [i+2]);
printf (".");
break;
default:
assert ("Unknown value type in the map definition of configfile.h");
}
}
input = &inputs;
memcpy (input, &configinput, sizeof (InputParameters));
}
/*
*************************************************************************
* Function:Return the index number from Map[] for a given parameter name.
* Input:parameter name string
* Output:
* Return: the index number if the string is a valid parameter name, \n
-1 for error
* Attention:
*************************************************************************
*/
int_32_t c_avs_enc:: ParameterNameToMapIndex (char *s)
{
int_32_t i = 0;
while (Map[i].TokenName != NULL)
if (0==strcmp (Map[i].TokenName, s))
return i;
else
i++;
return -1;
};
/*
*************************************************************************
* Function:Checks the input parameters for consistency.
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void c_avs_enc::PatchInp ()
{
// consistency check of QPs
input->fixed_picture_qp = 1;
if (input->qp0 > MAX_QP || input->qp0 < MIN_QP)
{
snprintf(errortext, ET_SIZE, "Error input parameter quant_0,check configuration file");
error (errortext, 400);
}
if (input->qpN > MAX_QP || input->qpN < MIN_QP)
{
snprintf(errortext, ET_SIZE, "Error input parameter quant_n,check configuration file");
error (errortext, 400);
}
if (input->qpB > MAX_QP || input->qpB < MIN_QP)
{
snprintf(errortext, ET_SIZE, "Error input parameter quant_B,check configuration file");
error (errortext, 400);
}
// consistency check no_multpred
if (input->no_multpred<1) input->no_multpred=1;
// consistency check size information
if (input->img_height % 16 != 0 || input->img_width % 16 != 0)
{
input->stuff_height = input->img_height;
input->stuff_width = input->img_width;
if (input->img_height %16 != 0 )
{
input->stuff_height = input->img_height;
input->img_height = input->img_height + 16 - (input->img_height%16);
configinput.img_height = input->img_height;
configinput.stuff_height = input->stuff_height;
}
//xzhao 20080709
if (input->img_width %16 != 0 )
{
input->stuff_width = input->img_width;
input->img_width = input->img_width + 16 - (input->img_width%16);
configinput.img_width = input->img_width;
configinput.stuff_width = input->stuff_width;
}
}
else
{
//if(input->img_height-input->stuff_height>16)
input->stuff_height = input->img_height;
//if(input->img_width-input->stuff_width>16)
input->stuff_width = input->img_width;
}
// check range of filter offsets
if (input->alpha_c_offset > 6 || input->alpha_c_offset < -6)
{
snprintf(errortext, ET_SIZE, "Error input parameter LFAlphaC0Offset, check configuration file");
error (errortext, 400);
}
if (input->beta_offset > 6 || input->beta_offset < -6)
{
snprintf(errortext, ET_SIZE, "Error input parameter LFBetaOffset, check configuration file");
error (errortext, 400);
}
// Open Files
if (strlen (input->infile) > 0 && (p_in=fopen(input->infile,"rb"))==NULL)
{
snprintf(errortext, ET_SIZE, "Input file %s does not exist",input->infile);
}
if (strlen (input->ReconFile) > 0 && (p_rec=fopen(input->ReconFile, "wb"))==NULL)
{
snprintf(errortext, ET_SIZE, "Error open file %s", input->ReconFile);
}
#ifdef _OUTPUT_DEC_IMG_
if (strlen (input->DecRecFile) > 0 && (p_org_dec=fopen(input->DecRecFile, "wb"))==NULL)
{
snprintf(errortext, ET_SIZE, "Error open file %s", input->DecRecFile);
}
#endif
if (strlen (input->TraceFile) > 0 && (p_trace=fopen(input->TraceFile,"w"))==NULL)
{
snprintf(errortext, ET_SIZE, "Error open file %s", input->TraceFile);
}
if (input->slice_row_nr==0)
{
input->slice_row_nr=input->img_height/16;
}
// Set block sizes
input->blc_size[0][0]=16;
input->blc_size[0][1]=16;
input->blc_size[1][0]=16;
input->blc_size[1][1]=16;
input->blc_size[2][0]=16;
input->blc_size[2][1]= 8;
input->blc_size[3][0]= 8;
input->blc_size[3][1]=16;
input->blc_size[4][0]= 8;
input->blc_size[4][1]= 8;
input->blc_size[8][0]= 8;
input->blc_size[8][1]= 8;
if (input->slice_row_nr==0)
{
input->slice_row_nr=input->img_height/16;
}
}
| [
"zhihang.wang@6c8d3a4c-d4d5-11dd-b6b4-918b84bbd919"
] | [
[
[
1,
520
]
]
] |
b3a231f53e9bdfaa6b86397670816596d16bb773 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/UIButton.inl | 7c758f7216b22561e0e2a5c76c8aade4eb73097e | [] | no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 811 | inl | namespace Halak
{
UIButton::State UIButton::GetCurrentState() const
{
return currentState;
}
UIWindow* UIButton::GetNormalWindow() const
{
return normalWindow;
}
UIWindow* UIButton::GetPushedWindow() const
{
return pushedWindow;
}
UIWindow* UIButton::GetHoveringWindow() const
{
return hoveringWindow;
}
UIWindow* UIButton::GetCurrentWindow() const
{
return currentWindow;
}
bool UIButton::GetHideInactives() const
{
return hideInactives;
}
bool UIButton::GetStateSizeReferenced() const
{
return stateSizeReferenced;
}
void UIButton::SetStateSizeReferenced(bool value)
{
stateSizeReferenced = value;
}
} | [
"[email protected]"
] | [
[
[
1,
42
]
]
] |
9cfcd4c3d9544ad1517e841be82dce0a18a9f1d2 | c70941413b8f7bf90173533115c148411c868bad | /plugins/SwfPlugin/include/vtxswfFontParser.h | c5fe9556d6700052cab53c7c57aaa787d554a08e | [] | no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,973 | h | /*
-----------------------------------------------------------------------------
This source file is part of "vektrix"
(the rich media and vector graphics rendering library)
For the latest info, see http://www.fuse-software.com/
Copyright (c) 2009-2010 Fuse-Software (tm)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef __vtxswfFontParser_H__
#define __vtxswfFontParser_H__
#include "vtxswf.h"
#include "vtxswfParserTypes.h"
namespace vtx { namespace swf {
//-----------------------------------------------------------------------
class FontParser
{
public:
void handleDefineFont(const TagTypes& tag_type, const uint& tag_length, SwfParser* parser);
protected:
// -> FLASH
SHAPE mFlashGlyph;
void writeGlyphContours(GlyphResource* glyph_resource);
};
//-----------------------------------------------------------------------
}}
#endif
| [
"fixxxeruk@9773a11d-1121-4470-82d2-da89bd4a628a",
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a"
] | [
[
[
1,
28
],
[
34,
34
],
[
38,
38
]
],
[
[
29,
33
],
[
35,
37
],
[
39,
51
]
]
] |
a58372368f68c257d4f5520163a37a1c6bf4647f | 718dc2ad71e8b39471b5bf0c6d60cbe5f5c183e1 | /soft micros/Codigo/codigo portable/Vista/DiagramaDeNavegacion/Boxes/BoxPropiedadVF.hpp | f01e5ada14b7f550d1bec4e9dbe92315bd6fb129 | [] | no_license | jonyMarino/microsdhacel | affb7a6b0ea1f4fd96d79a04d1a3ec3eaa917bca | 66d03c6a9d3a2d22b4d7104e2a38a2c9bb4061d3 | refs/heads/master | 2020-05-18T19:53:51.301695 | 2011-05-30T20:40:24 | 2011-05-30T20:40:24 | 34,532,512 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 2,861 | hpp | #ifndef _BOX_PROPIEDAD_VF_HPP
#define _BOX_PROPIEDAD_VF_HPP
#include "Box.hpp"
#include "Propiedades/PropiedadGetterVisual/PropGetterVisualVF.hpp"
#include "Propiedades/ConstructorPropiedadGetter.hpp"
#include "PE/include/PE_Types.h"
//#include "BoxPropiedadEntradaCondicional.hpp"
class BoxPropiedadVF:public Box{
public:
BoxPropiedadVF();
virtual ~BoxPropiedadVF();
/*
** ===================================================================
** Method : refresh
** Description : Funcion para refrescar los valores del Box
** ===================================================================
*/
void refresh();
/*
** ===================================================================
** Method : procesarTecla
** Description : Funcion que procesa la tecla del Box
** Returns: - STAY_BOX Sigue el mismo Box (si la tecla es de salida
** devuelve NULL ya que no tiene información del siguiente Box)
** - EXIT_BOX si el Box esta en condición de salida.
** - Constructor del siguiente box
** ===================================================================
*/
virtual Box * procesarTecla(uchar tecla,TEstadoBox& estado);
void printDescripcion(const char * str, OutputStream& os);
protected:
void setPropiedad(PropGetterVisualVF& propiedad,bool isIncrementable);
PropGetterVisualVF * getPropiedad();
private:
PropGetterVisualVF * propiedad;
bool isIncrementable;
bool save;
friend struct BoxPropiedadVFFactory;
friend struct BoxPropGetterVFFactory;
friend struct BoxPropiedadEntradaCondicionalFactory;
friend struct BoxPropGetterEntradaCondicionalFactory;
};
struct ConstructorBoxPropiedadVF{
struct ConstructorBox super;
const struct ConstructorPropGetterVisualVF * propiedad;
};
struct BoxPropiedadVFFactory:public BoxFactory{
virtual Box& getBox(const void*args,void*obj,uchar numObjeto)const{
BoxPropiedadVF&b = *new BoxPropiedadVF();
struct ConstructorBoxPropiedadVF * c = (struct ConstructorBoxPropiedadVF *)args;
b.setPropiedad(*(PropGetterVisualVF*)&c->propiedad->getPropiedad(obj,numObjeto),TRUE);
return b;
}
};
extern const struct BoxPropiedadVFFactory boxPropiedadVFFactory;
struct BoxPropGetterVFFactory:public BoxFactory{
virtual Box& getBox(const void*args,void*obj,uchar numObjeto)const{
BoxPropiedadVF &b = *new BoxPropiedadVF();
struct ConstructorBoxPropiedadVF * c = (struct ConstructorBoxPropiedadVF *)args;
b.setPropiedad(*(PropGetterVisualVF*)&c->propiedad->getPropiedad(obj,numObjeto),FALSE);
return b;
}
};
extern const struct BoxPropGetterFactory boxPropGetterFactory;
#endif | [
"nicopimen@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549"
] | [
[
[
1,
75
]
]
] |
a5394cf6b0ad21bb3a11ee9e1b8948ec01241acd | c1b7571589975476405feab2e8b72cdd2a592f8f | /paradebot10/TaskTemplate.h | a7f622ab5f742bf0035a5e2dec36879bdc983c07 | [] | no_license | chopshop-166/frc-2010 | ea9cd83f85c9eb86cc44156f21894410a9a4b0b5 | e15ceff05536768c29fad54fdefe65dba9a5fab5 | refs/heads/master | 2021-01-21T11:40:07.493930 | 2010-12-10T02:04:05 | 2010-12-10T02:04:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,412 | h | /*******************************************************************************
* Project : Framework
* File Name : TaskTemplate.h
* Owner : Software Group (FIRST Chopshop Team 166)
* Creation Date : January 18, 2010
* File Description : Template header file for tasks, with template functions
*******************************************************************************/
/*----------------------------------------------------------------------------*/
/* Copyright (c) MHS Chopshop Team 166, 2010. All Rights Reserved. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "WPILib.h"
#include "Robot.h"
//
// This constant defines how often we want this task to run in the form
// of miliseconds. Max allowed time is 999 miliseconds.
// You should rename this when you copy it into a new file
// <<CHANGEME>>
#define TEMPLATE_CYCLE_TIME (10) // 10ms
// Rename this, too, or you'll run into collisions
// <<CHANGEME>>
class Template166 : public Team166Task
{
public:
// task constructor
Template166(void);
// task destructor
virtual ~Template166(void);
// Main function of the task
virtual int Main(int a2, int a3, int a4, int a5,
int a6, int a7, int a8, int a9, int a10);
private:
// Any variables that the task has as members go here
// <<CHANGEME>>
};
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
1
],
[
3,
11
],
[
14,
19
],
[
22,
24
],
[
26,
42
],
[
44,
44
]
],
[
[
2,
2
],
[
12,
13
],
[
20,
21
],
[
25,
25
],
[
43,
43
]
]
] |
75bd1bbc515e82f8093d47907f4297d31eaf1c65 | 155c4955c117f0a37bb9481cd1456b392d0e9a77 | /Tessa/TessaInstructions/TessaInstruction.cpp | 51cfa24a870761a36a260693d415939967a3a703 | [] | no_license | zwetan/tessa | 605720899aa2eb4207632700abe7e2ca157d19e6 | 940404b580054c47f3ced7cf8995794901cf0aaa | refs/heads/master | 2021-01-19T19:54:00.236268 | 2011-08-31T00:18:24 | 2011-08-31T00:18:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,879 | cpp |
#include "TessaInstructionHeader.h"
#include "BasicBlock.h" // To avoid circular dependencies
namespace TessaInstructions {
TessaInstruction::TessaInstruction()
: TessaValue()
{
}
TessaInstruction::TessaInstruction(BasicBlock* basicBlockToInsert)
: TessaValue()
{
basicBlockToInsert->addInstruction(this);
}
bool TessaInstruction::isInstruction() {
return true;
}
bool TessaInstruction::modifiesMemory() {
return false;
}
bool TessaInstruction::isCondition() {
return false;
}
bool TessaInstruction::isBinary() {
return false;
}
bool TessaInstruction::isUnary() {
return false;
}
bool TessaInstruction::isLabel() {
return false;
}
bool TessaInstruction::isPhi() {
return false;
}
bool TessaInstruction::isArrayAccess() {
return false;
}
bool TessaInstruction::isReturn() {
return false;
}
bool TessaInstruction::isBranch() {
return false;
}
bool TessaInstruction::isConditionalBranch() {
return false;
}
bool TessaInstruction::isUnconditionalBranch() {
return false;
}
bool TessaInstruction::isParameter() {
return false;
}
bool TessaInstruction::isCall() {
return false;
}
bool TessaInstruction::isCallStatic() {
return false;
}
bool TessaInstruction::isCallVirtual() {
return false;
}
bool TessaInstruction::isInlineMethod() {
return false;
}
bool TessaInstruction::isConstruct() {
return false;
}
bool TessaInstruction::isNewObject() {
return false;
}
bool TessaInstruction::isNewArray() {
return false;
}
bool TessaInstruction::isConstructProperty() {
return false;
}
bool TessaInstruction::isCoerce() {
return false;
}
bool TessaInstruction::isConvert() {
return false;
}
bool TessaInstruction::modifiesScopeStack() {
return false;
}
bool TessaInstruction::isGetProperty() {
return false;
}
bool TessaInstruction::isSetProperty() {
return false;
}
bool TessaInstruction::isInitProperty() {
return false;
}
bool TessaInstruction::isPropertyAccess() {
return false;
}
bool TessaInstruction::isLocalVariableAccess() {
return false;
}
bool TessaInstruction::isSlotAccess() {
return false;
}
bool TessaInstruction::isConstantValue() {
return false;
}
bool TessaInstruction::isSuper() {
return false;
}
bool TessaInstruction::isConstructSuper() {
return false;
}
bool TessaInstruction::isCallSuper() {
return false;
}
bool TessaInstruction::isThis() {
return false;
}
bool TessaInstruction::isTypeOf() {
return false;
}
bool TessaInstruction::isSwitch() {
return false;
}
bool TessaInstruction::isCase() {
return false;
}
bool TessaInstruction::isLoadVirtualMethod() {
return false;
}
bool TessaInstruction::isNewActivation() {
return false;
}
bool TessaInstruction::isArrayOfInstructions() {
return false;
}
bool TessaInstruction::hasSideEffect() {
return false;
}
TessaInstruction* TessaInstruction::clone() {
TessaAssert (false);
printf("Wrong");
return this;
}
void TessaInstruction::print() {
TessaAssertMessage(false, "Should never print base tessa instruction");
}
string TessaInstruction::getPrintPrefix() {
// For some reason can't add ":" string at the end of the first line
char buffer[32];
VMPI_snprintf(buffer, sizeof(buffer), "%c%d :", ReferenceChar, getValueId());
return buffer;
}
string TessaInstruction::getOperandString() {
char buffer[32];
VMPI_snprintf(buffer, sizeof(buffer), "%c%d", ReferenceChar, getValueId());
return buffer;
}
BasicBlock* TessaInstruction::getInBasicBlock() {
return inBasicBlock;
}
void TessaInstruction::setInBasicBlock(BasicBlock* basicBlock) {
this->inBasicBlock = basicBlock;
}
/***
* follows the forward chain to the end
*/
TessaInstruction* TessaInstruction::resolve() {
if (forwardInstruction == NULL) {
return this;
} else {
return forwardInstruction->resolve();
}
}
void TessaInstruction::setForwardedInstruction(TessaInstruction* instruction) {
this->forwardInstruction = instruction;
}
/***
* Follows the forward chain only ONCE
*/
TessaInstruction* TessaInstruction::getForwardedInstruction() {
return this->forwardInstruction;
}
bool TessaInstruction::isBlockTerminator() {
return isReturn() || isBranch() || isSwitch();
}
std::string TessaInstruction::toString() {
return getOperandString();
}
TessaInstruction* TessaInstruction::getClonedValue(TessaValue* originalValue, MMgc::GCHashtable* originalToCloneMap) {
TessaInstruction* clonedValue = (TessaInstruction*) originalToCloneMap->get(originalValue);
AvmAssert(clonedValue != NULL);
return clonedValue;
}
TessaInstruction* TessaInstruction::clone(MMgc::GC* gc, MMgc::GCHashtable* originalToCloneMap, TessaVM::BasicBlock* insertCloneAtEnd) {
TessaAssertMessage(false, "Should not be cloning in TessaInstructions");
return this;
}
List<TessaValue*, LIST_GCObjects>* TessaInstruction::getOperands(MMgc::GC* gc) {
AvmAssertMsg(false, "No operands on basic instruction\n");
return NULL;
}
List<TessaInstruction*, LIST_GCObjects>* TessaInstruction::getOperandsAsInstructions(MMgc::GC* gc) {
List<TessaInstruction*, LIST_GCObjects>* instructionList = new (gc) List<TessaInstruction*, LIST_GCObjects>(gc);
List<TessaValue*, LIST_GCObjects>* operandList = getOperands(gc);
for (uint32_t i = 0; i < operandList->size(); i++) {
TessaValue* currentValue = operandList->get(i);
if (currentValue->isInstruction()) {
instructionList->add(currentValue->toInstruction());
} else {
AvmAssert(false);
}
}
return instructionList;
}
}; | [
"[email protected]"
] | [
[
[
1,
278
]
]
] |
4b25eaa6ad8b604702f1a1a00721df084ad2df8c | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/framework/XMLValidator.cpp | 9bfa690d07f7b82865488a911b2ddcb8eef1cf6a | [
"Apache-2.0"
] | permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,621 | cpp | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* $Log: XMLValidator.cpp,v $
* Revision 1.8 2004/09/08 13:55:59 peiyongz
* Apache License Version 2.0
*
* Revision 1.7 2004/01/09 04:39:56 knoaman
* Use a global static mutex for locking when creating local static mutexes instead of compareAndSwap.
*
* Revision 1.6 2003/12/24 15:24:13 cargilld
* More updates to memory management so that the static memory manager.
*
* Revision 1.5 2003/12/17 00:18:34 cargilld
* Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
*
* Revision 1.4 2003/05/15 18:26:07 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.3 2003/03/09 16:38:04 peiyongz
* PanicHandler
*
* Revision 1.2 2002/11/04 15:00:21 tng
* C++ Namespace Support.
*
* Revision 1.1.1.1 2002/02/01 22:21:52 peiyongz
* sane_include
*
* Revision 1.13 2001/11/30 22:18:18 peiyongz
* cleanUp function made member function
* cleanUp object moved to file scope
* double mutex lock removed
*
* Revision 1.12 2001/11/28 20:32:49 tng
* Do not increment the error count if it is a warning.
*
* Revision 1.11 2001/10/24 23:46:52 peiyongz
* [Bug 4342] fix the leak.
*
* Revision 1.10 2001/06/04 21:07:34 jberry
* Increment scanner error count from schema validator, not just in scanner itself.
*
* Revision 1.9 2001/05/11 13:25:33 tng
* Copyright update.
*
* Revision 1.8 2001/05/03 19:08:58 knoaman
* Support Warning/Error/FatalError messaging.
* Validity constraints errors are treated as errors, with the ability by user to set
* validity constraints as fatal errors.
*
* Revision 1.7 2001/03/21 21:56:02 tng
* Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar.
*
* Revision 1.6 2000/03/28 19:43:17 roddey
* Fixes for signed/unsigned warnings. New work for two way transcoding
* stuff.
*
* Revision 1.5 2000/03/02 19:54:25 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.4 2000/02/06 07:47:49 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 1999/12/08 00:15:06 roddey
* Some small last minute fixes to get into the 3.0.1 build that is going to be
* going out anyway for platform fixes.
*
* Revision 1.2 1999/12/02 19:02:56 roddey
* Get rid of a few statically defined XMLMutex objects, and lazy eval them
* using atomic compare and swap. I somehow let it get by me that we don't
* want any static/global objects at all.
*
* Revision 1.1.1.1 1999/11/09 01:08:37 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:44:40 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/util/Mutexes.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLRegisterCleanup.hpp>
#include <xercesc/internal/XMLScanner.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local static functions
// ---------------------------------------------------------------------------
static XMLMutex* sMsgMutex = 0;
static XMLRegisterCleanup msgLoaderCleanup;
static XMLMsgLoader* sMsgLoader = 0;
static XMLRegisterCleanup validatorMutexCleanup;
//
// We need to fault in this mutex. But, since its used for synchronization
// itself, we have to do this the low level way using a compare and swap.
//
static XMLMutex& gValidatorMutex()
{
if (!sMsgMutex)
{
XMLMutexLock lockInit(XMLPlatformUtils::fgAtomicMutex);
if (!sMsgMutex)
{
sMsgMutex = new XMLMutex;
validatorMutexCleanup.registerCleanup(XMLValidator::reinitMsgMutex);
}
}
return *sMsgMutex;
}
static XMLMsgLoader& getMsgLoader()
{
if (!sMsgLoader)
{
// Lock the mutex
XMLMutexLock lockInit(&gValidatorMutex());
if (!sMsgLoader)
{
sMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgValidityDomain);
if (!sMsgLoader)
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
//
// Register this XMLMsgLoader for cleanup at Termination.
//
msgLoaderCleanup.registerCleanup(XMLValidator::reinitMsgLoader);
}
}
return *sMsgLoader;
}
// ---------------------------------------------------------------------------
// XMLValidator: Error emitting methods
// ---------------------------------------------------------------------------
//
// These methods are called whenever the scanner wants to emit an error.
// It handles getting the message loaded, doing token replacement, etc...
// and then calling the error handler, if its installed.
//
void XMLValidator::emitError(const XMLValid::Codes toEmit)
{
// Bump the error count if it is not a warning
if (XMLValid::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
fScanner->incrementErrorCount();
// Call error reporter if we have one
if (fErrorReporter)
{
// Load the message into a local for display
const unsigned int msgSize = 1023;
XMLCh errText[msgSize + 1];
// load the text
if (!getMsgLoader().loadMsg(toEmit, errText, msgSize))
{
// <TBD> Probably should load a default msg here
}
//
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
//
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr->getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgValidityDomain
, XMLValid::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (((XMLValid::isError(toEmit) && fScanner->getValidationConstraintFatal())
|| XMLValid::isFatal(toEmit))
&& fScanner->getExitOnFirstFatal()
&& !fScanner->getInException())
{
throw toEmit;
}
}
void XMLValidator::emitError(const XMLValid::Codes toEmit
, const XMLCh* const text1
, const XMLCh* const text2
, const XMLCh* const text3
, const XMLCh* const text4)
{
// Bump the error count if it is not a warning
if (XMLValid::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
fScanner->incrementErrorCount();
// Call error reporter if we have one
if (fErrorReporter)
{
//
// Load the message into alocal and replace any tokens found in
// the text.
//
const unsigned int maxChars = 2047;
XMLCh errText[maxChars + 1];
// load the text
if (!getMsgLoader().loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, fScanner->getMemoryManager()))
{
// <TBD> Should probably load a default message here
}
//
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
//
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr->getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgValidityDomain
, XMLValid::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (((XMLValid::isError(toEmit) && fScanner->getValidationConstraintFatal())
|| XMLValid::isFatal(toEmit))
&& fScanner->getExitOnFirstFatal()
&& !fScanner->getInException())
{
throw toEmit;
}
}
void XMLValidator::emitError(const XMLValid::Codes toEmit
, const char* const text1
, const char* const text2
, const char* const text3
, const char* const text4)
{
// Bump the error count if it is not a warning
if (XMLValid::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
fScanner->incrementErrorCount();
// Call error reporter if we have one
if (fErrorReporter)
{
//
// Load the message into alocal and replace any tokens found in
// the text.
//
const unsigned int maxChars = 2047;
XMLCh errText[maxChars + 1];
// load the text
if (!getMsgLoader().loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, fScanner->getMemoryManager()))
{
// <TBD> Should probably load a default message here
}
//
// Create a LastExtEntityInfo structure and get the reader manager
// to fill it in for us. This will give us the information about
// the last reader on the stack that was an external entity of some
// sort (i.e. it will ignore internal entities.
//
ReaderMgr::LastExtEntityInfo lastInfo;
fReaderMgr->getLastExtEntityInfo(lastInfo);
fErrorReporter->error
(
toEmit
, XMLUni::fgValidityDomain
, XMLValid::errorType(toEmit)
, errText
, lastInfo.systemId
, lastInfo.publicId
, lastInfo.lineNumber
, lastInfo.colNumber
);
}
// Bail out if its fatal an we are to give up on the first fatal error
if (((XMLValid::isError(toEmit) && fScanner->getValidationConstraintFatal())
|| XMLValid::isFatal(toEmit))
&& fScanner->getExitOnFirstFatal()
&& !fScanner->getInException())
{
throw toEmit;
}
}
// ---------------------------------------------------------------------------
// XMLValidator: Hidden Constructors
// ---------------------------------------------------------------------------
XMLValidator::XMLValidator(XMLErrorReporter* const errReporter) :
fBufMgr(0)
, fErrorReporter(errReporter)
, fReaderMgr(0)
, fScanner(0)
{
}
// -----------------------------------------------------------------------
// Notification that lazy data has been deleted
// -----------------------------------------------------------------------
void XMLValidator::reinitMsgMutex()
{
delete sMsgMutex;
sMsgMutex = 0;
}
// -----------------------------------------------------------------------
// Reinitialise the message loader
// -----------------------------------------------------------------------
void XMLValidator::reinitMsgLoader()
{
delete sMsgLoader;
sMsgLoader = 0;
}
XERCES_CPP_NAMESPACE_END
| [
"[email protected]"
] | [
[
[
1,
371
]
]
] |
aa0419b5857d875f6366f6122f42998b5fd1d781 | 68282fb4d720ff76e2414a2646c8c5d2bb5aef2b | /vsoz/fn71112/logger.h | 73e92d57cda5b786fe23dccca0cf70fffd5bc15d | [] | no_license | marvellouz/fmi_projects | d0e67a1386c059bf5edadc3bd0336c12e7f4117b | b25b679e411456e91d2002b7e2c3be10b519b519 | refs/heads/master | 2021-01-17T14:00:24.529519 | 2011-10-24T18:00:54 | 2011-10-24T18:00:54 | 486,223 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 582 | h | #ifndef LOGGER_H
#define LOGGER_H
#include <iostream>
template <class Container>
std::ostream& log(Container const& container)
{
for (typename Container::const_iterator it = container.begin();
it != container.end();
it++)
{
std::clog << ' ' << *it;
}
return std::clog;
}
#ifdef LOGGING
# define LOG_CONTAINER(containerName, msg) \
std::clog << msg << std::endl; \
log(containerName) << std::endl
# define LOG_MSG(msg) \
std::clog << msg << endl
#else
# define LOG_CONTAINER(containerName, msg)
# define LOG_MSG(msg)
#endif
#endif
| [
"[email protected]"
] | [
[
[
1,
29
]
]
] |
d3b2303a71bea4f9aa9f09308390f18c1dccffda | ae2adbf262d2938684664e3195a3b71934f4448c | /trabalho 02/ConexComponent.h | 8ae671e8ed2ff94ee88a85475879bbad602223a3 | [] | no_license | cmdalbem/saint-ende | e5e251a0b274e40c02233ed4963ca0c619ed31eb | b5aeeea978108d1e906fd168c0c24618a3d35882 | refs/heads/master | 2020-07-09T08:21:07.963803 | 2009-12-21T17:32:25 | 2009-12-21T17:32:25 | 32,224,226 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,155 | h | #ifndef _CONEXCOMPONENT_H_
#define _CONEXCOMPONENT_H_
#include "bib/EasyBMP.h"
#include "Imagem.h"
class ConexComponent
{
private:
int area;
int perimeter;
int xo, yo; //um ponto qualquer pertencente à linha de borda do componente
int x1, x2, y1, y2; //coordenadas da bounding box
bool isMarkedPix(int x, int y, Imagem *image);
bool known;
public:
ConexComponent(int x, int y, Imagem *image);
~ConexComponent();
// pegadores
int getX1() {return x1;}
int getX2() {return x2;}
int getY1() {return y1;}
int getY2() {return y2;}
// FUNÇÕES
void findBoundingBox(int x, int y, Imagem *image);
void drawBoundingBox(Imagem *image);
void drawBoundingFillBox(Imagem *image);
void findArea(int x, int y, Imagem *image);
double getCompacity();
// Funções Específicas de Componentes
bool isKnown() {return known;}
bool isClock(Imagem *image);
const char* tellTimeOfClock(Imagem *image);
};
#endif
| [
"ninja.dalbem@7df66274-e10c-11de-a155-4d945b6d75ec",
"lfzawacki@7df66274-e10c-11de-a155-4d945b6d75ec",
"[email protected]@7df66274-e10c-11de-a155-4d945b6d75ec"
] | [
[
[
1,
4
],
[
6,
10
],
[
13,
18
],
[
20,
20
],
[
22,
23
],
[
31,
32
],
[
34,
34
],
[
36,
36
],
[
38,
38
],
[
40,
40
],
[
42,
46
],
[
49,
50
],
[
53,
60
]
],
[
[
5,
5
],
[
11,
12
],
[
21,
21
],
[
24,
24
],
[
33,
33
],
[
35,
35
],
[
37,
37
],
[
39,
39
],
[
41,
41
],
[
51,
52
]
],
[
[
19,
19
],
[
25,
30
],
[
47,
48
]
]
] |
42f844d763cf07f9f1dfc1f1ac46a57876a5a77d | 1081941fa4ea44f77ab76b325f7e41c4e89846c1 | /Utils.h | d5b750b6efbc64fa33465c4e8575461940d5eb19 | [] | no_license | Wu-Lab/Samo | da1bc7ccd78ebc0146cc64bed5a13b40fd868bda | 7f16cdf245f66686db4e6fb38df6625c41ede2de | refs/heads/master | 2020-07-09T08:54:06.531097 | 2010-12-29T08:57:12 | 2010-12-29T08:57:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,698 | h |
#ifndef __UTILS_H
#define __UTILS_H
#include <new>
#include <ctime>
#include <vector>
#include <iosfwd>
#include <iterator>
#include <boost/shared_ptr.hpp>
using namespace std;
namespace std {
namespace tr1 = ::boost;
}
class Timer {
static int m_instance_num;
int m_id;
clock_t m_start, m_finish;
bool m_running;
double m_duration;
char m_description[80];
public:
Timer() { m_id = m_instance_num++; }
void begin(const char *description);
void end();
void pause();
void resume();
double time() { return m_duration; }
};
class Logger {
static bool m_logging;
static int m_log_level;
static const int m_log_level_error;
static const int m_log_level_warning;
static const int m_log_level_info;
static const int m_log_level_verbose;
static const int m_log_level_debug;
static Timer m_timer[10];
public:
static int log_level() { return m_log_level; }
static int log_level_error() { return m_log_level_error; }
static int log_level_warning() { return m_log_level_warning; }
static int log_level_info() { return m_log_level_info; }
static int log_level_verbose() { return m_log_level_verbose; }
static int log_level_debug() { return m_log_level_debug; }
static Timer &timer(int i) { return m_timer[i]; }
static void error(const char *format, ...);
static void warning(const char *format, ...);
static void info(const char *format, ...);
static void verbose(const char *format, ...);
static void status(const char *format, ...);
static void debug(const char *format, ...);
static void print(int level, FILE *fp, const char *prompt, const char *format, ...);
static void println(int level, FILE *fp, const char *prompt, const char *format, ...);
static void setLogLevel(int level);
static void enableLogging();
static void disableLogging();
static bool isDebug() { return (m_log_level >= m_log_level_debug); }
static void beginTimer(int i, const char *description);
static void endTimer(int i);
static void pauseTimer(int i);
static void resumeTimer(int i);
private:
static void _print(int level, FILE *fp, const char *prompt, const char *format, va_list argptr);
static void _println(int level, FILE *fp, const char *prompt, const char *format, va_list argptr);
};
// something for using with STL
class StandardNewDelete {
public:
// normal new/delete
static void *operator new(std::size_t size) throw(std::bad_alloc)
{ return ::operator new(size); }
static void operator delete(void *pMemory) throw()
{ ::operator delete(pMemory); }
// placement new/delete
static void *operator new(std::size_t size, void *ptr) throw()
{ return ::operator new(size, ptr); }
static void operator delete(void *pMemory, void *ptr) throw()
{ ::operator delete(pMemory, ptr); }
// nothrow new/delete
static void *operator new(std::size_t size, const std::nothrow_t &nt) throw()
{ return ::operator new(size, nt); }
static void operator delete(void *pMemory, const std::nothrow_t &) throw()
{ ::operator delete(pMemory); }
// debug new/delete
#ifdef _DEBUG
static void *operator new(std::size_t size, int, const char *, int) throw(std::bad_alloc)
{ return operator new(size); }
static void operator delete(void *pMemory, int, const char *, int) throw()
{ operator delete(pMemory); }
#endif // _DEBUG
};
class NoThrowNewDelete : public StandardNewDelete {
public:
using StandardNewDelete::operator new;
using StandardNewDelete::operator delete;
// nothrow new/delete
static void *operator new(std::size_t size, const std::nothrow_t &) throw()
{ return operator new(size); }
static void operator delete(void *pMemory, const std::nothrow_t &) throw()
{ operator delete(pMemory); }
};
struct DeletePtr {
template<typename T>
void operator()(const T* ptr) const { delete ptr; }
};
struct DeleteAll {
template<typename T>
void operator()(const T& container) {
for_each(container.begin(), container.end(), DeletePtr());
}
};
struct DeleteAll_Clear {
template<typename T>
void operator()(T& container) {
for_each(container.begin(), container.end(), DeletePtr());
container.clear();
}
};
template<typename T>
ostream &operator<<(ostream &os, const vector<T> &v)
{
copy(v.begin(), v.end(), ostream_iterator<T>(os, " "));
return os;
};
// functions for string
void string_replace(string &str, const string &src, const string &dst);
void string_tokenize(vector<string> &tokens, const string &str, const string &delimiters, bool empty_field = true);
string int2str(int num);
int str2int(const string &str);
#endif // __UTILS_H
| [
"wulingyun@localhost"
] | [
[
[
1,
173
]
]
] |
ee939149fb8e7156afb67f7cf64056955ce65501 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/Tools/LayoutEditor/EditorWidgets.h | 8c10da0c92a772c91419b24329ae8dc1995b0bd4 | [] | no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,565 | h | #ifndef __EDITOR_WIDGETS_H__
#define __EDITOR_WIDGETS_H__
#include <sstream>
#include "WidgetContainer.h"
#include "SettingsSector.h"
namespace tools
{
typedef MyGUI::delegates::CMultiDelegate0 Event_ChangeWidgets;
typedef std::vector<WidgetContainer*> VectorWidgetContainer;
typedef MyGUI::Enumerator<VectorWidgetContainer> EnumeratorWidgetContainer;
class EditorWidgets :
public MyGUI::Singleton<EditorWidgets>
{
public:
EditorWidgets();
virtual ~EditorWidgets();
void initialise();
void shutdown();
bool load(const MyGUI::UString& _fileName);
bool save(const MyGUI::UString& _fileName);
void clear();
void loadxmlDocument(MyGUI::xml::Document* doc, bool _test = false);
MyGUI::xml::Document* savexmlDocument();
WidgetContainer* find(MyGUI::Widget* _widget);
WidgetContainer* find(const std::string& _name);
void add(WidgetContainer* _container);
void remove(MyGUI::Widget* _widget);
void remove(WidgetContainer* _container);
bool tryToApplyProperty(MyGUI::Widget* _widget, const std::string& _key, const std::string& _value, bool _test = false);
void invalidateWidgets();
EnumeratorWidgetContainer getWidgets();
SettingsSector* getSector(const MyGUI::UString& _sectorName);
int getNextGlobalCounter();
std::string getSkinReplace(const std::string& _skinName);
Event_ChangeWidgets eventChangeWidgets;
private:
WidgetContainer* _find(MyGUI::Widget* _widget, const std::string& _name, std::vector<WidgetContainer*> _widgets);
void parseWidget(MyGUI::xml::ElementEnumerator& _widget, MyGUI::Widget* _parent, bool _test = false);
void serialiseWidget(WidgetContainer* _container, MyGUI::xml::ElementPtr _node, bool _compatibility = false);
void loadIgnoreParameters(MyGUI::xml::ElementPtr _node, const std::string& _file, MyGUI::Version _version);
void loadSkinReplace(MyGUI::xml::ElementPtr _node, const std::string& _file, MyGUI::Version _version);
void notifyFrameStarted(float _time);
void loadSector(MyGUI::xml::ElementPtr _sectorNode);
void saveSectors(MyGUI::xml::ElementPtr _rootNode);
void destroyAllSectors();
void destroyAllWidgets();
private:
int mGlobalCounter;
bool mWidgetsChanged;
typedef std::vector<std::string> VectorString;
VectorString mIgnoreParameters;
VectorSettingsSector mSettings;
VectorWidgetContainer mWidgets;
typedef std::map<std::string, std::string> MapString;
MapString mSkinReplaces;
};
} // namespace tools
#endif // __EDITOR_WIDGETS_H__
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
] | [
[
[
1,
81
]
]
] |
5bb24b926f86cca1912f2484b1e45e0640e76d4b | b6e0e894be10de33532969a67b9e278753d392f9 | /timelabel.cpp | aaa7bcc080e505a431f40a7ec6db53dd74def350 | [] | no_license | faellsa/teachersmanagement | 4f9ef70ec91b1237d45cd2b7c71afdd2bc183e0e | 15f79a11eadac2e6c811fe27fbf727faa27d32c3 | refs/heads/master | 2020-05-16T19:01:29.339150 | 2011-05-21T09:46:30 | 2011-05-21T09:46:30 | 32,401,290 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 908 | cpp | #include "timelabel.h"
#include <QTime>
#include <QDate>
TimeLabel::TimeLabel(QWidget* parent)
: QLabel(parent)
{
setDayOfTime();
connect(&m_Timer, SIGNAL(timeout()), this, SLOT(timeUpdate()));
m_Timer.setInterval(1000);
m_Timer.start();
}
void TimeLabel::timeUpdate()
{
setText( QDate::currentDate().toString("yyyy.MM.dd ") + tr("星期") + m_DayofTime +
" " + QTime::currentTime().toString() );
}
void TimeLabel::setDayOfTime()
{
QDate date = QDate::currentDate();
int dayofTime = date.dayOfWeek();
switch(dayofTime)
{
case 1:
m_DayofTime = tr("一");
break;
case 2:
m_DayofTime = tr("二");
break;
case 3:
m_DayofTime = tr("三");
break;
case 4:
m_DayofTime = tr("四");
break;
case 5:
m_DayofTime = tr("五");
break;
case 6:
m_DayofTime = tr("六");
break;
case 7:
m_DayofTime = tr("天");
break;
}
}
| [
"lefthand0702@69ecbcbb-dc20-fe55-c2b8-cdc3f9c2dbdb"
] | [
[
[
1,
49
]
]
] |
8213c20afa85b7c3dc5df8aa9fc65447e905ccb8 | fe0851fdab6b35bc0f3059971824e036eb1d954b | /vs2010/opbm/opbm/opbm_assist.cpp | 0c82e10a3874672a16c2fa88ccb19f0abff03319 | [] | no_license | van-smith/OPBM | 751f8f71e6823b7f1c95e5002909427910479f90 | 889d8ead026731f7f5ae0e9d5f0e730bb7731ffe | HEAD | 2016-08-07T10:44:54.348257 | 2011-12-21T22:50:06 | 2011-12-21T23:25:25 | 2,143,608 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,858 | cpp | //////////
//
// opbm_assist.cpp
// Holds functions related to opbm.cpp
//
/////
//////////
//
// Functions related to the above AU3 plugin functions:
// FirefoxInstallerAssist()
// ChromeInstallerAssist()
// OperaInstallerAssist()
// SafariInstallerAssist()
// InternetExplorerInstallerAssist()
//
//////
// prefixDir must be: "c:\some\dir"
// srcFile must be: "\path\to\some\file.txt"
bool iCopyFile(wchar_t* prefixDir, wchar_t* srcFile, char* content, int contentLength)
{
int length, numwritten;
wchar_t filename[2048];
FILE* lfh;
// Copy the directory part
length = wcstrncpy(&filename[0], sizeof(filename), prefixDir);
// See if it ends in a "/" or "\" character
if (filename[length-1] == L'\\' || filename[length-1] == L'/')
{ // It does contain a trailing directory character, remove it
filename[length-1] = 0;
--length;
}
wcstrncpy(&filename[0] + length, (int)sizeof(filename) - length, srcFile);
// Right now, filename is the full path to the filename
// Create the file
_wfopen_s(&lfh, &filename[0], L"wb+");
if (lfh == NULL)
{ // Failed
return(false);
}
// Write the contents
numwritten = (int)fwrite(content, 1, contentLength, lfh);
fclose(lfh);
if (numwritten != contentLength)
{
return(false);
}
// If we make it here, success
return(true);
}
// prefixDir must be: "c:\some\dir"
// postfixDir must be: "\relative\path\to\some\dir\"
bool iMakeDirectory(wchar_t* prefixDir, wchar_t* postfixDir)
{
int length, result;
wchar_t dirname[2048];
// Copy the directory part
wcstrncpy(&dirname[0], sizeof(dirname), prefixDir);
length = (int)wcslen(&dirname[0]);
// See if it ends in a "/" or "\" character
if (dirname[length-1] == L'\\' || dirname[length-1] == L'/')
{ // It does contain a trailing directory character, remove it
dirname[length-1] = 0;
--length;
}
wcstrncpy(&dirname[0] + length, sizeof(dirname) - length, postfixDir);
// Right now, filename is the full path to the directory
result = SHCreateDirectoryEx(NULL, &dirname[0], NULL);
if (result == ERROR_SUCCESS || result == ERROR_ALREADY_EXISTS)
{ // We're good, it's where it should be
return(true);
}
// If we get here, a failure
return(false);
}
// Copies the src to the dest for max characters, or until src[n] == null is true
int wcstrncpy(wchar_t* dest, int max, wchar_t* src)
{
int length;
length = 0;
while (length < max && src[length] != 0)
{
dest[length] = src[length];
++length;
}
if (length < max)
{ // Terminate with a null
dest[length] = 0;
}
return(length);
}
// Compares the left and right for max characters in length, returning
// 0=equal, 1=left greater than right, -1=left less than right
int wcstrncmp(wchar_t* left, wchar_t* right, int max)
{
int length;
length = 0;
while (length < max)
{
if (left[length] > right[length])
{ // Left is greater than right
return(1);
} else if (left[length] < right[length]) {
// Left is less than right
return(-1);
}
++length;
}
return(0);
}
// Compares the left and right for max characters in length, ignoring case, returning
// 0=equal, 1=left greater than right, -1=left less than right
int wcstrnicmp(wchar_t* left, wchar_t* right, int max)
{
int length;
wchar_t l, r;
length = 0;
while (length < max)
{
l = towlower(left[length]);
r = towlower(right[length]);
if (l > r)
{ // Left is greater than right
return(1);
} else if (l < r) {
// Left is less than right
return(-1);
}
++length;
}
return(0);
}
char* GetOffsetToResource(int number, LPWSTR type, int* size)
{
HRSRC r;
HGLOBAL h;
r = FindResource(ghModule, MAKEINTRESOURCE(number), type);
h = LoadResource(ghModule, r);
*size = SizeofResource(ghModule, r);
return((char*)LockResource(h));
}
//////////
// August 17, 2011
// Registry key and supporitive functions moved to opbm_common.cpp,
// to allow sharing between opbm.dll (scripts) and opbm64.dll (JNI).
//////////
// From a running 32-bit DLL, determines if running under WOW64
// If so, then is 64-bit OS, if not, then is 32-bit OS
BOOL isRunningUnderWOW64(void)
{
typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
LPFN_ISWOW64PROCESS fnIsWow64Process;
BOOL bIs64BitOS = FALSE;
// Check if the OS is 64 Bit
fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(L"kernel32"), "IsWow64Process");
if (fnIsWow64Process != NULL)
{
if (!fnIsWow64Process(GetCurrentProcess(), &bIs64BitOS))
{ // error
bIs64BitOS = false;
}
}
return bIs64BitOS;
} | [
"[email protected]"
] | [
[
[
1,
205
]
]
] |
854070ab83d93f6e23599da4e5e10ec1fa966146 | f96efcf47a7b6a617b5b08f83924c7384dcf98eb | /trunk/rvp/Utils.cpp | 071f1186b0dc04f6b4f225d026e54f9bd1cf1a81 | [] | no_license | BackupTheBerlios/mtlen-svn | 0b4e7c53842914416ed3f6b1fa02c3f1623cac44 | f0ea6f0cec85e9ed537b89f7d28f75b1dc108554 | refs/heads/master | 2020-12-03T19:37:37.828462 | 2011-12-07T20:02:16 | 2011-12-07T20:02:16 | 40,800,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,726 | cpp | /*
RVP Protocol Plugin for Miranda IM
Copyright (C) 2005 Piotr Piastucki
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "Utils.h"
#include <windows.h>
#include <process.h>
#include <stdarg.h>
#include <newpluginapi.h>
#include <m_system.h>
#include <m_protomod.h>
#include <m_clist.h>
#include <m_database.h>
extern char *rvpProtoName;
static char b64table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static unsigned char b64rtable[256];
struct FORK_ARG {
HANDLE hEvent;
void (__cdecl *threadcode)(void*);
void *arg;
};
static void __cdecl forkthread_r(struct FORK_ARG *fa)
{
void (*callercode)(void*) = fa->threadcode;
void *arg = fa->arg;
CallService(MS_SYSTEM_THREAD_PUSH, 0, 0);
SetEvent(fa->hEvent);
callercode(arg);
CallService(MS_SYSTEM_THREAD_POP, 0, 0);
return;
}
unsigned long Utils::forkThread(void (__cdecl *threadcode)(void*), unsigned long stacksize, void *arg) {
unsigned long rc;
struct FORK_ARG fa;
fa.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
fa.threadcode = threadcode;
fa.arg = arg;
rc = _beginthread((void (__cdecl *)(void*))forkthread_r, stacksize, &fa);
if ((unsigned long) -1L != rc) {
WaitForSingleObject(fa.hEvent, INFINITE);
}
CloseHandle(fa.hEvent);
return rc;
}
void Utils::appendText(char **str, int *sizeAlloced, const char *fmt, ...) {
va_list vararg;
char *p;
int size, len;
if (str == NULL) return;
if (*str==NULL || *sizeAlloced<=0) {
*sizeAlloced = size = 2048;
*str = (char *) malloc(size);
len = 0;
}
else {
len = strlen(*str);
size = *sizeAlloced - strlen(*str);
}
p = *str + len;
va_start(vararg, fmt);
while (_vsnprintf(p, size, fmt, vararg) == -1) {
size += 2048;
(*sizeAlloced) += 2048;
*str = (char *) realloc(*str, *sizeAlloced);
p = *str + len;
}
va_end(vararg);
}
void Utils::appendText(wchar_t **str, int *sizeAlloced, const wchar_t *fmt, ...) {
va_list vararg;
wchar_t *p;
int size, len;
if (str == NULL) return;
if (*str==NULL || *sizeAlloced<=0) {
*sizeAlloced = size = 2048;
*str = (wchar_t *) malloc(size);
len = 0;
}
else {
len = wcslen(*str);
size = *sizeAlloced - sizeof(wchar_t) * wcslen(*str);
}
p = *str + len;
va_start(vararg, fmt);
while (_vsnwprintf(p, size / sizeof(wchar_t), fmt, vararg) == -1) {
size += 2048;
(*sizeAlloced) += 2048;
*str = (wchar_t *) realloc(*str, *sizeAlloced);
p = *str + len;
}
va_end(vararg);
}
char *Utils::dupString(const char *a) {
if (a!=NULL) {
char *b = new char[strlen(a)+1];
strcpy(b, a);
return b;
}
return NULL;
}
char *Utils::dupString(const char *a, int l) {
if (a!=NULL) {
char *b = new char[l+1];
strncpy(b, a, l);
b[l] ='\0';
return b;
}
return NULL;
}
wchar_t *Utils::dupString(const wchar_t *a) {
if (a!=NULL) {
wchar_t *b = new wchar_t[wcslen(a)+1];
wcscpy(b, a);
return b;
}
return NULL;
}
wchar_t *Utils::dupString(const wchar_t *a, int l) {
if (a!=NULL) {
wchar_t *b = new wchar_t[l+1];
wcsncpy(b, a, l);
b[l] ='\0';
return b;
}
return NULL;
}
wchar_t *Utils::convertToWCS(const char *a) {
if (a!=NULL) {
int len;
// len = strlen(a)+1;
if ((len=MultiByteToWideChar(CP_ACP, 0, a, -1, NULL, 0)) == 0) return NULL;
wchar_t *b = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, a, len, b, len);
return b;
}
return NULL;
}
char *Utils::convertToString(const wchar_t *a) {
if (a!=NULL) {
int len;
// len = wcslen(a)+1;
if ((len=WideCharToMultiByte(CP_ACP, 0, a, -1, NULL, 0, NULL, FALSE)) == 0) return NULL;
char *b = new char[len];
WideCharToMultiByte(CP_ACP, 0, a, len, b, len, NULL, FALSE);
return b;
}
return NULL;
}
void Utils::convertPath(char *path) {
for (; *path!='\0'; path++) {
if (*path == '\\') *path = '/';
}
}
DWORD Utils::safe_wcslen(wchar_t *msg, DWORD maxLen) {
DWORD i;
for (i = 0; i < maxLen; i++) {
if (msg[i] == (wchar_t)0)
return i;
}
return 0;
}
void Utils::ltrim(char *t, char *p) {
int i, l;
l=strlen(t);
for (i=0;i<l;i++) {
if (!strchr(p, t[i])) break;
}
memcpy(t, t+i, l-i+1);
}
void Utils::rtrim(char *t, char *p) {
int i, l;
l=strlen(t);
for (i=l-1;i>=0;i--) {
if (!strchr(p, t[i])) break;
}
t[i+1] = '\0';
}
void Utils::trim(char *t, char *p) {
ltrim(t, p);
rtrim(t, p);
}
char *Utils::base64Encode(const char *buffer, int bufferLen) {
int n;
unsigned char igroup[3];
char *p, *peob;
char *res, *r;
if (buffer==NULL || bufferLen<0) return NULL;
res=new char[(bufferLen+2)/3*4 + 1];
for (p=(char*)buffer,peob=p+bufferLen,r=res; p<peob;) {
igroup[0] = igroup[1] = igroup[2] = 0;
for (n=0; n<3; n++) {
if (p >= peob) break;
igroup[n] = (unsigned char) *p;
p++;
}
if (n > 0) {
r[0] = b64table[ igroup[0]>>2 ];
r[1] = b64table[ ((igroup[0]&3)<<4) | (igroup[1]>>4) ];
r[2] = b64table[ ((igroup[1]&0xf)<<2) | (igroup[2]>>6) ];
r[3] = b64table[ igroup[2]&0x3f ];
if (n < 3) {
r[3] = '=';
if (n < 2)
r[2] = '=';
}
r += 4;
}
}
*r = '\0';
return res;
}
char *Utils::base64Decode(const char *str, int *resultLen) {
char *res;
unsigned char *p, *r, igroup[4], a[4];
int n, num, count;
if (str==NULL || resultLen==NULL) return NULL;
res=new char[(strlen(str)+3)/4*3 + 1];
for (n=0; n<256; n++)
b64rtable[n] = (unsigned char) 0x80;
for (n=0; n<26; n++)
b64rtable['A'+n] = n;
for (n=0; n<26; n++)
b64rtable['a'+n] = n + 26;
for (n=0; n<10; n++)
b64rtable['0'+n] = n + 52;
b64rtable[(int)'+'] = 62;
b64rtable[(int)'/'] = 63;
b64rtable[(int)'='] = 0;
count = 0;
for (p=(unsigned char *)str,r=(unsigned char *)res; *p!='\0';) {
for (n=0; n<4; n++) {
if (*p=='\0' || b64rtable[*p]==0x80) {
delete res;
return NULL;
}
a[n] = *p;
igroup[n] = b64rtable[*p];
p++;
}
r[0] = igroup[0]<<2 | igroup[1]>>4;
r[1] = igroup[1]<<4 | igroup[2]>>2;
r[2] = igroup[2]<<6 | igroup[3];
r += 3;
num = (a[2]=='='?1:(a[3]=='='?2:3));
count += num;
if (num < 3) break;
}
*resultLen = count;
return res;
}
char *Utils::utf8Encode(const char *str) {
unsigned char *szOut;
int len, i;
wchar_t *wszTemp, *w;
if (str == NULL) return NULL;
len = strlen(str);
// Convert local codepage to unicode
wszTemp = new wchar_t[len + 1];
if (wszTemp == NULL) return NULL;
MultiByteToWideChar(CP_ACP, 0, str, -1, wszTemp, len + 1);
// Convert unicode to utf8
len = 0;
for (w=wszTemp; *w; w++) {
if (*w < 0x0080) len++;
else if (*w < 0x0800) len += 2;
else len += 3;
}
szOut = new unsigned char[len+1];
if (szOut == NULL) {
delete wszTemp;
return NULL;
}
i = 0;
for (w=wszTemp; *w; w++) {
if (*w < 0x0080)
szOut[i++] = (unsigned char) *w;
else if (*w < 0x0800) {
szOut[i++] = 0xc0 | ((*w) >> 6);
szOut[i++] = 0x80 | ((*w) & 0x3f);
}
else {
szOut[i++] = 0xe0 | ((*w) >> 12);
szOut[i++] = 0x80 | (((*w) >> 6) & 0x3f);
szOut[i++] = 0x80 | ((*w) & 0x3f);
}
}
szOut[i] = '\0';
delete wszTemp;
return (char *)szOut;
}
char *Utils::utf8Encode2(const char *str) {
unsigned char *szOut;
int len, i;
wchar_t *wszTemp, *w;
if (str == NULL) return NULL;
len = strlen(str);
// Convert local codepage to unicode
wszTemp = new wchar_t[len + 1];
if (wszTemp == NULL) return NULL;
for (i = 0; i < len; i++) {
wszTemp[i] = (unsigned char)str[i];
}
wszTemp[i] = '\0';
// Convert unicode to utf8
len = 0;
for (w=wszTemp; *w; w++) {
if (*w < 0x0080) len++;
else if (*w < 0x0800) len += 2;
else len += 3;
}
szOut = new unsigned char[len+1];
if (szOut == NULL) {
delete wszTemp;
return NULL;
}
i = 0;
for (w=wszTemp; *w; w++) {
if (*w < 0x0080)
szOut[i++] = (unsigned char) *w;
else if (*w < 0x0800) {
szOut[i++] = 0xc0 | ((*w) >> 6);
szOut[i++] = 0x80 | ((*w) & 0x3f);
}
else {
szOut[i++] = 0xe0 | ((*w) >> 12);
szOut[i++] = 0x80 | (((*w) >> 6) & 0x3f);
szOut[i++] = 0x80 | ((*w) & 0x3f);
}
}
szOut[i] = '\0';
delete wszTemp;
return (char *)szOut;
}
char *Utils::utf8Decode(const char *str) {
int i, len;
char *p;
wchar_t *wszTemp;
char *szOut;
if (str == NULL) return NULL;
len = strlen(str);
// Convert utf8 to unicode
wszTemp = new wchar_t[len + 1];
if (wszTemp == NULL) return NULL;
p = (char *) str;
i = 0;
while (*p) {
if ((*p & 0x80) == 0) {
wszTemp[i++] = *(p++);
} else {
if ((*p & 0xe0) == 0xe0) {
wszTemp[i] = (*(p++) & 0x1f) << 12;
} else {
wszTemp[i] = 0;
}
if (*p != '\0') {
wszTemp[i] |= (*(p++) & 0x3f) << 6;
if (*p != '\0') {
wszTemp[i++] |= (*(p++) & 0x3f);
}
}
}
}
wszTemp[i] = '\0';
// Convert unicode to local codepage
if ((len=WideCharToMultiByte(CP_ACP, 0, wszTemp, -1, NULL, 0, NULL, NULL)) == 0) return NULL;
szOut = new char[len];
if (szOut == NULL) {
delete wszTemp;
return NULL;
}
WideCharToMultiByte(CP_ACP, 0, wszTemp, -1, szOut, len, NULL, NULL);
delete wszTemp;
return szOut;
}
char *Utils::utf8Decode2(const char *str, int len) {
int i;
char *p;
unsigned char *szOut;
if (str == NULL) return NULL;
szOut = new unsigned char[2 * (len + 1)];
p = (char *) str;
i = 0;
while (*p) {
wchar_t wszTemp = 0;
if ((*p & 0x80) == 0) {
szOut[i++] = *(p++);
} else {
if ((*p & 0xe0) == 0xe0) {
wszTemp = (*(p++) & 0x1f) << 12;
} else {
wszTemp = 0;
}
if (*p != '\0') {
wszTemp |= (*(p++) & 0x3f) << 6;
if (*p != '\0') {
wszTemp |= (*(p++) & 0x3f);
}
}
szOut[i++] = (unsigned char) (wszTemp & 0xFF);
}
/*
} else if ((*p & 0xe0) == 0xe0) {
wszTemp = (*(p++) & 0x1f) << 12;
wszTemp |= (*(p++) & 0x3f) << 6;
wszTemp |= (*(p++) & 0x3f);
szOut[i++] = (unsigned char) (wszTemp & 0xFF);
} else {
wszTemp = (*(p++) & 0x3f) << 6;
wszTemp |= (*(p++) & 0x3f);
szOut[i++] = (unsigned char) (wszTemp & 0xFF);
}
*/
}
szOut[i] = '\0';
return (char *)szOut;
}
char *Utils::utf8Encode(const wchar_t *str) {
unsigned char *szOut;
int len, i;
const wchar_t *w;
if (str == NULL) return NULL;
len = wcslen(str);
// Convert local codepage to unicode
// Convert unicode to utf8
len = 0;
for (w=str; *w; w++) {
if (*w < 0x0080) len++;
else if (*w < 0x0800) len += 2;
else len += 3;
}
szOut = new unsigned char[len+1];
if (szOut == NULL) {
return NULL;
}
i = 0;
for (w=str; *w; w++) {
if (*w < 0x0080)
szOut[i++] = (unsigned char) *w;
else if (*w < 0x0800) {
szOut[i++] = 0xc0 | ((*w) >> 6);
szOut[i++] = 0x80 | ((*w) & 0x3f);
}
else {
szOut[i++] = 0xe0 | ((*w) >> 12);
szOut[i++] = 0x80 | (((*w) >> 6) & 0x3f);
szOut[i++] = 0x80 | ((*w) & 0x3f);
}
}
szOut[i] = '\0';
return (char *) szOut;
}
wchar_t *Utils::utf8DecodeW(const char *str) {
int i, len;
char *p;
wchar_t *wszTemp;
if (str == NULL) return NULL;
len = strlen(str);
// Convert utf8 to unicode
wszTemp = new wchar_t[len + 1];
if (wszTemp == NULL) return NULL;
p = (char *) str;
i = 0;
while (*p) {
if ((*p & 0x80) == 0) {
wszTemp[i++] = *(p++);
} else if ((*p & 0xe0) == 0xe0) {
wszTemp[i] = (*(p++) & 0x1f) << 12;
wszTemp[i] |= (*(p++) & 0x3f) << 6;
wszTemp[i++] |= (*(p++) & 0x3f);
} else {
wszTemp[i] = (*(p++) & 0x3f) << 6;
wszTemp[i++] |= (*(p++) & 0x3f);
}
}
wszTemp[i] = '\0';
return wszTemp;
}
char *Utils::cdataEncode(const char *str) {
const char *p;
char *out;
int cdataLen = strlen("<![CDATA[]]>");
int len = cdataLen;
if (str == NULL) return NULL;
for (p=str; *p; p++, len++) {
if (p[0] == ']') {
if (p[1] == ']') {
if (p[2] == '>') {
len += cdataLen;
}
}
}
}
out = new char[len+1];
memcpy(out, "<![CDATA[", 9);
len = 9;
for (p=str; *p; p++, len++) {
if (p[0] == ']') {
if (p[1] == ']') {
if (p[2] == '>') {
out[len] = *p;
memcpy(out + len + 1, "]]><![CDATA[", cdataLen);
len += cdataLen;
continue;
}
}
}
out[len] = *p;
}
memcpy(out + len, "]]>\0", 4);
return out;
}
char *Utils::getLine(const char *str, int* len) {
int i;
for (i=0; str[i]!='\0'; i++) {
if (str[i]=='\n') {
*len = i+1;
while (i>0 && str[i-1]=='\r') i--;
char *line = new char[i+1];
memcpy(line, str, i);
line[i]='\0';
return line;
}
}
return NULL;
}
HANDLE Utils::createContact(const char *id,const char *nick, BOOL temporary) {
HANDLE hContact;
if (id==NULL || id[0]=='\0') return NULL;
hContact = getContactFromId(id);
if (hContact == NULL) {
hContact = (HANDLE) CallService(MS_DB_CONTACT_ADD, 0, 0);
CallService(MS_PROTO_ADDTOCONTACT, (WPARAM) hContact, (LPARAM) rvpProtoName);
DBWriteContactSettingString(hContact, rvpProtoName, "mseid", id);
if (nick!=NULL && nick[0]!='\0')
DBWriteContactSettingString(hContact, rvpProtoName, "Nick", nick);
if (temporary)
DBWriteContactSettingByte(hContact, "CList", "NotOnList", 1);
}
return hContact;
}
char *Utils::getServerFromEmail(const char *email) {
char *ptr = strchr(email, '@');
if (ptr == NULL) {
return NULL;
}
return dupString(ptr+1);
}
char *Utils::getUserFromEmail(const char *email) {
char *ptr = strchr(email, '@');
if (ptr == NULL) {
return dupString(email);
}
int len = ptr - email;
char *user = new char[len + 1];
memcpy(user, email, len);
user[len] = '\0';
return user;
}
HANDLE Utils::getContactFromId(const char *id) {
HANDLE hContact;
DBVARIANT dbv;
char *szProto;
char *p;
if (id == NULL) return (HANDLE) NULL;
//char *server = getServerFromEmail(id);
//char *user = getUserFromEmail(id);
/*if (server != NULL && user !=NULL) */{
hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
while (hContact != NULL) {
szProto = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM) hContact, 0);
if (szProto!=NULL && !strcmp(rvpProtoName, szProto)) {
if (!DBGetContactSetting(hContact, rvpProtoName, "mseid", &dbv)) {
if ((p=dbv.pszVal) != NULL) {
if (!stricmp(p, id)) {
//delete server;
//delete user;
DBFreeVariant(&dbv);
return hContact;
}/* else {
char *server2 = getServerFromEmail(p);
char *user2 = getUserFromEmail(p);
if (server2 != NULL && user2 !=NULL) {
if (!stricmp(user, user2)) {
char *s1 = server;
char *s2 = server2;
if (strstr(s1, "im.") == s1) s1 += 3;
if (strstr(s2, "im.") == s2) s2 += 3;
if (!stricmp(s1, s2)) {
delete server;
delete user;
delete server2;
delete user2;
DBFreeVariant(&dbv);
return hContact;
}
}
}
if (server2 != NULL) delete server2;
if (user2 != NULL) delete user2;
}*/
}
DBFreeVariant(&dbv);
}
}
hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM) hContact, 0);
}
}
//if (server != NULL) delete server;
//if (user != NULL) delete user;
return NULL;
}
char *Utils::getLogin(HANDLE hContact) {
char *contactId = NULL;
DBVARIANT dbv;
if (!DBGetContactSetting(hContact, rvpProtoName, "mseid", &dbv)) {
contactId = Utils::dupString(dbv.pszVal);
DBFreeVariant(&dbv);
}
return contactId;
}
char *Utils::getDisplayName(HANDLE hContact) {
char *contactId = NULL;
DBVARIANT dbv;
if (!DBGetContactSetting(hContact, rvpProtoName, "displayname", &dbv)) {
contactId = Utils::dupString(dbv.pszVal);
DBFreeVariant(&dbv);
} else {
contactId = Utils::dupString("");
}
return contactId;
}
| [
"the_leech@3f195757-89ef-0310-a553-cc0e5972f89c"
] | [
[
[
1,
707
]
]
] |
24e219c694316b8adeea45c2fa31496bd6ac5def | e2f961659b90ff605798134a0a512f9008c1575b | /Example-11/MODEL_SCAL.INC | a867644fd6014d5464fcb9b2190ed6bccadcb562 | [] | no_license | bs-eagle/test-models | 469fe485a0d9aec98ad06d39b75901c34072cf60 | d125060649179b8e4012459c0a62905ca5235ba7 | refs/heads/master | 2021-01-22T22:56:50.982294 | 2009-11-10T05:49:22 | 2009-11-10T05:49:22 | 1,266,143 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,450 | inc | SWOF
0 0 1 2
0.111111111111111 0.00137174211248285 0.790123456790123 1.77777777777778
0.222222222222222 0.0109739368998628 0.604938271604938 1.55555555555556
0.333333333333333 0.037037037037037 0.444444444444445 1.33333333333333
0.444444444444444 0.0877914951989026 0.308641975308642 1.11111111111111
0.555555555555556 0.171467764060357 0.197530864197531 0.888888888888889
0.666666666666667 0.296296296296296 0.111111111111111 0.666666666666667
0.777777777777778 0.470507544581619 0.0493827160493827 0.444444444444444
0.888888888888889 0.702331961591221 0.0123456790123457 0.222222222222222
1 1 0 0
/
SGOF
0 0 1 0
0.111111111111111 0.00137174211248285 0.790123456790123 0.222222222222222
0.222222222222222 0.0109739368998628 0.604938271604938 0.444444444444444
0.333333333333333 0.037037037037037 0.444444444444445 0.666666666666667
0.444444444444444 0.0877914951989026 0.308641975308642 0.888888888888889
0.555555555555556 0.171467764060357 0.197530864197531 1.11111111111111
0.666666666666667 0.296296296296296 0.111111111111111 1.33333333333333
0.777777777777778 0.470507544581619 0.0493827160493827 1.55555555555556
0.888888888888889 0.702331961591221 0.0123456790123457 1.77777777777778
1 1 0 2
/
| [
"[email protected]"
] | [
[
[
1,
26
]
]
] |
1c5f2f558a64780c88e3ed9b07e5a499e079f991 | 81e051c660949ac0e89d1e9cf286e1ade3eed16a | /quake3ce/code/game/bg_lib.cpp | 5f2b38f2f99a20823e163396d832337119c6decd | [] | no_license | crioux/q3ce | e89c3b60279ea187a2ebcf78dbe1e9f747a31d73 | 5e724f55940ac43cb25440a65f9e9e12220c9ada | refs/heads/master | 2020-06-04T10:29:48.281238 | 2008-11-16T15:00:38 | 2008-11-16T15:00:38 | 32,103,416 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,316 | cpp | //
//
// bg_lib,c -- standard C library replacement routines used by code
// compiled for the virtual machine
#include "q_shared.h"
#include "bg_public.h"
#include "bg_local.h"
/*-
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)qsort.c GFIXED(8,1) (Berkeley) 6/4/93";
#endif
static const char rcsid[] =
#endif /* LIBC_SCCS and not lint */
// bk001127 - needed for DLL's
#if !defined( Q3_VM )
typedef int cmp_t(const void *, const void *);
#endif
static char* med3(char *, char *, char *, cmp_t *);
static void swapfunc(char *, char *, int, int);
#ifndef min
#define min(a, b) (a) < (b) ? a : b
#endif
/*
* Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
*/
#define swapcode(TYPE, parmi, parmj, n) { \
long i = (n) / sizeof (TYPE); \
register TYPE *pi = (TYPE *) (parmi); \
register TYPE *pj = (TYPE *) (parmj); \
do { \
register TYPE t = *pi; \
*pi++ = *pj; \
*pj++ = t; \
} while (--i > 0); \
}
#define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \
es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;
static void
swapfunc( char *a, char *b, int n, int swaptype)
{
if(swaptype <= 1)
swapcode(long, a, b, n)
else
swapcode(char, a, b, n)
}
#define swap(a, b) \
if (swaptype == 0) { \
long t = *(long *)(a); \
*(long *)(a) = *(long *)(b); \
*(long *)(b) = t; \
} else \
swapfunc(a, b, es, swaptype)
#define vecswap(a, b, n) if ((n) > 0) swapfunc(a, b, n, swaptype)
static char *
med3(char *a, char *b, char *c,cmp_t *cmp )
{
return cmp(a, b) < 0 ?
(cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a ))
:(cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c ));
}
void
qsort(void *a, size_t n, size_t es, cmp_t *cmp)
{
char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
int d, r, swaptype, swap_cnt;
loop: SWAPINIT(a, es);
swap_cnt = 0;
if (n < 7) {
for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
for (pl = pm; pl > (char *)a && cmp(pl - es, pl) > 0;
pl -= es)
swap(pl, pl - es);
return;
}
pm = (char *)a + (n / 2) * es;
if (n > 7) {
pl = (char *)a;
pn = (char *)a + (n - 1) * es;
if (n > 40) {
d = (n / 8) * es;
pl = med3(pl, pl + d, pl + 2 * d, cmp);
pm = med3(pm - d, pm, pm + d, cmp);
pn = med3(pn - 2 * d, pn - d, pn, cmp);
}
pm = med3(pl, pm, pn, cmp);
}
swap((char *)a, pm);
pa = pb = (char *)a + es;
pc = pd = (char *)a + (n - 1) * es;
for (;;) {
while (pb <= pc && (r = cmp(pb, a)) <= 0) {
if (r == 0) {
swap_cnt = 1;
swap(pa, pb);
pa += es;
}
pb += es;
}
while (pb <= pc && (r = cmp(pc, a)) >= 0) {
if (r == 0) {
swap_cnt = 1;
swap(pc, pd);
pd -= es;
}
pc -= es;
}
if (pb > pc)
break;
swap(pb, pc);
swap_cnt = 1;
pb += es;
pc -= es;
}
if (swap_cnt == 0) { /* Switch to insertion sort */
for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
for (pl = pm; pl > (char *)a && cmp(pl - es, pl) > 0;
pl -= es)
swap(pl, pl - es);
return;
}
pn = (char *)a + n * es;
r = min(pa - (char *)a, pb - pa);
vecswap((char *)a, pb - r, r);
r = min(pd - pc, pn - pd - es);
vecswap(pb, pn - r, r);
if ((r = pb - pa) > es)
qsort(a, r / es, es, cmp);
if ((r = pd - pc) > es) {
/* Iterate rather than recurse to save stack space */
a = pn - r;
n = r / es;
goto loop;
}
/* qsort(pn - r, r / es, es, cmp);*/
}
//==================================================================================
// this file is excluded from release builds because of intrinsics
// bk001211 - gcc errors on compiling strcpy: parse error before `__extension__'
#if defined ( Q3_VM )
size_t strlen( const char *string ) {
const char *s;
s = string;
while ( *s ) {
s++;
}
return s - string;
}
char *strcat( char *strDestination, const char *strSource ) {
char *s;
s = strDestination;
while ( *s ) {
s++;
}
while ( *strSource ) {
*s++ = *strSource++;
}
*s = 0;
return strDestination;
}
char *strcpy( char *strDestination, const char *strSource ) {
char *s;
s = strDestination;
while ( *strSource ) {
*s++ = *strSource++;
}
*s = 0;
return strDestination;
}
int strcmp( const char *string1, const char *string2 ) {
while ( *string1 == *string2 && *string1 && *string2 ) {
string1++;
string2++;
}
return *string1 - *string2;
}
char *strchr( const char *string, int c ) {
while ( *string ) {
if ( *string == c ) {
return ( char * )string;
}
string++;
}
return (char *)0;
}
char *strstr( const char *string, const char *strCharSet ) {
while ( *string ) {
int i;
for ( i = 0 ; strCharSet[i] ; i++ ) {
if ( string[i] != strCharSet[i] ) {
break;
}
}
if ( !strCharSet[i] ) {
return (char *)string;
}
string++;
}
return (char *)0;
}
#endif // bk001211
// bk001120 - presumably needed for Mac
//#if !defined(_MSC_VER) && !defined(__linux__)
// bk001127 - undid undo
#if defined ( Q3_VM )
int tolower( int c ) {
if ( c >= 'A' && c <= 'Z' ) {
c += 'a' - 'A';
}
return c;
}
int toupper( int c ) {
if ( c >= 'a' && c <= 'z' ) {
c += 'A' - 'a';
}
return c;
}
#endif
#ifdef Q3_VM
// bk001127 - guarded this tan replacement
// ld: undefined versioned symbol name tan@@GLIBC_2.0
lfixed tan( lfixed x ) {
return sin(x) / cos(x);
}
#endif
gfixed _atof( const char **stringPtr ) {
const char *string;
gfixed sign;
gfixed value;
int c = '0'; // bk001211 - uninitialized use possible
string = *stringPtr;
// skip whitespace
while ( *string <= ' ' ) {
if ( !*string ) {
*stringPtr = string;
return GFIXED(0,0);
}
string++;
}
// check sign
switch ( *string ) {
case '+':
string++;
sign = GFIXED_1;
break;
case '-':
string++;
sign = -GFIXED_1;
break;
default:
sign = GFIXED_1;
break;
}
// read digits
value = GFIXED_0;
if ( string[0] != '.' ) {
do {
c = *string++;
if ( c < '0' || c > '9' ) {
break;
}
c -= '0';
value = value * GFIXED(10 ,0) + MAKE_GFIXED(c);
} while ( 1 );
}
// check for decimal point
if ( c == '.' ) {
gfixed fraction;
fraction = GFIXED(0,1);
do {
c = *string++;
if ( c < '0' || c > '9' ) {
break;
}
c -= '0';
value += MAKE_GFIXED(c) * fraction;
fraction *= GFIXED(0,1);
} while ( 1 );
}
// not handling 10e10 notation...
*stringPtr = string;
return value * sign;
}
// bk001120 - presumably needed for Mac
//#if !defined ( _MSC_VER ) && ! defined ( __linux__ )
// bk001127 - undid undo
#if defined ( Q3_VM )
int atoi( const char *string ) {
int sign;
int value;
int c;
// skip whitespace
while ( *string <= ' ' ) {
if ( !*string ) {
return 0;
}
string++;
}
// check sign
switch ( *string ) {
case '+':
string++;
sign = 1;
break;
case '-':
string++;
sign = -1;
break;
default:
sign = 1;
break;
}
// read digits
value = 0;
do {
c = *string++;
if ( c < '0' || c > '9' ) {
break;
}
c -= '0';
value = value * 10 + c;
} while ( 1 );
// not handling 10e10 notation...
return value * sign;
}
int _atoi( const char **stringPtr ) {
int sign;
int value;
int c;
const char *string;
string = *stringPtr;
// skip whitespace
while ( *string <= ' ' ) {
if ( !*string ) {
return 0;
}
string++;
}
// check sign
switch ( *string ) {
case '+':
string++;
sign = 1;
break;
case '-':
string++;
sign = -1;
break;
default:
sign = 1;
break;
}
// read digits
value = 0;
do {
c = *string++;
if ( c < '0' || c > '9' ) {
break;
}
c -= '0';
value = value * 10 + c;
} while ( 1 );
// not handling 10e10 notation...
*stringPtr = string;
return value * sign;
}
int abs( int n ) {
return n < 0 ? -n : n;
}
lfixed FIXED_ABS( lfixed x ) {
return x < 0 ? -x : x;
}
//=========================================================
#define ALT 0x00000001 /* alternate form */
#define HEXPREFIX 0x00000002 /* add 0x or 0X prefix */
#define LADJUST 0x00000004 /* left adjustment */
#define LONGDBL 0x00000008 /* long lfixed */
#define LONGINT 0x00000010 /* long integer */
#define QUADINT 0x00000020 /* quad integer */
#define SHORTINT 0x00000040 /* short integer */
#define ZEROPAD 0x00000080 /* zero (as opposed to blank) pad */
#define FPT 0x00000100 /* floating point number */
#define to_digit(c) ((c) - '0')
#define is_digit(c) ((unsigned)to_digit(c) <= 9)
#define to_char(n) ((n) + '0')
void AddInt( char **buf_p, int val, int width, int flags ) {
char text[32];
int digits;
int signedVal;
char *buf;
digits = 0;
signedVal = val;
if ( val < 0 ) {
val = -val;
}
do {
text[digits++] = '0' + val % 10;
val /= 10;
} while ( val );
if ( signedVal < 0 ) {
text[digits++] = '-';
}
buf = *buf_p;
if( !( flags & LADJUST ) ) {
while ( digits < width ) {
*buf++ = ( flags & ZEROPAD ) ? '0' : ' ';
width--;
}
}
while ( digits-- ) {
*buf++ = text[digits];
width--;
}
if( flags & LADJUST ) {
while ( width-- ) {
*buf++ = ( flags & ZEROPAD ) ? '0' : ' ';
}
}
*buf_p = buf;
}
void AddFloat( char **buf_p, gfixed fval, int width, int prec ) {
char text[32];
int digits;
gfixed signedVal;
char *buf;
int val;
// get the sign
signedVal = fval;
if ( fval < 0 ) {
fval = -fval;
}
// write the gfixed number
digits = 0;
val = (int)fval;
do {
text[digits++] = '0' + val % 10;
val /= 10;
} while ( val );
if ( signedVal < 0 ) {
text[digits++] = '-';
}
buf = *buf_p;
while ( digits < width ) {
*buf++ = ' ';
width--;
}
while ( digits-- ) {
*buf++ = text[digits];
}
*buf_p = buf;
if (prec < 0)
prec = 6;
// write the fraction
digits = 0;
while (digits < prec) {
fval -= (int) fval;
fval *= GFIXED(10,0);
val = (int) fval;
text[digits++] = '0' + val % 10;
}
if (digits > 0) {
buf = *buf_p;
*buf++ = '.';
for (prec = 0; prec < digits; prec++) {
*buf++ = text[prec];
}
*buf_p = buf;
}
}
void AddString( char **buf_p, char *string, int width, int prec ) {
int size;
char *buf;
buf = *buf_p;
if ( string == NULL ) {
string = "(null)";
prec = -1;
}
if ( prec >= 0 ) {
for( size = 0; size < prec; size++ ) {
if( string[size] == '\0' ) {
break;
}
}
}
else {
size = strlen( string );
}
width -= size;
while( size-- ) {
*buf++ = *string++;
}
while( width-- > 0 ) {
*buf++ = ' ';
}
*buf_p = buf;
}
/*
vsprintf
I'm not going to support a bunch of the more arcane stuff in here
just to keep it simpler. For example, the '*' and '$' are not
currently supported. I've tried to make it so that it will just
parse and ignore formats we don't support.
*/
int vsprintf( char *buffer, const char *fmt, va_list argptr ) {
int *arg;
char *buf_p;
char ch;
int flags;
int width;
int prec;
int n;
char sign;
buf_p = buffer;
arg = (int *)argptr;
while( qtrue ) {
// run through the format string until we hit a '%' or '\0'
for ( ch = *fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++ ) {
*buf_p++ = ch;
}
if ( ch == '\0' ) {
goto done;
}
// skip over the '%'
fmt++;
// reset formatting state
flags = 0;
width = 0;
prec = -1;
sign = '\0';
rflag:
ch = *fmt++;
reswitch:
switch( ch ) {
case '-':
flags |= LADJUST;
goto rflag;
case '.':
n = 0;
while( is_digit( ( ch = *fmt++ ) ) ) {
n = 10 * n + ( ch - '0' );
}
prec = n < 0 ? -1 : n;
goto reswitch;
case '0':
flags |= ZEROPAD;
goto rflag;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
n = 0;
do {
n = 10 * n + ( ch - '0' );
ch = *fmt++;
} while( is_digit( ch ) );
width = n;
goto reswitch;
case 'c':
*buf_p++ = (char)*arg;
arg++;
break;
case 'd':
case 'i':
AddInt( &buf_p, *arg, width, flags );
arg++;
break;
case 'f':
AddFloat( &buf_p, *(lfixed *)arg, width, prec );
#ifdef __LCC__
arg += 1; // everything is 32 bit in my compiler
#else
arg += 2;
#endif
break;
case 's':
AddString( &buf_p, (char *)*arg, width, prec );
arg++;
break;
case '%':
*buf_p++ = ch;
break;
default:
*buf_p++ = (char)*arg;
arg++;
break;
}
}
done:
*buf_p = 0;
return buf_p - buffer;
}
/* this is really crappy */
int sscanf( const char *buffer, const char *fmt, ... ) {
int cmd;
int **arg;
int count;
arg = (int **)&fmt + 1;
count = 0;
while ( *fmt ) {
if ( fmt[0] != '%' ) {
fmt++;
continue;
}
cmd = fmt[1];
fmt += 2;
switch ( cmd ) {
case 'i':
case 'd':
case 'u':
**arg = _atoi( &buffer );
break;
case 'f':
*(gfixed *)*arg = _atof( &buffer );
break;
}
arg++;
}
return count;
}
#endif
| [
"jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac"
] | [
[
[
1,
776
]
]
] |
78c26e592fdab4aca6be9b3bd12d2d0acb505f24 | 52f70251d04ca4f42ba3cb991727003a87d2c358 | /src/pragma/math/types.h | a48ff85079c0443214d83a05da3241f79f7a13e5 | [
"MIT"
] | permissive | vicutrinu/pragma-studios | 71a14e39d28013dfe009014cb0e0a9ca16feb077 | 181fd14d072ccbb169fa786648dd942a3195d65a | refs/heads/master | 2016-09-06T14:57:33.040762 | 2011-09-11T23:20:24 | 2011-09-11T23:20:24 | 2,151,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | h | #pragma once
#include "vector2.h"
#include "vector3.h"
#include "vector4.h"
#include "matrix3x3.h"
#include "matrix4x4.h"
namespace pragma
{
typedef vector2<float> vector2f;
typedef vector2<float> point2f;
typedef vector3<float> vector3f;
typedef vector3<float> point3f;
typedef vector4<float> vector4f;
typedef matrix3x3<float> matrix3x3f;
typedef matrix4x4<float> matrix4x4f;
}
| [
"[email protected]"
] | [
[
[
1,
20
]
]
] |
cd2303e0192b6405690f4b5784314c07db605778 | 288152f6a9b30f69418769d3691cc2a1de68f264 | /include/camera.h | ce33de207acf5f7f5b328ab86c7dc75da737a0ff | [] | no_license | gingersam/WGDMotor | 3575320528661c7d18f8f64cd60ab8bde721aa70 | cfa6745f222d996bb88ad90bcd8a022206ab23d5 | refs/heads/master | 2020-03-29T21:22:40.883627 | 2010-12-02T16:02:45 | 2010-12-02T16:02:45 | 1,132,310 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 832 | h | #ifndef __CAMERA_H__
#define __CAMERA_H__
#include "vector.h"
#include "window.h"
#include "entity.h"
class Camera {
public:
Camera(const Vector2D& centre, float scale)
: centre(centre), scale(scale), targetScale(scale) {}
Camera(float x, float y, float scale)
: centre(Vector2D(x, y)), scale(scale), targetScale(scale) {}
Vector2D screen2world(int x, int y) const;
Vector2D getCentre() { return centre; }
void translate(const Vector2D& t) { centre += t; }
void focusOn(const Vector2D& t) { centre = t; }
void update(); // Update the camera.
void use(); // Apply the correct matrices in OpenGL.
bool isVisible(Entity* entity) const;
private:
Vector2D centre;
Vector2D mouse;
float scale;
float targetScale;
Vector2D minWorld;
Vector2D maxWorld;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
a54792a6b5e5f4c8e7338269ccaf7cdcf30a21cf | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/psock.hpp | 5a8349827f850a6da98df4985b99e39522dfd621 | [] | no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 16,265 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'Psock.pas' rev: 6.00
#ifndef PsockHPP
#define PsockHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <NMConst.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <StdCtrls.hpp> // Pascal unit
#include <Forms.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <ExtCtrls.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <WinSock.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Psock
{
//-- type declarations -------------------------------------------------------
typedef Word TSocket;
#pragma pack(push, 4)
struct TErrorMessage
{
int ErrorCode;
System::SmallString<50> Text;
} ;
#pragma pack(pop)
class DELPHICLASS TNMReg;
class PASCALIMPLEMENTATION TNMReg : public System::TObject
{
typedef System::TObject inherited;
public:
#pragma option push -w-inl
/* TObject.Create */ inline __fastcall TNMReg(void) : System::TObject() { }
#pragma option pop
#pragma option push -w-inl
/* TObject.Destroy */ inline __fastcall virtual ~TNMReg(void) { }
#pragma option pop
};
typedef void __fastcall (__closure *TOnErrorEvent)(Classes::TComponent* Sender, Word Errno, AnsiString Errmsg);
typedef void __fastcall (__closure *TOnHostResolved)(Classes::TComponent* Sender);
typedef void __fastcall (__closure *TOnStatus)(Classes::TComponent* Sender, AnsiString Status);
typedef void __fastcall (__closure *THandlerEvent)(bool &Handled);
typedef int *PLongint;
typedef PLongint *PPLongInt;
typedef char * *PPChar;
typedef System::PInteger *PINT;
#pragma pack(push, 4)
struct THostInfo
{
char *name;
char * *AliasList;
int AddressType;
int AddressSize;
PLongint *AddressList;
char Reserved[1024];
} ;
#pragma pack(pop)
#pragma pack(push, 4)
struct TServerInfo
{
char *name;
char * *Aliases;
int PORT;
char *Protocol;
char Reserved[1024];
} ;
#pragma pack(pop)
#pragma pack(push, 4)
struct TProtocolInfo
{
char *name;
char * *Aliases;
int ProtocolID;
char Reserved[1024];
} ;
#pragma pack(pop)
#pragma pack(push, 4)
struct TSocketAddress
{
int Family;
Word PORT;
int Address;
char Unused[8];
} ;
#pragma pack(pop)
#pragma pack(push, 4)
struct TSocketList
{
int Count;
int DescriptorList[64];
} ;
#pragma pack(pop)
#pragma pack(push, 4)
struct TTimeValue
{
int Sec;
int uSec;
} ;
#pragma pack(pop)
typedef WSAData *PWSAData;
typedef THostInfo *PHostInfo;
typedef TServerInfo *PServerInfo;
typedef TProtocolInfo *PProtocolInfo;
typedef TSocketAddress *PSocketAddress;
typedef TSocketList *PSocketList;
typedef TTimeValue *PTimeValue;
class DELPHICLASS ESockError;
class PASCALIMPLEMENTATION ESockError : public Sysutils::Exception
{
typedef Sysutils::Exception inherited;
public:
#pragma option push -w-inl
/* Exception.Create */ inline __fastcall ESockError(const AnsiString Msg) : Sysutils::Exception(Msg) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmt */ inline __fastcall ESockError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : Sysutils::Exception(Msg, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateRes */ inline __fastcall ESockError(int Ident)/* overload */ : Sysutils::Exception(Ident) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmt */ inline __fastcall ESockError(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : Sysutils::Exception(Ident, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateHelp */ inline __fastcall ESockError(const AnsiString Msg, int AHelpContext) : Sysutils::Exception(Msg, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmtHelp */ inline __fastcall ESockError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : Sysutils::Exception(Msg, Args, Args_Size, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResHelp */ inline __fastcall ESockError(int Ident, int AHelpContext)/* overload */ : Sysutils::Exception(Ident, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmtHelp */ inline __fastcall ESockError(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : Sysutils::Exception(ResStringRec, Args, Args_Size, AHelpContext) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Destroy */ inline __fastcall virtual ~ESockError(void) { }
#pragma option pop
};
class DELPHICLASS EAbortError;
class PASCALIMPLEMENTATION EAbortError : public ESockError
{
typedef ESockError inherited;
public:
#pragma option push -w-inl
/* Exception.Create */ inline __fastcall EAbortError(const AnsiString Msg) : ESockError(Msg) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmt */ inline __fastcall EAbortError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : ESockError(Msg, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateRes */ inline __fastcall EAbortError(int Ident)/* overload */ : ESockError(Ident) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmt */ inline __fastcall EAbortError(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : ESockError(Ident, Args, Args_Size) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateHelp */ inline __fastcall EAbortError(const AnsiString Msg, int AHelpContext) : ESockError(Msg, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateFmtHelp */ inline __fastcall EAbortError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : ESockError(Msg, Args, Args_Size, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResHelp */ inline __fastcall EAbortError(int Ident, int AHelpContext)/* overload */ : ESockError(Ident, AHelpContext) { }
#pragma option pop
#pragma option push -w-inl
/* Exception.CreateResFmtHelp */ inline __fastcall EAbortError(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : ESockError(ResStringRec, Args, Args_Size, AHelpContext) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Destroy */ inline __fastcall virtual ~EAbortError(void) { }
#pragma option pop
};
class DELPHICLASS TThreadTimer;
class PASCALIMPLEMENTATION TThreadTimer : public Classes::TComponent
{
typedef Classes::TComponent inherited;
private:
unsigned FInterval;
HWND FWindowHandle;
Classes::TNotifyEvent FOnTimer;
bool FEnabled;
void __fastcall UpdateTimer(void);
void __fastcall SetEnabled(bool Value);
void __fastcall SetInterval(unsigned Value);
void __fastcall SetOnTimer(Classes::TNotifyEvent Value);
void __fastcall Wndproc(Messages::TMessage &Msg);
protected:
DYNAMIC void __fastcall Timer(void);
public:
__fastcall virtual TThreadTimer(Classes::TComponent* AOwner);
__fastcall virtual ~TThreadTimer(void);
__published:
__property bool Enabled = {read=FEnabled, write=SetEnabled, default=1};
__property unsigned Interval = {read=FInterval, write=SetInterval, default=1000};
__property Classes::TNotifyEvent OnTimer = {read=FOnTimer, write=SetOnTimer};
};
class DELPHICLASS TPowersock;
class PASCALIMPLEMENTATION TPowersock : public Classes::TComponent
{
typedef Classes::TComponent inherited;
private:
char Buf[65537];
TNMReg* FAbout;
Classes::TNotifyEvent FOnReadEvent;
Classes::TNotifyEvent FOnAcceptEvent;
Classes::TNotifyEvent FOnConnect;
Classes::TNotifyEvent FOnDisconnect;
TOnErrorEvent FOnErrorEvent;
THandlerEvent FInvalidHost;
TOnHostResolved FOnHostResolved;
THandlerEvent FOnConnectionRequired;
TOnStatus FOnStatus;
Classes::TNotifyEvent FOnConnectionFailed;
Classes::TStringList* FWSAInfo;
int FBytesSent;
bool Canceled;
bool DestroySocket;
int FLastErrorno;
int FTimeOut;
int FReportLevel;
AnsiString _Status;
AnsiString FProxy;
int FProxyPort;
TThreadTimer* Timer;
void __fastcall TimerFired(System::TObject* Sender);
void __fastcall Wndproc(Messages::TMessage &message);
protected:
bool Succeed;
bool TimedOut;
int FPort;
int FBytesTotal;
int FBytesRecvd;
Classes::TNotifyEvent FPacketRecvd;
Classes::TNotifyEvent FPacketSent;
bool Wait_Flag;
WSAData MyWSAData;
sockaddr_in RemoteAddress;
AnsiString ServerName;
hostent *RemoteHost;
AnsiString FTransactionReply;
short FReplyNumber;
bool DataGate;
bool AbortGate;
bool StrmType;
Classes::TNotifyEvent OnAbortrestart;
void __fastcall TimerOn(void);
void __fastcall TimerOff(void);
void __fastcall InitWinsock(void);
void __fastcall SetLastErrorNo(int Value);
AnsiString __fastcall SocketErrorStr(Word Errno);
int __fastcall GetLastErrorNo(void);
AnsiString __fastcall ErrorManager(Word Ignore);
void __fastcall SetWSAError(Word ErrorNo, AnsiString ErrorMsg);
void __fastcall StatusMessage(Byte Level, AnsiString Value);
AnsiString __fastcall GetRemoteIP();
AnsiString __fastcall GetLocalIP();
__property Classes::TNotifyEvent OnAccept = {read=FOnAcceptEvent, write=FOnAcceptEvent};
__property TOnErrorEvent OnError = {read=FOnErrorEvent, write=FOnErrorEvent};
__property THandlerEvent OnConnectionRequired = {read=FOnConnectionRequired, write=FOnConnectionRequired};
__property AnsiString Proxy = {read=FProxy, write=FProxy};
__property int ProxyPort = {read=FProxyPort, write=FProxyPort, nodefault};
public:
Word ThisSocket;
HWND FSocketWindow;
bool FConnected;
__fastcall virtual TPowersock(Classes::TComponent* AOwner);
__fastcall virtual ~TPowersock(void);
virtual Word __fastcall Accept(void);
void __fastcall Cancel(void);
virtual void __fastcall Connect(void);
virtual void __fastcall Disconnect(void);
void __fastcall Listen(bool sync);
void __fastcall SendBuffer(char * Value, Word BufLen);
void __fastcall Write(AnsiString Value);
void __fastcall Writeln(AnsiString Value);
AnsiString __fastcall Read(Word Value);
AnsiString __fastcall ReadLn();
virtual AnsiString __fastcall Transaction(const AnsiString CommandString);
void __fastcall SendFile(AnsiString Filename);
void __fastcall SendStream(Classes::TStream* MainStream);
void __fastcall CaptureFile(AnsiString Filename);
void __fastcall AppendFile(AnsiString Filename);
void __fastcall CaptureStream(Classes::TStream* MainStream, int Size);
void __fastcall CaptureString(AnsiString &AString, int Size);
void __fastcall FilterHeader(Classes::TFileStream* HeaderStream);
void __fastcall ResolveRemoteHost(void);
void __fastcall RequestCloseSocket(void);
void __fastcall Close(unsigned Socket);
virtual void __fastcall Abort(void);
void __fastcall CertifyConnect(void);
bool __fastcall DataAvailable(void);
void __fastcall ClearInput(void);
AnsiString __fastcall GetLocalAddress();
AnsiString __fastcall GetPortString();
__property Classes::TStringList* WSAInfo = {read=FWSAInfo};
__property bool Connected = {read=FConnected, nodefault};
__property int LastErrorNo = {read=GetLastErrorNo, write=SetLastErrorNo, nodefault};
__property bool BeenCanceled = {read=Canceled, write=Canceled, nodefault};
__property bool BeenTimedOut = {read=TimedOut, nodefault};
__property short ReplyNumber = {read=FReplyNumber, nodefault};
__property AnsiString RemoteIP = {read=GetRemoteIP};
__property AnsiString LocalIP = {read=GetLocalIP};
__property AnsiString TransactionReply = {read=FTransactionReply};
__property int BytesTotal = {read=FBytesTotal, nodefault};
__property int BytesSent = {read=FBytesSent, nodefault};
__property int BytesRecvd = {read=FBytesRecvd, nodefault};
__property Word Handle = {read=ThisSocket, nodefault};
__property AnsiString Status = {read=_Status};
__property Classes::TNotifyEvent OnRead = {read=FOnReadEvent, write=FOnReadEvent};
__property Classes::TNotifyEvent OnPacketRecvd = {read=FPacketRecvd, write=FPacketRecvd};
__property Classes::TNotifyEvent OnPacketSent = {read=FPacketSent, write=FPacketSent};
__published:
__property AnsiString Host = {read=ServerName, write=ServerName};
__property int Port = {read=FPort, write=FPort, nodefault};
__property int TimeOut = {read=FTimeOut, write=FTimeOut, default=0};
__property int ReportLevel = {read=FReportLevel, write=FReportLevel, default=1};
__property Classes::TNotifyEvent OnDisconnect = {read=FOnDisconnect, write=FOnDisconnect};
__property Classes::TNotifyEvent OnConnect = {read=FOnConnect, write=FOnConnect};
__property THandlerEvent OnInvalidHost = {read=FInvalidHost, write=FInvalidHost};
__property TOnHostResolved OnHostResolved = {read=FOnHostResolved, write=FOnHostResolved};
__property TOnStatus OnStatus = {read=FOnStatus, write=FOnStatus};
__property Classes::TNotifyEvent OnConnectionFailed = {read=FOnConnectionFailed, write=FOnConnectionFailed};
__property TNMReg* About = {read=FAbout, write=FAbout};
};
class DELPHICLASS TNMGeneralServer;
typedef TNMGeneralServer* *PTNMGeneralServer;
class PASCALIMPLEMENTATION TNMGeneralServer : public TPowersock
{
typedef TPowersock inherited;
private:
Classes::TThreadList* ATlist;
Classes::TNotifyEvent FOnClientContact;
protected:
TNMGeneralServer* Chief;
public:
Classes::TThread* ItsThread;
__fastcall virtual TNMGeneralServer(Classes::TComponent* AOwner);
virtual void __fastcall Connect(void);
virtual void __fastcall Loaded(void);
virtual void __fastcall Serve(void);
virtual void __fastcall Abort(void);
__fastcall virtual ~TNMGeneralServer(void);
void __fastcall ServerAccept(System::TObject* Sender);
__published:
__property Classes::TNotifyEvent OnClientContact = {read=FOnClientContact, write=FOnClientContact};
};
class DELPHICLASS InstantiateServethread;
class PASCALIMPLEMENTATION InstantiateServethread : public Classes::TThread
{
typedef Classes::TThread inherited;
private:
TNMGeneralServer* ServSock;
protected:
virtual void __fastcall Execute(void);
public:
__fastcall InstantiateServethread(Classes::TComponent* Owner, Word ItsSocket);
__fastcall virtual ~InstantiateServethread(void);
};
//-- var, const, procedure ---------------------------------------------------
static const Shortint FD_ALL = 0x3f;
static const int MAX_RECV_BUF = 0x10000;
static const Shortint Status_None = 0x0;
static const Shortint Status_Informational = 0x1;
static const Shortint Status_Basic = 0x2;
static const Shortint Status_Routines = 0x4;
static const Shortint Status_Debug = 0x8;
static const Shortint Status_Trace = 0x10;
static const char CR = '\xd';
static const char LF = '\xa';
#define CRLF "\r\n"
static const Word WM_ASYNCHRONOUSPROCESS = 0x465;
static const Word WM_WAITFORRESPONSE = 0x466;
extern PACKAGE TErrorMessage WinsockMessage[51];
extern PACKAGE AnsiString __fastcall NthWord(AnsiString InputString, char Delimiter, int Number);
extern PACKAGE int __fastcall NthPos(AnsiString InputString, char Delimiter, int Number);
extern PACKAGE void __fastcall StreamLn(Classes::TStream* AStream, AnsiString AString);
extern PACKAGE HWND __fastcall PsockAllocateHWnd(System::TObject* Obj);
extern PACKAGE HWND __fastcall TmrAllocateHWnd(System::TObject* Obj);
} /* namespace Psock */
using namespace Psock;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // Psock
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
] | [
[
[
1,
461
]
]
] |
a3112475ce28e0fbc4ff04a3b45afe957f85889d | c2ffd6042f31e6f524a9b275e8242a7f18525f67 | /injector/injector/injector.cpp | 4d43e0b4cb1a822de2373178e9b9b5fedb5f21e3 | [] | no_license | tadasv/splinterbyte | 76ac6b64b192eb1d4d53b7e2c4ac8ca54c0168bb | d8b674d4dc9a6f7a186972b18cf33a6abcf29e95 | refs/heads/master | 2016-09-03T06:52:46.970481 | 2011-05-18T03:20:07 | 2011-05-18T03:20:07 | 1,764,249 | 9 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,142 | cpp | // injector.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
if (argc < 3) {
printf("Usage: injector <command line> <path to dll>\n");
return -1;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
HMODULE hKernel32;
HANDLE hRemoteThread;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
// Create suspended process
if(!CreateProcess(NULL,
argv[1],
NULL,
NULL,
FALSE,
CREATE_NEW_CONSOLE | CREATE_SUSPENDED | NORMAL_PRIORITY_CLASS,
NULL,
NULL,
&si, &pi))
{
printf("EE CreateProcess() failed. Error: %u\n", GetLastError());
return -1;
}
printf("II %s\n", argv[1]);
printf("II PID: %u\n", pi.dwProcessId);
printf("II TID: %u\n", pi.dwThreadId);
// Prepare process for DLL injection
LPVOID pFilename = VirtualAllocEx(pi.hProcess, NULL, strlen(argv[2]) + 1,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (pFilename == NULL) {
printf("EE VirtualAllocEx() failed. Error: %u\n", GetLastError());
if (!TerminateProcess(pi.hProcess, 0))
printf("EE TerminateProcess() failed. Error: %u\n", GetLastError());
return -1;
}
if (!GetModuleHandleEx(0, "kernel32.dll", &hKernel32)) {
printf("EE GetModuleHandleEx() failed. Error: %u\n", GetLastError());
goto cleanup;
}
if (!WriteProcessMemory(pi.hProcess, pFilename, argv[2], strlen(argv[2]), NULL)) {
printf("EE WriteProcessMemory() failed. Error: %u\n", GetLastError());
goto cleanup;
}
// inject DLL
hRemoteThread = CreateRemoteThread(pi.hProcess, NULL, NULL,
(LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32, "LoadLibraryA"),
pFilename, NULL, NULL);
if (hRemoteThread == NULL) {
printf("EE CreateRemoteThread() failed. Error: %u\n", GetLastError());
goto cleanup;
}
printf("II Waiting for remote thread to terminate.\n");
WaitForSingleObject(hRemoteThread, INFINITE);
HMODULE hInjection;
if (!GetExitCodeThread(hRemoteThread, (LPDWORD)&hInjection)) {
printf("EE GetExitCodeThread() failed. Error %u\n", GetLastError());
goto cleanup;
}
if (hInjection == NULL) {
printf("EE DLL injection failed\n");
goto cleanup;
} else {
printf("II Injection base. %08x\n", hInjection);
}
printf("II DLL injection was successful.\n");
if (!VirtualFreeEx(pi.hProcess, pFilename, 0, MEM_RELEASE))
printf("EE VirtualFreeEx() failed. Error %u\n", GetLastError());
pFilename = NULL;
if (ResumeThread(pi.hThread) == -1) {
printf("EE ResumeThread() failed. Error: %u\n", GetLastError());
}
if (pi.hProcess)
CloseHandle(pi.hProcess);
if (pi.hThread)
CloseHandle(pi.hThread);
if (hKernel32)
FreeLibrary(hKernel32);
return 0;
cleanup:
if (pFilename != NULL)
VirtualFreeEx(pi.hProcess, pFilename, 0, MEM_RELEASE);
if (!TerminateProcess(pi.hProcess, 0))
printf("EE TerminateProcess() failed. Error: %u\n", GetLastError());
if (pi.hProcess)
CloseHandle(pi.hProcess);
if (pi.hThread)
CloseHandle(pi.hThread);
if (hKernel32)
FreeLibrary(hKernel32);
return -1;
}
| [
"[email protected]"
] | [
[
[
1,
117
]
]
] |
f8ed39804077a1a5386236e5aa09f88552cb9f04 | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src/MtlProfile.h | 486e080b7f3d37da6c8c930e2f1ccf360d80d0bd | [] | no_license | plus7/DonutG | b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6 | 2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b | refs/heads/master | 2020-06-01T15:30:31.747022 | 2010-08-21T18:51:01 | 2010-08-21T18:51:01 | 767,753 | 1 | 2 | null | null | null | null | SHIFT_JIS | C++ | false | false | 26,185 | h | /**
* @file MtlProfile.h
* @brief MTL : プロファイラル.
*/
// MTL Version 0.03
// Copyright (C) 2000 MB<[email protected]>
// All rights unreserved.
//
// This file is a part of Mb Template Library.
// The code and information is *NOT* provided "as-is" without
// warranty of any kind, either expressed or implied.
//
// Last updated: August 16, 2000
#ifndef __MTLPROFILE_H__
#define __MTLPROFILE_H__
#pragma once
#include <stdafx.h>
#include <functional>
#include <iterator>
#include <algorithm>
#include <atlctrls.h>
#include <stdlib.h>
#include "Misc.h"
#include "MtlMisc.h"
#include "IniFile.h"
// #define _MTL_PROFILE_EXTRA_TRACE
namespace MTL {
using Misc::CRegKey; // using ATL::CRegKey; //+++ atl3対策でラッパーを通すようにした.
using ATL::CSimpleArray;
using WTL::CString;
using WTL::CReBarCtrl;
using WTL::CToolBarCtrl;
/////////////////////////////////////////////////////////////////////////////
// CProfileBinary, an adaptor
template <class _Profile>
class CProfileBinary {
public:
explicit CProfileBinary(_Profile &__x) : profile(&__x) { }
private:
// Operations
LONG SetValue(LPBYTE pValue, LPCTSTR lpszValueName, UINT nBytes)
{
// convert to string and write out
LPTSTR lpsz = new TCHAR[nBytes * 2 + 1];
for (UINT i = 0; i < nBytes; i++) {
lpsz[i * 2] = (TCHAR) ( (pValue[i] & 0x0F) + 'A' ); //low nibble
lpsz[i * 2 + 1] = (TCHAR) ( ( (pValue[i] >> 4) & 0x0F ) + 'A' ); //high nibble
}
lpsz[i * 2] = 0;
LONG lRet = profile->SetValue(lpsz, lpszValueName);
delete[] lpsz;
return lRet;
}
LONG QueryValue(BYTE **ppValue, LPCTSTR lpszValueName, UINT *pBytes)
{
ATLASSERT(ppValue != NULL);
ATLASSERT(pBytes != NULL);
*ppValue = NULL;
*pBytes = 0;
enum { SIZE = 4096 };
TCHAR szT[SIZE + 1];
ZeroMemory(szT, sizeof szT); //+++
DWORD dwCount = SIZE;
LONG lRet = profile->QueryValue(szT, lpszValueName, &dwCount);
if (lRet != ERROR_SUCCESS)
return lRet;
ATLASSERT(::lstrlen(szT) % 2 == 0);
int nLen = ::lstrlen(szT);
*pBytes = nLen / 2;
*ppValue = new BYTE[*pBytes];
for (int i = 0; i < nLen; i += 2) {
(*ppValue)[i / 2] = (BYTE) ( ( (szT[i + 1] - 'A') << 4 ) + (szT[i] - 'A') );
}
return lRet;
}
private: //protected:
_Profile *profile;
};
// Specialization for Misc::CRegKey
template <>
class CProfileBinary<Misc::CRegKey> {
public:
explicit CProfileBinary(Misc::CRegKey &__x) : regkey(&__x) { }
private:
// Operations
LONG SetValue(LPBYTE lpValue, LPCTSTR lpszValueName, UINT nBytes)
{
ATLASSERT(lpValue != NULL);
ATLASSERT(regkey->m_hKey != NULL);
return ::RegSetValueEx(regkey->m_hKey, lpszValueName, NULL, REG_BINARY, lpValue, nBytes);
}
LONG QueryValue(BYTE **ppValue, LPCTSTR lpszValueName, UINT *pBytes)
{
ATLASSERT(regkey->m_hKey != NULL);
DWORD dwType, dwCount;
LONG lResult = ::RegQueryValueEx(regkey->m_hKey, (LPTSTR) lpszValueName, NULL, &dwType, NULL, &dwCount);
*pBytes = dwCount;
if (lResult == ERROR_SUCCESS) {
ATLASSERT(dwType == REG_BINARY);
*ppValue = new BYTE[*pBytes];
lResult = ::RegQueryValueEx(regkey->m_hKey, (LPTSTR) lpszValueName, NULL, &dwType, *ppValue, &dwCount);
}
if (lResult != ERROR_SUCCESS) {
delete[] *ppValue;
*ppValue = NULL;
}
return lResult;
}
private:
Misc::CRegKey *regkey;
};
template <class _Profile>
inline CProfileBinary<_Profile> MtlProfileBinary(_Profile &__x)
{
return CProfileBinary<_Profile>(__x);
}
/////////////////////////////////////////////////////////////////////////////
// CWindowPlacement
class CWindowPlacement : public WINDOWPLACEMENT {
public:
// Constructors
CWindowPlacement()
{
length = sizeof (WINDOWPLACEMENT);
// random filled
}
CWindowPlacement(const WINDOWPLACEMENT &srcWndpl)
{
*(WINDOWPLACEMENT *) this = srcWndpl;
}
// Profile Operations
template <class _Profile>
void WriteProfile( _Profile &__profile, const CString &strPrefix = _T("wp.") ) const
{
MTLVERIFY(__profile.SetValue( flags , strPrefix + _T("flags") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( showCmd , strPrefix + _T("showCmd") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( ptMinPosition.x , strPrefix + _T("ptMinPosition.x") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( ptMinPosition.y , strPrefix + _T("ptMinPosition.y") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( ptMaxPosition.x , strPrefix + _T("ptMaxPosition.x") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( ptMaxPosition.y , strPrefix + _T("ptMaxPosition.y") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( rcNormalPosition.left , strPrefix + _T("rcNormalPosition.left") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( rcNormalPosition.top , strPrefix + _T("rcNormalPosition.top") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( rcNormalPosition.right, strPrefix + _T("rcNormalPosition.right") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( rcNormalPosition.bottom,strPrefix + _T("rcNormalPosition.bottom") ) == ERROR_SUCCESS);
}
template <class _Profile>
bool GetProfile( _Profile &__profile, const CString &strPrefix = _T("wp.") )
{
DWORD dwFlags = 0, dwShowCmd = 0,
dwMinX = 0, dwMinY = 0, dwMaxX = 0, dwMaxY = 0,
dwLeft = 0, dwTop = 0, dwRight = 0, dwBottom = 0;
if ( __profile.QueryValue( dwFlags , strPrefix + _T("flags") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwShowCmd, strPrefix + _T("showCmd") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwMinX , strPrefix + _T("ptMinPosition.x") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwMinY , strPrefix + _T("ptMinPosition.y") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwMaxX , strPrefix + _T("ptMaxPosition.x") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwMaxY , strPrefix + _T("ptMaxPosition.y") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwLeft , strPrefix + _T("rcNormalPosition.left") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwTop , strPrefix + _T("rcNormalPosition.top") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwRight , strPrefix + _T("rcNormalPosition.right") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwBottom , strPrefix + _T("rcNormalPosition.bottom")) == ERROR_SUCCESS)
{
flags = dwFlags;
showCmd = dwShowCmd;
ptMinPosition.x = dwMinX;
ptMinPosition.y = dwMinY;
ptMaxPosition.x = dwMaxX;
ptMaxPosition.y = dwMaxY;
rcNormalPosition.left = dwLeft;
rcNormalPosition.top = dwTop;
rcNormalPosition.right = dwRight;
rcNormalPosition.bottom = dwBottom;
return true;
}
return false;
}
private:
// Additional Operations
void operator =(const WINDOWPLACEMENT &srcWndpl)
{
*(WINDOWPLACEMENT *) this = srcWndpl;
}
public:
// Helper Operations
bool IsInsideScreen() const
{
#ifndef SM_CMONITORS
#define SM_XVIRTUALSCREEN 76
#define SM_YVIRTUALSCREEN 77
#define SM_CXVIRTUALSCREEN 78
#define SM_CYVIRTUALSCREEN 79
#define SM_CMONITORS 80
#endif
// I separate the code with multi or not, so I guess no need to install multimon.h's stub
int nMonitorCount = ::GetSystemMetrics(SM_CMONITORS);
// if win95, it will fail and return 0.
if (nMonitorCount > 0) { // multi monitor
int left = ::GetSystemMetrics(SM_XVIRTUALSCREEN);
int top = ::GetSystemMetrics(SM_YVIRTUALSCREEN);
CRect rcMonitor(
left,
top,
left + ::GetSystemMetrics(SM_CXVIRTUALSCREEN),
top + ::GetSystemMetrics(SM_CYVIRTUALSCREEN) );
if ( MtlIsCrossRect(rcMonitor, rcNormalPosition) )
return true;
else
return false;
} else {
CRect rcScreen( 0, 0, ::GetSystemMetrics(SM_CXSCREEN), ::GetSystemMetrics(SM_CYSCREEN) );
if ( MtlIsCrossRect(rcScreen, rcNormalPosition) )
return true;
else
return false;
}
}
private:
// Binary Profile Operations
template <class _ProfileBinary>
bool WriteProfileBinary( _ProfileBinary &__profile, const CString &strValueName = _T("WindowPlacement") ) const
{
LONG lRet = __profile.SetValue( (LPBYTE) this, strValueName, sizeof (WINDOWPLACEMENT) );
if (lRet == ERROR_SUCCESS)
return true;
else
return false;
}
template <class _ProfileBinary>
bool GetProfileBinary( _ProfileBinary &__profile, const CString &strValueName = _T("WindowPlacement") )
{
LPBYTE pData;
UINT nBytes;
LONG lRet = __profile.QueryValue(&pData, strValueName, &nBytes);
if (lRet != ERROR_SUCCESS)
return false;
::memcpy(static_cast<WINDOWPLACEMENT *>(this), pData, nBytes);
delete[] pData;
return true;
}
};
/////////////////////////////////////////////////////////////////////////////
// CLogFont
static const LOGFONT _lfDefault = {
0, 0, 0, 0, 0, FALSE, FALSE, FALSE, SHIFTJIS_CHARSET, //DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, _T("")
};
class CLogFont : public LOGFONT { // Fixed by DOGSTORE for serialization of 'lfCharSet', Thanks
public:
// Constructor
CLogFont()
{
// random filled
}
CLogFont(const LOGFONT &srcLogFont)
{
*(LOGFONT *) this = srcLogFont;
}
void InitDefault()
{
*(LOGFONT *) this = _lfDefault;
}
// Profile methods
template <class _Profile>
void WriteProfile( _Profile &__profile, HDC hDC = NULL, const CString &strPrefix = _T("lf.") ) const
{
MTLVERIFY(__profile.SetStringUW(lfFaceName, strPrefix + _T("lfFaceName" ) ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( GetPointSizeFromHeight(lfHeight, hDC), strPrefix + _T("lfPointSize") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( lfWeight, strPrefix + _T("lfWeight" ) ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( lfItalic, strPrefix + _T("lfItalic" ) ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( lfUnderline, strPrefix + _T("lfUnderLine") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( lfStrikeOut, strPrefix + _T("lfStrikeOut") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( lfCharSet, strPrefix + _T("lfCharSet" ) ) == ERROR_SUCCESS);
}
template <class _Profile>
bool GetProfile( _Profile &__profile, HDC hDC = NULL, const CString &strPrefix = _T("lf.") )
{
DWORD dwFaceSize = LF_FACESIZE, dwPointSize = 0, dwWeight = 0, dwItalic = 0, dwUnderline = 0, dwStrikeOut = 0, dwCharSet = 0;
CString strLfFaceName = __profile.GetStringUW(strPrefix + _T("lfFaceName")); //+++ UNICODE文字対応
if ( /* __profile.QueryString(lfFaceName , strPrefix + _T("lfFaceName"), &dwFaceSize) == ERROR_SUCCESS */
! strLfFaceName.IsEmpty() //+++
&& __profile.QueryValue( dwPointSize, strPrefix + _T("lfPointSize") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwWeight , strPrefix + _T("lfWeight") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwItalic , strPrefix + _T("lfItalic") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwUnderline, strPrefix + _T("lfUnderLine") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwStrikeOut, strPrefix + _T("lfStrikeOut") ) == ERROR_SUCCESS
&& __profile.QueryValue( dwCharSet , strPrefix + _T("lfCharSet") ) == ERROR_SUCCESS)
{
::lstrcpyn(lfFaceName, strLfFaceName, dwFaceSize); //+++
lfHeight = GetHeightFromPointSize(dwPointSize, hDC);
lfWeight = dwWeight;
lfItalic = (BYTE) dwItalic;
lfUnderline = (BYTE) dwUnderline;
lfStrikeOut = (BYTE) dwStrikeOut;
lfCharSet = (BYTE) dwCharSet;
return true;
}
return false;
}
// Additional Operations
void operator =(const LOGFONT &srcLogFont)
{
*(LOGFONT *) this = srcLogFont;
}
bool operator ==(const LOGFONT &lf) const
{
return ( lfHeight == lf.lfHeight
&& lfWidth == lf.lfWidth
&& lfEscapement == lf.lfEscapement
&& lfOrientation == lf.lfOrientation
&& lfWeight == lf.lfWeight
&& lfItalic == lf.lfItalic
&& lfUnderline == lf.lfUnderline
&& lfStrikeOut == lf.lfStrikeOut
&& lfCharSet == lf.lfCharSet
&& lfOutPrecision == lf.lfOutPrecision
&& lfClipPrecision == lf.lfClipPrecision
&& lfQuality == lf.lfQuality
&& lfPitchAndFamily == lf.lfPitchAndFamily
&& ::lstrcmp(lfFaceName, lf.lfFaceName) == 0);
}
bool operator !=(const LOGFONT &lf) const
{
return !(*this == lf);
}
private:
// Helper Operations
static LONG GetHeightFromPointSize(LONG nPointSize, HDC hDC = NULL)
{ // cf.WTL::CFont::CreatePointFontIndirect
HDC hDC1 = (hDC != NULL) ? hDC : ( ::GetDC(NULL) );
// convert nPointSize to logical units based on hDC
POINT pt = {0, 0};
//pt.y = ::GetDeviceCaps(hDC1, LOGPIXELSY) * nPointSize;
//pt.y /= 72; // 72 points/inch, 10 decipoints/point
pt.y = ::MulDiv(::GetDeviceCaps(hDC1, LOGPIXELSY), nPointSize, 72);
::DPtoLP(hDC1, &pt, 1);
POINT ptOrg = { 0, 0 };
::DPtoLP(hDC1, &ptOrg, 1);
if (hDC == NULL)
::ReleaseDC(NULL, hDC1);
return -abs(pt.y - ptOrg.y);
}
static LONG GetPointSizeFromHeight(LONG nHeight, HDC hDC = NULL)
{
HDC hDC1 = (hDC != NULL) ? hDC : ( ::GetDC(NULL) );
LONG nPointSize = ::MulDiv( -nHeight, 72, ::GetDeviceCaps(hDC1, LOGPIXELSY) );
if (hDC == NULL)
::ReleaseDC(NULL, hDC1);
return nPointSize;
}
};
/////////////////////////////////////////////////////////////////////////////
// MtlWrite&GetProfileMainFrameState
template <class _Profile>
void MtlWriteProfileMainFrameState( _Profile &__profile, HWND hWnd, const CString strPrefix = _T("frame.") )
{
ATLASSERT( ::IsWindow(hWnd) );
CWindowPlacement wndpl;
MTLVERIFY( ::GetWindowPlacement(hWnd, &wndpl) );
wndpl.WriteProfile(__profile, strPrefix);
}
//+++ 返値を追加: 0=最小化 1=通常 2=最大化 3:フル (とりあえずのtray復帰対策用...あとで変更予定)
template <class _Profile>
int MtlGetProfileMainFrameState(
_Profile & __profile,
HWND hWnd,
int nCmdShow,
bool bShowNoMinimized = true,
const CString strPrefix = _T("frame.") )
{
ATLASSERT( ::IsWindow(hWnd) );
CWindowPlacement wndpl;
if ( wndpl.GetProfile(__profile, strPrefix) && wndpl.IsInsideScreen() ) {
if (bShowNoMinimized) {
if (wndpl.showCmd == SW_SHOWMINIMIZED) {
if (wndpl.flags & WPF_RESTORETOMAXIMIZED)
wndpl.showCmd = SW_SHOWMAXIMIZED;
#if 0 //+++ unDonut r13test ではここが有効
else
wndpl.showCmd = SW_SHOWNORMAL;
#endif
}
}
nCmdShow = wndpl.showCmd; //+++
MTLVERIFY( ::SetWindowPlacement(hWnd, &wndpl) );
} else {
::ShowWindow(hWnd, nCmdShow);
}
#if 1 //+++ とりあえずのtray復帰対策
if (nCmdShow == SW_SHOWMAXIMIZED)
return 2;
//if (nCmdShow == SW_SHOWMINIMIZED)
// return 0;
return 1;
#endif
}
/////////////////////////////////////////////////////////////////////////////
// MtlWrite&GetProfileChildFrameState
template <class _Profile>
void MtlWriteProfileChildFrameState(
_Profile& __profile,
HWND hWnd,
const CString strPrefix = _T("frame.") )
{
ATLASSERT( ::IsWindow(hWnd) );
CWindowPlacement wndpl;
MTLVERIFY( ::GetWindowPlacement(hWnd, &wndpl) );
wndpl.WriteProfile(__profile, strPrefix);
}
template <class _Profile>
void MtlGetProfileChildFrameState(
_Profile & __profile,
HWND hWnd,
int nCmdShowDefault,
bool bShowNoActivate = false,
const CString strPrefix = _T("frame.") )
{
ATLASSERT( ::IsWindow(hWnd) );
CWindowPlacement wndpl;
if ( wndpl.GetProfile(__profile, strPrefix) && wndpl.IsInsideScreen() ) {
if (bShowNoActivate) {
if (wndpl.showCmd == SW_SHOWMINIMIZED)
wndpl.showCmd = SW_SHOWMINNOACTIVE;
else {
wndpl.showCmd = SW_SHOWNOACTIVATE;
}
}
MTLVERIFY( ::SetWindowPlacement(hWnd, &wndpl) );
} else {
if (bShowNoActivate)
nCmdShowDefault = SW_SHOWNOACTIVATE;
::ShowWindow(hWnd, nCmdShowDefault);
}
}
/////////////////////////////////////////////////////////////////////////////
// MtlWrite&GetProfileRebarBandsState
//+++
inline const CString dword_ptr_to_str(DWORD_PTR n)
{
char buf[128];
buf[0] = 0;
#ifdef _WIN64
_ui64toa(DWORD_PTR(n), buf, 10);
#else
_ultoa (DWORD(n), buf, 10);
#endif
return CString(buf);
}
template <class _Profile>
void MtlWriteProfileReBarBandsState( _Profile &__profile, CReBarCtrl rebar, const CString &strPrefix = _T("band") )
{
for (int nIndex = 0;; ++nIndex) {
CVersional<REBARBANDINFO> rbBand;
rbBand.fMask = RBBIM_SIZE | RBBIM_STYLE | RBBIM_CHILD;
if ( !rebar.GetBandInfo(nIndex, &rbBand) )
break;
CString strBuff = strPrefix + _T("#");
HANDLE hID = (HANDLE) ::GetProp( rbBand.hwndChild, _T("Donut_Plugin_ID") );
if (hID == NULL) {
strBuff.Append( CWindow(rbBand.hwndChild).GetDlgCtrlID() );
} else {
strBuff += dword_ptr_to_str(DWORD_PTR(hID));
::RemoveProp( rbBand.hwndChild, _T("Donut_Plugin_ID") );
}
MTLVERIFY(__profile.SetValue( nIndex, strBuff + _T(".index") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( rbBand.cx, strBuff + _T(".cx") ) == ERROR_SUCCESS);
MTLVERIFY(__profile.SetValue( rbBand.fStyle, strBuff + _T(".fStyle") ) == ERROR_SUCCESS);
}
}
struct CReBarBandInfo {
UINT nIndex; // must be filled, cause stable_sort requires CRT
HWND hWnd;
UINT_PTR nID;
UINT fStyle;
LPTSTR lpText;
UINT cx; // can be 0
};
template <class _MainFrame>
class __AddBand : public std::unary_function<const CReBarBandInfo &, void> {
public:
explicit __AddBand(_MainFrame &__m) : mainFrame(&__m) { }
void operator ()(const CReBarBandInfo &arg)
{
_MainFrame::AddSimpleReBarBandCtrl(mainFrame->m_hWndToolBar, arg.hWnd, arg.nID, arg.lpText, arg.fStyle, arg.cx, FALSE);
}
protected:
_MainFrame *mainFrame;
};
class __ShowBand : public std::unary_function<const CReBarBandInfo &, void> {
public:
explicit __ShowBand(HWND hWndReBar) : rebar(hWndReBar) , nIndex(0) { }
void operator ()(const CReBarBandInfo &arg)
{
rebar.ShowBand(nIndex++, (arg.fStyle & RBBS_HIDDEN) == 0 );
}
protected:
CReBarCtrl rebar;
int nIndex;
};
struct __ReBarBandInfoIndexOrdering : public std::binary_function<const CReBarBandInfo &, const CReBarBandInfo &, bool> {
bool operator ()(const CReBarBandInfo &arg1, const CReBarBandInfo &arg2) const
{
return arg1.nIndex < arg2.nIndex;
}
};
template <class _Profile, class _MainFrame>
bool MtlGetProfileReBarBandsState( CReBarBandInfo *__first, CReBarBandInfo *__last, _Profile __profile, _MainFrame &__mainFrame, const CString &strPrefix = _T("band") )
{
if (__first == __last)
return false;
CSimpleArray<CReBarBandInfo> tmp;
for (; __first != __last; ++__first) {
CString strBuff = strPrefix + _T("#");
strBuff += dword_ptr_to_str(__first->nID);
DWORD dwIndex = 0, dwCx = 0, dwStyle = 0;
if ( __profile.QueryValue( dwIndex , strBuff + _T(".index" ) ) == ERROR_SUCCESS
&& __profile.QueryValue( dwCx , strBuff + _T(".cx" ) ) == ERROR_SUCCESS
&& __profile.QueryValue( dwStyle , strBuff + _T(".fStyle") ) == ERROR_SUCCESS)
{
__first->nIndex = dwIndex;
__first->cx = dwCx;
__first->fStyle = dwStyle;
}
tmp.Add(*__first); // even if value not found, user's supplements used as default
}
if (tmp.GetSize() == 0) // need
return false;
// I want use std::stable_sort for users, but it requires CRT.
// I think easy sort algorithms have to be added to ATL/WTL.
std::sort ( &tmp[0], &tmp[0] + tmp.GetSize(), __ReBarBandInfoIndexOrdering() );
std::for_each( &tmp[0], &tmp[0] + tmp.GetSize(), __AddBand<_MainFrame>(__mainFrame) );
std::for_each( &tmp[0], &tmp[0] + tmp.GetSize(), __ShowBand(__mainFrame.m_hWndToolBar) );
return true;
}
/////////////////////////////////////////////////////////////////////////////
// MtlWrite&GetProfileStatusBarState
template <class _Profile>
bool MtlGetProfileStatusBarState(
_Profile & __profile,
HWND hWndStatusBar,
BOOL & bVisible,
const CString& strPrefix = _T("statusbar.") )
{
ATLASSERT( ::IsWindow(hWndStatusBar) );
DWORD dwValue = 0;
LONG lRet = __profile.QueryValue( dwValue, strPrefix + _T("Visible") );
if (lRet != ERROR_SUCCESS) {
bVisible = TRUE;
return false;
}
bVisible = (dwValue == 1) /*? TRUE : FALSE*/;
MTLVERIFY( ::ShowWindow(hWndStatusBar, bVisible ? SW_SHOWNOACTIVATE : SW_HIDE) );
return true;
}
/////////////////////////////////////////////////////////////////////////////
// Global functions for Profile
// app.exe -> APP.INI
// App.exe -> App.ini
inline void MtlIniFileNameInit( LPTSTR lpszIniFileName, DWORD nSize, LPCTSTR lpszExtText = _T(".INI") )
{
// cf.ATL::AtlModuleLoadTypeLib (we can't use _tsplitpath that requires CRT)
::GetModuleFileName(_Module.GetModuleInstance(), lpszIniFileName, nSize);
LPTSTR lpszExt = NULL;
LPTSTR lpsz;
for ( lpsz = lpszIniFileName; *lpsz != NULL; lpsz = ::CharNext(lpsz) ) {
if ( *lpsz == _T('.') )
lpszExt = lpsz;
}
if (lpszExt == NULL)
lpszExt = lpsz;
ATLASSERT(::lstrlen(lpszExtText) == 4);
::lstrcpy(lpszExt, lpszExtText);
#ifdef _MTL_PROFILE_EXTRA_TRACE
ATLTRACE2(atlTraceUI, 0, _T("MtlIniFileNameInit : %s\n"), lpszIniFileName);
#endif
}
/////////////////////////////////////////////////////////////////////////////
// MtlWrite&GetProfileString
template <class _InputIterString, class _Profile>
bool MtlWriteProfileString(
_InputIterString __first,
_InputIterString __last,
_Profile & __profile,
const CString & strPrefix = _T("string"),
DWORD nStartSuffix = 0)
{
// set new values
for (int n = nStartSuffix; __first != __last; ++__first, ++n) {
CString strBuff = strPrefix;
strBuff.Append(n);
MTLVERIFY(__profile.SetStringValue(strBuff, *__first) == ERROR_SUCCESS);
}
return true;
}
template <class _Profile, class _OutputIterString>
bool MtlGetProfileString(
_Profile & __profile,
_OutputIterString __result,
const CString & strPrefix = _T("string"),
DWORD nStartSuffix = 0,
DWORD nLastSuffix = -1)
{
_OutputIterString __resultSrc = __result;
DWORD n;
for (n = nStartSuffix;; ++n) {
CString strBuff = strPrefix;
strBuff.Append(n);
enum { SIZE = 4096 };
TCHAR szT[SIZE + 1];
ZeroMemory(szT, sizeof szT); //+++
DWORD dwCount = SIZE;
LONG lRet = __profile.QueryStringValue(strBuff, szT, &dwCount);
if (lRet == ERROR_SUCCESS)
*__result++ = szT;
else
break;
if (n == nLastSuffix)
break;
}
if (n == nStartSuffix)
return false;
else
return true;
}
/////////////////////////////////////////////////////////////////////////////
// MtlWrite&GetProfileTBBtns
// This will save a bitmap index, so you can't change it by toolbar resource editor.
// If you want to add a new button for your new app's version, you have to add it last of all.
template <class _Profile>
void MtlWriteProfileTBBtns( _Profile &__profile, CToolBarCtrl toolbar, const CString &strPrefix = _T("button") )
{
int iBtn = toolbar.GetButtonCount();
MTLVERIFY(__profile.SetValue( iBtn, strPrefix + _T(".count") ) == ERROR_SUCCESS);
for (int n = 0; n < iBtn; ++n) {
TBBUTTON tbBtn;
MTLVERIFY( toolbar.GetButton(n, &tbBtn) );
CString strBuff = strPrefix;
strBuff.Append(n);
int nIndex;
if (tbBtn.fsStyle & TBSTYLE_SEP)
nIndex = -1;
else
nIndex = tbBtn.iBitmap;
MTLVERIFY(__profile.SetValue( nIndex, strBuff + _T(".iBitmap") ) == ERROR_SUCCESS);
}
}
template <class _Profile>
bool MtlGetProfileTBBtns( _Profile &__profile, CSimpleArray<int> &arrBmpIndex, const CString &strPrefix = _T("button") )
{
// load profile
DWORD dwCount;
LONG lRet = __profile.QueryValue( dwCount, strPrefix + _T(".count") );
if (lRet != ERROR_SUCCESS)
return false; //not found
// insert buttons
for (DWORD n = 0; n < dwCount; ++n) {
CString strBuff = strPrefix;
strBuff.Append(n);
DWORD dwBitmap;
if (__profile.QueryValue( dwBitmap, strBuff + _T(".iBitmap") ) == ERROR_SUCCESS) {
int iBmpIndex = dwBitmap;
arrBmpIndex.Add(iBmpIndex);
}
}
return true;
}
template <class _Profile>
bool MtlGetProfileTBBtns( _Profile &__profile, CToolBarCtrl toolbar, const CString &strPrefix = _T("button") )
{
ATLASSERT( toolbar.IsWindow() );
// load profile
DWORD dwCount;
LONG lRet = __profile.QueryValue( dwCount, strPrefix + _T(".count") );
if (lRet != ERROR_SUCCESS)
return false; //not found
int iBtn = toolbar.GetButtonCount();
TBBUTTON* pTBBtn = (TBBUTTON *) _alloca( iBtn * sizeof (TBBUTTON) );
// save original tbbuttons
for (int i = 0; i < iBtn; ++i) {
TBBUTTON tbBtn;
MTLVERIFY( toolbar.GetButton(i, &tbBtn) );
pTBBtn[i] = tbBtn;
}
// clean up previous toolbar buttons
while ( toolbar.DeleteButton(0) )
;
// insert buttons
for (DWORD n = 0; n < dwCount; ++n) {
CString strBuff = strPrefix;
strBuff.Append(n);
DWORD dwBitmap;
if (__profile.QueryValue( dwBitmap, strBuff + _T(".iBitmap") ) == ERROR_SUCCESS) {
if (dwBitmap == -1) { // separator
TBBUTTON tbBtn;
tbBtn.iBitmap = 8;
tbBtn.idCommand = 0;
tbBtn.fsState = 0;
tbBtn.fsStyle = TBSTYLE_SEP;
tbBtn.dwData = 0;
tbBtn.iString = 0;
MTLVERIFY( toolbar.InsertButton(toolbar.GetButtonCount(), &tbBtn) );
} else {
int i;
for (i = 0; i < iBtn; ++i) {
if (!(pTBBtn[i].fsStyle & TBSTYLE_SEP) && pTBBtn[i].iBitmap == dwBitmap) {
MTLVERIFY( toolbar.InsertButton(toolbar.GetButtonCount(), &pTBBtn[i]) );
break;
}
}
ATLASSERT(i != iBtn);
}
}
}
return true;
}
} //namespace MTL
#endif // __MTLPROFILE_H__
| [
"[email protected]"
] | [
[
[
1,
917
]
]
] |
80ec119698a99eb441328628c0aabe7345e1cefb | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Framework/NodeWater.cpp | f51080891e39379ca30fd207501de7f950195f9d | [] | 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 | 22,839 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: NodeWater.cpp
Version: 0.07
---------------------------------------------------------------------------
*/
#include "NodeWater.h"
#include "ISerializer.h"
#include "ReflectionStage.h"
#include "Material.h"
#include "MaterialLibrary.h"
#include "MaterialManager.h"
#include "PostStage.h"
#include "Shader.h"
#include "ShaderConstant.h"
#include "ShaderInstance.h"
#include "TimeDate.h"
#include "Timer.h"
namespace nGENE
{
namespace Nature
{
// Initialize static members
TypeInfo NodeWater::Type(L"NodeWater", &Node::Type);
NodeWater::NodeWater(ReflectionStage* _stage):
m_pWaterMat(NULL),
m_fDayLength(360.0f),
m_fAmplitude(1.0f),
m_fRefractionIndex(1.33333f),
m_fWaterLevel(0.0f),
m_fHorizontalVisibility(4.0f),
m_bSimulate(true),
m_pReflectionStage(_stage),
m_vecWind(-0.3f, 0.7f),
m_vecWavesScale(0.005f, 0.005f),
m_vecFoam(0.65f, 1.35f, 0.5f),
m_vecExtinction(7.0f, 30.0f, 40.0f),
m_fMuddiness(0.15f),
m_fRefractionStrength(0.0f),
m_fRefractionScale(0.005f),
m_fShoreHardness(1.0f),
m_fShininess(0.7f),
m_fNormalScale(1.0f),
m_fDisplace(1.7f),
m_SunAngle(0.0f)
{
m_SunRise.hours = 8;
m_Sunset.hours = 22;
}
//----------------------------------------------------------------------
NodeWater::~NodeWater()
{
// Release reflection
ReflectionStage::releaseReflection();
}
//----------------------------------------------------------------------
void NodeWater::init()
{
m_pWaterMat = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"water");
// Add water material
m_PostWater.priority = 0;
m_PostWater.material = m_pWaterMat;
((PostStage*)Renderer::getSingleton().getRenderStage(L"PostProcess"))->addToRender(&m_PostWater);
// Bind default reflection stage if not set already
if(!m_pReflectionStage)
m_pReflectionStage = (ReflectionStage*)Renderer::getSingleton().getRenderStage(L"Reflection");
// Set default properties
setWavesAmplitude(m_fAmplitude);
setDepthColour(m_DepthColour);
setDisplacement(m_fDisplace);
setExtinction(m_vecExtinction);
setFoam(m_vecFoam);
setHorizontalVisibility(m_fHorizontalVisibility);
setMuddiness(m_fMuddiness);
setNormalScale(m_fNormalScale);
setRefractionIndex(m_fRefractionIndex);
setRefractionScale(m_fRefractionScale);
setRefractionStrength(m_fRefractionStrength);
setShininess(m_fShininess);
setShoreHardness(m_fShoreHardness);
setSurfaceColour(m_SurfaceColour);
setWaterLevel(m_fWaterLevel);
setWavesScale(m_vecWavesScale);
setWind(m_vecWind);
if(!m_bSimulate)
setDayTime(m_Time);
m_dwLastTime = Engine::getSingleton().getTimer().getMilliseconds();
// Request reflections
ReflectionStage::requestReflection();
// Simulate at least once
update();
}
//----------------------------------------------------------------------
void NodeWater::setDayTime(const TimeDate& _time)
{
m_Time = _time;
float fPassed = _time.hours * 3600.0f + _time.minutes * 60.0f + _time.seconds;
float fSunRise = m_SunRise.hours * 3600.0f + m_SunRise.minutes * 60.0f + m_SunRise.seconds;
float fSunset = m_Sunset.hours * 3600.0f + m_Sunset.minutes * 60.0f + m_Sunset.seconds;
float fDayLength = fSunset - fSunRise;
m_SunAngle = (fPassed - fSunRise) / (fDayLength) * 180.0f;
Maths::clamp <float> (m_SunAngle, 0.0f, 180.0f);
updateColours();
updateWater();
}
//----------------------------------------------------------------------
void NodeWater::onUpdate()
{
// No need to run simulation
if(!m_bSimulate)
return;
float delta = static_cast<float>(Engine::getSingleton().getTimer().getMilliseconds() - m_dwLastTime);
Timer time = Engine::getSingleton().getTimer();
m_dwLastTime = time.getMilliseconds();
m_SunAngle += delta * 0.18f / m_fDayLength;
Maths::clamp_roll <float> (m_SunAngle, 0.0f, 180.0f);
updateWater();
updateColours();
}
//----------------------------------------------------------------------
void NodeWater::updateColours()
{
if(m_SunAngle <= 105.0f)
{
float fPassed = m_SunAngle / 75.0f;
Maths::clamp(fPassed, 0.0f, 1.0f);
m_SunColour.setRed(Maths::lerp <int>(205, 255, fPassed));
m_SunColour.setGreen(Maths::lerp <int>(92, 255, fPassed));
m_SunColour.setBlue(Maths::lerp <int>(92, 255, fPassed));
}
else if(m_SunAngle > 105.0f)
{
float fPassed = (m_SunAngle - 105.0f) / 75.0f;
m_SunColour.setRed(Maths::lerp <int>(255, 255, fPassed));
m_SunColour.setGreen(Maths::lerp <int>(255, 145, fPassed));
m_SunColour.setBlue(Maths::lerp <int>(255, 20, fPassed));
}
}
//----------------------------------------------------------------------
void NodeWater::updateWater()
{
float angle = m_SunAngle * Maths::PI / 180.0f;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("lightDir");
if(pConstant)
{
Vector3 dir = Vector3(-cos(angle), -sin(angle), 0.0f);
dir.normalize();
pConstant->setDefaultValue(dir.getData());
}
pConstant = pShader->getConstant("sunColor");
if(pConstant)
{
float colour[3] = {m_SunColour.getRedF(),
m_SunColour.getGreenF(),
m_SunColour.getBlueF()};
pConstant->setDefaultValue(colour);
}
}
}
//----------------------------------------------------------------------
void NodeWater::setWavesAmplitude(Real _amplitude)
{
m_fAmplitude = _amplitude;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("maxAmplitude");
if(pConstant)
pConstant->setDefaultValue(&m_fAmplitude);
}
}
//----------------------------------------------------------------------
void NodeWater::setRefractionIndex(Real _index)
{
m_fRefractionIndex = _index;
float R0 = powf(1.0f - _index, 2.0f) / powf(1.0f + _index, 2.0f);
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("R0");
if(pConstant)
pConstant->setDefaultValue(&R0);
}
}
//----------------------------------------------------------------------
void NodeWater::setWaterLevel(Real _level)
{
m_fWaterLevel = _level;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("waterLevel");
if(pConstant)
pConstant->setDefaultValue(&m_fWaterLevel);
}
if(m_pReflectionStage)
m_pReflectionStage->setReflectionPlane(0.0f, 1.0f, 0.0f, -m_fWaterLevel);
}
//----------------------------------------------------------------------
void NodeWater::setSurfaceColour(const Colour& _colour)
{
m_SurfaceColour = _colour;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
float colour[3] = {m_SurfaceColour.getRedF(),
m_SurfaceColour.getGreenF(),
m_SurfaceColour.getBlueF()};
pConstant = pShader->getConstant("depthColour");
if(pConstant)
pConstant->setDefaultValue(colour);
}
}
//----------------------------------------------------------------------
void NodeWater::setDepthColour(const Colour& _colour)
{
m_DepthColour = _colour;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
float colour[3] = {m_DepthColour.getRedF(),
m_DepthColour.getGreenF(),
m_DepthColour.getBlueF()};
pConstant = pShader->getConstant("bigDepthColour");
if(pConstant)
pConstant->setDefaultValue(colour);
}
}
//----------------------------------------------------------------------
void NodeWater::setHorizontalVisibility(Real _visibility)
{
m_fHorizontalVisibility = _visibility;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("visibility");
if(pConstant)
pConstant->setDefaultValue(&m_fHorizontalVisibility);
}
}
//----------------------------------------------------------------------
void NodeWater::setEnabled(bool _value)
{
if(_value && !m_bEnabled)
ReflectionStage::requestReflection();
else if(!_value && m_bEnabled)
ReflectionStage::releaseReflection();
m_pWaterMat->setEnabled(_value);
Node::setEnabled(_value);
}
//----------------------------------------------------------------------
void NodeWater::setReflectionStage(ReflectionStage* _stage)
{
m_pReflectionStage = _stage;
}
//----------------------------------------------------------------------
ReflectionStage* NodeWater::getReflectionStage() const
{
return m_pReflectionStage;
}
//----------------------------------------------------------------------
void NodeWater::setMaterial(Material* _material)
{
// Remove previous material
PostStage* pStage = ((PostStage*)Renderer::getSingleton().getRenderStage(L"PostProcess"));
if(m_pWaterMat)
pStage->removeFromRender(&m_PostWater);
// Add water material
m_pWaterMat = _material;
m_PostWater.priority = 0;
m_PostWater.material = m_pWaterMat;
pStage->addToRender(&m_PostWater);
// Set default properties
setWavesAmplitude(m_fAmplitude);
setDepthColour(m_DepthColour);
setDisplacement(m_fDisplace);
setExtinction(m_vecExtinction);
setFoam(m_vecFoam);
setHorizontalVisibility(m_fHorizontalVisibility);
setMuddiness(m_fMuddiness);
setNormalScale(m_fNormalScale);
setRefractionIndex(m_fRefractionIndex);
setRefractionScale(m_fRefractionScale);
setRefractionStrength(m_fRefractionStrength);
setShininess(m_fShininess);
setShoreHardness(m_fShoreHardness);
setSurfaceColour(m_SurfaceColour);
setWaterLevel(m_fWaterLevel);
setWavesScale(m_vecWavesScale);
setWind(m_vecWind);
if(!m_bSimulate)
setDayTime(m_Time);
m_dwLastTime = Engine::getSingleton().getTimer().getMilliseconds();
// Simulate at least once
update();
}
//----------------------------------------------------------------------
void NodeWater::setPosition(const Vector3& _pos)
{
Node::setPosition(_pos);
setWaterLevel(_pos.y);
}
//----------------------------------------------------------------------
void NodeWater::setPosition(Real _x, Real _y, Real _z)
{
Node::setPosition(_x, _y, _z);
setWaterLevel(_y);
}
//----------------------------------------------------------------------
void NodeWater::setFoam(const Vector3& _foam)
{
m_vecFoam = _foam;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("foamExistence");
if(pConstant)
pConstant->setDefaultValue(m_vecFoam.getData());
}
}
//----------------------------------------------------------------------
Vector3& NodeWater::getFoam()
{
return m_vecFoam;
}
//----------------------------------------------------------------------
void NodeWater::setMuddiness(Real _value)
{
m_fMuddiness = _value;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("fadeSpeed");
if(pConstant)
pConstant->setDefaultValue(&m_fMuddiness);
}
}
//----------------------------------------------------------------------
void NodeWater::setRefractionStrength(Real _value)
{
m_fRefractionStrength = _value;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("refractionStrength");
if(pConstant)
pConstant->setDefaultValue(&m_fRefractionStrength);
}
}
//----------------------------------------------------------------------
void NodeWater::setShoreHardness(Real _value)
{
m_fShoreHardness = _value;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("shoreHardness");
if(pConstant)
pConstant->setDefaultValue(&m_fShoreHardness);
}
}
//----------------------------------------------------------------------
void NodeWater::setShininess(Real _shininess)
{
m_fShininess = _shininess;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("shininess");
if(pConstant)
pConstant->setDefaultValue(&m_fShininess);
}
}
//----------------------------------------------------------------------
void NodeWater::setDisplacement(Real _displacement)
{
m_fDisplace = _displacement;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("displace");
if(pConstant)
pConstant->setDefaultValue(&m_fDisplace);
}
}
//----------------------------------------------------------------------
Vector3& NodeWater::getExtinction()
{
return m_vecExtinction;
}
//----------------------------------------------------------------------
void NodeWater::setExtinction(const Vector3& _extinction)
{
m_vecExtinction = _extinction;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("extinction");
if(pConstant)
pConstant->setDefaultValue(m_vecExtinction.getData());
}
}
//----------------------------------------------------------------------
void NodeWater::setWind(const Vector2& _wind)
{
m_vecWind = _wind;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("wind");
if(pConstant)
pConstant->setDefaultValue(m_vecWind.getData());
}
}
//----------------------------------------------------------------------
void NodeWater::setWavesScale(const Vector2& _scale)
{
m_vecWavesScale = _scale;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("scale");
if(pConstant)
pConstant->setDefaultValue(m_vecWavesScale.getData());
}
}
//----------------------------------------------------------------------
void NodeWater::setRefractionScale(Real _scale)
{
m_fRefractionScale = _scale;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("refractionScale");
if(pConstant)
pConstant->setDefaultValue(&m_fRefractionScale);
}
}
//----------------------------------------------------------------------
void NodeWater::setNormalScale(Real _scale)
{
m_fNormalScale = _scale;
if(m_pWaterMat)
{
RenderPass& pass = m_pWaterMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("normalScale");
if(pConstant)
pConstant->setDefaultValue(&m_fNormalScale);
}
}
//----------------------------------------------------------------------
void NodeWater::serialize(ISerializer* _serializer, bool _serializeType, bool _serializeChildren)
{
if(_serializeType) _serializer->addObject(this->Type);
Node::serialize(_serializer, false, _serializeChildren);
Property <float> prSunAngle(m_SunAngle);
_serializer->addProperty("SunAngle", prSunAngle);
Property <float> prDayLength(m_fDayLength);
_serializer->addProperty("DayLength", prDayLength);
Property <float> prAmplitude(m_fAmplitude);
_serializer->addProperty("Amplitude", prAmplitude);
Property <float> prMuddiness(m_fMuddiness);
_serializer->addProperty("Muddiness", prMuddiness);
Property <float> prRefractionStrength(m_fRefractionStrength);
_serializer->addProperty("RefractionStrength", prRefractionStrength);
Property <float> prRefractionIndex(m_fRefractionIndex);
_serializer->addProperty("RefractionIndex", prRefractionIndex);
Property <float> prRefractionScale(m_fRefractionScale);
_serializer->addProperty("RefractionScale", prRefractionScale);
Property <float> prWaterLevel(m_fWaterLevel);
_serializer->addProperty("WaterLevel", prWaterLevel);
Property <float> prShoreHardness(m_fShoreHardness);
_serializer->addProperty("ShoreHardness", prShoreHardness);
Property <float> prShininess(m_fShininess);
_serializer->addProperty("Shininess", prShininess);
Property <float> prDisplace(m_fDisplace);
_serializer->addProperty("Displace", prDisplace);
Property <float> prNormalScale(m_fNormalScale);
_serializer->addProperty("NormalScale", prNormalScale);
Property <float> prHorizontalVisibility(m_fHorizontalVisibility);
_serializer->addProperty("HorizontalVisibility", prHorizontalVisibility);
Property <Vector2> prWind(m_vecWind);
_serializer->addProperty("Wind", prWind);
Property <Vector2> prWavesScale(m_vecWavesScale);
_serializer->addProperty("WavesScale", prWavesScale);
Property <Vector3> prFoam(m_vecFoam);
_serializer->addProperty("Foam", prFoam);
Property <Vector3> prExtinction(m_vecExtinction);
_serializer->addProperty("Extinction", prExtinction);
Property <Colour> prSurfaceColour(m_SurfaceColour);
_serializer->addProperty("SurfaceColour", prSurfaceColour);
Property <Colour> prDepthColour(m_DepthColour);
_serializer->addProperty("DepthColour", prDepthColour);
Property <bool> prSimulate(m_bSimulate);
_serializer->addProperty("Simulated", prSimulate);
Property <TimeDate> prTime(m_Time);
_serializer->addProperty("Time", prTime);
Property <TimeDate> prSunRise(m_SunRise);
_serializer->addProperty("SunRise", prSunRise);
Property <TimeDate> prSunset(m_Sunset);
_serializer->addProperty("Sunset", prSunset);
if(_serializeType) _serializer->endObject(this->Type);
}
//----------------------------------------------------------------------
void NodeWater::deserialize(ISerializer* _serializer)
{
Property <float> prSunAngle(m_SunAngle);
_serializer->getProperty("SunAngle", prSunAngle);
Property <float> prDayLength(m_fDayLength);
_serializer->getProperty("DayLength", prDayLength);
Property <float> prAmplitude(m_fAmplitude);
_serializer->getProperty("Amplitude", prAmplitude);
Property <float> prMuddiness(m_fMuddiness);
_serializer->getProperty("Muddiness", prMuddiness);
Property <float> prRefractionStrength(m_fRefractionStrength);
_serializer->getProperty("RefractionStrength", prRefractionStrength);
Property <float> prRefractionIndex(m_fRefractionIndex);
_serializer->getProperty("RefractionIndex", prRefractionIndex);
Property <float> prRefractionScale(m_fRefractionScale);
_serializer->getProperty("RefractionScale", prRefractionScale);
Property <float> prWaterLevel(m_fWaterLevel);
_serializer->getProperty("WaterLevel", prWaterLevel);
Property <float> prShoreHardness(m_fShoreHardness);
_serializer->getProperty("ShoreHardness", prShoreHardness);
Property <float> prShininess(m_fShininess);
_serializer->getProperty("Shininess", prShininess);
Property <float> prDisplace(m_fDisplace);
_serializer->getProperty("Displace", prDisplace);
Property <float> prNormalScale(m_fNormalScale);
_serializer->getProperty("NormalScale", prNormalScale);
Property <float> prHorizontalVisibility(m_fHorizontalVisibility);
_serializer->getProperty("HorizontalVisibility", prHorizontalVisibility);
Property <Vector2> prWind(m_vecWind);
_serializer->getProperty("Wind", prWind);
Property <Vector2> prWavesScale(m_vecWavesScale);
_serializer->getProperty("WavesScale", prWavesScale);
Property <Vector3> prFoam(m_vecFoam);
_serializer->getProperty("Foam", prFoam);
Property <Vector3> prExtinction(m_vecExtinction);
_serializer->getProperty("Extinction", prExtinction);
Property <Colour> prSurfaceColour(m_SurfaceColour);
_serializer->getProperty("SurfaceColour", prSurfaceColour);
Property <Colour> prDepthColour(m_DepthColour);
_serializer->getProperty("DepthColour", prDepthColour);
Property <bool> prSimulate(m_bSimulate);
_serializer->getProperty("Simulated", prSimulate);
Property <TimeDate> prTime(m_Time);
_serializer->getProperty("Time", prTime);
Property <TimeDate> prSunRise(m_SunRise);
_serializer->getProperty("SunRise", prSunRise);
Property <TimeDate> prSunset(m_Sunset);
_serializer->getProperty("Sunset", prSunset);
Node::deserialize(_serializer);
}
//----------------------------------------------------------------------
}
} | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
682
]
]
] |
522f41e9f262ea5fe9f588ae3112af5f637f4292 | b731c89fae7986809fae57045dca707948796c3a | /ocr/ocr/GlobalCofig.cpp | 94e793261cdcec4767c0c11dc5e21033cc74d3e6 | [] | no_license | hy1314200/ocr1 | 285a99251c8f03954afb6bee30521b6d9fb1c912 | 051b07224a4689c01315aea53050b0c936085f8c | refs/heads/master | 2016-09-07T23:57:04.680763 | 2008-06-07T21:51:08 | 2008-06-07T21:51:08 | 38,354,665 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 287 | cpp | #include "GlobalCofig.h"
const char *GlobalCofig::s_configFilePath = "data/config";
ConfigFile *GlobalCofig::s_config = NULL;
ConfigFile *GlobalCofig::getConfigFile()
{
if(s_config == NULL){
s_config = ConfigFile::parseConfig(s_configFilePath);
}
return s_config;
} | [
"liuyi1985@8b243031-8947-0410-b39a-2b519deb81bd"
] | [
[
[
1,
14
]
]
] |
069aec3cdf36a65a44807432d4748791538481cb | 968aa9bac548662b49af4e2b873b61873ba6f680 | /imgtools/romtools/readimage/src/image_reader.cpp | 2ac927abbeb08bd4cf8dc0f792ff731cdf8f3cf6 | [] | no_license | anagovitsyn/oss.FCL.sftools.dev.build | b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3 | f458a4ce83f74d603362fe6b71eaa647ccc62fee | refs/heads/master | 2021-12-11T09:37:34.633852 | 2010-12-01T08:05:36 | 2010-12-01T08:05:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,405 | cpp | /*
* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
* @internalComponent
* @released
*
*/
#include "image_reader.h"
#include <stdio.h>
#include <stdlib.h>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
ImageReader::ImageReader(const char* aFile) : iDisplayOptions(0),iImgFileName(aFile) {
}
ImageReader::~ImageReader() {
}
void ImageReader::SetDisplayOptions(TUint32 aFlag) {
iDisplayOptions |= aFlag;
}
bool ImageReader::DisplayOptions(TUint32 aFlag) {
return ((iDisplayOptions & aFlag) != 0);
}
void ImageReader::DumpData(TUint* aData, TUint aLength) {
TUint *p=aData;
TUint i=0;
char line[256];
char *cp=(char*)aData;
TUint j=0;
memset(line,' ',sizeof(line));
while (i<aLength) {
TUint ccount=0;
char* linep=&line[8*5+2];
*out<< "0x";
out->width(6);
out->fill('0');
*out << i << ":";
while (i<aLength && ccount<4) {
*out<< " ";
out->width(8);
out->fill('0');
*out << *p++;
i+=4;
ccount++;
for (j=0; j<4; j++) {
char c=*cp++;
if (c<32) {
c = '.';
}
*linep++ = c;
}
}
*linep = '\0';
*out << line+(ccount*5) << endl;
}
}
/**
Function to extract specified file from a given image.
@internalComponent
@released
@param aOffset - starting offset of the file in the image.
@param aSize - size of the file in the image.
@param aFileName - name of the file.
@param aPath - full path of the file inside image.
@param aFilePath - path where file has to be extracted.
*/
void ImageReader::ExtractFile(TUint aOffset,TInt aSize,const char* aFileName,const char* aPath,const char* aFilePath,const char* aData) {
// concatenate path where specified file needs to be extracted with
// path where file is located in the image.
string fullPath( aFilePath );
if(*aPath != SLASH_CHAR1 && *aPath != SLASH_CHAR2){
char ch = aFilePath[fullPath.length() - 1];
if(ch != SLASH_CHAR1 && ch != SLASH_CHAR2)
fullPath += SLASH_CHAR1 ;
}
int startImagePath = (int)fullPath.length();
fullPath += aPath ;
// create specified directory where file needs to be extracted.
// to lower
char* data = const_cast<char*>(fullPath.data() + startImagePath);
for(; *data != 0 ; data++){
if(*data >= 'A' && *data <= 'Z'){
*data |= 0x20 ;
}
}
CreateSpecifiedDir(fullPath);
data -- ;
if(*data != SLASH_CHAR1)
fullPath += SLASH_CHAR1 ;
// concatenate path information with the filename
fullPath += aFileName ;
// create an output stream to extract the specified file.
ofstream outfile (fullPath.c_str(), ios_base::out | ios_base::binary);
// create an input stream by opening the specified image file.
ifstream infile(ImageReader::iImgFileName.c_str(),ios_base::in|ios_base::binary);
//declare a buffer to store the data.
char* buffer = new char[aSize];
if(aData != NULL){
memcpy(buffer, aData + aOffset, aSize);
}
else if(infile.is_open()) {
// place the get pointer for the current input stream to offset bytes away from origin.
infile.seekg(aOffset,ios_base::beg);
//read number of bytes specified by the variable size
//from the stream and place it on to buffer.
if (aSize)
infile.read(buffer,aSize);
//close the input stream after reading.
infile.close();
}
else {
throw ImageReaderException(ImageReader::iImgFileName.c_str(), "Failed to open the image file");
}
if(outfile.is_open()) {
//writes number of bytes specified by the variable size
//from buffer to the current output stream.
if (aSize)
outfile.write(buffer,aSize);
//close the output stream after writing.
outfile.close();
}
else {
throw ImageReaderException(aFileName, "Failed to extract the file");
}
//delete the buffer.
delete[] buffer;
}
/**
Function to create a given directory.
@internalComponent
@released
@param aSrcPath - path of the directory that needs to be created.
*/
void ImageReader::CreateSpecifiedDir(const string& aSrcPath) {
char* currWorkingDir = new char[PATH_MAX];
int len = aSrcPath.length() ;
const char* origPath = aSrcPath.c_str();
char* path = new char[len + 2];
memcpy(path,origPath,len);
if(path[len - 1] != SLASH_CHAR1 && path[len - 1] != SLASH_CHAR2){
path[len] = SLASH_CHAR1 ;
len ++ ;
}
path[len] = 0;
char* start = path;
char* end = path + len ;
char errMsg[400] ;
*errMsg = 0;
char* dirEnd ;
// get the current working directory and store in buffer.
if( getcwd(currWorkingDir,PATH_MAX) == NULL ) {
// throw an exception if unable to get current working directory information.
snprintf(errMsg,400,"Failed to get the current working directory") ;
goto L_EXIT;
}
#ifdef WIN32
//check dir
if(isalpha(start[0]) && start[1] == ':'){
char ch = start[3] ;
start[3] = 0;
if(chdir(start)) {
snprintf(errMsg, 400 ,"Failed to change to the directory \"%s\".",path);
goto L_EXIT;
}
start[3] = ch ;
start += 3 ;
}
else if(*start == SLASH_CHAR1 || *start == SLASH_CHAR2){
if(chdir("\\")){
snprintf(errMsg, 400 ,"Failed to change to the directory \"\\\".");
goto L_EXIT;
}
start ++ ;
}
#else
if(*start == SLASH_CHAR1 || *start == SLASH_CHAR2){
if(chdir("/")) {
snprintf(errMsg, 400 ,"Failed to change to the directory \"/\".");
goto L_EXIT;
}
start ++ ;
}
#endif
dirEnd = start ;
while( start < end ) {
while(*dirEnd != SLASH_CHAR1 && *dirEnd != SLASH_CHAR2)
dirEnd ++ ;
*dirEnd = 0 ;
if(!exists(start)) {
MKDIR(start);
}
if(chdir(start)){
snprintf(errMsg, 400 ,"Failed to change to the directory \"%s\".",path);
goto L_EXIT;
}
*dirEnd = SLASH_CHAR1;
start = dirEnd + 1;
dirEnd = start ;
}
L_EXIT:
chdir(currWorkingDir);
delete[] currWorkingDir;
delete [] path;
if(*errMsg)
throw ImageReaderException(ImageReader::iImgFileName.c_str(), errMsg);
}
/**
Function to insert a given string with a delimiter.
@internalComponent
@released
@param aSrcStr - string to be modified.
@param aDelimiter - string to be checked.
@param aAppStr - string to be inserted with the delimiter.
*/
void ImageReader::FindAndInsertString(string& aSrcStr,string& aDelimiter,string& aAppStr) {
string::size_type loc = 0;
string::size_type pos =0;
while(( pos = aSrcStr.find( aDelimiter, loc ) ) != ( string::npos ) ) {
if( pos != string::npos ) {
aSrcStr.insert(pos,aAppStr);
loc = pos + aAppStr.length() + 1;
}
}
}
/**
Function to replace a delimiter with a given string.
@internalComponent
@released
@param aSrcStr - string to be modified.
@param aDelimiter - string to be checked.
@param aReplStr - string to be replaced with the delimiter.
*/
void ImageReader::FindAndReplaceString( string& aSrcStr, string& aDelimiter, string& aReplStr ) {
string::size_type loc = 0;
string::size_type pos =0;
while(( pos = aSrcStr.find( aDelimiter,loc) ) != ( string::npos ) ) {
if( pos != string::npos ) {
aSrcStr.replace( pos, aReplStr.length(),aReplStr );
loc = pos + aReplStr.length() + 1;
}
}
}
/**
Function to extract individual or a subset of file.
@internalComponent
@released
@param aData - ROM/ROFS image buffer pointer.
*/
void ImageReader::ExtractFileSet(const char* aData) {
FILEINFOMAP fileInfoMap;
TUint extfileCount = 0, noWcardFlag = 0 ;
//Get the filelist map
GetFileInfo(fileInfoMap);
//Check for wildcards
const char* patternStr = iPattern.c_str();
TInt dp = iPattern.length() - 1;
while(dp >= 0){
if(patternStr[dp] == SLASH_CHAR1 || patternStr[dp] == SLASH_CHAR2)
break ;
dp -- ;
}
size_t pos = iPattern.find_first_of("*?",dp + 1);
if(pos == string::npos)
noWcardFlag = 1;
//Process the map
if(fileInfoMap.size() > 0) {
FILEINFOMAP::iterator begin = fileInfoMap.begin();
FILEINFOMAP::iterator end = fileInfoMap.end();
// Replace all backslashes with forward slashes
string pat(iPattern);
for(size_t n = 0 ; n < iPattern.length(); n++){
if(patternStr[n] == SLASH_CHAR2)
pat[n] = SLASH_CHAR1 ;
}
// Insert root directory at the beginning if it is not there
pos = pat.find_first_not_of(" ", 0);
if(pos != string::npos) {
if(pat.at(pos) != SLASH_CHAR1)
pat.insert(pos, 1,SLASH_CHAR1);
}
// Assign CWD for destination path if it is empty
if(ImageReader::iZdrivePath.empty())
ImageReader::iZdrivePath.assign(".");
while(begin != end) {
string fileName((*begin).first);
PFILEINFO pInfo = (*begin).second;
// First match
int status = FileNameMatch(pat, fileName, (iDisplayOptions & RECURSIVE_FLAG));
// If no match
if((!status) && noWcardFlag) {
string newPattern(pat);
// Add * at the end
if(newPattern.at(pat.length()-1) != SLASH_CHAR1) {
newPattern += SLASH_CHAR1;
}
newPattern += "*";
status = FileNameMatch(newPattern, fileName, (iDisplayOptions & RECURSIVE_FLAG));
// If it matches update the pattern and reset wildcard flag
if(status) {
pat = newPattern;
noWcardFlag = 0;
}
}
if(status) {
// Extract the file
// Separarate the path and file name
int slash_pos = fileName.rfind(SLASH_CHAR1);
string fullPath = fileName.substr(0,slash_pos );
string file = fileName.substr(slash_pos + 1, fileName.length());
//FindAndReplaceString(fullPath, dirSep, backSlash);
char* fpStr = const_cast<char*>(fullPath.c_str());
for(size_t m = 0 ; m < fullPath.length() ; m++){
if(fpStr[m] == SLASH_CHAR2)
fpStr[m] = SLASH_CHAR1 ;
}
// Extract only those files exists in the image
if(pInfo->iSize && pInfo->iOffset) {
ExtractFile(pInfo->iOffset, pInfo->iSize, file.c_str(), fullPath.c_str() ,
ImageReader::iZdrivePath.c_str(), aData);
extfileCount++;
}
}
if(pInfo)
delete pInfo;
++begin;
}
fileInfoMap.clear();
}
// Throw error if the extracted file count is zero
if(!extfileCount) {
throw ImageReaderException(ImageReader::iImgFileName.c_str(), "No matching files found for the given pattern");
}
}
/**
To match the given file name aganist the given pattern with wildcards
@internalComponent
@released
@param aPattern - input filename pattern.
@param aFileName - input file name.
@param aRecursiveFlag - recursive search flag.
*/
int ImageReader::FileNameMatch(const string& aPattern, const string& aFileName, int aRecursiveFlag) {
const char *InputString = aFileName.c_str();
const char *Pattern = aPattern.c_str();
const char *CurrPattern = 0, *CurrString = 0;
// If the input is empty then return false
if((aPattern.empty()) || (!InputString))
return 0;
// First candidate match
// Step 1: Look for the exact matches between the input pattern and the given file-name till
// the first occurrence of wildcard character (*). This should also skip a character
// from matching for the occurrence of wildcard character(?) in the pattern.
while ((*InputString) && (*Pattern != '*')) {
if ((toupper(*Pattern) != toupper(*InputString)) && (*Pattern != '?')) {
return 0;
}
Pattern++;
InputString++;
}
// Wildcard match
// Step 2: Now the input string (file-name) should be checked against the wildcard characters (* and ?).
// Skip the input string if the pattern points to wildcard character(*). Do the exact match for
// other characters in the patterns except the wildcard character(?). The path-separator should be
// considered as non-match for non-recursive option.
while (*InputString) {
if ((*Pattern == '*')) {
if (!*++Pattern) {
// If recursive flag is set then this case matches for any character of the input string
// from the current position
if(aRecursiveFlag)
return 1;
}
// Update the current pattern and the current inputstring
CurrPattern = Pattern;
CurrString = InputString+1;
}
else if ((toupper(*Pattern) == toupper(*InputString)) || (*Pattern == '?')) {
// Exact match for the path separator
// So recursively call the function to look for the exact path level match
if(*Pattern == SLASH_CHAR1)
return FileNameMatch(Pattern, InputString, aRecursiveFlag);
// Exact match so increment both
Pattern++;
InputString++;
}
else if ((*InputString == SLASH_CHAR1) && (!aRecursiveFlag)) {
// Inputstring points to path separator and it is not expected here for non-recursive case
return 0;
}
else {
// Default case where it matches for the wildcard character *
Pattern = CurrPattern;
InputString = CurrString++;
}
}
// Leave any more stars in the pattern
while (*Pattern == '*')
Pattern++;
// Return the status
return !*Pattern;
}
| [
"none@none",
"[email protected]"
] | [
[
[
1,
98
],
[
100,
132
],
[
135,
144
],
[
147,
478
]
],
[
[
99,
99
],
[
133,
134
],
[
145,
146
]
]
] |
360bf26a55c88a9e1f8b59906bf847893f61f072 | 15732b8e4190ae526dcf99e9ffcee5171ed9bd7e | /SRC/Queue/priqueue.cc | 0e4e6ab1f451c7c5ebbc5d606d7cba4340c13392 | [] | 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 | 11,064 | cc | // GENERAL PUBLIC LICENSE AGREEMENT
//
// 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 Program is licensed, not sold to you by GEORGIA TECH RESEARCH
// CORPORATION ("GTRC"), owner of all code and accompanying documentation
// (hereinafter "Program"), for use only under the terms of this License,
// and GTRC reserves any rights not expressly granted to you.
//
// 1. This License allows you to:
//
// (a) 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 Article 5
// and 6 of this License. All notices that refer to this License and to
// the absence of any warranty must be kept intact at all times. A copy
// of this License must accompany any and all copies of the Program
// distributed to third parties.
//
// A fee may be charged to cover the cost associated with the physical
// act of transferring a copy to a third party. At no time shall the
// program be sold for commercial gain either alone or incorporated with
// other program(s) without entering into a separate agreement with GTRC.
//
//
// (b) 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,
// provided the following conditions are met:
//
// i) any and all modified files must be affixed with prominent
// notices that you have changed the files and the date that the changes
// occurred.
//
// ii) any work that you distribute, publish, or make available, that
// in whole or in part contains portions of the Program or derivative
// work thereof, must be licensed at no charge to all third parties under
// the terms of this License.
//
// iii) if the modified program normally reads commands interactively
// when run, you must cause it, when started running for such interactive
// use in the most ordinary way, to display and/or print an announcement
// with all appropriate copyright notices and disclaimer of warranty as
// set forth in Article 5 and 6 of this License to be clearly displayed.
// In addition, you must provide reasonable access to this License to the
// user.
//
// Any portion of a Modification that can be reasonably considered
// independent of the Program and separate work in and of itself is not
// subject to the terms and conditions set forth in this License as long
// as it is not distributed with the Program or any portion thereof.
//
//
// 2. This License further allows you to copy and distribute the Program
// or a work based on it, as set forth in Article 1 Section b in
// object code or executable form under the terms of Article 1 above
// provided that you also either:
//
// i) accompany it with complete corresponding machine-readable source
// code, which must be distributed under the terms of Article 1, on a
// medium customarily used for software interchange; or,
//
// ii) accompany it with a written offer, valid for no less than three
// (3) years from the time of distribution, to give any third party, for
// no consideration greater than the cost of physical transfer, a
// complete machine-readable copy of the corresponding source code, to be
// distributed under the terms of Article 1 on a medium customarily used
// for software interchange; or,
//
//
// 3. Export Law Assurance.
//
// You agree that the Software will not be shipped, transferred or
// exported, directly into any country prohibited by the United States
// Export Administration Act and the regulations thereunder nor will be
// used for any purpose prohibited by the Act.
//
// 4. 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.
//
//
// 5. Disclaimer of Warranties and Limitation on Liability.
//
// YOU ACCEPT THE PROGRAM ON AN "AS IS" BASIS. GTRC MAKES NO WARRANTY
// THAT ALL ERRORS CAN BE OR HAVE BEEN ELIMINATED FROM PROGRAM. GTRC
// SHALL NOT BE RESPONSIBLE FOR LOSSES OF ANY KIND RESULTING FROM THE USE
// OF PROGRAM AND ITS ACCOMPANYING DOCUMENT(S), AND CAN IN NO WAY PROVIDE
// COMPENSATION FOR ANY LOSSES SUSTAINED, INCLUDING BUT NOT LIMITED TO
// ANY OBLIGATION, LIABILITY, RIGHT, CLAIM OR REMEDY FOR TORT, OR FOR ANY
// ACTUAL OR ALLEGED INFRINGEMENT OF PATENTS, COPYRIGHTS, TRADE SECRETS,
// OR SIMILAR RIGHTS OF THIRD PARTIES, NOR ANY BUSINESS EXPENSE, MACHINE
// DOWNTIME OR DAMAGES CAUSED TO YOU BY ANY DEFICIENCY, DEFECT OR ERROR
// IN PROGRAM OR MALFUNCTION THEREOF, NOR ANY INCIDENTAL OR CONSEQUENTIAL
// DAMAGES, HOWEVER CAUSED. GTRC DISCLAIMS ALL WARRANTIES, BOTH EXPRESS
// AND IMPLIED RESPECTING THE USE AND OPERATION OF PROGRAM AND ITS
// ACCOMPANYING DOCUMENTATION, INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR PARTICULAR PURPOSE AND ANY IMPLIED
// WARRANTY ARISING FROM COURSE OF PERFORMANCE, COURSE OF DEALING OR
// USAGE OF TRADE. GTRC MAKES NO WARRANTY THAT PROGRAM IS ADEQUATELY OR
// COMPLETELY DESCRIBED IN, OR BEHAVES IN ACCORDANCE WITH ANY
// ACCOMPANYING DOCUMENTATION. THE USER OF PROGRAM IS EXPECTED TO MAKE
// THE FINAL EVALUATION OF PROGRAM'S USEFULNESS IN USER'S OWN
// ENVIRONMENT.
//
// GTRC represents that, to the best of its knowledge, the software
// furnished hereunder does not infringe any copyright or patent.
//
// GTRC shall have no obligation for support or maintenance of Program.
//
// 6. Copyright Notice.
//
// THE SOFTWARE AND ACCOMPANYING DOCUMENTATION ARE COPYRIGHTED WITH ALL
// RIGHTS RESERVED BY GTRC. UNDER UNITED STATES COPYRIGHT LAWS, THE
// SOFTWARE AND ITS ACCOMPANYING DOCUMENTATION MAY NOT BE COPIED EXCEPT
// AS GRANTED HEREIN.
//
// You acknowledge that GTRC is the sole owner of Program, including all
// copyrights subsisting therein. Any and all copies or partial copies
// of Program made by you shall bear the copyright notice set forth below
// and affixed to the original version or such other notice as GTRC shall
// designate. Such notice shall also be affixed to all improvements or
// enhancements of Program made by you or portions thereof in such a
// manner and location as to give reasonable notice of GTRC's copyright
// as set forth in Article 1.
//
// Said copyright notice shall read as follows:
//
// Copyright 2004
// Dr. George F. Riley
// Georgia Tech Research Corporation
// Atlanta, Georgia 30332-0415
// All Rights Reserved
//
// Georgia Tech Network Simulator - Priority Queue class
// Young-Jun Lee. Georgia Tech, Fall 2004
// Defines a strict priority queue.
#include <iostream>
#include <typeinfo>
#include "priqueue.h"
#include "droptail.h"
#include "G_debug.h"
using namespace std;
PriQueue::PriQueue()
{
for (Count_t i = 0; i < NO_PRIQUEUE; i++)
que.push_back(new DropTail());
}
PriQueue::PriQueue(Count_t no_queues, const Queue& q)
{
for (Count_t i = 0; i < no_queues; i++)
que.push_back(q.Copy());
}
PriQueue::PriQueue(const PriQueue& r)
{
for (QueVec_t::size_type i = 0; i < r.que.size(); ++i)
que.push_back(r.que[i]->Copy());
}
PriQueue::~PriQueue()
{
for (QueVec_t::size_type i = 0; i < que.size(); ++i)
delete que[i];
}
bool PriQueue::Enque(Packet* p)
{
Priority_t pri = p->Priority();
if (que.empty() || pri >= que.size()) return false;
return que[pri]->Enque(p);
}
Packet* PriQueue::Deque()
{
for (QueVec_t::reverse_iterator q = que.rbegin(); q != que.rend(); ++q) {
Packet* p = (*q)->Deque();
if (p) return p;
}
return nil;
}
Packet* PriQueue::PeekDeque()
{
for (QueVec_t::reverse_iterator q = que.rbegin(); q != que.rend(); ++q) {
Packet* p = (*q)->PeekDeque();
if (p) return p;
}
return nil;
}
Count_t PriQueue::DequeAllDstMac(MACAddr m)
{
Count_t count = 0;
for (QueVec_t::iterator q = que.begin(); q != que.end(); ++q)
{
count += (*q)->DequeAllDstMac(m);
}
return count;
}
Count_t PriQueue::DequeAllDstIP(IPAddr_t ip)
{
Count_t count = 0;
for (QueVec_t::iterator q = que.begin(); q != que.end(); ++q)
{
count += (*q)->DequeAllDstIP(ip);
}
return count;
}
Packet* PriQueue::DequeOneDstMac(MACAddr m)
{
for (QueVec_t::iterator q = que.begin(); q != que.end(); ++q)
{
Packet* p = (*q)->DequeOneDstMac(m);
if (p) return p;
}
return nil;
}
Packet* PriQueue::DequeOneDstIP(IPAddr_t ip)
{
for (QueVec_t::iterator q = que.begin(); q != que.end(); ++q)
{
Packet* p = (*q)->DequeOneDstIP(ip);
if (p) return p;
}
return nil;
}
Count_t PriQueue::Length()
{
Count_t len=0;
for (QueVec_t::iterator q = que.begin(); q != que.end(); ++q)
len += (*q)->Length();
return len;
}
Count_t PriQueue::LengthPkts()
{
Count_t lenPkts=0;
for (QueVec_t::iterator q = que.begin(); q != que.end(); ++q)
lenPkts += (*q)->LengthPkts();
return lenPkts;
}
Queue* PriQueue::Copy() const
{
return new PriQueue(*this);
}
void PriQueue::SetInterface(Interface* i)
{
#ifndef WIN32
interface = i;
#else
interface_ = i;
#endif
for (QueVec_t::iterator q = que.begin(); q != que.end(); ++q)
(*q)->SetInterface(i);
}
void PriQueue::SetLimit(Count_t l)
{
for (QueVec_t::iterator q = que.begin(); q != que.end(); ++q)
(*q)->SetLimit(l);
}
void PriQueue::SetLimitPkts(Count_t l)
{
for (QueVec_t::iterator q = que.begin(); q != que.end(); ++q)
{
(*q)->SetLimitPkts(l);
DEBUG0((cout << "PriQueue::SLP " << l << endl));
}
}
bool PriQueue::Check(Size_t s, Packet* p)
{
Priority_t pri = 0;
if (p) pri = p->Priority();
return que[pri]->Check(s);
}
Packet* PriQueue::GetPacket(Count_t k)
{
for (QueVec_t::reverse_iterator q = que.rbegin(); q != que.rend(); ++q)
{
Packet* p = (*q)->GetPacket(k);
if (p) return p;
k -= (*q)->LengthPkts();
}
return nil;
}
void PriQueue::GetPacketColors(ColorVec_t& cv)
{
#ifdef HAVE_QT
for (QueVec_t::reverse_iterator q = que.rbegin(); q != que.rend(); ++q)
{
(*q)->GetPacketColors(cv);
}
#endif
}
Queue* PriQueue::GetQueue(Count_t pri)
{
if (pri < que.size()) return que[pri];
return nil; // priority is out of range
}
bool PriQueue::Enque(Packet* p, Count_t pri)
{
return que[pri]->Enque(p);
}
Packet* PriQueue::Deque(Count_t pri)
{
return que[pri]->Deque();
}
Packet* PriQueue::PeekDeque(Count_t pri)
{
return que[pri]->PeekDeque();
}
| [
"pengelmer@f37e807c-cba8-11de-937e-2741d7931076"
] | [
[
[
1,
343
]
]
] |
caee7b01bde3cc57c656c821ced0fc5af1421f4b | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/v0-1/engine/script/include/ScriptSubsystem.h | 8ebc302f04758ce26e1747f06623c09d149d00d5 | [
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,209 | h | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#ifndef __ScriptSubsystem_H__
#define __ScriptSubsystem_H__
#include "ScriptPrerequisites.h"
#include "OgreSingleton.h"
namespace rl {
class _RlScriptExport ScriptSubsystem : public Ogre::Singleton<ScriptSubsystem>
{
public:
ScriptSubsystem();
virtual ~ScriptSubsystem();
static ScriptSubsystem& getSingleton();
static ScriptSubsystem* getSingletonPtr();
void log(const CeGuiString& message);
private:
void initializeScriptSubsystem();
};
}
#endif
| [
"blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
39
]
]
] |
4399ef677738ee43a23ffafa4be5c11772389cd5 | 1caba14ec096b36815b587f719dda8c963d60134 | /branches/smxgroup/smx/libsmx/qstr-new.h | 42083066847ca72d157022e8f4d987a2808a188e | [] | no_license | BackupTheBerlios/smx-svn | 0502dff1e494cffeb1c4a79ae8eaa5db647e5056 | 7955bd611e88b76851987338b12e47a97a327eaf | refs/heads/master | 2021-01-10T19:54:39.450497 | 2009-03-01T12:24:56 | 2009-03-01T12:24:56 | 40,749,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,117 | h | #ifndef _QSTR_H
#define _QSTR_H
#ifndef _STR_H
#include "str.h"
#include "map.h"
#include "lst.h"
#endif
#include "pstime.h"
inline CStr Dbl2Str(double num) {
CStr tmp(50);
_gcvt(num, 48, tmp);
tmp.Shrink();
return tmp.RTrim('.');
}
class qStr {
public:
virtual ~qStr() {};
// public instances
virtual qStr *New(int p1, int p2)
{return 0;}
virtual Delete()
{if (this) delete this;}
// reading
virtual char GetC()
{return EOF;}
virtual CStr GetS()
{return NULL;}
// writing
virtual void PutS(const char *s) // override for efficiency (if any)
{if (s) PutS(s, strlen(s));}
virtual void PutS(const CStr &s) // highly reccomended
{if (s) PutS(s, s.Length());}
virtual void PutC(char c) // highly reccomended
{PutS(&c, 1);}
virtual void PutS(const char *s, int len) // required
{}
virtual time_t GetLastModified()
{return -1;}
virtual void Clear()
{}
// write helpers
virtual void PutS(qStr &s)
{CStr t; while ((t = s.GetS()).Length() > 0) PutS(t);}
virtual void PutN(int i)
{char tmp[33]; _itoa(i, tmp, 10); PutS(tmp); }
virtual void PutN(double d)
{PutS(Dbl2Str(d)); }
};
class qStrApp : public qStr {
CStr *myBuf;
char *myP;
public:
qStrApp(CStr &buf)
{myBuf = &buf; myP = ((char *) *myBuf) + myBuf->Length();}
qStrApp()
{myP = *myBuf;};
char GetC()
{if (myP < ((char *) *myBuf) + myBuf->Length()) return *myP++; else return -1;}
CStr GetS()
{CStr tmp = myP; *myBuf = 0; return tmp;}
void PutS(const char *s)
{*myBuf << s;}
void PutS(const char *s, int len)
{myBuf->Append(s, len);}
void PutS(const CStr &s)
{if (s) PutS(s, s.Length());}
void PutC(char c)
{*myBuf << c;}
};
class qStrBuf : public qStr {
char * myX;
char * myP;
char * myE;
char * myBuf;
public:
qStrBuf(const CStr &buf) {
memcpy(myBuf = (char *) malloc(myX = buf.Count()), buf.Data(), buf.Count());
}
qStrBuf() {
myP = 0;
myE = 0;
myX = 0;
myBuf = 0;
}
virtual qStr *New()
{return new qStrBuf();}
char GetC()
{if (myP < myE) return *myP++; else return -1;}
CStr GetS()
{CStr tmp = (myP < myE) ? CStr(myP, myE-myP) : 0; myBuf.Clear(); return tmp;}
void PutS(const char *s)
{PutS(s, strlen(s));}
void PutS(const char *s, int len)
{myBuf.Append(s, len);}
void PutS(const CStr &s)
{if (s) PutS(s, s.Length());}
void PutC(char c)
{myBuf << c;}
void Clear()
{myBuf.Grow(0);}
};
class qStrFileI : public qStr {
FILE *myFile;
bool myFree;
public:
qStrFileI() {
myFile = NULL;
}
~qStrFileI() {
if (myFree)
fclose(myFile);
}
qStrFileI(FILE *fp, bool free = false) {
SetFile(fp, free);
}
void SetFile(FILE *fp, bool free = false) {
assert(fp!=NULL);
myFile = fp;
myFree = free;
}
char GetC() {
assert(myFile != NULL);
return fgetc(myFile);
}
CStr GetS() {
assert(myFile != NULL);
CStr tmp(1024);
tmp.Grow(fread((char *) tmp, 1, 1024, myFile));
return tmp;
}
time_t GetLastModified() {
assert(myFile != NULL);
return qTime::GetFileModified(myFile);
}
void PutS(const char *s) {}
void PutC(char c) {}
};
class qStrFileO : public qStr {
FILE *myFile;
bool myFree;
public:
qStrFileO(FILE *fp, bool free = false)
{myFile = fp; myFree = free;}
~qStrFileO()
{if (myFree && myFile) fclose(myFile);}
void PutS(const char *s)
{if (s) fputs(s, myFile);}
void PutS(const char *s, int n)
{if (s) fwrite(s, 1, n, myFile);}
void PutS(const CStr &s)
{if (s) PutS(s, s.Length());}
void PutC(char c)
{fputc(c, myFile);}
};
class qStrNLTrim : public qStr {
qStr *myStr;
bool myNL;
public:
qStrNLTrim(qStr *str)
{myStr = str; myNL = true;}
void PutS(const char *s);
void PutS(const char *s, int n);
void PutC(char c)
{PutS(&c, 1);}
};
inline qStrBuf::qStrBuf(const CStr &buf)
{
Copy(buf);
myP = 0;
}
class qStrNull : public qStr {
};
#endif //#ifndef _QSTR_H | [
"simul@407f561b-fe63-0410-8234-8332a1beff53"
] | [
[
[
1,
231
]
]
] |
6b9b462f9214eab6dac4cebd5270c0976935e1fa | 485a4c53387cbce41a835abfce40f1f462cd240a | /main.cpp | 354b763f8617c898383229b721a63a6285822b68 | [] | no_license | khandady/hw5 | a5ad43a8529366b8246234f979323c538d580a0d | d6973c78ba130419714f3ccd6fcd2a740d980ea9 | refs/heads/master | 2016-09-05T20:52:53.261518 | 2011-03-14T02:23:52 | 2011-03-14T02:23:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,130 | cpp | #include <iostream>
#include <string>
#include "LinkedList.h"
#include "VectorList.h"
using namespace std;
// display program instructions to user
void instructions()
{
cout << "Enter one of the following:\n"
<< " 1 to insert at beginning of list\n"
<< " 2 to insert at end of list\n"
<< " 3 to delete from beginning of list\n"
<< " 4 to delete from end of list\n"
<< " 5 to end list processing\n"
<< " 6 to sum list elements\n"
<< " 7 to access a list element\n"
<< " 8 to reverse list order\n";
}
// function to test map member function
template< typename T >
T timesfive(const T &anum)
{
return anum * 5;
}
// function to test filter
template< typename T >
bool even(const T &anum)
{
if ( anum % 2 == 0)
{return true;}
else {return false;}
}
// function to test a LinkedList
template< typename T >
void testLinkedList( LinkedList< T > &listObject, const string &typeName )
{
cout << "Testing a LinkedList of " << typeName << " values\n";
instructions(); // display instructions
int choice; // store user choice
T value; // store input value
do // perform user-selected actions
{
cout << "? ";
cin >> choice;
switch ( choice )
{
case 1: // insert at beginning
cout << "Enter " << typeName << ": ";
cin >> value;
listObject.insertAtFront( value );
listObject.print();
break;
case 2: // insert at end
cout << "Enter " << typeName << ": ";
cin >> value;
listObject.insertAtBack( value );
listObject.print();
break;
case 3: // remove from beginning
if ( listObject.removeFromFront( value ) )
cout << value << " removed from list\n";
listObject.print();
break;
case 4: // remove from end
if ( listObject.removeFromBack( value ) )
cout << value << " removed from list\n";
listObject.print();
break;
case 6:
cout << listObject.sum() << endl;
break;
case 7:
{cout << "Enter element subscript : ";
cin >> value;
T something = listObject[value];
cout << "\nEntry is : " << something << endl;
break;}
case 8:
listObject.reverse();
listObject.print();
break;
}
} while ( choice != 5 );
cout << "End list test\n\n";
}
// function to test a VectorList
template< typename T >
void testVectorList( VectorList< T > &listObject, const string &typeName )
{
cout << "Testing a VectorList of " << typeName << " values\n";
instructions(); // display instructions
int choice; // store user choice
T value; // store input value
do // perform user-selected actions
{
cout << "? ";
cin >> choice;
switch ( choice )
{
case 1: // insert at beginning
cout << "Enter " << typeName << ": ";
cin >> value;
listObject.insertAtFront( value );
listObject.print();
break;
case 2: // insert at end
cout << "Enter " << typeName << ": ";
cin >> value;
listObject.insertAtBack( value );
listObject.print();
break;
case 3: // remove from beginning
if ( listObject.removeFromFront( value ) )
cout << value << " removed from list\n";
listObject.print();
break;
case 4: // remove from end
if ( listObject.removeFromBack( value ) )
cout << value << " removed from list\n";
listObject.print();
break;
}
} while ( choice < 5 );
cout << "End list test\n\n";
}
int main()
{
// test LinkedList of int values
LinkedList< int > integerLinkedList;
testLinkedList( integerLinkedList, "integer" );
// test VectorList of int values
VectorList< int > integerVectorList;
testVectorList( integerVectorList, "integer" );
// test LinkedList of double values
LinkedList< double > doubleLinkedList;
testLinkedList( doubleLinkedList, "double" );
// test VectorList of double values
VectorList< double > doubleVectorList;
testVectorList( doubleVectorList, "double" );
cout << "testing shared : " << integerLinkedList.shared(integerLinkedList) << endl;
cout << "testing sort\n";
integerLinkedList.sort();
integerLinkedList.print();
cout << "testing map :\n";
integerLinkedList.map(timesfive);
cout << "testing filter\n";
integerLinkedList.filter(even);
integerLinkedList.print();
cout << "testing removeDup()\n";
integerLinkedList.removeDup();
integerLinkedList.print();
return 0;
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
17
],
[
19,
167
],
[
171,
173
]
],
[
[
18,
18
],
[
168,
170
]
]
] |
a834ec615d19f098c47016c9993dc0202e9d6e19 | cf579692f2e289563160b6a218fa5f1b6335d813 | /XBpatch/Patchers/CX24980Patcher.h | a42d4d8b11d456899ec43e7ea954d991bdac9396 | [] | no_license | opcow/XBtool | a7451971de3296e1ce5632b0c9d95430f6d3b223 | 718a7fbf87e08c12c0c829dd2e2c0d6cee967cbe | refs/heads/master | 2021-01-16T21:02:17.759102 | 2011-03-09T23:36:54 | 2011-03-09T23:36:54 | 1,461,420 | 8 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 747 | h | #include "CX24976Patcher.h"
class CX24981Patcher
: public CX24976Patcher {
public:
virtual XBPATCH_API void GetSupportedOptions(BIOS_Supported_Options &SupOpts);
virtual XBPATCH_API int Read(unsigned char *kernelBuffer, BIOS_Options *BIOSOptions);
virtual XBPATCH_API int Write(unsigned char *kernelBuffer, BIOS_Options *BIOSOptions);
XBPATCH_API CX24981Patcher() {};
void InitPatches();
int WritePreIDPatches(BIOS_Options *BIOSOptions);
int NoFloatReadColors(COLORREF &XLipHighlightsColor, COLORREF &XLipColor, COLORREF &XWallColor, COLORREF &XGlowColor, COLORREF &XboxColor);
int NoFloatWriteColors(COLORREF XLipHighlightsColor, COLORREF XLipColor, COLORREF XWallColor, COLORREF XGlowColor, COLORREF XboxColor);
};
| [
"[email protected]"
] | [
[
[
1,
17
]
]
] |
6fa54d701798438582aa72711e4b6f436595ab3e | 16d8b25d0d1c0f957c92f8b0d967f71abff1896d | /OblivionOnline/cegui/WindowRendererSets/Falagard/include/FalStaticImageProperties.h | 8f0cf5eea70972fa44a7e55e7f8c307df2c356c5 | [] | no_license | wlasser/oonline | 51973b5ffec0b60407b63b010d0e4e1622cf69b6 | fd37ee6985f1de082cbc9f8625d1d9307e8801a6 | refs/heads/master | 2021-05-28T23:39:16.792763 | 2010-05-12T22:35:20 | 2010-05-12T22:35:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,115 | h | /***********************************************************************
filename: FalagardStaticTextProperties.h
created: 17/9/2005
author: Tomas L Olsen (based on code by Paul D Turner)
purpose: Interface for properties for the FalagardStaticText class.
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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 _FalagardStaticImageProperties_h_
#define _FalagardStaticImageProperties_h_
#include "CEGUIProperty.h"
// Start of CEGUI namespace section
namespace CEGUI
{
// Start of FalagardStaticImageProperties namespace section
/*!
\brief
Namespace containing all classes that make up the properties interface for the FalagardStaticText class
*/
namespace FalagardStaticImageProperties
{
/*!
\brief
Property to access the image for the FalagardStaticImage widget.
\par Usage:
- Name: Image
- Format: "set:[text] image:[text]".
\par Where:
- set:[text] is the name of the Imageset containing the image. The Imageset name should not contain spaces. The Imageset specified must already be loaded.
- image:[text] is the name of the Image on the specified Imageset. The Image name should not contain spaces.
*/
class Image : public Property
{
public:
Image() : Property(
"Image",
"Property to get/set the image for the FalagardStaticImage widget. Value should be \"set:[imageset name] image:[image name]\".",
"")
{}
String get(const PropertyReceiver* receiver) const;
void set(PropertyReceiver* receiver, const String& value);
};
} // End of FalagardStaticImageProperties namespace section
} // End of CEGUI namespace section
#endif // end of guard _FalagardStaticImageProperties_h_
| [
"masterfreek64@2644d07b-d655-0410-af38-4bee65694944"
] | [
[
[
1,
77
]
]
] |
5edc80f45066c80cfe3d2417eda1c06c11f5fb10 | ccc3e2995bc64d09b9e88fea8c1c7e2029a60ed8 | /SO/Trabalhos/Trabalho 3/tmp_src/32142/without_test/Lib/SesError.cpp | e30c409d5be466c8c3a170e89cb5fac984abbc55 | [] | no_license | masterzdran/semestre5 | e559e93017f5e40c29e9f28466ae1c5822fe336e | 148d65349073f8ae2f510b5659b94ddf47adc2c7 | refs/heads/master | 2021-01-25T10:05:42.513229 | 2011-02-20T17:46:14 | 2011-02-20T17:46:14 | 35,061,115 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,820 | cpp | /**
* Implementação do módulo de tratamento de erros
*/
#include "../stdafx.h"
#include "../Include/SesError.h"
#include <stdlib.h>
const int MAX_CH_ERROR_TITLE = 64; // Dimensão max. do titulo em caracters
//const int ERROR_TITLE = 64;
const int MAX_CH_ERROR_MESSAGE = 256; // Dimensão max. da mensagem de erro em caracters
//----------------------------------------------------------------------------
// Função privada auxiliar que bloqueia o programa até o utilizador
// primir uma tecla.
// Em ambiente Unix deve premir ENTER
//
void terminar()
{
fputs("\nPrima uma tecla para terminar ", stderr);
_getch();
} // terminar
//----------------------------------------------------------------------------
// Função privada que sabe mostrar um erro
//
void DisplayError(int errorn, const TCHAR * fmtStr, va_list args) {
LPVOID errorBuf;
TCHAR msgBuffer[MAX_CH_ERROR_MESSAGE];
TCHAR title[MAX_CH_ERROR_TITLE] = TEXT("");
TCHAR * progName;
if ( GetConsoleTitle(title, MAX_CH_ERROR_TITLE) ) {
progName = _tcsrchr(title, '\\');
if ( progName != NULL ) {
if ( progName[ _tcslen(progName)-1 ] == '"')
progName[ _tcslen(progName)-1 ] = '\0';
//_stprintf(title, TEXT("Error on %s"), ++progName);
StringCchPrintf(title, MAX_CH_ERROR_TITLE, TEXT("Error on %s"), ++progName);
}
}
DWORD res = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorn,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Linguagem por omissão do sistema
(LPTSTR) &errorBuf,
0,
NULL );
//_vstprintf( msgBuffer, fmtStr, args );
StringCchVPrintf(msgBuffer, MAX_CH_ERROR_MESSAGE, fmtStr, args );
//_stprintf( msgBuffer + _tcsclen(msgBuffer), TEXT(": (%d) %s"), errorn, (res ? errorBuf : "") );
size_t dimMsg = _tcsclen(msgBuffer);
StringCchPrintf(msgBuffer + dimMsg, MAX_CH_ERROR_MESSAGE - dimMsg,
TEXT(": (%d) %s"), errorn, (res ? errorBuf : TEXT("")) );
MessageBox( NULL, (LPCTSTR)msgBuffer, title, MB_OK | MB_ICONERROR | MB_SETFOREGROUND);
// Libertar memória referenciada por lpMsgBuf alocada pela função FormatMessage
LocalFree( errorBuf );
} // DisplayError
//----------------------------------------------------------------------------
// Função privada que sabe mostrar um erro da aplicação
//
void DisplayErrorApp(const TCHAR * fmtStr, va_list args) {
TCHAR msgBuffer[MAX_CH_ERROR_MESSAGE];
TCHAR title[MAX_CH_ERROR_TITLE] = TEXT("");
TCHAR * progName;
if ( GetConsoleTitle(title, MAX_CH_ERROR_TITLE) ) {
progName = _tcsrchr(title, '\\');
if ( progName!=NULL ) {
if ( progName[ _tcsclen(progName)-1 ]=='"' )
progName[ _tcsclen(progName)-1 ] = '\0';
//_stprintf(title, TEXT("Error on %s"), ++progName);
StringCchPrintf(title, MAX_CH_ERROR_TITLE, TEXT("Error on %s"), ++progName);
}
}
//_vstprintf( msgBuffer, fmtStr, args );
StringCchVPrintf(msgBuffer, MAX_CH_ERROR_MESSAGE, fmtStr, args );
MessageBox( NULL, (LPCTSTR)msgBuffer, title, MB_OK | MB_ICONERROR | MB_SETFOREGROUND);
} // DisplayErrorApp
//----------------------------------------------------------------------------
// Erro de sistema
//
void ReportErrorSystem( const TCHAR *fmtStr, ... ) {
va_list args;
int error = GetLastError();
va_start( args, fmtStr );
DisplayError( error, fmtStr, args );
va_end( args );
} // ReportErrorSystem
//----------------------------------------------------------------------------
// Erro de sistema com terminação do programa
//
void FatalErrorSystem( const TCHAR *fmtStr, ... ) {
va_list args;
int error = GetLastError();
va_start( args, fmtStr );
DisplayError( error, fmtStr, args );
va_end( args );
terminar();
exit( 1 );
} // ErrorSystem
//----------------------------------------------------------------------------
// Erro da aplicação
//
void ReportErrorUser( const TCHAR *fmtStr, ... ) {
va_list args;
va_start( args, fmtStr );
DisplayErrorApp(fmtStr, args );
va_end( args );
} // ReportErrorSystem
//----------------------------------------------------------------------------
// Erro da aplicação com terminação do programa
//
void FatalErrorUser( const TCHAR *fmtStr, ... ) {
va_list args;
va_start( args, fmtStr );
DisplayErrorApp(fmtStr, args );
va_end( args );
terminar();
exit( 1 );
} // FatalErrorSystem
| [
"[email protected]@b139f23c-5e1e-54d6-eab5-85b03e268133"
] | [
[
[
1,
167
]
]
] |
15b50fdc005a88da0ed936e658b8a789ced43af9 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/SupportWFLib/symbian/HelpUrlHandler.cpp | 71ad18ceb2f565bdac988199ee3752ed3dcd958e | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,971 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "HelpUrlHandler.h"
#include "WFTextUtil.h"
#include <eikenv.h>
CHelpUrlHandler::CHelpUrlHandler(TInt aNoOfMappings) :
iNoOfMappings(aNoOfMappings)
{
}
void CHelpUrlHandler::ConstructL(const ViewNameMapping* aViewNameMappings,
TInt aLangCodeId)
{
iLangCode = CEikonEnv::Static()->AllocReadResourceL(aLangCodeId);
iLangCode->Des().LowerCase();
iViewNameMappings = new ViewNameMapping* [iNoOfMappings];
for (TInt i = 0; i < iNoOfMappings; i++) {
ViewNameMapping* viewMapping = new ViewNameMapping;
viewMapping->iViewId = aViewNameMappings[i].iViewId;
viewMapping->iViewName = WFTextUtil::strdupL(aViewNameMappings[i].iViewName);
iViewNameMappings[i] = viewMapping;
}
}
void CHelpUrlHandler::ConstructL(const ViewNameMapping* aViewNameMappings,
const TDesC& aLangCode)
{
iLangCode = aLangCode.AllocL();
iLangCode->Des().LowerCase();
iViewNameMappings = new ViewNameMapping* [iNoOfMappings];
for (TInt i = 0; i < iNoOfMappings; i++) {
ViewNameMapping* viewMapping = new ViewNameMapping;
viewMapping->iViewId = aViewNameMappings[i].iViewId;
viewMapping->iViewName = WFTextUtil::strdupL(aViewNameMappings[i].iViewName);
iViewNameMappings[i] = viewMapping;
}
}
CHelpUrlHandler::~CHelpUrlHandler()
{
delete iLangCode;
if (iViewNameMappings) {
for (TInt i = 0; i < iNoOfMappings; i++) {
delete[] iViewNameMappings[i]->iViewName;
delete iViewNameMappings[i];
}
delete[] iViewNameMappings;
}
}
CHelpUrlHandler* CHelpUrlHandler::NewLC(const ViewNameMapping* aViewNameMappings,
TInt aNoOfMappings,
TInt aLangCodeId)
{
CHelpUrlHandler* self =
new (ELeave) CHelpUrlHandler(aNoOfMappings);
CleanupStack::PushL(self);
self->ConstructL(aViewNameMappings, aLangCodeId);
return self;
}
CHelpUrlHandler* CHelpUrlHandler::NewL(const ViewNameMapping* aViewNameMappings,
TInt aNoOfMappings,
TInt aLangCodeId)
{
CHelpUrlHandler* self =
CHelpUrlHandler::NewLC(aViewNameMappings, aNoOfMappings, aLangCodeId);
CleanupStack::Pop(self);
return self;
}
CHelpUrlHandler* CHelpUrlHandler::NewLC(const ViewNameMapping* aViewNameMappings,
TInt aNoOfMappings,
const TDesC& aLangCode)
{
CHelpUrlHandler* self =
new (ELeave) CHelpUrlHandler(aNoOfMappings);
CleanupStack::PushL(self);
self->ConstructL(aViewNameMappings, aLangCode);
return self;
}
CHelpUrlHandler* CHelpUrlHandler::NewL(const ViewNameMapping* aViewNameMappings,
TInt aNoOfMappings,
const TDesC& aLangCode)
{
CHelpUrlHandler* self =
CHelpUrlHandler::NewLC(aViewNameMappings, aNoOfMappings, aLangCode);
CleanupStack::Pop(self);
return self;
}
HBufC* CHelpUrlHandler::FormatLC(TInt aViewId, const TDesC& aAnchorString)
{
_LIT(KFile, "file:///");
_LIT(KHelp, "help");
_LIT(KIndex, "index");
_LIT(KHtml, "html");
_LIT(KSlash, "/");
_LIT(KDot, ".");
_LIT(KHash, "#");
HBufC* pageName = GetHelpPageNameL(aViewId);
HBufC* url = HBufC::NewLC(KFile().Length() + KHelp().Length() +
KSlash().Length() + KIndex().Length() +
KDot().Length() + iLangCode->Length() +
KDot().Length() + KHtml().Length() +
KHash().Length() + pageName->Length() +
aAnchorString.Length());
url->Des().Append(KFile);
url->Des().Append(KHelp);
url->Des().Append(KSlash);
url->Des().Append(KIndex);
url->Des().Append(KDot);
url->Des().Append(*iLangCode);
url->Des().Append(KDot);
url->Des().Append(KHtml);
url->Des().Append(KHash);
url->Des().Append(*pageName);
url->Des().Append(aAnchorString); //nowadays pagename is actually the anchor.
delete pageName;
return url;
}
HBufC* CHelpUrlHandler::FormatLC(TInt aViewId, const HBufC* aAnchorString)
{
HBufC* url;
if (aAnchorString) {
url = FormatLC(aViewId, *aAnchorString);
} else {
url = FormatLC(aViewId, KNullDesC);
}
return url;
}
HBufC* CHelpUrlHandler::FormatL(TInt aViewId, const TDesC& aAnchorString)
{
HBufC* url = FormatLC(aViewId, aAnchorString);
CleanupStack::Pop(url);
return url;
}
HBufC* CHelpUrlHandler::FormatL(TInt aViewId, const HBufC* aAnchorString)
{
HBufC* url;
if (aAnchorString) {
url = FormatLC(aViewId, *aAnchorString);
} else {
url = FormatLC(aViewId, KNullDesC);
}
CleanupStack::Pop(url);
return url;
}
HBufC* CHelpUrlHandler::GetHelpPageNameL(TInt aViewId)
{
for (TInt i = 0; i < iNoOfMappings; i++) {
if (iViewNameMappings[i]->iViewId == aViewId) {
return WFTextUtil::AllocL(iViewNameMappings[i]->iViewName);
}
}
//If the view did not have any help page return the index page.
return WFTextUtil::AllocL(iViewNameMappings[0]->iViewName);
}
| [
"[email protected]"
] | [
[
[
1,
187
]
]
] |
cfa765c3403613c11ae87bb880e4950399a78782 | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_audio_devices/midi_io/juce_MidiInput.h | 57532dbce0a0e1d483453a32dda3f9b75b0ca4e1 | [] | no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,979 | h | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
#ifndef __JUCE_MIDIINPUT_JUCEHEADER__
#define __JUCE_MIDIINPUT_JUCEHEADER__
class MidiInput;
//==============================================================================
/**
Receives incoming messages from a physical MIDI input device.
This class is overridden to handle incoming midi messages. See the MidiInput
class for more details.
@see MidiInput
*/
class JUCE_API MidiInputCallback
{
public:
/** Destructor. */
virtual ~MidiInputCallback() {}
/** Receives an incoming message.
A MidiInput object will call this method when a midi event arrives. It'll be
called on a high-priority system thread, so avoid doing anything time-consuming
in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
for queueing incoming messages for use later.
@param source the MidiInput object that generated the message
@param message the incoming message. The message's timestamp is set to a value
equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
time when the message arrived.
*/
virtual void handleIncomingMidiMessage (MidiInput* source,
const MidiMessage& message) = 0;
/** Notification sent each time a packet of a multi-packet sysex message arrives.
If a long sysex message is broken up into multiple packets, this callback is made
for each packet that arrives until the message is finished, at which point
the normal handleIncomingMidiMessage() callback will be made with the entire
message.
The message passed in will contain the start of a sysex, but won't be finished
with the terminating 0xf7 byte.
*/
virtual void handlePartialSysexMessage (MidiInput* source,
const uint8* messageData,
const int numBytesSoFar,
const double timestamp)
{
// (this bit is just to avoid compiler warnings about unused variables)
(void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
}
};
//==============================================================================
/**
Represents a midi input device.
To create one of these, use the static getDevices() method to find out what inputs are
available, and then use the openDevice() method to try to open one.
@see MidiOutput
*/
class JUCE_API MidiInput
{
public:
//==============================================================================
/** Returns a list of the available midi input devices.
You can open one of the devices by passing its index into the
openDevice() method.
@see getDefaultDeviceIndex, openDevice
*/
static StringArray getDevices();
/** Returns the index of the default midi input device to use.
This refers to the index in the list returned by getDevices().
*/
static int getDefaultDeviceIndex();
/** Tries to open one of the midi input devices.
This will return a MidiInput object if it manages to open it. You can then
call start() and stop() on this device, and delete it when no longer needed.
If the device can't be opened, this will return a null pointer.
@param deviceIndex the index of a device from the list returned by getDevices()
@param callback the object that will receive the midi messages from this device.
@see MidiInputCallback, getDevices
*/
static MidiInput* openDevice (int deviceIndex,
MidiInputCallback* callback);
#if JUCE_LINUX || JUCE_MAC || DOXYGEN
/** This will try to create a new midi input device (Not available on Windows).
This will attempt to create a new midi input device with the specified name,
for other apps to connect to.
Returns 0 if a device can't be created.
@param deviceName the name to use for the new device
@param callback the object that will receive the midi messages from this device.
*/
static MidiInput* createNewDevice (const String& deviceName,
MidiInputCallback* callback);
#endif
//==============================================================================
/** Destructor. */
virtual ~MidiInput();
/** Returns the name of this device. */
const String& getName() const noexcept { return name; }
/** Allows you to set a custom name for the device, in case you don't like the name
it was given when created.
*/
void setName (const String& newName) noexcept { name = newName; }
//==============================================================================
/** Starts the device running.
After calling this, the device will start sending midi messages to the
MidiInputCallback object that was specified when the openDevice() method
was called.
@see stop
*/
virtual void start();
/** Stops the device running.
@see start
*/
virtual void stop();
protected:
//==============================================================================
String name;
void* internal;
explicit MidiInput (const String& name);
private:
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput);
};
#endif // __JUCE_MIDIINPUT_JUCEHEADER__
| [
"ow3nskip"
] | [
[
[
1,
183
]
]
] |
f4e51c9378723c8a5ab9683e58ad962a886fa0c1 | d752d83f8bd72d9b280a8c70e28e56e502ef096f | /FugueDLL/Virtual Machine/Operations/Debugging.h | c5b2e64e3d5b22b6af8a0996ddc27de01b0cb5f8 | [] | 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 | 2,183 | h | //
// The Epoch Language Project
// FUGUE Virtual Machine
//
// Operations for debugging Epoch programs
//
#pragma once
// Dependencies
#include "Virtual Machine/Core Entities/Operation.h"
namespace VM
{
namespace Operations
{
//
// Write an expression which evaluates to a string to the
// debugger. The expression should be pushed onto the stack
// prior to invoking the operation.
//
class DebugWriteStringExpression : public Operation, public SelfAware<DebugWriteStringExpression>
{
// Operation interface
public:
virtual void ExecuteFast(ExecutionContext& context);
virtual RValuePtr ExecuteAndStoreRValue(ExecutionContext& context);
virtual EpochVariableTypeID GetType(const ScopeDescription& scope) const
{ return EpochVariableType_Null; }
virtual size_t GetNumParameters(const VM::ScopeDescription& scope) const
{ return 1; }
};
//
// Perform a blocking read from the debugger UI, and
// return the resulting string.
//
class DebugReadStaticString : public Operation, public SelfAware<DebugReadStaticString>
{
// Operation interface
public:
virtual void ExecuteFast(ExecutionContext& context);
virtual RValuePtr ExecuteAndStoreRValue(ExecutionContext& context);
virtual EpochVariableTypeID GetType(const ScopeDescription& scope) const
{ return EpochVariableType_String; }
virtual size_t GetNumParameters(const VM::ScopeDescription& scope) const
{ return 0; }
};
//
// Deliberately crash the VM for testing for memory leaks etc.
//
class DebugCrashVM : public Operation, public SelfAware<DebugCrashVM>
{
// Operation interface
public:
virtual void ExecuteFast(ExecutionContext& context)
{ throw Exception("VM deliberately crashed"); }
virtual RValuePtr ExecuteAndStoreRValue(ExecutionContext& context)
{ throw Exception("VM deliberately crashed"); }
virtual EpochVariableTypeID GetType(const ScopeDescription& scope) const
{ return EpochVariableType_Null; }
virtual size_t GetNumParameters(const VM::ScopeDescription& scope) const
{ return 0; }
};
}
}
| [
"[email protected]",
"don.apoch@localhost"
] | [
[
[
1,
29
],
[
32,
48
],
[
51,
66
],
[
68,
69
],
[
71,
83
]
],
[
[
30,
31
],
[
49,
50
],
[
67,
67
],
[
70,
70
]
]
] |
28c1624a93ca961a20a9de5ba29a2df1092b5c8e | 3c6723c88064e74961ed26fbe8f70ef2e3856ebf | /dev/macro/TTileCommRun/THTMLDoc.cpp | c816a74c3156ff204774ef7a14e450713610abfb | [] | no_license | lauramoraes/WIS | 534fa416c14a25ba618b7d85323f8bb062fe9be2 | e7dbd4e456c4b93ea51d33d5d631263a60a6f3b9 | refs/heads/master | 2021-01-02T09:32:53.155405 | 2009-09-16T12:53:55 | 2009-09-16T12:53:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,454 | cpp | #define THTMLDoc_cxx
#include "THTMLDoc.h"
#ifdef THTMLDoc_cxx
THTMLDoc::THTMLDoc(TString title, TString pageTitle)
{
// Initialize HTML page elements
fTitle = "<title>";
fTitle += title;
fTitle += "</title>\n";
fPageTitle = "<h2>";
fPageTitle += pageTitle;
fPageTitle += "</h2>\n";
fStyleSheets = "<link href=\"";
fStyleSheets += defaultStyleSheet;
fStyleSheets += "\" type=\"text/css\" rel=\"stylesheet\" />\n";
fScripts = "";
fTopBar = "<!-- Top bar -->\n";
fTopBar += "<div id=\"top-bar\">\n";
fTopBar += " [ <a href=\"http://tileinfo.web.cern.ch/tileinfo/lps/WIS/hp/\">Project Home Page</a> ] .:. \n";
fTopBar += " [ <a href=\"http://www.cern.ch/\">CERN</a> ] .:. \n";
fTopBar += " [ <a href=\"http://atlas.web.cern.ch/\">ATLAS</a> ] .:. \n";
fTopBar += " [ <a href=\"http://atlas.web.cern.ch/Atlas/SUB_DETECTORS/TILE/tilecal.html\">Tile Calorimeter</a> ] .:. \n";
fTopBar += " [ <a href=\"http://www.ufrj.br\">Universidade Federal do Rio de Janeiro</a> ] \n";
fTopBar += "</div>\n";
fTopBar += "<!-- /Top bar -->\n";
fHeader = "<!-- Header -->\n";
fHeader += "<div id=\"header\">\n";
fHeader += " <h1>TileCal Commissioning Offline Shifts</h1>\n";
fHeader += "</div>\n";
fHeader += "<!-- /Header -->\n";
fMainContainer = "<!-- Main Container -->\n";
fMainContainer += "<div id=\"main-container\">\n";
fContents = " <!-- Contents -->\n";
fContents = " <div id=\"contents\">\n";
fFooter = "<!-- Footer -->\n";
fFooter += "<div id=\"footer\">\n";
fFooter += " Please <a href=\"mailto:[email protected],[email protected]\">send us</a> your comments and suggestions.\n";
fFooter += "</div>\n";
fFooter += "<!-- /Footer -->\n";
}
void THTMLDoc::AddTable(Int_t *matrix, const Int_t &nrows, const Int_t &ncols, const TString &rowsTitle, const TString &colsTitle, TString *rowNames, TString *colNames, Bool_t *selectedRows)
{
Int_t i, j;
TString table;
table = "<table class=\"main\">\n<tr><th></th>";
table += "<th colspan=\"";
table += ncols;
table += "\">";
table += colsTitle;
table += "</th></tr>\n";
table += "<tr><th>";
table += rowsTitle;
table += "</th>";
/*
cout << (matrix + (48*ncols) + 0) << endl;
cout << &NSlinkErrors[48][0] << endl;
*/
for (j = 0; j < ncols; j++)
{
table += "<th>";
table += colNames[j];
table += "</th>";
}
table += "</tr>\n";
for (i = 0; i < nrows; i++)
{
if (selectedRows && !selectedRows[i])
continue;
table += "<tr><th>";
table += rowNames[i];
table += "</th>";
for (j = 0; j < ncols; j++)
{
table += "<td>";
table += *(matrix + (i*ncols) + j);
table += "</td>";
}
table += "</tr>\n";
}
table += "</table>\n";
fContents += table;
}
void THTMLDoc::AddTable(TString &table, const vector< vector<Int_t> > &matrix, const Int_t &nrows, const Int_t &ncols, const TString &rowsTitle, const TString &colsTitle, TString *rowNames, TString *colNames, Bool_t *selectedRows)
{
Int_t i, j;
TString table;
table = "<table class=\"main\">\n<tr><th></th>";
table += "<th colspan=\"";
table += ncols;
table += "\">";
table += colsTitle;
table += "</th></tr>\n";
table += "<tr><th>";
table += rowsTitle;
table += "</th>";
/*
cout << (matrix + (48*ncols) + 0) << endl;
cout << &NSlinkErrors[48][0] << endl;
*/
for (j = 0; j < ncols; j++)
{
table += "<th>";
table += colNames[j];
table += "</th>";
}
table += "</tr>\n";
for (i = 0; i < nrows; i++)
{
if (selectedRows && !selectedRows[i])
continue;
table += "<tr><th>";
table += rowNames[i];
table += "</th>";
for (j = 0; j < ncols; j++)
{
table += "<td>";
table += matrix.at(i).at(j);
table += "</td>";
}
table += "</tr>\n";
}
table += "</table>\n";
fContents += table;
}
THTMLDoc::~THTMLDoc()
{
}
THTMLDoc::Output()
{
fContents += " </div>\n";
fContents += " <!-- /Contents -->\n";
fMainContents += fContents;
fMainContents += "</div>\n";
fMainContents += "<!-- /Main -->\n";
cout << "<html>" << endl;
cout << "<head>" << fTitle << "</head>" << endl;
cout << "<body>" << fTopBar << endl << fHeader << endl;
cout << fMainContents << endl << fFooter << endl << "</body>" << endl;
cout << "</html>" << endl;
}
#endif // #ifdef THTMLDoc_cxx
| [
"[email protected]"
] | [
[
[
1,
178
]
]
] |
16a8f6df8f66de28fbd071c7a8645b6a7f12e065 | 282057a05d0cbf9a0fe87457229f966a2ecd3550 | /EIBStdLib/src/TunnelAck.cpp | 952e4fee7dcef4385cad2c98b3657656d0351646 | [] | no_license | radtek/eibsuite | 0d1b1c826f16fc7ccfd74d5e82a6f6bf18892dcd | 4504fcf4fa8c7df529177b3460d469b5770abf7a | refs/heads/master | 2021-05-29T08:34:08.764000 | 2011-12-06T20:42:06 | 2011-12-06T20:42:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,910 | cpp | #include "TunnelAck.h"
#include "Globals.h"
using namespace EibStack;
CTunnelingAck::CTunnelingAck(unsigned char channelid, unsigned char sequencecounter, unsigned char status):
CEIBNetPacket<EIBNETIP_TUNNELING_ACK>(TUNNELLING_ACK)
{
_data.structlength = 4;
_data.channelid = channelid;
_data.sequencecounter = sequencecounter;
_data.typespecific = status;
}
CTunnelingAck::CTunnelingAck(unsigned char* data) :
CEIBNetPacket<EIBNETIP_TUNNELING_ACK>(data)
{
_data.structlength = data[0];
_data.channelid = data[1];
_data.sequencecounter = data[2];
_data.typespecific = data[4];
}
CTunnelingAck::~CTunnelingAck()
{
}
CString CTunnelingAck::GetStatusString() const
{
switch (_data.typespecific)
{
case E_CONNECTION_ID: return CString("Wrong channelid");
case E_CONNECTION_OPTION: return CString("Connection option not supported");
case E_CONNECTION_TYPE: return CString("Connection type not supported");
case E_DATA_CONNECTION: return CString("Problem with data connection");
case E_HOST_PROTOCOL_TYPE: return CString("Hostprotocol type not supported");
case E_KNX_CONNECTION: return CString("KNX connection error");
case E_NO_ERROR: return CString("No error");
case E_NO_MORE_CONNECTIONS: return CString("No more connections");
case E_SEQUENCE_NUMBER: return CString("Wrong Sequencenumber");
case E_TUNNELING_LAYER: return CString("Tunneling problem");
case E_VERSION_NOT_SUPPORTED: return CString("EIBNETIP version not supported");
default: return CString("Unknown error");
}
return EMPTY_STRING;
}
void CTunnelingAck::FillBuffer(unsigned char* buffer, int max_length)
{
CEIBNetPacket<EIBNETIP_TUNNELING_ACK>::FillBuffer(buffer,max_length);
unsigned char* tmp_ptr = buffer + GetHeaderSize();
memcpy(tmp_ptr,&_data,GetDataSize());
}
| [
"[email protected]"
] | [
[
[
1,
54
]
]
] |
a98a31ec6b8d012e739174c9d44270d0708d6e22 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_6_030.cpp | 2728419c51092c603c4434f1a5c68812cda7741e | [
"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 | 2,408 | cpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2006 Hartmut Kaiser. 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)
The tests included in this file were initially taken from the mcpp V2.5
preprocessor validation suite and were modified to fit into the Boost.Wave
unit test requirements.
The original files of the mcpp preprocessor are distributed under the
license reproduced at the end of this file.
=============================================================================*/
// Tests error reporting: ill-formed group in a source file.
// 17.6: Errorneous unterminated #if section in an included file.
//E t_6_030.hpp(49): warning: unbalanced #if/#endif in include file: $P(t_6_030.hpp)
#include "t_6_030.hpp"
#endif
/*-
* Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
*/
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
48
]
]
] |
c10bfc21cdde9013081353278c1904f43e025036 | 34fc82430b8a8a1c38019685888543fa1b124b1d | /planetariumfd/CConverter/stdafx.cpp | cbea8d9bfe3d4783ed85078d5c51995a9fc2861e | [] | no_license | witwall/planetariumfd | 5d70facd3304a98e54b0305a56b7339851c88618 | 25b516480ff39b89cbb5cd708a3add1d9aae0f1e | refs/heads/master | 2021-01-10T20:04:35.241471 | 2009-12-31T14:46:31 | 2009-12-31T14:46:31 | 37,585,240 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,388 | cpp | /* Copyright (C) 2005, 2006 Hartmut Holzgraefe
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* MySQL C client API example: mysql_fetch_fields()
*
* see also http://mysql.com/mysql_fetch_fields
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <mysql.h>
int main(int argc, char **argv)
{
MYSQL *mysql = NULL;
mysql = mysql_init(mysql);
if (!mysql) {
puts("Init faild, out of memory?");
return EXIT_FAILURE;
}
if (!mysql_real_connect(mysql, /* MYSQL structure to use */
"127.0.0.1", /* server hostname or IP address */
"root", /* mysql user */
"", /* password */
"test", /* default database to use, NULL for none */
0, /* port number, 0 for default */
NULL, /* socket file or named pipe name */
CLIENT_FOUND_ROWS /* connection flags */ )) {
puts("Connect failed\n");
} else {
mysql_query(mysql, "SET NAMES utf8");
if (mysql_query(mysql, "SELECT LPAD(i, 7, ' ') as t FROM test.f LIMIT 1")) {
printf("Query failed: %s\n", mysql_error(mysql));
} else {
MYSQL_RES *result = mysql_store_result(mysql);
if (!result) {
printf("Couldn't get results set: %s\n", mysql_error(mysql));
} else {
MYSQL_FIELD *fields;
fields = mysql_fetch_fields(result);
if (!fields) {
printf("Faild fetching fields: %s\n", mysql_error(mysql));
} else {
unsigned int i, num_fields = mysql_num_fields(result);
for (i = 0; i < num_fields; i++) {
printf("FIELD #%d\n", i);
printf(" %-20s %s\n", "Field name", fields[i].name);
#if MYSQL_VERSION_ID >= 40100
printf(" %-20s %s\n", "Original name", fields[i].org_name);
#endif
printf(" %-20s %s\n", "From table", fields[i].table);
printf(" %-20s %s\n", "Original name", fields[i].org_table);
printf(" %-20s %s\n", "Database", fields[i].db);
#if MYSQL_VERSION_ID >= 40100
printf(" %-20s %s\n", "Catalog", fields[i].catalog);
#endif
printf(" %-20s %s\n", "Default", fields[i].def);
printf(" %-20s %lu\n", "CREATE field length", fields[i].length);
printf(" %-20s %lu\n", "MAX field lengt", fields[i].max_length);
#if MYSQL_VERSION_ID >= 40100
printf(" %-20s %u\n", "Field name length", fields[i].name_length);
printf(" %-20s %u\n", "Original name length", fields[i].org_name_length);
printf(" %-20s %u\n", "Table name length", fields[i].table_length);
printf(" %-20s %u\n", "Original name length", fields[i].org_table_length);
printf(" %-20s %u\n", "DB name length", fields[i].db_length);
printf(" %-20s %u\n", "Catalog name length", fields[i].catalog_length);
printf(" %-20s %u\n", "Default length", fields[i].def_length);
#endif
/* TODO: decimals */
printf("\n");
}
}
}
}
}
mysql_close(mysql);
return EXIT_SUCCESS;
}
| [
"dimabur@5d7c0cd8-ee59-11de-8684-7d64432d61a3"
] | [
[
[
1,
105
]
]
] |
ed388c5639e689f118d42a3b8e55ed561caba3e5 | 60ef79535d316aaeb4efc4f79d700fcb1c87586f | /CUGBLinker/TipStatic.cpp | ef53a473e36c9a70453cc9d5185fca594bbd296f | [] | no_license | dinglx/cugblinker | 9b4cc5e129268cf3b2c14c99cd43a322c3f3487b | f4a2ee5bdecf41ec8ba91c63cf1923672964eae1 | refs/heads/master | 2021-01-16T00:27:54.122346 | 2009-12-16T17:00:50 | 2009-12-16T17:00:50 | 32,516,245 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,615 | cpp | // TipStatic.cpp : 实现文件
//
#include "stdafx.h"
#include "TipStatic.h"
// CTipStatic
IMPLEMENT_DYNAMIC(CTipStatic, CStatic)
CTipStatic::CTipStatic()
{
}
CTipStatic::~CTipStatic()
{
}
BEGIN_MESSAGE_MAP(CTipStatic, CStatic)
ON_WM_SETCURSOR()
ON_WM_CTLCOLOR_REFLECT()
END_MESSAGE_MAP()
// CTipStatic 消息处理程序
BOOL CTipStatic::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
::SetCursor(::LoadCursor(NULL,IDC_HAND));
return TRUE;
}
HBRUSH CTipStatic::CtlColor(CDC* pDC, UINT /*nCtlColor*/)
{
// TODO: 在此更改 DC 的任何属性
DWORD dwStyle = GetStyle();
if (!(dwStyle & SS_NOTIFY))
{
// Turn on notify flag to get mouse messages and STN_CLICKED.
// Otherwise, I'll never get any mouse clicks!
::SetWindowLong(m_hWnd, GWL_STYLE, dwStyle | SS_NOTIFY);
}
// TODO: 如果不应调用父级的处理程序,则返回非 null 画笔
pDC-> SetTextColor(RGB(0,0,255));
return NULL;
}
BOOL CTipStatic::PreTranslateMessage(MSG* pMsg)
{
// TODO: 在此添加专用代码和/或调用基类
m_tooltip.RelayEvent(pMsg);
return CStatic::PreTranslateMessage(pMsg);
}
void CTipStatic::PreSubclassWindow()
{
// TODO: 在此添加专用代码和/或调用基类
m_tooltip.Create(this);
m_tooltip.Activate(TRUE);
//m_tooltip.AddTool(this, "单击此处管理帐号");
//m_tooltip.SetMaxTipWidth(100);
CStatic::PreSubclassWindow();
}
void CTipStatic::SetText(CString text)
{
m_tooltip.AddTool(this,text);
}
| [
"dlx1986@4ddcaae0-7081-11de-ae35-f3f989a3c448",
"dinglinxiao@4ddcaae0-7081-11de-ae35-f3f989a3c448"
] | [
[
[
1,
39
],
[
41,
51
],
[
53,
78
]
],
[
[
40,
40
],
[
52,
52
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.