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
b2a19a2380d586236473ce5337850294ae9df470
c9f274dcf30c4a1911e39bc96190a810bb4216bc
/Sort/main.cpp
74522af7128e9c62c9c30e12c73cd40f5c65f8d7
[]
no_license
beatgammit/cs240
e88d054b3b9c489dfabc107351ded4a692f47015
8acd99469259d5fdb34ad5d43c8c82c02437ac73
refs/heads/master
2023-08-31T06:28:02.494209
2011-04-12T19:42:26
2011-04-12T19:42:26
1,467,628
0
1
null
null
null
null
UTF-8
C++
false
false
1,066
cpp
#include <iostream> #include <string.h> #include <stdlib.h> #include <fstream> #include "sort240.h" using namespace std; int main(int argc, char** args) { bool bReverse = false; bool bInsensitive = false; bool bAsNumber = false; int iColumn = 1; // start with the second param int iPos = 1; if(args[iPos][0] == '-'){ int iLength = strlen(args[iPos]); // skip the initial '-' for(int i = 1; i < iLength; i++){ switch(args[iPos][i]){ case 'r':{ bReverse = true; break; } case 'i':{ bInsensitive = true; break; } case 'n':{ bAsNumber = true; break; } } } iPos++; } iColumn = atoi(args[iPos]); iPos++; char* pFileName = args[iPos]; ifstream tFile; tFile.open(pFileName); Sort240 tSort240; tSort240.setFlags(bReverse, bInsensitive, bAsNumber); char tLine[MAX_LINE_LENGTH]; tLine[0] = '\0'; while(!tFile.eof()){ tFile.getline(tLine, MAX_LINE_LENGTH, '\n'); tSort240.addLine(tLine, iColumn); } tFile.close(); tSort240.sort(); tSort240.output(); return 0; }
[ "jameson@ubun64-lap.(none)" ]
[ [ [ 1, 64 ] ] ]
1ac8be1bca3f84d2b5ca81141e5f024139e558f3
5e2b72b494c5eec0cc74e26e89619089014f097a
/bola.h
fe9f35519228728f09f64dbf7bc3597e702c6420
[]
no_license
capaca/Destroyer3D
caeb57f05ff0857a630eb2cd94983e4fa81cae24
72a66594c696b502dc0aaf7fb8444ebde709a7b8
refs/heads/master
2021-01-18T18:17:48.943523
2009-06-16T20:47:08
2009-06-16T20:47:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
722
h
//=========================================================================== /* \author: <http://www.chai3d.org> \author: Remis Balaniuk \version 1.1 \date 10/2005 */ //=========================================================================== //--------------------------------------------------------------------------- #ifndef bolaH #define bolaH //--------------------------------------------------------------------------- #include "dynamicObject.h" #define SLICES 15 class bola : public dynamicObject { public: bola(dynamicWorld *mundo, float densidade, float raio); void criaBola(); float _densidade,_raio; }; #endif
[ [ [ 1, 31 ] ] ]
2166251e08bce6c102eac3b17cb80ab5a4c31134
0a69372d2ad5a8c3236097d182e50f13a4bd2f66
/tlibc/file.cpp
c7b9cc6b3071d48724179fb08961b7356d585903
[]
no_license
Tobbe/tvol
4f13d587fa016e95ba17fc08fd33559092b4bcd7
9f46410acd903d829371e3b4b6d417b2e74159a7
refs/heads/master
2021-04-26T06:31:52.992034
2009-03-02T22:20:21
2009-03-02T22:20:21
139,994
2
0
null
null
null
null
UTF-8
C++
false
false
7,434
cpp
// file.cpp // file routine overrides // 08/20/05 (mv) #include <windows.h> #include <stdio.h> #include "libct.h" /* FILE, as defined in stdio.h struct _iobuf { char *_ptr; int _cnt; char *_base; Used to store HANDLE int _flag; int _file; int _charbuf; int _bufsiz; char *_tmpfname; }; typedef struct _iobuf FILE; */ //_flag values (not the ones used by the normal CRT #define _FILE_TEXT 0x0001 #define _FILE_EOF 0x0002 #define _FILE_ERROR 0x0004 struct _FILE : public FILE { void set_handle(HANDLE h) {_base = (char*)h;}; HANDLE get_handle() const {return (HANDLE)_base;}; }; // used directly by the stdin, stdout, and stderr macros _FILE __iob[3]; FILE *__iob_func() {return (FILE*)__iob;} void _init_file() { // STDIN __iob[0].set_handle(GetStdHandle(STD_INPUT_HANDLE)); __iob[0]._flag = _FILE_TEXT; // STDOUT __iob[1].set_handle(GetStdHandle(STD_OUTPUT_HANDLE)); __iob[1]._flag = _FILE_TEXT; // STDERR __iob[2].set_handle(GetStdHandle(STD_ERROR_HANDLE)); __iob[2]._flag = _FILE_TEXT; } BEGIN_EXTERN_C /*int _fileno(FILE *fp) { return (int)fp; // FIXME: This doesn't work under Win64 } HANDLE _get_osfhandle(int i) { return (HANDLE)i; // FIXME: This doesn't work under Win64 }*/ FILE *fopen(const char *path, const char *attrs) { DWORD access, disp; if (strchr(attrs, 'w')) { access = GENERIC_WRITE; disp = CREATE_ALWAYS; } else { access = GENERIC_READ; disp = OPEN_EXISTING; } HANDLE hFile = CreateFileA(path, access, 0, 0, disp, 0, 0); if (hFile == INVALID_HANDLE_VALUE) return 0; _FILE *file = new _FILE; memset(file, 0, sizeof(_FILE)); file->set_handle(hFile); if (strchr(attrs, 't')) file->_flag |= _FILE_TEXT; return file; } FILE *_wfopen(const wchar_t *path, const wchar_t *attrs) { DWORD access, disp; if (wcschr(attrs, L'w')) { access = GENERIC_WRITE; disp = CREATE_ALWAYS; } else { access = GENERIC_READ; disp = OPEN_EXISTING; } HANDLE hFile = CreateFileW(path, access, 0, 0, disp, 0, 0); if (hFile == INVALID_HANDLE_VALUE) return 0; _FILE *file = new _FILE; memset(file, 0, sizeof(_FILE)); file->set_handle(hFile); if (wcschr(attrs, L't')) file->_flag |= _FILE_TEXT; return file; } int fprintf(FILE *fp, const char *s, ...) { va_list args; va_start(args, s); char bfr[1024]; int len = wvsprintfA(bfr, s, args); va_end(args); fwrite(bfr, len+1, sizeof(char), fp); return len; } int fwprintf(FILE *fp, const wchar_t *s, ...) { va_list args; va_start(args, s); wchar_t bfr[1024]; int len = wvsprintfW(bfr, s, args); va_end(args); char ansibfr[1024]; WideCharToMultiByte(CP_ACP, 0, bfr, -1, ansibfr, sizeof(ansibfr), 0, 0); fwrite(ansibfr, len+1, sizeof(char), fp); return len; } int fclose(FILE *fp) { CloseHandle(((_FILE*)fp)->get_handle()); delete fp; return 0; } int feof(FILE *fp) { return (fp->_flag & _FILE_EOF) ? 1 : 0; } int fseek(FILE *str, long offset, int origin) { DWORD meth = FILE_BEGIN; if (origin == SEEK_CUR) meth = FILE_CURRENT; else if (origin == SEEK_END) meth = FILE_END; SetFilePointer(((_FILE*)str)->get_handle(), offset, 0, meth); ((_FILE*)str)->_flag &= ~_FILE_EOF; return 0; } long ftell(FILE *fp) { return SetFilePointer(((_FILE*)fp)->get_handle(), 0, 0, FILE_CURRENT); } size_t fread(void *buffer, size_t size, size_t count, FILE *str) { if (size*count == 0) return 0; if (feof(str)) return 0; HANDLE hFile = ((_FILE*)str)->get_handle(); int textMode = ((_FILE*)str)->_flag & _FILE_TEXT; char *src; if (textMode) src = (char*)malloc(size*count); else src = (char*)buffer; DWORD br; if (!ReadFile(hFile, src, (DWORD)(size*count), &br, 0)) ((_FILE*)str)->_flag |= _FILE_ERROR; else if (!br) // nonzero return value and no bytes read = EOF ((_FILE*)str)->_flag |= _FILE_EOF; if (!br) return 0; // Text-mode translation is always ANSI if (textMode) // text mode: must translate CR -> LF { char *dst = (char*)buffer; for (DWORD i = 0; i < br; i++) { if (src[i] != '\r') { *dst++ = src[i]; continue; } // If next char is LF -> convert CR to LF if (i+1 < br) { if (src[i+1] == '\n') { *dst++ = '\n'; i++; } else *dst++ = src[i]; } else if (br > 1) { // This is the hard part: must peek ahead one byte DWORD br2 = 0; char peekChar = 0; ReadFile(hFile, &peekChar, 1, &br2, 0); if (!br2) *dst++ = src[i]; else if (peekChar == '\n') *dst++ = '\n'; else { fseek(str, -1, SEEK_CUR); *dst++ = src[i]; } } else *dst++ = src[i]; } free(src); } return br/size; } size_t fwrite(const void *buffer, size_t size, size_t count, FILE *str) { DWORD bw = 0, bw2 = 0; if (size*count == 0) return 0; HANDLE hFile = ((_FILE*)str)->get_handle(); int textMode = ((_FILE*)str)->_flag & _FILE_TEXT; // Text-mode translation is always ANSI! if (textMode) // text mode -> translate LF -> CRLF { const char *src = (const char*)buffer; size_t startpos = 0, i = 0; for (i = 0; i < size*count; i++) { if (src[i] != '\n') continue; if (i > 0 && src[i-1] == '\r') // don't translate CRLF continue; if (i > startpos) { WriteFile(hFile, &src[startpos], i-startpos, &bw2, 0); bw += bw2; } const char *crlf = "\r\n"; WriteFile(hFile, crlf, 2, &bw2, 0); bw++; // one '\n' written startpos = i+1; } if (i > startpos) { WriteFile(hFile, &src[startpos], i-startpos, &bw2, 0); bw += bw2; } } else WriteFile(hFile, buffer, (DWORD)(size*count), &bw, 0); return bw/size; } char *fgets(char *str, int n, FILE *s) { if (feof(s)) return 0; int i; for (i = 0; i < n-1; i++) { if (!fread(&str[i], 1, sizeof(char), s)) break; if (str[i] == '\r') { i--; continue; } if (str[i] == '\n') { i++; break; } } str[i] = 0; return str; } wchar_t *fgetws(wchar_t *str, int n, FILE *s) { // Text-mode fgetws converts MBCS->Unicode if (((_FILE*)str)->_flag & _FILE_TEXT) { char *bfr = (char*)malloc(n); fgets(bfr, n, s); MultiByteToWideChar(CP_ACP, 0, bfr, -1, str, n); free(bfr); return str; } // Binary fgetws reads as Unicode if (feof(s)) return 0; int i; for (i = 0; i < n-1; i++) { if (!fread(&str[i], 1, sizeof(wchar_t), s)) break; if (str[i] == L'\r') { i--; continue; // does i++ } if (str[i] == L'\n') { i++; break; } } str[i] = 0; return str; } int fgetc(FILE *s) { if (s == 0 || feof(s)) return EOF; char c; fread(&c, 1, sizeof(char), s); return (int)c; } wint_t fgetwc(FILE *s) { if (s == 0 || feof(s)) return (wint_t)EOF; // text-mode fgetwc reads and converts MBCS if (((_FILE*)s)->_flag & _FILE_TEXT) { char ch = (char)fgetc(s); wint_t wch; MultiByteToWideChar(CP_ACP, 0, &ch, 1, (LPWSTR)&wch, 1); return wch; } // binary fgetwc reads unicode wint_t c; fread(&c, 1, sizeof(wint_t), s); return c; } END_EXTERN_C
[ [ [ 1, 404 ] ] ]
1932617609e85bedfa19ab5c37ac78ac279889a9
5d35825d03fbfe9885316ec7d757b7bcb8a6a975
/inc/ColladaReader.h
1f6953d72c62ed4d4057bd72c58fd614efc5e148
[]
no_license
jjzhang166/3D-Landscape-linux
ce887d290b72ebcc23386782dd30bdd198db93ef
4f87eab887750e3dc5edcb524b9e1ad99977bd94
refs/heads/master
2023-03-15T05:24:40.303445
2010-03-25T00:23:43
2010-03-25T00:23:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,224
h
#ifndef __COLLADDA_READER_H__ #define __COLLADDA_READER_H__ #include <dae.h> #include <dom/domCOLLADA.h> #include <dom/domElements.h> #include <iostream> #include <string> #include <vector> #include <map> #include <cstring> #include <definesall.h> #include <QString> #include <QStringList> #define FILENAME "./cube5.dae" using namespace std; struct TSource { vector<float> data; string name; }; struct TVertices { vector<float> data; string name; }; struct TMaterial { bool texture; string name; float color[4]; //RGBA string imageURL; }; //structure, representing <triangles> element with corresponding texture filename, vertices, normals and texture coordinates struct TTriangles { vector<float> vertices; vector<float> normals; vector<float> textureCoords; //string textureFileName; int textureIndex; bool texture; float color[4]; //RGBA }; struct TGeomInfo { //number of different vertices arrays int groupsNum; //size of each vertex array int *groupsSize; //texture file name for each vertex array char **textFileNames; //array of vertices arrays float **vertices; //array of normal arrays corresponding to vertices arrays float **normals; //array of texture coordinates arrays corresponding to vertices arrays float **textureCoords; ~TGeomInfo(); }; struct TGeometry { vector<TTriangles> trianglesStrs; vector<TVertices> verticesStrs; vector<TSource> sourcesStrs; //vector<string> textureFileNames; //vector<int> textureIndices; }; struct TRotation { float rotation[4]; }; struct TTranslation { float translation[3]; }; struct TScaling { float scaling[3]; }; //structure, representing <node> + geometry information struct TNode { //vector<TGeometry> geometries; //translations, scalings, rotations //vector<TPut> puts; //IDs of geometry elements used by this node vector<string> geometryIDs; //translations vector<TTranslation> translations; //scalings vector<TScaling> scalings; //rotations vector<TRotation> rotations; string id; }; class ColladaReader { public: ColladaReader(); ColladaReader(char *path); virtual ~ColladaReader(); //get a scene information from file together with the geometry u_short getScene(); u_short getGeometries(); //vector of node structures vector<TNode> nodes; //map of geometry structures (its elements are referenced by nodes) map<string, TGeometry> geometries; //all the textures used by geometries vector<string> textureFileNames; private: u_short getMaterials(); u_short getVertices(vector<daeElement*> nodes); //fills in array of vertices for the geometry u_short getVerticesS(TGeometry &geometry, domMesh *currMesh); //fills in array of sources for the geometry u_short getSourcesS(TGeometry &geometry, domMesh *currMesh); u_short getSources(vector<daeElement*> nodes); void buildAddTrianglesStructureS(int verticesStructIndex, int normalsStructIndex, int textCoordsStructIndex, int materialsStructIndex, int vertexOffset, int normalOffset, int textCoordOffset, int inputsNum, domListOfUInts pArray, TGeometry &geometry ); //returns an index of the texture file name if it is already in textureFileNames //structure. -1, otherwise int isTextureLoaded(string textureFileName); DAE dae; daeElement* root; string openedDoc; //arrays of triangles for each mesh vector<domTriangles_Array> triangles; vector<TVertices> verticesStrs; vector<TSource> sourcesStrs; //vector<string> textureFileNames; vector<TMaterial> materialsStrs; //vector of TTriangles structures vector<TTriangles> trianglesStrs; }; #endif //__COLLADDA_READER_H__
[ [ [ 1, 181 ] ] ]
e47d4694ff7689ffecebdf39f5b80ac8fc926b6f
6e563096253fe45a51956dde69e96c73c5ed3c18
/ZKit/ZKit_TLV.h
a85ac6d23a2937cc5c2624f051bd42b93332abcd
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
GB18030
C++
false
false
2,376
h
#ifndef _ZKit_TLV_h_ #define _ZKit_TLV_h_ #include "ZKit_Protocol.h" #include "ZKit_ISerializable.h" #include "ZKit_BitConverter.h" #include "ZKit_Mutex.h" #include "ZKit_Locker.h" BEGIN_ZKIT class TLV : public ISerializable { public: TLV(); TLV(const uint16 type, const uint32 length, const char* value); virtual ~TLV(); //属性. uint16 GetType() const { return m_type; } uint32 GetLength() const { return m_length; } const char* GetValue() const { return m_value; } bool Check() const { return GetType() > 0 && GetLength() > 0 && GetValue() != NULL; } uint32 GetTotalLength() const; //标准初始化函数 void Init(const uint16 type, const uint32 length, const char* value); //如果参数只是简单数值类型如int, short, 可以采用此函数来初始化tlv template<typename T> void Init(const uint16 type, const T& value) { char buf[sizeof(T)]; BitConverter::ToBytes(value, buf); Init(type, sizeof(T), buf); } //如果参数是简单数值类型的数组如int[], 可以采用此函数来初始化tlv template<typename T> void Init(const uint16 type, const T* p, size_t size) { std::vector<char> v; v.reserve(size * sizeof(T)); for (size_t i = 0; i < size; ++i) { BitConverter::AppendValue(v, p[i]); } Init(type, (uint32)v.size(), &v[0]); } template<typename T> void GetArg(T& value) { BitConverter::GetValue(m_value, 0, value); } TLV& operator = (const TLV& rhs) { if (&rhs != this) { Init(rhs.GetType(), rhs.GetLength(), rhs.GetValue()); } return *this; } TLV(const TLV& rhs) : m_type(0), m_length(0), m_value(NULL) { *this = rhs; } bool Equals(const TLV& rhs) const { return m_type == rhs.m_type && m_length == rhs.m_length && 0 == memcmp(m_value, rhs.m_value, m_length); } bool operator == (const TLV& rhs) const { return this->Equals(rhs); } std::string ToString() const; virtual bool Serialize(std::vector<char>& bytes) const; virtual bool Deserialize(const std::vector<char>& bytes); private: uint16 m_type; uint32 m_length; char* m_value; }; //注意<< 和 >> 不应该是成员函数, 但它们是类接口 std::ostream& operator << (std::ostream& os, const TLV& tlv); END_ZKIT #endif // _ZKit_TLV_h_
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 117 ] ] ]
3ff49a728b0a7c8760e817f2911569a80eba95e1
6fa6532d530904ba3704da72327072c24adfc587
/SCoder/QtGUI/headers/enterkeypage.h
e5a9b1e2dea8b8b7b7f92b40ef925424d5e627d4
[]
no_license
photoguns/code-hnure
277b1c0a249dae75c66e615986fb1477e6e0f938
92d6ab861a9de3f409c5af0a46ed78c2aaf13c17
refs/heads/master
2020-05-20T08:56:07.927168
2009-05-29T16:49:34
2009-05-29T16:49:34
35,911,792
0
0
null
null
null
null
UTF-8
C++
false
false
1,168
h
#ifndef _ENTERKEYPAGE_H_ #define _ENTERKEYPAGE_H_ //////////////////////////////////////////////////////////////////////////////// #include <QWizardPage> //////////////////////////////////////////////////////////////////////////////// class QLineEdit; /** C++ class representing GUI Wizard page * * * @author Roman Pasechnik * @since May 24th, 2009 * @updated May 24th, 2009 * */ class EnterKeyPage : public QWizardPage { //////////////////////////////////////////////////////////////////////////////// Q_OBJECT public: //////////////////////////////////////////////////////////////////////////////// /** Constructor */ EnterKeyPage( QWidget* _parent = NULL ); /** Destructor */ virtual ~EnterKeyPage(); /** Next page handler */ virtual int nextId() const; //////////////////////////////////////////////////////////////////////////////// private: //////////////////////////////////////////////////////////////////////////////// /** Line edit */ QLineEdit* m_Key; //////////////////////////////////////////////////////////////////////////////// }; #endif
[ "[email protected]@8592428e-0b6d-11de-9036-69e38a880166", "cutwatercore@8592428e-0b6d-11de-9036-69e38a880166" ]
[ [ [ 1, 22 ], [ 24, 55 ] ], [ [ 23, 23 ] ] ]
3486ddc8321f22150c5182fe5b74c8acdf40a891
554a3b859473dc4dfebc6a31b16dfd14c84ffd09
/sxsim/flags.hpp
edb97fc4cf03fa8e7207a4158d3b3f0455ca82f4
[ "BSL-1.0" ]
permissive
DannyHavenith/sxsim
c0fbaf016fc7dcae7535e152ae9e33f3386d3792
e3d5ad1f6f75157397d03c191b4b4b0af00ebb60
refs/heads/master
2021-01-19T11:22:20.615306
2011-05-30T22:11:18
2011-05-30T22:11:18
1,822,817
0
0
null
null
null
null
UTF-8
C++
false
false
762
hpp
// Copyright Danny Havenith 2006 - 2009. // 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) /// definition of the flag bits of an SX microcontroller #if !defined( FLAGS_INCLUDED) #define FLAGS_INCLUDED // definition of sx flags struct sx_flags { static const int DC_MASK = 0x0f; static const int CARRY_MASK = 0xff; static const int LEFT_OUTSIDE_CARRY_MASK = (CARRY_MASK | (CARRY_MASK << 1)) ^ CARRY_MASK; static const int NO_FLAGS = 0; static const int Z = (1<<2); static const int DC = (1<<1); static const int C = (1<<0); }; typedef sx_flags sx_flags_definition; #endif //FLAGS_INCLUDED
[ "danny@3a7aa2ed-2c50-d14e-a1b9-f07bebb4988c", "Danny@3a7aa2ed-2c50-d14e-a1b9-f07bebb4988c" ]
[ [ [ 1, 8 ] ], [ [ 9, 28 ] ] ]
4cb9710583a4c921d9107f6746261102d6661ffc
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/MyGUIEngine/include/MyGUI_IResource.h
bbde3d368b4372357cc1b39a18bec0513ab1eeb4
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
1,795
h
/*! @file @author Albert Semenov @date 09/2008 */ /* This file is part of MyGUI. MyGUI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __MYGUI_I_RESOURCE_H__ #define __MYGUI_I_RESOURCE_H__ #include "MyGUI_Prerequest.h" #include "MyGUI_XmlDocument.h" #include "MyGUI_Version.h" #include "MyGUI_ISerializable.h" namespace MyGUI { class IResource; typedef IResource* IResourcePtr; class ResourceManager; class MYGUI_EXPORT IResource : public ISerializable { // для серелизации и удаления friend class ResourceManager; MYGUI_RTTI_DERIVED( IResource ) public: const std::string& getResourceName() const { return mResourceName; } protected: IResource() { } private: // constructors and operator =, without implementation, just for private IResource(IResource const&); IResource& operator = (IResource const&); protected: virtual void deserialization(xml::ElementPtr _node, Version _version) { _node->findAttribute("name", mResourceName); } virtual ~IResource() { } protected: std::string mResourceName; }; } // namespace MyGUI #endif // __MYGUI_I_RESOURCE_H__
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 72 ] ] ]
416eb4c75541599821fdcb5b48d47c40f80c6dcf
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/misc/post90s/d_diverboy.cpp
4bd07885a98d4961ac643133022cd0f09d88ffee
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
12,505
cpp
// FB Alpha Diverboy driver module // Based on MAME driver by David Haywood #include "tiles_generic.h" #include "msm6295.h" static unsigned char *AllMem; static unsigned char *MemEnd; static unsigned char *AllRam; static unsigned char *RamEnd; static unsigned char *Drv68KROM; static unsigned char *Drv68KRAM; static unsigned char *DrvZ80ROM; static unsigned char *DrvZ80RAM; static unsigned char *DrvSndROM; static unsigned char *DrvGfxROM0; static unsigned char *DrvGfxROM1; static unsigned char *DrvPalRAM; static unsigned char *DrvSprRAM; static unsigned int *DrvPalette; static unsigned char DrvRecalc; static unsigned char DrvJoy1[16]; static unsigned char DrvJoy2[16]; static unsigned char DrvDips[1]; static unsigned char DrvReset; static unsigned short DrvInputs[2]; static unsigned char *soundlatch; static unsigned char *samplebank; static struct BurnInputInfo DiverboyInputList[] = { {"Coin 1", BIT_DIGITAL, DrvJoy2 + 0, "p1 coin" }, {"Coin 2", BIT_DIGITAL, DrvJoy2 + 1, "p2 coin" }, {"Coin 3", BIT_DIGITAL, DrvJoy2 + 2, "p3 coin" }, {"P1 Start", BIT_DIGITAL, DrvJoy1 + 7, "p1 start" }, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" }, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" }, {"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left" }, {"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" }, {"P2 Start", BIT_DIGITAL, DrvJoy1 + 15, "p2 start" }, {"P2 Up", BIT_DIGITAL, DrvJoy1 + 8, "p2 up" }, {"P2 Down", BIT_DIGITAL, DrvJoy1 + 9, "p2 down" }, {"P2 Left", BIT_DIGITAL, DrvJoy1 + 10, "p2 left" }, {"P2 Right", BIT_DIGITAL, DrvJoy1 + 11, "p2 right" }, {"P2 Button 1", BIT_DIGITAL, DrvJoy1 + 12, "p2 fire 1" }, {"P2 Button 2", BIT_DIGITAL, DrvJoy1 + 13, "p2 fire 2" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset" }, {"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" }, }; STDINPUTINFO(Diverboy) static struct BurnDIPInfo DiverboyDIPList[]= { {0x12, 0xff, 0xff, 0xb8, NULL }, {0 , 0xfe, 0 , 8, "Coinage" }, {0x12, 0x01, 0x07, 0x07, "4 Coins 1 Credits" }, {0x12, 0x01, 0x07, 0x06, "3 Coins 1 Credits" }, {0x12, 0x01, 0x07, 0x05, "2 Coins 1 Credits" }, {0x12, 0x01, 0x07, 0x00, "1 Coin 1 Credits" }, {0x12, 0x01, 0x07, 0x01, "1 Coin 2 Credits" }, {0x12, 0x01, 0x07, 0x02, "1 Coin 3 Credits" }, {0x12, 0x01, 0x07, 0x03, "1 Coin 4 Credits" }, {0x12, 0x01, 0x07, 0x04, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 2, "Lives" }, {0x12, 0x01, 0x08, 0x00, "2" }, {0x12, 0x01, 0x08, 0x08, "3" }, {0 , 0xfe, 0 , 2, "Display Copyright" }, {0x12, 0x01, 0x10, 0x00, "No" }, {0x12, 0x01, 0x10, 0x10, "Yes" }, {0 , 0xfe, 0 , 4, "Difficulty" }, {0x12, 0x01, 0x60, 0x00, "Easy" }, {0x12, 0x01, 0x60, 0x20, "Normal" }, {0x12, 0x01, 0x60, 0x40, "Hard" }, {0x12, 0x01, 0x60, 0x60, "Hardest" }, {0 , 0xfe, 0 , 2, "Free Play" }, {0x12, 0x01, 0x80, 0x80, "No" }, {0x12, 0x01, 0x80, 0x00, "Yes" }, }; STDDIPINFO(Diverboy) void __fastcall diverboy_write_byte(unsigned int /*address*/, unsigned char /*data*/) { } void __fastcall diverboy_write_word(unsigned int address, unsigned short data) { if (address == 0x100000) { *soundlatch = data; ZetSetIRQLine(0, ZET_IRQSTATUS_AUTO); return; } } unsigned char __fastcall diverboy_read_byte(unsigned int address) { switch (address) { case 0x180000: return DrvInputs[0] >> 8; case 0x180001: return DrvInputs[0] & 0xff; case 0x180009: return DrvInputs[1] & 0xf7; } return 0; } unsigned short __fastcall diverboy_read_word(unsigned int address) { switch (address) { case 0x180002: return DrvDips[0]; case 0x180008: return DrvInputs[1]; } return 0; } static inline void sample_bank(int data) { *samplebank = data & 3; MSM6295ROM = DrvSndROM + ((data & 3) << 18); } void __fastcall diverboy_sound_write(unsigned short address, unsigned char data) { switch (address) { case 0x9000: sample_bank(data); return; case 0x9800: MSM6295Command(0, data); return; } } unsigned char __fastcall diverboy_sound_read(unsigned short address) { switch (address) { case 0x9800: return MSM6295ReadStatus(0); case 0xa000: return *soundlatch; } return 0; } static int DrvDoReset() { DrvReset = 0; memset (AllRam, 0, RamEnd - AllRam); SekOpen(0); SekReset(); SekClose(); ZetOpen(0); ZetReset(); ZetClose(); sample_bank(0); MSM6295Reset(0); return 0; } static int MemIndex() { unsigned char *Next; Next = AllMem; Drv68KROM = Next; Next += 0x040000; DrvZ80ROM = Next; Next += 0x010000; DrvGfxROM0 = Next; Next += 0x200000; DrvGfxROM1 = Next; Next += 0x100000; MSM6295ROM = Next; DrvSndROM = Next; Next += 0x100000; DrvPalette = (unsigned int*)Next; Next += 0x0400 * sizeof(int); AllRam = Next; Drv68KRAM = Next; Next += 0x010000; DrvPalRAM = Next; Next += 0x000800; DrvSprRAM = Next; Next += 0x004000; DrvZ80RAM = Next; Next += 0x000800; soundlatch = Next; Next += 0x000001; samplebank = Next; Next += 0x000001; RamEnd = Next; MemEnd = Next; return 0; } static int DrvGfxDecode() { int Plane[4] = { 0, 1, 2, 3 }; int XOffs[16] = { 56, 60, 48, 52, 40, 44, 32, 36, 24, 28, 16, 20, 8, 12, 0, 4 }; int YOffs[16] = { 0, 64, 128, 192, 256, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960 }; unsigned char *tmp = (unsigned char*)malloc(0x100000); if (tmp == NULL) { return 1; } memcpy (tmp, DrvGfxROM0, 0x100000); GfxDecode(0x2000, 4, 16, 16, Plane, XOffs, YOffs, 0x400, tmp, DrvGfxROM0); memcpy (tmp, DrvGfxROM1, 0x080000); GfxDecode(0x1000, 4, 16, 16, Plane, XOffs, YOffs, 0x400, tmp, DrvGfxROM1); free (tmp); return 0; } static int DrvInit() { AllMem = NULL; MemIndex(); int nLen = MemEnd - (unsigned char *)0; if ((AllMem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(AllMem, 0, nLen); MemIndex(); { if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1; if (BurnLoadRom(DrvZ80ROM, 2, 1)) return 1; memcpy (DrvZ80ROM, DrvZ80ROM + 0x8000, 0x8000); if (BurnLoadRom(DrvGfxROM0 + 0x000000, 3, 2)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x000001, 4, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x000000, 5, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x000001, 6, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x040000, 7, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x040001, 8, 2)) return 1; if (BurnLoadRom(DrvSndROM + 0x000000, 9, 1)) return 1; memcpy (DrvSndROM + 0xc0000, DrvSndROM + 0x60000, 0x20000); memcpy (DrvSndROM + 0x80000, DrvSndROM + 0x40000, 0x20000); memcpy (DrvSndROM + 0x40000, DrvSndROM + 0x20000, 0x20000); if (BurnLoadRom(DrvSndROM + 0x020000, 10, 1)) return 1; memcpy (DrvSndROM + 0xe0000, DrvSndROM + 0x20000, 0x20000); memcpy (DrvSndROM + 0xa0000, DrvSndROM + 0x20000, 0x20000); memcpy (DrvSndROM + 0x60000, DrvSndROM + 0x20000, 0x20000); DrvGfxDecode(); } SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KROM, 0x000000, 0x03ffff, SM_ROM); SekMapMemory(Drv68KRAM, 0x040000, 0x04ffff, SM_RAM); SekMapMemory(DrvSprRAM, 0x080000, 0x083fff, SM_RAM); SekMapMemory(DrvPalRAM, 0x140000, 0x1407ff, SM_RAM); SekSetWriteByteHandler(0, diverboy_write_byte); SekSetWriteWordHandler(0, diverboy_write_word); SekSetReadByteHandler(0, diverboy_read_byte); SekSetReadWordHandler(0, diverboy_read_word); SekClose(); ZetInit(1); ZetOpen(0); ZetMapArea(0x0000, 0x7fff, 0, DrvZ80ROM); ZetMapArea(0x0000, 0x7fff, 2, DrvZ80ROM); ZetMapArea(0x8000, 0x87ff, 0, DrvZ80RAM); ZetMapArea(0x8000, 0x87ff, 1, DrvZ80RAM); ZetMapArea(0x8000, 0x87ff, 2, DrvZ80RAM); ZetSetWriteHandler(diverboy_sound_write); ZetSetReadHandler(diverboy_sound_read); ZetMemEnd(); ZetClose(); MSM6295Init(0, 1320000 / 132, 100.0, 0); GenericTilesInit(); DrvDoReset(); return 0; } static int DrvExit() { GenericTilesExit(); MSM6295Exit(0); SekExit(); ZetExit(); free (AllMem); AllMem = NULL; MSM6295ROM = NULL; return 0; } static void draw_sprites() { unsigned short *vram = (unsigned short*)DrvSprRAM; for (int offs = 0; offs < 0x4000 / 2; offs+=8) { int sy = ( 256 - swapWord(vram[offs + 4])) - 16; int sx = ((480 - swapWord(vram[offs + 0])) & 0x1ff) - 173; int attr = swapWord(vram[offs + 1]); int code = swapWord(vram[offs + 3]); int color = ((attr & 0x00f0) >> 4) | ((attr & 0x000c) << 2); int flash = (attr & 0x1000); int bank = (attr & 0x0002) >> 1; if (flash && (GetCurrentFrame() & 1)) continue; if (sx >= nScreenWidth || sy >= nScreenHeight || sx < -15 || sy < -15) continue; if (attr & 0x0008) { Render16x16Tile_Clip(pTransDraw, code, sx, sy, color, 4, 0, bank ? DrvGfxROM1 : DrvGfxROM0); } else { Render16x16Tile_Mask_Clip(pTransDraw, code, sx, sy, color, 4, 0, 0, bank ? DrvGfxROM1 : DrvGfxROM0); } } } static int DrvDraw() { if (DrvRecalc) { unsigned char r,g,b; unsigned short *pal = (unsigned short*)DrvPalRAM; for (int i = 0; i < 0x800 / 2; i++, pal++) { r = ((swapWord(*pal) << 4) & 0xf0) | ((swapWord(*pal) << 0) & 0x0f); g = ((swapWord(*pal) >> 0) & 0xf0) | ((swapWord(*pal) >> 4) & 0x0f); b = ((swapWord(*pal) >> 4) & 0xf0) | ((swapWord(*pal) >> 8) & 0x0f); DrvPalette[i] = BurnHighCol(r, g, b, 0); } } draw_sprites(); BurnTransferCopy(DrvPalette); return 0; } static int DrvFrame() { if (DrvReset) { DrvDoReset(); } { DrvInputs[0] = ~0; DrvInputs[1] = ~8; for (int i = 0; i < 16; i++) { DrvInputs[0] ^= (DrvJoy1[i] & 1) << i; DrvInputs[1] ^= (DrvJoy2[i] & 1) << i; } } int nSegment; int nInterleave = 10; int nTotalCycles[2] = { 12000000 / 60, 4000000 / 60 }; int nCyclesDone[2] = { 0, 0 }; SekOpen(0); ZetOpen(0); for (int i = 0; i < nInterleave; i++) { nSegment = (nTotalCycles[0] - nCyclesDone[0]) / (nInterleave - i); nCyclesDone[0] += SekRun(nSegment); nSegment = (nTotalCycles[1] - nCyclesDone[1]) / (nInterleave - i); nCyclesDone[1] += ZetRun(nSegment); } SekSetIRQLine(6, SEK_IRQSTATUS_AUTO); if (pBurnSoundOut) { MSM6295Render(0, pBurnSoundOut, nBurnSoundLen); } ZetClose(); SekClose(); if (pBurnDraw) { DrvDraw(); } return 0; } static int DrvScan(int nAction, int *pnMin) { struct BurnArea ba; if (pnMin != NULL) { *pnMin = 0x029698; } if (nAction & ACB_MEMORY_RAM) { memset(&ba, 0, sizeof(ba)); ba.Data = AllRam; ba.nLen = RamEnd-AllRam; ba.szName = "All Ram"; BurnAcb(&ba); } if (nAction & ACB_DRIVER_DATA) { SekScan(nAction); ZetScan(nAction); MSM6295Scan(0, nAction); if (nAction & ACB_WRITE) { sample_bank(*samplebank); } } return 0; } // Diver Boy static struct BurnRomInfo diverboyRomDesc[] = { { "db_01.bin", 0x20000, 0x6aa11366, 1 | BRF_PRG | BRF_ESS }, // 0 68K Code { "db_02.bin", 0x20000, 0x45f8a673, 1 | BRF_PRG | BRF_ESS }, // 1 { "db_05.bin", 0x10000, 0xffeb49ec, 2 | BRF_PRG | BRF_ESS }, // 2 Z80 Code { "db_08.bin", 0x80000, 0x7bb96220, 3 | BRF_GRA }, // 3 Bank 0 Graphics { "db_09.bin", 0x80000, 0x12b15476, 3 | BRF_GRA }, // 4 { "db_07.bin", 0x20000, 0x18485741, 4 | BRF_GRA }, // 5 Bank 1 Graphics { "db_10.bin", 0x20000, 0xc381d1cc, 4 | BRF_GRA }, // 6 { "db_06.bin", 0x20000, 0x21b4e352, 4 | BRF_GRA }, // 7 { "db_11.bin", 0x20000, 0x41d29c81, 4 | BRF_GRA }, // 8 { "db_03.bin", 0x80000, 0x50457505, 5 | BRF_SND }, // 9 Oki6295 Samples { "db_04.bin", 0x20000, 0x01b81da0, 5 | BRF_SND }, // 10 }; STD_ROM_PICK(diverboy) STD_ROM_FN(diverboy) struct BurnDriver BurnDrvDiverboy = { "diverboy", NULL, NULL, "1992", "Diver Boy\0", NULL, "Electronic Devices Italy", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, diverboyRomInfo, diverboyRomName, DiverboyInputInfo, DiverboyDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 320, 240, 4, 3 };
[ [ [ 1, 497 ] ] ]
bfd44a24e470435befd255e229ca0adf9c83be3d
842997c28ef03f8deb3422d0bb123c707732a252
/src/moaicore/MOAIXmlParser.cpp
b9a345471e7b1c548ffd0b82bf9f0bb7b40386d7
[]
no_license
bjorn/moai-beta
e31f600a3456c20fba683b8e39b11804ac88d202
2f06a454d4d94939dc3937367208222735dd164f
refs/heads/master
2021-01-17T11:46:46.018377
2011-06-10T07:33:55
2011-06-10T07:33:55
1,837,561
2
1
null
null
null
null
UTF-8
C++
false
false
4,301
cpp
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <tinyxml.h> #include <moaicore/MOAILogMessages.h> #include <moaicore/MOAIXmlParser.h> //================================================================// // local //================================================================// //----------------------------------------------------------------// /** @name parseFile @text Parses the contents of the specified file as XML. @in MOAIXmlParser self @in string filename The path of the file to read the XML data from. @out table data A tree of tables representing the XML. */ int MOAIXmlParser::_parseFile ( lua_State* L ) { USLuaState state ( L ); if ( !state.CheckParams ( 1, "S" )) return 0; cc8* filename = lua_tostring ( state, 1 ); MOAI_CHECK_FILE ( filename ); TiXmlDocument doc; doc.LoadFile ( filename ); MOAIXmlParser::Parse ( state, doc.RootElement ()); return 1; } //----------------------------------------------------------------// /** @name parseString @text Parses the contents of the specified string as XML. @in MOAIXmlParser self @in string filename The XML data stored in a string. @out table data A tree of tables representing the XML. */ int MOAIXmlParser::_parseString ( lua_State* L ) { USLuaState state ( L ); if ( !state.CheckParams ( 1, "S" )) return 0; cc8* xml = lua_tostring ( state, 1 ); TiXmlDocument doc; doc.Parse ( xml ); MOAIXmlParser::Parse ( state, doc.RootElement ()); return 1; } //================================================================// // MOAIXmlParser //================================================================// //----------------------------------------------------------------// MOAIXmlParser::MOAIXmlParser () { } //----------------------------------------------------------------// MOAIXmlParser::~MOAIXmlParser () { } //----------------------------------------------------------------// void MOAIXmlParser::Parse ( USLuaState& state, TiXmlNode* node ) { if ( !node ) return; TiXmlElement* element = node->ToElement(); if ( element ) { lua_newtable ( state ); // element name lua_pushstring ( state, element->Value ()); lua_setfield ( state, -2, "type" ); // parse attributes TiXmlAttribute* attribute = element->FirstAttribute (); if ( attribute ) { lua_newtable ( state ); for ( ; attribute; attribute = attribute->Next ()) { lua_pushstring ( state, attribute->Value ()); lua_setfield ( state, -2, attribute->Name ()); } lua_setfield ( state, -2, "attributes" ); } // round up the children STLSet < string > children; TiXmlElement* childElement = node->FirstChildElement (); for ( ; childElement; childElement = childElement->NextSiblingElement ()) { children.affirm ( childElement->Value ()); } if ( children.size ()) { lua_newtable ( state ); STLSet < string >::iterator childrenIt = children.begin (); for ( ; childrenIt != children.end (); ++childrenIt ) { string name = *childrenIt; lua_newtable ( state ); childElement = node->FirstChildElement ( name ); for ( u32 count = 1; childElement; childElement = childElement->NextSiblingElement ( name ), ++count ) { MOAIXmlParser::Parse ( state, childElement ); lua_rawseti ( state, -2, count ); } lua_setfield ( state, -2, name.c_str ()); } lua_setfield ( state, -2, "children" ); } // handle text children TiXmlNode* child = node->FirstChild (); if ( child ) { TiXmlText* text = child->ToText (); if ( text ) { lua_pushstring ( state, text->Value ()); lua_setfield ( state, -2, "value" ); } } } } //----------------------------------------------------------------// void MOAIXmlParser::RegisterLuaClass ( USLuaState& state ) { luaL_Reg regTable[] = { { "parseFile", _parseFile }, { "parseString", _parseString }, { NULL, NULL } }; luaL_register( state, 0, regTable ); } //----------------------------------------------------------------// void MOAIXmlParser::RegisterLuaFuncs ( USLuaState& state ) { UNUSED ( state ); }
[ [ [ 1, 149 ] ] ]
3b7686b85e1a85812b7a109e955bb474209ba92e
62cd42ea3851a4e80a8e631ee02cc58433ac2731
/istreamTS.h
361c7398dfe71a43ec1e69d761b9fb773360df92
[]
no_license
linuxts2epg/ts2epg
a0b84979b8437140843b7b07bc5cad25be3a2585
749f82a9412d94e39dd62570dfb7de2973f20a03
refs/heads/master
2020-05-20T11:28:52.982115
2008-09-07T15:06:36
2008-09-07T15:06:36
50,156
2
2
null
null
null
null
UTF-8
C++
false
false
554
h
/* * istreamTS.h * * Created on: 2008/09/04 * Author: linux_ts2epg */ #ifndef ISTREAMTS_H_ #define ISTREAMTS_H_ #include <iostream> #include <fstream> #include "SectionFormat.h" using namespace std; class istreamTS { istream &ris; unsigned char sectionBuf[6144]; size_t sectionBufLength; size_t sectionLength; public: istreamTS(istream &ris); ~istreamTS(); istreamTS &operator >>(SectionFormat &section); // istreamTS &operator >>(istreamTS &(*pmanipFunc)(istreamTS &)); }; #endif /* ISTREAMTS_H_ */
[ [ [ 1, 30 ] ] ]
3bfb8e75703ef9b60594b65f8b991ecbce7e46f1
55c675d13726d1ce015f0193654593e3b6b0f269
/stdafx.cpp
984f49bf9667a01f045252ea7db645d2df7834c5
[]
no_license
fourier/Geometry2d
c4e0e9eaa16375f675fddecaab01f75b9b99dbf0
2f84511e06ae012d6c9052796e70015d5f81acc6
refs/heads/master
2020-12-24T14:10:07.238982
2009-05-26T06:57:15
2009-05-26T06:57:15
12,709,941
1
0
null
null
null
null
UTF-8
C++
false
false
210
cpp
// stdafx.cpp : source file that includes just the standard includes // Geometry2d.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ [ [ 1, 7 ] ] ]
956cd764171a835360c47bc6fd800d58575330c2
8edb23872f88889745ec028ae2bd57686ed1a5d6
/PocketPenny/Expense.h
5961fde6ee84a5fb4a693966978f76e64d6960b4
[]
no_license
mayankk4/PocketPenny
725a0ba9072ac04b82684ce05c6305c2b09df179
113f0c58dc7d8e0454dcec6b87af3971da99935b
refs/heads/master
2020-05-19T09:57:02.662381
2011-02-15T07:18:42
2011-02-15T07:18:42
2,845,420
1
0
null
null
null
null
UTF-8
C++
false
false
696
h
#ifndef EXPENSE_H #define EXPENSE_H #include <QString> #include <QDate> #include <QTime> class Expense { private: int expId; int catId; float amount; int expDay; int expMonth; int expYear; QTime expTime; public: Expense(); Expense(int,float,int,int,int,QTime); void setExpId(int); int getExpId(); void setCatId(int); int getCatId(); void setAmount(float); float getAmount(); void setExpDay(int); int getExpDay(); void setExpMonth(int); int getExpMonth(); void setExpYear(int); int getExpYear(); void setExpTime(QTime); QTime getExpxpTime(); }; #endif // EXPENSE_H
[ "[email protected]@8a4d664d-70e0-44f4-806d-ec41310e5d3c" ]
[ [ [ 1, 37 ] ] ]
b426d60b8978b1f11f2a11e0c6845e1b48b14427
9ab5db1fbf99317fdf9fa327d3aae6e45493e993
/SimpleEngine.h
0bf52dd9eb352cbcdc0857f8beddd0edb204c828
[]
no_license
SeanBoocock/simd-optimized-software-triangle-rasterizer
4c68a57da8a99284977252fe9f0c110193290809
abdf88e6871135b3fa2d04a2fd14c96a6fa66b49
refs/heads/master
2021-01-10T15:36:18.363163
2011-10-14T19:39:34
2011-10-14T19:39:34
52,691,253
0
0
null
null
null
null
UTF-8
C++
false
false
264
h
#ifndef SIMPLE_ENGINE_H_ #define SIMPLE_ENGINE_H_ #include "Mesh.h" class Window; class SimpleEngine { public: SimpleEngine(); ~SimpleEngine(); void Initialize(); void Run(); void Finalize(); private: Window* win; Mesh m; }; #endif
[ [ [ 1, 22 ] ] ]
b0cb988ece50da38a297f2d9d710bd82bf3d45fc
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/iostreams/test/bzip2_test.cpp
aba8216bf202d38b74c17742248ab425543a835a
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,346
cpp
// (C) Copyright Jonathan Turkanis 2004 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.) // See http://www.boost.org/libs/iostreams for documentation. #include <string> #include <boost/iostreams/filter/bzip2.hpp> #include <boost/iostreams/filter/test.hpp> #include <boost/test/test_tools.hpp> #include <boost/test/unit_test.hpp> #include "detail/sequence.hpp" using namespace std; using namespace boost; using namespace boost::iostreams; using namespace boost::iostreams::test; using boost::unit_test::test_suite; struct bzip2_alloc : std::allocator<char> { }; void bzip2_test() { text_sequence data; BOOST_CHECK( test_filter_pair( bzip2_compressor(), bzip2_decompressor(), std::string(data.begin(), data.end()) ) ); BOOST_CHECK( test_filter_pair( basic_bzip2_compressor<bzip2_alloc>(), basic_bzip2_decompressor<bzip2_alloc>(), std::string(data.begin(), data.end()) ) ); } test_suite* init_unit_test_suite(int, char* []) { test_suite* test = BOOST_TEST_SUITE("bzip2 test"); test->add(BOOST_TEST_CASE(&bzip2_test)); return test; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 42 ] ] ]
aa116cf369a275354687881fc96c0e65e7bb8fde
8cb15b44b77d09454b598775f6b21ee823e3a731
/trunk/boost/sql/postgres/connection.hpp
d300f7fb813290d82826fc053b36adcd1c245f17
[ "BSL-1.0" ]
permissive
BackupTheBerlios/async-db-svn
a8215bd5e4e50fa21d2df106d4ad8478267b2bc5
0bf8bbd4a1114e6c3b3de6132fbab88a7849120d
refs/heads/master
2020-05-28T10:52:50.918170
2008-06-19T17:10:11
2008-06-19T17:10:11
40,441,314
0
0
null
null
null
null
UTF-8
C++
false
false
1,484
hpp
/************************************************************** * Copyright (c) 2008 Daniel Pfeifer * * * * Distributed under the Boost Software License, Version 1.0. * **************************************************************/ #ifndef BOOST_SQL_POSTGRES_CONNECTION_HPP #define BOOST_SQL_POSTGRES_CONNECTION_HPP #include <libpq-fe.h> #include <pg_config.h> #include <boost/shared_ptr.hpp> #include <stdexcept> namespace boost { namespace sql { namespace postgres { class connection { public: connection() : impl(0) { } ~connection() { PQfinish(impl); } void open(const char* conninfo) { impl = PQconnectdb(conninfo); if (PQstatus(impl) != CONNECTION_OK) { throw std::runtime_error(PQerrorMessage(impl)); } } unsigned long client_version() { return PG_VERSION_NUM; } unsigned long server_version() { return PQserverVersion(impl); } void execute(const std::string& cmd) { boost::shared_ptr<PGresult> res(PQexec(impl, cmd.c_str()), PQclear); if (PQresultStatus(res.get()) != PGRES_COMMAND_OK) { throw std::runtime_error(PQresultErrorMessage(res.get())); } } PGconn* implementation() const { return impl; } private: PGconn* impl; }; } // end namespace postgres } // end namespace sql } // end namespace boost #endif /*BOOST_SQL_POSTGRES_CONNECTION_HPP*/
[ "purplekarrot@56c89ae0-533d-0410-bf25-c904ecb77cb6" ]
[ [ [ 1, 75 ] ] ]
63b76b9547676609c4b28423bba673accdee0cb9
f991e120eba945efb040a25fc0cdaabf98562ee0
/trunk/west-chamber-windows/WestChamberWindows/WCWController/WCWController.cpp
d82d6c956ac9beedc6732800dcb97f7a5493f7c1
[]
no_license
enthus/scholarzhang0
d2ac2706ca1c48c549c66292b88a7c1c4ede1317
ca7bf237e7bb6a7ad8b825baf03e1cd7c8561046
refs/heads/master
2020-04-06T03:44:30.896618
2011-11-07T13:53:22
2011-11-07T13:53:22
558,715
2
2
null
null
null
null
GB18030
C++
false
false
1,159
cpp
// WCWController.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" enum FILTER_STATE { FILTER_STATE_NONE, FILTER_STATE_IPLOG, FILTER_STATE_ALL }; #define WEST_CHAMBER_FILTER_SET CTL_CODE(FILE_DEVICE_NETWORK,0,METHOD_BUFFERED,FILE_ANY_ACCESS) #define WEST_CHAMBER_FILTER_GET CTL_CODE(FILE_DEVICE_NETWORK,1,METHOD_BUFFERED,FILE_ANY_ACCESS) int _tmain(int argc, _TCHAR* argv[]) { printf("westchamber windows controller\n"); HANDLE handle = CreateFile(L"\\\\.\\WestChamber",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if(handle == INVALID_HANDLE_VALUE ) { printf("Cannot get device!\n"); return -1; } printf("Current status(%d=NONE,%d=IPLOG,%d=ALL) : ",FILTER_STATE_NONE,FILTER_STATE_IPLOG,FILTER_STATE_ALL); UINT status; DWORD recv; DeviceIoControl(handle,WEST_CHAMBER_FILTER_GET,NULL,0,&status,4,&recv,NULL); printf("%d\n",status); printf("New status="); ULONG nstatus; scanf("%d",&nstatus); DeviceIoControl(handle,WEST_CHAMBER_FILTER_SET,&nstatus,4,NULL,0,&recv,NULL); printf("...done\n"); CloseHandle(handle); return 0; }
[ "elysion51@dcf2ae5c-931b-11de-97c9-d5744c8abab9" ]
[ [ [ 1, 36 ] ] ]
51589b0582f11b718128a85de3d17d6b294c8c57
3ec3b97044e4e6a87125470cfa7eef535f26e376
/cltatman-mountain_valley/code/Include/back/ImageBank.hpp
29ca1f808427f6751e599d89e0fa2fe1eced1b26
[]
no_license
strategist922/TINS-Is-not-speedhack-2010
6d7a43ebb9ab3b24208b3a22cbcbb7452dae48af
718b9d037606f0dbd9eb6c0b0e021eeb38c011f9
refs/heads/master
2021-01-18T14:14:38.724957
2010-10-17T14:04:40
2010-10-17T14:04:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,756
hpp
#ifndef IMAGEBANK_HPP #define IMAGEBANK_HPP #include <string> #include <OpenLayer.hpp> /** @brief Manages image files. * * A singleton that keeps track of loaded image files. Supports bmp, tga, png. */ class ImageBank { public: /** @brief Returns the ImageBank instance. * * Returns a pointer to the static instance of ImageBank. If the * instance has not been created yet, it is created. */ static ImageBank* _(); /** @brief Loads an image from a file. * * @param filepath The path to the image file. * * @return True on a successful load, or if the file has already been * loaded. False otherwise. */ bool load( const std::string& filepath ); /** @brief Retrieves an image from the bank. * * Grabs an image from the bank. If the image is not found it is loaded. * If loading fails a yellow placeholder image is returned. * This operation has logarithmic speed, provided that the image has been * loaded. * * @return A pointer to the image, an ol::Bitmap. If the image cannot be * loaded, a yellow placeholder image is returned. */ ol::Bitmap* get( const std::string& filepath ); /** @brief Empties the image bank. * * You should obviously avoid doing this in the middle of a game loop. The * memory being used to hold the images is freed, and any graphics will * need to be reloaded. */ void flush(); void set( const std::string& name, ol::Bitmap* image ); private: ImageBank(); static ImageBank* instance; std::map< std::string, ol::Bitmap* > images; }; #endif
[ [ [ 1, 65 ] ] ]
cd6a71a3bb887ec450e1ff74964b4f848e09cc65
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/odephysics/nodetrimesh.cc
d4d49005fcbc1c4af2682998761d1bc892fce5c3
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,915
cc
#define N_IMPLEMENTS nOdeTriMesh //-------------------------------------------------------------------- // nodetrimesh.cc // // (c) 2003 Vadim Macagon // // nOdeTriMesh is licensed under the terms of the Nebula License. //-------------------------------------------------------------------- #include "kernel/nfileserver2.h" #include "odephysics/nodetrimesh.h" #include "mathlib/vector.h" #include "mathlib/triangle.h" #include "mathlib/line.h" #include "gfx/ngfxserver.h" #include "odephysics/nodeserver.h" #include "odephysics/nodetrimeshshape.h" //------------------------------------------------------------------------------ /** */ nOdeTriMesh::nOdeTriMesh( const char* id ) : nHashNode(id), refCount(0), numVertices(0), numFaces(0), vertexData(0), faceData(0), isLoaded(false), meshDataId(0) { this->odeServer = (nOdeServer*)nOdeServer::kernelServer-> Lookup( "/sys/servers/ode" ); n_assert( this->odeServer ); } //------------------------------------------------------------------------------ /** */ nOdeTriMesh::~nOdeTriMesh() { if ( this->meshDataId ) { dGeomTriMeshDataDestroy( this->meshDataId ); } if ( this->vertexData ) { n_free( this->vertexData ); this->vertexData = 0; } if ( this->faceData ) { n_free( this->faceData ); this->faceData = 0; } n_assert( 0 == this->refCount ); } //------------------------------------------------------------------------------ /** */ int nOdeTriMesh::AddRef() { return ++refCount; } //------------------------------------------------------------------------------ /** */ int nOdeTriMesh::RemRef() { n_assert( refCount > 0 ); return --refCount; } //------------------------------------------------------------------------------ /** */ int nOdeTriMesh::GetRef() { return refCount; } //------------------------------------------------------------------------------ /** */ bool nOdeTriMesh::IsLoaded() { return this->isLoaded; } //------------------------------------------------------------------------------ /** */ void nOdeTriMesh::Begin( int numVerts, int numTris ) { n_assert( !this->isLoaded ); n_assert( !this->vertexData ); n_assert( !this->faceData ); this->numVertices = numVerts; this->numFaces = numTris; this->vertexData = (float*) n_malloc(numVerts * 3 * sizeof(float)); this->faceData = (int*) n_malloc(numTris * 3 * sizeof(int)); } //------------------------------------------------------------------------------ /** */ void nOdeTriMesh::SetVertex( int index, vector3& v ) { n_assert( this->vertexData ); n_assert( (index >= 0) && (index < this->numVertices) ); float* ptr = this->vertexData + 3 * index; ptr[0] = v.x; ptr[1] = v.y; ptr[2] = v.z; } //------------------------------------------------------------------------------ /** */ void nOdeTriMesh::SetTriangle( int index, int p0Index, int p1Index, int p2Index ) { n_assert( this->faceData ); n_assert( (index >= 0) && (index < this->numFaces) ); n_assert( (p0Index >= 0) && (p0Index < this->numVertices) ); n_assert( (p1Index >= 0) && (p1Index < this->numVertices) ); n_assert( (p2Index >= 0) && (p2Index < this->numVertices) ); int* ptr = this->faceData + 3 * index; ptr[0] = p0Index; ptr[1] = p1Index; ptr[2] = p2Index; } //------------------------------------------------------------------------------ /** */ void nOdeTriMesh::End() { n_assert( (this->numVertices > 0) && (this->numFaces > 0) ); n_assert( this->faceData && this->vertexData ); n_assert( !this->meshDataId ); this->meshDataId = dGeomTriMeshDataCreate(); dGeomTriMeshDataBuildSingle( this->meshDataId, this->vertexData, sizeof(float) * 3, this->numVertices, this->faceData, this->numFaces * 3, sizeof(int) * 3 ); /* OPCODECREATE opcc; opcc.NbTris = this->numFaces; opcc.NbVerts = this->numVertices; opcc.Tris = (const unsigned int*) this->faceData; opcc.Verts = (const Point*) this->vertexData; opcc.Rules = SPLIT_COMPLETE | SPLIT_SPLATTERPOINTS; // ??? opcc.NoLeaf = false; // true; opcc.Quantized = false; // true; this->opcModel.Build( opcc ); */ n_assert( !this->isLoaded ); this->isLoaded = true; } //------------------------------------------------------------------------------ /** OPCODE uses a callback function to actually get triangle data for the collision test. */ /* void nOdeTriMesh::collCallback( udword triangleIndex, VertexPointers& triangle, udword userData ) { nOdeTriMesh* self = (nOdeTriMesh*)userData; int* indexPtr = &(self->faceData[3 * triangleIndex]); triangle.Vertex[0] = (Point*)&(self->vertexData[3 * indexPtr[0]]); triangle.Vertex[1] = (Point*)&(self->vertexData[3 * indexPtr[1]]); triangle.Vertex[2] = (Point*)&(self->vertexData[3 * indexPtr[2]]); } */ //------------------------------------------------------------------------------ /** @brief Obtain the AABB for the mesh. */ /* void nOdeTriMesh::ComputeAABB( const dMatrix3& R, const dVector3& P, dReal aabb[6] ) { const AABBCollisionTree* tree = (const AABBCollisionTree*)this->opcModel.GetTree(); const AABBCollisionNode* node = tree->GetNodes(); dReal xrange = dFabs( R[0] * node->mAABB.mExtents.x ) + dFabs( R[1] * node->mAABB.mExtents.y ) + dFabs( R[2] * node->mAABB.mExtents.z ); dReal yrange = dFabs( R[4] * node->mAABB.mExtents.x ) + dFabs( R[5] * node->mAABB.mExtents.y ) + dFabs( R[6] * node->mAABB.mExtents.z ); dReal zrange = dFabs( R[8] * node->mAABB.mExtents.x ) + dFabs( R[9] * node->mAABB.mExtents.y ) + dFabs( R[10] * node->mAABB.mExtents.z ); aabb[0] = P[0] - xrange; aabb[1] = P[0] + xrange; aabb[2] = P[1] - yrange; aabb[3] = P[1] + yrange; aabb[4] = P[2] - zrange; aabb[5] = P[2] + zrange; } */ //------------------------------------------------------------------------------ /** */ /* void nOdeTriMesh::GetAABB( dGeomID g, dReal aabb[6] ) { const dVector3& P = *(const dVector3*)dGeomGetPosition( g ); const dMatrix3& R = *(const dMatrix3*)dGeomGetRotation( g ); nOdeTriMeshShape* shape = (nOdeTriMeshShape*)dGeomGetData( g ); shape->GetTriMesh()->ComputeAABB( R, P, aabb ); } */ //------------------------------------------------------------------------------ /** */ /* int nOdeTriMesh::TestAABB( dGeomID g1, dGeomID g2, dReal aabb2[6] ) { // not used or necessary atm. return 1; //return ((nOdeCollideObject*)dGeomGetData( g1 ))->GetShape()->TestAABB( aabb2 ); } */ //------------------------------------------------------------------------------ /** */ bool nOdeTriMesh::Load( nFileServer2* fs, const char* fname ) { if ( strstr( fname, ".n3d" ) ) { return this->LoadN3D( fs, fname ); } else if ( strstr( fname, ".nvx" ) ) { return this->LoadNVX( fs, fname ); } else { n_printf( "nOdeTriMesh: Unknown file format '%s'\n", fname ); return false; } } //------------------------------------------------------------------------------ /** Render a AABBCollisionNode and recurse. */ /* void nOdeTriMesh::VisualizeAABBCollisionNode( nGfxServer* gs, const AABBCollisionNode* node ) { n_assert(gs && node); vector3 center( node->mAABB.mCenter.x, node->mAABB.mCenter.y, node->mAABB.mCenter.z ); vector3 extent( node->mAABB.mExtents.x, node->mAABB.mExtents.y, node->mAABB.mExtents.z ); vector3 v00(center.x - extent.x, center.y - extent.y, center.z - extent.z); vector3 v01(center.x - extent.x, center.y - extent.y, center.z + extent.z); vector3 v02(center.x + extent.x, center.y - extent.y, center.z + extent.z); vector3 v03(center.x + extent.x, center.y - extent.y, center.z - extent.z); vector3 v10(center.x - extent.x, center.y + extent.y, center.z - extent.z); vector3 v11(center.x - extent.x, center.y + extent.y, center.z + extent.z); vector3 v12(center.x + extent.x, center.y + extent.y, center.z + extent.z); vector3 v13(center.x + extent.x, center.y + extent.y, center.z - extent.z); // render ground rect gs->Coord(v00.x, v00.y, v00.z); gs->Coord(v01.x, v01.y, v01.z); gs->Coord(v01.x, v01.y, v01.z); gs->Coord(v02.x, v02.y, v02.z); gs->Coord(v02.x, v02.y, v02.z); gs->Coord(v03.x, v03.y, v03.z); gs->Coord(v03.x, v03.y, v03.z); gs->Coord(v00.x, v00.y, v00.z); // render top rect gs->Coord(v10.x, v10.y, v10.z); gs->Coord(v11.x, v11.y, v11.z); gs->Coord(v11.x, v11.y, v11.z); gs->Coord(v12.x, v12.y, v12.z); gs->Coord(v12.x, v12.y, v12.z); gs->Coord(v13.x, v13.y, v13.z); gs->Coord(v13.x, v13.y, v13.z); gs->Coord(v10.x, v10.y, v10.z); // render vertical lines gs->Coord(v00.x, v00.y, v00.z); gs->Coord(v10.x, v10.y, v10.z); gs->Coord(v01.x, v01.y, v01.z); gs->Coord(v11.x, v11.y, v11.z); gs->Coord(v02.x, v02.y, v02.z); gs->Coord(v12.x, v12.y, v12.z); gs->Coord(v03.x, v03.y, v03.z); gs->Coord(v13.x, v13.y, v13.z); if (!node->IsLeaf()) { const AABBCollisionNode* neg = node->GetNeg(); const AABBCollisionNode* pos = node->GetPos(); this->VisualizeAABBCollisionNode( gs, neg ); this->VisualizeAABBCollisionNode( gs, pos ); } } */ //------------------------------------------------------------------------------ /** Renders the collide model's triangle soup through the provided gfx server. */ void nOdeTriMesh::Visualize( nGfxServer* gs ) { n_assert( gs ); n_assert( this->vertexData && this->faceData ); // render the triangle soup gs->Begin( N_PTYPE_LINE_LIST ); int i; for ( i = 0; i < this->numFaces; i++ ) { int* indexPtr = this->faceData + 3 * i; float* v0 = this->vertexData + 3 * indexPtr[0]; float* v1 = this->vertexData + 3 * indexPtr[1]; float* v2 = this->vertexData + 3 * indexPtr[2]; gs->Coord(v0[0], v0[1], v0[2]); gs->Coord(v1[0], v1[1], v1[2]); gs->Coord(v1[0], v1[1], v1[2]); gs->Coord(v2[0], v2[1], v2[2]); gs->Coord(v2[0], v2[1], v2[2]); gs->Coord(v0[0], v0[1], v0[2]); } gs->End(); /* // render the AABB tree gs->Rgba(0.5f, 0.0f, 0.0f, 1.0f); gs->Begin(N_PTYPE_LINE_LIST); const AABBCollisionTree* tree = (const AABBCollisionTree*) this->opcModel.GetTree(); this->VisualizeAABBCollisionNode(gs, tree->GetNodes()); gs->End(); */ } //------------------------------------------------------------------------------ /** Load a geometry file in n3d format as collide shape. */ bool nOdeTriMesh::LoadN3D( nFileServer2* fileServer, const char* filename ) { n_assert( fileServer ); n_assert( filename ); // load wavefront file int numVertices; int numFaces; char line[1024]; nFile* file = fileServer->NewFileObject(); n_assert( file ); if ( !file->Open( filename, "r" ) ) { n_printf( "nOdeTriMesh::Load(): Could not open file '%s'!\n", filename ); return false; } // Pass1, count vertices and faces numVertices = 0; numFaces = 0; while ( file->GetS( line, sizeof(line) ) ) { char *kw = strtok( line, " \t\n" ); if ( kw ) { if ( strcmp( kw, "v" ) == 0 ) numVertices++; else if ( strcmp( kw, "f" ) == 0 ) numFaces++; } } // any errors? if ( 0 == numVertices ) { n_printf( "nOdeTriMesh::Load(): file '%s' has no vertices!\n", filename ); file->Close(); delete file; return false; } if ( 0 == numFaces ) { n_printf( "nOdeTriMesh::Load(): file '%s' has no triangles!\n", filename ); file->Close(); delete file; return false; } // read vertices, add triangles... this->Begin( numVertices, numFaces ); file->Seek( 0, nFile::START ); int actVertex = 0; int actFace = 0; vector3 vec3; while ( file->GetS( line, sizeof(line) ) ) { char *kw = strtok( line, " \t\n" ); if ( kw ) { if ( strcmp( kw, "v" ) == 0 ) { // a vertex definition char *xs = strtok( NULL, " \t\n" ); char *ys = strtok( NULL, " \t\n" ); char *zs = strtok( NULL, " \t\n" ); n_assert( xs && ys && zs ); float x = (float)atof( xs ); float y = (float)atof( ys ); float z = (float)atof( zs ); vec3.set( x, y, z ); this->SetVertex( actVertex++, vec3 ); } else if ( strcmp( kw, "f" ) == 0 ) { // a face definition only read first index in // corner definition, read only 3 corners, ignore all others ulong i; int indices[3]; for ( i = 0; i < 3; i++ ) { char *tmp = strtok( NULL, " \t\n" ); if ( tmp ) { char *slash; if ( (slash = strchr( tmp, '/' )) ) *slash = 0; int curIndex = atoi( tmp ) - 1; n_assert( curIndex < numVertices ); indices[i] = curIndex; } } // add the triangle to the geometry this->SetTriangle( actFace++, indices[0], indices[1], indices[2] ); } } } // finish adding geometry this->End(); file->Close(); delete file; return true; } //------------------------------------------------------------------------------ /** Reads a 32 bit int from file. FIXME: Endian correction! */ int nOdeTriMesh::readInt( nFile* file ) { n_assert( file ); int var; file->Read( &var, sizeof(var) ); return var; } //------------------------------------------------------------------------------ /** */ bool nOdeTriMesh::LoadNVX( nFileServer2* fileServer, const char* filename ) { n_assert( fileServer ); n_assert( filename ); // open file nFile* file = fileServer->NewFileObject(); n_assert( file ); if ( !file->Open( filename, "rb" ) ) { n_printf( "nOdeTriMesh::LoadNVX(): could not load file '%s'\n", filename ); return false; } // read header int magicNumber = this->readInt(file); if ( magicNumber != 'NVX1' ) { n_printf( "nOdeTriMesh::LoadNVX(): '%s' is not a NVX1 file!\n", filename ); file->Close(); delete file; return false; } int numVertices = this->readInt( file ); int numIndices = this->readInt( file ); int numWingedEdges = this->readInt( file ); nVertexType vertexType = (nVertexType)this->readInt( file ); int dataStart = this->readInt( file ); int dataSize = this->readInt( file ); // compute vertex stride n_assert( vertexType & N_VT_COORD ); int vertexStride = 3; if ( vertexType & N_VT_NORM ) { vertexStride += 3; } if ( vertexType & N_VT_RGBA ) { vertexStride += 1; } if ( vertexType & N_VT_UV0 ) { vertexStride += 2; } if ( vertexType & N_VT_UV1 ) { vertexStride += 2; } if ( vertexType & N_VT_UV2 ) { vertexStride += 2; } if ( vertexType & N_VT_UV3 ) { vertexStride += 2; } if ( vertexType & N_VT_JW ) { vertexStride += 6; } // read the complete data block into a memory buffer and close file char* buffer = (char*)n_malloc( dataSize ); file->Seek( dataStart, nFile::START ); int num = file->Read( buffer, dataSize ); file->Close(); delete file; file = 0; n_assert( num == dataSize ); // get pointer to beginning of vertices and to beginning of indices float* vertexData = (float*)buffer; int wingedEdgeStride = 2; ushort* indexData = (ushort*)(vertexData + (numVertices * vertexStride) + (numWingedEdges * wingedEdgeStride)); // iterate over triangle list and add triangles to collide shape int numTriangles = numIndices / 3; this->Begin( numVertices, numTriangles ); // add vertices vector3 vec3; int i; for ( i = 0; i < numVertices; i++ ) { float* vPtr = vertexData + (i * vertexStride); vec3.set( vPtr[0], vPtr[1], vPtr[2] ); this->SetVertex( i, vec3 ); } // add triangles for ( i = 0; i < numTriangles; i++ ) { int i0 = *indexData++; int i1 = *indexData++; int i2 = *indexData++; this->SetTriangle( i, i0, i1, i2 ); } this->End(); n_free( buffer ); return true; } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 573 ] ] ]
2d0a420af91aae68cf73e7049e5e56b4ee8396ba
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/UnitTests/UnitTest_TreeControl/TreeControl.cpp
c17da39b752901058bde8b5b2b3e7e1005ab4107
[]
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
WINDOWS-1251
C++
false
false
13,503
cpp
/*! @file @author Pavel Turin @date 08/2009 */ #include "precompiled.h" #include "TreeControl.h" #include "TreeControlItem.h" namespace MyGUI { TreeControl::Node::Node(TreeControl* pOwner) : GenericNode<Node, TreeControl>(pOwner), mbIsPrepared(false), mbIsExpanded(true), mstrImage("Folder") { } TreeControl::Node::Node(const UString& strText, Node* pParent) : GenericNode<Node, TreeControl>(strText, pParent), mbIsPrepared(false), mbIsExpanded(false), mstrImage("Folder") { } TreeControl::Node::Node(const UString& strText, const UString& strImage, Node* pParent) : GenericNode<Node, TreeControl>(strText, pParent), mbIsPrepared(false), mbIsExpanded(false), mstrImage(strImage) { } TreeControl::Node::~Node() { } void TreeControl::Node::prepare() { if (mbIsPrepared || !mpOwner) return; mpOwner->eventTreeNodePrepare(mpOwner, this); mbIsPrepared = true; } size_t TreeControl::Node::prepareChildren() { prepare(); size_t nResult = 0; for (VectorNodePtr::iterator Iterator = getChildren().begin(); Iterator != getChildren().end(); ++Iterator) { TreeControl::Node* pChild = *Iterator; nResult++; pChild->prepare(); if (pChild->isExpanded()) nResult += pChild->prepareChildren(); } return nResult; } void TreeControl::Node::setExpanded(bool bIsExpanded) { if (mbIsExpanded == bIsExpanded) return; mbIsExpanded = bIsExpanded; invalidate(); } void TreeControl::Node::setImage(const UString& strImage) { mstrImage = strImage; invalidate(); } TreeControl::TreeControl() : mpWidgetScroll(nullptr), mbScrollAlwaysVisible(true), mbInvalidated(false), mbRootVisible(false), mnItemHeight(1), mnScrollRange(-1), mnTopIndex(0), mnTopOffset(0), mnFocusIndex(ITEM_NONE), mpSelection(nullptr), mpRoot(nullptr), mnExpandedNodes(0), mnLevelOffset(0), mClient(nullptr) { } void TreeControl::initialiseOverride() { Base::initialiseOverride(); // FIXME перенесенно из конструктора, проверить смену скина mpRoot = new Node(this); //FIXME setNeedKeyFocus(true); assignWidget(mpWidgetScroll, "VScroll"); if (mpWidgetScroll != nullptr) { mpWidgetScroll->eventScrollChangePosition += newDelegate(this, &TreeControl::notifyScrollChangePosition); mpWidgetScroll->eventMouseButtonPressed += newDelegate(this, &TreeControl::notifyMousePressed); } assignWidget(mClient, "Client"); if (mClient != nullptr) { mClient->eventMouseButtonPressed += newDelegate(this, &TreeControl::notifyMousePressed); setWidgetClient(mClient); } MYGUI_ASSERT(nullptr != mpWidgetScroll, "Child VScroll not found in skin (TreeControl must have VScroll)"); MYGUI_ASSERT(nullptr != mClient, "Child Widget Client not found in skin (TreeControl must have Client)"); if (isUserString("SkinLine")) mstrSkinLine = getUserString("SkinLine"); if (isUserString("HeightLine")) mnItemHeight = utility::parseValue<int>(getUserString("HeightLine")); if (isUserString("LevelOffset")) mnLevelOffset = utility::parseValue<int>(getUserString("LevelOffset")); MYGUI_ASSERT(!mstrSkinLine.empty(), "SkinLine property not found (TreeControl must have SkinLine property)"); if (mnItemHeight < 1) mnItemHeight = 1; mpWidgetScroll->setScrollPage((size_t)mnItemHeight); mpWidgetScroll->setScrollViewPage((size_t)mnItemHeight); invalidate(); } void TreeControl::shutdownOverride() { mpWidgetScroll = nullptr; mClient = nullptr; // FIXME перенесенно из деструктора, проверить смену скина delete mpRoot; Base::shutdownOverride(); } void TreeControl::setRootVisible(bool bValue) { if (mbRootVisible == bValue) return; mbRootVisible = bValue; invalidate(); } void TreeControl::setSelection(Node* pSelection) { if (mpSelection == pSelection) return; mpSelection = pSelection; while (pSelection) { pSelection->setExpanded(true); pSelection = pSelection->getParent(); } invalidate(); eventTreeNodeSelected(this, mpSelection); } void TreeControl::onMouseWheel(int nValue) { notifyMouseWheel(nullptr, nValue); Widget::onMouseWheel(nValue); } void TreeControl::onKeyButtonPressed(KeyCode Key, Char Character) { // TODO Widget::onKeyButtonPressed(Key, Character); } void TreeControl::setSize(const IntSize& Size) { Widget::setSize(Size); invalidate(); } void TreeControl::setCoord(const IntCoord& Bounds) { Widget::setCoord(Bounds); invalidate(); } void TreeControl::notifyFrameEntered(float nTime) { if (!mbInvalidated) return; mnExpandedNodes = mpRoot->prepareChildren(); if (mbRootVisible) mnExpandedNodes++; updateScroll(); updateItems(); validate(); mbInvalidated = false; Gui::getInstance().eventFrameStart -= newDelegate(this, &TreeControl::notifyFrameEntered); } void TreeControl::updateScroll() { mnScrollRange = (mnItemHeight * (int)mnExpandedNodes) - mClient->getHeight(); if (!mbScrollAlwaysVisible || mnScrollRange <= 0 || mpWidgetScroll->getLeft() <= mClient->getLeft()) { if (mpWidgetScroll->getVisible()) { mpWidgetScroll->setVisible(false); mClient->setSize(mClient->getWidth() + mpWidgetScroll->getWidth(), mClient->getHeight()); } } else if (!mpWidgetScroll->getVisible()) { mClient->setSize(mClient->getWidth() - mpWidgetScroll->getWidth(), mClient->getHeight()); mpWidgetScroll->setVisible(true); } mpWidgetScroll->setScrollRange(mnScrollRange + 1); if (mnExpandedNodes) mpWidgetScroll->setTrackSize(mpWidgetScroll->getLineSize() * mClient->getHeight() / mnItemHeight / mnExpandedNodes); } void TreeControl::updateItems() { int nPosition = mnTopIndex * mnItemHeight + mnTopOffset; int nHeight = (int)mItemWidgets.size() * mnItemHeight - mnTopOffset; while ((nHeight <= (mClient->getHeight() + mnItemHeight)) && mItemWidgets.size() < mnExpandedNodes) { TreeControlItem* pItem = mClient->createWidget<TreeControlItem>( mstrSkinLine, 0, nHeight, mClient->getWidth(), mnItemHeight, Align::Top | Align::HStretch); pItem->eventMouseButtonPressed += newDelegate(this, &TreeControl::notifyMousePressed); pItem->eventMouseButtonDoubleClick += newDelegate(this, &TreeControl::notifyMouseDoubleClick); pItem->eventMouseWheel += newDelegate(this, &TreeControl::notifyMouseWheel); pItem->eventMouseSetFocus += newDelegate(this, &TreeControl::notifyMouseSetFocus); pItem->eventMouseLostFocus += newDelegate(this, &TreeControl::notifyMouseLostFocus); pItem->_setInternalData((size_t)mItemWidgets.size()); pItem->getButtonExpandCollapse()->eventMouseButtonClick += newDelegate(this, &TreeControl::notifyExpandCollapse); mItemWidgets.push_back(pItem); nHeight += mnItemHeight; }; if (nPosition >= mnScrollRange) { if (mnScrollRange <= 0) { if (nPosition || mnTopOffset || mnTopIndex) { nPosition = 0; mnTopIndex = 0; mnTopOffset = 0; } } else { int nCount = mClient->getHeight() / mnItemHeight; mnTopOffset = mnItemHeight - (mClient->getHeight() % mnItemHeight); if (mnTopOffset == mnItemHeight) { mnTopOffset = 0; nCount--; } mnTopIndex = ((int)mnExpandedNodes) - nCount - 1; nPosition = mnTopIndex * mnItemHeight + mnTopOffset; } } mpWidgetScroll->setScrollPosition(nPosition); } void TreeControl::validate() { typedef std::pair<VectorNodePtr::iterator, VectorNodePtr::iterator> PairNodeEnumeration; typedef std::list<PairNodeEnumeration> ListNodeEnumeration; ListNodeEnumeration EnumerationStack; PairNodeEnumeration Enumeration; VectorNodePtr vectorNodePtr; if (mbRootVisible) { vectorNodePtr.push_back(mpRoot); Enumeration = PairNodeEnumeration(vectorNodePtr.begin(), vectorNodePtr.end()); } else Enumeration = PairNodeEnumeration(mpRoot->getChildren().begin(), mpRoot->getChildren().end()); size_t nLevel = 0; size_t nIndex = 0; size_t nItem = 0; int nOffset = 0 - mnTopOffset; while (true) { if (Enumeration.first == Enumeration.second) { if (EnumerationStack.empty()) break; Enumeration = EnumerationStack.back(); EnumerationStack.pop_back(); nLevel--; continue; } Node* pNode = *Enumeration.first; Enumeration.first++; if (nIndex >= (size_t)mnTopIndex) { // FIXME проверка вставлена так как падает индекс айтема больше чем всего айтемов if (nItem >= mItemWidgets.size()) break; if (nIndex >= mnExpandedNodes || mItemWidgets[nItem]->getTop() > mClient->getHeight()) break; TreeControlItem* pItem = mItemWidgets[nItem]; pItem->setVisible(true); pItem->setCaption(pNode->getText()); pItem->setPosition(IntPoint(nLevel * mnLevelOffset, nOffset)); pItem->setStateSelected(pNode == mpSelection); pItem->setUserData(pNode); Button* pButtonExpandCollapse = pItem->getButtonExpandCollapse(); pButtonExpandCollapse->setVisible(pNode->hasChildren()); pButtonExpandCollapse->setStateSelected(!pNode->isExpanded()); StaticImage* pIcon = pItem->getIcon(); if (pIcon) { ResourceImageSetPtr pIconResource = pIcon->getItemResource(); if (pIconResource) { UString strIconType(pNode->isExpanded() ? "Expanded" : "Collapsed"); ImageIndexInfo IconInfo = pIconResource->getIndexInfo(pNode->getImage(), strIconType); if (IconInfo.size.empty()) pIcon->setItemResourceInfo(pIconResource->getIndexInfo(pNode->getImage(), "Common")); else pIcon->setItemResourceInfo(IconInfo); } } nOffset += mnItemHeight; nItem++; } nIndex++; if (pNode->hasChildren() && pNode->isExpanded()) { EnumerationStack.push_back(Enumeration); Enumeration.first = pNode->getChildren().begin(); Enumeration.second = pNode->getChildren().end(); nLevel++; } } if (nItem < mItemWidgets.size()) { for (; nItem < mItemWidgets.size(); ++nItem) { mItemWidgets[nItem]->setStateSelected(false); mItemWidgets[nItem]->setVisible(false); } } } void TreeControl::invalidate() { if (mbInvalidated) return; Gui::getInstance().eventFrameStart += newDelegate(this, &TreeControl::notifyFrameEntered); mbInvalidated = true; } void TreeControl::scrollTo(size_t nPosition) { mnTopOffset = ((int)nPosition % mnItemHeight); mnTopIndex = ((int)nPosition / mnItemHeight); invalidate(); } void TreeControl::sendScrollingEvents(size_t nPosition) { eventTreeScrolled(this, nPosition); if (mnFocusIndex != ITEM_NONE) eventTreeNodeMouseSetFocus(this, mItemWidgets[mnFocusIndex]->getNode()); } void TreeControl::notifyMousePressed(Widget* pSender, int nLeft, int nTop, MouseButton nID) { if ((nID == MouseButton::Left || nID == MouseButton::Right) && pSender != mpWidgetScroll) { Node* pSelection = mpSelection; if (pSender == mClient) pSelection = nullptr; else if (pSender->getVisible()) pSelection = *pSender->getUserData<Node*>(); setSelection(pSelection); if (nID == MouseButton::Right) eventTreeNodeContextMenu(this, mpSelection); } } void TreeControl::notifyMouseWheel(Widget* pSender, int nValue) { if (mnScrollRange <= 0) return; int nPosition = (int)mpWidgetScroll->getScrollPosition(); if (nValue < 0) nPosition += mnItemHeight; else nPosition -= mnItemHeight; if (nPosition >= mnScrollRange) nPosition = mnScrollRange; else if (nPosition < 0) nPosition = 0; if ((int)mpWidgetScroll->getScrollPosition() == nPosition) return; mpWidgetScroll->setScrollPosition(nPosition); scrollTo(nPosition); sendScrollingEvents(nPosition); } void TreeControl::notifyMouseDoubleClick(Widget* pSender) { if (mpSelection) eventTreeNodeActivated(this, mpSelection); } void TreeControl::notifyMouseSetFocus(Widget* pSender, Widget* pPreviousWidget) { mnFocusIndex = *pSender->_getInternalData<size_t>(); eventTreeNodeMouseSetFocus(this, mItemWidgets[mnFocusIndex]->getNode()); } void TreeControl::notifyMouseLostFocus(Widget* pSender, Widget* pNextWidget) { if (!pNextWidget || (pNextWidget->getParent() != mClient)) { mnFocusIndex = ITEM_NONE; eventTreeNodeMouseLostFocus(this, nullptr); } } void TreeControl::notifyScrollChangePosition(VScroll* pSender, size_t nPosition) { scrollTo(nPosition); sendScrollingEvents(nPosition); } void TreeControl::notifyExpandCollapse(Widget* pSender) { TreeControlItem* pItem = pSender->getParent()->castType<TreeControlItem>(false); if (!pItem) return; Node* pNode = pItem->getNode(); pNode->setExpanded(!pNode->isExpanded()); if (!pNode->isExpanded() && mpSelection && mpSelection->hasAncestor(pNode)) { mpSelection = pNode; eventTreeNodeSelected(this, mpSelection); } invalidate(); } }
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 518 ] ] ]
4bb9d97cc2e14cf64a370899e89a2722adcff9fd
184455acbcc5ee6b2ee0c77c66b436375e1171e9
/src/Music.h
fa6d67aca0d1096329a1502fd1be521211a1374e
[]
no_license
Karkasos/Core512
d996d40e57be899e6c4c9aec106e371356152b36
b83151ab284b7cf2e058fdd218dcc676946f43aa
refs/heads/master
2020-04-07T14:19:51.907224
2011-11-01T06:46:20
2011-11-01T06:46:20
2,753,621
0
0
null
null
null
null
UTF-8
C++
false
false
109
h
#pragma once class Music { HSTREAM hStream; public: Music(); ~Music(); void Play(); };
[ [ [ 1, 13 ] ] ]
217fe0f79859cd7559d3eba0c194b4b0a55bd739
19918873906ee31c789140d964900c01d961197a
/hw6_sortMerge11/include/heapfile.h
48fe8c07b53dea5ad44ec58938616844e7ed637f
[]
no_license
b97068/DBMS_hw6
1a043d6cae69ca9b631e5031bccc8f4872d039ff
1921dcf7365f0dec5416bd9a913baa8dd21226e6
refs/heads/master
2021-01-16T18:45:35.933280
2011-12-27T09:01:30
2011-12-27T09:01:30
3,055,418
1
1
null
null
null
null
UTF-8
C++
false
false
3,088
h
/* * class HeapFile * $Id: heapfile.h,v 1.1 1997/01/02 12:46:39 flisakow Exp $ */ #ifndef _HEAPFILE_H #define _HEAPFILE_H #include "minirel.h" #include "page.h" // This heapfile implementation is directory-based. We maintain a // directory of info about the data pages (which are of type HFPage // when loaded into memory). The directory itself is also composed // of HFPages, with each record being of type DataPageInfo // as defined below. // // The first directory page is a header page for the entire database // (it is the one to which our filename is mapped by the DB). // All directory pages are in a doubly-linked list of pages, each // directory entry points to a single data page, which contains // the actual records. // // The heapfile data pages are implemented as slotted pages, with // the slots at the front and the records in the back, both growing // into the free space in the middle of the page. // See the file 'hfpage.h' for specifics on the page implementation. // // We can store roughly pagesize/sizeof(DataPageInfo) records per // directory page; for any given HeapFile insertion, it is likely // that at least one of those referenced data pages will have // enough free space to satisfy the request. // Error codes for HEAPFILE. enum heapErrCodes { BAD_RID, BAD_REC_PTR, HFILE_EOF, INVALID_UPDATE, NO_SPACE, NO_RECORDS, END_OF_PAGE, INVALID_SLOTNO, ALREADY_DELETED, }; // DataPageInfo: the type of records stored on a directory page: struct DataPageInfo { PageId pageId; char filler[4]; //int availspace; // HFPage returns int for avail space, so we use int here //int recct; // for efficient implementation of getRecCnt() //PageId pageId; // obvious: id of this particular data page (a HFPage) }; class HFPage; class HeapFile { public: // Initialize. A null name produces a temporary heapfile which will be // deleted by the destructor. If the name already denotes a file, the // file is opened; otherwise, a new empty file is created. HeapFile( const char *name, Status& returnStatus ); ~HeapFile(); // return number of records in file int getRecCnt(); // insert record into file Status insertRecord(char *recPtr, int recLen, RID& outRid); // delete record from file Status deleteRecord(const RID& rid); // updates the specified record in the heapfile. Status updateRecord(const RID& rid, char *recPtr, int reclen); // read record from file, returning pointer and length Status getRecord(const RID& rid, char *recPtr, int& recLen); // initiate a sequential scan class Scan *openScan(Status& status); // delete the file from the database Status deleteFile(); private: friend class Scan; enum Filetype { TEMP, ORDINARY }; PageId _firstPageId; // page number of header page Filetype _ftype; bool _file_deleted; char *_fileName; }; #endif // _HEAPFILE_H
[ [ [ 1, 107 ] ] ]
715279fc7512bebb039623175630159bbb57330b
26a3a3d5f909da240cf1953a6e740f91cec72767
/PhotoEffects/ImageEffect/ImageEffect.cpp
f85becc48d5b46a388fc2c95ccc7ba774e87f2e9
[]
no_license
leejungho2/xynotecgui
4952229017a2b7d6464dc8be2dd5a119e4596018
c37421aa0769d39a024c6d3a25cb75e70d47efea
refs/heads/master
2020-05-30T14:34:20.263390
2011-10-10T09:28:24
2011-10-10T09:28:24
38,726,453
0
0
null
null
null
null
UTF-8
C++
false
false
10,797
cpp
// This is the main DLL file. #include "stdafx.h" #include "ImageEffect.h" ImageEffect::ApplyBasicEffect::ApplyBasicEffect(System::Drawing::Bitmap^ img) { if (img) { mImg = img; imgWidth = mImg->Width; imgHeight = mImg->Height; } } void ImageEffect::ApplyBasicEffect::SetImage(System::Drawing::Bitmap^ img) { if (img) { mImg = img; imgWidth = mImg->Width; imgHeight = mImg->Height; } } void ImageEffect::ApplyBasicEffect::ApplyColorFilter(Color_Filter filter) { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; ColorFilter(data, imgWidth, imgHeight, (COLOR_FILTER)filter); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyGamma(double red, double green, double blue) { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Gamma(data, imgWidth, imgHeight, red, green, blue); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyBrightness(int brightness) { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Brightness(data, imgWidth, imgHeight, brightness); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyContrast(double contrast) { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Contrast(data, imgWidth, imgHeight, contrast); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyGrayscale() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Grayscale(data, imgWidth, imgHeight); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyInvert() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; //Invert(data, imgWidth, imgHeight); Vignette(data, imgWidth, imgHeight); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplySmooth() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Smooth(data, imgWidth, imgHeight, 1); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyGaussianBlur() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; GaussianBlur(data, imgWidth, imgHeight, 4); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyMeanRemoval() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; MeanRemoval(data, imgWidth, imgHeight, 9); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplySharpen() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Sharpen(data, imgWidth, imgHeight, 11); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyEmbossLaplacian() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; EmbossLaplacian(data, imgWidth, imgHeight); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyEdgeDetectQuick() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; EdgeDetectQuick(data, imgWidth, imgHeight); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyFlip() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Flip(data, imgWidth, imgHeight, true, true); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyRandomJitter() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; RandomJitter(data, imgWidth, imgHeight, 5); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplySwirl() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Swirl(data, imgWidth, imgHeight, .04, false); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplySphere() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Sphere(data, imgWidth, imgHeight, false); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyTimeWarp() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; TimeWarp(data, imgWidth, imgHeight, 15, false); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyMoire() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Moire(data, imgWidth, imgHeight, 3); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyWater() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Water(data, imgWidth, imgHeight, 15, false); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyPixelate() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; Pixelate(data, imgWidth, imgHeight, 15, false); mImg->UnlockBits(bmData); } void ImageEffect::ApplyBasicEffect::ApplyFishEye() { System::Drawing::Rectangle mRect(0, 0, imgWidth, imgHeight); System::Drawing::Imaging::BitmapData^ bmData = mImg->LockBits(mRect, System::Drawing::Imaging::ImageLockMode::ReadWrite, System::Drawing::Imaging::PixelFormat::Format32bppArgb); System::IntPtr Scan0 = bmData->Scan0; BMP_ARGB *data = (BMP_ARGB *)(void *)Scan0; FishEye(data, imgWidth, imgHeight, 0.03, false, false); mImg->UnlockBits(bmData); }
[ [ [ 1, 348 ] ] ]
aa2600a99f9874ff989ee76e5cd98fce5dea565d
6d25f0b33ccaadd65b35f77c442b80097a2fce8e
/gbt/gbtree.cpp
36301a309dac25b4e7e7b67cbe0467fff4758c41
[]
no_license
zhongyunuestc/felix-academic-project
8b282d3a783aa48a6b56ff6ca73dc967f13fd6cf
cc71c44fba50a5936b79f7d75b5112d247af17fe
refs/heads/master
2021-01-24T10:28:38.604955
2010-03-20T08:33:59
2010-03-20T08:33:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,707
cpp
#include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <cmath> #include <limits> #include <rank_common.h> #include <rank_gbtree.h> #include <tree.h> #include <cart.h> using namespace std; /* struct GBTree { TreeVec treeVec; double learningRate; doubles_t w; int nDims; void train(const Dataset& trainset, int nDims, const Dataset& testset, const Dataset& valset, const MartParam& martParam); void test(const Dataset& ds, doubles_t& res) const; double getLoss(const Dataset& ds, const doubles_t& res) const; void save(const string& fn) const; void load(const string& fn); }; */ Dataset trainset, testset, valset; string trainfn, testfn, modelfn, valfn, trainfn2, resfn; MartParam martParam; int task; GBTree model; Metric* m=NULL; int parseArgs(int argc, char* argv[]) { if(strcmp(argv[1], "-t")==0) { task = 1; testfn = argv[2]; modelfn = argv[3]; resfn = argv[4]; if(argc>=6) valfn = argv[5]; return 0; } if(strcmp(argv[1], "-a")==0) { task = 2; modelfn = argv[2]; return 0; } trainfn = argv[1]; modelfn = argv[2]; martParam.learningRate = 0.01; martParam.nIters = 400; martParam.samplePrec = 0.4; martParam.cartParam.nLeafNodes = 20; martParam.cartParam.minNode = 5; martParam.cartParam.maxDepth = 10; martParam.cartParam.sample = 1.0; martParam.cartParam.splitRate = 0.1; string metric; for(int i=3;i<argc;i++) { if(strcmp("-lr", argv[i])==0) { assert(from_string<double>(martParam.learningRate, argv[++i])); continue; } if(strcmp("-iter", argv[i])==0) { assert(from_string<int>(martParam.nIters, argv[++i])); continue; } if(strcmp("-sample", argv[i])==0) { assert(from_string<double>(martParam.samplePrec, argv[++i])); continue; } if(strcmp("-size", argv[i])==0) { assert(from_string<int>(martParam.cartParam.nLeafNodes, argv[++i])); continue; } if(strcmp("-sr", argv[i])==0) { assert(from_string<double>(martParam.cartParam.splitRate, argv[++i])); continue; } if(strcmp("-depth", argv[i])==0) { assert(from_string<int>(martParam.cartParam.maxDepth, argv[++i])); continue; } if(strcmp("-minNode", argv[i])==0) { assert(from_string<int>(martParam.cartParam.minNode, argv[++i])); continue; } if(strcmp("-csample", argv[i])==0) { assert(from_string<double>(martParam.cartParam.sample, argv[++i])); continue; } if(strcmp("-train2", argv[i])==0) { trainfn2 = argv[++i]; continue; } if(strcmp("-t", argv[i])==0) { testfn = argv[++i]; continue; } if(strcmp("-v", argv[i])==0) { valfn = argv[++i]; continue; } if(strcmp("-metric", argv[i])==0) { metric = argv[++i]; continue; } cout << "Unknow Param: " << argv[i] << endl; return -1; } if(metric.compare("dcg")==0) { m = new DcgMetric<GalaxyGain, GalaxyDiscount>(5); } else if(metric.compare("ndcg")==0) { m = new NdcgMetric<>(5); } else { m = new MSError(); } return 0; } int main(int argc, char* argv[]) { if(parseArgs(argc, argv)!=0) { return -1; } if(task==1) { // test model.load(modelfn); int nDims = loadDataset(testfn, testset); if(nDims<0) { cout << "Error Read testing data: " << testfn << endl; return -1; } cout << "Test Dimension:\t" << nDims << endl; if(!valfn.empty()) { int td = loadDataset(valfn, valset); if(td<0) { cout << "Error Read testing data: " << valfn << endl; return -1; } assert(nDims==td); } doubles_t ty(testset.size(), model.b), vy(valset.size(), model.b); doubles_t ndcgT, ndcgV, precT, precV, bestndcg, bestprec; double mapT, mapV, bestmap = -numeric_limits<double>::max(), bestV = -numeric_limits<double>::max(); doubles_t tres, tvres; for(size_t iter=0;iter<model.treeVec.size();iter++) { for(size_t i=0;i<testset.size();i++) { double yhat = apply_cart(testset[i].x, model.treeVec[iter]); ty[i] += model.learningRate*model.w[iter]*yhat; } for(size_t i=0;i<valset.size();i++) { double yhat = apply_cart(valset[i].x, model.treeVec[iter]); vy[i] += model.learningRate*model.w[iter]*yhat; } if(iter%10==0) { cout << "Iter = " << iter; cal_metric(testset, ty, ndcgT, precT, mapT); cout << " TLoss = " << model.getLoss(testset, ty) << " TNDCG5 = " << ndcgT[4] << endl; if(!valset.empty()) { cal_metric(valset, vy, ndcgV, precV, mapV); if(iter>100 && dcmp(bestV-ndcgV[4])<0) { bestV = ndcgV[4]; bestndcg = ndcgT; bestprec = precT; bestmap = mapT; } } else { if(iter>100&& dcmp(bestV-ndcgT[4])<0) { bestV = ndcgT[4]; bestndcg = ndcgT; bestprec = precT; bestmap = mapT; } } } } cout << endl; cout << "Precision:"; for(size_t i=0;i<bestprec.size();i++) cout << "\t" << bestprec[i]; cout << endl; cout << "MAP:\t" << bestmap << endl; cout << "NDCG:"; for(size_t i=0;i<bestndcg.size();i++) cout << "\t" << bestndcg[i]; cout << endl; ofstream f(resfn.c_str()); for(size_t i=0;i<ty.size();i++) f << ty[i] << endl; f.close(); return 0; } if(task==2) { // model analysis model.load(modelfn); doubles_t d(model.nDims); for(size_t i=0;i<model.treeVec.size();i++) { for(int fid=0;fid<model.nDims;fid++) { d[fid] += cal_dependent(model.treeVec[i], fid); } if(i%10==0) { for(size_t j=0;j<d.size();j++) cout << '\t' << d[j]/(i+1); cout << endl; } } return 0; } int nDims = loadDataset(trainfn, trainset); if(nDims<=0) { cout << "Error Reading training data:" << trainfn << endl; return -1; } if(!trainfn2.empty()) { Dataset trainset2; int td = loadDataset(trainfn2, trainset2); if(td<0) { cout << "Error Read train2 data: " << trainfn2 << endl; return -1; } cout << "Train2 Dimension:\t" << td << endl; // trainset.push_back(trainset2.begin(), trainset2.end()); for(Dataset::const_iterator it=trainset2.begin();it!=trainset2.end();it++) { trainset.push_back(*it); } } cout << "Dimension:\t" << nDims << endl; if(!testfn.empty()) { int td = loadDataset(testfn, testset); if(td<0) { cout << "Error Read testing data: " << testfn << endl; return -1; } cout << "Test Dimension:\t" << td << endl; assert(nDims==td); } if(!valfn.empty()) { int td = loadDataset(valfn, valset); if(td<0) { cout << "Error Read testing data: " << valfn << endl; return -1; } assert(nDims==td); } for(Dataset::iterator it=trainset.begin();it!=trainset.end();it++) it->x.resize(nDims); for(Dataset::iterator it=testset.begin();it!=testset.end();it++) it->x.resize(nDims); for(Dataset::iterator it=valset.begin();it!=valset.end();it++) it->x.resize(nDims); sort(trainset.begin(), trainset.end()); sort(testset.begin(), testset.end()); sort(valset.begin(), valset.end()); model.train(trainset, nDims, testset, valset, martParam, m); model.save(modelfn); if(!m) delete m; return 0; }
[ "Felix.Guozq@fe1a0076-fbb2-11de-b7cb-b1160b2c2156" ]
[ [ [ 1, 267 ] ] ]
3ba109244148b2989aebf2f874776596298a803e
8a88075abf60e213a490840bebee97df01b8827a
/implementation/geometry/include/geometry/direction_concept.hpp
97a940591bcfef0a01d7c155f28b86f05ded1624
[]
no_license
DavidGeorge528/minigeolib
e078f1bbc874c09584ae48e1c269f5f90789ebfb
58233609203953acf1c0346cd48950d2212b8922
refs/heads/master
2020-05-20T09:36:53.921996
2009-04-23T16:25:30
2009-04-23T16:25:30
33,925,133
0
1
null
null
null
null
UTF-8
C++
false
false
1,148
hpp
#ifndef GEOMETRY_DIRECTION_CONCEPT_HPP #define GEOMETRY_DIRECTION_CONCEPT_HPP #include "geometry/geometric_object_concept.hpp" #include "geometry/impl/enablers.hpp" #include <boost/concept/usage.hpp> namespace geometry { struct direction_tag {}; template< typename D> class Direction: public GeometricObject< D, direction_tag> { public: BOOST_CONCEPT_USAGE( Direction) { } }; template< typename D> class Direction3D: public Direction<D> { public: BOOST_CONCEPT_USAGE( Direction3D) { unit_type dx = d_.dx(); unit_type dy = d_.dy(); unit_type dz = d_.dz(); } private: D d_; }; template< typename D> class Direction2D: public Direction<D> { public: BOOST_CONCEPT_USAGE( Direction2D) { unit_type dx = d_.dx(); unit_type dy = d_.dy(); } private: D d_; }; namespace impl { template< typename Dir, unsigned D> struct is_direction { BOOST_STATIC_CONSTANT( bool, value = (is_a< Dir, direction_tag>::value && has_dimensions< typename Dir::coord_system, D>::value)); }; } // namespace impl } // geometry #endif // GEOMETRY_DIRECTION_CONCEPT_HPP
[ "cpitis@834bb202-e8be-11dd-9d8c-a70aa0a93a20" ]
[ [ [ 1, 69 ] ] ]
25c049a52ab7cb33ffe85a2bc5c25d6fca7d4b60
51ebb9684ac1a4b65a5426e5c9ee79ebf8eb3db8
/Windows/CmmHdr/StdString.h
0b25ee7cdb73c745da15b2935d2f685279602457
[]
no_license
buf1024/lgcbasic
d4dfe6a6bd19e4e4ac0e5ac2b7a0590e04dd5779
11db32c9be46d9ac0740429e09ebf880a7a00299
refs/heads/master
2021-01-10T12:55:12.046835
2011-09-03T15:45:57
2011-09-03T15:45:57
49,615,513
0
0
null
null
null
null
UTF-8
C++
false
false
8,443
h
//////////////////////////////////////////////////////////////////////////////////////// // // LGCUI -- Personal Windowless UI Library Project // // FileName : StdString.h // Purpose : Extend string functionality // The reason why some paramters don't use reference is simple becase we // Sometimes need convenience to convert when pass pointer string. // Version : 2011-05-09 (21:16) 1.0 Created // 2011-05-29 (17:47) 1.1 Privode two versions, char and wchat_t // Author : heidong // Contact : [email protected] // Copyright(c): HEIDONG //////////////////////////////////////////////////////////////////////////////////////// /** @file StdString.h */ #pragma once #include <stdlib.h> #include <string> #include <list> #include <CmmWinHdr.h> #if _UNICODE #define StdString std::wstring #define StdChar wchar_t #else #define StdString std::string #define StdChar char #endif //extend string service /** * Convert an ANSI string to ANSI string * @return the ANSI string */ inline std::string GetAnsiString(const std::string strValue) { return strValue; } /** * Convert a wide string to ANSI string * @return the ANSI string */ inline std::string GetAnsiString(const std::wstring strValue) { if (strValue.empty()) { return ""; } int nLen = (strValue.length() + 1)*2; //int nLen = strValue.length() + 1; char* pszBuf = new char[nLen]; //We don't use C Runtime convert function here ::WideCharToMultiByte(CP_ACP, 0L, strValue.c_str(), -1, pszBuf, nLen, NULL, NULL); //wcstombs(pszBuf, strValue.c_str(), nLen); std::string strRet = pszBuf; delete[] pszBuf; return strRet; } /** * Convert a wide string to wide string * @return the wide string */ inline std::wstring GetWideString(const std::wstring strValue) { return strValue; } /** * Convert a ANSI string to wide string * @return the wide string */ inline std::wstring GetWideString(const std::string strValue) { if (strValue.empty()) { return L""; } int nLen = strValue.length() + 1; wchar_t* pszBuf = new wchar_t[nLen]; //We don't use C Runtime convert function here ::MultiByteToWideChar(CP_ACP, 0L, strValue.c_str(), -1, pszBuf, nLen); //mbstowcs(pszBuf, strValue.c_str(), nLen); std::wstring strRet = pszBuf; delete[] pszBuf; return strRet; } /** * Convert a ANSI string to std string * @return the std string */ inline StdString GetStdString(std::string strValue) { #if _UNICODE return GetWideString(strValue); #else return strValue; #endif } /** * Convert a wide string to std string * @return the std string */ inline StdString GetStdString(const std::wstring strValue) { #if _UNICODE return strValue; #else return GetAnsiString(strValue); #endif } /** * @see GetCStyleStdString */ inline const char* GetCStyleAnsiString(const std::string strValue, char* pBuf) { //std::string strVal = GetAnsiString(strValue); std::string strVal = strValue; int nLen = strVal.length() + 1; memcpy(pBuf, strVal.c_str(), nLen); return pBuf; } /** * @see GetCStyleStdString */ inline const char* GetCStyleAnsiString(const std::wstring strValue, char* pBuf) { return GetCStyleAnsiString( GetAnsiString(strValue), pBuf); } /** * @see GetCStyleStdString */ inline const wchar_t* GetCStyleWideString(const std::wstring strValue, wchar_t* pBuf) { std::wstring strVal = strValue; int nLen = (strVal.length() + 1)*sizeof(wchar_t); memcpy(pBuf, strVal.c_str(), nLen); return pBuf; } /** * @see GetCStyleStdString */ inline const wchar_t* GetCStyleWideString(const std::string strValue, wchar_t* pBuf) { return GetCStyleWideString( GetWideString(strValue), pBuf); } /** * @see GetCStyleStdString */ inline const StdChar* GetCStyleStdString(const std::string strValue, StdChar* pBuf) { #if _UNICODE return GetCStyleWideString(strValue, pBuf); #else return GetCStyleAnsiString(strValue, pBuf); #endif } /** * Get the C style string * @param strValue the string * @param pBuf the buffer to hold the value * @return the C style string */ inline const StdChar* GetCStyleStdString(const std::wstring strValue, StdChar* pBuf) { #if _UNICODE return GetCStyleWideString(strValue, pBuf); #else return GetCStyleAnsiString(strValue, pBuf); #endif } /** * Split a given string into group * @param strValue the string that will be handled * @param strDelim the delimiter * @param rgpRet the result that return * @return the count of the split result */ template<typename T> int Split(T& strValue, const T& strDelim, std::list<T>& rgpRet) { rgpRet.clear(); if (strDelim.empty()) { return -1; } size_t nStartPos = 0; size_t nIdx = strValue.find_first_of(strDelim); while(nIdx != T::npos) { T strSub = strValue.substr(nStartPos, nIdx - nStartPos); if (!strSub.empty()) { rgpRet.push_back(strSub); } nStartPos = nIdx + 1; nIdx = strValue.find_first_of(strDelim, nStartPos); } if (nStartPos < strValue.length()) { rgpRet.push_back(strValue.substr(nStartPos)); } return rgpRet.size(); } /** * Trim the left of a given string * @param strValue the string that will be handled * @param strDelim the delimiter * @return the trimmed result * @see TrimRight * @see Trim */ template<typename T> T TrimLeft(T& strValue, const T& strDelim) { const T::traits_type::_Elem* pData = strValue.c_str(); size_t nStart = 0; for(size_t i=0; i<strValue.length(); i++) { if (strDelim.find(pData[i]) != T::npos) { nStart++; } else { break; } } return pData + nStart; } /** * Trim the right of a given string * @param strValue the string that will be handled * @param strDelim the delimiter * @return the trimmed result * @see TrimLeft * @see Trim */ template<typename T> T TrimRight(T& strValue, const T& strDelim) { const T::traits_type::_Elem* pData = strValue.c_str(); size_t nEnd = strValue.length(); for(size_t i=nEnd-1; i>=0; i--) { if (strDelim.find(pData[i]) != T::npos) { nEnd--; } else { break; } } return strValue.substr(0, nEnd); } /** * Trim the given string * @param strValue the string that will be handled * @param strDelim the delimiter * @return the trimmed result * @see TrimLeft * @see TrimRight */ template<typename T> inline T Trim(T& strValue, const T& strDelim) { return TrimLeft( TrimRight(strValue, strDelim), strDelim); } /** * Check whether a string is starts with another string * @param strValue the string that will be checked * @param strSubStr the started string * @return true is a string is starts with another string, false otherwise */ template<typename T> bool StartsWith(const T& strValue, const T& strSubStr) { T str = strValue.substr(0, strSubStr.length()); return str == strSubStr; } /** * Check whether a string is ends with another string * @param strValue the string that will be checked * @param strSubStr the ended string * @return true is a string is ends with another string, false otherwise */ //template<typename T> //bool EndsWith(T& strValue, T& strSubStr); template<typename T> bool EndsWith(const T& strValue, const T& strSubStr) { int nPos = strValue.length() - strSubStr.length(); if (nPos >= 0) { T str = strValue.substr(nPos); return str == strSubStr; } return false; } /** * Check whether a string contains another string * @param strValue the string that will be checked * @param strSubStr the ended string * @return true is a string is ends with another string, false otherwise */ template<typename T> bool Contains(const T& strValue, const T& strSubStr) { return strValue.find(strSubStr) != T::npos; }
[ "buf1024@10f8a008-2033-b5f4-5ad9-01b5c2a83ee0" ]
[ [ [ 1, 345 ] ] ]
38fe1aa687d761e5f77703293cf24c9675e17286
975e3cacad2b513dff73ddd5ce3d449ad40c293b
/babel-2014-minett_a/trunk/debug/moc_TalkWindow.cpp
455197a1d327bde12ac75ef0e8b699b82aacae40
[]
no_license
alex-min/babelroxor
08a2babfbd1cf51dcfcba589d9acc7afcebee6e3
53cbdedd7d4b68943fe99d74dbb5443b799cca05
refs/heads/master
2021-01-10T14:24:12.257931
2011-12-13T10:57:30
2011-12-13T10:57:30
46,981,346
0
0
null
null
null
null
UTF-8
C++
false
false
3,003
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'TalkWindow.h' ** ** Created: Fri 2. Dec 17:01:33 2011 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.4) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../babelClient/TalkWindow.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'TalkWindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.4. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_Graphic__TalkWindow[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 4, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 21, 20, 20, 20, 0x0a, 34, 20, 20, 20, 0x0a, 57, 52, 20, 20, 0x0a, 79, 20, 20, 20, 0x0a, 0 // eod }; static const char qt_meta_stringdata_Graphic__TalkWindow[] = { "Graphic::TalkWindow\0\0changeBold()\0" "changeUnderline()\0name\0changeFamily(QString)\0" "sendTextToServer()\0" }; const QMetaObject Graphic::TalkWindow::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_Graphic__TalkWindow, qt_meta_data_Graphic__TalkWindow, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &Graphic::TalkWindow::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *Graphic::TalkWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *Graphic::TalkWindow::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_Graphic__TalkWindow)) return static_cast<void*>(const_cast< TalkWindow*>(this)); if (!strcmp(_clname, "InterfaceTalkWindow")) return static_cast< InterfaceTalkWindow*>(const_cast< TalkWindow*>(this)); return QWidget::qt_metacast(_clname); } int Graphic::TalkWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: changeBold(); break; case 1: changeUnderline(); break; case 2: changeFamily((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 3: sendTextToServer(); break; default: ; } _id -= 4; } return _id; } QT_END_MOC_NAMESPACE
[ [ [ 1, 89 ] ] ]
3098355ca9b9a5c765ab6d2241c3afc271c1a402
c8f467a4cee0b4067b93936574c884c9de0b36cf
/include/irrMath.h
2f02f63d8949d27932c7baadaa594a95820b4deb
[ "LicenseRef-scancode-unknown-license-reference", "Zlib", "LicenseRef-scancode-other-permissive" ]
permissive
flaithbheartaigh/mirrlicht
1ff418d29017e55e5f4a27a70dcfd5a88cb244b5
ccc16e8f5465fb72e81ae986e56ef2e4c3e7654b
refs/heads/master
2021-01-10T11:29:49.569701
2009-01-12T21:08:31
2009-01-12T21:08:31
49,994,212
0
0
null
null
null
null
UTF-8
C++
false
false
8,624
h
// Copyright (C) 2002-2007 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __IRR_MATH_H_INCLUDED__ #define __IRR_MATH_H_INCLUDED__ #include "IrrCompileConfig.h" #include "irrTypes.h" #include <math.h> #if defined(_IRR_SOLARIS_PLATFORM_) || defined(__BORLANDC__) || defined (__BCPLUSPLUS__) || defined(__SYMBIAN32__) #define sqrtf(X) sqrt(X) #define sinf(X) sin(X) #define cosf(X) cos(X) #define ceilf(X) ceil(X) #define floorf(X) floor(X) #define powf(X,Y) pow(X,Y) #define fmodf(X,Y) fmod(X,Y) #endif namespace irr { namespace core { //! Rounding error constant often used when comparing f32 values. #ifdef IRRLICHT_FAST_MATH const f32 ROUNDING_ERROR_32 = 0.00005f; const f64 ROUNDING_ERROR_64 = 0.000005f; #else const f32 ROUNDING_ERROR_32 = 0.000001f; const f64 ROUNDING_ERROR_64 = 0.00000001f; #endif //! Constant for PI. const f32 PI = 3.14159265359f; //! Constant for 64bit PI. const f64 PI64 = 3.1415926535897932384626433832795028841971693993751; //! 32bit Constant for converting from degrees to radians const f32 DEGTORAD = PI / 180.0f; //! 32bit constant for converting from radians to degrees (formally known as GRAD_PI) const f32 RADTODEG = 180.0f / PI; //! 64bit constant for converting from degrees to radians (formally known as GRAD_PI2) const f64 DEGTORAD64 = PI64 / 180.0; //! 64bit constant for converting from radians to degrees const f64 RADTODEG64 = 180.0 / PI64; //! returns minimum of two values. Own implementation to get rid of the STL (VS6 problems) template<class T> inline const T min_(const T a, const T b) { return a < b ? a : b; } //! returns minimum of three values. Own implementation to get rid of the STL (VS6 problems) template<class T> inline const T min_(const T a, const T b, const T c) { return a < b ? min_(a, c) : min_(b, c); } //! returns maximum of two values. Own implementation to get rid of the STL (VS6 problems) template<class T> inline T max_(const T a, const T b) { return a < b ? b : a; } //! returns minimum of three values. Own implementation to get rid of the STL (VS6 problems) template<class T> inline const T max_(const T a, const T b, const T c) { return a < b ? max_(b, c) : max_(a, c); } //! returns abs of two values. Own implementation to get rid of STL (VS6 problems) template<class T> inline T abs_(const T a) { return a < 0 ? -a : a; } //! returns linear interpolation of a and b with ratio t //! \return: a if t==0, b if t==1, and the linear interpolation else template<class T> inline T lerp(const T a, const T b, const T t) { return (a*(1-t)) + (b*t); } //! clamps a value between low and high template <class T> inline const T clamp (const T value, const T low, const T high) { return min_ (max_(value,low), high); } //! returns if a float equals the other one, taking floating //! point rounding errors into account inline bool equals(const f32 a, const f32 b, const f32 tolerance = ROUNDING_ERROR_32) { return (a + tolerance > b) && (a - tolerance < b); } //! returns if a float equals zero, taking floating //! point rounding errors into account inline bool iszero(const f32 a, const f32 tolerance = ROUNDING_ERROR_32) { return fabs ( a ) < tolerance; } inline s32 s32_min ( s32 a, s32 b) { s32 mask = (a - b) >> 31; return (a & mask) | (b & ~mask); } inline s32 s32_max ( s32 a, s32 b) { s32 mask = (a - b) >> 31; return (b & mask) | (a & ~mask); } inline s32 s32_clamp (s32 value, s32 low, s32 high) { return s32_min (s32_max(value,low), high); } /* float IEEE-754 bit represenation 0 0x00000000 1.0 0x3f800000 0.5 0x3f000000 3 0x40400000 +inf 0x7f800000 -inf 0xff800000 +NaN 0x7fc00000 or 0x7ff00000 in general: number = (sign ? -1:1) * 2^(exponent) * 1.(mantissa bits) */ #define F32_AS_S32(f) (*((s32 *) &(f))) #define F32_AS_U32(f) (*((u32 *) &(f))) #define F32_AS_U32_POINTER(f) ( ((u32 *) &(f))) #define F32_VALUE_0 0x00000000 #define F32_VALUE_1 0x3f800000 #define F32_SIGN_BIT 0x80000000U #define F32_EXPON_MANTISSA 0x7FFFFFFFU //! code is taken from IceFPU //! Integer representation of a floating-point value. #define IR(x) ((u32&)(x)) //! Absolute integer representation of a floating-point value #define AIR(x) (IR(x)&0x7fffffff) //! Floating-point representation of an integer value. #define FR(x) ((f32&)(x)) #define IEEE_1_0 0x3f800000 //!< integer representation of 1.0 #define IEEE_255_0 0x437f0000 //!< integer representation of 255.0 #define F32_LOWER_0(f) (F32_AS_U32(f) > F32_SIGN_BIT) #define F32_LOWER_EQUAL_0(f) (F32_AS_S32(f) <= F32_VALUE_0) #define F32_GREATER_0(f) (F32_AS_S32(f) > F32_VALUE_0) #define F32_GREATER_EQUAL_0(f) (F32_AS_U32(f) <= F32_SIGN_BIT) #define F32_EQUAL_1(f) (F32_AS_U32(f) == F32_VALUE_1) #define F32_EQUAL_0(f) ( (F32_AS_U32(f) & F32_EXPON_MANTISSA ) == F32_VALUE_0) // only same sign #define F32_A_GREATER_B(a,b) (F32_AS_S32((a)) > F32_AS_S32((b))) #ifndef REALINLINE #ifdef _MSC_VER #define REALINLINE __forceinline #else #define REALINLINE inline #endif #endif //! conditional set based on mask and arithmetic shift REALINLINE u32 if_c_a_else_b ( const s32 condition, const u32 a, const u32 b ) { return ( ( -condition >> 31 ) & ( a ^ b ) ) ^ b; } //! conditional set based on mask and arithmetic shift REALINLINE u32 if_c_a_else_0 ( const s32 condition, const u32 a ) { return ( -condition >> 31 ) & a; } /* if (condition) state |= m; else state &= ~m; */ REALINLINE void setbit ( u32 &state, s32 condition, u32 mask ) { // 0, or any postive to mask //s32 conmask = -condition >> 31; state ^= ( ( -condition >> 31 ) ^ state ) & mask; } #ifdef IRRLICHT_FAST_MATH REALINLINE void clearFPUException () { __asm fnclex; } // comes from Nvidia #if 1 REALINLINE f32 reciprocal_squareroot(const f32 x) { u32 tmp = (u32(IEEE_1_0 << 1) + IEEE_1_0 - *(u32*)&x) >> 1; f32 y = *(f32*)&tmp; return y * (1.47f - 0.47f * x * y * y); } #endif // an sse2 version #if 0 REALINLINE f32 reciprocal_squareroot(const f32 x) { __asm { movss xmm0, x rsqrtss xmm0, xmm0 movss x, xmm0 } return x; } #endif //! i do not divide through 0.. (fpu expection) // instead set f to a high value to get a return value near zero.. // -1000000000000.f.. is use minus to stay negative.. // must test's here (plane.normal dot anything ) checks on <= 0.f REALINLINE f32 reciprocal ( const f32 f ) { return 1.f / f; //u32 x = (-(AIR(f) != 0 ) >> 31 ) & ( IR(f) ^ 0xd368d4a5 ) ^ 0xd368d4a5; //return 1.f / FR ( x ); } REALINLINE f32 reciprocal_approxim ( const f32 p ) { register u32 x = 0x7F000000 - IR ( p ); const f32 r = FR ( x ); return r * (2.0f - p * r); } REALINLINE s32 floor32(f32 x) { const f32 h = 0.5f; s32 t; __asm { fld x fsub h fistp t } return t; } REALINLINE s32 ceil32 ( f32 x ) { const f32 h = 0.5f; s32 t; __asm { fld x fadd h fistp t } return t; } REALINLINE s32 round32(f32 x) { s32 t; __asm { fld x fistp t } return t; } #else REALINLINE void clearFPUException () { } inline f32 reciprocal_squareroot(const f32 x) { return 1.f / sqrtf ( x ); } inline f32 reciprocal ( const f32 x ) { return 1.f / x; } inline f32 reciprocal_approxim ( const f32 x ) { return 1.f / x; } inline s32 floor32 ( f32 x ) { return (s32) floorf ( x ); } inline s32 ceil32 ( f32 x ) { return (s32) ceilf ( x ); } inline s32 round32 ( f32 x ) { return (s32) ( x + 0.5f ); } inline f32 f32_max3(const f32 a, const f32 b, const f32 c) { return a > b ? (a > c ? a : c) : (b > c ? b : c); } inline f32 f32_min3(const f32 a, const f32 b, const f32 c) { return a < b ? (a < c ? a : c) : (b < c ? b : c); } #endif inline f32 fract ( f32 x ) { return x - floorf ( x ); } inline f32 round ( f32 x ) { return floorf ( x + 0.5f ); } } // end namespace core } // end namespace irr #endif
[ "limingchina@c8d24273-d621-0410-9a95-1b5ff033c8bf" ]
[ [ [ 1, 383 ] ] ]
a4cf0e06447aae57e506ae57356b4bde48053f00
c3531ade6396e9ea9c7c9a85f7da538149df2d09
/Param/include/hj_3rd/hjlib/sparse/solver.h
91317ea7bc36de92bca40d8e4780d4d9ed1ef55c
[]
no_license
feengg/MultiChart-Parameterization
ddbd680f3e1c2100e04c042f8f842256f82c5088
764824b7ebab9a3a5e8fa67e767785d2aec6ad0a
refs/heads/master
2020-03-28T16:43:51.242114
2011-04-19T17:18:44
2011-04-19T17:18:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,837
h
#ifndef HJ_SPARSE_SOLVER_H_ #define HJ_SPARSE_SOLVER_H_ #include "config.h" extern "C" { //! sizeof_val = sizeof(float,double), not sizeof(complex<float>, complex<double>) ///! direct solver HJ_SPARSE_API void *hj_sparse_direct_solver_A_create( unsigned char sizeof_int, unsigned char sizeof_val, unsigned char real_or_complex, size_t nrows, size_t ncols, const void *ptr, const void *idx, const void *val, //< link for internal use const char *name, //< copy to internal void *opts); //< link for internal use HJ_SPARSE_API int hj_sparse_direct_solver_A_solve(void *ctx, const void *b, void *x, const size_t nrhs, void *opts); HJ_SPARSE_API void hj_sparse_direct_solver_A_destroy(void *ctx); ///! iterative solver HJ_SPARSE_API void *hj_sparse_iterative_solver_A_create( unsigned char sizeof_int, unsigned char sizeof_val, unsigned char real_or_complex, size_t nrows, size_t ncols, const void *ptr, const void *idx, const void *val, //< link for internal use const char *name, //< copy to internal void *opts); //< link for internal use HJ_SPARSE_API int hj_sparse_iterative_solver_A_solve(void *ctx, const void *b, void *x, const size_t nrhs, void *opts); HJ_SPARSE_API void hj_sparse_iterative_solver_A_destroy(void *ctx); struct laspack_opts { char *iter_name_, *precond_name_; size_t iter_num_; double precision_, relax_; }; } #include <complex> #include "./type_traits.h" namespace hj { namespace sparse { class solver_base { public: virtual ~solver_base(){} virtual int solve(const void *b, void *x, size_t nrhs = 1, void *opts = 0) = 0; protected: solver_base(void *ctx):ctx_(ctx){} void *ctx_; }; //! direct solvers //! @brief solve Ax=b class direct_solver_A : public solver_base { public: template <typename VAL_TYPE, typename INT_TYPE> static direct_solver_A *create( const csc<VAL_TYPE, INT_TYPE> &A, const char *name = 0, void *opts = 0) { void *ctx = hj_sparse_direct_solver_A_create( sizeof(INT_TYPE), value_type<VAL_TYPE>::size, value_type<VAL_TYPE>::type, A.size(1), A.size(2), &A.ptr_[0], &A.idx_[0], &A.val_[0], name, opts); if(ctx) return new direct_solver_A(ctx); return 0; } virtual int solve(const void *b, void *x, size_t nrhs = 1, void *opts = 0) { return hj_sparse_direct_solver_A_solve(ctx_, b, x, nrhs, opts); } ~direct_solver_A(void) { hj_sparse_direct_solver_A_destroy(ctx_); } protected: direct_solver_A(void *ctx):solver_base(ctx){} }; //! @brief solve AA^Tx=Ab class direct_solver_AAT : public solver_base { public: template <typename VAL_TYPE, typename INT_TYPE> static direct_solver_AAT *create( const csc<VAL_TYPE, INT_TYPE> &A, const char *name = 0, void *opts = 0) { return 0; } virtual int solve(const void *b, void *x, const void *nrhs = 0, void *opts = 0) { return 0; } protected: direct_solver_AAT(void *ctx):solver_base(ctx){} }; //! @brief solve Ax=b with iterative method class iterative_solver_A : public solver_base { public: template <typename VAL_TYPE, typename INT_TYPE> static iterative_solver_A *create( const csc<VAL_TYPE, INT_TYPE> &A, const char *name = 0, void *opts = 0) { void *ctx = hj_sparse_iterative_solver_A_create( sizeof(INT_TYPE), value_type<VAL_TYPE>::size, value_type<VAL_TYPE>::type, A.size(1), A.size(2), &A.ptr_[0], &A.idx_[0], &A.val_[0], name, opts); if(ctx) return new iterative_solver_A(ctx); return 0; } virtual int solve(const void *b, void *x, size_t nrhs = 1, void *opts = 0) { return hj_sparse_iterative_solver_A_solve(ctx_, b, x, nrhs, opts); } ~iterative_solver_A(void) { hj_sparse_iterative_solver_A_destroy(ctx_); } protected: iterative_solver_A(void *ctx):solver_base(ctx){} }; }} #endif
[ [ [ 1, 139 ] ] ]
b446629fce1858e5f1349167e8cba157ca4c15fa
35f23e4f6a24dbcb0d2382f42c1246635b98a1a5
/source/Collectors/IIS7/nativesyslogmodule.cpp
579d789960e90c94bb6b46f8cc5e13e21ff5ba56
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
Cloudxtreme/Realtime-Web-Monitoring
d53c1f22e7de6d74499a56852985f6231b7fb211
6fcf2bcee10ce6567b972c153f66233c1e0cf6b5
refs/heads/master
2021-06-01T07:49:13.134965
2011-09-19T21:03:21
2011-09-19T21:03:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,249
cpp
#include "precomp.h" #include <sys/timeb.h> REQUEST_NOTIFICATION_STATUS CNativeSyslogModule::OnBeginRequest( IN IHttpContext * pHttpContext, IN IHttpEventProvider * pProvider ) { UNREFERENCED_PARAMETER( pProvider ); LARGE_INTEGER li; QueryPerformanceCounter(&li); struct _timeb timebuffer; char timeline[26]; _ftime64_s( &timebuffer ); ctime_s(timeline, 26, &(timebuffer.time)); if ((uiFacility < 0) || (uiFacility > 23)) uiFacility = 13; // fix invalid values at 13. USHORT uSeverity = (uiFacility << 3) + 6; // priority of 6 indicates this is an informational message USHORT *headerLength = 0; cstrMsgHdr.Empty(); cstrMsgHdr.AppendFormat(_T("<%d>"), uSeverity); cstrMsgHdr.AppendFormat(_T("%.15s "), &timeline[4]); // Jun 03 12:00:00 IHttpRequest *pHttpRequest = pHttpContext->GetRequest(); cstrMsgHdr.AppendFormat(_T("%s IISNSL: "), pHttpRequest->GetHeader(HttpHeaderHost, headerLength)); // www.sitename.com cstrMsgHdr.AppendFormat(_T("%8d "), (li.QuadPart/100)); // 123456789 longTimeSeconds = ((long)timebuffer.time) * 1000 + timebuffer.millitm; // this coverts the seconds into milliseconds return RQ_NOTIFICATION_CONTINUE; } REQUEST_NOTIFICATION_STATUS CNativeSyslogModule::OnSendResponse( IN IHttpContext * pHttpContext, IN ISendResponseProvider * pProvider ) { HRESULT hr = S_OK; // Retrieve a a pointer to the current response. IHttpResponse *pHttpResponse = pHttpContext->GetResponse(); IHttpRequest *pHttpRequest = pHttpContext->GetRequest(); IHttpApplication *pHttpApplication = pHttpContext->GetApplication(); // Test for errors. if (pHttpResponse != NULL) { struct _timeb timebuffer; char timeline[26]; _ftime64_s( &timebuffer ); ctime_s(timeline, 26, &(timebuffer.time)); long longElapsedSeconds = (((long)timebuffer.time) * 1000 + timebuffer.millitm) - longTimeSeconds; // compute out the difference between the start time and now for ttfb USHORT *headerLength = 0; USHORT uStatusCode = 0; USHORT uSubStatus = 0; // Retrieve the current HTTP status code. pHttpResponse->GetStatus(&uStatusCode,&uSubStatus); CString cstrMsgHdr2(_T("")); cstrMsgHdr2.AppendFormat(_T("%d.%d %d "), uStatusCode, uSubStatus, longElapsedSeconds); // 200.0 10 CString cstrMsgBody(pHttpRequest->GetHttpMethod()); // GET cstrMsgBody.AppendFormat(_T(" %s "), pHttpRequest->GetRawHttpRequest()->pRawUrl); // /path/to/page.html if (pHttpResponse->GetHeader(HttpHeaderContentType, headerLength) == NULL) cstrMsgBody.Append(_T("- ")); else { CString cstrContentType(pHttpResponse->GetHeader(HttpHeaderContentType, headerLength)); if (cstrContentType.Find(';',0) > 0) cstrMsgBody.AppendFormat(_T("%s "), cstrContentType.Left(cstrContentType.Find(';',0))); else cstrMsgBody.AppendFormat(_T("%s "), cstrContentType); } if (pHttpRequest->GetRemoteAddress()!= NULL) cstrMsgBody.AppendFormat(_T("%s "), inet_ntoa(((PSOCKADDR_IN)pHttpRequest->GetRemoteAddress())->sin_addr)); // 10.0.0.1 else cstrMsgHdr.Append(_T("- ")); cstrMsgBody.AppendFormat(_T("%s "), pHttpApplication->GetApplicationId()); // /LM/W3SVC/1/ROOT cstrMsgBody.AppendFormat(_T("%s "), pHttpRequest->GetHeader(HttpHeaderReferer, headerLength)); // scheme://server/path/to/the%20source.html CStringA strUserAgent(pHttpRequest->GetHeader(HttpHeaderUserAgent, headerLength)); strUserAgent.Replace(_T(" "), _T("+")); // replace spaces with + signs cstrMsgBody.AppendFormat(_T("%s "), strUserAgent); // Mozilla/5.0+(Windows+NT+6.1;+WOW64;) int iMaxMessageLength = (uiMaxMessageSize - cstrMsgHdr.GetLength()) - cstrMsgHdr2.GetLength(); // length of each piece of the message body is the max length minus the headers int iMessageLength = cstrMsgBody.GetLength(); // total amount to send USHORT i = 1; do { CString cstrMsgPart(cstrMsgHdr); cstrMsgPart.Append(cstrMsgHdr2); cstrMsgPart.AppendFormat(_T("%d %d "), i, (iMessageLength / iMaxMessageLength) + 1); // 1 2 (current message part and total message parts) if (iMessageLength > (i * iMaxMessageLength)) cstrMsgPart.AppendFormat(_T("%s"), cstrMsgBody.Mid(iMaxMessageLength * (i - 1), iMaxMessageLength)); // we can't send it all so send the most we can else cstrMsgPart.AppendFormat(_T("%s"), cstrMsgBody.Mid(iMaxMessageLength * (i - 1))); // send whatever is left since it fits in a single message hr = SendSyslogMessage(cstrMsgPart.GetString()); if (FAILED(hr)) break; } while ((i < 4) && (i++ * iMaxMessageLength) <= iMessageLength); // the reasonable maximum number of chars in a url is about 2000. given a min mtu of 1500*4 = 6000 we have more than enough space } if ( FAILED( hr ) ) return RQ_NOTIFICATION_FINISH_REQUEST; else return RQ_NOTIFICATION_CONTINUE; } // Sends the given string as a syslog message. HRESULT CNativeSyslogModule::SendSyslogMessage( PCSTR pszMessage ) { WSADATA wsaData; HRESULT hr = S_OK; // Initialize Winsock hr = WSAStartup(MAKEWORD(2,2), &wsaData); if (SUCCEEDED(hr)) { ADDRINFOW *result = NULL, *ptr = NULL, hints; ZeroMemory( &hints, sizeof(hints) ); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; // Resolve the server address and port hr = GetAddrInfoW(bstrServerName, bstrPort, &hints, &result); // If we have an address if (SUCCEEDED(hr)) { SOCKET ConnectSocket = INVALID_SOCKET; // Attempt to connect to the first address returned by // the call to getaddrinfo ptr=result; // Create a SOCKET for connecting to server ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (ConnectSocket != INVALID_SOCKET) { // Connect to server. hr = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen); if (hr != SOCKET_ERROR) { // compute the socket reported max message size... if it is smaller then that is what we will use. int intMaxMsgSize; int argSize = sizeof(int); hr = getsockopt(ConnectSocket, SOL_SOCKET, SO_MAX_MSG_SIZE, (char*)&intMaxMsgSize, &argSize); if (intMaxMsgSize < uiMaxMessageSize) intMaxMsgSize = uiMaxMessageSize; size_t uLength = strlen(pszMessage); if (uLength > intMaxMsgSize) uLength = intMaxMsgSize; // Send an initial buffer hr = send(ConnectSocket, pszMessage, uLength, 0); // TODO: check for failed send... abort hr = shutdown(ConnectSocket, SD_SEND); } closesocket(ConnectSocket); ConnectSocket = INVALID_SOCKET; } else // failure to open socket { int errNum = WSAGetLastError(); // trace out error message here. } } // clean up any found address records FreeAddrInfoW(result); } // take down the winsock WSACleanup(); return hr; }
[ [ [ 1, 187 ] ] ]
6f18c980f69478948a656b41afe73d92ad9136b1
521721c2e095daf757ad62a267b1c0f724561935
/bsShaderManager.cpp
38dd22fe580e559ea10cc5be08edd9e0526b2832
[]
no_license
MichaelSPG/boms
251922d78f2db85ece495e067bd56a1e9fae14b1
23a13010e0aaa79fea3b7cf1b23e2faab02fa5d4
refs/heads/master
2021-01-10T16:23:51.722062
2011-12-08T00:04:33
2011-12-08T00:04:33
48,052,727
1
0
null
null
null
null
UTF-8
C++
false
false
13,790
cpp
#include "StdAfx.h" #include "bsShaderManager.h" #include <string> #include <time.h> #include <time.inl> #include <D3Dcompiler.h> #include "bsFileSystem.h" #include "bsLog.h" #include "bsAssert.h" #include "bsDx11Renderer.h" #include "bsFileUtil.h" #include "bsTimer.h" bsShaderManager::bsShaderManager(bsDx11Renderer& dx11Renderer, const bsFileSystem& fileSystem, const std::string& precompiledShaderDirectory) : mFileSystem(fileSystem) , mDx11Renderer(&dx11Renderer) , mNumCreatedShaders(0) , mPrecompiledShaderDirectory(precompiledShaderDirectory) { //Create the directory for precompiled shaders. //This call may fail if the directory is a file, or if the folder already exists. CreateDirectoryA(mPrecompiledShaderDirectory.c_str(), nullptr); //Verify that the directory exist. If it is a file, the above call probably //failed to create a directory with the same name. if (!bsFileUtil::directoryExists(mPrecompiledShaderDirectory.c_str())) { bsLog::logf(bsLog::SEV_CRICICAL, "Unable to create precompiled shader directory" " '%s'. Please ensure that the directory name is not used by a file", mPrecompiledShaderDirectory.c_str()); BS_ASSERT2(false, "Unable to create precompiled shader directory. Please ensure" " that the directory name is not used by a file"); } } void bsShaderManager::setVertexShader(const std::shared_ptr<bsVertexShader>& vertexShader) { BS_ASSERT(vertexShader); ID3D11DeviceContext* context = mDx11Renderer->getDeviceContext(); context->IASetInputLayout(vertexShader->mInputLayout); context->VSSetShader(vertexShader->mVertexShader, nullptr, 0); } void bsShaderManager::setPixelShader(const std::shared_ptr<bsPixelShader>& pixelShader) { BS_ASSERT(pixelShader); ID3D11DeviceContext* context = mDx11Renderer->getDeviceContext(); context->PSSetShader(pixelShader->mPixelShader, nullptr, 0); } std::shared_ptr<bsVertexShader> bsShaderManager::getVertexShader(const std::string& fileName, const D3D11_INPUT_ELEMENT_DESC* inputDescs, unsigned int inputDescCount) const { BS_ASSERT(fileName.length()); BS_ASSERT2(inputDescCount, "Zero length input description"); //Get the path for the file const std::string filePath = mFileSystem.getPathFromFilename(fileName); if (!filePath.length()) { //The path for the given mesh name was not found bsLog::logf(bsLog::SEV_ERROR, "Shader '%s' does not exist in any known resource" "paths, it will not be created", fileName.c_str()); BS_ASSERT2(false, "Failed to load shader, file not found"); return nullptr; } //See if the shader already exists auto val = mVertexShaders.find(filePath); if (val != mVertexShaders.end()) { return val->second; } //Not found, create and return the shader //createVertexShader is not const, so must cast const away return const_cast<bsShaderManager*>(this)->createVertexShader(filePath, inputDescs, inputDescCount); } std::shared_ptr<bsVertexShader> bsShaderManager::createVertexShader(const std::string& fileName, const D3D11_INPUT_ELEMENT_DESC* inputDescs, unsigned int inputDescCount) { //Load shader blob and create the shader. ID3DBlob* blob = nullptr; bool usingPrecompiledShader = false; //See if a precompiled version of the shader exists. const std::string precompiledPath(std::move(getPrecompiledVertexShaderPath(fileName))); if (bsFileUtil::fileExists(fileName.c_str()) && bsFileUtil::fileExists(precompiledPath.c_str())) { const time_t lastModifiedPrecompiled = bsFileUtil::lastModifiedTime(precompiledPath.c_str()); const time_t lastModifiedUncompiled = bsFileUtil::lastModifiedTime(fileName.c_str()); //Check if precompiled version is newer than uncompiled version. //If it's not newer, the precompiled version is outdated and needs to be compiled //again. if (difftime(lastModifiedPrecompiled, lastModifiedUncompiled) > 0.0f) { //Precompiled version was made after the uncompiled shader, load it. loadCompiledShaderFromFile(precompiledPath.c_str(), blob); usingPrecompiledShader = blob != nullptr; } } if (blob == nullptr) { //Precompiled version not found or was outdated, recompile it. if (!compileVertexShaderBlobFromFile(&blob, fileName, inputDescs, inputDescCount)) { //Compilation failed. return nullptr; } saveCompiledShaderToFile(precompiledPath.c_str(), *blob); } //Create the shader from the loaded blob. return createVertexShaderFromBlob(blob, usingPrecompiledShader ? precompiledPath : fileName, inputDescs, inputDescCount); } std::shared_ptr<bsVertexShader> bsShaderManager::createVertexShaderFromBlob(ID3DBlob* blob, const std::string& fileName, const D3D11_INPUT_ELEMENT_DESC* inputDescs, unsigned int inputDescCount) { //Create shader ID3D11VertexShader* vertexShader = nullptr; if (FAILED(mDx11Renderer->getDevice()->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &vertexShader))) { if (blob) { blob->Release(); } bsLog::logf(bsLog::SEV_ERROR, "Failed to create vertex shader '%s'", fileName.c_str()); BS_ASSERT2(false, "Failed to create vertex shader"); return nullptr; } //Create input layout ID3D11InputLayout* vertexLayout = nullptr; if (FAILED(mDx11Renderer->getDevice()->CreateInputLayout(inputDescs, inputDescCount, blob->GetBufferPointer(), blob->GetBufferSize(), &vertexLayout))) { if (blob) { blob->Release(); } std::string errorMessage("Failed to create input layout for '"); errorMessage += fileName + '\''; BS_ASSERT2(false, errorMessage.c_str()); return nullptr; } auto vs = std::make_pair(fileName, std::make_shared<bsVertexShader>(vertexShader, vertexLayout, getUniqueShaderID())); vs.second->mInputLayoutDescriptions.insert(std::begin(vs.second->mInputLayoutDescriptions), inputDescs, inputDescs + inputDescCount); #ifdef BS_DEBUG //Set debug data in the D3D objects. std::string bufferName("VS "); bufferName.append(fileName); vs.second->mVertexShader->SetPrivateData(WKPDID_D3DDebugObjectName, bufferName.size(), bufferName.c_str()); bufferName = "IL "; bufferName.append(fileName); vs.second->mInputLayout->SetPrivateData(WKPDID_D3DDebugObjectName, bufferName.size(), bufferName.c_str()); #endif // BS_DEBUG mVertexShaders.insert(vs); bsLog::logf(bsLog::SEV_INFO, "Created vertex shader '%s'", fileName.c_str()); return vs.second; } bool bsShaderManager::compileVertexShaderBlobFromFile(ID3DBlob** blobOut, const std::string& fileName, const D3D11_INPUT_ELEMENT_DESC* inputDescs, unsigned int inputDescCount) { //TODO: Return a default fallback shader if this fails. //Compile shader if (FAILED(mDx11Renderer->compileShader(fileName.c_str(), "VS", "vs_4_0", blobOut))) { if (blobOut) { (*blobOut)->Release(); *blobOut = nullptr; } std::string errorMessage("Failed to compile vertex shader '"); errorMessage += fileName + '\''; BS_ASSERT2(false, errorMessage.c_str()); return false; } return true; } ////////////////////////////////////////////////////////////////////////// // Pixel shader ////////////////////////////////////////////////////////////////////////// std::shared_ptr<bsPixelShader> bsShaderManager::getPixelShader(const std::string& fileName) const { BS_ASSERT2(fileName.length(), "Zero length file name. Use \".\" for current path"); //Get the path for the file const std::string filePath = mFileSystem.getPathFromFilename(fileName); if (!filePath.length()) { bsLog::logf(bsLog::SEV_ERROR, "'%s' does not exist in any known resource paths," " it will not be created", fileName.c_str()); BS_ASSERT2(false, "Failed to create pixel shader, file not found"); return nullptr; } //See if the shader already exists auto val = mPixelShaders.find(filePath); if (val != mPixelShaders.end()) { return val->second; } //Create the shader from the loaded blob. return const_cast<bsShaderManager*>(this)->createPixelShader(filePath); } std::shared_ptr<bsPixelShader> bsShaderManager::createPixelShader(const std::string& fileName) { //Load shader blob and create the shader. ID3DBlob* blob = nullptr; bool usingPrecompiledShader = false; //See if a precompiled version of the shader exists. const std::string precompiledPath(std::move(getPrecompiledPixelShaderPath(fileName))); if (bsFileUtil::fileExists(fileName.c_str()) && bsFileUtil::fileExists(precompiledPath.c_str())) { const time_t lastModifiedPrecompiled = bsFileUtil::lastModifiedTime(precompiledPath.c_str()); const time_t lastModifiedUncompiled = bsFileUtil::lastModifiedTime(fileName.c_str()); //Check if precompiled version is newer than uncompiled version. //If it's not newer, the precompiled version is outdated and needs to be compiled //again. if (difftime(lastModifiedPrecompiled, lastModifiedUncompiled) > 0.0f) { //Precompiled version was made after the uncompiled shader, load it. loadCompiledShaderFromFile(precompiledPath.c_str(), blob); usingPrecompiledShader = blob != nullptr; } } if (blob == nullptr) { //Precompiled version not found or was outdated, recompile it. if (!compilePixelShaderBlobFromFile(&blob, fileName)) { //Compilation failed. return nullptr; } saveCompiledShaderToFile(precompiledPath.c_str(), *blob); } //Create the shader from the loaded blob. return createPixelShaderFromBlob(blob, usingPrecompiledShader ? precompiledPath : fileName); } std::shared_ptr<bsPixelShader> bsShaderManager::createPixelShaderFromBlob(ID3DBlob* blob, const std::string& fileName) { //Create shader ID3D11PixelShader* pixelShader = nullptr; if (FAILED(mDx11Renderer->getDevice()->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &pixelShader))) { if (pixelShader) { pixelShader->Release(); } std::string message("Failed to create pixel shader '"); message += fileName + '\''; BS_ASSERT2(false, message.c_str()); return nullptr; } auto ps = std::make_pair(fileName, std::make_shared<bsPixelShader>(pixelShader, getUniqueShaderID())); #ifdef BS_DEBUG //Set debug data in the D3D object. std::string bufferName("PS "); bufferName.append(fileName); ps.second->mPixelShader->SetPrivateData(WKPDID_D3DDebugObjectName, bufferName.size(), bufferName.c_str()); #endif // BS_DEBUG mPixelShaders.insert(ps); bsLog::logf(bsLog::SEV_INFO, "Created pixel shader '%s'", fileName.c_str()); return ps.second; } bool bsShaderManager::compilePixelShaderBlobFromFile(ID3DBlob** blobOut, const std::string& fileName) { if (FAILED(mDx11Renderer->compileShader(fileName.c_str(),"PS", "ps_4_0", blobOut))) { if (blobOut) { (*blobOut)->Release(); *blobOut = nullptr; } std::string message("Failed to compile pixel shader '"); message += fileName + '\''; BS_ASSERT2(false, message.c_str()); return false; } return true; } bool bsShaderManager::saveCompiledShaderToFile(const char* fileName, ID3DBlob& shaderBlobToSave) const { FILE* file = fopen(fileName, "wb"); if (file != nullptr) { const unsigned int shaderBlobSize = shaderBlobToSave.GetBufferSize(); const size_t written1 = fwrite(&shaderBlobSize, sizeof(unsigned int), 1, file); const size_t written2 = fwrite(shaderBlobToSave.GetBufferPointer(), shaderBlobSize, 1, file); fclose(file); return written1 == 1 && written2 == 1; } return false; } void bsShaderManager::loadCompiledShaderFromFile(const char* fileName, ID3DBlob*& shaderBlobOut) const { FILE* file = fopen(fileName, "rb"); if (file) { //Load first 4 bytes (size of shader blob), then the shader. unsigned int shaderBlobSize; const size_t read1 = fread(&shaderBlobSize, sizeof(unsigned int), 1, file); char* buffer = static_cast<char*>(malloc(shaderBlobSize)); const size_t read2 = fread(buffer, shaderBlobSize, 1, file); if (read1 && read2) { //Reading succeeded, copy loaded buffer into blob. D3DCreateBlob(shaderBlobSize, &shaderBlobOut); memcpy(shaderBlobOut->GetBufferPointer(), buffer, shaderBlobSize); } free(buffer); } } inline std::string bsShaderManager::getPrecompiledShaderPath(const std::string& filePath) const { std::string compiledShaderFileName(mPrecompiledShaderDirectory); if (compiledShaderFileName.back() != '\\') { compiledShaderFileName.push_back('\\'); } //Append file name from parameter to base precompiled directory. compiledShaderFileName.append(filePath.substr(filePath.find_last_of('\\') + 1)); //Erase file extension. compiledShaderFileName.erase(compiledShaderFileName.find_last_of('.') + 1); #ifdef BS_DEBUG //Add "dbg_" to file extensions when compiling in debug to avoid name conflicts. compiledShaderFileName.append("dbg_"); #endif return std::move(compiledShaderFileName); } std::string bsShaderManager::getPrecompiledVertexShaderPath(const std::string& filePath) const { std::string compiledShaderFileName(std::move(getPrecompiledShaderPath(filePath))); //Append file extension (pcvs = precompiled vertex shader). compiledShaderFileName.append("pcvs"); return compiledShaderFileName; } std::string bsShaderManager::getPrecompiledPixelShaderPath(const std::string& filePath) const { std::string compiledShaderFileName(std::move(getPrecompiledShaderPath(filePath))); //Append file extension (pcps = precompiled pixel shader). compiledShaderFileName.append("pcps"); return compiledShaderFileName; }
[ [ [ 1, 450 ] ] ]
094d49df2c9ce5acfaca87214c563b5c6dd25ce9
d6eba554d0c3db3b2252ad34ffce74669fa49c58
/Source/EventSystem/playHandler.h
deeb9b971b1a0562fa6d097f080a05cdf039b529
[]
no_license
nbucciarelli/Polarity-Shift
e7246af9b8c3eb4aa0e6aaa41b17f0914f9d0b10
8b9c982f2938d7d1e5bd1eb8de0bdf10505ed017
refs/heads/master
2016-09-11T00:24:32.906933
2008-09-26T18:01:01
2008-09-26T18:01:01
3,408,115
1
0
null
null
null
null
UTF-8
C++
false
false
1,752
h
////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // File: "playerHandler.h" // Author: Scott Smallback (SS) // Purpose: Handles the events for the player /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "listener.h" class eventManager; class objManager; class objFactory; class objFileLoader; class baseObj; class playHandler : public listener { protected: eventManager* EM; objManager* OM; objFactory* OF; objFileLoader* FL; void onGameLoad(); void killActor(baseObj* obj); public: ////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: "HandleEvent" // Last Modified: August 25, 2008 // Purpose: Handles the event system for the player ////////////////////////////////////////////////////////////////////////////////////////////////////// void HandleEvent(gameEvent* ev); ////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: "initialize" // Last Modified: August 25, 2008 // Purpose: Initializes the event system for the player ////////////////////////////////////////////////////////////////////////////////////////////////////// void initialize(); ////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: "shutdown" // Last Modified: August 25, 2008 // Purpose: Stops the event system for the player ////////////////////////////////////////////////////////////////////////////////////////////////////// void shutdown(); };
[ [ [ 1, 49 ] ] ]
694d8626cfba42604ecbe3434e4335fd81e6578f
68cfffb549ab1cb32e02db4f80ed001a912e455b
/reference/snake.cpp
aeec0eb819f74f95f9f625ecd45bbe9b6d53067f
[]
no_license
xhbang/Console-snake
e462d6c206dc1dd071640f0ad203eb367460b2c8
a61cf9d91744f084741e2c29b930d9646256479b
refs/heads/master
2016-09-10T20:18:10.598179
2011-12-05T10:33:51
2011-12-05T10:33:51
2,902,986
0
0
null
null
null
null
GB18030
C++
false
false
1,860
cpp
#include<iostream> #include<conio.h> #include<time.h> #include<windows.h> using namespace std; char a[22][22]; int x=10,y=10; void qipan(); bool player(int *n,int *s,int *w,int *e); void food(); void putout(int score); int main() { int score=0; //记录分数 int n=0,s=0,w=0,e=0; bool f=true; srand(time(0)); qipan(); //画边线 a[x][y]=1; while(f) { food(); //生成食物 f=player(&n,&s,&w,&e); //玩家操作 if(a[x][y]=='*') //吃到食物 score++; a[x][y]=1; putout(score); Sleep(100); } cout<<endl<<"game over!"<<endl; Sleep(1000); return 0; } bool player(int *n,int *s,int *w,int *e) //上下左右 { char c; bool f=true; a[x][y]=' '; if(kbhit()) { switch(c=getch()) { case '1': *w=1;*n=0,*s=0,*e=0;break; case '3': *e=1;*n=0,*s=0,*w=0;break; case '2': *s=1;*n=0,*w=0,*e=0;break; case '5': *n=1;*w=0,*s=0,*e=0;break; } } if(*n) x--; if(x<1) f=false; if(*s) x++; if(x>20) f=false; if(*w) y--; if(y<1) f=false; if(*e) y++; if(y>20) f=false; return f; } void food() { int i,j; for(i=1;i<21;i++) for(j=1;j<21;j++) if(a[i][j]=='*') i=100; //i=100则已有食物 if(i==21) { do{ i=rand()%21+1; j=rand()%21+1; } while(a[i][j]!=' '); a[i][j]='*'; } } void qipan() { int i,j; for(i=1;i<21;++i) for(j=1;j<21;++j) a[i][j]=' '; for(i=0,j=0;j<22;j++) a[i][j]='*'; for(i=21,j=0;j<22;j++) a[i][j]='*'; for(i=0,j=0;i<22;i++) a[i][j]='*'; for(i=0,j=21;i<22;i++) a[i][j]='*'; } void putout(int score) { int i,j; system("cls"); for(i=0;i<22;i++) { for(j=0;j<22;j++) cout<<a[i][j]<<" "; cout<<endl; } cout<<"score:"<<score; }
[ [ [ 1, 106 ] ] ]
38180ce5a21e73c6c0be7f51e5c0cc4ebb4358db
b947582d4a5a285af530b5091bb242d8d0edf855
/pemilik/LihatData.cpp
4167fc4e3453f033359d8afbb00d7abecaa392dc
[]
no_license
dieend/simproyek1
c58a1d1335b350f1fab837f8283e62f964570abc
fc56985d471626c9f063b120aecfc7a7434506a6
refs/heads/master
2021-01-19T01:48:53.547580
2010-10-24T08:12:40
2010-10-24T08:12:40
32,120,427
0
0
null
null
null
null
UTF-8
C++
false
false
47
cpp
#include "StdAfx.h" #include "LihatData.h"
[ "[email protected]@3f482c3b-0193-a96f-f1fb-1ccff6c3e739" ]
[ [ [ 1, 3 ] ] ]
2ddcd6c294a6313eb85dede4348a6dca3b313676
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/AranPhy/SliderJoint.h
5298c72747486aaa204bdf5a9576fd222e4564a3
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
1,211
h
#ifndef SLIDERJOINT_H #define SLIDERJOINT_H #include "LinearJoint.h" class SliderJoint : public LinearJoint { public: SliderJoint(const OdeSpaceContext* osc); virtual ~SliderJoint(); virtual const char* getJointTypeName() const { return "Slider"; } virtual dReal getPosition(int anum) const { return dJointGetSliderPosition(getId()); } virtual double getVelocity(int anum) const { return dJointGetSliderPositionRate(getId()); } virtual void setAxis(int anum, const ArnVec3& pos) { dJointSetSliderAxis(getId(), pos.x, pos.y, pos.z); } virtual void getAxis(int anum, dVector3 result) const { dJointGetSliderAxis(getId(), result); } virtual double getValue(int ) { return getPosition(1); } virtual void setParamVelocity(int , dReal v) { dJointSetSliderParam(getId(), dParamVel, v); } virtual void setParamFMax(int , dReal v) { dJointSetSliderParam(getId(), dParamFMax, v); } virtual void setParamLoHiStop(int anum, dReal lo, dReal hi); virtual void renderJointAxis() const; virtual void updateFrame(); protected: virtual void doReset(); private: }; inline void SliderJoint::updateFrame() { updateFrameInternal(1); } #endif // SLIDERJOINT_H
[ [ [ 1, 40 ] ] ]
c11aaf328747119272cf342c1cb6b936464dc0c3
f4f8ec5c50bf0411b31379f55b8365d9b82cb61e
/derived-class/重复继承.cpp
fe4a718c151f4a503e6f111d16b9b660e0953161
[]
no_license
xhbang/cpp-homework
388da7b07ddc296bf67d373c96b7ea134c42ef0c
fb9a21fef40ac042210b662964ca120998ac8bcf
refs/heads/master
2021-01-22T05:20:59.989600
2011-12-05T10:31:14
2011-12-05T10:31:14
2,915,735
0
0
null
null
null
null
UTF-8
C++
false
false
1,140
cpp
#include <iostream.h> class A{ int x; public: A(int i):x(i){ cout<<"A begin"<<endl; }; ~A(){ cout<<"A end"<<endl; } void show(){ cout<<"show A:"<<x<<endl; } }; class B1:public A{ int x; public: B1(int i,int j):A(i){ cout<<"B1 begin"<<endl; x=j; } ~B1(){ cout<<"B end"<<endl; } void show(){ // A.show(); cout<<"x in B1"<<x<<endl; } void showA(){ A::show(); } }; class B2:public A{ int x; public: B2(int i,int j):A(i){ cout<<"B2 begin"<<endl; x=j; } ~B2(){ cout<<"B2 end"<<endl; } void show(){ // A.show(); cout<<"x in B2"<<x<<endl; } void showA(){ A::show(); } }; class C:public B1,public B2{ int x; public: C(int i,int j,int k,int p):B1(i,j),B2(j,k){ x=p; cout<<"C begin"<<endl; } ~C(){ cout<<"C end"<<endl; } void show(){ cout<<"x in C"<<x<<endl; } }; int main(){ C c(100,200,300,400); c.show(); c.B1::show(); c.B2::show(); //way1,using pointer A *p=(A*)(B1 *)&c; p->show(); cout<<endl; //way2,:: c.B1::showA(); c.B2::showA(); return 0; }
[ [ [ 1, 100 ] ] ]
1953be83ae495a327bc449961c317d0306b47dec
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestfontinput/src/bctestfontinputdocument.cpp
e2d283bd959160839e214adfd500bdbb755eb091
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
2,245
cpp
/* * Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Avkon FontInput test application * */ // INCLUDE FILES #include "BCTestfontinputDocument.h" #include "BCTestfontinputAppUi.h" // ================= MEMBER FUNCTIONS ========================================= // ---------------------------------------------------------------------------- // CBCTestfontinputDocument* CBCTestfontinputDocument::NewL( CEikApplication& ) // Symbian OS two-phased constructor. // ---------------------------------------------------------------------------- // CBCTestFontInputDocument* CBCTestFontInputDocument::NewL( CEikApplication& aApp ) { CBCTestFontInputDocument* self = new( ELeave ) CBCTestFontInputDocument( aApp ); return self; } // ---------------------------------------------------------------------------- // CBCTestFontInputDocument::~CBCTestFontInputDocument() // Destructor. // ---------------------------------------------------------------------------- // CBCTestFontInputDocument::~CBCTestFontInputDocument() { } // ---------------------------------------------------------------------------- // CBCTestFontInputDocument::CBCTestFontInputDocument( CEikApplication& ) // Overload constructor. // ---------------------------------------------------------------------------- // CBCTestFontInputDocument::CBCTestFontInputDocument( CEikApplication& aApp ) :CEikDocument( aApp ) { } // ---------------------------------------------------------------------------- // CEikAppUi* CBCTestFontInputDocument::CreateAppUiL() // Constructs CBCTestVolumeAppUi. // ---------------------------------------------------------------------------- // CEikAppUi* CBCTestFontInputDocument::CreateAppUiL() { return new( ELeave ) CBCTestFontInputAppUi; } // End of File
[ "none@none" ]
[ [ [ 1, 65 ] ] ]
d5fdf530ac0781a913db122cbfc852e215e3f8bd
f177b64040f6e70ff885ca6911babf647103ddaa
/source/main.cpp
931456b2f4e3cb6e6e11ed65be1038656883fb50
[]
no_license
xflash/redraid
b7b662853a09e529e20b5ceee74b4f51ba6d6689
1d6b010bbadc2586232ec92df99be7ec49adb43d
refs/heads/master
2016-09-10T03:57:18.746840
2008-06-07T16:11:18
2008-06-07T16:11:18
32,315,933
0
0
null
null
null
null
UTF-8
C++
false
false
80
cpp
#include "RedRaid.h" int main() { RedRaid g; g.run(); return 0; }
[ "rcoqueugniot@c32521c4-154f-0410-b136-dfa89fbbf926" ]
[ [ [ 1, 8 ] ] ]
f110d4290fb1f9a29c0575ac2a792f21528b894e
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Plugins/Plugin_AwesomiumWidget/Plugin.cpp
2271fef8e0e746aaaf2ebb5201a9e1d9bf722ae0
[]
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
WINDOWS-1251
C++
false
false
1,222
cpp
/*! @file @author Albert Semenov @date 10/2009 */ #include "Plugin.h" #include "MyGUI_LogManager.h" #include "MyGUI_PluginManager.h" namespace plugin { const std::string Plugin::LogSection = "Plugin"; Plugin::Plugin() : mFactory(0) { } Plugin::~Plugin() { } void Plugin::install() { } void Plugin::uninstall() { } void Plugin::initialize() { MYGUI_LOGGING(LogSection, Info, "initialize"); // создаем фабрики mFactory = new Awesomium::AwesomiumWidgetFactory(); } void Plugin::shutdown() { MYGUI_LOGGING(LogSection, Info, "shutdown"); // удаляем фабрику delete mFactory; mFactory = 0; } const std::string& Plugin::getName() const { static std::string type("Plugin"); return type; } } // namespace plugin plugin::Plugin* plugin_item = 0; extern "C" MYGUI_EXPORT_DLL void dllStartPlugin(void) { plugin_item = new plugin::Plugin(); MyGUI::PluginManager::getInstance().installPlugin(plugin_item); } extern "C" MYGUI_EXPORT_DLL void dllStopPlugin(void) { MyGUI::PluginManager::getInstance().uninstallPlugin(plugin_item); delete plugin_item; plugin_item = 0; }
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 72 ] ] ]
120fc7a8a0b140ca88b4e639fca4505dcae16ba4
8a271e88a59baa915c5ef498b755610b94a4028a
/src/Shape.cpp
15bdf3e59ae55bea6ec099a56954b87e59b31f2a
[]
no_license
maburgess/kDFA
372824dc2a7c5ad6a745f3f9fa49117a383c1284
ae16671a4d55b96dbc217cb7a3386ff77833b364
refs/heads/master
2020-12-25T16:25:39.085168
2011-07-19T19:49:21
2011-07-19T19:49:21
2,072,795
0
0
null
null
null
null
UTF-8
C++
false
false
43,548
cpp
#include "Shape.h" //#define DEBUG Shape::Shape() { name=""; type=""; firstDist=0; surfRelaxDist=0; firstPos=0; nextShape=0; maxShell=0; diffPatt=0; /* try{ diffPatt=new Pattern* [Pattern::nLambda]; for (int i=0;i<Pattern::nLambda;i++){ diffPatt[i]=new Pattern(shape); } } catch (exception& e){ printf("\nException found in Shape diffPatt initialization: %s\n", e.what()); }*/ element=""; a=0; nParams_a=0; a_D=0; wShape=0; mu=0; sigma=0; alpha=0; beta=0; f=0; kappa=0; n_R=0; wShell=0; nRelaxShells=0; derivSRD_mu=0; derivSRD_sig=0; distribution=""; deltaSize=0; p=0; dW_mu=0; dW_sig=0; endSize=0; posPath=""; distPath=""; D=0; nA_D=0; nAtoms=0; preCalcPatts=0; nPreCalcPatts=0; } Shape::~Shape(void) { delete surfRelaxDist; if (diffPatt){ for (int i=0;i<Pattern::nLambda; i++){ delete diffPatt[i]; } delete [] diffPatt; } delete [] wShell; delete [] p; delete [] dW_mu; delete [] dW_sig; if (a){ if (!(a[0]->global)){ for (int i=0;i<nParams_a; i++){ delete a[i]; } delete [] a; } } delete wShape; //NOTE: when adding a global parameter deallocate it in ~Compare() if (mu){ if (!mu->global){ delete mu; } } if (sigma){ if (!sigma->global){ delete sigma; } } if (alpha){ if (!alpha->global){ delete alpha; } } if (beta){ if (!beta->global){ delete beta; } } if (f){ if (!f->global){ delete f; } } if (kappa){ if (!kappa->global){ delete kappa; } } if (n_R){ if (!n_R->global){ delete n_R; } } if (deltaSize){ if (!deltaSize->global){ delete deltaSize; } } delete [] D; delete [] a_D; delete [] nA_D; if (preCalcPatts){ for (int i=0;i<nPreCalcPatts;i++){ if (preCalcPatts[i]){ //for (int j=0;j<Pattern::nLambda;j++){ // delete preCalcPatts[i][j]; //} delete [] preCalcPatts[i]; } } delete [] preCalcPatts; } } int Shape::LoadPositions() { //TODO Change so that function kills program in the case of errors int err=0; Position *curPos, *prevPos=0; ifstream posfiles; string temp=posPath+"positionFiles.txt"; posfiles.open(temp.c_str()); if(posfiles.is_open()){ printf("Reading position files for shape %s ...\n", name.c_str()); int count=1; while(!posfiles.eof()){ posfiles >> temp; if (!posfiles.eof()){ curPos = new Position(const_cast<char *>(temp.c_str())); if (firstPos==0){ firstPos=curPos; prevPos=curPos; } else{ if (prevPos){ prevPos->nextPos=curPos; prevPos=curPos; } } err=curPos->ReadPosFile(); curPos->shell=count; maxShell=getmax(maxShell,curPos->shell); if (err!=0) { printf("Could not open position file: %s", temp.c_str()); return -1; } count++; } } posfiles.close(); } else{ printf("Error: Cannot find list of position files %s\n", temp.c_str()); return -1; } printf("MaxShell: %i\n",maxShell); //Check to max sure pos files of all shells are found and sort linked list /* //TODO Below is pointless because pos->shell is given counter above in loop int shell, place, missing=0; Position *orderPos; orderPos=firstPos; for (shell=1;shell<=maxShell;shell++){ curPos=orderPos; prevPos=orderPos; if (orderPos==firstPos) place=1+missing; else place=orderPos->shell+missing; flag=false; while(curPos!=0&&!flag) { if (curPos->shell==shell){ flag=true; if(place!=shell){ prevPos->nextPos=curPos->nextPos; if (shell==1){ curPos->nextPos=firstPos; firstPos=curPos; } else{ curPos->nextPos=orderPos->nextPos; orderPos->nextPos=curPos; } } orderPos=curPos; } prevPos=curPos; curPos=curPos->nextPos; place++; } if (!flag){ printf("Position file for shell %i is missing", shell); err=-1; missing++; } } */ return err; } void Shape::LoadDistances() { int nDist=0; Distance *curDist, *prevDist=0; ifstream distfiles; string temp=distPath+"distanceFiles.txt"; distfiles.open(temp.c_str()); if(distfiles.is_open()){ printf("Reading distance files for shape %s ...\n", name.c_str()); while(!distfiles.eof()){ distfiles >> temp; if (!distfiles.eof()){ curDist = new Distance(const_cast<char *>(temp.c_str())); if (firstDist==0){ firstDist=curDist; } else{ if (prevDist){ prevDist->nextDist=curDist; } } prevDist=curDist; curDist->ReadDistFile(); nDist++; } } distfiles.close(); } else{ printf("Could not find list of distance files: %s\n", temp.c_str()); exit(1); } curDist=firstDist; int maxDistShell=0; for (int i=0;i<nDist;i++){ maxDistShell=getmax(curDist->shell,maxDistShell); curDist=curDist->nextDist; } if (maxDistShell>maxShell){ cout<<"Error: maximum distance shell is larger than maximum position shell for shape: "<< name<<endl; } else{ maxDistShell=getmax(maxDistShell,maxShell); } //Init ordered list Distance **orderedDistList=new Distance * [maxDistShell]; for (int i=0; i<maxDistShell; i++){ orderedDistList[i]=0; } //Fill in already existing distances curDist=firstDist; for (int i=0; i<nDist; i++){ orderedDistList[curDist->shell-1]=curDist; curDist=curDist->nextDist; } //Find missing distances, calculate and output them string prefix="distances."+type+"Shell", suffix=".debye"; for (int i=0;i<maxDistShell;i++){ if (orderedDistList[i]==0){ int shell=i+1; printf("Distance file for shell %i is missing\n", shell); ostringstream num; num<<shell; string filename=prefix+num.str()+suffix; orderedDistList[i]= new Distance(); orderedDistList[i]->fileName=filename; orderedDistList[i]->shell=shell; CalcDistForShell(orderedDistList[i]); #define OUTDIST #ifdef OUTDIST orderedDistList[i]->OutputDistToFile(distPath, type); printf("Distance file calculated for shell %i\n",shell); #endif } } //Rebuild Linked List firstDist=orderedDistList[0]; curDist=firstDist; for (int i=1;i<maxDistShell;i++){ curDist->nextDist=orderedDistList[i]; curDist=curDist->nextDist; } curDist->nextDist=0; delete [] orderedDistList; } void Shape::FindPreCalcPatts() { //Allocate the precalculated intensity array nPreCalcPatts=GetNumSizes(); try{ preCalcPatts=new Pattern *[nPreCalcPatts]; for (int i=0;i<nPreCalcPatts;i++){ preCalcPatts[i]=0; } } catch(exception &e){ cout<<"Error: exception in LoadPatterns()"<<e.what()<<endl; exit(0); } // Read the precalculated patterns and compare with the existing positions ifstream pattfiles; string temp=pattPath+"intensityFiles.txt"; pattfiles.open(temp.c_str()); if(pattfiles.is_open()){ printf("Reading intensity files for shape %s ...\n", name.c_str()); while(!pattfiles.eof()){ pattfiles >> temp; if (!pattfiles.eof()){ int intShell=0; ifstream calcedPatt; //Read the shellSize from the first line of the intensity file calcedPatt.open(temp.c_str()); if (calcedPatt.is_open()){ string firstLine; getline(calcedPatt, firstLine); stringstream test(firstLine); while (!test.eof()){ string stuff; test>>stuff; if (stuff=="shell:"){ test>>intShell; } } calcedPatt.close(); } else{ cout<<"Warning: Unable to open intensity file: "<<temp<<endl; } if (intShell!=0){ int intIndex=GetIndexOfShell(intShell); if (intIndex>=0){ //Allocate and Load Intensity try{ preCalcPatts[intIndex]=new Pattern [Pattern::nLambda]; } catch(exception &e){ cout<<"Error: exception in LoadPatterns()"<<e.what()<<endl; exit(1); } for (int i=0;i<Pattern::nLambda;i++){ preCalcPatts[intIndex][i].fileName=temp; preCalcPatts[intIndex][i].shellIndex=intIndex; //preCalcPatts[intIndex][i].LoadIntFromFile(temp, i); } } else{ cout<<"Warning: Positions of shell "<<intShell<<" are not loaded..."<<endl; cout<<"Ignoring intensity file: "<<temp<<endl; } } else{ cout<<"Warning: Unable to determine shell size of intensity from file: "<<temp<<endl; cout<<"Check file format."<<endl; } } } pattfiles.close(); } } void Shape::LoadPatterns() { for (int i=0;i<nPreCalcPatts;i++){ if (preCalcPatts[i]!=0){ //NOTE: Need to have the lattice parameter determined for a given size before loading patterns. double aD=a_D[preCalcPatts[i][0].shellIndex]; LoadIntFromFile(preCalcPatts[i], aD); } } } void Shape::CheckPreCalcPatts() { //Check list of intensities and calculate necessary intensities for (int i=0;i<nPreCalcPatts;i++){ if (preCalcPatts[i]==0){ //Call routine to calculate the intensity // The x-axis must be in terms of q*a (dimensionless) } } } /* int Shape::InitParamBounds() { int err=0; if (wShape->val==-1) err=-1; wShape->name=name+"Weight"; wShape->min=0; wShape->max=1; wShape->global=false; if (a[0]->val==-1) err=-1; if (a[0]->min==-1) a[0]->min=0; if (a[0]->max==-1) a[0]->max=10; // Want to rewrite this to calc min and max given the range of shell sizes if (distribution=="LogNorm"){ if (mu->val==-1) err=-1; if (mu->min==-1) mu->min=-1000; if (mu->max==-1) mu->max=1000; if (sigma->val==-1) err=-1; if (sigma->min==-1) sigma->min=0; if (sigma->max==-1) sigma->max=1000; } // Not sure that kappa has no real bounds, need to look into it some more. if (f->val==-1) err=-1; if (f->min==-1) f->min=0; if (f->max==-1) f->max=1; if (kappa->val==-1) err=-1; if (kappa->min==-1) kappa->min=0; if (kappa->max==-1) kappa->max=1000; if (err==-1) printf("Parameter not initalized for shape %s\n",name.c_str()); return err; } */ /* int Shape::SurfaceRelaxation(double *derivfSize_mu, double *derivfSize_sig) { Currently not used and needs some work before use!! int i,j, k,err=0; printf("Calculating surface relaxation for %s\n", shape.c_str()); //Initialize temp surface relax position files Position **surfRelaxPos=0; Distance *tempSRDist=0; surfRelaxPos=(Position**) malloc(nRelaxShells*sizeof(Position*)); if (surfRelaxPos==0) err=-1; //for (i=0;i<nRelaxShells&&!err;i++){ surfRelaxPos[i] = new Position(); if (surfRelaxPos[i]!=0){ surfRelaxPos[i]->f=f->val; surfRelaxPos[i]->kappa=kappa->val; } else err=-1; } //Initlaize surface relax distance files if (!err){ tempSRDist = new Distance (); if (tempSRDist==0) err=-1; } if (!err){ if (surfRelaxDist==0) surfRelaxDist= new Distance(); if (surfRelaxDist==0) err=-1; } if (!err) InitSRDistance(*tempSRDist); if (!err) InitSRDistance(*surfRelaxDist); if (derivSRD_mu==0&&!err) derivSRD_mu=new Distance(); if (derivSRD_sig==0&&!err) derivSRD_sig=new Distance(); if (derivSRD_mu==0||derivSRD_sig==0) err=-1; if (!err) err=InitSRDistance(*derivSRD_mu); if (!err) err=InitSRDistance(*derivSRD_sig); int startSize=1; if (!err){ if (distribution=="LogNorm"){ // if (startSize<1||endSize>maxShell){ printf("Needed range of Prob function is not possible with given distances\n"); err=-1; } } else if (distribution=="Delta"){ startSize=size; endSize=startSize; } } //calculate SR and distances for this shape Position **posPlaceHold=(Position **) malloc(nRelaxShells*sizeof(Position*)); for (i=0;i<nRelaxShells&&!err;i++){ if (posPlaceHold) posPlaceHold[i]=firstPos; else {printf("Error in memory allocation in Surface Relaxation function\n"); err=-1;} surfRelaxPos[i]= new Position(); } for (i=startSize; i<=endSize&&!err; i++){ if (distribution=="LogNorm"){ for (j=0;j<nRelaxShells && j<i && !err;j++){ //if (surfRelaxPos[j]->nAtoms==0) err=CopyPosition(surfRelaxPos[j], firstPos); //else err=CopyPosition(surfRelaxPos[j], surfRelaxPos[j]->nextPos); if (surfRelaxPos[j]!=0){ err=CopyPosition(*surfRelaxPos[j],posPlaceHold[j]); } else err=-1; if (!err) surfRelaxPos[j]->ApplyPlanarSurfaceRelax(i); else{ printf("Error in Surface Relaxation position memory allocation\n"); err=-1; } } } else if (distribution=="Delta"){ Position *tempPos=firstPos; for (j=0;j<size-nRelaxShells; j++) tempPos=tempPos->nextPos; for (j=nRelaxShells-1; j>=0&&!err; j--){ err=CopyPosition(*surfRelaxPos[j], tempPos); if (!err){ surfRelaxPos[j]->ApplyPlanarSurfaceRelax(i); tempPos=tempPos->nextPos; } else{ printf("Error in Surface Relaxation position memory allocation\n"); err=-1; } } } if (!err){ Position *curPos; for (j=0;j<nRelaxShells && j<i;j++){ curPos=firstPos; // for each relaxed shell calc distances between other relaxed shells for (k=j;k<nRelaxShells&&k<i;k++){ //Need to check that this produces correct results tempSRDist->DebbyCalcSums(surfRelaxPos[j]->x,surfRelaxPos[j]->y,surfRelaxPos[j]->z, surfRelaxPos[j]->nAtoms, surfRelaxPos[k]->x, surfRelaxPos[k]->y, surfRelaxPos[k]->z, surfRelaxPos[k]->nAtoms, tempSRDist->mult, SRPREC, tempSRDist->nDist, j==k, 0); } // for each relaxed shell calc distances between core shells for (k=0;k<i-nRelaxShells;k++){ tempSRDist->DebbyCalcSums(surfRelaxPos[j]->x,surfRelaxPos[j]->y,surfRelaxPos[j]->z, surfRelaxPos[j]->nAtoms, curPos->x, curPos->y, curPos->z, curPos->nAtoms, tempSRDist->mult, SRPREC, tempSRDist->nDist, false, 0); curPos=curPos->nextPos; } } // For each size weight the mult by the size distribution int startind=0; if (surfRelaxDist->dist[0]==0){ surfRelaxDist->mult[0]+=p[i-1]*tempSRDist->mult[0]; derivSRD_mu->mult[0]+=derivfSize_mu[i-1]*tempSRDist->mult[0]; derivSRD_sig->mult[0]+=derivfSize_sig[i-1]*tempSRDist->mult[0]; tempSRDist->mult[0]=0; startind++; } for (j=startind;j<tempSRDist->nDist;j++){ surfRelaxDist->mult[j]+=2*p[i-1]*tempSRDist->mult[j]; derivSRD_mu->mult[j]+=2*derivfSize_mu[i-1]*tempSRDist->mult[j]; derivSRD_sig->mult[j]+=2*derivfSize_sig[i-1]*tempSRDist->mult[j]; tempSRDist->mult[j]=0; } //memset(tempSRDist->mult, 0, tempSRDist->nDist*sizeof(double)); } for (j=0; j<nRelaxShells&&j<i;j++){ posPlaceHold[j]=posPlaceHold[j]->nextPos; } } // Consolidate the relaxation distances if (!err){ surfRelaxDist->ConsolidateDistance(); derivSRD_mu->ConsolidateDistance(); derivSRD_sig->ConsolidateDistance(); } return err; } */ // Working on this function //TODO Debug SurfaceRelaxation int Shape::SurfaceRelaxation(Distance *totSRDist) { int err=0, startSize=1, startind=0; Position *curPos; Position **surfRelaxPos, **posPlaceHold; Distance *tempSRDist; #ifdef DEBUG cout<<"Entering SurfaceRelaxation\n"; #endif //Initialize temp surface relax position files try{ surfRelaxPos=new Position* [nRelaxShells]; for (int i=0;i<nRelaxShells;i++) surfRelaxPos[i]=new Position(); posPlaceHold = new Position* [nRelaxShells]; tempSRDist = new Distance(); } catch (exception& e){ printf("\nException found in SurfaceRelaxation alloc: %s\n", e.what()); exit(1); } //Initialize surface relax distance files InitSRDistance(tempSRDist); InitSRDistance(totSRDist); //Change startSize if (distribution=="LogNorm"||distribution=="Gamma"){ /* //startSize=floor(exp(mu->val-3*sig->val)/GetShapeScaleFactor()); startSize=1; if (startSize<1||endSize>maxShell){ printf("Needed range of Prob function is not possible with given distances\n"); err=-1; } */ } else if (distribution=="Delta"){ int shell= CalcDeltaShellSize(); if (shell==-1){ //Do not calculate SR in this case cout<<"Not Calculating SurfaceRelaxation, Delta size not supported.\n"; startSize=1; endSize=startSize-1; } else{ startSize=shell; } } else{ cout<< "Size Distribution: "<<distribution<<" is not supported in Surface Relaxation.\n"; err=-1; } //calculate SR and distances for this shape printf("Calculating surface relaxation for %s\n", name.c_str()); //Initialize place holder for (int i=0;i<nRelaxShells;i++) posPlaceHold[i]=firstPos; //Copy positions and Apply surface relax for (int i=startSize; i<=endSize&&!err; i++){ startind=0; if (distribution=="LogNorm"||distribution=="Gamma"){ for (int j=0;j<nRelaxShells && j<i && !err;j++){ CopyPosition(surfRelaxPos[j],posPlaceHold[j]); if (type=="sphere"||type=="sphere_Cerv"){ // surfRelaxPos[j]->ApplyPlanarSurfaceRelax(i, f->val, kappa->val);//surfRelaxPos[j]->ApplyRadialSurfaceRelax(i, GetShapeScaleFactor()/(2.0*a->val)); if (n_R==0){ surfRelaxPos[j]->ApplyNormExpRadialSurfRelax(i, f->GetVal(), kappa->GetVal(), GetShapeShellD()*10.0/2.0); } else{ surfRelaxPos[j]->ApplyNormOscExpRadialSurfRelax(i, f->GetVal(), kappa->GetVal(), n_R->GetVal(), GetShapeShellD()*10.0/2.0); } } else surfRelaxPos[j]->ApplyPlanarSurfaceRelax(i, f->GetVal(), kappa->GetVal()); surfRelaxPos[j]->ScalePos(a_D[i-1]); } } //Not Tested yet!! else if (distribution=="Delta"){ Position *tempPos=firstPos; int shell= CalcDeltaShellSize(); for (int j=0;j<shell-nRelaxShells; j++) tempPos=tempPos->nextPos; //for (int j=nRelaxShells-1; j>=0&&!err; j--){ for (int j=0;j<nRelaxShells&&!err;j++){ CopyPosition(surfRelaxPos[j], tempPos); if (type=="sphere"||type=="sphere_Cerv"){ if (n_R==0){ surfRelaxPos[j]->ApplyNormExpRadialSurfRelax(i, f->GetVal(), kappa->GetVal(), GetShapeShellD()*10.0/2.0); } else{ surfRelaxPos[j]->ApplyNormOscExpRadialSurfRelax(i, f->GetVal(), kappa->GetVal(), n_R->GetVal(), GetShapeShellD()*10.0/2.0); } } else surfRelaxPos[j]->ApplyPlanarSurfaceRelax(i, f->GetVal(), kappa->GetVal()); surfRelaxPos[j]->ScalePos(a_D[i-1]); tempPos=tempPos->nextPos; } } else{ cout<<"\nERROR in SurfaceRelaxation()\n"; err=-1; } //Calculate distances including surface relax shells if (!err){ for (int j=0;j<nRelaxShells && j<i;j++){ curPos=firstPos; // for each relaxed shell calc distances between other relaxed shells for (int k=j;k<nRelaxShells&&k<i;k++){ tempSRDist->DebbyCalcSums(surfRelaxPos[j]->x,surfRelaxPos[j]->y,surfRelaxPos[j]->z, surfRelaxPos[j]->nAtoms, surfRelaxPos[k]->x, surfRelaxPos[k]->y, surfRelaxPos[k]->z, surfRelaxPos[k]->nAtoms, tempSRDist->mult, float(SRPREC), tempSRDist->nDist, j==k, 0); } // for each relaxed shell calc distances between core shells for (int k=0;k<i-nRelaxShells;k++){ Position tempPos; CopyPosition(&tempPos, curPos); //Scale position so can use a(D) and surface relax at same time. tempPos.ScalePos(a_D[i-1]); tempSRDist->DebbyCalcSums(surfRelaxPos[j]->x,surfRelaxPos[j]->y,surfRelaxPos[j]->z, surfRelaxPos[j]->nAtoms, tempPos.x, tempPos.y, tempPos.z, tempPos.nAtoms, tempSRDist->mult, float(SRPREC), tempSRDist->nDist, false, 0); curPos=curPos->nextPos; } } // For each size weight the mult by the size distribution if (totSRDist->dist[0]==0){ totSRDist->mult[0]+=p[i-1]*tempSRDist->mult[0]; tempSRDist->mult[0]=0; startind=1; } for (int j=startind;j<tempSRDist->nDist;j++){ totSRDist->mult[j]+=2*p[i-1]*tempSRDist->mult[j]; tempSRDist->mult[j]=0; } } //Increase placeholder will not increase more holders than there are shells for the given size for (int j=0; j<nRelaxShells&& j<i;j++){ posPlaceHold[j]=posPlaceHold[j]->nextPos; } } // Consolidate the relaxation distances if (!err){ totSRDist->ConsolidateDistance(); } delete tempSRDist; for (int i=0;i<nRelaxShells;i++) delete surfRelaxPos[i]; delete [] surfRelaxPos; delete [] posPlaceHold; return err; } //Problem in release mode!! void Shape::CopyPosition(Position* to, Position* from) { to->nAtoms=from->nAtoms; to->shell= from->shell; to->nextPos=from->nextPos; if (to->x!=0) _mm_free (to->x); to->x= (float *) _mm_malloc (to->nAtoms*sizeof(float),16); if (to->y!=0) _mm_free (to->y); to->y= (float *) _mm_malloc (to->nAtoms*sizeof(float),16); if (to->z!=0) _mm_free (to->z); to->z= (float *) _mm_malloc (to->nAtoms*sizeof(float),16); if (to->x==0||to->y==0||to->z==0){ printf("\nException found in CopyPosition alloc: error in aligned memory alloc\n"); exit(1); } for (int i=0;i<to->nAtoms;i++){ to->x[i]=from->x[i]; to->y[i]=from->y[i]; to->z[i]=from->z[i]; } } void Shape::CopyDistance(Distance * to, Distance *from) { to->f=from->f; to->kappa=from->kappa; to->fileName=from->fileName; to->shell=from->shell; to->nDist=from->nDist; try{ if (to->dist){ delete [] to->dist; } if (to->mult){ delete [] to->mult; } to->dist=new double [to->nDist]; to->mult=new double [to->nDist]; } catch(exception &e){ cout<<"Error in CopyDistance: "<<e.what()<<endl; exit(-1); } for (int i=0;i<to->nDist;i++){ to->dist[i]=from->dist[i]; to->mult[i]=from->mult[i]; } } void Shape::InitSRDistance(Distance *currSRDist) { double maxDistSq, maxDist; double delD=GetShapeShellD()*10/2.0; Distance *currDist=firstDist; for (int i=0;i<endSize-1;i++) currDist=currDist->nextDist; if (currDist->shell==endSize){ maxDist=currDist->dist[currDist->nDist-1]; maxDist/=2.0; maxDist=2*sqrt(maxDist*maxDist+2*f->GetVal()*delD*maxDist+f->GetVal()*f->GetVal()*delD*delD); //Scale by lattice parameter so can use a_D with SR. maxDist*=a_D[endSize-1]; } else { printf("Error in finding maxDist for InitSRDistance\n"); exit(0); } maxDistSq=(maxDist+2)*(maxDist+2); currSRDist->InitDistance((int)(ceil(maxDistSq/SRPREC))); } // TODO make recalculation of diffraction pattern slightly more efficient by using preloaded intensities // As long as lattice param has not changed. int Shape::CalcPattern() { int err=0; if (!diffPatt){ try{ diffPatt=new Pattern* [Pattern::nLambda]; for (int i=0;i<Pattern::nLambda;i++){ diffPatt[i]=new Pattern(name); } } catch (exception& e){ printf("\nException found in Shape diffPatt initialization: %s\n", e.what()); return -1; } } // Initialize lattice parameter for different size particles InitLatticeParam(); // Initialize the size distribution CalcSizeDistribution(); // Load any pre-calculated intensities from file if (nPreCalcPatts>0){ LoadPatterns(); } // Calculated then number of SurfaceRelaxation shells and the wieghts of each shell nRelaxShells=GetNumSRShells(); CalcShellWeights(); cout<<"maxShell: " <<maxShell<<" nRelaxShells: "<<nRelaxShells<<endl; // Calculate the SurfaceRelaxation distances if (nRelaxShells>0){ if (surfRelaxDist==0){ try{ surfRelaxDist=new Distance(); } catch (exception& e){ printf("\nException found in Shape->CalcPattern: %s\n", e.what()); exit(1); } } err=SurfaceRelaxation(surfRelaxDist); } else { if (surfRelaxDist!=0){ delete surfRelaxDist; surfRelaxDist=0; } } if (!err){ //Calc pattern for each lambda for (int j=0;j<Pattern::nLambda&&!err;j++){ if(preCalcPatts==0){ //Routines to use when preCalculated patterns are NOT loaded. if (nParams_a>1){ //Calculates for each size separately, scaling by a(D) diffPatt[j]->CalcPattern(firstDist,endSize, p, a_D, nRelaxShells, surfRelaxDist, j); } else{ //Faster when only using constant lattice parameter because using wShell diffPatt[j]->CalcPattern(firstDist, endSize, wShell, a[0]->GetVal(), surfRelaxDist, j); } } else{ //Routine to use when precalculated patterns are loaded. diffPatt[j]->CalcPattern(firstDist,endSize, p, a_D, nRelaxShells, surfRelaxDist, j, preCalcPatts); } } } return err; } //"Diameters" of shapes double Shape::GetShapeShellD() { //Returns the maximum distance stepping for a given shape. //Currently unitless. //when multiplied by the lattice parameter in Ang,=>D(nm) if (type=="tetrahedron") return (2*sqrt(2.0)/10.0); else if (type=="octahedron") return (2/10.0); else if (type=="cuboctahedron") return (sqrt(2.0)/10.0); else if (type=="cube") return (sqrt(3.0)/10.0); else if (type=="sphere") return (sqrt(2.0)/10.0);//NN Def else if (type=="sphere_Cerv") return (.7815926418);//Cerv Def else if (type=="sphereDefFaultAtCenter") return (sqrt(2.0)/10.0); else if (type=="sphereTwinAtCenter") return (sqrt(2.0)/10.0); else if (type=="cuboid1x1_1x1_21") return (sqrt(3.31)/10.0); else if (type=="cuboid1x1_2x1_44") return (sqrt(3.64)/10.0); else if (type=="icosahedron") return (sqrt(2.0)*(0.95105)*(1.05146)/10.0); else if (type=="decahedron") return (sqrt(2.0)*(0.8506508)/10.0); else if (type=="centroDecahedron") return (2*sqrt(2.0)*(0.8506508)/10.0); else return 0; } //"Edge Lengths" of shapes double Shape::GetShapeShellL() { //Returns the maximum distance stepping for a given shape. //Currently unitless. //when multiplied by the lattice parameter =>D(units of a) if (type=="tetrahedron") return (2*sqrt(2.0)); else if (type=="octahedron") return ((sqrt(2.0))); else if (type=="cuboctahedron") return (1.0/(sqrt(2.0))); else if (type=="cube") return (1.0); else if (type=="sphere") return (sqrt(2.0));//NN Def else if (type=="sphereDefFaultAtCenter") return (sqrt(2.0)); else if (type=="sphereTwinAtCenter") return (sqrt(2.0)); else if (type=="cuboid1x1_1x1_21") return (1.0); else if (type=="cuboid1x1_2x1_44") return (1.0); else if (type=="icosahedron") return (1.05146/(sqrt(2.0))); else if (type=="decahedron") return (1.0/(sqrt(2.0))); else if (type=="centroDecahedron") return (sqrt(2.0)); //else if (type=="sphere_Cerv") return (.7815926418);//Cerv Def else return 0; } double Shape::CalcTotVol() { double vTot=0; int i; for (i=1;i<=maxShell; i++) { vTot+=p[i-1]*GetUnitlessVolume(i)*a_D[i-1]*a_D[i-1]*a_D[i-1]; } return vTot; } double Shape::GetUnitlessVolume(int n) { //Assume Lattice Parameter is unity //Actual volume is then (Unitless volume) * a^3 (units of a^3) double vol=0, sideLength=n*GetShapeShellL(); if (type=="tetrahedron"){ vol=sqrt(2.0)*sideLength*sideLength*sideLength/12.0; } else if (type =="octahedron"){ vol=sqrt(2.0)*sideLength*sideLength*sideLength/3.0; } else if (type=="cuboctahedron"){ vol=5*sqrt(2.0)*sideLength*sideLength*sideLength/3.0; } else if (type=="sphere"||type=="sphere_Cerv"||type=="sphereDefFaultAtCenter"||type=="sphereTwinAtCenter"){ vol=PI*sideLength*sideLength*sideLength/6.0; } else if (type=="cube"){ vol=sideLength*sideLength*sideLength; } else if (type=="cuboid1x1_1x1_21"){ vol=sideLength*1.1*sideLength*1.21*sideLength; } else if (type=="cuboid1x1_2x1_44"){ vol=sideLength*1.2*sideLength*1.44*sideLength; } else if (type=="icosahedron"){ vol=5*(3+sqrt(5.0))*sideLength*sideLength*sideLength/12.0; } else if (type=="decahedron"){ vol=(5+sqrt(5.0))*sideLength*sideLength*sideLength/12.0; } else if (type=="centroDecahedron"){ vol=(5+sqrt(5.0))*sideLength*sideLength*sideLength/12.0; } return vol; } void Shape::CalcNumAtoms() { Position *curPos=firstPos; if (!nA_D){ try{ nA_D=new int [maxShell]; } catch(exception &e){ cout<<"Exception found in Shape::GetNumAtoms: "<<e.what()<<endl; } for (int i=0;i<maxShell;i++){ nA_D[i]=0; } int total=0; for (int i=0;i<maxShell;i++){ total+=curPos->nAtoms; nA_D[i]=total; curPos=curPos->nextPos; } } nAtoms=0; for (int i=0;i<maxShell;i++){ nAtoms+=nA_D[i]*p[i]; } printf("Number of atoms: %f\n", nAtoms); } void Shape::CalcSizeDistribution() { if (!a_D){ cout<<"Error in CalcWeights: Lattice Parameter array is not initialized\n"; exit(0); } //Use lattice parameter in nanometers double *a_nm; try{ if (p){ delete [] p; } p = new double [maxShell]; a_nm = new double [maxShell]; } catch (exception &e){ cout<<"\nException found in CalcWeights: "<<e.what()<<endl; exit(1); } //Initialize arrays for (int i=0;i<maxShell;i++){ p[i]=0; a_nm[i]=a_D[i]/10.0; } //Check for Diameter Array if (!D) { InitDiameterArray(); } CheckShellThickness(); //Calculate probabilty distribution function (p[i]) if (distribution=="Delta") DeltaDist(&p[0]); else if(distribution=="LogNorm") LogNormalDist(&D[0], &p[0], &a_nm[0]); else if (distribution=="Gamma") GammaDist(&D[0], &p[0], &a_nm[0]); else { cout<<endl<<"Error: Unsupported Size distribution: "<<distribution<<endl; exit(0); } NormalizeSizeDistribution(); // Get endsize by looking at volume*weights CalcEndSize(); //Check Number of Surf Relax Shells. cout<<"Max size cutoff implied: "<<endSize<<endl; cout<<"Calculating shell weights for "<< name<<endl; try{ delete [] a_nm; } catch(exception &e){ cout<<"Error in CalcSizeDistributions: "<<e.what()<<"\n"; exit(1); } } void Shape::CalcShellWeights() { try{ if (wShell){ delete [] wShell; } wShell = new double [maxShell]; } catch (exception &e){ cout<<"\nException found in CalcWeights: "<<e.what()<<endl; exit(1); } for (int i=0;i<maxShell;i++){ wShell[i]=0; //Weights for shells without SR for (int j=i+nRelaxShells;j<endSize;j++){ wShell[i]+=p[j]; } } } void Shape::NormalizeSizeDistribution() { double tot=0; for (int i=0;i<maxShell; i++){ tot+=p[i]; } for (int i=0;i<maxShell; i++){ p[i]/=tot; } } int Shape::WriteIntFileHeader(string _fPath, string _fName) { int err=0; string filename=_fPath+_fName; ifstream infile; infile.open(filename.c_str()); if (infile.is_open()) printf("Intensity file %s exists.. Appending Header\n", _fName.c_str()); else printf("Creating Intensity file %s and writing header\n", _fName.c_str()); infile.close(); fstream file(filename.c_str(), ios_base::out|ios_base::app); //|ios_base::trunc); file.setf(ios::fixed, ios::floatfield); if (file.is_open()){ if (element!="") file<<"ELEM "; file<<"SHAPE A DISTRIBUTION "; if (distribution=="Delta") file<<"SHELLS "; else if (distribution=="LogNorm") file<<"MU SIGMA "; if (f!=0&&kappa!=0){ if (f->GetVal()!=0) file<<"SR_F SR_KAPPA "; } file<<"WEIGHT"; file<<endl; if(element!="") file<<element<<" "; file<<type<<" "<<a_D[maxShell-1]<<" "<<distribution<<" "; if (distribution=="Delta") file<<deltaSize->GetVal()<<" "; else if (distribution=="LogNorm") file<<mu->GetVal()<<" "<<sigma->GetVal()<<" "; if (f!=0&&kappa!=0){ if (f->GetVal()!=0) file<<f->GetVal()<<" "<<kappa->GetVal()<<" "; } file<<wShape->GetVal(); file<<endl; } else{ printf ("Error writing to file %s\n", filename.c_str()); err=-1; } file.close(); return err; } void Shape::CalcEndSize() { bool stop=false; int n=0; double *volWeightSizeDist, maxVal=0; Position *curPos=firstPos; try{ volWeightSizeDist=new double [maxShell]; } catch (exception& e){ printf("\nException found in CalcEndSize: %s\n", e.what()); exit(1); } for (int i=0;i<maxShell;i++){ n+=curPos->nAtoms; volWeightSizeDist[i]=p[i]*n; maxVal=getmax(maxVal, volWeightSizeDist[i]); curPos=curPos->nextPos; } endSize=maxShell; for (int i=(maxShell-1);i>=0&&!stop; i--) { if (volWeightSizeDist[i]<(.001*maxVal)){ endSize--; } else{ stop=true; } } delete [] volWeightSizeDist; } double Shape::GammLn(const double xx) { // Returns the value ln(Gamma(xx)) for xx>0 //Taken from Numerical Recipes 3rd Edition pg. 257 int j; double x, tmp, y, ser; static const double cof[14]={57.1562356658629235, -59.5979603554754912, 14.1360979747417471, -0.491913816097620199, .339946499848118887e-4, .465236289270485756e-4,-.983744753048795646e-4, .158088703224912494e-3, -.210264441724104883e-3, .217439618115212643e-3, -.164318106536763890e-3, .844182239838527433e-4, -.261908384015814087e-4, .368991826595316234e-5}; if (xx<0) throw("bad arg in GammLn"); y=x=xx; tmp = x+5.2421875000; tmp = (x+0.5)*log(tmp)-tmp; ser=0.999999999999997092; for (j=0;j<14;j++) ser+=cof[j]/++y; return tmp+log(2.5066282746310005*ser/x); } void Shape::GammaDist(double *d, double *P, double *scale) { //Param *alpha=0, *beta=0; if (!alpha||!beta){ cout<<"Uninitialized alpha and beta, cannot calculate Gamma distribution"<<endl; exit(0); } double delD=(d[1]-d[0]); if (delD==0){ cout<<"Error: shell diameter array in GammaDist"<<endl; exit(0); } double c1=alpha->GetVal()*log(beta->GetVal()), c2=GammLn(alpha->GetVal()); for(int i=0;i<maxShell; i++){ P[i]=c1-c2+(alpha->GetVal()-1)*log(d[i]*scale[i])-(beta->GetVal()*d[i]*scale[i]); P[i]=exp(P[i]); if (i==0){ delD=d[i]*scale[i]; } else{ delD=d[i]*scale[i]-d[i-1]*scale[i-1]; } P[i]*=delD; } } void Shape::LogNormalDist(double *d, double *P, double *scale) { if (!mu||!sigma){ cout<<"Uninitialized mu and sigma, cannot calculate Lognormal distribution"<<endl; exit(0); } double delD=(d[1]-d[0]); if (delD==0){ cout<<"Error: shell diameter array in LogNormalDist"<<endl; exit(0); } //For other shapes other than spheres Diameter is replaced by the characteristic size parameter (L) in the shape before any strain is applied. for (int i=0;i<maxShell;i++){ P[i]=exp(-(log(d[i]*scale[i])-mu->GetVal())*(log(d[i]*scale[i])-mu->GetVal())/(2*sigma->GetVal()*sigma->GetVal()))/(d[i]*scale[i]*sigma->GetVal()*sqrt(2*PI)); if (i==0){ delD=d[i]*scale[i]; } else{ delD=d[i]*scale[i]-d[i-1]*scale[i-1]; } P[i]*=delD; } } void Shape::DeltaDist(double *P) { int shell=CalcDeltaShellSize(); for (int i=0;i<maxShell;i++){ P[i]=0.0; } if (shell==-1){ cout<<"\nWARNING: Particle size "<<deltaSize->GetVal()<<" is not supported by Delta Distribution, setting all size probabilities to 0.\n"; } else{ //Adjust the particle size to a multiple of the shell thickness for clarity. deltaSize->ChangeVal(shell*a[0]->GetVal()*GetShapeShellL()); cout<<"Delta Size Set to: "<<deltaSize->GetVal()<<endl; P[shell-1]=1.0; } } void Shape::InitLatticeParam() { if (!a_D){ try{ a_D=new double [maxShell]; } catch(exception &e){ cout<<"Exception in InitLatticeParameter: "<<e.what()<<endl; exit(1); } } if (a[0]->name.find("Poly")!=string::npos){ PolynomialLatticeParam(); } else{ ConstantLatticeParam(); } } // Generates array of lattice parameter following polynomial a+bx+cx^2 // Diameter of sphere with equivalent volume is used a size parameter // This is so same lattice parmeter array can be applied to multiple shapes void Shape::PolynomialLatticeParam() { for (int i=0;i<maxShell;i++){ double d=exp(log(GetUnitlessVolume(i+1)*6/PI)/3.0); a_D[i]=a[0]->GetVal(); double temp=d; for (int j=1; j<nParams_a;j++){ a_D[i]+=a[j]->GetVal()*temp; temp*=d; } } } void Shape::ConstantLatticeParam() { for (int i=0;i<maxShell;i++){ a_D[i]=a[0]->GetVal(); } } // void Shape::InitDiameterArray() { try{ D=new double [maxShell]; } catch(exception &e){ cout<<"Exception found in InitDiameterArray: "<<e.what()<<endl; exit(0); } //double deltaD=GetShapeShellD(); double deltaD=GetShapeShellL(); if (!deltaD){ cout<<"Unrecognized shape name in GetShapeShellD: "<<name<<endl; exit(0); } for (int i=0;i<maxShell;i++){ D[i]=(i+1)*deltaD; } } void Shape::CalcDistForShell(Distance *curDist) { float minx=0, miny=0, minz=0, maxx=0, maxy=0, maxz=0; Position *outsideShell=firstPos; for (int i=1;i<curDist->shell;i++){ outsideShell=outsideShell->nextPos; } minx=outsideShell->x[0]; maxx=minx; miny=outsideShell->y[0]; maxy=miny; minz=outsideShell->z[0]; maxz=minz; for (int i=1;i<outsideShell->nAtoms;i++){ maxx=getmax(maxx,outsideShell->x[i]); minx=getmin(minx,outsideShell->x[i]); maxy=getmax(maxy,outsideShell->y[i]); miny=getmin(miny,outsideShell->y[i]); maxz=getmax(maxz,outsideShell->z[i]); minz=getmin(minz,outsideShell->z[i]); } if (type=="decahedron"){ Position *tempShell=firstPos; for (int j=1;j<curDist->shell-1;j++){ for (int i=1;i<tempShell->nAtoms;i++){ maxx=getmax(maxx,outsideShell->x[i]); minx=getmin(minx,outsideShell->x[i]); maxy=getmax(maxy,outsideShell->y[i]); miny=getmin(miny,outsideShell->y[i]); maxz=getmax(maxz,outsideShell->z[i]); minz=getmin(minz,outsideShell->z[i]); } tempShell=tempShell->nextPos; } } curDist->nDist=(int) ceil(((maxx-minx)*(maxx-minx)+(maxy-miny)*(maxy-miny)+(maxz-minz)*(maxz-minz))/DISTPREC)+1; try{ curDist->dist= new double [curDist->nDist]; curDist->mult=new double [curDist->nDist]; } catch (exception &e){ cout<<"Error in distance array memory allocation.\n"; exit(1); } for (int i=0;i<curDist->nDist;i++){ curDist->dist[i]=sqrt(i*DISTPREC); curDist->mult[i]=0; } Position *curPos=firstPos; for (int i=1;i<curDist->shell;i++){ curDist->DebbyCalcSums(curPos->x, curPos->y, curPos->z, curPos->nAtoms, outsideShell->x, outsideShell->y, outsideShell->z, outsideShell->nAtoms, curDist->mult, DISTPREC, curDist->nDist, false, 0); curPos=curPos->nextPos; } curDist->DebbyCalcSums(curPos->x, curPos->y, curPos->z, curPos->nAtoms, outsideShell->x, outsideShell->y, outsideShell->z, outsideShell->nAtoms, curDist->mult, DISTPREC, curDist->nDist, true, 0); curDist->ConsolidateDistance(); for (int i=1; i<curDist->nDist;i++ ){ curDist->mult[i]*=2.0; } } int Shape::GetNumSRShells() { // Determine if there is surface relaxation // Only apply to a shell if the amplitude is as large as the distance precision if (f!=0&&kappa!=0){ if (f->GetVal()!=0){ //TODO Check that this SR function is correct.. double shellT=GetShapeShellD()*10.0*a_D[maxShell-1]/2.0; if (shellT==0){ cout<<"Warning: Shape not supported in GetNumSRShells routine, using lattice parameter as shell thickness...\n"; shellT=a_D[maxShell-1]; } //int nSR=(int)ceil(kappa->GetVal()*log(shellT*abs(f->GetVal())/SRPREC)); //For now just calculate all shells int nSR=endSize; if (nSR>maxShell){ cout<<"Warning: surface relaxation extends throughout particle and does not go to zero at center. \n"; nSR=maxShell; } if (nRelaxShells>endSize){ nRelaxShells=endSize; cout<<"Number of Surf. Relax Shells is larger than largest considered particle..\n"; cout<<"Setting Number of Surf. Relax Shells to: "<<nRelaxShells<<endl; } else if (nSR<2){ cout<<"Warning: number of surface relaxation shells <2 !!!!"<<endl; cout<<"Setting number of surface relaxation shells = 2\n"; nSR=2; } else{ cout<<"Number of Surface Relaxed Shells = "<<nSR<<endl; } return nSR; //return (int)ceil(-kappa->GetVal()*log(SRPREC)); } else { cout<<"No Surface Relaxation applied (f=0)\n"; return 0; } } else{ cout<<"No Surface Relaxation applied (f and/or kappa are uninitialized).\n"; return 0; } } void Shape::CheckSupportedShapes() { if (type=="tetrahedron") ; else if (type=="cuboctahedron") ; else if (type=="octahedron") ; else if (type=="sphere") ; else if (type=="sphere_Cerv") ; else if (type=="cube") ; else if (type=="sphereDefFaultAtCenter") ; else if (type=="sphereTwinAtCenter") ; else if (type=="cuboid1x1_1x1_21") ; else if (type=="cuboid1x1_2x1_44") ; else if (type=="icosahedron") ; else if (type=="decahedron") ; else if (type=="centroDecahedron") ; else { cout<<"Unsupported Shape Type: "<<type<<endl; exit(0); } } void Shape::CheckShellThickness() { for (int i=1;i<maxShell;i++){ if ((D[i]*a_D[i])<(D[i-1]*a_D[i-1])){ cout<<"Error in Shape::CheckShellThickness(), lattice parameter results in negative shell thickness. "<<i<<endl; exit(0); } } } int Shape::CalcDeltaShellSize() { //Assuming that lattice parameter is independent of size. double N=deltaSize->GetVal()/(a[0]->GetVal()*GetShapeShellL()); //Consider +/- 0.5 int shell=getmax((int)N, (int)(N+0.5)); if (shell<1||shell>maxShell){ return -1; } else{ return shell; } } int Shape::GetNumSizes() { int nSizes=0; Position *curPos=firstPos; while(curPos!=0){ nSizes++; curPos=curPos->nextPos; } return nSizes; } int Shape::GetIndexOfShell(int shell) { int index=0; Position *curPos=firstPos; while(curPos!=0){ if (curPos->shell==shell){ return index; } else{ index++; curPos=curPos->nextPos; } } return -1; } void Shape::LoadIntFromFile(Pattern *patts, double aD) { string lattice, shape; int shell, nI, nAtoms; double minSa, maxSa, dsa; double *inSa, *inI; ifstream calcedPatt; //Read the important info from the first line of the intensity file calcedPatt.open(patts[0].fileName.c_str()); if (calcedPatt.is_open()){ string firstLine; getline(calcedPatt, firstLine); stringstream test(firstLine); while (!test.eof()){ string stuff; test>>stuff; if (stuff=="shell:"){ test>>shell; } else if(stuff=="latt:"){ test>>lattice; } else if (stuff=="shape:"){ test>>shape; } else if (stuff=="nAtoms:"){ test>>nAtoms; } else if (stuff=="minS*a:"){ test>>minSa; } else if (stuff=="maxS*a;"){ test>>maxSa; } else if (stuff=="d(s*a):"){ test>>dsa; } else if (stuff=="nInt:"){ test>>nI; } else{ } } //Allocate and Input the intensity from file try{ inSa=new double [nI]; inI=new double [nI]; for (int i=0;i<nI;i++){ inSa[i]=minSa+i*dsa; test>>inI[i]; } } catch(exception &e){ cout<<"Error: Exception caught in Pattern::LoadIntFromFile"<<e.what()<<endl; exit(1); } calcedPatt.close(); } else{ cout<<"Warning: Unable to open intensity file: "<<patts[0].fileName<<endl; return; } //Allocate and interpolate each intensity file. for (int i=0;i<Pattern::nLambda;i++){ double *neededSa; try{ if (patts[i].I){ delete [] patts[i].I; } patts[i].I=new double [Pattern::nInt]; neededSa =new double [Pattern::nInt]; for (int j=0;j<Pattern::nInt;j++){ neededSa[j]=Pattern::offsetq[i][j]*aD/(2*PI); } } catch(exception &e){ cout<<"Error: Exception caught in Pattern::LoadIntFromFile"<<e.what()<<endl; exit(1); } //TODO Insert call to interpolation routine // Interpolate(inQ, inI, neededSa,patts[i].I); interp(neededSa, Pattern::nInt, inSa, inI, nI, &(patts[i].I) ); delete [] neededSa; } delete [] inSa; delete [] inI; }
[ [ [ 1, 1575 ], [ 1577, 1582 ] ], [ [ 1576, 1576 ] ] ]
7578086621decd8eb8d46ed8e51ee27992c54882
f6d91584f5b92a90b22a1eb09d2ce203d4185f00
/ensembl/misc-scripts/alternative_splicing/AltSplicingToolkit/src/as/Coordinates.cpp
9ba7be28c52327bd7419367aa1ad55c4fc6f56c0
[ "BSD-2-Clause", "LicenseRef-scancode-philippe-de-muyter" ]
permissive
pamag/pmgEnsembl
8f807043bf6d0b6cfdfee934841d2af33c8d171c
ad0469e4d37171a69318f6bd1372477e85f4afb2
refs/heads/master
2021-06-01T10:58:22.839415
2011-10-18T16:09:52
2011-10-18T16:09:52
2,599,520
0
1
null
null
null
null
UTF-8
C++
false
false
2,951
cpp
/* * AltSplicingToolkit * Author: Gautier Koscielny <[email protected]> * * Copyright (c) 1999-2010 The European Bioinformatics Institute and * Genome Research Limited, and others. 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 "Ensembl" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected] * * 4. Products derived from this software may not be called "Ensembl" * nor may "Ensembl" appear in their names without prior written * permission of the Ensembl developers. * * 5. Redistributions in any form whatsoever must retain the following * acknowledgement: * * "This product includes software developed by Ensembl * (http://www.ensembl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE ENSEMBL GROUP ``AS IS'' AND ANY * EXPRESSED 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 ENSEMBL GROUP OR ITS * 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 "Coordinates.h" namespace as { Coordinates::Coordinates() { // TODO Auto-generated constructor stub } Coordinates::Coordinates(unsigned int start, unsigned int end) : start(start), end(end) { } Coordinates::~Coordinates() { // TODO Auto-generated destructor stub } unsigned int Coordinates::getStart() const { return start; } unsigned int Coordinates::getEnd() const { return end; } unsigned int Coordinates::getLength() const { return end-start+1; } void Coordinates::setStart(unsigned int v) { start = v; } void Coordinates::setEnd(unsigned int v) { end = v; } }
[ [ [ 1, 93 ] ] ]
92f30177ab61dc6509f01944b93ded6eee8413fd
71ffdff29137de6bda23f02c9e22a45fe94e7910
/LevelEditor/src/gui/CLayerControl.h
a99a2fc44f79a51283694017c22ce5ce9cd81985
[]
no_license
anhoppe/killakoptuz3000
f2b6ecca308c1d6ebee9f43a1632a2051f321272
fbf2e77d16c11abdadf45a88e1c747fa86517c59
refs/heads/master
2021-01-02T22:19:10.695739
2009-03-15T21:22:31
2009-03-15T21:22:31
35,839,301
0
0
null
null
null
null
UTF-8
C++
false
false
3,581
h
/******************************************************************** created: 2009/03/04 created: 4:3:2009 19:44 filename: c:\hoppe\develop\KK3000\LevelEditor\src\CLayerControl.h file path: c:\hoppe\develop\KK3000\LevelEditor\src file base: CLayerControl file ext: h author: anhoppe purpose: GUI panel for object layer control *********************************************************************/ #ifndef CLAYER_CONTROL_H #define CLAYER_CONTROL_H #include "wx/wx.h" #include "wx/tglbtn.h" #include "../data/IUpdate.h" #include "../data/ISetObject.h" #include <vector> class CLayerControl : public wxPanel, IUpdate, ISetObject { ////////////////////////////////////////////////////////////////////////// // Public Methods ////////////////////////////////////////////////////////////////////////// public: CLayerControl(wxWindow* t_parentPtr); ~CLayerControl(); virtual void update(); virtual void setObject(int t_index); ////////////////////////////////////////////////////////////////////////// // Private Methods ////////////////////////////////////////////////////////////////////////// void createControls(); /** assigns layer numbers to all objects before saving */ void assignLayerPosition(); /** assigns layer number to a single object, used by the other assignLayerPosition method */ void assignLayerPosition(int t_objectIndex, int t_index); /** insert layers after loading */ void insertLayers(std::vector<int>& t_layerPositions); /** Checks if at a given index in the list box is an object (return true) or a layer separator (false) */ bool isObject(int t_index); /** * Retrieves the index in the object list of an item, * -1 if at t_index is no object but a layer separator * (list row position to object index) */ int getObjectPosition(int t_index); /** * Retrieves the index of the row of an object * (object index to list row index) */ int getObjectRow(int t_index); /** Retrieves index in layer position vector of selected row index, -1 if at row index is no layer */ int getLayerIndex(int t_rowIndex); /** Checks if the layer with the given index in the layer position vector can be moved up */ bool canMoveLayerUp(int t_index); /** Checks if the layer with the given index in the layer position vector can be moved down */ bool canMoveLayerDown(int t_index); /** deletes layer at given index */ void deleteLayerByIndex(int t_index); ////////////////////////////////////////////////////////////////////////// // Events ////////////////////////////////////////////////////////////////////////// DECLARE_EVENT_TABLE() void onButtonAddObject(wxCommandEvent& t_event); void onButtonAddEnemy(wxCommandEvent& t_event); void onButtonInsertLayer(wxCommandEvent& t_event); void onButtonDeleteLayer(wxCommandEvent& t_event); void onButtonObjectUp(wxCommandEvent& t_event); void onButtonObjectDown(wxCommandEvent& t_event); void onListObjects(wxCommandEvent& t_event); ////////////////////////////////////////////////////////////////////////// // Private Variables ////////////////////////////////////////////////////////////////////////// private: wxListBox* m_listLayersPtr; wxToggleButton* m_buttonAddObjectPtr; wxToggleButton* m_buttonAddEnemyPtr; /** Vector with layer positions in the object list */ std::vector<int> m_layerPositions; }; #endif
[ "anhoppe@9386d06f-8230-0410-af72-8d16ca8b68df" ]
[ [ [ 1, 100 ] ] ]
3cb37fe6e2290632b3060e9181621c9f66746d92
0d5c8865066a588602d621f3ea1657f9abb14768
/loadddo.cpp
02baba8b98e4437a45df24b00051dc27cb25409e
[]
no_license
peerct/Conquest-DICOM-Server
301e6460c87b8a8d5d95f0057af95e8357dd4e7c
909978a7c8e5838ec8eb61d333e3a3fdd637ef60
refs/heads/master
2021-01-18T05:03:42.221986
2009-06-15T14:00:15
2009-06-15T14:00:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,100
cpp
/* * Reads DICOMObject's from disk. As well as makes Windows BITMAP * Structures. * * Bugs: Does not handle sequence objects * Does not support the recent change to DICOM Chapter 10 * Only works on 32 bit little-endian architecture * Notes: * * Eventually this routine will be not be needed. I will * add Disk I/O to the PDU_Service class, which will be a much cleaner, * and much more portable solution. * Mark Oskin * */ /* 19980409 mvh Added NKI private decompression engine VR 0x7fdf,0x0010 19980410 mvh Added run length encoding of zero differences 19980410 ljz+mvh Fix 16 bit absolute value decode 19980415 ljz+mvh Fix leak on decompress 19980625 mvh Added compression in SaveDicomDataObject(C10) 19980703 mvh+ljz Made DObjectSerialize thread save (removed statics) 19990105 ljz Fix: SaveDICOMDataObjectC10 created VR 0x0002 0x0013 twice Added comment in SaveDICOMDataObjectC10; CleanUp Put the nki-routines also in dgate.hpp Added LoadImplicitLittleEndianFile 19990317 ljz Decompression removed from LoadImplicitLittleEndianFile; added a VR-sizelimit of that reader 19990827 mvh NOTE: LoadImplicitLittleEndianFile allocates 100 MB and crashes when passing chapter 10 file (happens when extension is wrongly .v2) 19990830 ljz Fixed problem above: 'LoadImplicitLittleEndianFile' uses 'PDU.LoadDICOMDataObject' in such cases. 19991117 ljz Added parameter FileCompressMode to in nki_private_compress call 20000629 ljz Logging of trouble now starts with '***' 20001104 mvh Renamed _LittleEndianUID to _LittleEndianUID_space 20001105 mvh Fixed where malloc and new were mixed (vr->data) 20001106 mvh Use delete [] operation for vr->Data 20001128 ljz Fix in 'Implicit length' code in LoadImplicitLittleEndian 20010429 mvh Use faster and safer decompressor 20020412 ljz Added class CBufferedIO for faster reading from DVD (stream functions do not seem to be cacheing...) 20020415 mvh Removed diagnostic time code (did not compile on ms4.2) Made buffer size dependent on iVrSizelimit (i.e, use smaller for regen, slightly faster) 20030706 mvh Attach VRType to PDU's for implicit little endian support 20041130 mvh Documented crash on win2000 server in code - remain to be fixed 20050107 mvh Adapted for linux compile 20051219 mvh Use ReAlloc instead of new BYTE[] to fill VR data 20070308 bcb And little/big endian. */ #ifdef WIN32 #include <io.h> #else #include <unistd.h> #endif #include <fcntl.h> #include <sys/stat.h> #ifndef WHEDGE # include "dgate.hpp" #else # include "master.h" #endif typedef struct _DEIVR { UINT16 Group; UINT16 Element; UINT32 Length; } DEIVR; // Serializes the input of a DICOM Data object 1 byte at a time. Very usefull // routine to use if memory constraints are present typedef struct _DOBJECTSERSTATE { int state; UINT16 stuint16; UINT32 stuint32; DEIVR deivr; VR *vr; UINT sDIndex; } DOBJECTSERSTATE; DICOMDataObject * DObjectSerialize ( DICOMDataObject *DDO, unsigned char ch, BOOL LFrame, DOBJECTSERSTATE *doss) { // NOTE: THIS CODE WAS NOT THREADSAVE DUE TO THE USE OF STATIC VARIABLES ! // static int state; // static UINT16 stuint16; // static UINT32 stuint32; // static DEIVR deivr; // static VR *vr; // static UINT sDIndex; UINT32 tuint32; if(!DDO) // re-intialize state engine { doss->state = 0; return (new DICOMDataObject); } tuint32 = ch; switch ( doss->state ) { case 0: // base state doss->stuint16 = (UINT16) (tuint32 << 0); doss->state = 1; return (DDO); case 1: doss->stuint16 = doss->stuint16 | (UINT16) (tuint32 << 8); doss->deivr.Group = doss->stuint16; doss->state = 2; return ( DDO ); case 2: doss->stuint16 = (UINT16) (tuint32 << 0); doss->state = 3; return ( DDO ); case 3: doss->stuint16 = doss->stuint16 | (UINT16) (tuint32 << 8); doss->deivr.Element = doss->stuint16; doss->state = 4; return ( DDO ); case 4: doss->stuint32 = (tuint32 << 0); doss->state = 5; return ( DDO ); case 5: doss->stuint32 = doss->stuint32 | (tuint32 << 8); doss->state = 6; return ( DDO ); case 6: doss->stuint32 = doss->stuint32 | (tuint32 << 16); doss->state = 7; return ( DDO ); case 7: doss->stuint32 = doss->stuint32 | (tuint32 << 24); doss->deivr.Length = doss->stuint32; doss->sDIndex = 0; if(doss->deivr.Group==0x7fe0 && doss->deivr.Element==0x0010) if(LFrame) { return ( NULL ); } if(doss->deivr.Group==0x7fdf && doss->deivr.Element==0x0010) if(LFrame) { return ( NULL ); } doss->vr = new VR(doss->deivr.Group, doss->deivr.Element, doss->deivr.Length, TRUE); if(!doss->deivr.Length) { DDO->Push(doss->vr); doss->state = 0; } else doss->state = 8; return ( DDO ); case 8: if(!doss->vr->Data) return ( NULL ); // error ((BYTE *) doss->vr->Data ) [doss->sDIndex] = ch; ++(doss->sDIndex); if(doss->sDIndex == doss->deivr.Length) { if(doss->deivr.Group==0x7fdf && doss->deivr.Element==0x0010) { VR *v; signed char *CompressedData = ((signed char *)(doss->vr->Data)); int UncompressedLength = get_nki_private_decompressed_length(CompressedData); v = new VR(0x7fe0, 0x0010, UncompressedLength, TRUE); nki_private_decompress((short *)(v->Data), CompressedData, v->Length); DDO->Push(v); delete doss->vr; // we stored a copy } else DDO->Push(doss->vr); doss->state = 0; } return ( DDO ); } return ( NULL ); // error } DICOMDataObject * LoadDICOMDataObject(char *filename) { DICOMDataObject *DDO; UINT MemBlock, Block; UINT32 TCount, Index; unsigned char *mem; FILE *fp; DOBJECTSERSTATE doss; MemBlock = 50000; fp = fopen(filename, "rb"); if(!fp) { return ( FALSE ); } mem = (unsigned char *) malloc(MemBlock); if(!mem) { fclose(fp); return ( FALSE ); } DDO = DObjectSerialize(NULL, 0, FALSE, &doss); if(!DDO) { free(mem); return ( FALSE ); } TCount = 0; while( TRUE ) { Block = fread(mem, 1, MemBlock, fp); Index = 0; if(!TCount) { if(!strncmp((char*) &mem[128], "DICM", 4)) Index = 128 + 4; } TCount += Block; while(Index < Block) { DObjectSerialize(DDO, mem[Index], FALSE, &doss); ++Index; } if(Block!=MemBlock) break; } free(mem); fclose ( fp ); return ( DDO ); } static BOOL SaveDDO(DICOMDataObject* DDOPtr, FILE* fp, int FileCompressMode) { VR *TempVR; #if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like Apple power pc UINT16 beGroup, beElement; UINT32 beLength; #endif //Big Endian while(TempVR = DDOPtr->Pop()) { if(TempVR->Group==0x7fe0 && TempVR->Element==0x0010 && FileCompressMode) { int DataLength; short CompressedGroup = 0x7fdf, CompressedElement = 0x0010; signed char *CompressedData; CompressedData = new signed char [(TempVR->Length/2) * 3 + 10]; DataLength = nki_private_compress(CompressedData, (short int *)(TempVR->Data), TempVR->Length/2, FileCompressMode); if (!CompressedData) { OperatorConsole.printf("***Out of memory NKI-compress"); return FALSE; } if (DataLength&1) CompressedData[DataLength++] = 0; #if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian fwrite(&CompressedGroup, 1, 2, fp); fwrite(&CompressedElement, 1, 2, fp); fwrite(&DataLength, 1, 4, fp); #else //Big Endian like Apple power pc beGroup = SwitchEndian((UINT16) CompressedGroup); beElement = SwitchEndian((UINT16) CompressedElement); beLength = SwitchEndian((UINT32) DataLength); fwrite(&beGroup, 1, 2, fp); fwrite(&beElement, 1, 2, fp); fwrite(&beLength, 1, 4, fp); #endif //Big Endian if (fwrite(CompressedData, 1, DataLength, fp) != (unsigned int)DataLength) { free(CompressedData); OperatorConsole.printf("***Failed to save compressed pixel data (disk full?)"); return FALSE; } delete [] CompressedData; } else { #if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian fwrite(&TempVR->Group, 1, 2, fp); fwrite(&TempVR->Element, 1, 2, fp); fwrite(&TempVR->Length, 1, 4, fp); #else //Big Endian like Apple power pc beGroup = SwitchEndian((UINT16) TempVR->Group); beElement = SwitchEndian((UINT16) TempVR->Element); beLength = SwitchEndian((UINT32) TempVR->Length); fwrite(&beGroup, 1, 2, fp); fwrite(&beElement, 1, 2, fp); fwrite(&beLength, 1, 4, fp); #endif //Big Endian if(TempVR->Length) { if(!TempVR->Data) { OperatorConsole.printf("***Missing data in VR (0x%04x,0x%04x)", TempVR->Group, TempVR->Element); return FALSE; } fwrite(TempVR->Data, 1, TempVR->Length, fp); } } delete TempVR; } return TRUE; } BOOL SaveDICOMDataObject(DICOMDataObject *DDOPtr, char *filename, int FileCompressMode) { FILE* fp; BOOL rc; fp = fopen(filename, "wb"); if(!fp) return FALSE; rc = SaveDDO(DDOPtr, fp, FileCompressMode); fclose(fp); return rc; } # define _LittleEndianUID_space "1.2.840.10008.1.2 " # define _ImplementationUID "none yet" # define _ImplementationVersion "0.1AlphaUCDMC " # define _SourceApplicationAE "none " BOOL SaveDICOMDataObjectC10(DICOMDataObject *DDOPtr, char *filename, int FileCompressMode) { VR *vr, *vr1; UINT16 tuint16; FILE *fp; char s[140]; BOOL rc; vr = DDOPtr->GetVR(0x0002, 0x0001); if(!vr) { // This does not contain the C10 Header yet, so we need to // constuct it // FileMetaInformationVersion vr = new VR(0x0002, 0x0001, 0x0002, TRUE); tuint16 = 0x0001; memcpy(vr->Data, (void*)&tuint16, 2); DDOPtr->Push(vr); // SOPClassUID vr = DDOPtr->GetVR(0x0008, 0x0016); if(vr) { // MediaStorageSOPClassUID vr1 = new VR(0x0002, 0x0002, vr->Length, TRUE); memcpy(vr1->Data, vr->Data, vr->Length); DDOPtr->Push(vr1); } // SOPInstanceUID vr = DDOPtr->GetVR(0x0008, 0x0018); if(vr) { // MediaStorageSOPInstanceUID vr1 = new VR(0x0002, 0x0003, vr->Length, TRUE); memcpy(vr1->Data, vr->Data, vr->Length); DDOPtr->Push(vr1); } // TransferSyntaxUID vr = new VR(0x0002, 0x0010, strlen(_LittleEndianUID_space), TRUE); memset(vr->Data, 0, vr->Length); memcpy(vr->Data, (void*)_LittleEndianUID_space, strlen(_LittleEndianUID_space)); DDOPtr->Push(vr); // ImplementationClassUID vr = new VR(0x0002, 0x0012, strlen(_ImplementationUID), TRUE); memset(vr->Data, 0, vr->Length); memcpy(vr->Data, (void*)_ImplementationUID, strlen(_ImplementationUID)); DDOPtr->Push(vr); // ImplementationVersionName vr = new VR(0x0002, 0x0013, strlen(_ImplementationVersion), TRUE); memset(vr->Data, 0, vr->Length); memcpy(vr->Data, (void*)_ImplementationVersion, strlen(_ImplementationVersion)); DDOPtr->Push(vr); // SourceApplicationEntityTitle vr = new VR(0x0002, 0x0016, strlen(_SourceApplicationAE), TRUE); memset(vr->Data, 0, vr->Length); memcpy(vr->Data, (void*)_SourceApplicationAE, strlen(_SourceApplicationAE)); DDOPtr->Push(vr); } fp = fopen(filename, "wb"); if(!fp) return FALSE; memset((void*)s, 0, 128); strcpy(&s[128], "DICM"); fwrite(s, 128 + 4, 1, fp); rc = SaveDDO(DDOPtr, fp, FileCompressMode); fclose(fp); return rc; } static BOOL OrgLoadImplicitLittleEndian(DICOMDataObject* pDDO, FILE* fp, unsigned int iVrSizeLimit) { DICOMDataObject* pNewDDO; VR* pVR; char Buf[2 + 2 + 4]; while (fread(Buf, 1, sizeof(Buf), fp) == sizeof(Buf)) { /* Group, Element and Size could be read */ pVR = new VR; if (!pVR) return FALSE; #if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian pVR->Group = *((unsigned short*) Buf); pVR->Element = *((unsigned short*)(Buf + 2)); pVR->Length = *((unsigned int*) (Buf + 2 + 2)); #else //Big Endian like Apple power pc pVR->Group = SwitchEndian( *((UINT16*) Buf)); pVR->Element = SwitchEndian( *((UINT16*)(Buf + 2))); pVR->Length = SwitchEndian( *((UINT32*) (Buf + 2 + 2))); #endif //Big Endian if (pVR->Group == 0xfffe) { /* A deliminator */ if ((pVR->Element == 0xe0dd) || (pVR->Element == 0xe00d)) { delete pVR; return TRUE; } if (pVR->Length == 0xffffffff) { /* Implicit length... Go until deliminator */ pVR->Length = 0; delete pVR; pNewDDO = new DICOMDataObject; if (OrgLoadImplicitLittleEndian(pNewDDO, fp, iVrSizeLimit)) { pDDO->Push(pNewDDO); continue; } else { delete pNewDDO; return FALSE; } } if (pVR->Element == 0xe000) { /* Sequence begin ? */ pVR->Length = 0; delete pVR; pNewDDO = new DICOMDataObject; if (OrgLoadImplicitLittleEndian(pNewDDO, fp, iVrSizeLimit)) { pDDO->Push(pNewDDO); continue; } else { delete pNewDDO; return FALSE; } } } if (pVR->Length == 0xffffffff) { pVR->Length = 0; pDDO->Push(pVR); if (!OrgLoadImplicitLittleEndian(pDDO, fp, iVrSizeLimit)) return FALSE; continue; } /* Check whether the current VR has to be read. NKI DicomNodes can restrict what has to be read Following code assumes that reading is finished when pixeldata are encountered. (Maybe a problem here!!!) */ if (pVR->Length > iVrSizeLimit) { if (((pVR->Group == 0x7fdf) || (pVR->Group == 0x7fe0)) && (pVR->Element == 0x0010)) { /* Ready !? */ pVR->Length = 0; delete pVR; return TRUE; } else { /* Read it, throw it away and continue */ // pVR->Data = new char [pVR->Length]; pVR->ReAlloc(pVR->Length); if (!pVR->Data) return FALSE; fread(pVR->Data, 1, pVR->Length, fp); delete pVR; continue; } } if (pVR->Length) { // pVR->Data = new char [pVR->Length]; pVR->ReAlloc(pVR->Length); if (!pVR->Data) return FALSE; fread(pVR->Data, 1, pVR->Length, fp); /* if ((pVR->Group == 0x7fdf) && (pVR->Element == 0x0010)) { VR* v; signed char *CompressedData = ((signed char *)(pVR->Data)); int UncompressedLength = get_nki_private_decompressed_length(CompressedData); v = new VR(0x7fe0, 0x0010, UncompressedLength, TRUE); nki_private_decompress((short *)(v->Data), CompressedData); delete pVR; pVR = v; } */ } else pVR->Data = NULL; pDDO->Push(pVR); } return TRUE; } DICOMDataObject* OrgLoadImplicitLittleEndianFile(char* filename, unsigned int iVrSizeLimit) { DICOMDataObject* pDDO; FILE* fp; char Buf[128 + 4]; PDU_Service PDU; PDU.AttachRTC(&VRType); fp = fopen(filename, "rb"); if(!fp) { return NULL; } /* Find out whether marker 'DICM' exists */ if (fread(Buf, 1, 128 + 4, fp) != 128 + 4) { fclose(fp); return NULL; } else { if (strncmp(Buf + 128, "DICM", 4) != 0) { fseek(fp, 0, SEEK_SET); /* We are at beginning of the VRs */ pDDO = new DICOMDataObject; OrgLoadImplicitLittleEndian(pDDO, fp, iVrSizeLimit); fclose ( fp ); return pDDO; } else { /* The function 'LoadImplicitLittleEndianFile' is not intended for DICM files, however don't be fuzzy about it... */ fclose(fp); pDDO = PDU.LoadDICOMDataObject(filename); return pDDO; } } } /*-----------------------------------------------------------------------*/ class CBufferedIO { private: char* m_pBuf; int m_iBufSize; int m_iCurPos; int m_iNbBytesInBuffer; int m_iNbBlocksRead; public: CBufferedIO(int iBufSize = 0x4000); ~CBufferedIO(); int read (int handle, void *buffer, unsigned int count); long lseek(int handle, long offset, int origin); }; CBufferedIO::CBufferedIO(int iBufSize) { m_pBuf = NULL; m_iBufSize = iBufSize; m_iCurPos = 0; m_iNbBytesInBuffer = 0; m_iNbBlocksRead = 0; }; CBufferedIO::~CBufferedIO() { if (m_pBuf) free(m_pBuf); }; int CBufferedIO::read (int handle, void *buffer, unsigned int count) { int iNbBytesCopied = 0; if (!m_pBuf) { if (m_iBufSize <= 0) return -1; m_pBuf = (char*)malloc(m_iBufSize); if (!m_pBuf) return -1; } while (count - iNbBytesCopied > m_iNbBytesInBuffer - m_iCurPos) { memcpy(buffer, m_pBuf + m_iCurPos, m_iNbBytesInBuffer - m_iCurPos); buffer = (char*)buffer + m_iNbBytesInBuffer - m_iCurPos; iNbBytesCopied += m_iNbBytesInBuffer - m_iCurPos; m_iCurPos = 0; m_iNbBytesInBuffer = ::read(handle, m_pBuf, m_iBufSize); m_iNbBlocksRead ++; if (m_iNbBytesInBuffer <= 0) return iNbBytesCopied; } /* crash probably when read failed of file after: 2004-11-30 09:46:48 [RT8769103] Sending file : y:\dv0_0001\20001314\1.2.840.113619.2.22.287.1.369.2.20000619.221935_0002_000014_96263112199.V2 0001:0001fb70 ?read@CBufferedIO@@QAEHHPAXI@Z 00420b70 f loadddo.obj 0001:0001fc40 ?lseek@CBufferedIO@@QAEJHJH@Z 00420c40 f loadddo.obj function: <nosymbols> 00420c0d 5b pop ebx 00420c0e c20c00 ret 0xc 00420c11 8b44241c mov eax,[esp+0x1c] ss:0b6c89cf=???????? 00420c15 8b7500 mov esi,[ebp+0x0] ss:02b85cb6=???????? 00420c18 8bd0 mov edx,eax 00420c1a 037508 add esi,[ebp+0x8] ss:02b85cb6=???????? 00420c1d 2bd3 sub edx,ebx 00420c1f 8b7c2418 mov edi,[esp+0x18] ss:0b6c89cf=???????? 00420c23 8bca mov ecx,edx 00420c25 c1e902 shr ecx,0x2 FAULT ->00420c28 f3a5 rep movsd ds:023c2000=???????? es:1f838480=00000000 00420c2a 8bca mov ecx,edx 00420c2c 83e103 and ecx,0x3 00420c2f f3a4 rep movsb ds:023c2000=?? es:1f838480=00 00420c31 8bc8 mov ecx,eax 00420c33 2bcb sub ecx,ebx 00420c35 014d08 add [ebp+0x8],ecx ss:02b85cb6=???????? 00420c38 5d pop ebp 00420c39 5f pop edi 00420c3a 5e pop esi 00420c3b 5b pop ebx 00420c3c c20c00 ret 0xc */ memcpy(buffer, m_pBuf + m_iCurPos, count - iNbBytesCopied); m_iCurPos += count - iNbBytesCopied; return count; } long CBufferedIO::lseek(int handle, long offset, int origin) { long rc; /* Just handle the special case for the 'DICM' test */ if ((origin == SEEK_SET) && (offset < m_iNbBytesInBuffer) && (m_iNbBlocksRead == 1)) { m_iCurPos = offset; rc = offset; } else { /* Make sure that above special case does not re-appear */ m_iNbBlocksRead = 999; if (origin == SEEK_CUR) /* Adjust the file-position to where the caller thinks it is */ offset = offset - (m_iNbBytesInBuffer - m_iCurPos); rc = ::lseek(handle, offset, origin); m_iCurPos = 0; m_iNbBytesInBuffer = 0; } return rc; } /*-----------------------------------------------------------------------*/ static BOOL LoadImplicitLittleEndian(DICOMDataObject* pDDO, CBufferedIO* pBufferedIO, int handle, unsigned int iVrSizeLimit) { DICOMDataObject* pNewDDO; VR* pVR; char Buf[2 + 2 + 4]; while (pBufferedIO->read(handle, Buf, sizeof(Buf)) == sizeof(Buf)) { /* Group, Element and Size could be read */ pVR = new VR; if (!pVR) return FALSE; #if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian pVR->Group = *((unsigned short*) Buf); pVR->Element = *((unsigned short*)(Buf + 2)); pVR->Length = *((unsigned int*) (Buf + 2 + 2)); #else //Big Endian like Apple power pc pVR->Group = SwitchEndian( *((UINT16*) Buf)); pVR->Element = SwitchEndian( *((UINT16*)(Buf + 2))); pVR->Length = SwitchEndian( *((UINT32*) (Buf + 2 + 2))); #endif //Big Endian if (pVR->Group == 0xfffe) { /* A deliminator */ if ((pVR->Element == 0xe0dd) || (pVR->Element == 0xe00d)) { delete pVR; return TRUE; } if (pVR->Length == 0xffffffff) { /* Implicit length... Go until deliminator */ pVR->Length = 0; delete pVR; pNewDDO = new DICOMDataObject; if (LoadImplicitLittleEndian(pNewDDO, pBufferedIO, handle, iVrSizeLimit)) { pDDO->Push(pNewDDO); continue; } else { delete pNewDDO; return FALSE; } } if (pVR->Element == 0xe000) { /* Sequence begin ? */ pVR->Length = 0; delete pVR; pNewDDO = new DICOMDataObject; if (LoadImplicitLittleEndian(pNewDDO, pBufferedIO, handle, iVrSizeLimit)) { pDDO->Push(pNewDDO); continue; } else { delete pNewDDO; return FALSE; } } } if (pVR->Length == 0xffffffff) { pVR->Length = 0; pDDO->Push(pVR); if (!LoadImplicitLittleEndian(pDDO, pBufferedIO, handle, iVrSizeLimit)) return FALSE; continue; } /* Check whether the current VR has to be read. NKI DicomNodes can restrict what has to be read Following code assumes that reading is finished when pixeldata are encountered. (Maybe a problem here!!!) */ if (pVR->Length > iVrSizeLimit) { if (((pVR->Group == 0x7fdf) || (pVR->Group == 0x7fe0)) && (pVR->Element == 0x0010)) { /* Ready !? */ pVR->Length = 0; delete pVR; return TRUE; } else { /* Read it, throw it away and continue */ // pVR->Data = new char [pVR->Length]; pVR->ReAlloc(pVR->Length); if (!pVR->Data) return FALSE; pBufferedIO->read(handle, pVR->Data, pVR->Length); delete pVR; continue; } } if (pVR->Length) { // pVR->Data = new char [pVR->Length]; pVR->ReAlloc(pVR->Length); if (!pVR->Data) return FALSE; pBufferedIO->read(handle, pVR->Data, pVR->Length); } else pVR->Data = NULL; pDDO->Push(pVR); } return TRUE; } DICOMDataObject* LoadImplicitLittleEndianFile(char* filename, unsigned int iVrSizeLimit) { DICOMDataObject* pDDO; int handle; char Buf[128 + 4]; PDU_Service PDU; unsigned int iLastTime, iCurTime; CBufferedIO* pBufferedIO; PDU.AttachRTC(&VRType); #ifdef WIN32 handle = sopen( filename, O_RDONLY | O_BINARY, SH_DENYNO, S_IREAD); #else handle = open( filename, O_RDONLY); #endif if (handle == -1) { return NULL; } pBufferedIO = new CBufferedIO(iVrSizeLimit < 0x1000 ? 0x1000 : 0x8000); /* Find out whether marker 'DICM' exists */ if (pBufferedIO->read(handle, Buf, 128 + 4) != 128 + 4) { delete pBufferedIO; close(handle); return NULL; } else { if (strncmp(Buf + 128, "DICM", 4) != 0) { pBufferedIO->lseek(handle, 0, SEEK_SET); /* We are at beginning of the VRs */ pDDO = new DICOMDataObject; LoadImplicitLittleEndian(pDDO, pBufferedIO, handle, iVrSizeLimit); //iLastTime = timeGetTime(); delete pBufferedIO; close(handle); //iCurTime = timeGetTime(); //printf("fopen=%d\r\n", iCurTime - iLastTime); return pDDO; } else { /* The function 'LoadImplicitLittleEndianFile' is not intended for DICM files, however don't be fuzzy about it... */ delete pBufferedIO; close(handle); pDDO = PDU.LoadDICOMDataObject(filename); return pDDO; } } } DICOMDataObject * LoadDICOMDataObjectFrame(char *filename) { DICOMDataObject *DDO; UINT MemBlock, Block; UINT32 TCount, Index; unsigned char *mem; FILE *fp; DOBJECTSERSTATE doss; MemBlock = 50000; fp = fopen(filename, "rb"); if(!fp) { return ( FALSE ); } mem = (unsigned char *) malloc(MemBlock); if(!mem) { fclose(fp); return ( FALSE ); } DDO = DObjectSerialize(NULL, 0, FALSE, &doss); if(!DDO) { free(mem); return ( FALSE ); } TCount = 0; while( TRUE ) { Block = fread(mem, 1, MemBlock, fp); Index = 0; if(!TCount) { if(!strncmp((char*) &mem[128], "DICM", 4)) Index = 128 + 4; } TCount += Block; while(Index < Block) { if(!DObjectSerialize(DDO, mem[Index], TRUE, &doss)) { free(mem); fclose(fp); return(DDO); } ++Index; } if(Block!=MemBlock) break; } free(mem); fclose ( fp ); return ( DDO ); }
[ [ [ 1, 963 ] ] ]
80f7ee2699babd83b2f798c449232e80e7235937
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/signals/test/signal_n_test.cpp
39b770c23297743651cbaa5b540c6615b6626a23
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
4,450
cpp
// Boost.Signals library // Copyright Douglas Gregor 2001-2003. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // For more information, see http://www.boost.org #include <boost/test/minimal.hpp> #include <boost/signal.hpp> #include <functional> template<typename T> struct max_or_default { typedef T result_type; template<typename InputIterator> typename InputIterator::value_type operator()(InputIterator first, InputIterator last) const { if (first == last) return T(); T max = *first++; for (; first != last; ++first) max = (*first > max)? *first : max; return max; } }; struct make_int { make_int(int n, int cn) : N(n), CN(n) {} int operator()() { return N; } int operator()() const { return CN; } int N; int CN; }; template<int N> struct make_increasing_int { make_increasing_int() : n(N) {} int operator()() const { return n++; } mutable int n; }; int get_37() { return 37; } static void test_zero_args() { make_int i42(42, 41); make_int i2(2, 1); make_int i72(72, 71); make_int i63(63, 63); make_int i62(62, 61); { boost::signal0<int, max_or_default<int>, std::string> s0; boost::BOOST_SIGNALS_NAMESPACE::connection c2 = s0.connect(i2); boost::BOOST_SIGNALS_NAMESPACE::connection c72 = s0.connect("72", i72); boost::BOOST_SIGNALS_NAMESPACE::connection c62 = s0.connect("6x", i62); boost::BOOST_SIGNALS_NAMESPACE::connection c42 = s0.connect(i42); boost::BOOST_SIGNALS_NAMESPACE::connection c37 = s0.connect(&get_37); BOOST_TEST(s0() == 72); s0.disconnect("72"); BOOST_TEST(s0() == 62); c72.disconnect(); // Double-disconnect should be safe BOOST_TEST(s0() == 62); s0.disconnect("72"); // Triple-disconect should be safe BOOST_TEST(s0() == 62); // Also connect 63 in the same group as 62 s0.connect("6x", i63); BOOST_TEST(s0() == 63); // Disconnect all of the 60's s0.disconnect("6x"); BOOST_TEST(s0() == 42); c42.disconnect(); BOOST_TEST(s0() == 37); c37.disconnect(); BOOST_TEST(s0() == 2); c2.disconnect(); BOOST_TEST(s0() == 0); } { boost::signal0<int, max_or_default<int> > s0; boost::BOOST_SIGNALS_NAMESPACE::connection c2 = s0.connect(i2); boost::BOOST_SIGNALS_NAMESPACE::connection c72 = s0.connect(i72); boost::BOOST_SIGNALS_NAMESPACE::connection c62 = s0.connect(i62); boost::BOOST_SIGNALS_NAMESPACE::connection c42 = s0.connect(i42); const boost::signal0<int, max_or_default<int> >& cs0 = s0; BOOST_TEST(cs0() == 72); } { make_increasing_int<7> i7; make_increasing_int<10> i10; boost::signal0<int, max_or_default<int> > s0; boost::BOOST_SIGNALS_NAMESPACE::connection c7 = s0.connect(i7); boost::BOOST_SIGNALS_NAMESPACE::connection c10 = s0.connect(i10); BOOST_TEST(s0() == 10); BOOST_TEST(s0() == 11); } } static void test_one_arg() { boost::signal1<int, int, max_or_default<int> > s1; s1.connect(std::negate<int>()); s1.connect(std::bind1st(std::multiplies<int>(), 2)); BOOST_TEST(s1(1) == 2); BOOST_TEST(s1(-1) == 1); } static void test_signal_signal_connect() { boost::signal1<int, int, max_or_default<int> > s1; s1.connect(std::negate<int>()); BOOST_TEST(s1(3) == -3); { boost::signal1<int, int, max_or_default<int> > s2; s1.connect(s2); s2.connect(std::bind1st(std::multiplies<int>(), 2)); s2.connect(std::bind1st(std::multiplies<int>(), -3)); BOOST_TEST(s2(-3) == 9); BOOST_TEST(s1(3) == 6); } // s2 goes out of scope and disconnects BOOST_TEST(s1(3) == -3); } struct EventCounter { EventCounter() : count(0) {} void operator()() { ++count; } int count; }; static void test_ref() { EventCounter ec; boost::signal0<void> s; { boost::BOOST_SIGNALS_NAMESPACE::scoped_connection c = s.connect(boost::ref(ec)); BOOST_TEST(ec.count == 0); s(); BOOST_TEST(ec.count == 1); } s(); BOOST_TEST(ec.count == 1); } int test_main(int, char* []) { test_zero_args(); test_one_arg(); test_signal_signal_connect(); test_ref(); return 0; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 192 ] ] ]
129b3c88e48eab30bd423147b9e6d73b82b786d2
1a5b43c98479a5c44c6da4b01fa35af95c6d7bcd
/CFGGen/SyntaxUtils.h
966de44440f1e03152ffeacb53df2b7201de4568
[]
no_license
eknowledger/mcfromc
827641a5f670d18ee2a7e1d8d76b783d37d33004
41b6ba1065b27a8468d3b70c3698cbcef0dc698b
refs/heads/master
2016-09-05T12:11:29.137266
2010-08-08T05:11:43
2010-08-08T05:11:43
34,752,799
0
0
null
null
null
null
UTF-8
C++
false
false
556
h
#pragma once class SNode; class SyntaxUtils { public: static bool isLoop( SNode* node); static bool isForLoop( SNode* node); static bool isDoWhileLoop( SNode* node); static bool isWhileLoop( SNode* node); static bool isIfBranch( SNode* node); static bool isIfElseBranch( SNode* node); static bool isBranch( SNode* node); static bool isExpressionsOnlyStatement(SNode* statementNode); static bool isExpression(SNode* node); static bool isStatement(SNode* node); private: SyntaxUtils(void); virtual ~SyntaxUtils(void); };
[ "man701@46565ccc-2a3b-0f42-2bc5-e45c9856c86c" ]
[ [ [ 1, 22 ] ] ]
5b5b93e290a94582cb2a288731c29ac1c962ae2a
92bedc8155e2fb63f82603c5bf4ddec445d49468
/src/pdf/PDFThreadReader.cpp
6d951b4b25fe438c1bd7b8ef12d875741e38e556
[]
no_license
jemyzhang/pluto-hades
16372453f05510918b07720efa210c748b887316
78d9cf2ec7022ad35180e4fb685d780525ffc45d
refs/heads/master
2016-09-06T15:11:35.964172
2009-09-26T09:53:12
2009-09-26T09:53:12
32,126,635
0
0
null
null
null
null
UTF-8
C++
false
false
10,396
cpp
/******************************************************************************* ** ** NAME: PDFThreadReader.cpp ** VER: 1.0 ** CREATE DATE: 2009/07/06 ** AUTHOR: Roger.Yi ([email protected]) ** ** Copyright (C) 2009 - PlutoWare All Rights Reserved ** ** ** PURPOSE: Class PDFThreadReader ** ** -------------------------------------------------------------- ** ** HISTORY: v1.0, 2009/08/13 ** ** *******************************************************************************/ #include "stdafx.h" #include "PDFThreadReader.h" namespace pdf { static const quint32 MAX_ACCEPT_MEM_USE = 80; struct PDFThreadReader::PDFThreadReaderImpl { QCache<int, pltCompressedImage> pages; QCache<int, pltCompressedImage> thumbs; QQueue<int> requests; QMutex requestMutex; QMutex cacheMutex; QSemaphore renderSemaphore; volatile int requestPageNo; volatile int renderingPageNo; PDFThreadReader::ZoomLevel zoomLevel; int screenWidth; int screenHeight; int rotation; volatile bool stopFlag; bool convert16bits; bool useFastAlgo; QSize thumbSize; int prefetchNum; bool useCache; bool enableCaching; PDFThreadReaderImpl() : requestMutex(QMutex::Recursive) , cacheMutex(QMutex::Recursive) , renderingPageNo(-1) , convert16bits(false) , thumbSize (128, 128) , prefetchNum (2) , useCache (true) , enableCaching (true) , useFastAlgo (false) { } pltCompressedImage* addIntoCache(int pageNo, const QImage& image) { pltCompressedImage* page = new pltCompressedImage(false, useFastAlgo); page->compress(image); if (page->size() != 0 && page->size() < pages.maxCost()) { QMutexLocker locker(&cacheMutex); pages.insert(pageNo, page, page->size()); } else { SAFE_DELETE(page); } return page; } void clearCache() { QMutexLocker locker(&cacheMutex); pages.clear(); } QImage addThumb(int pageNo, const QImage& image) { QImage thumbImg = QImage(image.scaled(thumbSize, Qt::KeepAspectRatio, Qt::SmoothTransformation)); pltCompressedImage* thumb = new pltCompressedImage(true, false); thumb->compress(thumbImg); if (thumb->size() != 0 && thumb->size() < thumbs.maxCost()) { thumbs.insert(pageNo, thumb, thumb->size()); } else { SAFE_DELETE(thumb); } __LOG(QString("Add thumb, size : %1").arg(thumb->size())); return thumbImg; } void clearThumbs() { thumbs.clear(); } void enqueueRequest(int pageNo) { QMutexLocker locker(&requestMutex); requests.enqueue(pageNo); } int dequeueRequest() { QMutexLocker locker(&requestMutex); return requests.dequeue(); } void clearRequest() { QMutexLocker locker(&requestMutex); requests.clear(); } void setRenderingPageNo(int pageNo) { renderingPageNo = pageNo; } void resetRenderingPageNo() { renderingPageNo = -1; } }; PDFThreadReader::PDFThreadReader(QObject *parent /*= NULL*/, int cacheSize /*= 1024 * 1024 * 10*/, int gcBufSize /*= 1024 * 512*/) : QThread(parent) , PDFReader(gcBufSize) , impl_ (new PDFThreadReaderImpl) { impl_->pages.setMaxCost(cacheSize); impl_->thumbs.setMaxCost(cacheSize / 5); } PDFThreadReader::~PDFThreadReader() { this->stop(); SAFE_DELETE(impl_); } bool PDFThreadReader::hasPage(int pageNo) const { return impl_->pages.contains(pageNo); } QImage PDFThreadReader::pageImage(int pageNo) const { QImage image; pltCompressedImage* page = impl_->pages.object(pageNo); if (page) { image = page->uncompress(); } return image; } PDFThreadReader::ZoomLevel PDFThreadReader::zoomLevel() const { return impl_->zoomLevel; } void PDFThreadReader::open(const QString& pdfFile, const QString& password /*= ""*/) { if (QFileInfo(pdfFile) != QFileInfo(this->filePath())) { this->stopAndClean(); PDFReader::open(pdfFile, password); } } void PDFThreadReader::setMargin(double leftPercent /*= 0.05*/, double rightPercent /*= 0.05*/, double topPercent /*= 0.0*/, double bottomPercent /*= 0.0*/, int ignorePages /*= 0*/) { if (qAbs(this->leftMargin() - leftPercent) > 0.01 || qAbs(this->rightMargin() - rightPercent) > 0.01 || qAbs(this->topMargin() - topPercent) > 0.01 || qAbs(this->bottomMargin() - bottomPercent) > 0.01) { this->stopAndClean(); PDFReader::setMargin(leftPercent, rightPercent, topPercent, bottomPercent, ignorePages); } } void PDFThreadReader::setRenderParams(ZoomLevel level, int screenW, int screenH, int rotation /*= 0*/) { if (impl_->zoomLevel != level || impl_->screenWidth != screenW || impl_->screenHeight != screenH || impl_->rotation != rotation) { this->stopAndClean(); impl_->zoomLevel = level; impl_->screenWidth = screenW; impl_->screenHeight = screenH; impl_->rotation = rotation; if (impl_->useCache) { if (level <= FitWidth250) { impl_->enableCaching = false; impl_->prefetchNum = 0; } else if (level < FitWidth150) { impl_->enableCaching = true; impl_->prefetchNum = 1; } else { impl_->enableCaching = true; impl_->prefetchNum = 2; } } } } void PDFThreadReader::setUseFastCompressAlgo(bool use) { impl_->useFastAlgo = use; } void PDFThreadReader::setUseCache(bool use) { impl_->useCache = use; if (use) { impl_->enableCaching = true; } else { impl_->enableCaching = false; impl_->clearCache(); } } void PDFThreadReader::askRender(int pageNo, bool wait) { pageNo = qBound(1, pageNo, this->pageCount()); impl_->requestPageNo = pageNo; impl_->clearRequest(); if (this->hasPage(pageNo)) { QImage image = this->pageImage(pageNo); QImage thumb = this->pageThumb(pageNo); if (!image.isNull()) { this->emitRendered(pageNo, image, thumb); } else { emit renderError(QString("Render p%1 error - %2") .arg(pageNo).arg("Out of memory")); } } else { if (impl_->renderingPageNo != pageNo) impl_->enqueueRequest(pageNo); emit rendering(QString("Rendering p%1, please wait").arg(pageNo)); if (!this->isRunning()) { //start impl_->stopFlag = false; this->start(QThread::LowPriority); if (wait) { impl_->renderSemaphore.acquire( impl_->renderSemaphore.available() + 1); } } } if (impl_->enableCaching) this->prefetch(pageNo, impl_->prefetchNum); } void PDFThreadReader::run() { while (!impl_->stopFlag) { if (impl_->requests.isEmpty()) { this->msleep(100); } else { int pageNo = impl_->dequeueRequest(); if (this->hasPage(pageNo)) { //do not need to render, already has page if (pageNo == impl_->requestPageNo) { this->emitRendered(pageNo, this->pageImage(pageNo), this->pageThumb(pageNo)); } } else { //need to render this->renderPage(pageNo); } } } } void PDFThreadReader::stop() { if (this->isRunning()) { impl_->stopFlag = true; if (!this->wait(10000)) { this->terminate(); } } } void PDFThreadReader::stopAndClean() { this->stop(); impl_->clearCache(); impl_->clearThumbs(); impl_->clearRequest(); impl_->resetRenderingPageNo(); pltCompressedImage::resetCompressLevel(); } void PDFThreadReader::prefetch(int pageNo, int count) { int nextPage = pageNo + 1; for (int i = 0; i < count; ++i) { if (!this->hasPage(nextPage) && nextPage <= this->pageCount()) { impl_->enqueueRequest(nextPage); } ++nextPage; } } void PDFThreadReader::renderPage(int pageNo) { try { impl_->setRenderingPageNo(pageNo); QImage image = this->render(pageNo, impl_->zoomLevel, impl_->screenWidth, impl_->screenHeight, impl_->rotation); //release memory this->clearEngineBuffer(); //check if (image.isNull()) { __THROW_L(PDFException, "Out of memory"); } //convert to 16bits if (impl_->convert16bits) { image = image.convertToFormat(QImage::Format_RGB16); } //add thumb QImage thumb; if (this->hasPageThumb(pageNo)) { thumb = this->pageThumb(pageNo); } { thumb = impl_->addThumb(pageNo, image); } if (!impl_->stopFlag) { //cache then emit if (impl_->enableCaching) this->cache(pageNo, image); if (pageNo == impl_->requestPageNo) { this->emitRendered(pageNo, image, thumb); } } impl_->resetRenderingPageNo(); } catch (PDFException& e) { //release memory this->clearEngineBuffer(); emit renderError(QString("Render p%1 error - %2").arg(pageNo).arg(e.what())); } } void PDFThreadReader::emitRendered(int pageNo, const QImage& image, const QImage& thumb) { impl_->renderSemaphore.release(); emit rendered(pageNo, image, thumb); } void PDFThreadReader::cache(int pageNo, const QImage& image) { pltCompressedImage* page = impl_->addIntoCache(pageNo, image); QString cachedMsg = QString("Cached p%1 (%2), cost %3k (%4m / %5m) - [%6]") .arg(pageNo) .arg(impl_->pages.size()) .arg(page->size() / 1024) .arg(impl_->pages.totalCost() * 1.0 / (1024 * 1024), 0, 'f', 1) .arg(impl_->thumbs.totalCost() * 1.0 / (1024 * 1024), 0, 'f', 1) .arg(pltCompressedImage::compressLevel()); emit cached(cachedMsg); __LOG(cachedMsg); if (page == NULL && pageNo == impl_->requestPageNo) { //too large, can not add into cache //remove the later request impl_->clearRequest(); } } void PDFThreadReader::setConvertTo16Bits(bool convert) { impl_->convert16bits = convert; } void PDFThreadReader::setThumbSize(QSize size) { impl_->thumbSize = size; } bool PDFThreadReader::hasPageThumb(int pageNo) const { return impl_->thumbs.contains(pageNo); } QImage PDFThreadReader::pageThumb(int pageNo) const { QImage thumbImg; pltCompressedImage* thumb = impl_->thumbs.object(pageNo); if (thumb) { thumbImg = thumb->uncompress(); } return thumbImg; } //end namespace }
[ "roger2yi@35b8d456-67b3-11de-a2f9-0f955267958a" ]
[ [ [ 1, 575 ] ] ]
30c1235993285335a97afff60de2e67e37115064
3464482d0516fe967133bce6e374b4993d426f35
/CedeCrypt/CedeCrypt/EncryptWindow.h
3eb71a3c6fc8702a220807c1d5681994bfe3b7d8
[]
no_license
dannydraper/CedeCryptPortable
75fc2cc0b17546469b9da7d0e82dcc150c6e24ab
e848915107597d1ada0c7de18a8ede46e9a44de1
refs/heads/master
2021-01-09T20:03:52.722661
2010-09-27T18:49:42
2010-09-27T18:49:42
63,583,875
0
0
null
null
null
null
UTF-8
C++
false
false
2,609
h
#pragma once #include <windows.h> #include <io.h> #include <commctrl.h> #include <shlobj.h> #include "UIWindow.h" #include "Diagnostics.h" #include "UIHandler.h" #include "UIBanner.h" #include "MultiContent.h" #include "UIRect.h" #include "UIPicButton.h" #include "StandardEncryption.h" #include "SingleFileInfo.h" class EncryptWindow : public UIWindow { public: EncryptWindow (); ~EncryptWindow (); void SetDiagnostics (Diagnostics *pdiag); void DoSomething (); void DoEncryption (char *szVaultpath); void AddFileInfo (char *szFilepath, char *szRootdir, bool IsDir); void AddFileInfo (char *szFilepath, bool IsDir); void DoBlankSetup (); void ClearFileInfo (); void GetPathOnly (char *szInpath, char *szOutpath, char *szOutfile, char *szSep); void StripStartPath (char *szStartpath, char *szFullpath, char *szOutpath); void DoDecryption (); void Initialise (HWND hWnd, unsigned int uID); void OutputInt (LPCSTR lpszText, int iValue); void OutputText (LPCSTR lpszText); void OutputText (LPCSTR lpszName, LPCSTR lpszValue); void SetPassword (char *szPassword); int m_idecrypterrorcount; private: // Private Member Variables & objects // The UI Handler required for multiple handling of custom controls. UIHandler m_uihandler; // ID ofthis window - required for window class registration purposes unsigned int m_ID; // Global Window Handle HWND m_hwnd; HWND m_parenthwnd; HWND m_hwndprogress; // DynList storing all of the File Infos // which have been added to encrypt DynList m_dlFileinfolist; // Flag indicating if we're using diagnostics bool m_bUseDiagnostics; Diagnostics *m_pdiag; bool m_binitialised; StandardEncryption m_enc; char m_szPassword[SIZE_STRING]; // Registered class name // We need a different class name for every instance of // this window. This class name // Is created by the Initialise routine // with a uID value suffixed to the end char m_szClassname[SIZE_STRING]; // event notification from base class void OnDestroy (HWND hWnd); void OnCreate (HWND hWnd); void OnClose (HWND hWnd); void OnCommand (HWND hWnd, WPARAM wParam, LPARAM lParam); void OnUICommand (HWND hWnd, WPARAM wParam, LPARAM lParam); void OnUIScroll (HWND hWnd, WPARAM wParam, LPARAM lParam); void OnPaint (HWND hWnd); void OnTimer (WPARAM wParam); void OnMouseMove (HWND hWnd, int mouseXPos, int mouseYPos); void OnLButtonDown (HWND hWnd); void OnLButtonUp (HWND hWnd); };
[ "ddraper@06f4e086-0d69-e349-ad0a-cc76533d4475" ]
[ [ [ 1, 95 ] ] ]
a282f5be740518c901b85bc778c139fe72644a04
cfc9acc69752245f30ad3994cce0741120e54eac
/bikini/private/source/flash/avm2.cpp
ca6fcee94a22be1d30e4067cd8fb0dc19610f233
[]
no_license
Heartbroken/bikini-iii
3b7852d1af722b380864ac87df57c37862eb759b
93ffa5d43d9179b7c5e7f7c2df9df7dafd79a739
refs/heads/master
2020-03-28T00:41:36.281253
2009-04-30T14:58:10
2009-04-30T14:58:10
37,190,689
0
0
null
null
null
null
UTF-8
C++
false
false
3,479
cpp
/*---------------------------------------------------------------------------------------------*//* Binary Kinematics 3 - C++ Game Programming Library Copyright (C) 2008 Viktor Reutzky [email protected] *//*---------------------------------------------------------------------------------------------*/ #include "header.hpp" namespace bk { /*--------------------------------------------------------------------------------*/ namespace flash { /*-----------------------------------------------------------------------------*/ namespace as { /*--------------------------------------------------------------------------------*/ using namespace avmplus; struct _mmgc_helper { _mmgc_helper() : m_GC_p(0) { MMgc::GCHeap::Init(); MMgc::FixedMalloc::Init(); } ~_mmgc_helper() { if(m_GC_p) delete m_GC_p; MMgc::FixedMalloc::Destroy(); MMgc::GCHeap::Destroy(); } MMgc::GC* get_GC() { if(m_GC_p == 0) m_GC_p = new MMgc::GC(MMgc::GCHeap::GetGCHeap()); return m_GC_p; } //MMgc::GCHeap* get_heap() { // return MMgc::GCHeap::GetGCHeap(); //} private: MMgc::GC *m_GC_p; }; static _mmgc_helper sg_mmgc_helper; // avm2 avm2::avm2() : avmplus::AvmCore(sg_mmgc_helper.get_GC()), m_toplevel_p(0) { //config.verbose = true; initBuiltinPool(); m_toplevel_p = initTopLevel(); } bool avm2::do_ABC(pointer _data, uint _size) { avmplus::ReadOnlyScriptBufferImpl l_script((byte*)_data, _size); TRY(this, kCatchAction_ReportAsError) { handleActionBlock(avmplus::ScriptBuffer(&l_script), 0, m_toplevel_p->domainEnv(), m_toplevel_p, 0, 0); } CATCH(avmplus::Exception* e) { std::cerr << string(e->atom) << "\n"; } END_CATCH END_TRY return true; } void avm2::interrupt(avmplus::MethodEnv *env) { } void avm2::stackOverflow(avmplus::MethodEnv *env) { } } /* namespace as -------------------------------------------------------------------------------*/ } /* namespace flash ----------------------------------------------------------------------------*/ } /* namespace bk -------------------------------------------------------------------------------*/ // #ifdef AVMPLUS_MOPS namespace avmplus { // memory object glue bool Domain::isMemoryObject(Traits *t) const { assert(0); //Traits *cur = t; //// walk the traits to find a builtin pool //while(cur && !cur->pool->isBuiltin) // cur = cur->base; //// have a traits with a builtin pool //if(cur) //{ // Stringp uri = core->constantString("flash.utils"); // Namespace* ns = core->internNamespace(core->newNamespace(uri)); // // try to get traits from flash.utils.ByteArray // Traits *baTraits = cur->pool->getTraits(core->constantString("ByteArray"), ns); // // and see if the original traits contains it! // return t->containsInterface(baTraits) != 0; //} return false; } bool Domain::globalMemorySubscribe(ScriptObject *mem) const { assert(0); //if(isMemoryObject(mem->traits())) //{ // avmshell::ByteArray::GlobalMemoryNotifyFunc notify = &Domain::notifyGlobalMemoryChanged; // return ((avmshell::ByteArrayObject *)mem)->globalMemorySubscribe(this, notify); //} return false; } bool Domain::globalMemoryUnsubscribe(ScriptObject *mem) const { assert(0); //if(isMemoryObject(mem->traits())) //{ // return ((avmshell::ByteArrayObject *)mem)->globalMemoryUnsubscribe(this); //} return false; } } #endif
[ "my.mass.storage@f4697e32-284f-0410-9ba2-936c71724aef", "[email protected]" ]
[ [ [ 1, 16 ], [ 19, 41 ], [ 47, 49 ], [ 56, 116 ] ], [ [ 17, 18 ], [ 42, 46 ], [ 50, 55 ] ] ]
3c36bd2ae14f22872a388f8996a14ef2bfbf1969
1c80a726376d6134744d82eec3129456b0ab0cbf
/Project/C++/C++/vc源码/source/source/ViewerToolBar.cpp
e7cd3428766f1c4910759ee81551415bdd4779f7
[]
no_license
dabaopku/project_pku
338a8971586b6c4cdc52bf82cdd301d398ad909f
b97f3f15cdc3f85a9407e6bf35587116b5129334
refs/heads/master
2021-01-19T11:35:53.500533
2010-09-01T03:42:40
2010-09-01T03:42:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,264
cpp
// ViewerToolBar.cpp: implementation of the CViewerToolBar class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "History.h" #include "FlashNow.h" #include "ViewerFrame.h" #include "ViewerToolBar.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CViewerToolBar::CViewerToolBar() { } CViewerToolBar::~CViewerToolBar() { } void CViewerToolBar::OnDropDownButton(UINT nID) { int pos=CommandToIndex(nID); CRect rect; GetItemRect(pos,&rect); ClientToScreen(&rect); if(nID==ID_FILE_SAVE_NOW) { CMenu Menu; Menu.LoadMenu(IDM_SAVEPATH_POP); CMenu* pMenu = Menu.GetSubMenu(0); CStringQueue *pList=&(::theApp.p_Viewer->m_SavePath); int Count=pList->GetCount(); if(Count) { for(int i=0;i<Count;i++) { pMenu->InsertMenu(0,MF_BYPOSITION,0xff20+i,pList->GetAt(i)); } } else pMenu->RemoveMenu(0,MF_BYPOSITION); pMenu->TrackPopupMenu(TPM_RIGHTBUTTON, rect.left, rect.bottom, this); return; } }
[ "[email protected]@592586dc-1302-11df-8689-7786f20063ad" ]
[ [ [ 1, 58 ] ] ]
e377fa52af041935d6d2cb9f232d23119ea38ba3
d8f64a24453c6f077426ea58aaa7313aafafc75c
/GUI/ItemButton.h
650287ff0d350701811e39df7fe1594c7a01fa6d
[]
no_license
dotted/wfto
5b98591645f3ddd72cad33736da5def09484a339
6eebb66384e6eb519401bdd649ae986d94bcaf27
refs/heads/master
2021-01-20T06:25:20.468978
2010-11-04T21:01:51
2010-11-04T21:01:51
32,183,921
1
0
null
null
null
null
UTF-8
C++
false
false
1,361
h
#ifndef ITEM_BUTTON_H #define ITEM_BUTTON_H #include "TexturedGUIButton.h" using namespace GUI; #include "DKTextureList.h" namespace DK_GUI { class CItemButton: public CTexturedGUIButton { public: CItemButton(CDKTextureList *game_textures, GLint name); ~CItemButton(); virtual GLvoid on_mouse_over(); virtual GLvoid on_not_mouse_over(); virtual GLvoid on_mouse_down(); virtual GLvoid on_mouse_up(); virtual GLvoid on_mouse_out(); virtual GLvoid on_mouse_click(); virtual GLvoid draw(); virtual GLvoid init(GLint screen_width, GLint screen_height); virtual GLvoid set_extent(EXTENT extent); GLvoid set_top_texture(GLint top_texture); GLvoid fix_top_texture(); /* this buttons can be in different states: - unavailable: empty frame - needs to be researched/discovered - available but not used - available and used */ enum BUTTON_STATE{BS_UNAVAILABLE=0, BS_RESEARCH, BS_AVAILABLE_NOT_USED, BS_AVAILABLE_USED }; GLvoid set_button_state(BUTTON_STATE button_state); BUTTON_STATE get_button_state(); private: GLuint normal_texture, mouse_over_texture, mouse_down_texture, top_texture; EXTENT top_texture_extent; bool first_down; BUTTON_STATE button_state; CDKTextureList *game_textures; }; } #endif // ITEM_BUTTON_H
[ [ [ 1, 59 ] ] ]
0a9ef0702c0c7550c68996bb3bd36cf703920b7c
a381a69db3bd4f37266bf0c7129817ebb999e7b8
/vdash/src/fsd/XeXtractor.cpp
ce0ca50902ba188e172b48e64b3018aef56101e2
[]
no_license
oukiar/vdash
4420d6d6b462b7a833929b59d1ca232bd410e632
d2bff3090c7d1c081d5b7ab41abb963f03d6118b
refs/heads/master
2021-01-10T06:00:03.653067
2011-12-29T10:19:01
2011-12-29T10:19:01
49,607,897
0
0
null
null
null
null
UTF-8
C++
false
false
13,525
cpp
#include "stdafx.h" #include "XeXtractor.h" BOOL XeCryptBnQwBeSigVerifyCustom(XECRYPT_SIG * pSig, BYTE * pbHash, BYTE * pbSalt, XECRYPT_RSA * pRsa) { // Check our size and exponent if(pRsa->cqw != 0x20) return FALSE; if(pRsa->dwPubExp != 3 && pRsa->dwPubExp != 0x10001) return FALSE; QWORD inverse = XeCryptBnQwNeModInv(((XECRYPT_RSAPUB_2048*)pRsa)->aqwM[0]); QWORD signatureBuffer[0x20]; XeCryptBnQw_Copy((QWORD*)pSig, signatureBuffer, 0x20); DWORD exponent = pRsa->dwPubExp; while(exponent > 1) { exponent >>= 1; XeCryptBnQwNeModMul(signatureBuffer, signatureBuffer, signatureBuffer, inverse, ((XECRYPT_RSAPUB_2048*)pRsa)->aqwM, 0x20); } XeCryptBnQwNeModMul(signatureBuffer, (QWORD*)pSig, (QWORD*)pSig, inverse, ((XECRYPT_RSAPUB_2048*)pRsa)->aqwM, 0x20); XeCryptBnQwBeSigFormat((XECRYPT_SIG*)signatureBuffer, pbHash, pbSalt); return memcmp(pSig, signatureBuffer, 0x20 * 0x08) == 0; } XeXtractor::XeXtractor() { isOpen = FALSE; isRetailXex = FALSE; FullHeader = NULL; Header = NULL; DirectoryEntries = NULL; SecurityInfo = NULL; PageInfo = NULL; } XeXtractor::~XeXtractor() { CloseXex(); } HRESULT XeXtractor::OpenXex(string XexPath) { // Close if already open CloseXex(); // Check if the file exists first if(!FileExists(XexPath)) { return 1; } // Open our xex and begin to read it fopen_s(&fHandle, XexPath.c_str(), "rb"); IMAGE_XEX_HEADER tempHeader; fread(&tempHeader, sizeof(IMAGE_XEX_HEADER), 1, fHandle); // Make sure its a valid xex if(tempHeader.Magic != IMAGE_XEX_HEADER_MAGIC){ fclose(fHandle); return 2; } // Its a valid xex so lets go back and read the full header FullHeader = (PBYTE)malloc(tempHeader.SizeOfHeaders); fseek(fHandle, 0, SEEK_SET); fread(FullHeader, tempHeader.SizeOfHeaders, 1, fHandle); Header = (PIMAGE_XEX_HEADER)FullHeader; DirectoryEntries = (PIMAGE_XEX_DIRECTORY_ENTRY)(Header + 1); SecurityInfo = (PXEX_SECURITY_INFO)(FullHeader + Header->SecurityInfo); PageInfo = (PHV_PAGE_INFO)(SecurityInfo + 1); // Lets do some basic verficiation to "try" and detect xex type BYTE digest[0x14]; XeCryptRotSumSha((byte*)&SecurityInfo->ImageInfo.InfoSize, SecurityInfo->ImageInfo.InfoSize - 0x100, 0, 0, digest, 0x14); XECRYPT_RSAPUB_2048 pubRsaKey; WORD keySize = 0x110; XeKeysGetKey(0x39, &pubRsaKey, &keySize); // Verify our signature -- if the RSA signatures do not match, it is assumed devkit xex BOOL validSignature = XeCryptBnQwBeSigVerifyCustom( (XECRYPT_SIG*)SecurityInfo->ImageInfo.Signature, digest, (BYTE*)XexSalt, (XECRYPT_RSA*)&pubRsaKey); // if the signature is not valid- we still need to check for a zerostring RSA signature if(!validSignature) { validSignature = TRUE; for(int x = 0; x < 0x100; x++) if(SecurityInfo->ImageInfo.Signature[x] != 0x00) { validSignature = FALSE; break; } } // This will let us know what public key we used, a devkit or a retail DWORD consoleType = 0; XeKeysGetConsoleTypeCustom(&consoleType); if(consoleType == CONSOLETYPE_RETAIL && validSignature) isRetailXex = TRUE; // Its a retail and a valid signature else if(consoleType == CONSOLETYPE_RETAIL && !validSignature) isRetailXex = FALSE; // Its a retail and not a valid signature else if(consoleType != CONSOLETYPE_RETAIL && validSignature) isRetailXex = FALSE; // Its not a retail and a valid signature else if(consoleType != CONSOLETYPE_RETAIL && !validSignature) isRetailXex = TRUE; // Its not a retail but also not a valid signature // Our file is now open isOpen = TRUE; return S_OK; } HRESULT XeXtractor::CloseXex() { if(isOpen) { // Free all our header stuff Header = NULL; DirectoryEntries = NULL; SecurityInfo = NULL; PageInfo = NULL; free(FullHeader); // Close our file fclose(fHandle); isOpen = FALSE; } return S_OK; } HRESULT XeXtractor::GetOptionalHeader(DWORD OptHeaderKey, PVOID* Data) { // Loop through all our headers and try and find the key DWORD x; BOOL found = FALSE; for(x = 0; x < Header->HeaderDirectoryEntryCount; x++) { if(DirectoryEntries[x].Key == OptHeaderKey) { found = TRUE; break; } } // Make sure we found a key if(!found) return 1; // We found our key so lets get our data size DWORD dataSize = OptHeaderKey & 0xFF; // If our data size is 1 dword then its stored in our data if(dataSize == 1){ *Data = &DirectoryEntries[x].Value; return S_OK; } // Its stored in a optional header *Data = FullHeader + DirectoryEntries[x].Value; return S_OK; } HRESULT XeXtractor::CalculateDecryptKey(PBYTE DecryptKey){ // Setup our ctx and iv XECRYPT_AES_STATE ctx; ZeroMemory(&ctx, sizeof(XECRYPT_AES_STATE)); BYTE iv[16]; ZeroMemory(iv, 16); // Set our key to use if(isRetailXex) XeCryptAesKey(&ctx, (BYTE*)RetailKey); else XeCryptAesKey(&ctx, (BYTE*)DevkitKey); // Get our decrypt key XeCryptAesCbc(&ctx, SecurityInfo->ImageInfo.ImageKey, 16, DecryptKey, iv, 0); return S_OK; } HRESULT XeXtractor::GetBaseFile(PBYTE* Basefile, PDWORD Size){ // Get our base file format PXEX_FILE_DATA_DESCRIPTOR descriptor = NULL; if(GetOptionalHeader(DIRECTORY_KEY_BASEFILE_DESCRIPTOR, (PVOID*)&descriptor) != S_OK) return 1; // Setup our result HRESULT result = S_OK; // Alocate our space *Size = SecurityInfo->ImageSize; *Basefile = (PBYTE)malloc(SecurityInfo->ImageSize); ZeroMemory(*Basefile, SecurityInfo->ImageSize); PBYTE BasefilePos = *Basefile; // Setup our decrypt key incase we need it BYTE key[16]; CalculateDecryptKey(key); XECRYPT_AES_STATE ctx; BYTE iv[16]; ZeroMemory(iv, 16); XeCryptAesKey(&ctx, key); // Seek to our data location DWORD sizeLeft = *Size; fseek(fHandle, Header->SizeOfHeaders, SEEK_SET); // Get our format if(descriptor->Format == FILE_DATA_FORMAT_NOT_COMPRESSED){ // Get our block count and ptr DWORD blockCount = (descriptor->Size - sizeof(XEX_FILE_DATA_DESCRIPTOR)) / sizeof(XEX_RAW_DATA_DESCRIPTOR); PXEX_RAW_DATA_DESCRIPTOR rawBlocks = (PXEX_RAW_DATA_DESCRIPTOR)(descriptor + 1); // Loop through all our blocks for(DWORD x = 0; x < blockCount; x++){ // Read our data into our basefile and decrypt if needed fread(BasefilePos, rawBlocks[x].DataSize, 1, fHandle); if(descriptor->Flags & FILE_DATA_FLAGS_ENCRYPTED) XeCryptAesCbc(&ctx, BasefilePos, rawBlocks[x].DataSize, BasefilePos, iv, 0); BasefilePos += (rawBlocks[x].DataSize + rawBlocks[x].ZeroSize); sizeLeft -= (rawBlocks[x].DataSize + rawBlocks[x].ZeroSize); } } else if(descriptor->Format == FILE_DATA_FORMAT_COMPRESSED) { // Get our base info and block info PXEX_COMPRESSED_DATA_DESCRIPTOR baseInfo = (PXEX_COMPRESSED_DATA_DESCRIPTOR)(descriptor + 1); XEX_DATA_DESCRIPTOR block; memcpy(&block, &baseInfo->FirstDescriptor, sizeof(XEX_DATA_DESCRIPTOR)); // Create decompression context DWORD maxSize = 0x8000; DWORD ldiCtx = 0xFFFFFFFF; DWORD unknown = 0; LZX_DECOMPRESS lzx = {baseInfo->WindowSize, 1}; VOID* allocate = malloc(0x23200 + baseInfo->WindowSize); if(LDICreateDecompression(&maxSize, &lzx, 0, 0, allocate, &unknown, &ldiCtx) != 0) { result = 2; free(allocate); goto CLEANUP; } // Loop through and decompress while(result == S_OK && block.Size > 0){ // Read our block and decrypt if we must PBYTE buffer = (PBYTE)malloc(block.Size); fread(buffer, block.Size, 1, fHandle); if(descriptor->Flags & FILE_DATA_FLAGS_ENCRYPTED) XeCryptAesCbc(&ctx, buffer, block.Size, buffer, iv, 0); // Verify our hash for this block BYTE digest[0x14]; XeCryptSha(buffer, block.Size, NULL, 0, NULL, 0, digest, 0x14); if(memcmp(digest, block.DataDigest, 0x14) != 0) { result = 3; break; } // Copy over our next block descriptor memcpy(&block, buffer, sizeof(XEX_DATA_DESCRIPTOR)); // Decompress all the sub blocks within this block PWORD subBlockSize = (PWORD)(buffer + sizeof(XEX_DATA_DESCRIPTOR)); PBYTE subBlockData = (PBYTE)(subBlockSize + 1); while(*subBlockSize > 0){ // Decompress our data DWORD decompressedSize = (sizeLeft < 0x8000) ? sizeLeft : 0x8000; if(LDIDecompress(ldiCtx, subBlockData, *subBlockSize, BasefilePos, &decompressedSize) != 0) { result = 4; break; } // Setup the next block BasefilePos += decompressedSize; sizeLeft -= decompressedSize; subBlockSize = (PWORD)(subBlockData + *subBlockSize); subBlockData = (PBYTE)(subBlockSize + 1); } // Free our temp block free(buffer); } // Clean up our buffers LDIDestroyDecompression(ldiCtx); free(allocate); } else { result = 5; } // Verify our image now BasefilePos = *Basefile; BYTE pageDigest[0x14]; PBYTE pageVerifyDigest = SecurityInfo->ImageInfo.ImageHash; DWORD pageSize = (SecurityInfo->ImageInfo.ImageFlags & IMAGE_FLAG_PAGE_SIZE_4KB) ? 0x1000 : 0x10000; for(DWORD x = 0; x < SecurityInfo->PageDescriptorCount; x++) { DWORD currentPageSize = PageInfo[x].PageDescription.Size * pageSize; XeCryptSha(BasefilePos, currentPageSize, (PBYTE)&PageInfo[x], sizeof(HV_PAGE_INFO), NULL, 0, pageDigest, 0x14); if(memcmp(pageDigest, pageVerifyDigest, 0x14) != 0) { /*result = 6;*/ break; } BasefilePos += currentPageSize; pageVerifyDigest = PageInfo[x].DataDigest; } CLEANUP: if(result != S_OK) { free(*Basefile); *Basefile = NULL; *Size = 0; } return result; } HRESULT XeXtractor::ExtractResource(string ResrouceName, PBYTE* Resource, PDWORD Size){ // Get our resource header PXEX_SECTION_INFO sectionInfo = NULL; if(GetOptionalHeader(DIRECTORY_KEY_SECTION, (PVOID*)&sectionInfo) != S_OK) return 1; // Now lets try and find our resource name int resourceCount = (sectionInfo->Size - sizeof(DWORD)) / sizeof(XEX_SECTION_HEADER); bool found = false; PXEX_SECTION_HEADER resource = NULL; CHAR resTitle[9]; ZeroMemory(resTitle, 9); for(int x = 0; x < resourceCount; x++){ memcpy(resTitle, sectionInfo->Section[x].SectionName, 8); if(strcmp(resTitle, ResrouceName.c_str()) == 0){ resource = &sectionInfo->Section[x]; found = true; break; } } if(!found) { return 2; } // Okay we got our resource info lets get our basefile PBYTE baseFile; DWORD baseSize; if(GetBaseFile(&baseFile, &baseSize) != S_OK) { return 3; } // Now lets allocate our resource and copy from our basefile *Resource = (PBYTE)malloc(resource->VirtualSize); *Size = resource->VirtualSize; PBYTE resourceData = baseFile + (resource->VirtualAddress - SecurityInfo->ImageInfo.LoadAddress); memcpy(*Resource, resourceData, resource->VirtualSize); // All done lets clean up free(baseFile); return S_OK; } HRESULT XeXtractor::ExtractTitleSPA(PBYTE* Resrouce, PDWORD Size){ // Get our execution id PXEX_EXECUTION_ID executionId = NULL; if(GetOptionalHeader(DIRECTORY_KEY_EXECUTION_ID, (PVOID*)&executionId) != S_OK) return 2; // Get a resource using our title id char tid[9]; sprintf(tid,"%08X", executionId->TitleID); return ExtractResource(tid, Resrouce, Size); } HRESULT XeXtractor::GetExecutionId(PXEX_EXECUTION_ID ExecutionId){ // Get our execution id PXEX_EXECUTION_ID executionId = NULL; if(GetOptionalHeader(DIRECTORY_KEY_EXECUTION_ID, (PVOID*)&executionId) != S_OK) return 1; // Copy it over memcpy(ExecutionId, executionId, sizeof(XEX_EXECUTION_ID)); // Clean up return S_OK; } HRESULT XeXtractor::GetRating(BYTE RatingType, PBYTE Rating) { // Get our raitings PXEX_GAME_RATINGS ratings = NULL; if(GetOptionalHeader(DIRECTORY_KEY_GAME_RATINGS, (PVOID*)&ratings) != S_OK) return 1; // Now get the proper one for our type *Rating = ratings->Ratings[RatingType]; return S_OK; } HRESULT XeXtractor::PrintInfo() { // Display some debug information DebugMsg("XeXtractor", "Magic : %08x", Header->Magic); DebugMsg("XeXtractor", "ModuleFlag : %08x", Header->ModuleFlags); DebugMsg("XeXtractor", "DataOffset : %08x", Header->SizeOfHeaders); DebugMsg("XeXtractor", "SecInfoOff : %08x", Header->SecurityInfo); DebugMsg("XeXtractor", "OptHeadCnt : %08x", Header->HeaderDirectoryEntryCount); DebugMsg("XeXtractor", "GameRegion : %08x", SecurityInfo->ImageInfo.GameRegion); return S_OK; } BOOL XeXtractor::IsKinectEnabled() { // Check 3 different privilages to get a good idea if this is a kinect game if(CheckExecutablePrivilege(XEX_PRIVILEGE_NATAL_TILT_CONTROL) || CheckExecutablePrivilege(XEX_PRIVILEGE_TITLE_REQUIRES_SKELETAL_TRACKING) || CheckExecutablePrivilege(XEX_PRIVILEGE_TITLE_SUPPORTS_SKELETAL_TRACKING)) return TRUE; // None of them are enabled, so we are guessing this isnt a kinect game return FALSE; } BOOL XeXtractor::CheckExecutablePrivilege(DWORD Privilege) { // Get the key to use DWORD privilegeKey = ((Privilege & 0xFFFFFFE0) + 0x6000) << 3; // See if we have it in our header, if not just return false DWORD* privilegeValue = NULL; if(GetOptionalHeader(privilegeKey, (PVOID*)&privilegeValue) != S_OK) return FALSE; // We have it now lets check our value DWORD privilageMask = 1 << (Privilege & 0x1F); if((*privilegeValue & privilageMask) == privilageMask) return TRUE; // This privilege isnt enabled return FALSE; }
[ [ [ 1, 422 ] ] ]
242d2c4040dff2d525ae2e7df59a718de6256707
037faae47a5b22d3e283555e6b5ac2a0197faf18
/branches/pcsx2_0.9.1/memcpy_amd.cpp
1ebd68d323d4605f08a061d7104f82ee21104c26
[]
no_license
isabella232/pcsx2-sourceforge
6e5aac8d0b476601bfc8fa83ded66c1564b8c588
dbb2c3a010081b105a8cba0c588f1e8f4e4505c6
refs/heads/master
2023-03-18T22:23:15.102593
2008-11-17T20:10:17
2008-11-17T20:10:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,262
cpp
/****************************************************************************** Copyright (c) 2001 Advanced Micro Devices, Inc. LIMITATION OF LIABILITY: THE MATERIALS ARE PROVIDED *AS IS* WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT OF THIRD-PARTY INTELLECTUAL PROPERTY, OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL AMD OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, LOSS OF INFORMATION) ARISING OUT OF THE USE OF OR INABILITY TO USE THE MATERIALS, EVEN IF AMD HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME JURISDICTIONS PROHIBIT THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO YOU. AMD does not assume any responsibility for any errors which may appear in the Materials nor any responsibility to support or update the Materials. AMD retains the right to make changes to its test specifications at any time, without notice. NO SUPPORT OBLIGATION: AMD is not obligated to furnish, support, or make any further information, software, technical information, know-how, or show-how available to you. So that all may benefit from your experience, please report any problems or suggestions about this software to [email protected] AMD Developer Technologies, M/S 585 Advanced Micro Devices, Inc. 5900 E. Ben White Blvd. Austin, TX 78741 [email protected] ******************************************************************************/ #include <assert.h> #include <xmmintrin.h> #include <emmintrin.h> /***************************************************************************** MEMCPY_AMD.CPP ******************************************************************************/ // Very optimized memcpy() routine for AMD Athlon and Duron family. // This code uses any of FOUR different basic copy methods, depending // on the transfer size. // NOTE: Since this code uses MOVNTQ (also known as "Non-Temporal MOV" or // "Streaming Store"), and also uses the software prefetch instructions, // be sure you're running on Athlon/Duron or other recent CPU before calling! #define TINY_BLOCK_COPY 64 // upper limit for movsd type copy // The smallest copy uses the X86 "movsd" instruction, in an optimized // form which is an "unrolled loop". #define IN_CACHE_COPY 2 * 1024 // upper limit for movq/movq copy w/SW prefetch // Next is a copy that uses the MMX registers to copy 8 bytes at a time, // also using the "unrolled loop" optimization. This code uses // the software prefetch instruction to get the data into the cache. #define UNCACHED_COPY 4 * 1024 // upper limit for movq/movntq w/SW prefetch // For larger blocks, which will spill beyond the cache, it's faster to // use the Streaming Store instruction MOVNTQ. This write instruction // bypasses the cache and writes straight to main memory. This code also // uses the software prefetch instruction to pre-read the data. // USE 64 * 1024 FOR THIS VALUE IF YOU'RE ALWAYS FILLING A "CLEAN CACHE" #define BLOCK_PREFETCH_COPY infinity // no limit for movq/movntq w/block prefetch #define CACHEBLOCK 80h // number of 64-byte blocks (cache lines) for block prefetch // For the largest size blocks, a special technique called Block Prefetch // can be used to accelerate the read operations. Block Prefetch reads // one address per cache line, for a series of cache lines, in a short loop. // This is faster than using software prefetch. The technique is great for // getting maximum read bandwidth, especially in DDR memory systems. // Inline assembly syntax for use with Visual C++ extern "C" { #ifdef __WIN32__ #include <windows.h> #endif #include "ps2etypes.h" #include "misc.h" void FreezeMMXRegs_(int save); void FreezeXMMRegs_(int save); extern u32 g_EEFreezeRegs; #define FreezeMMXRegs(save) if( g_EEFreezeRegs && CHECK_EEREC ) { FreezeMMXRegs_(save); } #define FreezeXMMRegs(save) if( g_EEFreezeRegs && CHECK_EEREC ) { FreezeXMMRegs_(save); } #ifdef _DEBUG extern char g_globalMMXLocked, g_globalMMXSaved; void checkregs() { assert( !g_globalMMXLocked || g_globalMMXSaved ); } #endif void * memcpy_amd(void *dest, const void *src, size_t n) { FreezeMMXRegs(1); #ifdef _DEBUG __asm call checkregs #endif __asm { mov ecx, [n] ; number of bytes to copy mov edi, [dest] ; destination mov esi, [src] ; source mov ebx, ecx ; keep a copy of count cld cmp ecx, TINY_BLOCK_COPY jb $memcpy_ic_3 ; tiny? skip mmx copy cmp ecx, 32*1024 ; don't align between 32k-64k because jbe $memcpy_do_align ; it appears to be slower cmp ecx, 64*1024 jbe $memcpy_align_done $memcpy_do_align: mov ecx, 8 ; a trick that's faster than rep movsb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update copy count neg ecx ; set up to jump into the array add ecx, offset $memcpy_align_done jmp ecx ; jump to array of movsb's align 4 movsb movsb movsb movsb movsb movsb movsb movsb $memcpy_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to copy shr ecx, 6 ; get 64-byte block count jz $memcpy_ic_2 ; finish the last few bytes cmp ecx, IN_CACHE_COPY/64 ; too big 4 cache? use uncached copy jae $memcpy_uc_test // This is small block copy that uses the MMX registers to copy 8 bytes // at a time. It uses the "unrolled loop" optimization, and also uses // the software prefetch instruction to get the data into the cache. align 16 $memcpy_ic_1: ; 64-byte block copies, in-cache copy prefetchnta [esi + (200*64/34+192)] ; start reading ahead movq mm0, [esi+0] ; read 64 bits movq mm1, [esi+8] movq [edi+0], mm0 ; write 64 bits movq [edi+8], mm1 ; note: the normal movq writes the movq mm2, [esi+16] ; data to cache; a cache line will be movq mm3, [esi+24] ; allocated as needed, to store the data movq [edi+16], mm2 movq [edi+24], mm3 movq mm0, [esi+32] movq mm1, [esi+40] movq [edi+32], mm0 movq [edi+40], mm1 movq mm2, [esi+48] movq mm3, [esi+56] movq [edi+48], mm2 movq [edi+56], mm3 add esi, 64 ; update source pointer add edi, 64 ; update destination pointer dec ecx ; count down jnz $memcpy_ic_1 ; last 64-byte block? $memcpy_ic_2: mov ecx, ebx ; has valid low 6 bits of the byte count $memcpy_ic_3: shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memcpy_last_few jmp ecx ; jump to array of movsd's $memcpy_uc_test: cmp ecx, UNCACHED_COPY/64 ; big enough? use block prefetch copy jae $memcpy_bp_1 $memcpy_64_test: or ecx, ecx ; tail end of block prefetch will jump here jz $memcpy_ic_2 ; no more 64-byte blocks left // For larger blocks, which will spill beyond the cache, it's faster to // use the Streaming Store instruction MOVNTQ. This write instruction // bypasses the cache and writes straight to main memory. This code also // uses the software prefetch instruction to pre-read the data. align 16 $memcpy_uc_1: ; 64-byte blocks, uncached copy prefetchnta [esi + (200*64/34+192)] ; start reading ahead movq mm0,[esi+0] ; read 64 bits add edi,64 ; update destination pointer movq mm1,[esi+8] add esi,64 ; update source pointer movq mm2,[esi-48] movntq [edi-64], mm0 ; write 64 bits, bypassing the cache movq mm0,[esi-40] ; note: movntq also prevents the CPU movntq [edi-56], mm1 ; from READING the destination address movq mm1,[esi-32] ; into the cache, only to be over-written movntq [edi-48], mm2 ; so that also helps performance movq mm2,[esi-24] movntq [edi-40], mm0 movq mm0,[esi-16] movntq [edi-32], mm1 movq mm1,[esi-8] movntq [edi-24], mm2 movntq [edi-16], mm0 dec ecx movntq [edi-8], mm1 jnz $memcpy_uc_1 ; last 64-byte block? jmp $memcpy_ic_2 ; almost done // For the largest size blocks, a special technique called Block Prefetch // can be used to accelerate the read operations. Block Prefetch reads // one address per cache line, for a series of cache lines, in a short loop. // This is faster than using software prefetch. The technique is great for // getting maximum read bandwidth, especially in DDR memory systems. $memcpy_bp_1: ; large blocks, block prefetch copy cmp ecx, CACHEBLOCK ; big enough to run another prefetch loop? jl $memcpy_64_test ; no, back to regular uncached copy mov eax, CACHEBLOCK / 2 ; block prefetch loop, unrolled 2X add esi, CACHEBLOCK * 64 ; move to the top of the block align 16 $memcpy_bp_2: mov edx, [esi-64] ; grab one address per cache line mov edx, [esi-128] ; grab one address per cache line sub esi, 128 ; go reverse order to suppress HW prefetcher dec eax ; count down the cache lines jnz $memcpy_bp_2 ; keep grabbing more lines into cache mov eax, CACHEBLOCK ; now that it's in cache, do the copy align 16 $memcpy_bp_3: movq mm0, [esi ] ; read 64 bits movq mm1, [esi+ 8] movq mm2, [esi+16] movq mm3, [esi+24] movq mm4, [esi+32] movq mm5, [esi+40] movq mm6, [esi+48] movq mm7, [esi+56] add esi, 64 ; update source pointer movntq [edi ], mm0 ; write 64 bits, bypassing cache movntq [edi+ 8], mm1 ; note: movntq also prevents the CPU movntq [edi+16], mm2 ; from READING the destination address movntq [edi+24], mm3 ; into the cache, only to be over-written, movntq [edi+32], mm4 ; so that also helps performance movntq [edi+40], mm5 movntq [edi+48], mm6 movntq [edi+56], mm7 add edi, 64 ; update dest pointer dec eax ; count down jnz $memcpy_bp_3 ; keep copying sub ecx, CACHEBLOCK ; update the 64-byte block count jmp $memcpy_bp_1 ; keep processing chunks // The smallest copy uses the X86 "movsd" instruction, in an optimized // form which is an "unrolled loop". Then it handles the last few bytes. align 4 movsd movsd ; perform last 1-15 dword copies movsd movsd movsd movsd movsd movsd movsd movsd ; perform last 1-7 dword copies movsd movsd movsd movsd movsd movsd $memcpy_last_few: ; dword aligned from before movsd's mov ecx, ebx ; has valid low 2 bits of the byte count and ecx, 11b ; the last few cows must come home jz $memcpy_final ; no more, let's leave rep movsb ; the last 1, 2, or 3 bytes $memcpy_final: emms ; clean up the MMX state sfence ; flush the write buffer mov eax, [dest] ; ret value = destination pointer } } // mmx memcpy implementation, size has to be a multiple of 8 // returns 0 is equal, nonzero value if not equal // ~10 times faster than standard memcmp // (zerofrog) int memcmp_mmx(const void* src1, const void* src2, int cmpsize) { FreezeMMXRegs(1); assert( (cmpsize&7) == 0 ); __asm { mov ecx, cmpsize mov edi, src1 mov esi, src2 mov ebx, ecx cmp ecx, 32 jl Done4 // custom test first 8 to make sure things are ok movq mm0, [esi] movq mm1, [esi+8] pcmpeqd mm0, [edi] pcmpeqd mm1, [edi+8] pand mm0, mm1 movq mm2, [esi+16] pmovmskb eax, mm0 movq mm3, [esi+24] // check if eq cmp eax, 0xff je NextComp mov eax, 1 jmp End NextComp: pcmpeqd mm2, [edi+16] pcmpeqd mm3, [edi+24] pand mm2, mm3 pmovmskb eax, mm2 // check if eq cmp eax, 0xff je Continue mov eax, 1 jmp End sub ecx, 32 add esi, 32 add edi, 32 cmp ecx, 64 jl Done8 Cmp8: movq mm0, [esi] movq mm1, [esi+8] movq mm2, [esi+16] movq mm3, [esi+24] movq mm4, [esi+32] movq mm5, [esi+40] movq mm6, [esi+48] movq mm7, [esi+56] pcmpeqd mm0, [edi] pcmpeqd mm1, [edi+8] pcmpeqd mm2, [edi+16] pcmpeqd mm3, [edi+24] pand mm0, mm1 pcmpeqd mm4, [edi+32] pand mm0, mm2 pcmpeqd mm5, [edi+40] pand mm0, mm3 pcmpeqd mm6, [edi+48] pand mm0, mm4 pcmpeqd mm7, [edi+56] pand mm0, mm5 pand mm0, mm6 pand mm0, mm7 pmovmskb eax, mm0 // check if eq cmp eax, 0xff je Continue mov eax, 1 jmp End Continue: sub ecx, 64 add esi, 64 add edi, 64 cmp ecx, 64 jge Cmp8 Done8: test ecx, 0x20 jz Done4 movq mm0, [esi] movq mm1, [esi+8] movq mm2, [esi+16] movq mm3, [esi+24] pcmpeqd mm0, [edi] pcmpeqd mm1, [edi+8] pcmpeqd mm2, [edi+16] pcmpeqd mm3, [edi+24] pand mm0, mm1 pand mm0, mm2 pand mm0, mm3 pmovmskb eax, mm0 sub ecx, 32 add esi, 32 add edi, 32 Done4: cmp ecx, 24 jne Done2 movq mm0, [esi] movq mm1, [esi+8] movq mm2, [esi+16] pcmpeqd mm0, [edi] pcmpeqd mm1, [edi+8] pcmpeqd mm2, [edi+16] pand mm0, mm1 pand mm0, mm2 pmovmskb eax, mm0 // check if eq xor edx, edx cmp eax, 0xff cmove eax, edx jmp End Done2: cmp ecx, 16 jne Done1 movq mm0, [esi] movq mm1, [esi+8] pcmpeqd mm0, [edi] pcmpeqd mm1, [edi+8] pand mm0, mm1 pmovmskb eax, mm0 // check if eq xor edx, edx cmp eax, 0xff cmove eax, edx jmp End Done1: cmp ecx, 8 jne Done mov eax, [esi] mov ebx, [esi+4] cmp eax, [edi] je Next mov eax, 1 jmp End Next: cmp ebx, [edi+4] je Done mov eax, 1 jmp End Done: xor eax, eax End: emms } } // returns the xor of all elements, cmpsize has to be mult of 8 void memxor_mmx(void* dst, const void* src1, int cmpsize) { FreezeMMXRegs(1); assert( (cmpsize&7) == 0 ); __asm { mov ecx, cmpsize mov esi, src1 mov ebx, ecx mov edx, dst cmp ecx, 64 jl Setup4 movq mm0, [esi] movq mm1, [esi+8] movq mm2, [esi+16] movq mm3, [esi+24] movq mm4, [esi+32] movq mm5, [esi+40] movq mm6, [esi+48] movq mm7, [esi+56] sub ecx, 64 add esi, 64 cmp ecx, 64 jl End8 Cmp8: pxor mm0, [esi] pxor mm1, [esi+8] pxor mm2, [esi+16] pxor mm3, [esi+24] pxor mm4, [esi+32] pxor mm5, [esi+40] pxor mm6, [esi+48] pxor mm7, [esi+56] sub ecx, 64 add esi, 64 cmp ecx, 64 jge Cmp8 End8: pxor mm0, mm4 pxor mm1, mm5 pxor mm2, mm6 pxor mm3, mm7 cmp ecx, 32 jl End4 pxor mm0, [esi] pxor mm1, [esi+8] pxor mm2, [esi+16] pxor mm3, [esi+24] sub ecx, 32 add esi, 32 jmp End4 Setup4: cmp ecx, 32 jl Setup2 movq mm0, [esi] movq mm1, [esi+8] movq mm2, [esi+16] movq mm3, [esi+24] sub ecx, 32 add esi, 32 End4: pxor mm0, mm2 pxor mm1, mm3 cmp ecx, 16 jl End2 pxor mm0, [esi] pxor mm1, [esi+8] sub ecx, 16 add esi, 16 jmp End2 Setup2: cmp ecx, 16 jl Setup1 movq mm0, [esi] movq mm1, [esi+8] sub ecx, 16 add esi, 16 End2: pxor mm0, mm1 cmp ecx, 8 jl End1 pxor mm0, [esi] End1: movq [edx], mm0 jmp End Setup1: movq mm0, [esi] movq [edx], mm0 End: emms } } }
[ "zerofrog@23c756db-88ba-2448-99d7-e6e4c676ec84" ]
[ [ [ 1, 590 ] ] ]
7807a94c71110281c39f138e6a5f77174bf4edd4
b5ab57edece8c14a67cc98e745c7d51449defcff
/Captain's Log/MainGame/Source/GameObjects/CActive.cpp
c4337b7aea38bf917605915f9bbbba0ff3801eb4
[]
no_license
tabu34/tht-captainslog
c648c6515424a6fcdb628320bc28fc7e5f23baba
72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2
refs/heads/master
2020-05-30T15:09:24.514919
2010-07-30T17:05:11
2010-07-30T17:05:11
32,187,254
0
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
#include "precompiled_header.h" #include "CActive.h" CActive::CActive() { ItemType(ITEMTYPE_ACTIVE); } void CActive::AddEffect() { CItem::AddEffect(); } void CActive::RemoveEffect() { }
[ "notserp007@34577012-8437-c882-6fb8-056151eb068d", "dpmakin@34577012-8437-c882-6fb8-056151eb068d" ]
[ [ [ 1, 1 ] ], [ [ 2, 17 ] ] ]
2e28eac4b2da7169992bf33cbc6a80a472a2d127
38d9a3374e52b67ca01ed8bbf11cd0b878cce2a5
/branches/tbeta/CCV-fid/libs/openFrameworks/video/ofVideoGrabber.cpp
55216e473f8ac9b8e29e8d8e5bd86bbbfecdcb13
[]
no_license
hugodu/ccv-tbeta
8869736cbdf29685a62d046f4820e7a26dcd05a7
246c84989eea0b5c759944466db7c591beb3c2e4
refs/heads/master
2021-04-01T10:39:18.368714
2011-03-09T23:05:24
2011-03-09T23:05:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,988
cpp
#include "ofVideoGrabber.h" #include "ofUtils.h" #ifdef OF_VIDEO_CAPTURE_V4L #include "ofV4LUtils.h" #endif //-------------------------------------------------------------------- ofVideoGrabber::ofVideoGrabber(){ //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- initializeQuicktime(); bSgInited = false; pixels = NULL; gSeqGrabber = NULL; offscreenGWorldPixels = NULL; //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_DIRECTSHOW //--------------------------------- bVerbose = false; bDoWeNeedToResize = false; //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_V4L // kept around if people have unicap issues... //-------------------------------- bV4LGrabberInited = false; //--------------------------------- #endif //--------------------------------- // common bIsFrameNew = false; bVerbose = false; bGrabberInited = false; bUseTexture = true; bChooseDevice = false; deviceID = 0; width = 320; // default setting height = 240; // default setting pixels = NULL; } //-------------------------------------------------------------------- ofVideoGrabber::~ofVideoGrabber(){ close(); //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- if (offscreenGWorldPixels != NULL){ delete[] offscreenGWorldPixels; } //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_UNICAP //-------------------------------- if(bGrabberInited) ucGrabber.close_unicap(); //--------------------------------- #endif //--------------------------------- } //-------------------------------------------------------------------- void ofVideoGrabber::listDevices(){ //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- bool bNeedToInitGrabberFirst = false; if (!bSgInited) bNeedToInitGrabberFirst = true; //if we need to initialize the grabbing component then do it if( bNeedToInitGrabberFirst ){ if( !qtInitSeqGrabber() ){ return; } } ofLog(OF_LOG_NOTICE, "-------------------------------------"); /* //input selection stuff (ie multiple webcams) //from http://developer.apple.com/samplecode/SGDevices/listing13.html //and originally http://lists.apple.com/archives/QuickTime-API/2008/Jan/msg00178.html */ SGDeviceList deviceList; SGGetChannelDeviceList (gVideoChannel, sgDeviceListIncludeInputs, &deviceList); unsigned char pascalName[256]; unsigned char pascalNameInput[256]; //this is our new way of enumerating devices //quicktime can have multiple capture 'inputs' on the same capture 'device' //ie the USB Video Class Video 'device' - can have multiple usb webcams attached on what QT calls 'inputs' //The isight for example will show up as: //USB Video Class Video - Built-in iSight ('input' 1 of the USB Video Class Video 'device') //Where as another webcam also plugged whill show up as //USB Video Class Video - Philips SPC 1000NC Webcam ('input' 2 of the USB Video Class Video 'device') //this means our the device ID we use for selection has to count both capture 'devices' and their 'inputs' //this needs to be the same in our init grabber method so that we select the device we ask for int deviceCount = 0; ofLog(OF_LOG_NOTICE, "listing available capture devices"); for(int i = 0 ; i < (*deviceList)->count ; ++i) { SGDeviceName nameRec; nameRec = (*deviceList)->entry[i]; SGDeviceInputList deviceInputList = nameRec.inputs; int numInputs = 0; if( deviceInputList ) numInputs = ((*deviceInputList)->count); memcpy(pascalName, (*deviceList)->entry[i].name, sizeof(char) * 256); //this means we can use the capture method if(nameRec.flags != sgDeviceNameFlagDeviceUnavailable){ //if we have a capture 'device' (qt's word not mine - I would prefer 'system' ) that is ready to be used //we go through its inputs to list all physical devices - as there could be more than one! for(int j = 0; j < numInputs; j++){ //if our 'device' has inputs we get their names here if( deviceInputList ){ SGDeviceInputName inputNameRec = (*deviceInputList)->entry[j]; memcpy(pascalNameInput, inputNameRec.name, sizeof(char) * 256); } ofLog(OF_LOG_NOTICE, "device[%i] %s - %s", deviceCount, p2cstr(pascalName), p2cstr(pascalNameInput) ); //we count this way as we need to be able to distinguish multiple inputs as devices deviceCount++; } }else{ ofLog(OF_LOG_NOTICE, "(unavailable) device[%i] %s", deviceCount, p2cstr(pascalName) ); deviceCount++; } } ofLog(OF_LOG_NOTICE, "-------------------------------------"); //if we initialized the grabbing component then close it if( bNeedToInitGrabberFirst ){ qtCloseSeqGrabber(); } //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_DIRECTSHOW //--------------------------------- ofLog(OF_LOG_NOTICE, "---"); VI.listDevices(); ofLog(OF_LOG_NOTICE, "---"); //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_UNICAP //-------------------------------- ucGrabber.listUCDevices(); //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_V4L //-------------------------------- struct stat st; ofLog(OF_LOG_NOTICE, "listing available capture devices"); ofLog(OF_LOG_NOTICE, "---"); for (int i = 0; i < 8; i++) { sprintf(dev_name, "/dev/video%i", i); if (stat (dev_name, &st) == 0) { ofLog(OF_LOG_NOTICE, "Video device %i = /dev/video%i",i,i); } else { } } ofLog(OF_LOG_NOTICE, "---"); //--------------------------------- #endif //--------------------------------- } //-------------------------------------------------------------------- void ofVideoGrabber::setVerbose(bool bTalkToMe){ bVerbose = bTalkToMe; //--------------------------------- #ifdef OF_VIDEO_CAPTURE_UNICAP //-------------------------------- ucGrabber.verbose=bVerbose; //--------------------------------- #endif //--------------------------------- } //-------------------------------------------------------------------- void ofVideoGrabber::setDeviceID(int _deviceID){ deviceID = _deviceID; bChooseDevice = true; } //--------------------------------------------------------------------------- unsigned char * ofVideoGrabber::getPixels(){ return pixels; } //------------------------------------ //for getting a reference to the texture ofTexture & ofVideoGrabber::getTextureReference(){ if(!tex.bAllocated() ){ ofLog(OF_LOG_WARNING, "ofVideoGrabber - getTextureReference - texture is not allocated"); } return tex; } //--------------------------------------------------------------------------- bool ofVideoGrabber::isFrameNew(){ return bIsFrameNew; } //-------------------------------------------------------------------- void ofVideoGrabber::update(){ grabFrame(); } //-------------------------------------------------------------------- void ofVideoGrabber::grabFrame(){ //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- if (bGrabberInited == true){ SGIdle(gSeqGrabber); // set the top pixel alpha = 0, so we can know if it // was a new frame or not.. // or else we will process way more than necessary // (ie opengl is running at 60fps +, capture at 30fps) if (offscreenGWorldPixels[0] != 0x00){ offscreenGWorldPixels[0] = 0x00; bHavePixelsChanged = true; convertPixels(offscreenGWorldPixels, pixels, width, height); if (bUseTexture){ tex.loadData(pixels, width, height, GL_RGB); } } } // newness test for quicktime: if (bGrabberInited == true){ bIsFrameNew = false; if (bHavePixelsChanged == true){ bIsFrameNew = true; bHavePixelsChanged = false; } } //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_DIRECTSHOW //--------------------------------- //printf("ofVideoGrabber.grabFrame.bGrabberInited: %s ",bGrabberInited ? "true" : "false"); //printf("ofVideoGrabber.grabFrame.VI.isFrameNew(device): %s \n",VI.isFrameNew(device) ? "true" : "false"); if (bGrabberInited == true){ bIsFrameNew = false; if (VI.isFrameNew(device)){ bIsFrameNew = true; /* rescale -- currently this is nearest neighbor scaling not the greatest, but fast this can be optimized too with pointers, etc better -- make sure that you ask for a "good" size.... */ unsigned char * viPixels = VI.getPixels(device, true, true); if (bDoWeNeedToResize == true){ int inputW = VI.getWidth(device); int inputH = VI.getHeight(device); float scaleW = (float)inputW / (float)width; float scaleH = (float)inputH / (float)height; for(int i=0;i<width;i++){ for(int j=0;j<height;j++){ float posx = i * scaleW; float posy = j * scaleH; /* // start of calculating // for linear interpolation int xbase = (int)floor(posx); int xhigh = (int)ceil(posx); float pctx = (posx - xbase); int ybase = (int)floor(posy); int yhigh = (int)ceil(posy); float pcty = (posy - ybase); */ int posPix = (((int)posy * inputW * 3) + ((int)posx * 3)); pixels[(j*width*3) + i*3 ] = viPixels[posPix ]; pixels[(j*width*3) + i*3 + 1] = viPixels[posPix+1]; pixels[(j*width*3) + i*3 + 2] = viPixels[posPix+2]; } } } else { memcpy(pixels, viPixels, width*height*3); } if (bUseTexture){ tex.loadData(pixels, width, height, GL_RGB); } } } //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_UNICAP //-------------------------------- if (bGrabberInited){ bIsFrameNew = ucGrabber.getFrameUC(&pixels); if(bIsFrameNew) { if (bUseTexture){ tex.loadData(pixels, width, height, GL_RGB); } } } //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_V4L //-------------------------------- if (bV4LGrabberInited == true){ bIsFrameNew = getFrameV4L(pixels); if(bIsFrameNew) { if (bUseTexture){ tex.loadData(pixels, width, height, GL_RGB); } } } //--------------------------------- #endif //--------------------------------- } //-------------------------------------------------------------------- void ofVideoGrabber::close(){ //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- qtCloseSeqGrabber(); //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_V4L //-------------------------------- closeV4L(); //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_DIRECTSHOW //--------------------------------- if (bGrabberInited == true){ VI.stopDevice(device); bGrabberInited = false; } //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_UNICAP //-------------------------------- if(bGrabberInited){ ucGrabber.close_unicap(); bGrabberInited = false; deviceID = 0; bIsFrameNew = false; bChooseDevice = false; } //--------------------------------- #endif //--------------------------------- if (pixels != NULL){ delete[] pixels; pixels = NULL; } tex.clear(); } //-------------------------------------------------------------------- void ofVideoGrabber::videoSettings(void){ //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- Rect curBounds, curVideoRect; ComponentResult err; // Get our current state err = SGGetChannelBounds (gVideoChannel, &curBounds); if (err != noErr){ ofLog(OF_LOG_ERROR, "Error in SGGetChannelBounds"); return; } err = SGGetVideoRect (gVideoChannel, &curVideoRect); if (err != noErr){ ofLog(OF_LOG_ERROR, "Error in SGGetVideoRect"); return; } // Pause err = SGPause (gSeqGrabber, true); if (err != noErr){ ofLog(OF_LOG_ERROR, "Error in SGPause"); return; } #ifdef TARGET_OSX //load any saved camera settings from file loadSettings(); static SGModalFilterUPP gSeqGrabberModalFilterUPP = NewSGModalFilterUPP(SeqGrabberModalFilterUPP); ComponentResult result = SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, nil, seqGrabSettingsPreviewOnly, gSeqGrabberModalFilterUPP, nil); if (result != noErr){ ofLog(OF_LOG_ERROR, "error in dialogue"); return; } //save any changed settings to file saveSettings(); #else SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, nil, seqGrabSettingsPreviewOnly, NULL, 0); #endif SGSetChannelBounds(gVideoChannel, &videoRect); SGPause (gSeqGrabber, false); //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_DIRECTSHOW //--------------------------------- if (bGrabberInited == true) VI.showSettingsWindow(device); //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_UNICAP //-------------------------------- ucGrabber.queryUC_imageProperties(); //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_V4L //-------------------------------- queryV4L_imageProperties(); //--------------------------------- #endif //--------------------------------- } //-------------------------------------------------------------------- #ifdef TARGET_OSX //-------------------------------------------------------------------- //--------------------------------------------------------------------- bool ofVideoGrabber::saveSettings(){ if (bGrabberInited != true) return false; ComponentResult err; UserData mySGVideoSettings = NULL; // get the SGChannel settings cofigured by the user err = SGGetChannelSettings(gSeqGrabber, gVideoChannel, &mySGVideoSettings, 0); if ( err != noErr ){ ofLog(OF_LOG_ERROR, "Error getting camera settings %i",err); return false; } string pref = "ofVideoSettings-"+deviceName; CFStringRef cameraString = CFStringCreateWithCString(kCFAllocatorDefault,pref.c_str(),kCFStringEncodingMacRoman); //get the settings using the key "ofVideoSettings-the name of the device" SaveSettingsPreference( cameraString, mySGVideoSettings); DisposeUserData(mySGVideoSettings); return true; } //--------------------------------------------------------------------- bool ofVideoGrabber::loadSettings(){ if (bGrabberInited != true || deviceName.length() == 0) return false; ComponentResult err; UserData mySGVideoSettings = NULL; // get the settings using the key "ofVideoSettings-the name of the device" string pref = "ofVideoSettings-"+deviceName; CFStringRef cameraString = CFStringCreateWithCString(kCFAllocatorDefault,pref.c_str(),kCFStringEncodingMacRoman); GetSettingsPreference(cameraString, &mySGVideoSettings); if (mySGVideoSettings){ Rect curBounds, curVideoRect; //we need to make sure the dimensions don't get effected //by our preferences // Get our current state err = SGGetChannelBounds (gVideoChannel, &curBounds); if (err != noErr){ ofLog(OF_LOG_ERROR, "Error in SGGetChannelBounds"); } err = SGGetVideoRect (gVideoChannel, &curVideoRect); if (err != noErr){ ofLog(OF_LOG_ERROR, "Error in SGGetVideoRect"); } // use the saved settings preference to configure the SGChannel err = SGSetChannelSettings(gSeqGrabber, gVideoChannel, mySGVideoSettings, 0); if ( err != noErr ) { ofLog(OF_LOG_ERROR, "Error applying stored settings %i", err); return false; } DisposeUserData(mySGVideoSettings); // Pause err = SGPause (gSeqGrabber, true); if (err != noErr){ ofLog(OF_LOG_ERROR, "Error in SGPause"); } SGSetChannelBounds(gVideoChannel, &videoRect); SGPause (gSeqGrabber, false); }else{ ofLog(OF_LOG_WARNING, "No camera settings to load"); return false; } return true; } //------------------------------------------------------ bool ofVideoGrabber::qtInitSeqGrabber(){ if (bSgInited != true){ OSErr err = noErr; ComponentDescription theDesc; Component sgCompID; // this crashes when we get to // SGNewChannel // we get -9405 as error code for the channel // ----------------------------------------- // gSeqGrabber = OpenDefaultComponent(SeqGrabComponentType, 0); // this seems to work instead (got it from hackTV) // ----------------------------------------- theDesc.componentType = SeqGrabComponentType; theDesc.componentSubType = NULL; theDesc.componentManufacturer = 'appl'; theDesc.componentFlags = NULL; theDesc.componentFlagsMask = NULL; sgCompID = FindNextComponent (NULL, &theDesc); // ----------------------------------------- if (sgCompID == NULL){ ofLog(OF_LOG_ERROR, "error:FindNextComponent did not return a valid component"); return false; } gSeqGrabber = OpenComponent(sgCompID); err = GetMoviesError(); if (gSeqGrabber == NULL || err) { ofLog(OF_LOG_ERROR, "error: can't get default sequence grabber component"); return false; } err = SGInitialize(gSeqGrabber); if (err != noErr) { ofLog(OF_LOG_ERROR, "error: can't initialize sequence grabber component"); return false; } err = SGSetDataRef(gSeqGrabber, 0, 0, seqGrabDontMakeMovie); if (err != noErr) { ofLog(OF_LOG_ERROR, "error: can't set the destination data reference"); return false; } // windows crashes w/ out gworld, make a dummy for now... // this took a long time to figure out. err = SGSetGWorld(gSeqGrabber, 0, 0); if (err != noErr) { ofLog(OF_LOG_ERROR, "error: setting up the gworld"); return false; } err = SGNewChannel(gSeqGrabber, VideoMediaType, &(gVideoChannel)); if (err != noErr) { ofLog(OF_LOG_ERROR, "error: creating a channel. Check if you have any qt capable cameras attached"); return false; } bSgInited = true; return true; } return false; } //-------------------------------------------------------------------- bool ofVideoGrabber::qtCloseSeqGrabber(){ if (gSeqGrabber != NULL){ SGStop (gSeqGrabber); CloseComponent (gSeqGrabber); gSeqGrabber = NULL; bSgInited = false; return true; } return false; } //-------------------------------------------------------------------- bool ofVideoGrabber::qtSelectDevice(int deviceNumber, bool didWeChooseADevice){ //note - check for memory freeing possibly needed for the all SGGetChannelDeviceList mac stuff // also see notes in listDevices() regarding new enunemeration method. //Generate a device list and enumerate //all devices availble to the channel SGDeviceList deviceList; SGGetChannelDeviceList(gVideoChannel, sgDeviceListIncludeInputs, &deviceList); unsigned char pascalName[256]; unsigned char pascalNameInput[256]; int numDevices = (*deviceList)->count; if(numDevices == 0){ ofLog(OF_LOG_ERROR, "error: No catpure devices found"); return false; } int deviceCount = 0; for(int i = 0 ; i < numDevices; ++i) { SGDeviceName nameRec; nameRec = (*deviceList)->entry[i]; SGDeviceInputList deviceInputList = nameRec.inputs; int numInputs = 0; if( deviceInputList ) numInputs = ((*deviceInputList)->count); memcpy(pascalName, (*deviceList)->entry[i].name, sizeof(char) * 256); memset(pascalNameInput, 0, sizeof(char)*256); //this means we can use the capture method if(nameRec.flags != sgDeviceNameFlagDeviceUnavailable){ //if we have a capture 'device' (qt's word not mine - I would prefer 'system' ) that is ready to be used //we go through its inputs to list all physical devices - as there could be more than one! for(int j = 0; j < numInputs; j++){ //if our 'device' has inputs we get their names here if( deviceInputList ){ SGDeviceInputName inputNameRec = (*deviceInputList)->entry[j]; memcpy(pascalNameInput, inputNameRec.name, sizeof(char) * 256); } //if the device number matches we try and setup the device //if we didn't specifiy a device then we will try all devices till one works! if( deviceCount == deviceNumber || !didWeChooseADevice ){ ofLog(OF_LOG_NOTICE, "attempting to open device[%i] %s - %s", deviceCount, p2cstr(pascalName), p2cstr(pascalNameInput) ); OSErr err1 = SGSetChannelDevice(gVideoChannel, pascalName); OSErr err2 = SGSetChannelDeviceInput(gVideoChannel, j); int successLevel = 0; //if there were no errors then we have opened the device without issue if ( err1 == noErr && err2 == noErr){ successLevel = 2; } //parameter errors are not fatal so we will try and open but will caution the user else if ( (err1 == paramErr || err1 == noErr) && (err2 == noErr || err2 == paramErr) ){ successLevel = 1; } //the device is opened! if ( successLevel > 0 ){ deviceName = (char *)p2cstr(pascalName); deviceName += "-"; deviceName += (char *)p2cstr(pascalNameInput); if(successLevel == 2)ofLog(OF_LOG_NOTICE, "device opened successfully"); else ofLog(OF_LOG_WARNING, "device opened with some paramater errors - should be fine though!"); //no need to keep searching - return that we have opened a device! return true; }else{ //if we selected a device in particular but failed we want to go through the whole list again - starting from 0 and try any device. //so we return false - and try one more time without a preference if( didWeChooseADevice ){ ofLog(OF_LOG_WARNING, "problems setting device[%i] %s - %s *****", deviceNumber, p2cstr(pascalName), p2cstr(pascalNameInput)); return false; }else{ ofLog(OF_LOG_WARNING, "unable to open device, trying next device"); } } } //we count this way as we need to be able to distinguish multiple inputs as devices deviceCount++; } }else{ //ofLog(OF_LOG_ERROR, "(unavailable) device[%i] %s", deviceCount, p2cstr(pascalName) ); deviceCount++; } } return false; } //--------------------------------- #endif //--------------------------------- //-------------------------------------------------------------------- bool ofVideoGrabber::initGrabber(int w, int h, bool setUseTexture){ bUseTexture = setUseTexture; //--------------------------------- #ifdef OF_VIDEO_CAPTURE_QUICKTIME //--------------------------------- //---------------------------------- 1 - open the sequence grabber if( !qtInitSeqGrabber() ){ ofLog(OF_LOG_ERROR, "error: unable to initialize the seq grabber"); return false; } //---------------------------------- 2 - set the dimensions width = w; height = h; MacSetRect(&videoRect, 0, 0, width, height); //---------------------------------- 3 - buffer allocation // Create a buffer big enough to hold the video data, // make sure the pointer is 32-byte aligned. // also the rgb image that people will grab offscreenGWorldPixels = (unsigned char*)malloc(4 * width * height + 32); pixels = new unsigned char[width*height*3]; QTNewGWorldFromPtr (&videogworld, k32ARGBPixelFormat, &videoRect, NULL, NULL, 0, offscreenGWorldPixels, 4 * width); LockPixels(GetGWorldPixMap(videogworld)); SetGWorld (videogworld, NULL); SGSetGWorld(gSeqGrabber, videogworld, nil); //---------------------------------- 4 - device selection bool didWeChooseADevice = bChooseDevice; bool deviceIsSelected = false; //if we have a device selected then try first to setup //that device if(didWeChooseADevice){ deviceIsSelected = qtSelectDevice(deviceID, true); if(!deviceIsSelected && bVerbose) ofLog(OF_LOG_WARNING, "unable to open device[%i] - will attempt other devices", deviceID); } //if we couldn't select our required device //or we aren't specifiying a device to setup //then lets try to setup ANY device! if(deviceIsSelected == false){ //lets list available devices listDevices(); setDeviceID(0); deviceIsSelected = qtSelectDevice(deviceID, false); } //if we still haven't been able to setup a device //we should error and stop! if( deviceIsSelected == false){ goto bail; } //---------------------------------- 5 - final initialization steps OSStatus err; err = SGSetChannelUsage(gVideoChannel,seqGrabPreview); if ( err != noErr ) goto bail; err = SGSetChannelBounds(gVideoChannel, &videoRect); if ( err != noErr ) goto bail; err = SGPrepare(gSeqGrabber, true, false); //theo swapped so preview is true and capture is false if ( err != noErr ) goto bail; err = SGStartPreview(gSeqGrabber); if ( err != noErr ) goto bail; bGrabberInited = true; loadSettings(); ofLog(OF_LOG_NOTICE,"end setup ofVideoGrabber"); ofLog(OF_LOG_NOTICE,"-------------------------------------\n"); //---------------------------------- 6 - setup texture if needed if (bUseTexture){ // create the texture, set the pixels to black and // upload them to the texture (so at least we see nothing black the callback) tex.allocate(width,height,GL_RGB); memset(pixels, 0, width*height*3); tex.loadData(pixels, width, height, GL_RGB); } // we are done return true; //--------------------- (bail) something's wrong ----- bail: ofLog(OF_LOG_ERROR, "***** ofVideoGrabber error *****"); ofLog(OF_LOG_ERROR, "-------------------------------------\n"); //if we don't close this - it messes up the next device! if(bSgInited) qtCloseSeqGrabber(); bGrabberInited = false; return false; //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_DIRECTSHOW //--------------------------------- //printf("ofVideoGrabber.bChooseDevice: %s",bChooseDevice ? "true" : "false"); if (bChooseDevice){ device = deviceID; ofLog(OF_LOG_NOTICE, "choosing %i", deviceID); } else { device = 0; } width = w; height = h; bGrabberInited = false; bool bOk = VI.setupDevice(device, width, height); int ourRequestedWidth = width; int ourRequestedHeight = height; std::cout << "ourRequestedWidth :"<< width<<std::endl; std::cout << "bOk :"<< bOk<<std::endl; if (bOk == true){ bGrabberInited = true; width = VI.getWidth(device); height = VI.getHeight(device); if (width == ourRequestedWidth && height == ourRequestedHeight){ bDoWeNeedToResize = false; } else { bDoWeNeedToResize = true; width = ourRequestedWidth; height = ourRequestedHeight; } std::cout << "ourRequestedWidth :"<< width<<std::endl; pixels = new unsigned char[width * height * 3]; if (bUseTexture){ // create the texture, set the pixels to black and // upload them to the texture (so at least we see nothing black the callback) tex.allocate(width,height,GL_RGB); memset(pixels, 0, width*height*3); tex.loadData(pixels, width, height, GL_RGB); } return true; } else { ofLog(OF_LOG_ERROR, "error allocating a video device"); ofLog(OF_LOG_ERROR, "please check your camera with AMCAP or other software"); bGrabberInited = false; return false; } //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_UNICAP //-------------------------------- if( !bGrabberInited ){ if ( !bChooseDevice ){ deviceID = 0; } width = w; height = h; pixels = new unsigned char[width * height * 3]; if (bUseTexture){ // create the texture, set the pixels to black and // upload them to the texture (so at least we see nothing black the callback) tex.allocate(width,height,GL_RGB); memset(pixels, 0, width*height*3); tex.loadData(pixels, width, height, GL_RGB); } bGrabberInited = ucGrabber.open_device (deviceID); if( bGrabberInited ){ ofLog(OF_LOG_NOTICE, "choosing device %i: %s", deviceID,ucGrabber.device_identifier()); ucGrabber.set_format(w,h); ucGrabber.start_capture(); } } return bGrabberInited; //--------------------------------- #endif //--------------------------------- //--------------------------------- #ifdef OF_VIDEO_CAPTURE_V4L //-------------------------------- if (bChooseDevice){ device = deviceID; } else { device = 0; } sprintf(dev_name, "/dev/video%i", device); ofLog(OF_LOG_NOTICE, "choosing device "+dev_name+""); bool bOk = initV4L(w, h, dev_name); if (bOk == true){ bV4LGrabberInited = true; width = getV4L_Width(); height = getV4L_Height(); pixels = new unsigned char[width * height * 3]; if (bUseTexture){ // create the texture, set the pixels to black and // upload them to the texture (so at least we see nothing black the callback) tex.allocate(width,height,GL_RGB); //memset(pixels, 0, width*height*3); //tex.loadData(pixels, width, height, GL_RGB); } ofLog(OF_LOG_NOTICE, "success allocating a video device "); return true; } else { ofLog(OF_LOG_ERROR, "error allocating a video device"); ofLog(OF_LOG_ERROR, "please check your camera and verify that your driver is correctly installed."); return false; } //--------------------------------- //--------------------------------- #endif //--------------------------------- } //------------------------------------ void ofVideoGrabber::setUseTexture(bool bUse){ bUseTexture = bUse; } //we could cap these values - but it might be more useful //to be able to set anchor points outside the image //---------------------------------------------------------- void ofVideoGrabber::setAnchorPercent(float xPct, float yPct){ if (bUseTexture)tex.setAnchorPercent(xPct, yPct); } //---------------------------------------------------------- void ofVideoGrabber::setAnchorPoint(int x, int y){ if (bUseTexture)tex.setAnchorPoint(x, y); } //---------------------------------------------------------- void ofVideoGrabber::resetAnchor(){ if (bUseTexture)tex.resetAnchor(); } //------------------------------------ void ofVideoGrabber::draw(float _x, float _y, float _w, float _h){ if (bUseTexture){ tex.draw(_x, _y, _w, _h); } } //------------------------------------ void ofVideoGrabber::draw(float _x, float _y){ draw(_x, _y, (float)width, (float)height); } //---------------------------------------------------------- float ofVideoGrabber::getHeight(){ return (float)height; } //---------------------------------------------------------- float ofVideoGrabber::getWidth(){ return (float)width; }
[ "schlupek@463ed9da-a5aa-4e33-a7e2-2d3b412cff85" ]
[ [ [ 1, 1154 ] ] ]
1540815b983deaf4869fcb74dcaf92347d9e7201
285ed351936e4b8c71fa9c60f7670863447828a0
/apps/addonsExamples/ccv/src/testApp.h
c91cb301c4e56c3f4c18dbdc2726789703cb6653
[]
no_license
encukou/openFrameworks
98b9929a5e685355881d4ea6e9e2f8152f683518
16bc2a979cc19dc45e5995a450f14f57f43ce529
refs/heads/master
2021-01-17T13:01:24.263586
2011-03-10T13:32:02
2011-03-10T13:32:02
1,460,531
0
0
null
null
null
null
UTF-8
C++
false
false
679
h
#ifndef _TEST_APP #define _TEST_APP //if standalone mode/non-addon #define STANDALONE //addon #include "ofxNCore.h" //main #include "ofMain.h" class testApp : public ofBaseApp, public TouchListener { public: testApp() { TouchEvents.addListener(this); } ofxNCoreVision * tbeta; void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(); //Touch Events void TouchDown(Blob b); void TouchMoved(Blob b); void TouchUp(Blob b); }; #endif
[ [ [ 1, 39 ] ] ]
69686b2cc1b98a4a0c86a708c236d72bf471264e
0cf09d7cc26a513d0b93d3f8ef6158a9c5aaf5bc
/twittle/src/http/http_client.cpp
be391e3973d89bdaca683c6aad14aef0c96ff45d
[]
no_license
shenhuashan/Twittle
0e276c1391c177e7586d71c607e6ca7bf17e04db
03d3d388d5ba9d56ffcd03482ee50e0a2a5f47a1
refs/heads/master
2023-03-18T07:53:25.305468
2009-08-11T05:55:07
2009-08-11T05:55:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,567
cpp
#include <sstream> #include <fstream> #include <iomanip> #include "application.h" #include "http/http_client.h" #include <wx/app.h> #include <wx/filesys.h> #include <wx/sstream.h> #include <wx/wfstream.h> #include <wx/url.h> #include <wx/xml/xml.h> #include <wx/protocol/http.h> HttpClient::HttpClient() { SetTimeout(10); // 10 seconds of timeout instead of 10 minutes SetHeader(_T("User-Agent"), wxGetApp().APPNAME + _T(" ") + wxGetApp().APPVERSION); } HttpClient::HttpClient(const wxString& user, const wxString& password) { HttpClient(); SetUser(user); SetPassword(password); } unsigned long HttpClient::GetContentLength() { unsigned long val; wxString lenstr = this->GetHeader(_T("Content-length")); lenstr.ToULong(&val); return val; } wxInputStream *HttpClient::GetResourceStream(const wxURL& url) { // Connect to server and setup stream on path unsigned short port; url.GetPort().ToULong(reinterpret_cast<unsigned long *>(&port)); Connect(url.GetServer(), port); wxString path = (url.GetPath() == _T("") ? _T("/") : url.GetPath()); wxInputStream *stream = GetInputStream(path); // Only return the stream if it's valid if (GetError() != wxPROTO_CONNERR) { return stream; } else { return NULL; } } wxString HttpClient::Get(const wxURL& url) { wxString data; wxInputStream *httpStream = GetResourceStream(url); if (httpStream) { wxStringOutputStream out_stream(&data); httpStream->Read(out_stream); } // Close the stream delete httpStream; return data; } wxXmlDocument HttpClient::GetXml(const wxURL& url) { wxXmlDocument doc; wxInputStream *httpStream = GetResourceStream(url); if (httpStream) doc.Load(*httpStream); // Close the stream delete httpStream; return doc; } unsigned long HttpClient::GetToFile(const wxURL& url, const wxString& filename) { wxInputStream *httpStream = GetResourceStream(url); if (httpStream) { wxFileOutputStream file(filename); httpStream->Read(file); } // Close the stream delete httpStream; Close(); return GetContentLength(); } wxString HttpClient::UrlEncode(const wxString& input) { std::stringstream out; const wxCharBuffer data = input.utf8_str(); for (unsigned int i = 0; i < input.length(); i++) { char c = data[i]; char cminus = tolower((int)c); if (cminus < 'a' || cminus > 'z') { out << '%' << std::hex << std::setw(2) << (int)c; } else { out << c; } } return wxString::From8BitData(out.rdbuf()->str().c_str()); }
[ [ [ 1, 114 ] ] ]
a1f9f24d2e4d412f989601ee1aceddb6502f311a
d504537dae74273428d3aacd03b89357215f3d11
/src/Renderer/Dx9/Texture3D9/Textures.cpp
7431a04096d0568ea806094e20cebd1c710465f5
[]
no_license
h0MER247/e6
1026bf9aabd5c11b84e358222d103aee829f62d7
f92546fd1fc53ba783d84e9edf5660fe19b739cc
refs/heads/master
2020-12-23T05:42:42.373786
2011-02-18T16:16:24
2011-02-18T16:16:24
237,055,477
1
0
null
2020-01-29T18:39:15
2020-01-29T18:39:14
null
UTF-8
C++
false
false
22,642
cpp
//----------------------------------------------------------------------------- // File: Textures.cpp // // Desc: DirectShow sample code - uses the Direct3D Textures Tutorial05 as // a base to create an application that uses DirectShow to draw a video // on a DirectX 9.0 Texture surface. // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #include "textures.h" #include "resource.h" #include "d3dfont.h" #include <math.h> #include <streams.h> #pragma warning( disable : 4100 4238) //----------------------------------------------------------------------------- // Global variables //----------------------------------------------------------------------------- LPDIRECT3D9 g_pD3D = NULL; // Used to create the D3DDevice LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; // Our rendering device LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; // Buffer to hold vertices LPDIRECT3DTEXTURE9 g_pTexture = NULL; // Our texture HINSTANCE hInstance = 0; HWND g_hWnd = 0; bool g_bDeviceLost = false; CD3DFont* g_pFont = NULL; const int nGrid = 50; BYTE bkRed = 50; BYTE bkGrn = 100; BYTE bkBlu = 150; DWORD g_StartTime = 0L; extern TCHAR* g_pachRenderMethod; extern CComPtr<IBaseFilter> g_pRenderer; // our custom renderer // A structure for our custom vertex type. We added texture coordinates. struct CUSTOMVERTEX { D3DXVECTOR3 position; // The position D3DCOLOR color; // The color FLOAT tu, tv; // The texture coordinates }; // Our custom FVF, which describes our custom vertex structure #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1) #define CLASSNAME TEXT("DirectShow Texture3D9 Sample") #define TIMER_ID 100 #define TIMER_RATE 20 // milliseconds // Function prototypes void AddAboutMenuItem(HWND hWnd); LRESULT CALLBACK AboutDlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); //----------------------------------------------------------------------------- // Name: InitD3D() // Desc: Initializes Direct3D //----------------------------------------------------------------------------- HRESULT InitD3D( HWND hWnd ) { HRESULT hr; // Create the D3D object. if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) ) return E_FAIL; // Get the current desktop display mode, so we can set up a back // buffer of the same format D3DDISPLAYMODE d3ddm; if ( FAILED( hr = g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ) ) ) { Msg(TEXT("Could not read adapter display mode! hr=0x%x"), hr); return hr; } // Set up the structure used to create the D3DDevice. Since we are now // using more complex geometry, we will create a device with a zbuffer. D3DPRESENT_PARAMETERS d3dpp; ZeroMemory( &d3dpp, sizeof(d3dpp) ); d3dpp.Windowed = TRUE; d3dpp.SwapEffect = D3DSWAPEFFECT_COPY; d3dpp.BackBufferFormat = d3ddm.Format; d3dpp.EnableAutoDepthStencil = TRUE; d3dpp.AutoDepthStencilFormat = D3DFMT_D16; // Create the D3DDevice hr = g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED, &d3dpp, &g_pd3dDevice ); if (FAILED(hr)) { Msg(TEXT("Could not create the D3D9 device! hr=0x%x\r\n\r\n") TEXT("This sample is attempting to create a buffer that might not\r\n") TEXT("be supported by your video card in its current mode.\r\n\r\n") TEXT("You may want to reduce your screen resolution or bit depth\r\n") TEXT("and try to run this sample again."), hr); return hr; } hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP ); hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP ); // Add filtering hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); hr = g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR ); // set maximum ambient light hr = g_pd3dDevice->SetRenderState(D3DRS_AMBIENT,RGB(255,255,255)); // Turn off culling hr = g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); // Turn off D3D lighting hr = g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); // Turn on the zbuffer hr = g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); // Set texture states hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); hr = g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); g_pFont = new CD3DFont(TEXT("Trebuchet MS"), 10); if( g_pFont ) { hr = g_pFont->InitDeviceObjects( g_pd3dDevice ); if( FAILED(hr)) { delete g_pFont; g_pFont = NULL; } else { hr = g_pFont->RestoreDeviceObjects(); if( FAILED(hr)) { delete g_pFont; g_pFont = NULL; } } } return hr; } //----------------------------------------------------------------------------- // Name: InitGeometry() // Desc: Create the textures and vertex buffers //----------------------------------------------------------------------------- HRESULT InitGeometry() { HRESULT hr; // Create the vertex buffer. if( FAILED( hr = g_pd3dDevice->CreateVertexBuffer( nGrid*2*sizeof(CUSTOMVERTEX), 0, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL ) ) ) { Msg(TEXT("Could not create a vertex buffer! hr=0x%x"), hr); return E_FAIL; } // Fill the vertex buffer. We are setting the tu and tv texture // coordinates, which range from 0.0 to 1.0 CUSTOMVERTEX* pVertices; if ( FAILED( hr = g_pVB->Lock( 0, 0, (void**)&pVertices, 0 ) ) ) { Msg(TEXT("Could not lock the vertex buffer! hr=0x%x"), hr); return E_FAIL; } for( DWORD i=0; i<nGrid; i++ ) { FLOAT theta = (2*D3DX_PI*i)/(nGrid-1) + (FLOAT)(D3DX_PI/2.f); pVertices[2*i+0].position = D3DXVECTOR3( sinf(theta),-1.0f, cosf(theta) ); pVertices[2*i+0].color = 0xffffffff; pVertices[2*i+0].tu = ((FLOAT)i)/((FLOAT)nGrid-1.f); pVertices[2*i+0].tv = 1.0f; pVertices[2*i+1].position = D3DXVECTOR3( sinf(theta), 1.0f, cosf(theta) ); pVertices[2*i+1].color = 0xffffffff; pVertices[2*i+1].tu = ((FLOAT)i)/((FLOAT)nGrid-1.f); pVertices[2*i+1].tv = 0.0f; } g_pVB->Unlock(); // DShow: Set up filter graph with our custom renderer. if( FAILED( InitDShowTextureRenderer() ) ) return E_FAIL; return S_OK; } //----------------------------------------------------------------------------- // Name: UpgradeGeometry() //----------------------------------------------------------------------------- HRESULT UpgradeGeometry( LONG lActualW, LONG lTextureW, LONG lActualH, LONG lTextureH ) { HRESULT hr = S_OK; if( 0 == lTextureW || 0 == lTextureH ) { return E_INVALIDARG; } FLOAT tuW = (FLOAT)lActualW / (FLOAT)lTextureW; FLOAT tvH = (FLOAT)lActualH / (FLOAT)lTextureH; // Fill the vertex buffer. We are setting the tu and tv texture // coordinates, which range from 0.0 to 1.0 CUSTOMVERTEX* pVertices; if ( FAILED( hr = g_pVB->Lock( 0, 0, (void**)&pVertices, 0 ) ) ) { Msg(TEXT("Could not lock the vertex buffer! hr=0x%x"), hr); return E_FAIL; } for( DWORD i=0; i<nGrid; i++ ) { FLOAT theta = (2*D3DX_PI*i)/(nGrid-1) + (FLOAT)(D3DX_PI/2.f); pVertices[2*i+0].tu = tuW * ((FLOAT)i)/((FLOAT)nGrid-1.f); pVertices[2*i+0].tv = tvH; pVertices[2*i+1].tu = tuW * ((FLOAT)i)/((FLOAT)nGrid-1.f); pVertices[2*i+1].tv = 0.0f; } g_pVB->Unlock(); return S_OK; } //----------------------------------------------------------------------------- // Name: Cleanup() // Desc: Releases all previously initialized objects //----------------------------------------------------------------------------- VOID Cleanup() { CleanupDShow(); if( g_pTexture != NULL ) g_pTexture->Release(); if( g_pVB != NULL ) g_pVB->Release(); if( g_pd3dDevice != NULL ) g_pd3dDevice->Release(); if( g_pD3D != NULL ) g_pD3D->Release(); if( g_pFont ) { delete g_pFont; g_pFont = NULL; } } //----------------------------------------------------------------------------- // Name: SetupMatrices() // Desc: Sets up the world, view, and projection transform matrices. //----------------------------------------------------------------------------- VOID SetupMatrices() { HRESULT hr; if( 0 == g_StartTime ) { srand( timeGetTime()); g_StartTime = (DWORD)(timeGetTime()/2000.0f); } // For our world matrix, we will just leave it as the identity D3DXMATRIX matWorld; D3DXMatrixIdentity( &matWorld ); D3DXMatrixRotationX( &matWorld, (FLOAT)(timeGetTime()/2000.0f - g_StartTime + D3DX_PI/2.0)); hr = g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld ); if (FAILED(hr)) { Msg(TEXT("Could not set D3DTS_WORLD transform! hr=0x%x"), hr); } // Set up our view matrix. A view matrix can be defined given an eye point, // a point to look at, and a direction for which way is up. Here, we set the // eye five units back along the z-axis and up three units, look at the // origin, and define "up" to be in the y-direction. D3DXMATRIX matView; D3DXMatrixLookAtLH( &matView, &D3DXVECTOR3( 0.0f, 3.0f,-3.0f ), &D3DXVECTOR3( 0.0f, 0.0f, 0.0f ), &D3DXVECTOR3( 0.0f, 1.0f, 0.0f ) ); hr = g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView ); if (FAILED(hr)) { Msg(TEXT("Could not set D3DTS_VIEW transform! hr=0x%x"), hr); } // For the projection matrix, we set up a perspective transform (which // transforms geometry from 3D view space to 2D viewport space, with // a perspective divide making objects smaller in the distance). To build // a perpsective transform, we need the field of view (1/4 pi is common), // the aspect ratio, and the near and far clipping planes (which define at // what distances geometry should be no longer be rendered). D3DXMATRIX matProj; D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.0f, 1.0f, 100.0f ); hr = g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj ); if (FAILED(hr)) { Msg(TEXT("Could not set D3DTS_PROJECTION transform! hr=0x%x"), hr); } } //----------------------------------------------------------------------------- // Name: CalculateShades() // Desc: Calculates shades of vertices depending on current time and background color //----------------------------------------------------------------------------- void CalculateShades() { float cost = (float)cos(timeGetTime()/2000.0f - g_StartTime); static BYTE btRed1, btGrn1, btBlu1; static BYTE btRed2, btGrn2, btBlu2; CUSTOMVERTEX* pVertices = 0; if ( SUCCEEDED( g_pVB->Lock( 0, 0, (void**)&pVertices, 0 ) ) ) { { btRed1 = (BYTE)(((0xFF-bkRed)*cost + (0xFF+bkRed))/2); btGrn1 = (BYTE)(((0xFF-bkGrn)*cost + (0xFF+bkGrn))/2); btBlu1 = (BYTE)(((0xFF-bkBlu)*cost + (0xFF+bkBlu))/2); } { btRed2 = (BYTE)(((bkRed-0xFF)*cost + (0xFF+bkRed))/2); btGrn2 = (BYTE)(((bkGrn-0xFF)*cost + (0xFF+bkGrn))/2); btBlu2 = (BYTE)(((bkBlu-0xFF)*cost + (0xFF+bkBlu))/2); } for( DWORD i=0; i<nGrid; i++ ) { pVertices[2*i+0].color = D3DCOLOR_XRGB(btRed1, btGrn1, btBlu1); pVertices[2*i+1].color = D3DCOLOR_XRGB(btRed2, btGrn2, btBlu2); } g_pVB->Unlock(); } } //----------------------------------------------------------------------------- // Name: DrawText() // Desc: Draws help text over the scene //----------------------------------------------------------------------------- VOID DrawText() { HRESULT hr = S_OK; if( !g_pFont ) return; TCHAR achMsg[MAX_PATH]; int nFPS = 0; CComPtr<IQualProp> pQp; if( g_pRenderer ) { hr = g_pRenderer->QueryInterface( IID_IQualProp, (void**)&(pQp.p)); if( SUCCEEDED(hr)) { hr = pQp->get_AvgFrameRate( &nFPS ); if( SUCCEEDED(hr)) { _stprintf( achMsg, TEXT("FPS = %5.3f"), (float)nFPS / 100.f); } g_pFont->DrawText(5, 20, D3DCOLOR_ARGB(0xCC,0xFF,0xFF,0x00), achMsg ); } } if( g_pachRenderMethod ) { _stprintf( achMsg, TEXT("Rendering method: %s"), g_pachRenderMethod); g_pFont->DrawText(5, 40, D3DCOLOR_ARGB(0xCC,0xFF,0xFF,0x00), achMsg ); } _stprintf( achMsg, TEXT("[Space]: change background color")); g_pFont->DrawText(5, 60, D3DCOLOR_ARGB(0xCC,0xFF,0xFF,0x00), achMsg ); _stprintf( achMsg, TEXT("[Enter]: set background color to black")); g_pFont->DrawText(5, 80, D3DCOLOR_ARGB(0xCC,0xFF,0xFF,0x00), achMsg ); } //----------------------------------------------------------------------------- // Name: Render() // Desc: Draws the scene //----------------------------------------------------------------------------- VOID Render() { HRESULT hr = S_OK; if (!g_pd3dDevice) return; // Handle the loss of the Direct3D surface (for example, by switching // to a full-screen command prompt and back again) if( g_bDeviceLost ) { // Test the cooperative level to see if it's okay to render if( FAILED( hr = g_pd3dDevice->TestCooperativeLevel() ) ) { // If the device was lost, do not render until we get it back if( D3DERR_DEVICELOST == hr ) return; // Check if the device needs to be reset. if( D3DERR_DEVICENOTRESET == hr ) { // Reset the D3D environment Cleanup(); hr = InitD3D(g_hWnd); hr = InitGeometry(); } return; } // TestCooperativeLevel() succeeded, so we have regained the device g_bDeviceLost = false; } // Clear the backbuffer and the zbuffer hr = g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(bkRed,bkGrn,bkBlu), 1.0f, 0 ); // Begin the scene hr = g_pd3dDevice->BeginScene(); // Setup the world, view, and projection matrices SetupMatrices(); CalculateShades(); // Setup our texture. Using textures introduces the texture stage states, // which govern how textures get blended together (in the case of multiple // textures) and lighting information. In this case, we are modulating // (blending) our texture with the diffuse color of the vertices. hr = g_pd3dDevice->SetTexture( 0, g_pTexture ); // Render the vertex buffer contents hr = g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof(CUSTOMVERTEX) ); hr = g_pd3dDevice->SetVertexShader( NULL ); hr = g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX ); hr = g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2*nGrid-2 ); DrawText(); // End the scene hr = g_pd3dDevice->EndScene(); // Present the backbuffer contents to the display hr = g_pd3dDevice->Present( NULL, NULL, NULL, NULL ); // If the Present call failed because we lost the Direct3D surface, // set a state variable for the next render pass, where we will attempt // to recover the lost surface. if( D3DERR_DEVICELOST == hr ) g_bDeviceLost = true; // Check to see if we need to restart the movie CheckMovieStatus(); } //----------------------------------------------------------------------------- // Name: MsgProc() // Desc: The window's message handler //----------------------------------------------------------------------------- LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); return 0; case WM_TIMER: case WM_PAINT: Render(); // Update the main window when needed break; // If the display mode changes, tear down the graph and rebuild it. // The resolution may have changed or we may have lost surfaces due to // a transition from another application's full screen exclusive mode. case WM_DISPLAYCHANGE: Cleanup(); InitD3D(hWnd); InitGeometry(); break; case WM_CHAR: { // Close the app if the ESC key is pressed if (wParam == VK_ESCAPE) { PostMessage(hWnd, WM_CLOSE, 0, 0); } // else maybe background color change by space else if(wParam == VK_SPACE) { bkRed = (BYTE)(rand()%0xFF); bkGrn = (BYTE)(rand()%0xFF); bkBlu = (BYTE)(rand()%0xFF); } // else if 'enter' return to black else if(wParam == VK_RETURN ) { bkRed = bkGrn = bkBlu = 0x0; } } break; case WM_SYSCOMMAND: { switch (wParam) { case ID_HELP_ABOUT: // Create a modeless dialog to prevent rendering interruptions CreateDialog(hInstance, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, (DLGPROC) AboutDlgProc); return 0; } } break; } return DefWindowProc( hWnd, msg, wParam, lParam ); } //----------------------------------------------------------------------------- // Name: AboutDlgProc() // Desc: Message handler for About box //----------------------------------------------------------------------------- LRESULT CALLBACK AboutDlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: if (wParam == IDOK) { EndDialog(hWnd, TRUE); return TRUE; } break; } return FALSE; } //----------------------------------------------------------------------------- // Name: AddAboutMenuItem() // Desc: Adds a menu item to the end of the app's system menu //----------------------------------------------------------------------------- void AddAboutMenuItem(HWND hWnd) { // Add About box menu item HMENU hwndMain = GetSystemMenu(hWnd, FALSE); // Add separator BOOL rc = AppendMenu(hwndMain, MF_SEPARATOR, 0, NULL); // Add menu item rc = AppendMenu(hwndMain, MF_STRING | MF_ENABLED, ID_HELP_ABOUT, TEXT("About Texture3D9...\0")); } //----------------------------------------------------------------------------- // Name: WinMain() // Desc: The application's entry point //----------------------------------------------------------------------------- INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE hInstPrev, LPSTR lpCmdLine, INT nCmdShow) { UINT uTimerID=0; // Initialize COM CoInitialize (NULL); // Register the window class WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL), LoadIcon(hInst, MAKEINTRESOURCE(IDI_TEXTURES)), NULL, NULL, NULL, CLASSNAME, NULL }; RegisterClassEx( &wc ); hInstance = hInst; // Create the application's window g_hWnd = CreateWindow( CLASSNAME, TEXT("DirectShow Texture3D9 Sample"), WS_OVERLAPPEDWINDOW, 100, 100, 300, 300, GetDesktopWindow(), NULL, wc.hInstance, NULL ); // Add a menu item to the app's system menu AddAboutMenuItem(g_hWnd); // Initialize Direct3D if( SUCCEEDED( InitD3D( g_hWnd ) ) ) { // Create the scene geometry if( SUCCEEDED( InitGeometry() ) ) { // // Set a timer to queue render operations // uTimerID = (UINT) SetTimer(g_hWnd, TIMER_ID, TIMER_RATE, NULL); // Show the window ShowWindow( g_hWnd, SW_SHOWDEFAULT ); UpdateWindow( g_hWnd ); // Enter the message loop MSG msg; ZeroMemory( &msg, sizeof(msg) ); // Main message loop while( msg.message!=WM_QUIT ) { if(GetMessage( &msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } } } // Stop the rendering timer KillTimer(g_hWnd, TIMER_ID); // Clean up everything and exit the app Cleanup(); UnregisterClass( CLASSNAME, wc.hInstance ); CoUninitialize(); return 0L; }
[ [ [ 1, 660 ] ] ]
4cf541a223fd04d932d197ac3ec7052cc196d2e1
3dca0a6382ea348a8617be05e1bfa6f4ed70d77c
/include/PgeOverlay.h
d3aa7a5c14d88cfc8a571e1bd6b432e5ba723994
[]
no_license
David-Haim-zz/pharaoh-game-engine
9c766916559f9c74667e981b9b3f03b43920bc4e
b71db3fd99ebad0ab40a0888360d560748f63131
refs/heads/master
2021-05-29T15:17:23.043407
2011-01-23T17:53:39
2011-01-23T17:53:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,631
h
/*! $Id$ * @file PgeOverlay.h * @author Chad M. Draper * @date April 6, 2009 * @brief Base class for overlays. * */ #ifndef PGEOVERLAY_H #define PGEOVERLAY_H #if ( PGE_PLATFORM == PGE_PLATFORM_WIN32 ) # include <windows.h> #endif #include "PgePlatform.h" #include "PgeSharedPtr.h" #include "PgeTypes.h" #include <OISMouse.h> #include <OISKeyboard.h> #include <OISJoyStick.h> namespace PGE { class OverlayElement; /** @class Overlay The overlay class allows us to render layers on top of the scene. Typical uses are for displaying user stats (health, lives remaining, etc.) They may also be used for displaying 3D elements on top of the scene, such as the cockpit of an airplane, or the dashboard of a race car. The overlay itself will fill the entire frame, but since it is the elements that are rendered, and not the overlay, then only those areas that contain an element will have something rendered. @par Overlays will receive input commands from the overlay manager, but not as an input listener. All input listeners receive every command, so that they can do processing as necessary. It is not desireable for each overlay to process every command. For instance, in a UI situation where two elements in separate overlays overlap, we would want a mouse click to only affect the top-most element, and others should ignore the click. Similarly, keyboard entries should only go to the active element, and not to each overlay. */ class _PgeExport Overlay { protected: typedef SharedPtr< OverlayElement > ElementPtr; typedef std::map< String, ElementPtr > ElementMap; ElementMap mElements; String mActiveElement; ///< Index of the active element bool mIsVisible; ///< Indicates if the overlay is currently being rendered bool mAcceptsInput; ///< Indicates if the overlay accepts input, or if it is for display only public: /** Constructor */ Overlay(); /** IsVisible Returns whether the overlay is currently being displayed. */ bool IsVisible() const { return mIsVisible; } /** Show or hide the overlay */ void Show( bool isVisible ) { mIsVisible = isVisible; } /** AcceptsInput Returns whether the overlay may accept user input. This is also dependent on whether the overlay is visible, so if the overlay is currently hidden, this will return false. */ bool AcceptsInput() const { return mIsVisible && mAcceptsInput; } /** Set the flag to accept or ignore input */ void AcceptInput( bool accept ) { mAcceptsInput = accept; } /** Add an element to the overlay */ void AddElement( OverlayElement* elem, const String& name ); /** Get a pointer to a named element */ OverlayElement* GetElement( const String& name ); /** Get a pointer to the active element. If there is no active element, then the last element is returned. */ OverlayElement* GetActiveElement(); /** Render the elements in this overlay */ void Render(); /** Key pressed */ bool KeyPressed( const OIS::KeyEvent& e ); /** Key released */ bool KeyReleased( const OIS::KeyEvent& e ); /** Mouse moved */ bool MouseMoved( const OIS::MouseEvent& e ); /** Mouse button pressed */ bool MousePressed( const OIS::MouseEvent& e, OIS::MouseButtonID id ); /** Mouse button released */ bool MouseReleased( const OIS::MouseEvent& e, OIS::MouseButtonID id ); /** Joystick axis moved */ bool AxisMoved( const OIS::JoyStickEvent& e, int axis ); /** Joystick pov moved */ bool PovMoved( const OIS::JoyStickEvent& e, int index ); /** Joystick 3D vector moved */ bool Vector3Moved( const OIS::JoyStickEvent& e, int index ); /** Joystick slider moved */ bool SliderMoved( const OIS::JoyStickEvent& e, int index ); /** Joystick button pressed */ bool ButtonPressed( const OIS::JoyStickEvent& e, int button ); /** Joystick button released */ bool ButtonReleased( const OIS::JoyStickEvent& e, int button ); }; // class Overlay } // namespace PGE #endif // PGEOVERLAY_H
[ "pharaohgameengine@555db735-7c4c-0410-acd0-0358cc0c1ac3" ]
[ [ [ 1, 126 ] ] ]
f541c8660ba189105f4fa0b68acef7fc0745ecdd
25f79693b806edb9041e3786fa3cf331d6fd4b97
/src/core/cal/ConstBuffer.cpp
2a77e8519547adcba1c02d5818752428ea3737f6
[]
no_license
ouj/amd-spl
ff3c9faf89d20b5d6267b7f862c277d16aae9eee
54b38e80088855f5e118f0992558ab88a7dea5b9
refs/heads/master
2016-09-06T03:13:23.993426
2009-08-29T08:55:02
2009-08-29T08:55:02
32,124,284
0
0
null
null
null
null
UTF-8
C++
false
false
3,475
cpp
////////////////////////////////////////////////////////////////////////// //! //! \file ConstBuffer.cpp //! \date 28:2:2009 21:56 //! \author //! //! \brief Contains definition of ConstBuffer class. //! ////////////////////////////////////////////////////////////////////////// #include "ConstBuffer.h" #include <stdio.h> namespace amdspl { namespace core { namespace cal { ////////////////////////////////////////////////////////////////////////// //! //! \return Constructor //! //! \brief Construct the ConstBuffer object //! ////////////////////////////////////////////////////////////////////////// ConstBuffer::ConstBuffer() : RemoteBuffer(CAL_FORMAT_FLOAT_4, MAX_CONST_NUM, 0), _buffer(MAX_CONST_NUM) { isModified = false; } ////////////////////////////////////////////////////////////////////////// //! //! \param size The new size of the constant buffer. //! \return bool True if the constant buffer is successfully resized. //! False if there is an error during the resizing. //! //! \brief Resize the constant buffer. The new size cannot exceeded //! MAX_CONST_NUM. //! ////////////////////////////////////////////////////////////////////////// bool ConstBuffer::resize(unsigned int size) { if (size > MAX_CONST_NUM) { fprintf(stderr, "Constant buffer size cannot exceed %d\n", MAX_CONST_NUM); return false; } _buffer.resize(size); isModified = false; return true; } ////////////////////////////////////////////////////////////////////////// //! //! \return Destructor //! //! \brief Destroy the ConstBuffer object. //! ////////////////////////////////////////////////////////////////////////// ConstBuffer::~ConstBuffer() { } ////////////////////////////////////////////////////////////////////////// //! //! \return bool True if the constant values are successfully synchronized //! to the CAL buffer. False if an error happens during //! data synchronization. //! //! \brief Synchronize the constant values data in system memory to the //! CAL buffer. //! ////////////////////////////////////////////////////////////////////////// bool ConstBuffer::sync() { if (isModified) { waitInputEvent(); CALuint pitch; void* data = getPointerCPU(pitch); if(!data) { return false; } memcpy(data, &_buffer[0], _buffer.size() * sizeof(float4)); releasePointerCPU(); } return true; } } } }
[ "jiawei.ou@1960d7c4-c739-11dd-8829-37334faa441c", "the729@1960d7c4-c739-11dd-8829-37334faa441c" ]
[ [ [ 1, 10 ], [ 12, 96 ] ], [ [ 11, 11 ] ] ]
62736f3929efd7c198f4c2e5262aafcd3e9050c3
288840a48549582b64d2eb312c2e348d588b278b
/src/logging.cpp
a26a89165900beb5439def2cc5c9ca0afb849f64
[]
no_license
mikegogulski/Mephbot
590672d2cf859b2b125514d4f581b9543894ff46
efa1e17a447300b763111f0993a6bc91b6a7b0d4
refs/heads/master
2016-09-06T02:05:43.197714
2011-12-10T20:07:46
2011-12-10T20:07:46
1,107,469
9
5
null
null
null
null
UTF-8
C++
false
false
4,257
cpp
////////////////////////////////////////////////////////////////////////////// // // COPYRIGHT // // This program is Copyright (c) 2002 by Mike Gogulski <[email protected]> // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // // Syadasti's open-source human-readable software LICENSE // // This code is freely redistributable, provided that all credits and // copyright notices are preserved. // // You may use this code in your own software without restriction, provided // that your software is distributed with complete source code. // // You agree by making use of this code that whatever problems you experience // as a result are your fault, and yours alone. // ////////////////////////////////////////////////////////////////////////////// #define WIN32_LEAN_AND_MEAN #include "logging.h" VOID WriteLog(char *szFile, char *aMsg) { if (hLogFile && ftell(hLogFile) >= 0) { fprintf(hLogFile, "%s\n", aMsg); fflush(hLogFile); } // FIXME: we should handle the "failed to open file" exception here, but // definitely NOT with dprintf! return; } // what a beast this became... used to be a single little #define! VOID dprint(char *aMsg1) { char TimeBuf[9], DateBuf[9]; char dprintMsgBuf[4096], dprintMsgBuf2[4096]; memset(dprintMsgBuf, 0, 4096); memset(dprintMsgBuf2, 0, 4096); //#define MAX_DPRINT 163 // draft handling for on-screen printing of very large messages //for (int i = 0; i <= strlen(aMsg1) / MAX_DPRINT; i++) { //strncpy(buf, aMsg1 + (i * MAX_DPRINT), MAX_DPRINT); if (InGame() && fDebugToScreen) { sprintf(dprintMsgBuf2, "mephbot: %82s%s\0", " ", aMsg1 /*+ (i * MAX_DPRINT)*/); server->GamePrintInfo(dprintMsgBuf2); } _strtime(TimeBuf); _strdate(DateBuf); sprintf(dprintMsgBuf, "%s %s %08d mephbot: %s\0", DateBuf, TimeBuf, dwTickGlobal, aMsg1); WriteLog(szLogFileName, dprintMsgBuf); //} return; } VOID dprintf(int flags, const char *fmt, ...) { if (fDebug) { if (DebugLevel == DEBUG_ALL || flags == DEBUG_ALL || flags & DebugLevel) { va_list args; char dprintfBuf[4096]; memset(dprintfBuf, 0, 4096); va_start(args, fmt); vsprintf(dprintfBuf, fmt, args); dprint(dprintfBuf); va_end(args); delete args; } } return; } VOID DumpPacket(BYTE *aPacket, DWORD aLen, int flag) { // from thohell & druttis's sniffer.d2h module char t[4096]; memset(t, 0, 4096); sprintf(t, flag ? "RECV:" : "SENT:"); for(int i = 0; i < aLen; i++) sprintf(t, "%s %.2x", t, aPacket[i]); if (DebugLevel & DEBUG_PACKETS_ASCII) { sprintf(t, "%s ", t); for(i=0; i < aLen; i++) sprintf(t, "%s%c", t, aPacket[i] > 31 && aPacket[i] < 128 ? aPacket[i] : '_'); } dprintf(DEBUG_PACKETS, t); if (DebugLevel & DEBUG_PACKETS_PKTIDENT) { // from masterste0's pktident.d2h module char text[256]; char c[5]; memset(text, 0, 256); sprintf(c, "%.2x%.2x\0", aPacket[0], aPacket[1]); strcpy(text, server->GetHackProfileString("pktident", flag ? "recv" : "send", c)); if (strlen(text) > 4) { dprintf(DEBUG_PACKETS, text); } else { sprintf(c,"%.2x\0",aPacket[0]); strcpy(text, server->GetHackProfileString("pktident", flag ? "recv" : "send", c)); if (strlen(text) > 4) { dprintf(DEBUG_PACKETS, text); } } } return; } VOID SetUpLogInfo(char *buf, DWORD tglobal, DWORD tgame, DWORD restarts, DWORD aborts, DWORD runs, DWORD kills, DWORD deaths, DWORD chickens) { sprintf(buf, "tGlobal=~%d:%02d:%02d.%d tGame=~%02d:%02d.%d Restarts=%02d Aborts=%02d Runs=%02d Kills=%02d Deaths=%02d Chickens=%02d", tglobal / 10 / 60 / 60, // hr (tglobal / 10 / 60) % 60, // min (tglobal / 10) % 60, // sec tglobal % 10, // tenths (tgame / 10 / 60) % 60, // min (tgame / 10) % 60, // sec tgame % 10, // tenths restarts, aborts, runs, kills, deaths, chickens); return; } VOID LogInfo(char *buf, DWORD tglobal, DWORD tgame, DWORD restarts, DWORD aborts, DWORD runs, DWORD kills, DWORD deaths, DWORD chickens) { SetUpLogInfo(buf, tglobal, tgame, restarts, aborts, runs, kills, deaths, chickens); dprintf(DEBUG_ALL, buf); return; }
[ [ [ 1, 115 ] ] ]
403828478aa5cc606b01645799b76bea29dc1339
3b0bcc3e6cba0109463101aea0b1a3406fc45429
/Debugger/source/Utilities.cpp
75e5792a44b34eee632bbf4c25f2dae6648ef5d6
[ "MIT" ]
permissive
lsalamon/slimgen
85a5dad4995b590152f761b18eebc174f9baebbc
a4c959438a9d6dfc487fc34856e2b69a146c1e61
refs/heads/master
2021-01-10T08:17:50.381747
2010-11-07T04:29:26
2010-11-07T04:29:26
54,969,433
0
0
null
null
null
null
UTF-8
C++
false
false
3,257
cpp
/* * Copyright (c) 2007-2010 SlimGen Group * * 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 "stdafx.h" #include "Utilities.h" #include "RuntimeMethodReplacer.h" #include "SigFormat.h" namespace SlimGen { std::wstring GetMethodNameFromDef( IMetaDataImport2* metadata, mdMethodDef methodDef) { ULONG methodNameLength; PCCOR_SIGNATURE signature; ULONG signatureLength; metadata->GetMethodProps(methodDef, 0, 0, 0, &methodNameLength, 0, 0, 0, 0, 0); std::wstring methodName(methodNameLength, 0); std::wstring signatureStr; metadata->GetMethodProps(methodDef, 0, &methodName[0], methodNameLength, &methodNameLength, 0, &signature, &signatureLength, 0, 0); wchar_t sigStr[2048]; SigFormat formatter(sigStr, 2048, methodDef, metadata, metadata); formatter.Parse(static_cast<const sig_byte*>(signature), signatureLength); signatureStr = sigStr; return methodName.substr(0, methodName.length() - 1) + signatureStr; } std::wstring GetTypeNameFromDef(IMetaDataImport2* metadata, mdTypeDef typeDef) { ULONG typeNameLength; metadata->GetTypeDefProps(typeDef, 0, 0, &typeNameLength, 0, 0); std::wstring typeName(typeNameLength, 0); metadata->GetTypeDefProps(typeDef, &typeName[0], typeNameLength, &typeNameLength, 0, 0); return std::wstring(typeName.begin(), typeName.end() - 1); } std::wstring GetRuntimeVersion(int processId) { Handle handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId); if (handle.IsInvalid()) throw std::runtime_error("Unable to open process."); std::wstringstream wss; wss<<std::hex<<handle<<std::endl<<processId; DWORD length; if (FAILED(GetVersionFromProcess(handle, NULL, 0, &length))) throw std::runtime_error("Unable to get version length from process."); std::wstring version(length, 0); if (FAILED(GetVersionFromProcess(handle, &version[0], length, &length))) throw std::runtime_error("Unable to get version from process."); return version; } }
[ "ryoohki@dc685512-7b07-11de-a624-ab7c8f4ec817" ]
[ [ [ 1, 78 ] ] ]
4145d30733e1648e45f1e0c644936e62f2f3dd78
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Ngllib/src/EffectParameter.cpp
1b50e4c49cff6c353719c4c7b621170d94ce420d
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
8,729
cpp
/*******************************************************************************/ /** * @file EffectParameter.cpp. * * @brief エフェクトパラメータクラスソースファイル. * * @date 2008/07/10. * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #include "Ngl/EffectParameter.h" #include <cassert> using namespace Ngl; /*=========================================================================*/ /** * @brief コンストラクタ * * @param[in] effect エフェクトクラスのポインタ. * @param[in] parameterName パラメータ名. */ EffectParameter::EffectParameter( IEffect* effect, const std::string parameterName ): effect_( effect ), parameterName_( parameterName ) { assert( effect_ != 0 ); } /*=========================================================================*/ /** * @brief デストラクタ * * @param[in] なし. */ EffectParameter::~EffectParameter() { effect_ = 0; } /*=========================================================================*/ /** * @brief パラメータ名を取得 * * @param[in] なし. * @return パラメータ名. */ const std::string& EffectParameter::name() const { return parameterName_; } /*=========================================================================*/ /** * @brief スカラーパラメータインターフェースを取得 * * @param[in] なし. * @return スカラーパラメータインターフェースのポインタ. */ IEffectScalarParameter* EffectParameter::asScalar() { return this; } /*=========================================================================*/ /** * @brief ベクトルパラメータインターフェースを取得 * * @param[in] なし. * @return ベクトルパラメータインターフェースのポインタ. */ IEffectVectorParameter* EffectParameter::asVector() { return this; } /*=========================================================================*/ /** * @brief 行列パラメータインターフェースを取得 * * @param[in] なし. * @return 行列パラメータインターフェースのポインタ. */ IEffectMatrixParameter* EffectParameter::asMatrix() { return this; } /*=========================================================================*/ /** * @brief テクスチャパラメータインターフェースを取得 * * @param[in] なし. * @return テクスチャパラメータインターフェースのポインタ. */ IEffectTextureParameter* EffectParameter::asTexture() { return this; } /*=========================================================================*/ /** * @brief int型のパラメータを設定 * * @param[in] v 設定するパラメータ. * @return なし. */ void EffectParameter::setInt( int v ) { effect_->setScalar( name().c_str(), v ); } /*=========================================================================*/ /** * @brief int型配列のパラメータを設定 * * @param[in] v 設定する配列パラメータの先頭ポインタ. * @param[in] count 要素数. * @return なし. */ void EffectParameter::setIntArray( const int* v, unsigned int count ) { effect_->setScalarArray( name().c_str(), const_cast< int* >( v ), count ); } /*=========================================================================*/ /** * @brief float型のパラメータを設定 * * @param[in] v 設定するパラメータ. * @return なし. */ void EffectParameter::setFloat( float v ) { effect_->setScalar( name().c_str(), v ); } /*=========================================================================*/ /** * @brief float型配列のパラメータを設定 * * @param[in] v 設定する配列パラメータの先頭ポインタ. * @param[in] count 要素数. * @return なし. */ void EffectParameter::setFloatArray( const float* v, unsigned int count ) { effect_->setScalarArray( name().c_str(), const_cast< float* >( v ), count ); } /*=========================================================================*/ /** * @brief RGBAカラー構造体のパラメータを設定 * * @param[in] color 設定するRGBAカラー構造体パラメータ. * @return なし. */ void EffectParameter::setColor( const Color4& color ) { effect_->setVector( name().c_str(), color.r, color.g, color.b, color.a ); } /*=========================================================================*/ /** * @brief RGBAカラー構造体配列のパラメータを設定 * * @param[in] color 設定するRGBAカラー配列パラメータの先頭ポインタ. * @param[in] count 要素数. * @return なし. */ void EffectParameter::setColorArray( const Color4* color, unsigned int count ) { effect_->setVectorArray( name().c_str(), (float*)color, count ); } /*=========================================================================*/ /** * @brief 2次元ベクトルを設定する * * @param[in] v2 設定する2次元ベクトル構造体. * @return なし. */ void EffectParameter::setVector2( const Vector2& v2 ) { effect_->setScalarArray( name().c_str(), (float*)v2, 2 ); } /*=========================================================================*/ /** * @brief 2次元ベクトルの配列を設定する * * @param[in] v2 設定する2次元ベクトル構造体配列の先頭ポインタ. * @param[in] count 配列の要素数 * @return なし. */ void EffectParameter::setVector2Array( const Vector2& v2, unsigned int count ) { effect_->setVectorArray( name().c_str(), (float*)v2, count ); } /*=========================================================================*/ /** * @brief 3次元ベクトルを設定する * * @param[in] v3 設定する3次元ベクトル構造体. * @return なし. */ void EffectParameter::setVector3( const Vector3& v3 ) { effect_->setVector( name().c_str(), v3.x, v3.y, v3.z ); } /*=========================================================================*/ /** * @brief 3次元ベクトルの配列を設定する * * @param[in] v3 設定する3次元ベクトル構造体配列の先頭ポインタ. * @param[in] count 配列の要素数 * @return なし. */ void EffectParameter::setVector3Array( const Vector3& v3, unsigned int count ) { effect_->setVectorArray( name().c_str(), (float*)v3, count ); } /*=========================================================================*/ /** * @brief 4次元ベクトルを設定する * * @param[in] v4 設定する4次元ベクトル構造体. * @return なし. */ void EffectParameter::setVector4( const Vector4& v4 ) { effect_->setVector( name().c_str(), v4.x, v4.y, v4.z, v4.w ); } /*=========================================================================*/ /** * @brief 4次元ベクトルの配列を設定する * * @param[in] v4 設定する4次元ベクトル構造体配列の先頭ポインタ. * @param[in] count 配列の要素数 * @return なし. */ void EffectParameter::setVector4Array( const Vector4& v4, unsigned int count ) { effect_->setVectorArray( name().c_str(), (float*)v4, count ); } /*=========================================================================*/ /** * @brief 4x4行列を設定する * * @param[in] matrix 設定する4x4行列構造体. * @return なし. */ void EffectParameter::setMatrix( const Matrix4& matrix ) { effect_->setMatrix( parameterName_.c_str(), (float*)matrix ); } /*=========================================================================*/ /** * @brief 4x4行列の配列を設定する * * @param[in] matrix 設定する4x4行列構造体配列の先頭ポインタ. * @param[in] count 要素数 * @return なし. */ void EffectParameter::setMatrixArray( const Matrix4* matrix, unsigned int count ) { effect_->setMatrixArray( parameterName_.c_str(), (float*)matrix, count ); } /*=========================================================================*/ /** * @brief テクスチャパラメータを設定 * * @param[in] texture 設定するテクスチャインターフェースのポインタ. * @return なし. */ void EffectParameter::setTexture( ITexture* texture ) { effect_->setTexture( parameterName_.c_str(), texture ); } /*===== EOF ==================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 334 ] ] ]
d72c3fc53c9c25a80c41041a10aed2564d52c550
46c766a3da1fbfb390613f8d4aeaea079180d739
/quicksort.h
08d1f4754909e620989f4a004af4fc81e139eaf6
[]
no_license
laosland/CSCE350_final_project
c72cf43905b76dbd0fd429b0f359df3cf19134b8
90e4a85f96497be5e3f52e1468b70e19c2679d77
refs/heads/master
2021-01-10T19:09:01.746106
2011-10-25T22:10:19
2011-10-25T22:10:19
2,621,820
0
0
null
null
null
null
UTF-8
C++
false
false
382
h
#ifndef QUICKSORT_H #define QUICKSORT_H #include "sorts.h" #include <iostream> class quicksort : public sorts { public: quicksort(); quicksort(vector <int>); quicksort(vector <int>, int, int); virtual ~quicksort(); bool sort(vector<int>); protected: private: int findPivot( int ); }; #endif // QUICKSORT_H
[ [ [ 1, 19 ] ] ]
d25ad6eb73ad4e1d55c91fddebc4cd98626b02c8
7f6fe18cf018aafec8fa737dfe363d5d5a283805
/ntk/application/messenger.h
54cebf5b02cc2dc9ce5e8c4a38edf7b9f57632dc
[]
no_license
snori/ntk
4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba
86d1a32c4ad831e791ca29f5e7f9e055334e8fe7
refs/heads/master
2020-05-18T05:28:49.149912
2009-08-04T16:47:12
2009-08-04T16:47:12
268,861
2
0
null
null
null
null
UTF-8
C++
false
false
1,899
h
/****************************************************************************** The NTK Library Copyright (C) 1998-2003 Noritaka Suzuki $Id: messenger.h,v 1.5 2003/11/11 12:07:05 nsuzuki Exp $ ******************************************************************************/ #pragma once #ifndef __NTK_APPLICATION_MESSENGER_H__ #define __NTK_APPLICATION_MESSENGER_H__ #ifndef __NTK_DEFS_H__ #include <ntk/defs.h> #endif #ifndef __NTK_SUPPORT_STATUS_H__ #include <ntk/support/status.h> #endif namespace ntk { class Message; class Looper; class Handler; class Messenger { public: // // methods // NtkExport Messenger(Handler* target, Looper* looper = NULL, status_t* result = NULL); NtkExport Messenger(const Messenger& messenger); NtkExport virtual ~Messenger(); NtkExport virtual Messenger& operator=(const Messenger& messenger); NtkExport virtual status_t send_message(uint command, Handler* reply_handler = NULL) const; NtkExport virtual status_t send_message(const Message& message, Handler* reply_handler = NULL) const; // // accessors and manipulators // NtkExport virtual Handler* target(Looper** looper_ = NULL) const; NtkExport virtual status_t set_target(Handler* target_, Looper* looper_ = NULL); NtkExport virtual bool is_valid() const; // // operators // NtkExport friend bool operator==(const Messenger& lhs, const Messenger& rhs); private: // // data // Handler* m_target; Looper* m_looper; };// class Messenger #ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME typedef Messenger messenger_t; #endif } namespace Ntk = ntk; #ifdef NTK_TYPEDEF_TYPES_AS_GLOBAL_TYPE #ifdef NTK_TYPEDEF_GLOBAL_NCLASS typedef ntk::Messenger NMessenger; #endif #ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME typedef ntk::Messenger ntk_messenger; #endif #endif #endif//EOH
[ [ [ 1, 86 ] ] ]
5fb6df0dd09b7da15ad34a08c074f6dfde345041
2d4221efb0beb3d28118d065261791d431f4518a
/OIDE源代码/OLIDE/Data/HintString.cpp
e97b0c7a8c18cc88bf094bf4cfced3518e108e44
[]
no_license
ophyos/olanguage
3ea9304da44f54110297a5abe31b051a13330db3
38d89352e48c2e687fd9410ffc59636f2431f006
refs/heads/master
2021-01-10T05:54:10.604301
2010-03-23T11:38:51
2010-03-23T11:38:51
48,682,489
1
0
null
null
null
null
GB18030
C++
false
false
7,007
cpp
#include "stdafx.h" #include "HintString.h" #include "./StdioFile/StdioFileEx.h" #include "../Controls/scintilla/SyntaxCtrl.h" #include "../MainFrm.h" #include "../Common/Common.h" CHintString::CHintString() { //OASM自动完成提示数组 m_nOASMAutoCompleteItemCount = 0; m_phsOASMAutoComplete = NULL; //OASM信息提示数组 m_nOASMTipDataCount = 0; m_phsOASMTipData = NULL; //OML自动完成提示数组 m_nOMLAutoCompleteItemCount = 0; m_phsOMLAutoComplete = NULL; //OML信息提示数组 m_nOMLTipDataCount = 0; m_phsOMLTipData = NULL; } CHintString::~CHintString() { ClearData(m_phsOASMAutoComplete,m_nOASMAutoCompleteItemCount); ClearData(m_phsOASMTipData,m_nOASMTipDataCount); ClearData(m_phsOMLAutoComplete,m_nOMLAutoCompleteItemCount); ClearData(m_phsOMLTipData,m_nOMLTipDataCount); } void CHintString::LoadHintData() { CMainFrame* pMainFrame = (CMainFrame*)AfxGetMainWnd(); CString strOASMAutoCompleteFileName = pMainFrame->m_systemOption.m_strOASMAutoCompleteFileName; CString strOASMTipFileName = pMainFrame->m_systemOption.m_strOASMTipFileName; CString strAppDir = pMainFrame->GetAppDirectory(); if(!strOASMAutoCompleteFileName.IsEmpty() && strOASMAutoCompleteFileName[0] == _T('.')) { GetAbsolutePathByRelativePath(strOASMAutoCompleteFileName,strAppDir); } if(!strOASMTipFileName.IsEmpty() && strOASMTipFileName[0] == _T('.')) { GetAbsolutePathByRelativePath(strOASMTipFileName,strAppDir); } if(m_strOASMAutoCompleteFileName != strOASMAutoCompleteFileName) { m_strOASMAutoCompleteFileName = strOASMAutoCompleteFileName; ClearData(m_phsOASMAutoComplete,m_nOASMAutoCompleteItemCount); LoadData(m_strOASMAutoCompleteFileName,m_phsOASMAutoComplete,m_nOASMAutoCompleteItemCount); } if(m_strOASMTipFileName != strOASMTipFileName) { m_strOASMTipFileName = strOASMTipFileName; ClearData(m_phsOASMTipData,m_nOASMTipDataCount); LoadData(m_strOASMTipFileName,m_phsOASMTipData,m_nOASMTipDataCount); } ////////////////////////////////////////////////////////////////////////// CString strOMLAutoCompleteFileName = pMainFrame->m_systemOption.m_strOMLAutoCompleteFileName; CString strOMLTipFileName = pMainFrame->m_systemOption.m_strOMLTipFileName; if(!strOMLAutoCompleteFileName.IsEmpty() && strOMLAutoCompleteFileName[0] == _T('.')) { GetAbsolutePathByRelativePath(strOMLAutoCompleteFileName,strAppDir); } if(!strOMLTipFileName.IsEmpty() && strOMLTipFileName[0] == _T('.')) { GetAbsolutePathByRelativePath(strOMLTipFileName,strAppDir); } if(m_strOMLAutoCompleteFileName != strOMLAutoCompleteFileName) { m_strOMLAutoCompleteFileName = strOMLAutoCompleteFileName; ClearData(m_phsOMLAutoComplete,m_nOMLAutoCompleteItemCount); LoadData(m_strOMLAutoCompleteFileName,m_phsOMLAutoComplete,m_nOMLAutoCompleteItemCount); } if(m_strOMLTipFileName != strOMLTipFileName) { m_strOMLTipFileName = strOMLTipFileName; ClearData(m_phsOMLTipData,m_nOMLTipDataCount); LoadData(m_strOMLTipFileName,m_phsOMLTipData,m_nOMLTipDataCount); } } BOOL CHintString::LoadConfigFile(const CString& strAutoFileName,CStringArray& strarrayData) { CStdioFileEx stdFile; if(stdFile.Open(strAutoFileName, CFile::modeRead|CFile::typeText)) { CString strLine; while(stdFile.ReadStringEx(strLine,TRUE,_T(';'))) { while(strLine[strLine.GetLength()-1] == _T('\\')) { strLine.TrimRight(_T('\\')); CString strTemp; if(stdFile.ReadStringEx(strTemp,TRUE,_T(';'))) { strLine += strTemp; } } strarrayData.Add(strLine); } return TRUE; } return FALSE; } BOOL CHintString::LoadData(const CString& strAutoFileName,HINT_STRING*& phsData,int& nCount) { CStringArray strarrayAutoData; if(!LoadConfigFile(strAutoFileName,strarrayAutoData)) return FALSE; nCount = strarrayAutoData.GetCount(); if(nCount > 0) { phsData = new HINT_STRING[nCount]; int nPos = 0,nNextPos = 0; CString strLine; for(int i=0;i<nCount;++i) { strLine = strarrayAutoData[i]; nPos = strLine.Find(_T('\'')); if(nPos >= 0) { nNextPos = strLine.Find(_T('\''),nPos+1); phsData[i].m_strInput = strLine.Mid(nPos+1,nNextPos-nPos-1); } nPos = strarrayAutoData[i].Find(_T('"')); if(nPos >= 0) { nNextPos = strLine.Find(_T('"'),nPos+1); while((nNextPos > 1) && strLine.GetAt(nNextPos-1) == _T('\\')) { nNextPos = strLine.Find(_T('"'),nNextPos+1); } phsData[i].m_strHint = strLine.Mid(nPos+1,nNextPos-nPos-1); phsData[i].m_strHint.Replace(_T("\\\""),_T("\"")); phsData[i].m_strHint.Replace(_T("\\n"),_T("\n")); phsData[i].m_strHint.Replace(_T("\\r"),_T("\r")); } } Convert2UTF8(phsData,nCount); return TRUE; } return FALSE; } void CHintString::Convert2UTF8(HINT_STRING* phsData,int nItemCount) { #ifdef _UNICODE for(int i=0;i<nItemCount;++i) { CScintillaCtrl::W2UTF8(phsData[i].m_strInput,-1,phsData[i].m_pInput); } #else for(int i=0;i<nItemCount;++i) { phsData[i].m_pInput = (LPCTSTR)phsData[i].m_strInput; } #endif } void CHintString::ClearData(HINT_STRING*& phsData,int& nItemCount) { if(phsData) { for(int i=0;i<nItemCount;++i) { if(phsData[i].m_pInput) { delete[] phsData[i].m_pInput; phsData[i].m_pInput = NULL; } } nItemCount = 0; delete[] phsData; phsData = NULL; } } int CHintString::GetItemCount(int nHintStringType) { ASSERT(nHintStringType>HST_NULL && nHintStringType<HST_END); switch(nHintStringType) { case HST_OASM_AUTO_COMPLETE: return m_nOASMAutoCompleteItemCount; case HST_OASM_TIP: return m_nOASMTipDataCount; case HST_OML_AUTO_COMPLETE: return m_nOMLAutoCompleteItemCount; case HST_OML_TIP: return m_nOMLTipDataCount; } return 0; } char* CHintString::GetItemInput(int nHintStringType,int nItem) { ASSERT(nHintStringType>HST_NULL && nHintStringType<HST_END); ASSERT(nItem>=0 && GetItemCount(nHintStringType)); switch(nHintStringType) { case HST_OASM_AUTO_COMPLETE: return m_phsOASMAutoComplete[nItem].m_pInput; case HST_OASM_TIP: return m_phsOASMTipData[nItem].m_pInput; case HST_OML_AUTO_COMPLETE: return m_phsOMLAutoComplete[nItem].m_pInput; case HST_OML_TIP: return m_phsOMLTipData[nItem].m_pInput; } return NULL; } CString& CHintString::GetItemHint(int nHintStringType,int nItem) { ASSERT(nHintStringType>HST_NULL && nHintStringType<HST_END); ASSERT(nItem>=0 && GetItemCount(nHintStringType)); switch(nHintStringType) { case HST_OASM_AUTO_COMPLETE: return m_phsOASMAutoComplete[nItem].m_strHint; case HST_OASM_TIP: return m_phsOASMTipData[nItem].m_strHint; case HST_OML_AUTO_COMPLETE: return m_phsOMLAutoComplete[nItem].m_strHint; case HST_OML_TIP: return m_phsOMLTipData[nItem].m_strHint; } return *((CString*)NULL); }
[ [ [ 1, 260 ] ] ]
2639fad1a21f54cf2d2a171b38672d2f851ec183
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/auxiliary/xml/xmldocument.h
185da2424ebcbbdafc44b5912c236f4a65ece0a2
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
714
h
/*! @file @brief XMLドキュメント */ #ifndef maid2_auxiliary_xml_xmldocument_h #define maid2_auxiliary_xml_xmldocument_h #include"../config/define.h" #include"xmlnode.h" #include"../functionresult.h" #include<string> namespace Maid { class XMLDocument { public: FUNCTIONRESULT Parse( const std::string& TextImage ); XMLNode& GetRoot(); const XMLNode& GetRoot() const; private: struct ATTRIBUTE { String Name; String Value; }; void DivAttribute( const String& Element, String& Name, std::vector<ATTRIBUTE>& Attribute ); SPXMLNODE ReadChildNode( const String& token ); private: SPXMLNODE m_pRootNode; }; } #endif
[ [ [ 1, 41 ] ] ]
d95ab9a416572e7fb534ba1d56fb69dbdf1a264c
f177993b13e97f9fecfc0e751602153824dfef7e
/ImPro/ImProFilters/GSFrameCaptureFilter/GSFrameCaptureFilter.h
d32f4aa6782b70d17accc26fb9bb6ee35b888f92
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
1,363
h
#pragma once #include "IGSFrameCaptureFilter.h" #include "dshow.h" #include "Streams.h" #include <initguid.h> #include "combase.h" #include "GSDXFilterBase.h" #include "GSDXMuxFilter.h" #include "IGSPersist.h" class GSFrameCaptureFilter : public GSMuxFilter, public IGSFrameCaptureFilter, public ISpecifyPropertyPages, public IGSPersist { public: static CUnknown *WINAPI CreateInstance(LPUNKNOWN punk, HRESULT *phr); //for COM interface STDMETHODIMP NonDelegatingQueryInterface(REFIID iid, void **ppv); DECLARE_IUNKNOWN; //implement DShow Property Page STDMETHODIMP GetPages(CAUUID *pPages); //from IGSPersist virtual HRESULT SaveToFile(WCHAR* path); virtual HRESULT LoadFromFile(WCHAR* path); virtual HRESULT GetName(WCHAR* name, UINT szName); //implement IGSFrameCaptureFilter protected: virtual HRESULT CreatePins(); static HRESULT __stdcall OnTransform(void* self, IMediaSample *pInSample, CMediaType* pInMT, IMediaSample *pOutSample, CMediaType* pOutMT); public: GSFrameCaptureFilter(IUnknown * pOuter, HRESULT *phr, BOOL ModifiesData); virtual ~GSFrameCaptureFilter(); public: bool isSaveImg ; int ImgCount ; WCHAR saveName[_MAX_PATH]; virtual void setIsSaveImg() ; virtual void resetSavingCount() ; virtual void setImgName(WCHAR* name) ; WCHAR wszCur[_MAX_PATH]; };
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a", "claire3kao@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 24 ], [ 26, 34 ], [ 36, 40 ], [ 49, 49 ] ], [ [ 25, 25 ], [ 35, 35 ], [ 41, 48 ] ] ]
e39df7e01603a6a5bcb8745b73735ffe1d5bafa9
96b4d383b517e578d44f9beab0814bdf18797fce
/lib/preloader.cpp
1c73b512add4468f4200a0e5cffba2e11a7e61e7
[ "MIT" ]
permissive
mkottman/LuaNode
e675f2199acfaa8190cf6c9b09f85bb9f9196f36
b059225855939477147c5d4a6e8df3350c0a25fb
refs/heads/master
2021-01-16T19:19:29.942269
2011-01-30T00:09:50
2011-01-30T00:09:50
1,234,094
2
0
null
null
null
null
UTF-8
C++
false
false
7,355
cpp
#include "preloader.h" static int luaopen_LuaNode_Class(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Class.precomp" if(extension_status) { return lua_error(L); } lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_ChildProcess(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/child_process.precomp" if(extension_status) { return lua_error(L); } lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_Crypto(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Crypto.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B2,sizeof(B2),"LuaNode.Crypto"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_Dns(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Dns.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B3,sizeof(B3),"LuaNode.Dns"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_EventEmitter(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/event_emitter.precomp" if(extension_status) { return lua_error(L); } lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_FreeList(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/free_list.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B5,sizeof(B5),"LuaNode.FreeList"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_Fs(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Fs.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B6,sizeof(B6),"LuaNode.Fs"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_Http(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Http.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B7,sizeof(B7),"LuaNode.Http"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_Net(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Net.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B8,sizeof(B8),"LuaNode.Net"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_Path(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Path.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B9,sizeof(B9),"LuaNode.Path"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_QueryString(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Querystring.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B10,sizeof(B10),"LuaNode.QueryString"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_Stream(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Stream.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B11,sizeof(B11),"LuaNode.Stream"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_Url(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Url.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B12,sizeof(B12),"LuaNode.Url"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_Timers(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Timers.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B13,sizeof(B13),"LuaNode.Net.Timeout"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_Console(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/console.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B13,sizeof(B13),"LuaNode.Console"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_LuaNode_Utils(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/Utils.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B13,sizeof(B13),"LuaNode.Console"); lua_insert(L,1); lua_call(L,arg,1); return 1; } static int luaopen_StackTracePlus(lua_State* L) { int extension_status = 1; int arg = lua_gettop(L); #include "../build/temp/StackTracePlus.precomp" if(extension_status) { return lua_error(L); } //luaL_loadbuffer(L,(const char*)B13,sizeof(B13),"StackTracePlus"); lua_insert(L,1); lua_call(L,arg,1); return 1; } void PreloadModules(lua_State* L) { luaL_findtable(L, LUA_GLOBALSINDEX, "package.preload", 1); //int preload = lua_gettop(L); lua_pushcfunction(L, luaopen_LuaNode_Class); lua_setfield(L, -2, "luanode.class"); lua_pushcfunction(L, luaopen_LuaNode_ChildProcess); lua_setfield(L, -2, "luanode.child_process"); lua_pushcfunction(L, luaopen_LuaNode_Crypto); lua_setfield(L, -2, "luanode.crypto"); lua_pushcfunction(L, luaopen_LuaNode_Dns); lua_setfield(L, -2, "luanode.dns"); lua_pushcfunction(L, luaopen_LuaNode_EventEmitter); lua_setfield(L, -2, "luanode.event_emitter"); lua_pushcfunction(L, luaopen_LuaNode_FreeList); lua_setfield(L, -2, "luanode.free_list"); lua_pushcfunction(L, luaopen_LuaNode_Fs); lua_setfield(L, -2, "luanode.fs"); lua_pushcfunction(L, luaopen_LuaNode_Http); lua_setfield(L, -2, "luanode.http"); lua_pushcfunction(L, luaopen_LuaNode_Net); lua_setfield(L, -2, "luanode.net"); lua_pushcfunction(L, luaopen_LuaNode_Path); lua_setfield(L, -2, "luanode.path"); lua_pushcfunction(L, luaopen_LuaNode_QueryString); lua_setfield(L, -2, "luanode.querystring"); lua_pushcfunction(L, luaopen_LuaNode_Stream); lua_setfield(L, -2, "luanode.stream"); lua_pushcfunction(L, luaopen_LuaNode_Url); lua_setfield(L, -2, "luanode.url"); lua_pushcfunction(L, luaopen_LuaNode_Timers); lua_setfield(L, -2, "luanode.timers"); lua_pushcfunction(L, luaopen_LuaNode_Console); lua_setfield(L, -2, "luanode.console"); lua_pushcfunction(L, luaopen_LuaNode_Utils); lua_setfield(L, -2, "luanode.utils"); lua_pop(L, 1); } ////////////////////////////////////////////////////////////////////////// /// void PreloadAdditionalModules(lua_State* L) { luaL_findtable(L, LUA_GLOBALSINDEX, "package.preload", 1); //int preload = lua_gettop(L); lua_pushcfunction(L, luaopen_StackTracePlus); lua_setfield(L, -2, "stacktraceplus"); lua_pop(L, 1); }
[ [ [ 1, 5 ], [ 7, 29 ], [ 31, 42 ], [ 44, 80 ], [ 82, 93 ], [ 95, 106 ], [ 108, 119 ], [ 121, 132 ], [ 134, 145 ], [ 147, 158 ], [ 160, 286 ] ], [ [ 6, 6 ], [ 30, 30 ], [ 43, 43 ], [ 81, 81 ], [ 94, 94 ], [ 107, 107 ], [ 120, 120 ], [ 133, 133 ], [ 146, 146 ], [ 159, 159 ], [ 287, 287 ] ] ]
04d32642eb34a357a5655c4e92512390939dc263
c0bd82eb640d8594f2d2b76262566288676b8395
/src/game/World.h
bb6a8725dc83e8b7b282b7c7c695e496abd043d6
[ "FSFUL" ]
permissive
vata/solution
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
774fca057d12a906128f9231831ae2e10a947da6
refs/heads/master
2021-01-10T02:08:50.032837
2007-11-13T22:01:17
2007-11-13T22:01:17
45,352,930
0
1
null
null
null
null
UTF-8
C++
false
false
12,567
h
// Copyright (C) 2004 WoW Daemon // // 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. // // World.h // #ifndef __WORLD_H #define __WORLD_H class Object; class WorldPacket; class WorldSession; class Unit; class Creature; class GameObject; class DynamicObject; class Player; class EventableObjectHolder; class MapMgr; enum Rates { RATE_HEALTH=0, RATE_POWER1, RATE_POWER2, RATE_POWER3, RATE_DROP, RATE_XP, RATE_RESTXP, RATE_QUESTXP, MAX_RATES }; enum IntRates { INTRATE_SAVE=0, INTRATE_COMPRESSION, INTRATE_PVPTIMER, MAX_INTRATES }; enum EnviromentalDamage { DAMAGE_EXHAUSTED = 0, DAMAGE_DROWNING = 1, DAMAGE_FALL = 2, DAMAGE_LAVA = 3, DAMAGE_SLIME = 4, DAMAGE_FIRE = 5 }; enum CharCreateErrors { SUCCESS, FAILURE, CANCELLED, DISCONNECT_FROM_SERVER, FAILED_TO_CONNECT, CONNECTED, WRONG_CLIENT_VERSION, CONNECTING_TO_SERVER, NEGOTIATING_SECURITY, NEGOTIATING_SECURITY_COMPLETE, NEGOTIATING_SECURITY_FAILED, AUTHENTICATING, AUTHENTICATION_SUCCESSFUL, AUTHENTICATION_FAILED, LOGIN_UNAVAIBLE, SERVER_IS_NOT_VALID, SYSTEM_UNAVAIBLE, SYSTEM_ERROR, BILLING_SYSTEM_ERROR, ACCOUNT_BILLING_EXPIRED, WRONG_CLIENT_VERSION_2, UNKNOWN_ACCOUNT, INCORRECT_PASSWORD, SESSION_EXPIRED, SERVER_SHUTTING_DOWN, ALREADY_LOGGED_IN, INVALID_LOGIN_SERVER, POSITION_IN_QUEUE_0, THIS_ACCOUNT_HAS_BEEN_BANNED, THIS_CHARACTER_STILL_LOGGED_ON, YOUR_WOW_SUBSCRIPTION_IS_EXPIRED, THIS_SESSION_HAS_TIMED_OUT, THIS_ACCOUNT_TEMP_SUSPENDED, ACCOUNT_BLOCKED_BY_PARENTAL_CONTROL, RETRIEVING_REALMLIST, REALMLIST_RETRIEVED, UNABLE_TO_CONNECT_REALMLIST_SERVER, INVALID_REALMLIST, GAME_SERVER_DOWN, CREATING_ACCOUNT, ACCOUNT_CREATED, ACCOUNT_CREATION_FAIL, RETRIEVE_CHAR_LIST, CHARLIST_RETRIEVED, CHARLIST_ERROR, CREATING_CHARACTER, CHARACTER_CREATED, ERROR_CREATING_CHARACTER, CHARACTER_CREATION_FAIL, NAME_IS_IN_USE, CREATION_OF_RACE_DISABLED, ALL_CHARS_ON_PVP_REALM_MUST_AT_SAME_SIDE, ALREADY_HAVE_MAXIMUM_CHARACTERS, ALREADY_HAVE_MAXIMUM_CHARACTERS_2, SERVER_IS_CURRENTLY_QUEUED, ONLY_PLAYERS_WHO_HAVE_CHARACTERS_ON_THIS_REALM, NEED_EXPANSION_ACCOUNT, DELETING_CHARACTER, CHARACTER_DELETED, CHARACTER_DELETION_FAILED, ENTERING_WOW, LOGIN_SUCCESFUL, WORLD_SERVER_DOWN, A_CHARACTER_WITH_THAT_NAME_EXISTS, NO_INSTANCE_SERVER_AVAIBLE, LOGIN_FAILED, LOGIN_FOR_THAT_RACE_DISABLED, LOGIN_FOR_THAT_RACE_CLASS_DISABLED,//check ENTER_NAME_FOR_CHARACTER, NAME_AT_LEAST_TWO_CHARACTER, NAME_AT_MOST_12_CHARACTER, NAME_CAN_CONTAIN_ONLY_CHAR, NAME_CONTAIN_ONLY_ONE_LANG, NAME_CONTAIN_PROFANTY, NAME_IS_RESERVED, YOU_CANNOT_USE_APHOS, YOU_CAN_ONLY_HAVE_ONE_APHOS, YOU_CANNOT_USE_SAME_LETTER_3_TIMES, NO_SPACE_BEFORE_NAME, BLANK, INVALID_CHARACTER_NAME, BLANK_1 //All further codes give the number in dec. }; // ServerMessages.dbc enum ServerMessageType { SERVER_MSG_SHUTDOWN_TIME = 1, SERVER_MSG_RESTART_TIME = 2, SERVER_MSG_STRING = 3, SERVER_MSG_SHUTDOWN_CANCELLED = 4, SERVER_MSG_RESTART_CANCELLED = 5 }; enum WorldMapInfoFlag { WMI_INSTANCE_ENABLED = 0x1, WMI_INSTANCE_WELCOME = 0x2, WMI_INSTANCE_MULTIMODE = 0x4, WMI_INSTANCE_XPACK_01 = 0x8, //The Burning Crusade expansion }; enum AccountFlags { ACCOUNT_FLAG_VIP = 0x1, ACCOUNT_FLAG_XTEND_INFO = 0x4, ACCOUNT_FLAG_XPACK_01 = 0x8, }; struct MapInfo { bool HasFlag(uint32 flag) { return (flags & flag) != 0; } uint32 mapid; uint32 screenid; uint32 type; uint32 playerlimit; uint32 minlevel; float repopx; float repopy; float repopz; uint32 repopmapid; uint32 flags; std::string name; }; struct AreaTable; typedef std::set<WorldSession*> SessionSet; class WorldSocket; // Slow for remove in middle, oh well, wont get done much. typedef std::vector<WorldSocket*> QueueSet; typedef set<WorldSession*> SessionSet; class WOWD_SERVER_DECL World : public Singleton<World>, public EventableObject { public: World(); ~World(); WorldSession* FindSession(uint32 id) const; WorldSession* FindSessionByName(std::string Name); void AddSession(WorldSession *s); void RemoveSession(uint32 id); void AddGlobalSession(WorldSession *session); void RemoveGlobalSession(WorldSession *session); void DeleteSession(WorldSession *session); inline uint32 GetSessionCount() const { return m_sessions.size(); } inline uint32 GetNonGmSessionCount(); inline uint32 GetPlayerLimit() const { return m_playerLimit; } void SetPlayerLimit(uint32 limit) { m_playerLimit = limit; } inline bool getAllowMovement() const { return m_allowMovement; } void SetAllowMovement(bool allow) { m_allowMovement = allow; } inline bool getGMTicketStatus() { return m_gmTicketSystem; }; bool toggleGMTicketStatus() { m_gmTicketSystem = !m_gmTicketSystem; return m_gmTicketSystem; }; inline bool getReqGmClient() { return reqGmClient; } inline std::string getGmClientChannel() { return GmClientChannel; } void SetMotd(const char *motd) { m_motd = motd; } inline const char* GetMotd() const { return m_motd.c_str(); } inline time_t GetGameTime() const { return m_gameTime; } void SetInitialWorldSettings(); void SendWorldText(const char *text, WorldSession *self = 0); void SendWorldWideScreenText(const char *text, WorldSession *self = 0); void SendGlobalMessage(WorldPacket *packet, WorldSession *self = 0); void SendZoneMessage(WorldPacket *packet, uint32 zoneid, WorldSession *self = 0); inline void SetStartTime(uint32 val) { m_StartTime = val; } inline uint32 GetUptime(void) { return (uint32)time(NULL) - m_StartTime; } inline uint32 GetStartTime(void) { return m_StartTime; } inline std::string GetUptimeString() { int seconds = (uint32)time(NULL) - m_StartTime; int mins=0; int hours=0; int days=0; if(seconds >= 60) { mins = seconds / 60; if(mins) { seconds -= mins*60; if(mins >= 60) { hours = mins / 60; if(hours) { mins -= hours*60; if(hours >= 24) { days = hours/24; if(days) hours -= days*24; } } } } } char str[200]; sprintf(str, "%d days, %d hours, %d minutes, %d seconds.", days, hours, mins, seconds); return str; } // update the world server every frame void Update(time_t diff); void UpdateAuctions(); void UpdateSessions(uint32 diff); //Global objects(not in any map) void AddGlobalObject(Object *obj); void RemoveGlobalObject(Object *obj); bool HasGlobalObject(Object *obj) { return !(m_globalObjects.find(obj) == m_globalObjects.end()); } inline void setRate(int index,float value) { regen_values[index]=value; } inline float getRate(int index) { return regen_values[index]; } inline uint32 getIntRate(int index) { return int_rates[index]; } inline void setIntRate(int index, uint32 value) { int_rates[index] = value; } // map text emote to spell prices typedef std::map< uint32, uint32> SpellPricesMap; SpellPricesMap mPrices; // area trigger void LoadAreaTriggerInformation(); void AddAreaTrigger(AreaTrigger *pArea); AreaTrigger *GetAreaTrigger(uint32 id); //world map information void LoadMapInformation(); void AddMapInformation(MapInfo *mapinfo); MapInfo *GetMapInformation(uint32 mapid); inline uint32 GetTimeOut(){return TimeOut;} std::string GenerateName(uint32 type = 0); void SetUpdateDistance(float dist) { m_UpdateDistance = (float)pow(dist, 2); } inline float GetUpdateDistance() { return (m_UpdateDistance ? m_UpdateDistance : 79.1f); } static Unit* GetUnit(const uint64 & guid); static Player* GetPlayer(const uint64 & guid); static Creature* GetCreature(const uint64 & guid); static GameObject* GetGameObject(const uint64 & guid); static DynamicObject* GetDynamicObject(const uint64 & guid); uint32 mActiveCellCount; uint32 mInactiveCellCount; uint32 mHalfActiveCellCount; uint32 mTotalCells; uint32 mLoadedCreatures[2]; uint32 mLoadedGameObjects[2]; std::map<uint32, AreaTable*> mAreaIDToTable; std::map<uint32, AreaTable*> mZoneIDToTable; uint32 AddQueuedSocket(WorldSocket* Socket); void RemoveQueuedSocket(WorldSocket* Socket); uint32 GetQueuePos(WorldSocket* Socket); void UpdateQueuedSessions(uint32 diff); Mutex queueMutex; uint32 mQueueUpdateInterval; bool m_useIrc; bool sendRevisionOnJoin; void SaveAllPlayers(); uint32 LevelCap; string MapPath; bool UnloadMapFiles; bool BreathingEnabled; bool SpeedhackProtection; void EventDeleteInstance(uint32 mapid, uint32 instanceid); uint32 mInWorldPlayerCount; uint32 mAcceptedConnections; inline void AddExtendedSession(WorldSession * session) { mExtendedSessions.insert(session); } inline void RemoveExtendedSession(WorldSession * session) { mExtendedSessions.erase(session); } void BroadcastExtendedMessage(WorldSession * self, const char* str, ...); uint32 HordePlayers; uint32 AlliancePlayers; SessionSet gmList; void ShutdownClasses(); protected: // update Stuff, FIXME: use diff time_t _UpdateGameTime() { // Update Server time time_t thisTime = time(NULL); m_gameTime += thisTime - m_lastTick; m_lastTick = thisTime; return m_gameTime; } void FillSpellReplacementsTable(); private: EventableObjectHolder * eventholder; //! Timers typedef HM_NAMESPACE::hash_map<uint32, WorldSession*> SessionMap; SessionMap m_sessions; typedef HM_NAMESPACE::hash_map<uint32, AreaTrigger*> AreaTriggerMap; AreaTriggerMap m_AreaTrigger; public: typedef HM_NAMESPACE::hash_map<uint32, MapInfo*> MapInfoMap; inline MapInfoMap::iterator GetMapInfoBegin() { return m_mapinfo.begin(); } inline MapInfoMap::iterator GetMapInfoEnd() { return m_mapinfo.end(); } protected: MapInfoMap m_mapinfo; SessionSet Sessions; //Global objects(not in any map) typedef std::set<Object*> ObjectSet; ObjectSet m_globalObjects; float regen_values[MAX_RATES]; uint32 int_rates[MAX_INTRATES]; uint32 m_playerLimit; bool m_allowMovement; bool m_gmTicketSystem; std::string m_motd; bool reqGmClient; std::string GmClientChannel; time_t m_gameTime; time_t m_lastTick; uint32 TimeOut; float m_UpdateDistance; uint32 m_StartTime; uint32 m_queueUpdateTimer; QueueSet mQueuedSessions; SessionSet mExtendedSessions; }; #define sWorld World::getSingleton() #endif
[ [ [ 1, 449 ] ] ]
1049b3bee7089d105aa77b4fa68c20266c04c10f
6a1a184ceb7be1f73c490fcbaf8fba7a64cab1ff
/Source/Fluidic/FluidException.h
b1cfb06d5c0279e9890b72a335f7892d7fa1f0ec
[ "MIT" ]
permissive
alexsaen/fluidic
c8aa913ce03e8d3d9bc8091a31aa96a7d1e5b4ad
bf7eb0f3e9ca4e15f53623020c7f0313315f4e49
refs/heads/master
2020-12-24T15:14:17.261742
2010-04-06T13:10:54
2010-04-06T13:10:54
32,979,664
1
0
null
null
null
null
UTF-8
C++
false
false
1,554
h
/* Copyright (c) 2010 Steven Leigh 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. */ #pragma once #include <string> namespace Fluidic { /** * Simple exception class to handle things thrown by this library */ class FluidException { public: FluidException(); FluidException(const std::string &msg) : mMessage(msg) {} FluidException(const FluidException &other) : mMessage(other.mMessage){}; ~FluidException(){}; const std::string &GetMessage() const { return mMessage; } protected: std::string mMessage; }; }
[ "xwipeoutx@6c3c8482-2914-11df-ad47-1d73243ccc9f" ]
[ [ [ 1, 44 ] ] ]
85c0a06c86c4810144266c3116944fb5e2971378
4711cae65505af5a33baf4f4652e757bfbf54b78
/RSEngine/RSEngine/Src/RSOgreHandler.cpp
5d34007ec95ef03c6459b77f3e8ecc305710e669
[]
no_license
ashishlijhara/RSEngine
19ad68844df952abe8682777d3281dbf46ff913c
cac48b492597d119fc9c7364088c1930314a923c
refs/heads/master
2016-09-10T10:12:49.781187
2011-05-31T12:34:49
2011-05-31T12:34:49
1,822,577
0
0
null
null
null
null
UTF-8
C++
false
false
4,495
cpp
#include "RSOgreHandler.h" #include "CheckGameApp.h" template<> RSE::RSOgreHandler* Ogre::Singleton<RSE::RSOgreHandler>::ms_Singleton = 0; namespace RSE{ RSOgreHandler* RSOgreHandler::getSingletonPtr(void) { return ms_Singleton; } RSOgreHandler& RSOgreHandler::getSingleton(void) { assert( ms_Singleton ); return ( *ms_Singleton ); } RSOgreHandler::RSOgreHandler():m_bPaused(false){ } RSOgreHandler::~RSOgreHandler(){ } const FResult RSOgreHandler::VInitOgre(const bool &bShowConfigDialog, String sWindowTitle){ FResult returnResult; memset(&returnResult, 0,sizeof(FResult)); InitOgreRoot(); if(bShowConfigDialog){ if(!m_pRSRoot->showConfigDialog()) { SetError(&returnResult, "Error Displaying Ogre Config Dialog"); return returnResult; } } InitRenderWindow(sWindowTitle); m_pRSViewport = m_pRSRenderWindow->addViewport(0); m_pRSViewport->setBackgroundColour(ColourValue(0.0f,0.0f,0.0f)); m_pRSViewport->setCamera(0); LoadOgreResources(); m_pBaseGameApp = dynamic_cast<IBaseGameApp*>(new Check::CheckGameApp()); m_pBaseGameApp->VInit(); m_pRSRenderWindow->setActive(true); return returnResult; } void RSOgreHandler::InitOgreRoot(){ m_pRSRoot = new Root(); } void RSOgreHandler::InitRenderWindow(String title){ m_pRSRenderWindow = m_pRSRoot->initialise(true,title); } void RSOgreHandler::LoadOgreResources(const int &iDefaultNumMipMaps){ #pragma region Load The Resources String sSecName, sTypeName, sArchName; ConfigFile cf; cf.load("resources.cfg"); ConfigFile::SectionIterator seci = cf.getSectionIterator(); while(seci.hasMoreElements()){ sSecName = seci.peekNextKey(); ConfigFile::SettingsMultiMap *settings = seci.getNext(); ConfigFile::SettingsMultiMap::iterator i; for(i = settings->begin(); i != settings->end();++i){ sTypeName = i->first; sArchName = i->second; ResourceGroupManager::getSingleton().addResourceLocation(sArchName, sTypeName, sSecName); } } #pragma endregion #pragma region Cache/Init The Resources TextureManager::getSingleton().setDefaultNumMipmaps(5); ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); #pragma endregion //m_pRSRoot->startRendering(); } const FResult RSOgreHandler::VUpdateOgre(const float &delTime){ FResult returnResult; memset(&returnResult,0,sizeof(FResult)); assert(m_pBaseGameApp); WindowEventUtilities::messagePump(); m_pRSRoot->renderOneFrame(); returnResult = (m_bPaused)?(m_pBaseGameApp->VRenderPaused()):(m_pBaseGameApp->VRender()); returnResult = m_pBaseGameApp->VUpdate(delTime); return returnResult; } const FResult RSOgreHandler::VPauseOgre(const bool &paused){ FResult returnResult; memset(&returnResult,0,sizeof(FResult)); m_bPaused = paused; m_pBaseGameApp->VSetPaused(paused); return returnResult; } const FResult RSOgreHandler::VEndOgre(){ FResult returnResult; memset(&returnResult,0,sizeof(FResult)); return returnResult; } const FResult RSOgreHandler::VCleanupOgre(){ FResult returnResult; memset(&returnResult,0,sizeof(FResult)); //Don't change the order m_pBaseGameApp->VCleanup(); if(!Release(m_pBaseGameApp)){ assert(m_pBaseGameApp); SetError(&returnResult, "Unable to release Base Game App Object"); } if(!Release(m_pRSRoot)) { assert(m_pRSRoot); SetError(&returnResult, "Unable to release root"); } return returnResult; } const void RSOgreHandler::VShowConfigDialog(const bool& value){ m_bPaused = value; } const FResult RSOgreHandler::VSetBaseGameApp(IBaseGameApp *app){ FResult returnResult; memset(&returnResult,0,sizeof(FResult)); assert(app); m_pBaseGameApp = app; m_pBaseGameApp->VInit(); return returnResult; } const IBaseGameApp* RSOgreHandler::VGetBaseGameApp() const{ return m_pBaseGameApp; } Root*const RSOgreHandler::GetRSRoot() const{ return m_pRSRoot; } RenderWindow* RSOgreHandler::GetRenderWindow() const{ return m_pRSRenderWindow; } void RSOgreHandler::SetRSRoot(Root* pRoot){ m_pRSRoot = pRoot; } Viewport* RSOgreHandler::GetViewport() const{ assert(m_pRSViewport); return m_pRSViewport; } void RSOgreHandler::SetViewPort(Viewport *pViewport){ assert(pViewport); m_pRSViewport = pViewport; } }
[ [ [ 1, 191 ] ] ]
d1dfeecbbebe647ad940df009636482761df627e
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/spirit/example/lex/example5.cpp
317505325ccfa84af483a04a464677fce662ad8d
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,976
cpp
// Copyright (c) 2001-2009 Hartmut Kaiser // Copyright (c) 2001-2007 Joel de Guzman // // 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) // This example shows how to create a simple lexer recognizing a couple of // different tokens aimed at a simple language and how to use this lexer with // a grammar. It shows how to associate values to tokens and how to access the // token values from inside the grammar. // // Additionally, this example demonstrates, how to define a token set usable // as the skip parser during parsing, allowing to define several tokens to be // ignored. // // The main purpose of this example is to show, how inheritance can be used to // overload parts of a base grammar and add token definitions to a base lexer. // // Further, it shows how you can use the 'omitted' attribute type specifier // for token definitions to force the token to have no attribute (expose an // unused attribute). // // This example recognizes a very simple programming language having // assignment statements and if and while control structures. Look at the file // example5.input for an example. #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/lex_lexer_lexertl.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <iostream> #include <fstream> #include <string> #include "example.hpp" using namespace boost::spirit; using namespace boost::spirit::qi; using namespace boost::spirit::lex; using namespace boost::spirit::arg_names; using boost::phoenix::val; /////////////////////////////////////////////////////////////////////////////// // Token definition base, defines all tokens for the base grammar below /////////////////////////////////////////////////////////////////////////////// template <typename Lexer> struct example5_base_tokens : lexer_def<Lexer> { typedef typename Lexer::token_set token_set; template <typename Self> void def (Self& self) { // define the tokens to match identifier = "[a-zA-Z_][a-zA-Z0-9_]*"; constant = "[0-9]+"; if_ = "if"; while_ = "while"; // define the whitespace to ignore (spaces, tabs, newlines and C-style // comments) white_space = token_def<>("[ \\t\\n]+") | "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/" ; // associate the tokens and the token set with the lexer self += token_def<>('(') | ')' | '{' | '}' | '=' | ';' | constant; self += if_ | while_ | identifier; self("WS") = white_space; } // these tokens have no value token_def<omitted> if_, while_; // The following two tokens have an associated value type, identifier // carries a string (the identifier name) and constant carries the matched // integer value. // // Note: any explicitly token value type specified during a token_def<> // declaration needs to be listed during token type definition as // well (see the typedef for the token_type below). // // The conversion of the matched input to an instance of this type occurs // once (on first access), which makes token values as efficient as // possible. Moreover, token instances are constructed once by the lexer // library. From this point on tokens are passed by reference only, // avoiding tokens being copied around. token_def<std::string> identifier; token_def<unsigned int> constant; // token set to be used as the skip parser token_set white_space; }; /////////////////////////////////////////////////////////////////////////////// // Grammar definition base, defines a basic language /////////////////////////////////////////////////////////////////////////////// template <typename Iterator, typename Lexer> struct example5_base_grammar : grammar<Iterator, in_state_skipper<typename Lexer::token_set> > { template <typename TokenDef> example5_base_grammar(TokenDef const& tok) : example5_base_grammar::base_type(program) { program = +block ; block = '{' >> *statement >> '}' ; statement = assignment | if_stmt | while_stmt ; assignment = (tok.identifier >> '=' >> expression >> ';') [ std::cout << val("assignment statement to: ") << _1 << "\n" ] ; if_stmt = (tok.if_ >> '(' >> expression >> ')' >> block) [ std::cout << val("if expression: ") << _1 << "\n" ] ; while_stmt = (tok.while_ >> '(' >> expression >> ')' >> block) [ std::cout << val("while expression: ") << _1 << "\n" ] ; // since expression has a variant return type accommodating for // std::string and unsigned integer, both possible values may be // returned to the calling rule expression = tok.identifier [ _val = _1 ] | tok.constant [ _val = _1 ] ; } typedef grammar<Iterator, in_state_skipper<typename Lexer::token_set> > base_type; typedef typename base_type::skipper_type skipper_type; rule<Iterator, skipper_type> program, block, statement; rule<Iterator, skipper_type> assignment, if_stmt; rule<Iterator, skipper_type> while_stmt; // the expression is the only rule having a return value typedef boost::variant<unsigned int, std::string> expression_type; rule<Iterator, expression_type(), skipper_type> expression; }; /////////////////////////////////////////////////////////////////////////////// // Token definition for derived lexer, defines additional tokens /////////////////////////////////////////////////////////////////////////////// template <typename Lexer> struct example5_tokens : example5_base_tokens<Lexer> { typedef typename Lexer::token_set token_set; template <typename Self> void def (Self& self) { // define the additional token to match else_ = "else"; // associate the new token with the lexer, note we add 'else' before // anything else to add it to the token set before the identifier // token, otherwise "else" would be matched as an identifier self = else_; // call the base class definition function example5_base_tokens<Lexer>::def(self); } // this token has no value token_def<omitted> else_; }; /////////////////////////////////////////////////////////////////////////////// // Derived grammar definition, defines a language extension /////////////////////////////////////////////////////////////////////////////// template <typename Iterator, typename Lexer> struct example5_grammar : example5_base_grammar<Iterator, Lexer> { template <typename TokenDef> example5_grammar(TokenDef const& tok) : example5_base_grammar<Iterator, Lexer>(tok) { // we alter the if_stmt only this->if_stmt = this->if_stmt.copy() >> -(tok.else_ >> this->block) ; } }; /////////////////////////////////////////////////////////////////////////////// int main() { // iterator type used to expose the underlying input stream typedef std::string::iterator base_iterator_type; // This is the lexer token type to use. The second template parameter lists // all attribute types used for token_def's during token definition (see // calculator_tokens<> above). Here we use the predefined lexertl token // type, but any compatible token type may be used instead. // // If you don't list any token value types in the following declaration // (or just use the default token type: lexertl_token<base_iterator_type>) // it will compile and work just fine, just a bit less efficient. This is // because the token value will be generated from the matched input // sequence every time it is requested. But as soon as you specify at // least one token value type you'll have to list all value types used // for token_def<> declarations in the token definition class above, // otherwise compilation errors will occur. typedef lexertl_token< base_iterator_type, boost::mpl::vector<unsigned int, std::string> > token_type; // Here we use the lexertl based lexer engine. typedef lexertl_lexer<token_type> lexer_type; // This is the token definition type (derived from the given lexer type). typedef example5_tokens<lexer_type> example5_tokens; // this is the iterator type exposed by the lexer typedef lexer<example5_tokens>::iterator_type iterator_type; // this is the type of the grammar to parse typedef example5_grammar<iterator_type, lexer_type> example5_grammar; // now we use the types defined above to create the lexer and grammar // object instances needed to invoke the parsing process example5_tokens tokens; // Our token definition example5_grammar calc(tokens); // Our grammar definition lexer<example5_tokens> lex(tokens); // Our lexer std::string str (read_from_file("example5.input")); // At this point we generate the iterator pair used to expose the // tokenized input stream. std::string::iterator it = str.begin(); iterator_type iter = lex.begin(it, str.end()); iterator_type end = lex.end(); // Parsing is done based on the the token stream, not the character // stream read from the input. // Note, how we use the token_set defined above as the skip parser. It must // be explicitly wrapped inside a state directive, switching the lexer // state for the duration of skipping whitespace. std::string ws("WS"); bool r = phrase_parse(iter, end, calc, in_state(ws)[tokens.white_space]); if (r && iter == end) { std::cout << "-------------------------\n"; std::cout << "Parsing succeeded\n"; std::cout << "-------------------------\n"; } else { std::cout << "-------------------------\n"; std::cout << "Parsing failed\n"; std::cout << "-------------------------\n"; } std::cout << "Bye... :-) \n\n"; return 0; }
[ "metrix@Blended.(none)" ]
[ [ [ 1, 284 ] ] ]
486672ded5c8ef262466a175198de8420abb174a
00fdb9c8335382401ee0a8c06ad6ebdcaa136b40
/ARM9/source/procbody/proc_DPGPlay/proc_DPGPlay.cpp
df10e7b8b4eefab37249fff4bca054b79425dd6d
[]
no_license
Mbmax/ismart-kernel
d82633ba0864f9f697c3faa4ebc093a51b8463b2
f80d8d7156897d019eb4e16ef9cec8a431d15ed3
refs/heads/master
2016-09-06T13:28:25.260481
2011-03-29T10:31:04
2011-03-29T10:31:04
35,029,299
1
2
null
null
null
null
UTF-8
C++
false
false
33,606
cpp
#include <nds.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "_console.h" #include "_consolewritelog.h" #include "maindef.h" #include "memtool.h" #include "_const.h" #include "../../ipc6.h" #include "arm9tcm.h" #include "lang.h" #include "glib/glib.h" #include "fat2.h" #include "shell.h" #include "splash.h" #include "resume.h" #include "procstate.h" #include "strtool.h" #include "unicode.h" #include "rect.h" #include "skin.h" #include "component.h" #include "sndeff.h" #include "strpcm.h" #include "cfont.h" static bool ScreenRedrawFlag; #define SeekBarHeight (48) static u32 SeekBarRedrawCount; static bool SeekBarExecuteRedraw; static TRect VolumeBarRect; static CglCanvas *pCompBG; static CFont *pTimeFont; static s32 BrightLevel; static u32 PanelClosePowerOffTimeOut; static bool ToCustomMode; // ----------------------------- #include "plug_dpg.h" static FAT_FILE *pDPGfh1,*pDPGfh2; static void ProcDPG(void) { if(DPG_RequestSyncStart==true){ _consolePrint("DPG_RequestSyncStart\n"); DPG_RequestSyncStart=false; if(ProcState.DPG.EnabledFastStart==false){ _consolePrint("Load disk cache.\n"); extern void DiskCache_LoadAllBuffer(void); DiskCache_LoadAllBuffer(); } DPGAudioStream_SyncSamples=0; DPGAudioStream_PregapSamples=0; u32 PreDecodeFramesCount; if(ProcState.DPG.EnabledFastStart==false){ PreDecodeFramesCount=FrameCache_GetReadFramesCount(); if(DPG_GetCurrentFrameCount()!=0) PreDecodeFramesCount/=2; }else{ PreDecodeFramesCount=4; } _consolePrintf("Pre-decode %dframes.\n",PreDecodeFramesCount); for(u32 idx=0;idx<PreDecodeFramesCount;idx++){ _consolePrintf("%d,",DPG_GetCurrentFrameCount()); UpdateDPG_Video(); } _consolePrintf("rendered.\n"); VBlank_AutoFlip_Disabled(); switch(DPG_GetDPGAudioFormat()){ case DPGAF_MP2: { IPC6->MP2PauseFlag=false; strpcmStart(false,DPG_GetSampleRate(),8,0,SPF_MP2); } break; } DPGAudioStream_PregapSamples=DPG_GetSampleRate()/60; // pre decode per frame _consolePrint("wait for flash.\n"); while(IPC6->IR_flash==true){ swiWaitForIRQ(); UpdateDPG_Audio(); } _consolePrint("flashed.\n"); REG_IME=0; VBlankPassedCount=0; REG_IME=1; PrintFreeMem(); SeekBarRedrawCount=0; SeekBarExecuteRedraw=true; } if(UpdateDPG_Video()==false){ _consolePrintf("Set strpcmRequestStop.\n"); strpcmRequestStop=true; } } void DPGOpen(const UnicodeChar *pFilenameUnicode) { pDPGfh1=Shell_FAT_fopen_Split(RelationalFilePathUnicode,pFilenameUnicode); pDPGfh2=Shell_FAT_fopen_Split(RelationalFilePathUnicode,pFilenameUnicode); if((pDPGfh1==NULL)||(pDPGfh2==NULL)){ _consolePrintf("Fatal error: can not open file.\n"); ShowLogHalt(); } if(StartDPG(pDPGfh1,pDPGfh2)==false){ _consolePrintf("Fatal error: can not open DPG format.\n"); ShowLogHalt(); } IPC6->MP2PauseFlag=false; DPG_RequestSyncStart=true; } void DPGClose(void) { _consolePrintf("satrpcmStop();\n"); strpcmStop(); _consolePrintf("FreeDPG();\n"); FreeDPG(); if(pDPGfh1!=NULL){ FAT2_fclose(pDPGfh1); pDPGfh1=NULL; } if(pDPGfh2!=NULL){ FAT2_fclose(pDPGfh2); pDPGfh2=NULL; } IPC6->MP2PauseFlag=false; _consolePrintf("DPG closed.\n"); PrintFreeMem(); } // ----------------------------- #include "proc_DPGPlay_BGM.h" // ----------------------------- typedef struct { bool Visible; u32 TimeoutCount; CglTGF *pTGF; } TModeLabel; static TModeLabel ModeLabel; static void ModeLabel_Init(void) { TModeLabel *pml=&ModeLabel; pml->Visible=false; pml->TimeoutCount=0; pml->pTGF=NULL; } static void ModeLabel_Draw(CglCanvas *pCanvas) { TModeLabel *pml=&ModeLabel; if(pml->Visible==false) return; u32 x=12,y=8; if(pml->pTGF!=NULL) pml->pTGF->BitBlt(pCanvas,x,y); } static void ModeLabel_Start(void) { TProcState_DPG *pdpg=&ProcState.DPG; EMoviePlayerSkinAlpha EMPSA; switch(pdpg->PlayMode){ case EDPM_Repeat: EMPSA=EMPSA_modelbl_repeat; break; case EDPM_AllRep: EMPSA=EMPSA_modelbl_allrep; break; case EDPM_Random: EMPSA=EMPSA_modelbl_random; break; default: return; break; } TModeLabel *pml=&ModeLabel; pml->Visible=true; pml->TimeoutCount=60*2; pml->pTGF=MoviePlayerAlpha_GetSkin(EMPSA); } static void ModeLabel_Vsync(u32 VsyncCount) { TModeLabel *pml=&ModeLabel; if(pml->TimeoutCount==0) return; if(pml->TimeoutCount<VsyncCount){ pml->TimeoutCount=0; }else{ pml->TimeoutCount-=VsyncCount; } if(pml->TimeoutCount==0){ ModeLabel_Init(); ScreenRedrawFlag=true; } } // ----------------------------- static void Exec_Next(bool RelationalPlayMode) { if(RelationalPlayMode==false){ BGM_Next(); return; } switch(ProcState.DPG.PlayMode){ case EDPM_Repeat: { BGM_Repeat(); } break; case EDPM_AllRep: { BGM_Next(); } break; case EDPM_Random: { BGM_NextRandom(); } break; } } // ----------------------------- enum ECompLabels {ECLSCount}; #define CompLabelsCount (ECLSCount) static TComponentLabel CompLabels[CompLabelsCount]; enum ECompChecks {ECCSCount}; #define CompChecksCount (ECCSCount) static TComponentCheck CompChecks[CompChecksCount]; enum ECompButtons {ECBS_ModeBtn,ECBS_PlayBtn,ECBS_StopBtn,ECBS_PrevBtn,ECBS_NextBtn,ECBSCount}; #define CompButtonsCount (ECBSCount) static TComponentButton CompButtons[CompButtonsCount]; static void Setting_Redraw(void) { pCompBG->SetCglFont(pCglFontDefault); { CglCanvas *pcan=pCompBG; CglB15 *pbg=MoviePlayer_GetSkin(EMPS_bg); pbg->pCanvas->BitBltFullBeta(pcan); char idxstr[16]; snprintf(idxstr,32,"%d / %d",1+BGMListIndex,BGMListCount); u32 idxstrw=pcan->GetTextWidthA(idxstr)+8; u32 x=16+2,y=ScreenHeight-SeekBarHeight-28+2; x++; y++; pcan->SetFontTextColor(ColorTable.Video.FilenameShadow); pcan->TextOutA(x,y+(12*0),idxstr); pcan->TextOutW(x+idxstrw,y+(12*0),RelationalFilePathUnicode); pcan->TextOutW(x,y+(12*1),BGM_GetCurrentFilename()); x--; y--; pcan->SetFontTextColor(ColorTable.Video.FilenameText); pcan->TextOutA(x,y+(12*0),idxstr); pcan->TextOutW(x+idxstrw,y+(12*0),RelationalFilePathUnicode); pcan->TextOutW(x,y+(12*1),BGM_GetCurrentFilename()); CglTGF *ptgf=MoviePlayerAlpha_GetSkin(EMPSA_backlight); ptgf->BitBlt(pcan,ScreenWidth-ptgf->GetWidth(),ScreenHeight-SeekBarHeight-ptgf->GetHeight()); } { CglCanvas *pcan=pCompBG; CglTGF *pon=MoviePlayerAlpha_GetSkin(EMPSA_volbar_on); CglTGF *poff=MoviePlayerAlpha_GetSkin(EMPSA_volbar_off); TRect r=VolumeBarRect; r.y-=SeekBarHeight; s32 vol=strpcmGetVolume64(); s32 limy=(vol*r.h)/strpcmVolumeMax; limy=r.h-limy; if(limy<0) limy=0; if(r.h<limy) limy=r.h; poff->BitBltLimitY(pcan,r.x,r.y,limy,0); pon->BitBltLimitY(pcan,r.x,r.y+limy,r.h-limy,limy); u32 x=r.x+r.w+8; u32 y=r.y+r.h-24; u16 col1=ColorTable.Video.VolumeShadow; u16 col2=ColorTable.Video.VolumeText; char str[16]; if(vol==0){ snprintf(str,16,Lang_GetUTF8("DV_VolumeMute")); }else{ if(vol<strpcmVolumeMax){ snprintf(str,16,Lang_GetUTF8("DV_VolumeValue"),vol*100/64); }else{ col1=ColorTable.Video.VolumeMaxShadow; col2=ColorTable.Video.VolumeMaxText; snprintf(str,16,Lang_GetUTF8("DV_VolumeMax")); } } const char *plblmsg=Lang_GetUTF8("DV_VolumeLabel"); u32 w0=pcan->GetTextWidthA(plblmsg); u32 w1=pcan->GetTextWidthA(str); x++; y++; pcan->SetFontTextColor(col1); pcan->TextOutA(x-w0,y+(12*0),plblmsg); pcan->TextOutA(x-w1,y+(12*1),str); x--; y--; pcan->SetFontTextColor(col2); pcan->TextOutA(x-w0,y+(12*0),plblmsg); pcan->TextOutA(x-w1,y+(12*1),str); } { EMoviePlayerSkinAlpha Icon; TProcState_DPG *pdpg=&ProcState.DPG; switch(pdpg->PlayMode){ case EDPM_Repeat: Icon=EMPSA_mode_repeat; break; case EDPM_AllRep: Icon=EMPSA_mode_allrep; break; case EDPM_Random: Icon=EMPSA_mode_random; break; default: { _consolePrintf("Unknown DPG play mode. (%d)\n",pdpg->PlayMode); ShowLogHalt(); } break; } CompButtons[ECBS_ModeBtn].pIcon=MoviePlayerAlpha_GetSkin(Icon); } { TComponentButton *pcb=&CompButtons[ECBS_PlayBtn]; if(IPC6->MP2PauseFlag==false){ pcb->pIcon=MoviePlayerAlpha_GetSkin(EMPSA_pause); }else{ pcb->pIcon=MoviePlayerAlpha_GetSkin(EMPSA_play); } } for(u32 idx=0;idx<CompLabelsCount;idx++){ ComponentLabel_Draw(&CompLabels[idx]); } for(u32 idx=0;idx<CompChecksCount;idx++){ ComponentCheck_Draw(&CompChecks[idx]); } for(u32 idx=0;idx<CompButtonsCount;idx++){ ComponentButton_Draw(&CompButtons[idx]); } ModeLabel_Draw(pCompBG); pCompBG->BitBlt(pScreenSub->pCanvas,0,SeekBarHeight,pCompBG->GetWidth(),pCompBG->GetHeight(),0,0,false); } static void CB_ModeBtn_Click(void *pComponentButton) { TProcState_DPG *pdpg=&ProcState.DPG; switch(pdpg->PlayMode){ case EDPM_Repeat: pdpg->PlayMode=EDPM_AllRep; break; case EDPM_AllRep: pdpg->PlayMode=EDPM_Random; break; case EDPM_Random: pdpg->PlayMode=EDPM_Repeat; break; default: pdpg->PlayMode=EDPM_Repeat; break; } ProcState_RequestSave=true; ModeLabel_Start(); } static void CB_PlayBtn_Click(void *pComponentButton) { if(IPC6->MP2PauseFlag==true){ IPC6->MP2PauseFlag=false; }else{ cwl(); IPC6->MP2PauseFlag=true; Sound_Start(WAVFN_Click); } } static void CB_PrevBtn_Click(void *pComponentButton) { Sound_Start(WAVFN_Click); BGM_Prev(); } static void CB_NextBtn_Click(void *pComponentButton) { Sound_Start(WAVFN_Click); Exec_Next(false); } static void CB_StopBtn_Click(void *pComponentButton) { Sound_Start(WAVFN_Click); SetNextProc(ENP_FileList,EPFE_CrossFade); } static void CompsInit(void) { CglCanvas *pcan=pCompBG; for(u32 idx=0;idx<CompLabelsCount;idx++){ ComponentLabel_Init(&CompLabels[idx],pcan); } for(u32 idx=0;idx<CompChecksCount;idx++){ ComponentCheck_Init(&CompChecks[idx],pcan); } for(u32 idx=0;idx<CompButtonsCount;idx++){ ComponentButton_Init(&CompButtons[idx],pcan); } s32 x,y,w,h; x=8; y=0; w=64; h=64; { TComponentButton *pcb=&CompButtons[ECBS_PrevBtn]; pcb->CallBack_Click=CB_PrevBtn_Click; pcb->pIcon=MoviePlayerAlpha_GetSkin(EMPSA_prev); pcb->pMsgUTF8=""; pcb->Rect=CreateRect(x,y,w,h); pcb->DrawFrame=false; } x+=w; { TComponentButton *pcb=&CompButtons[ECBS_PlayBtn]; pcb->CallBack_Click=CB_PlayBtn_Click; pcb->pIcon=MoviePlayerAlpha_GetSkin(EMPSA_play); pcb->pMsgUTF8=""; pcb->Rect=CreateRect(x,y,w,h); pcb->DrawFrame=false; } x+=w; { TComponentButton *pcb=&CompButtons[ECBS_NextBtn]; pcb->CallBack_Click=CB_NextBtn_Click; pcb->pIcon=MoviePlayerAlpha_GetSkin(EMPSA_next); pcb->pMsgUTF8=""; pcb->Rect=CreateRect(x,y,w,h); pcb->DrawFrame=false; } x+=w; y+=h; w=48; h=48; x=8+64+((64-48)/2)-w; { TComponentButton *pcb=&CompButtons[ECBS_ModeBtn]; pcb->CallBack_Click=CB_ModeBtn_Click; pcb->pIcon=MoviePlayerAlpha_GetSkin(EMPSA_mode_allrep); pcb->pMsgUTF8=""; pcb->Rect=CreateRect(x,y,w,h); pcb->DrawFrame=false; } x+=w; { TComponentButton *pcb=&CompButtons[ECBS_StopBtn]; pcb->CallBack_Click=CB_StopBtn_Click; pcb->pIcon=MoviePlayerAlpha_GetSkin(EMPSA_stop); pcb->pMsgUTF8=""; pcb->Rect=CreateRect(x,y,w,h); pcb->DrawFrame=false; } x+=w; } // ----------------------------- // ----------------------------- static bool seeking; static bool KeySeeking; static void CB_KeyPress(u32 VsyncCount,u32 Keys) { if((Keys&(KEY_L|KEY_R))!=0){ if((Keys&KEY_LEFT)!=0){ CB_PrevBtn_Click(NULL); ScreenRedrawFlag=true; } if((Keys&KEY_RIGHT)!=0){ Sound_Start(WAVFN_Click); Exec_Next(false); ScreenRedrawFlag=true; } if((Keys&KEY_UP)!=0){ CB_PlayBtn_Click(NULL); ScreenRedrawFlag=true; } if((Keys&KEY_DOWN)!=0){ CB_ModeBtn_Click(NULL); ScreenRedrawFlag=true; } if((Keys&(KEY_X|KEY_Y))!=0){ if((Keys&KEY_X)!=0) ChangeNextBacklightLevel(); if((Keys&KEY_Y)!=0) ChangePrevBacklightLevel(); } return; } if((Keys&(KEY_START|KEY_SELECT))!=0){ Sound_Start(WAVFN_Click); ToCustomMode=true; SetNextProc(ENP_DPGCustom,EPFE_None); } if((Keys&KEY_B)!=0){ Sound_Start(WAVFN_Click); SetNextProc(ENP_FileList,EPFE_CrossFade); } if((Keys&KEY_A)!=0){ CB_PlayBtn_Click(NULL); ScreenRedrawFlag=true; } if((Keys&(KEY_Y|KEY_X))!=0){ s32 Volume=ProcState.System.Volume64; if(Keys==(KEY_Y|KEY_X)){ Volume=64; }else{ if((Keys&KEY_Y)!=0) Volume-=2; if((Keys&KEY_X)!=0) Volume+=2; if(Volume<0) Volume=0; if(Volume>strpcmVolumeMax) Volume=strpcmVolumeMax; } Volume&=~1; strpcmSetVolume64(Volume); ProcState.System.Volume64=Volume; ProcState_RequestSave=true; // if(Volume==64) Sound_Start(WAVFN_Click); ScreenRedrawFlag=true; } if((Keys&(KEY_UP|KEY_DOWN|KEY_LEFT|KEY_RIGHT))!=0){ s32 v=0; if((Keys&KEY_UP)!=0) v=-30; if((Keys&KEY_DOWN)!=0) v=+30; if((Keys&KEY_LEFT)!=0) v=-5; if((Keys&KEY_RIGHT)!=0) v=+5; s32 curf,tagf; curf=(s32)DPG_GetCurrentFrameCount(); tagf=curf+((s32)DPG_GetFPS()*v/0x100); if(tagf<0) tagf=0; _consolePrintf("Move frame %d to %d.\n",curf,tagf); if((s32)DPG_GetTotalFrameCount()<=tagf){ cwl(); strpcmRequestStop=true; }else{ cwl(); if(KeySeeking==false){ KeySeeking=true; strpcmStop(); seeking=true; } DPG_SetFrameCount((u32)tagf); swiWaitForVBlank(); DPG_SliceOneFrame(pScreenMain->pBackCanvas->GetVRAMBuf(),pScreenMain->pViewCanvas->GetVRAMBuf()); VBlank_AutoFlip_Enabled(); SeekBarRedrawCount=0; SeekBarExecuteRedraw=true; } ScreenRedrawFlag=true; } } static void CB_KeySameLRDown(void) { CB_PlayBtn_Click(NULL); ScreenRedrawFlag=true; } enum EMouseMode {EMM_Idle,EMM_Comp,EMM_Seek,EMM_Volume,EMM_Title}; static EMouseMode MouseMode; static TComponentButton *pPressingButton; static bool DrawInfoFlag; static u32 DrawInfoDiffCount; static void CB_Mouse_ins_SetVolume(s32 x,s32 y) { s32 Volume=(strpcmVolumeMax*(y-VolumeBarRect.y))/VolumeBarRect.h; Volume=strpcmVolumeMax-Volume; if(Volume<0) Volume=0; if(strpcmVolumeMax<Volume) Volume=strpcmVolumeMax; if(((64-4)<Volume)&&(Volume<=(64+4))) Volume=64; strpcmSetVolume64(Volume); ProcState.System.Volume64=Volume; ProcState_RequestSave=true; ScreenRedrawFlag=true; } static s32 CB_Mouse_ins_SeekBarGetFrameNum(s32 x) { s32 curf=(s32)DPG_GetCurrentFrameCount(); s32 ttlf=(s32)DPG_GetTotalFrameCount(); s32 tagf=(ttlf*x)/ScreenWidth; _consolePrintf("Move frame %d to %d.\n",curf,tagf); if(tagf<0) tagf=0; if(ttlf<=tagf) tagf=-1; return(tagf); } static void CB_MouseDown(s32 x,s32 y) { MouseMode=EMM_Idle; if(ProcState.DPG.BacklightFlag==false){ ProcState.DPG.BacklightFlag=true; ProcState_RequestSave=true; ScreenRedrawFlag=true; SeekBarRedrawCount=0; SeekBarExecuteRedraw=true; return; } if(y<SeekBarHeight){ s32 tagf=CB_Mouse_ins_SeekBarGetFrameNum(x); if(tagf==-1){ strpcmRequestStop=true; MouseMode=EMM_Idle; }else{ cwl(); strpcmStop(); seeking=true; DPG_SetFrameCount((u32)tagf); swiWaitForVBlank(); DPG_SliceOneFrame(pScreenMain->pBackCanvas->GetVRAMBuf(),pScreenMain->pViewCanvas->GetVRAMBuf()); VBlank_AutoFlip_Enabled(); } SeekBarRedrawCount=0; SeekBarExecuteRedraw=true; MouseMode=EMM_Seek; return; } if(isInsideRect(VolumeBarRect,x,y)==true){ CB_Mouse_ins_SetVolume(x,y); MouseMode=EMM_Volume; return; } if((ScreenHeight-28)<=y){ if(x<24){ pCompBG->SetCglFont(pCglFontDefault); pCompBG->SetFontTextColor(ColorTable.Video.InfoText); pCompBG->FillFull(ColorTable.Video.InfoBG); DPG_DrawInfoDiff(pCompBG); DPG_DrawInfo(pCompBG); pCompBG->BitBlt(pScreenSub->pCanvas,0,SeekBarHeight,pCompBG->GetWidth(),pCompBG->GetHeight(),0,0,false); DrawInfoFlag=true; DrawInfoDiffCount=1; }else{ CglTGF *ptgf=MoviePlayerAlpha_GetSkin(EMPSA_backlight); u32 tgfwidth=ptgf->GetWidth(); if(x<(ScreenWidth-tgfwidth)){ ProcState.DPG.BacklightFlag=false; ProcState_RequestSave=true; }else{ ChangeNextBacklightLevel(); } } MouseMode=EMM_Title; return; } y-=SeekBarHeight; for(u32 idx=0;idx<CompButtonsCount;idx++){ TComponentButton *pcb=&CompButtons[idx]; if(ComponentButton_GetIndexFromPos(pcb,x,y)!=-1){ pPressingButton=pcb; pcb->Pressing=true; ComponentButton_Draw(pcb); Setting_Redraw(); MouseMode=EMM_Comp; return; } } } static void CB_MouseMove(s32 x,s32 y) { if(MouseMode==EMM_Comp) y-=SeekBarHeight; switch(MouseMode){ case EMM_Idle: { } break; case EMM_Comp: { } break; case EMM_Seek: { s32 tagf=CB_Mouse_ins_SeekBarGetFrameNum(x); if(tagf==-1){ strpcmRequestStop=true; VBlank_AutoFlip_Disabled(); seeking=false; MouseMode=EMM_Idle; }else{ cwl(); DPG_SetFrameCount((u32)tagf); swiWaitForVBlank(); DPG_SliceOneFrame(pScreenMain->pBackCanvas->GetVRAMBuf(),pScreenMain->pViewCanvas->GetVRAMBuf()); } SeekBarRedrawCount=0; SeekBarExecuteRedraw=true; } break; case EMM_Volume: { CB_Mouse_ins_SetVolume(x,y); } break; case EMM_Title: { } break; } } static void CB_MouseUp(s32 x,s32 y) { if(MouseMode!=EMM_Seek) y-=SeekBarHeight; EMouseMode _MouseMode=MouseMode; MouseMode=EMM_Idle; switch(_MouseMode){ case EMM_Idle: { } break; case EMM_Comp: { if(pPressingButton!=NULL){ pPressingButton->Pressing=false; ComponentButton_Draw(pPressingButton); for(u32 idx=0;idx<CompButtonsCount;idx++){ TComponentButton *pcb=&CompButtons[idx]; if(pcb==pPressingButton){ if(ComponentButton_GetIndexFromPos(pcb,x,y)!=-1){ ComponentButton_MouseUp(&CompButtons[idx],x,y); } } } pPressingButton=NULL; } ScreenRedrawFlag=true; return; } break; case EMM_Seek: { Resume_SetPos(DPG_GetCurrentFrameCount()); Resume_Save(); DPG_RequestSyncStart=true; SeekBarRedrawCount=0; SeekBarExecuteRedraw=true; IPC6->MP2PauseFlag=false; ScreenRedrawFlag=true; seeking=false; } break; case EMM_Volume: { } break; case EMM_Title: { DrawInfoFlag=false; ScreenRedrawFlag=true; } break; } } static void CB_PanelClose(void) { Resume_SetPos(DPG_GetCurrentFrameCount()); Resume_Save(); if(ProcState.DPG.PauseWhenPanelClosed==true){ IPC6->MP2PauseFlag=true; PanelClosePowerOffTimeOut=10*60*60; } return; DPGClose(); IPC6->LCDPowerControl=LCDPC_SOFT_POWEROFF; while(1); } static void CB_PanelOpen(void) { IPC6->MP2PauseFlag=false; PanelClosePowerOffTimeOut=0; } // ----------------------------- static bool Process_SeekNext,Process_SeekPrev; static u32 Process_WaitCount; static void CB_Start(void) { REG_POWERCNT = (REG_POWERCNT & ~POWER_SWAP_LCDS) | POWER_SWAP_LCDS; pScreenMain->SetMode(ESMM_ForARM7); pScreenSub->pCanvas->FillFull(ColorTable.Video.InitBG); // pScreenMainOverlay->pCanvas->FillFull(0); pScreenMain->pBackCanvas->FillFull(ColorTable.Video.InitBG); pScreenMain->pViewCanvas->FillFull(ColorTable.Video.InitBG); ToCustomMode=false; MouseMode=EMM_Idle; pPressingButton=NULL; seeking=false; DrawInfoFlag=false; DrawInfoDiffCount=0; KeySeeking=false; Process_SeekNext=false; Process_SeekPrev=false; Process_WaitCount=0; PanelClosePowerOffTimeOut=0; ModeLabel_Init(); if(ProcState.DPG.BacklightFlag==false){ IPC6->LCDPowerControl=LCDPC_ON_TOP; BrightLevel=0*0x100; }else{ IPC6->LCDPowerControl=LCDPC_ON_BOTH; BrightLevel=16*0x100; } pScreenSub->SetBlackOutLevel16(16-(BrightLevel/0x100)); { CglTGF *ptgf=MoviePlayerAlpha_GetSkin(EMPSA_volbar_on); VolumeBarRect.w=ptgf->GetWidth(); VolumeBarRect.h=ptgf->GetHeight(); VolumeBarRect.x=ScreenWidth-16-VolumeBarRect.w; VolumeBarRect.y=ScreenHeight-40-VolumeBarRect.h; } pCompBG=new CglCanvas(NULL,ScreenWidth,ScreenHeight-SeekBarHeight,pf15bit); if(pCompBG==NULL){ _consolePrintf("Fatal error: pCompBG memory overflow.\n"); ShowLogHalt(); } pTimeFont=new CFont(EBM_TGF,NULL,MoviePlayerAlpha_GetSkin(EMPSA_digits)); CompsInit(); ScreenRedrawFlag=true; pDPGfh1=NULL; pDPGfh2=NULL; SeekBarRedrawCount=0; SeekBarExecuteRedraw=true; if((Unicode_isEmpty(RelationalFilePathUnicode)==false)&&(Unicode_isEmpty(RelationalFileNameUnicode)==false)){ BGM_Start(RelationalFilePathUnicode,RelationalFileNameUnicode); if(RelationalFilePos!=DPG_GetCurrentFrameCount()) DPG_SetFrameCount(RelationalFilePos); Resume_SetPos(RelationalFilePos); Resume_Save(); } } static void RedrawSeekBar(void) { u32 curframe=DPG_GetCurrentFrameCount(); u32 ttlframe=DPG_GetTotalFrameCount(); u32 fps=DPG_GetFPS(); CglCanvas *pcan=pScreenSub->pCanvas; CglB15 *pbgon=MoviePlayer_GetSkin(EMPS_seekbar_on); CglB15 *pbgoff=MoviePlayer_GetSkin(EMPS_seekbar_off); s32 parx=(curframe*ScreenWidth)/ttlframe; if(parx<0) parx=0; if(ScreenWidth<parx) parx=ScreenWidth; pbgon->pCanvas->BitBlt(pcan,0,0,parx,SeekBarHeight,0,0,false); pbgoff->pCanvas->BitBlt(pcan,parx,0,ScreenWidth-parx,SeekBarHeight,parx,0,false); { CglTGF *ptgf=MoviePlayerAlpha_GetSkin(EMPSA_seekbargrip); s32 w=ptgf->GetWidth(); parx-=w/2; if(parx<0) parx=0; if((ScreenWidth-w)<parx) parx=ScreenWidth-w; DrawSkinAlpha(ptgf,pcan,parx,0); } u32 cursec=curframe*0x100/fps; u32 ttlsec=ttlframe*0x100/fps; char str[32]; snprintf(str,256,"%02d:%02d:%02d / %02d:%02d:%02d",cursec/(60*60),(cursec/60)%60,cursec%60,ttlsec/(60*60),(ttlsec/60)%60,ttlsec%60); u32 x=128,y=28; y+=(SeekBarHeight-y)/2; pTimeFont->DrawText(pcan,x,y,str); } static void RedrawFrameCacheBar(void) { CglCanvas *pcan=pScreenSub->pCanvas; u32 max=FrameCache_GetReadFramesCount(); u32 last=FrameCache_GetReadFrameLastCount(); if(max<=last) last=max-1; u32 con=ColorTable.Video.FrameCacheOn; u32 coff=ColorTable.Video.FrameCacheOff; if(last<=4){ con=ColorTable.Video.FrameCacheWarn; } if((max-4)<last) return; max*=2; last*=2; for(u32 idx=0;idx<max;idx++){ u16 c=con; if(last<idx) c=coff; pcan->SetPixel(4+idx,34+0,c); pcan->SetPixel(4+idx,34+1,c); } } static void CB_VsyncUpdate(u32 VsyncCount) { UpdateDPG_Audio(); if(PanelClosePowerOffTimeOut!=0){ if(PanelClosePowerOffTimeOut<VsyncCount){ PanelClosePowerOffTimeOut=0; }else{ PanelClosePowerOffTimeOut-=VsyncCount; } if(PanelClosePowerOffTimeOut==0){ _consolePrintf("Panel closed timeout. Auto power off.\n"); Sound_Start(WAVFN_PowerOff); u32 vsync=Sound_GetCurrentPlayTimePerVsync(); _consolePrintf("Wait for terminate. (%d)\n",vsync); for(u32 w=0;w<vsync;w++){ swiWaitForVBlank(); } IPC6->LCDPowerControl=LCDPC_SOFT_POWEROFF; while(1); } } if(BGMResumeSaveTimeVSync!=0){ BGMResumeSaveTimeVSync+=VsyncCount; if((60*5)<BGMResumeSaveTimeVSync){ BGMResumeSaveTimeVSync=1; u32 pos=DPG_GetCurrentFrameCount(); if(pos!=Resume_GetPos()){ Resume_SetPos(pos); Resume_Save(); } /* PrintFreeMem(); ProcState_RequestSave=true; */ ProcState_Save(); } } if(KeySeeking==true){ u32 KEYS_CUR=(~REG_KEYINPUT)&0x3ff; if(KEYS_CUR==0){ KeySeeking=false; Resume_SetPos(DPG_GetCurrentFrameCount()); Resume_Save(); DPG_RequestSyncStart=true; SeekBarRedrawCount=0; SeekBarExecuteRedraw=true; IPC6->MP2PauseFlag=false; ScreenRedrawFlag=true; seeking=false; } } if((Process_SeekNext==true)||(Process_SeekPrev==true)){ if(Process_WaitCount!=0){ Process_WaitCount=10; }else{ s32 v=0; if(Process_SeekPrev==true) v=-5; if(Process_SeekNext==true) v=+5; s32 curf,tagf; curf=(s32)DPG_GetCurrentFrameCount(); tagf=curf+((s32)DPG_GetFPS()*v/0x100); if(tagf<0) tagf=0; _consolePrintf("Move frame %d to %d.\n",curf,tagf); if((s32)DPG_GetTotalFrameCount()<=tagf){ cwl(); strpcmRequestStop=true; }else{ DPG_SetFrameCount((u32)tagf); swiWaitForVBlank(); DPG_SliceOneFrame(pScreenMain->pBackCanvas->GetVRAMBuf(),pScreenMain->pViewCanvas->GetVRAMBuf()); VBlank_AutoFlip_Enabled(); SeekBarRedrawCount=0; SeekBarExecuteRedraw=true; } } } ModeLabel_Vsync(VsyncCount); if(ProcState.DPG.BacklightFlag==true){ { // Enable VRAM buffer write cache u32 r0=7; __asm { mcr p15, 0, r0, c3, c0, 0 } } if(SeekBarRedrawCount!=0){ if(SeekBarRedrawCount<=VsyncCount){ SeekBarRedrawCount=0; }else{ SeekBarRedrawCount-=VsyncCount; } } if(SeekBarRedrawCount==0){ if(SeekBarExecuteRedraw==true){ SeekBarExecuteRedraw=false; SeekBarRedrawCount=60; RedrawSeekBar(); }else{ if(VsyncCount<=3){ SeekBarRedrawCount=60; RedrawSeekBar(); } } } RedrawFrameCacheBar(); if(ScreenRedrawFlag==true){ ScreenRedrawFlag=false; Setting_Redraw(); } if(DrawInfoFlag==true){ if(DrawInfoDiffCount!=0){ if(DrawInfoDiffCount<VsyncCount){ DrawInfoDiffCount=0; }else{ DrawInfoDiffCount-=VsyncCount; } if(DrawInfoDiffCount==0){ DrawInfoDiffCount=5; pCompBG->SetCglFont(pCglFontDefault); pCompBG->SetFontTextColor(ColorTable.Video.InfoText); pCompBG->SetColor(ColorTable.Video.InfoBG); u32 height=DPG_DrawInfoDiffHeight(); pCompBG->FillFast(0,0,ScreenWidth,height); DPG_DrawInfoDiff(pCompBG); pCompBG->BitBlt(pScreenSub->pCanvas,0,SeekBarHeight,pCompBG->GetWidth(),height,0,0,false); } } } { // Disable VRAM buffer write cache u32 r0=6; __asm { mcr p15, 0, r0, c3, c0, 0 } } } if(seeking==false){ while(VBlankPassedFlag==false){ ProcDPG(); } if(strpcmRequestStop==true){ _consolePrint("Wait for terminate.\n"); while(FrameCache_isReadEmpty()==false){ UpdateDPG_Audio(); } Exec_Next(true); ScreenRedrawFlag=true; ProcDPG(); } } if(ProcState.DPG.BacklightFlag==false){ if(BrightLevel!=(0*0x100)){ BrightLevel-=VsyncCount*64; pScreenSub->SetBlackOutLevel16(16-(BrightLevel/0x100)); if(BrightLevel<=(0*0x100)){ BrightLevel=0*0x100; pScreenSub->SetBlackOutLevel16(16-(BrightLevel/0x100)); IPC6->LCDPowerControl=LCDPC_ON_TOP; } } }else{ if(BrightLevel!=(16*0x100)){ IPC6->LCDPowerControl=LCDPC_ON_BOTH; BrightLevel+=VsyncCount*128; pScreenSub->SetBlackOutLevel16(16-(BrightLevel/0x100)); if((16*0x100)<=BrightLevel){ BrightLevel=16*0x100; pScreenSub->SetBlackOutLevel16(16-(BrightLevel/0x100)); } } } } static void CB_End(void) { TCallBack *pCallBack=CallBack_GetPointer(); pCallBack->VBlankHandler=NULL; VBlank_AutoFlip_Disabled(); if(ToCustomMode==false){ RelationalFile_Clear(); }else{ Unicode_Copy(RelationalFileNameUnicode,BGM_GetCurrentFilename()); RelationalFilePos=DPG_GetCurrentFrameCount(); } Resume_Clear(); Unicode_Copy(ProcState.FileList.SelectFilenameUnicode,BGM_GetCurrentFilename()); ProcState_RequestSave=true; ProcState_Save(); BGM_Free(); if(pCompBG!=NULL){ delete pCompBG; pCompBG=NULL; } if(pTimeFont!=NULL){ delete pTimeFont; pTimeFont=NULL; } CglCanvas *ptmpcan=new CglCanvas(NULL,ScreenWidth,ScreenHeight,pf15bit); if(ProcState.DPG.BacklightFlag==false){ pScreenSub->pCanvas->FillFull(ColorTable.Video.InitBG); } pScreenSub->pCanvas->BitBltFullBeta(ptmpcan); swiWaitForVBlank(); REG_POWERCNT = (REG_POWERCNT & ~POWER_SWAP_LCDS); // | POWER_SWAP_LCDS; pScreenMain->SetMode(ESMM_Normal); pScreenMain->Flip(true); pScreenMainOverlay->pCanvas->FillFull(0); // pScreenMain->GetCanvas(ScrMainID_View)->FillFull(ColorTable.Video.InitBG); ptmpcan->BitBltFullBeta(pScreenMain->pViewCanvas); pScreenSub->pCanvas->FillFull(ColorTable.Video.InitBG); delete ptmpcan; ptmpcan=NULL; IPC6->LCDPowerControl=LCDPC_ON_BOTH; pScreenSub->SetBlackOutLevel16(0); } DATA_IN_DTCM u32 reqflip=0; #include "plug_dpg.h" extern u32 FrameCache_GetBufferSizeByte(void); extern u16* FrameCache_ReadStart(u64 CurrentSamples); extern void FrameCache_ReadEnd(void); static void CB_VBlankHandler(void) { u64 SyncSamples=DPGAudioStream_SyncSamples; if(IPC6->MP2PauseFlag==false) SyncSamples+=DPGAudioStream_PregapSamples; DPGAudioStream_SyncSamples=SyncSamples; u16 *pbuf=FrameCache_ReadStart(SyncSamples); if(pbuf!=NULL){ if(reqflip!=0){ if(reqflip==3) pScreenMain->Flip(false); pScreenMain->SetBlendLevel(16); reqflip=0; } u16 *pVRAMBuf=pScreenMain->pBackCanvas->GetVRAMBuf(); u32 len=FrameCache_GetBufferSizeByte(); while(DMA0_CR & DMA_BUSY); // DCache_CleanRangeOverrun(pbuf,len); // DCache_FlushRangeOverrun(pVRAMBuf,len); DMA0_SRC = (uint32)pbuf; DMA0_DEST = (uint32)&pVRAMBuf[(((ScreenWidth*ScreenHeight*2)-len)/2)/2]; DMA0_CR = DMA_ENABLE | DMA_SRC_INC | DMA_DST_INC | DMA_32_BIT | (len>>2); reqflip=3; FrameCache_ReadEnd(); } if(reqflip!=0){ if(reqflip==3){ pScreenMain->Flip(false); pScreenMain->SetBlendLevel(6); }else{ if(reqflip==2){ pScreenMain->SetBlendLevel(11); }else{ pScreenMain->SetBlendLevel(16); } } reqflip--; } } #include "proc_DPGPlay_Trigger_CallBack.h" void ProcDPGPlay_SetCallBack(TCallBack *pCallBack) { pCallBack->Start=CB_Start; pCallBack->VsyncUpdate=CB_VsyncUpdate; pCallBack->End=CB_End; pCallBack->KeyPress=CB_KeyPress; pCallBack->KeySameLRDown=CB_KeySameLRDown; pCallBack->MouseDown=CB_MouseDown; pCallBack->MouseMove=CB_MouseMove; pCallBack->MouseUp=CB_MouseUp; pCallBack->VBlankHandler=CB_VBlankHandler; pCallBack->PanelClose=CB_PanelClose; pCallBack->PanelOpen=CB_PanelOpen; pCallBack->Trigger_ProcStart=CB_Trigger_ProcStart; pCallBack->Trigger_ProcEnd=CB_Trigger_ProcEnd; pCallBack->Trigger_Down=CB_Trigger_Down; pCallBack->Trigger_Up=CB_Trigger_Up; pCallBack->Trigger_LongStart=CB_Trigger_LongStart; pCallBack->Trigger_LongEnd=CB_Trigger_LongEnd; pCallBack->Trigger_SingleClick=CB_Trigger_SingleClick; pCallBack->Trigger_SingleLongStart=CB_Trigger_SingleLongStart; pCallBack->Trigger_SingleLongEnd=CB_Trigger_SingleLongEnd; pCallBack->Trigger_DoubleClick=CB_Trigger_DoubleClick; pCallBack->Trigger_DoubleLongStart=CB_Trigger_DoubleLongStart; pCallBack->Trigger_DoubleLongEnd=CB_Trigger_DoubleLongEnd; pCallBack->Trigger_TripleClick=CB_Trigger_TripleClick; }
[ "feng.flash@4bd7f34a-4c62-84e7-1fb2-5fbc975ebfb2" ]
[ [ [ 1, 1331 ] ] ]
da6f30737d4aa8fd4f5e17b3539727c3bbb442e6
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/vis/writer/vis_pdf_writer.h
8b923cc433839f9eca8ece5097c8ccd2db6655a2
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,549
h
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) ** ** and SWARMS (www.swarms.de) ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the GNU General Public License, version 2. ** ************************************************************************/ #ifndef __SHAWN_TUBSAPPS_VIS_PDF_WRITER_H #define __SHAWN_TUBSAPPS_VIS_PDF_WRITER_H #include "../buildfiles/_apps_enable_cmake.h" #ifdef ENABLE_VIS #include "apps/vis/base/vis_needs_cairo.h" #include "apps/vis/writer/vis_writer.h" namespace vis { /** \brief PDF Writer class. * This is the PDF output class, which is used to save the visualization output to a PDF * file. * * @sa vis::Writer * @sa vis::PNGWriter */ class PDFWriter : public Writer { public: ///@name Contructor/Destructor ///@{ PDFWriter(); virtual ~PDFWriter(); ///@} protected: /** * Creates a new cairo surface. If there is already a surface, it is * dropped automatically. */ virtual void make_surface( int, int ) throw(); /** * Writes the current frame to the output file. */ virtual void write_frame_to_file( cairo_t* cr ) throw( std::runtime_error ); }; } #endif #endif
[ [ [ 1, 50 ] ] ]
8ccd8fd4c67880c1383685f4f0944eb88794f2ca
cc336f796b029620d6828804a866824daa6cc2e0
/screensavers/GreyNetic/GreyNetic.cpp
321e66e5a2db27082ca37fd4957b29eb3fbf470a
[]
no_license
tokyovigilante/xbmc-sources-fork
84fa1a4b6fec5570ce37a69d667e9b48974e3dc3
ac3c6ef8c567f1eeb750ce6e74c63c2d53fcde11
refs/heads/master
2021-01-19T10:11:37.336476
2009-03-09T20:33:58
2009-03-09T20:33:58
29,232
2
0
null
null
null
null
UTF-8
C++
false
false
10,647
cpp
/* * GreyNetic Screensaver for XBox Media Center * Copyright (c) 2004 Team XBMC * * Ver 1.0 26 Fed 2005 Dylan Thurston (Dinomight) * * 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. */ /* * * Greynetic was inspired by the Xscreensaver hack of the same name * This is a very basic kinda boring screen saver, but it works. * if you find any bugs please let me know * [email protected] * */ #include "GreyNetic.h" #include "XmlDocument.h" // use the 'dummy' dx8 lib - this allow you to make // DX8 calls which XBMC will emulate for you. #pragma comment (lib, "lib/xbox_dx8.lib" ) #define MAX_BOXES 10000 struct CUSTOMVERTEX { FLOAT x, y, z, rhw; // The transformed position for the vertex DWORD color; // The vertex color }; int NumberOfBoxes = MAX_BOXES; int MaxSizeX = 200; int MinSizeX = 0; int MaxSizeY = 200; int MinSizeY = 0; int MaxSquareSize = 200; int MinSquareSize = 0; int MaxAlpha = 255; int MinAlpha = 0; int MaxRed = 255; int MinRed = 0; int MaxGreen = 255; int MinGreen = 0; int MaxBlue = 255; int MinBlue = 0; int MaxJoined = 255; int MinJoined = 0; bool MakeSquares = false; bool JoinedSizeX = false; bool JoinedSizeY = false; bool JoinedRed = false; bool JoinedGreen = false; bool JoinedBlue = false; bool JoinedAlpha = false; int m_width; int m_height; float m_centerx; float m_centery; int xa[MAX_BOXES]; int ya[MAX_BOXES]; int wa[MAX_BOXES]; int ha[MAX_BOXES]; D3DCOLOR dwcolor[MAX_BOXES]; LPDIRECT3DVERTEXBUFFER8 m_pVB; //m_szScrName = "template"; // XBMC has loaded us into memory, // we should set our core values // here and load any settings we // may have from our config file extern "C" void Create(LPDIRECT3DDEVICE8 pd3dDevice, int iWidth, int iHeight, const char* szScreenSaverName) { strcpy(m_szScrName,szScreenSaverName); m_pd3dDevice = pd3dDevice; m_iWidth = iWidth; m_iHeight = iHeight; // Load the settings LoadSettings(); } // XBMC tells us we should get ready // to start rendering. This function // is called once when the screensaver // is activated by XBMC. extern "C" void Start() { return; } void DrawRectangle(int x, int y, int w, int h, D3DCOLOR dwColour) { VOID* pVertices; //MYCUSTOMVERTEX cvVertices[300*4]; //Store each point of the triangle together with it's colour MYCUSTOMVERTEX cvVertices[] = { {(float) x, (float) y+h, 0.0f, 0.5, dwColour,}, {(float) x, (float) y, 0.0f, 0.5, dwColour,}, {(float) x+w, (float) y+h, 0.0f, 0.5, dwColour,}, {(float) x+w, (float) y, 0.0f, 0.5, dwColour,}, }; //Create the vertex buffer from our device m_pd3dDevice->CreateVertexBuffer(4 * sizeof(MYCUSTOMVERTEX), D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_MANAGED, &g_pVertexBuffer); //Get a pointer to the vertex buffer vertices and lock the vertex buffer g_pVertexBuffer->Lock(0, sizeof(cvVertices), (BYTE**)&pVertices, 0); //Copy our stored vertices values into the vertex buffer memcpy(pVertices, cvVertices, sizeof(cvVertices)); //Unlock the vertex buffer g_pVertexBuffer->Unlock(); // Draw it m_pd3dDevice->SetVertexShader(D3DFVF_CUSTOMVERTEX); m_pd3dDevice->SetStreamSource(0, g_pVertexBuffer, sizeof(MYCUSTOMVERTEX)); m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); // Every time we Create a vertex buffer, we must release one!. g_pVertexBuffer->Release(); return; } // XBMC tells us to render a frame of // our screensaver. This is called on // each frame render in XBMC, you should // render a single frame only - the DX // device will already have been cleared. extern "C" void Render() { for (int i=NumberOfBoxes - 1 ; i>0; i--){ xa[i] = xa[i-1] ; ya[i] = ya[i-1] ; ha[i] = ha[i-1] ; wa[i] = wa[i-1] ; dwcolor[i] = dwcolor[i-1] ; } double red = rand() %(MaxRed - MinRed) + MinRed; double green = rand() %(MaxGreen - MinGreen) + MinGreen; double blue = rand() %(MaxBlue - MinBlue) + MinBlue; double alpha = rand() %(MaxAlpha - MinAlpha) + MinAlpha; double joined = rand() %(MaxJoined - MinJoined) + MinJoined; if(JoinedRed){ red = joined; } if(JoinedGreen){ green = joined; } if(JoinedBlue){ blue = joined; } if(JoinedAlpha){ alpha = joined; } dwcolor[0] = D3DCOLOR_RGBA((int) red, (int) green, (int) blue, (int) alpha); xa[0] = rand()%m_iWidth; ya[0] = rand()%m_iHeight; ha[0] = rand() % (MaxSizeY - MinSizeY) + MinSizeY; wa[0] = rand() % (MaxSizeX - MinSizeX) + MinSizeX; if(MakeSquares){ ha[0] = rand() % (MaxSquareSize - MinSquareSize) + MinSquareSize; wa[0] = ha[0]; } if(JoinedSizeY){ ha[0] = joined; } if(JoinedSizeX){ wa[0] = joined; } //ha[0] = wa[0]; for (int i=NumberOfBoxes - 1 ; i>0; i--){ DrawRectangle(xa[i],ya[i],wa[i],ha[i], dwcolor[i]); } return; } // XBMC tells us to stop the screensaver // we should free any memory and release // any resources we have created. extern "C" void Stop() { return; } // Load settings from the [screensavername].xml configuration file // the name of the screensaver (filename) is used as the name of // the xml file - this is sent to us by XBMC when the Init func // is called. void LoadSettings() { XmlNode node, childNode, grandChild; CXmlDocument doc; // Set up the defaults SetDefaults(); char szXMLFile[1024]; strcpy(szXMLFile, "Q:\\screensavers\\"); strcat(szXMLFile, m_szScrName); strcat(szXMLFile, ".xml"); OutputDebugString("Loading XML: "); OutputDebugString(szXMLFile); // Load the config file if (doc.Load(szXMLFile) >= 0) { node = doc.GetNextNode(XML_ROOT_NODE); while(node > 0) { if (strcmpi(doc.GetNodeTag(node),"screensaver")) { node = doc.GetNextNode(node); continue; } if (childNode = doc.GetChildNode(node,"NumberOfBoxes")){ OutputDebugString("found number of boxes settings"); NumberOfBoxes = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MaxSizeX")){ MaxSizeX = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MinSizeX")){ MinSizeX = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MaxSizeY")){ MaxSizeY = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MinSizeY")){ MinSizeY = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MakeSquares")){ MakeSquares = !strcmpi(doc.GetNodeText(childNode),"true"); } if (childNode = doc.GetChildNode(node,"MinSquareSize")){ MinSquareSize = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MaxSquareSize")){ MaxSquareSize = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MaxAlpha")){ MaxAlpha = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MinAlpha")){ MinAlpha = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MaxRed")){ MaxRed = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MinRed")){ MinRed = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MaxGreen")){ MaxGreen = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MinGreen")){ MinGreen = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MaxBlue")){ MaxBlue = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MinBlue")){ MinBlue = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MaxJoined")){ MinJoined = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"MinJoined")){ MinJoined = atoi(doc.GetNodeText(childNode)); } if (childNode = doc.GetChildNode(node,"JoinedsizeX")){ if(!strcmpi(doc.GetNodeText(childNode),"true")){ JoinedSizeX = true; } } if (childNode = doc.GetChildNode(node,"JoinedsizeY")){ if(!strcmpi(doc.GetNodeText(childNode),"true")){ JoinedSizeY = true; } } if (childNode = doc.GetChildNode(node,"JoinedAlpha")){ if(!strcmpi(doc.GetNodeText(childNode),"true")){ JoinedAlpha = true; } } if (childNode = doc.GetChildNode(node,"JoinedRed")){ if(!strcmpi(doc.GetNodeText(childNode),"true")){ JoinedRed = true; } } if (childNode = doc.GetChildNode(node,"JoinedGreen")){ if(!strcmpi(doc.GetNodeText(childNode),"true")){ JoinedGreen = true; } } if (childNode = doc.GetChildNode(node,"JoinedBlue")){ if(!strcmpi(doc.GetNodeText(childNode),"true")){ JoinedBlue = true; } } node = doc.GetNextNode(node); } doc.Close(); } } void SetDefaults() { // set any default values for your screensaver's parameters return; } extern "C" void GetInfo(SCR_INFO* pInfo) { // not used, but can be used to pass info // back to XBMC if required in the future return; } extern "C" { struct ScreenSaver { public: void (__cdecl* Create)(LPDIRECT3DDEVICE8 pd3dDevice, int iWidth, int iHeight, const char* szScreensaver); void (__cdecl* Start) (); void (__cdecl* Render) (); void (__cdecl* Stop) (); void (__cdecl* GetInfo)(SCR_INFO *info); } ; void __declspec(dllexport) get_module(struct ScreenSaver* pScr) { pScr->Create = Create; pScr->Start = Start; pScr->Render = Render; pScr->Stop = Stop; pScr->GetInfo = GetInfo; } };
[ "spiff_@568bbfeb-2a22-0410-94d2-cc84cf5bfa90" ]
[ [ [ 1, 398 ] ] ]
350a1c3a6419085695bad3e8f2f3268162ce530a
eb8a27a2cc7307f0bc9596faa4aa4a716676c5c5
/WinEdition/browser-lcc/jscc/src/v8/v8/src/scanner-base.h
9c6f59eb7f83358d6282b23aaa3c5ee84def03ca
[ "BSD-3-Clause", "bzip2-1.0.6", "LicenseRef-scancode-public-domain", "Artistic-2.0", "Artistic-1.0" ]
permissive
baxtree/OKBuzzer
c46c7f271a26be13adcf874d77a7a6762a8dc6be
a16e2baad145f5c65052cdc7c767e78cdfee1181
refs/heads/master
2021-01-02T22:17:34.168564
2011-06-15T02:29:56
2011-06-15T02:29:56
1,790,181
0
0
null
null
null
null
UTF-8
C++
false
false
20,627
h
// Copyright 2011 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. // Features shared by parsing and pre-parsing scanners. #ifndef V8_SCANNER_BASE_H_ #define V8_SCANNER_BASE_H_ #include "globals.h" #include "checks.h" #include "allocation.h" #include "token.h" #include "unicode-inl.h" #include "char-predicates.h" #include "utils.h" #include "list-inl.h" namespace v8 { namespace internal { // Returns the value (0 .. 15) of a hexadecimal character c. // If c is not a legal hexadecimal character, returns a value < 0. inline int HexValue(uc32 c) { c -= '0'; if (static_cast<unsigned>(c) <= 9) return c; c = (c | 0x20) - ('a' - '0'); // detect 0x11..0x16 and 0x31..0x36. if (static_cast<unsigned>(c) <= 5) return c + 10; return -1; } // --------------------------------------------------------------------- // Buffered stream of characters, using an internal UC16 buffer. class UC16CharacterStream { public: UC16CharacterStream() : pos_(0) { } virtual ~UC16CharacterStream() { } // Returns and advances past the next UC16 character in the input // stream. If there are no more characters, it returns a negative // value. inline uc32 Advance() { if (buffer_cursor_ < buffer_end_ || ReadBlock()) { pos_++; return static_cast<uc32>(*(buffer_cursor_++)); } // Note: currently the following increment is necessary to avoid a // parser problem! The scanner treats the final kEndOfInput as // a character with a position, and does math relative to that // position. pos_++; return kEndOfInput; } // Return the current position in the character stream. // Starts at zero. inline unsigned pos() const { return pos_; } // Skips forward past the next character_count UC16 characters // in the input, or until the end of input if that comes sooner. // Returns the number of characters actually skipped. If less // than character_count, inline unsigned SeekForward(unsigned character_count) { unsigned buffered_chars = static_cast<unsigned>(buffer_end_ - buffer_cursor_); if (character_count <= buffered_chars) { buffer_cursor_ += character_count; pos_ += character_count; return character_count; } return SlowSeekForward(character_count); } // Pushes back the most recently read UC16 character (or negative // value if at end of input), i.e., the value returned by the most recent // call to Advance. // Must not be used right after calling SeekForward. virtual void PushBack(int32_t character) = 0; protected: static const uc32 kEndOfInput = -1; // Ensures that the buffer_cursor_ points to the character at // position pos_ of the input, if possible. If the position // is at or after the end of the input, return false. If there // are more characters available, return true. virtual bool ReadBlock() = 0; virtual unsigned SlowSeekForward(unsigned character_count) = 0; const uc16* buffer_cursor_; const uc16* buffer_end_; unsigned pos_; }; class UnicodeCache { // --------------------------------------------------------------------- // Caching predicates used by scanners. public: UnicodeCache() {} typedef unibrow::Utf8InputBuffer<1024> Utf8Decoder; StaticResource<Utf8Decoder>* utf8_decoder() { return &utf8_decoder_; } bool IsIdentifierStart(unibrow::uchar c) { return kIsIdentifierStart.get(c); } bool IsIdentifierPart(unibrow::uchar c) { return kIsIdentifierPart.get(c); } bool IsLineTerminator(unibrow::uchar c) { return kIsLineTerminator.get(c); } bool IsWhiteSpace(unibrow::uchar c) { return kIsWhiteSpace.get(c); } private: unibrow::Predicate<IdentifierStart, 128> kIsIdentifierStart; unibrow::Predicate<IdentifierPart, 128> kIsIdentifierPart; unibrow::Predicate<unibrow::LineTerminator, 128> kIsLineTerminator; unibrow::Predicate<unibrow::WhiteSpace, 128> kIsWhiteSpace; StaticResource<Utf8Decoder> utf8_decoder_; DISALLOW_COPY_AND_ASSIGN(UnicodeCache); }; // ---------------------------------------------------------------------------- // LiteralBuffer - Collector of chars of literals. class LiteralBuffer { public: LiteralBuffer() : is_ascii_(true), position_(0), backing_store_() { } ~LiteralBuffer() { if (backing_store_.length() > 0) { backing_store_.Dispose(); } } inline void AddChar(uc16 character) { if (position_ >= backing_store_.length()) ExpandBuffer(); if (is_ascii_) { if (character < kMaxAsciiCharCodeU) { backing_store_[position_] = static_cast<byte>(character); position_ += kASCIISize; return; } ConvertToUC16(); } *reinterpret_cast<uc16*>(&backing_store_[position_]) = character; position_ += kUC16Size; } bool is_ascii() { return is_ascii_; } Vector<const uc16> uc16_literal() { ASSERT(!is_ascii_); ASSERT((position_ & 0x1) == 0); return Vector<const uc16>( reinterpret_cast<const uc16*>(backing_store_.start()), position_ >> 1); } Vector<const char> ascii_literal() { ASSERT(is_ascii_); return Vector<const char>( reinterpret_cast<const char*>(backing_store_.start()), position_); } int length() { return is_ascii_ ? position_ : (position_ >> 1); } void Reset() { position_ = 0; is_ascii_ = true; } private: static const int kInitialCapacity = 16; static const int kGrowthFactory = 4; static const int kMinConversionSlack = 256; static const int kMaxGrowth = 1 * MB; inline int NewCapacity(int min_capacity) { int capacity = Max(min_capacity, backing_store_.length()); int new_capacity = Min(capacity * kGrowthFactory, capacity + kMaxGrowth); return new_capacity; } void ExpandBuffer() { Vector<byte> new_store = Vector<byte>::New(NewCapacity(kInitialCapacity)); memcpy(new_store.start(), backing_store_.start(), position_); backing_store_.Dispose(); backing_store_ = new_store; } void ConvertToUC16() { ASSERT(is_ascii_); Vector<byte> new_store; int new_content_size = position_ * kUC16Size; if (new_content_size >= backing_store_.length()) { // Ensure room for all currently read characters as UC16 as well // as the character about to be stored. new_store = Vector<byte>::New(NewCapacity(new_content_size)); } else { new_store = backing_store_; } char* src = reinterpret_cast<char*>(backing_store_.start()); uc16* dst = reinterpret_cast<uc16*>(new_store.start()); for (int i = position_ - 1; i >= 0; i--) { dst[i] = src[i]; } if (new_store.start() != backing_store_.start()) { backing_store_.Dispose(); backing_store_ = new_store; } position_ = new_content_size; is_ascii_ = false; } bool is_ascii_; int position_; Vector<byte> backing_store_; DISALLOW_COPY_AND_ASSIGN(LiteralBuffer); }; // ---------------------------------------------------------------------------- // Scanner base-class. // Generic functionality used by both JSON and JavaScript scanners. class Scanner { public: // -1 is outside of the range of any real source code. static const int kNoOctalLocation = -1; typedef unibrow::Utf8InputBuffer<1024> Utf8Decoder; class LiteralScope { public: explicit LiteralScope(Scanner* self); ~LiteralScope(); void Complete(); private: Scanner* scanner_; bool complete_; }; explicit Scanner(UnicodeCache* scanner_contants); // Returns the current token again. Token::Value current_token() { return current_.token; } // One token look-ahead (past the token returned by Next()). Token::Value peek() const { return next_.token; } struct Location { Location(int b, int e) : beg_pos(b), end_pos(e) { } Location() : beg_pos(0), end_pos(0) { } bool IsValid() const { return beg_pos >= 0 && end_pos >= beg_pos; } int beg_pos; int end_pos; }; static Location NoLocation() { return Location(-1, -1); } // Returns the location information for the current token // (the token returned by Next()). Location location() const { return current_.location; } Location peek_location() const { return next_.location; } // Returns the location of the last seen octal literal int octal_position() const { return octal_pos_; } void clear_octal_position() { octal_pos_ = -1; } // Returns the literal string, if any, for the current token (the // token returned by Next()). The string is 0-terminated and in // UTF-8 format; they may contain 0-characters. Literal strings are // collected for identifiers, strings, and numbers. // These functions only give the correct result if the literal // was scanned between calls to StartLiteral() and TerminateLiteral(). bool is_literal_ascii() { ASSERT_NOT_NULL(current_.literal_chars); return current_.literal_chars->is_ascii(); } Vector<const char> literal_ascii_string() { ASSERT_NOT_NULL(current_.literal_chars); return current_.literal_chars->ascii_literal(); } Vector<const uc16> literal_uc16_string() { ASSERT_NOT_NULL(current_.literal_chars); return current_.literal_chars->uc16_literal(); } int literal_length() const { ASSERT_NOT_NULL(current_.literal_chars); return current_.literal_chars->length(); } // Returns the literal string for the next token (the token that // would be returned if Next() were called). bool is_next_literal_ascii() { ASSERT_NOT_NULL(next_.literal_chars); return next_.literal_chars->is_ascii(); } Vector<const char> next_literal_ascii_string() { ASSERT_NOT_NULL(next_.literal_chars); return next_.literal_chars->ascii_literal(); } Vector<const uc16> next_literal_uc16_string() { ASSERT_NOT_NULL(next_.literal_chars); return next_.literal_chars->uc16_literal(); } int next_literal_length() const { ASSERT_NOT_NULL(next_.literal_chars); return next_.literal_chars->length(); } static const int kCharacterLookaheadBufferSize = 1; protected: // The current and look-ahead token. struct TokenDesc { Token::Value token; Location location; LiteralBuffer* literal_chars; }; // Call this after setting source_ to the input. void Init() { // Set c0_ (one character ahead) ASSERT(kCharacterLookaheadBufferSize == 1); Advance(); // Initialize current_ to not refer to a literal. current_.literal_chars = NULL; } // Literal buffer support inline void StartLiteral() { LiteralBuffer* free_buffer = (current_.literal_chars == &literal_buffer1_) ? &literal_buffer2_ : &literal_buffer1_; free_buffer->Reset(); next_.literal_chars = free_buffer; } inline void AddLiteralChar(uc32 c) { ASSERT_NOT_NULL(next_.literal_chars); next_.literal_chars->AddChar(c); } // Complete scanning of a literal. inline void TerminateLiteral() { // Does nothing in the current implementation. } // Stops scanning of a literal and drop the collected characters, // e.g., due to an encountered error. inline void DropLiteral() { next_.literal_chars = NULL; } inline void AddLiteralCharAdvance() { AddLiteralChar(c0_); Advance(); } // Low-level scanning support. void Advance() { c0_ = source_->Advance(); } void PushBack(uc32 ch) { source_->PushBack(c0_); c0_ = ch; } inline Token::Value Select(Token::Value tok) { Advance(); return tok; } inline Token::Value Select(uc32 next, Token::Value then, Token::Value else_) { Advance(); if (c0_ == next) { Advance(); return then; } else { return else_; } } uc32 ScanHexEscape(uc32 c, int length); // Scans octal escape sequence. Also accepts "\0" decimal escape sequence. uc32 ScanOctalEscape(uc32 c, int length); // Return the current source position. int source_pos() { return source_->pos() - kCharacterLookaheadBufferSize; } UnicodeCache* unicode_cache_; // Buffers collecting literal strings, numbers, etc. LiteralBuffer literal_buffer1_; LiteralBuffer literal_buffer2_; TokenDesc current_; // desc for current token (as returned by Next()) TokenDesc next_; // desc for next token (one token look-ahead) // Input stream. Must be initialized to an UC16CharacterStream. UC16CharacterStream* source_; // Start position of the octal literal last scanned. int octal_pos_; // One Unicode character look-ahead; c0_ < 0 at the end of the input. uc32 c0_; }; // ---------------------------------------------------------------------------- // JavaScriptScanner - base logic for JavaScript scanning. class JavaScriptScanner : public Scanner { public: // A LiteralScope that disables recording of some types of JavaScript // literals. If the scanner is configured to not record the specific // type of literal, the scope will not call StartLiteral. class LiteralScope { public: explicit LiteralScope(JavaScriptScanner* self) : scanner_(self), complete_(false) { scanner_->StartLiteral(); } ~LiteralScope() { if (!complete_) scanner_->DropLiteral(); } void Complete() { scanner_->TerminateLiteral(); complete_ = true; } private: JavaScriptScanner* scanner_; bool complete_; }; explicit JavaScriptScanner(UnicodeCache* scanner_contants); // Returns the next token. Token::Value Next(); // Returns true if there was a line terminator before the peek'ed token. bool has_line_terminator_before_next() const { return has_line_terminator_before_next_; } // Scans the input as a regular expression pattern, previous // character(s) must be /(=). Returns true if a pattern is scanned. bool ScanRegExpPattern(bool seen_equal); // Returns true if regexp flags are scanned (always since flags can // be empty). bool ScanRegExpFlags(); // Tells whether the buffer contains an identifier (no escapes). // Used for checking if a property name is an identifier. static bool IsIdentifier(unibrow::CharacterStream* buffer); // Seek forward to the given position. This operation does not // work in general, for instance when there are pushed back // characters, but works for seeking forward until simple delimiter // tokens, which is what it is used for. void SeekForward(int pos); protected: bool SkipWhiteSpace(); Token::Value SkipSingleLineComment(); Token::Value SkipMultiLineComment(); // Scans a single JavaScript token. void Scan(); void ScanDecimalDigits(); Token::Value ScanNumber(bool seen_period); Token::Value ScanIdentifierOrKeyword(); Token::Value ScanIdentifierSuffix(LiteralScope* literal); void ScanEscape(); Token::Value ScanString(); // Scans a possible HTML comment -- begins with '<!'. Token::Value ScanHtmlComment(); // Decodes a unicode escape-sequence which is part of an identifier. // If the escape sequence cannot be decoded the result is kBadChar. uc32 ScanIdentifierUnicodeEscape(); bool has_line_terminator_before_next_; }; // ---------------------------------------------------------------------------- // Keyword matching state machine. class KeywordMatcher { // Incrementally recognize keywords. // // Recognized keywords: // break case catch const* continue debugger* default delete do else // finally false for function if in instanceof native* new null // return switch this throw true try typeof var void while with // // *: Actually "future reserved keywords". These are the only ones we // recognize, the remaining are allowed as identifiers. // In ES5 strict mode, we should disallow all reserved keywords. public: KeywordMatcher() : state_(INITIAL), token_(Token::IDENTIFIER), keyword_(NULL), counter_(0), keyword_token_(Token::ILLEGAL) {} Token::Value token() { return token_; } inline bool AddChar(unibrow::uchar input) { if (state_ != UNMATCHABLE) { Step(input); } return state_ != UNMATCHABLE; } void Fail() { token_ = Token::IDENTIFIER; state_ = UNMATCHABLE; } private: enum State { UNMATCHABLE, INITIAL, KEYWORD_PREFIX, KEYWORD_MATCHED, C, CA, CO, CON, D, DE, E, EX, F, I, IM, IMP, IN, N, P, PR, S, T, TH, TR, V, W }; struct FirstState { const char* keyword; State state; Token::Value token; }; // Range of possible first characters of a keyword. static const unsigned int kFirstCharRangeMin = 'b'; static const unsigned int kFirstCharRangeMax = 'y'; static const unsigned int kFirstCharRangeLength = kFirstCharRangeMax - kFirstCharRangeMin + 1; // State map for first keyword character range. static FirstState first_states_[kFirstCharRangeLength]; // If input equals keyword's character at position, continue matching keyword // from that position. inline bool MatchKeywordStart(unibrow::uchar input, const char* keyword, int position, Token::Value token_if_match) { if (input != static_cast<unibrow::uchar>(keyword[position])) { return false; } state_ = KEYWORD_PREFIX; this->keyword_ = keyword; this->counter_ = position + 1; this->keyword_token_ = token_if_match; return true; } // If input equals match character, transition to new state and return true. inline bool MatchState(unibrow::uchar input, char match, State new_state) { if (input != static_cast<unibrow::uchar>(match)) { return false; } state_ = new_state; return true; } inline bool MatchKeyword(unibrow::uchar input, char match, State new_state, Token::Value keyword_token) { if (input != static_cast<unibrow::uchar>(match)) { return false; } state_ = new_state; token_ = keyword_token; return true; } void Step(unibrow::uchar input); // Current state. State state_; // Token for currently added characters. Token::Value token_; // Matching a specific keyword string (there is only one possible valid // keyword with the current prefix). const char* keyword_; int counter_; Token::Value keyword_token_; }; } } // namespace v8::internal #endif // V8_SCANNER_BASE_H_
[ [ [ 1, 663 ] ] ]
9546dacb86379bec7ce36d12ce25d9678183bb30
1cf1543cd5460621f530f730a4f3969cfa74197c
/Node.h
a0c2e1eb1facf2365180c25fb1bc0f0726af4483
[]
no_license
derpepe/sysprog
042048d0c8f30fb26f0fb79a024530f67a852ca9
2fa6fb3b7c7f53b3fa8ff6aeb74d8d3e3331ba61
refs/heads/master
2021-01-18T14:01:45.742680
2010-02-23T22:23:25
2010-02-23T22:23:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
428
h
#pragma once #include "parserConst.h" #include "NodeInfo.h" #include <iostream> class Node { public: Node(NodeInfo *myInfo); NodeInfo *getInfo(); void setInfo(NodeInfo *myInfo); int getChildrenCount(); Node *addChild(Node* myChild); Node *getChild(int which); void print(); bool isLeave(); private: NodeInfo *myInfo; int childrenCount; Node *childNodes[MAX_CHILD_NODES]; };
[ [ [ 1, 29 ] ] ]
e2020028f89690a8e067541e47090fcd9f875e67
1d2705c9be9ee0f974c224eb794f2f8a9e9a3d50
/exploring_machine/main.cpp
7016001be76bbff00963aee257b4818c17a59ea8
[]
no_license
llvllrbreeze/alcorapp
dfe2551f36d346d73d998f59d602c5de46ef60f7
3ad24edd52c19f0896228f55539aa8bbbb011aac
refs/heads/master
2021-01-10T07:36:01.058011
2008-12-16T12:51:50
2008-12-16T12:51:50
47,865,136
0
0
null
null
null
null
UTF-8
C++
false
false
155
cpp
#include "alcor.apps\xpr\exploring_machine.h" using namespace all; int main() { xpr::exploring_machine machine; getchar(); return 0; }
[ "andrea.carbone@1ffd000b-a628-0410-9a29-793f135cad17" ]
[ [ [ 1, 11 ] ] ]
687c3ea78fff05e2f102f7954af33fe3b75ff4f1
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/techdemo2/engine/common/include/Tripel.h
cdcc86b6016a5d8f412b3887900bd56b69009c68
[ "ClArtistic", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
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,922
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 __RL_TRIPEL_H__ #define __RL_TRIPEL_H__ namespace rl { template<typename T> class Tripel { public: T first; T second; T third; Tripel() : first(), second(), third() { } Tripel(const T& t1, const T& t2, const T& t3) : first(t1), second(t2), third(t3) { } Tripel(const Tripel& rhs) : first(rhs.first), second(rhs.second), third(rhs.third) { } Tripel& operator=(const Tripel& rhs) { if(this != &rhs) { first = rhs.first; second = rhs.second; third = rhs.third; } return *this; } bool operator==(const Tripel& rhs) { return first == rhs.first && second == rhs.second && third == rhs.third; } bool operator<(const Tripel& rhs) { return first < rhs.first || (first == rhs.first && second < rhs.second) || (first == rhs.first && second == rhs.second && third < rhs.third); } }; } #endif
[ "tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 72 ] ] ]
2ec89ad4b9eab91160b99b1d605e332cfebdb359
d258dd0ca5e8678c8eb81777e5fe360b8bbf7b7e
/Library/PhysXCPP/NxaMath.cpp
5593066fe6f8c5944d4b3dedfd13f83eac11d229
[]
no_license
ECToo/physxdotnet
1e7d7e9078796f1dad5c8582d28441a908e11a83
2b85d57bc877521cdbf1a9147bd6716af68a64b0
refs/heads/master
2021-01-22T07:17:58.918244
2008-04-13T11:15:26
2008-04-13T11:15:26
32,543,781
0
0
null
null
null
null
UTF-8
C++
false
false
3,231
cpp
#include "StdAfx.h" #include "NxaMath.h" NxMat33 NxaMath::MatrixRotXNAToPhysX([In] Matrix% m) { pin_ptr<float> ptr = &(m.M11); NxMat33 mat; mat.setColumnMajorStride4(ptr); return mat; } NxMat34 NxaMath::MatrixRotPosXNAToPhysX([In] Matrix% m) { pin_ptr<float> ptr = &(m.M11); NxMat34 mat; mat.setColumnMajor44(ptr); return mat; } Matrix NxaMath::MatrixPhysXToXNA(const NxMat33& m) { Matrix val = Matrix::Identity; m.getColumnMajorStride4(&val.M11); return val; } Matrix NxaMath::MatrixPhysXToXNA(const NxMat34& m) { Matrix val = Matrix::Identity; m.getColumnMajor44(&val.M11); return val; } NxVec3 NxaMath::Vector3XNAToPhysX([In] Matrix% m) { return NxVec3(m.M41, m.M42, m.M43); } NxVec3 NxaMath::Vector3XNAToPhysX([In] Vector3% v) { return NxVec3(v.X, v.Y, v.Z); } Vector3 NxaMath::Vector3PhysXToXNA(const NxVec3 &v) { return Vector3(v.x, v.y, v.z); } void NxaMath::Vector3PhysXToXNA(const NxVec3 &v, [Out] Vector3% out) { out.X = v.x; out.Y = v.y; out.Z = v.z; } NxQuat NxaMath::QuaternionXNAToPhysX([In] Quaternion% q) { NxQuat quat; quat.x = q.X; quat.y = q.Y; quat.z = q.Z; quat.w = q.W; return quat; } Quaternion NxaMath::QuaternionPhysXToXNA(const NxQuat &q) { return Quaternion(q.x, q.y, q.z, q.w); } void NxaMath::QuaternionPhysXToXNA(const NxQuat &q, [Out] Quaternion% out) { out.X = q.x; out.Y = q.y; out.Z = q.z; out.W = q.w; } Vector3 NxaMath::TransformWorldPointToLocal([In] Matrix% m, [In] Vector3% point) { float numX = point.X - m.Translation.X; float numY = point.Y - m.Translation.Y; float numZ = point.Z - m.Translation.Z; float nX = (numX * m.M11) + (numY * m.M12) + (numZ * m.M13); float nY = (numY * m.M21) + (numY * m.M22) + (numZ * m.M23); float nZ = (numZ * m.M31) + (numY * m.M32) + (numZ * m.M33); return Vector3(nX, nY, nZ); } Vector3 NxaMath::TransformWorldNormalToLocal([In] Matrix% m, [In] Vector3% normal) { float nX = (normal.X * m.M11) + (normal.Y * m.M12) + (normal.Z * m.M13); float nY = (normal.X * m.M21) + (normal.Y * m.M22) + (normal.Z * m.M23); float nZ = (normal.X * m.M31) + (normal.Y * m.M32) + (normal.Z * m.M33); return Vector3(nX, nY, nZ); } Vector3 NxaMath::GetPerpendicularVector([In] Vector3% v) { Vector3 vec = Vector3(v.X * v.X, v.Y * v.Y, v.Z * v.Z); Vector3 vec2 = Vector3::UnitZ; if ((vec.X <= vec.Y) && (vec.X <= vec.Z)) { vec2 = Vector3::UnitX; } else if ((vec.Y <= vec.X) && (vec.Y <= vec.Z)) { vec2 = Vector3::UnitY; } Vector3 result; Vector3::Cross(v, vec2, result); result.Normalize(); return result; } NxExtendedVec3 NxaMath::Vector3XNAToExtendedPhysX([In] Vector3% v) { float x = v.X; float y = v.Y; float z = v.Z; NxExtendedVec3 vec; if(float::IsPositiveInfinity(x) || float::IsPositiveInfinity(y) || float::IsPositiveInfinity(z)) vec.setPlusInfinity(); else if(float::IsNegativeInfinity(x) || float::IsNegativeInfinity(y) || float::IsNegativeInfinity(z)) vec.setMinusInfinity(); else vec.set(v.X, v.Y, v.Z); return vec; } Vector3 NxaMath::Vector3ExtendedPhysXToXNA(const NxExtendedVec3& v) { return Vector3(v.x, v.y, v.z); }
[ "amiles@e8b6d1ee-b643-0410-9178-bfabf5f736f5", "thomasfannes@e8b6d1ee-b643-0410-9178-bfabf5f736f5" ]
[ [ [ 1, 108 ], [ 131, 131 ] ], [ [ 109, 130 ] ] ]
95f526d08529455902e319bddc0a004a3cf0fd3a
86c8c65dd5d7c07b46f134f6df76d5127e9428ff
/参考/ghy/Code/P012.cpp
50d8924a807b1ba3bbbf70edb2627b6af9a7b7fd
[]
no_license
kyokey/MIPT
2d2fc233475e414b33fe889594929be6af696b92
f0dcc64731deaf5d0f0949884865216c15c15dbe
refs/heads/master
2020-04-27T09:10:48.472859
2011-01-04T16:35:26
2011-01-04T16:35:26
1,219,926
0
0
null
null
null
null
UTF-8
C++
false
false
974
cpp
#include <iostream> #include <map> #include <vector> using namespace std; const int maxn = 1000; map<string, int> names; int defined[maxn], visit[maxn]; vector<int> ele[maxn]; bool DFS(int u) { visit[u] = 1; for (int i = 0, v; i < ele[u].size(); i ++) if (v = ele[u][i], visit[v] == 1 || DFS(v)) return 1; visit[u] = 2; return 0; }; int main() { int N, k; for (int i = 0; i < 1000; i ++) defined[i] = 0; cin >> N; names.clear(); int y = 1, m = 0; while (N--) { string term, st; cin >> term >> k; if (!names.count(term)) names[term] = m++; if (defined[names[term]]) y = 0; defined[names[term]] = 1; while (k--) { cin >> st; if (!names.count(st)) names[st] = m++; ele[names[term]].push_back(names[st]); }; }; for (int i = 0; i < m; i ++) visit[i] = 0; for (int i = 0; i < m; i ++) if (!visit[i] && DFS(i)) y = 0; if (y) cout << "CORRECT\n"; else cout << "NOT CORRECT\n"; }
[ "pq@pq-laptop.(none)" ]
[ [ [ 1, 48 ] ] ]
30a026126faa1362ef75a0dc37d6b43adf79c2c7
4bc2bc854b8a69dd8af8a1473ac5a4c375834aba
/model3d.h
ccd1e2fead4bc595c9329be7eb1f98d25d3f2713
[]
no_license
joshmg/modeler
e81f6b733728020554a90a4b7fcc6ec7a7a2991d
e1ab30b242636f2186922e056b9a4859b548c046
refs/heads/master
2021-01-23T13:37:02.936790
2010-11-21T08:53:29
2010-11-21T08:53:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,574
h
// File: model3d.h // Written by Joshua Green #ifndef MODEL3D_H #define MODEL3D_H #include "vectXf.h" #include <vector> #include <string> #include <GL/gl.h> const vect3f DEFAULT_COLOR(1.0f, 0.0f, 1.0f); struct facet { int id; vect3f color; mutable vect3f normal; facet(); facet(int _id, const vect3f& _color, const vect3f& _normal=vect3f(0.0, 0.0, 1.0)); }; struct index2d { int data[2]; index2d() { clear(); } index2d(int a, int b) { data[0] = a; data[1] = b; } index2d(const int* const ab) { data[0] = ab[0]; data[1] = ab[1]; } void clear() { data[0] = -1; data[1] = -1; } int& operator[](int i) { return data[i]; } const int& operator[](int i) const { return data[i]; } operator int* () { return data; } operator const int* () const { return data; } }; class model3d { private: inline static std::string SAVE_FILE_HEADER() { return std::string("model3d="); } GLenum _draw_mode; std::vector<vect3f> _coordinates; std::vector<std::vector<facet>> _facet_data; int _vertex_count; bool _need_normals; std::vector<model3d> _sub_models; vect3f _pos, _axis; float _orientation, _new_orientation, _old_orientation; bool _smart_rotate, _anchored, _child_animate_flag; int _speed; void _initialize(); int _get_facet_id(const vect3f& point) const; template <typename T> bool _in_bounds(const int* const indices, const std::vector<std::vector<T>>& vect) const; void _calculate_normals() const; bool _use_draw_funcs; void (*_pre_draw)(const model3d&); void (*_post_draw)(const model3d&); public: bool set_material; vect4f diffuse, specular, shine; model3d(); model3d(const std::vector<vect3f>& coordinates, const std::vector<std::vector<facet>>& facets); void clear(); void enable_draw_funcs(void (*pre)(const model3d&), void (*post)(const model3d&)); void disable_draw_funcs(); std::vector<vect3f> get_coordinates() const; const std::vector<vect3f>* const get_coordinates_ptr() const; std::vector<std::vector<facet>> get_facet_data() const; const std::vector<std::vector<facet>>* const get_facet_data_ptr() const; GLenum get_draw_mode() const; void set_draw_mode(GLenum); void set_vertex_color(const int* const vertex_id, const vect3f& color); vect3f get_vertex_color(const int* const vertex_id) const; index2d add_vertex(const vect3f& point, const vect3f& color=DEFAULT_COLOR, const vect3f* const normal=0); void edit_coord(int coord_id, const vect3f& point); void edit_vertex(const int* const vertex_id, const facet& vertex); void remove_vertex(const int* const vertex_id); // int vertex_id[2] (indexing into a two-dimensional array) void push_face(); void pop_face(); void recalculate_normals() const; void face_resolution(int polygon_count); int vertex_count() const; void save(std::string& filename=std::string()) const; // produces filename if filename has zero length to the saved file name bool load(const std::string& filename); void set_pos(const vect3f& pos); vect3f get_pos() const; void add_submodel(const model3d& child); void anchor(bool t=true); void set_axis(const vect3f& axis); void set_orientation(float theta); void enable_smart_rotate(bool t=true); void set_speed(float s); void toggle_child_animations(); void operator++(int); void draw() const; }; #endif
[ [ [ 1, 119 ] ] ]
21489f52ca2a49a2afdcb600cb55a5d5b3359ef9
e8d9619e262531453688550db22d0e78f1b51dab
/ping_protocol/pinglist.cpp
9cebcfc33ee6f85a5957a35030f9dddcbc4b512d
[]
no_license
sje397/sje-miranda-plugins
e9c562f402daef2cfbe333ce9a8a888cd81c9573
effb7ea736feeab1c68db34a86da8a2be2b78626
refs/heads/master
2016-09-05T16:42:34.162442
2011-05-22T14:48:15
2011-05-22T14:48:15
1,784,020
2
1
null
null
null
null
UTF-8
C++
false
false
8,031
cpp
#include "stdafx.h" #include "pinglist.h" #include "options.h" PINGLIST list_items; CRITICAL_SECTION list_cs; HANDLE reload_event_handle; BOOL clist_handle_changing = FALSE; BOOL changing_clist_handle() { return clist_handle_changing; } void set_changing_clist_handle(BOOL flag) { clist_handle_changing = flag; } // lParam is address of pointer to a std::list<PINGADDRESS> // copies data into this structure int GetPingList(WPARAM wParam,LPARAM lParam) { PINGLIST *pa = (PINGLIST *)lParam; EnterCriticalSection(&list_cs); *pa = list_items; LeaveCriticalSection(&list_cs); return 0; } void reset_myhandle() { EnterCriticalSection(&list_cs); set_changing_clist_handle(true); for(PINGLIST::iterator i = list_items.begin(); i != list_items.end(); i++) { DBWriteContactSettingString(i->hContact, "CList", "MyHandle", i->pszLabel); } set_changing_clist_handle(false); LeaveCriticalSection(&list_cs); } void write_ping_address(PINGADDRESS *i) { bool is_contact = (bool)(CallService(MS_DB_CONTACT_IS, (WPARAM)i->hContact, 0) != 0); if(!is_contact) { //MessageBox(0, "Creating contact", "Ping", MB_OK); i->hContact = (HANDLE)CallService(MS_DB_CONTACT_ADD, 0, 0); CallService( MS_PROTO_ADDTOCONTACT, ( WPARAM )i->hContact, ( LPARAM )PROTO ); CallService(MS_IGNORE_IGNORE, (WPARAM)i->hContact, (WPARAM)IGNOREEVENT_USERONLINE); } DBWriteContactSettingString(i->hContact, PROTO, "Address", i->pszName); set_changing_clist_handle(TRUE); DBWriteContactSettingString(i->hContact, "CList", "MyHandle", i->pszLabel); set_changing_clist_handle(FALSE); DBWriteContactSettingString(i->hContact, PROTO, "Nick", i->pszLabel); DBWriteContactSettingWord(i->hContact, PROTO, "Status", i->status); DBWriteContactSettingDword(i->hContact, PROTO, "Port", i->port); DBWriteContactSettingString(i->hContact, PROTO, "Proto", i->pszProto); if(strlen(i->pszCommand)) DBWriteContactSettingString(i->hContact, PROTO, "Command", i->pszCommand); else DBDeleteContactSetting(i->hContact, PROTO, "Command"); if(strlen(i->pszParams)) DBWriteContactSettingString(i->hContact, PROTO, "CommandParams", i->pszParams); else DBDeleteContactSetting(i->hContact, PROTO, "CommandParams"); DBWriteContactSettingWord(i->hContact, PROTO, "SetStatus", i->set_status); DBWriteContactSettingWord(i->hContact, PROTO, "GetStatus", i->get_status); DBWriteContactSettingWord(i->hContact, PROTO, "Index", i->index); if(strlen(i->pszCListGroup)) DBWriteContactSettingString(i->hContact, "CList", "Group", i->pszCListGroup); else DBDeleteContactSetting(i->hContact, "CList", "Group"); } // call with list_cs locked void write_ping_addresses() { int index = 0; for(PINGLIST::iterator i = list_items.begin(); i != list_items.end(); i++, index++) { i->index = index; write_ping_address(&(*i)); } } void read_ping_address(PINGADDRESS &pa) { DBVARIANT dbv; DBGetContactSetting(pa.hContact, PROTO, "Address", &dbv); strncpy(pa.pszName, dbv.pszVal, MAX_PINGADDRESS_STRING_LENGTH); DBFreeVariant(&dbv); if(!DBGetContactSetting(pa.hContact, PROTO, "Nick", &dbv)) { strncpy(pa.pszLabel, dbv.pszVal, MAX_PINGADDRESS_STRING_LENGTH); DBFreeVariant(&dbv); set_changing_clist_handle(TRUE); DBWriteContactSettingString(pa.hContact, "CList", "MyHandle", pa.pszLabel); set_changing_clist_handle(FALSE); } else { if(!DBGetContactSetting(pa.hContact, PROTO, "Label", &dbv)) { strncpy(pa.pszLabel, dbv.pszVal, MAX_PINGADDRESS_STRING_LENGTH); DBFreeVariant(&dbv); set_changing_clist_handle(TRUE); DBWriteContactSettingString(pa.hContact, "CList", "MyHandle", pa.pszLabel); set_changing_clist_handle(FALSE); DBWriteContactSettingString(pa.hContact, PROTO, "Nick", pa.pszLabel); DBDeleteContactSetting(pa.hContact, PROTO, "Label"); } else { if(!DBGetContactSetting(pa.hContact, "CList", "MyHandle", &dbv)) { strncpy(pa.pszLabel, dbv.pszVal, MAX_PINGADDRESS_STRING_LENGTH); DBFreeVariant(&dbv); } else pa.pszLabel[0] = '\0'; } } pa.status = DBGetContactSettingWord(pa.hContact, PROTO, "Status", options.nrstatus); pa.port = (int)DBGetContactSettingDword(pa.hContact, PROTO, "Port", (DWORD)-1); if(!DBGetContactSetting(pa.hContact, PROTO, "Proto", &dbv)) { strncpy(pa.pszProto, dbv.pszVal, MAX_PINGADDRESS_STRING_LENGTH); DBFreeVariant(&dbv); } else pa.pszProto[0] = '\0'; if(!DBGetContactSetting(pa.hContact, PROTO, "Command", &dbv)) { strncpy(pa.pszCommand, dbv.pszVal, MAX_PATH); DBFreeVariant(&dbv); } else pa.pszCommand[0] = '\0'; if(!DBGetContactSetting(pa.hContact, PROTO, "CommandParams", &dbv)) { strncpy(pa.pszParams, dbv.pszVal, MAX_PATH); DBFreeVariant(&dbv); } else pa.pszParams[0] = '\0'; pa.set_status = DBGetContactSettingWord(pa.hContact, PROTO, "SetStatus", ID_STATUS_ONLINE); pa.get_status = DBGetContactSettingWord(pa.hContact, PROTO, "GetStatus", ID_STATUS_OFFLINE); pa.responding = false; pa.round_trip_time = 0; pa.miss_count = 0; pa.index = DBGetContactSettingWord(pa.hContact, PROTO, "Index", 0); if(!DBGetContactSetting(pa.hContact, "CList", "Group", &dbv)) { strncpy(pa.pszCListGroup, dbv.pszVal, MAX_PINGADDRESS_STRING_LENGTH); DBFreeVariant(&dbv); } else pa.pszCListGroup[0] = '\0'; } // call with list_cs locked void read_ping_addresses() { HANDLE hContact = ( HANDLE )CallService( MS_DB_CONTACT_FINDFIRST, 0, 0 ); PINGADDRESS pa; list_items.clear(); while ( hContact != NULL ) { char *proto = ( char* )CallService( MS_PROTO_GETCONTACTBASEPROTO, ( WPARAM )hContact,0 ); if ( proto && lstrcmp( PROTO, proto) == 0) { pa.hContact = hContact; read_ping_address(pa); list_items.push_back(pa); } hContact = ( HANDLE )CallService( MS_DB_CONTACT_FINDNEXT,( WPARAM )hContact, 0 ); } std::sort(list_items.begin(), list_items.end(), SAscendingSort()); } int LoadPingList(WPARAM wParam, LPARAM lParam) { EnterCriticalSection(&list_cs); read_ping_addresses(); LeaveCriticalSection(&list_cs); NotifyEventHooks(reload_event_handle, 0, 0); return 0; } // wParam is zero // lParam is zero int SavePingList(WPARAM wParam, LPARAM lParam) { EnterCriticalSection(&list_cs); write_ping_addresses(); LeaveCriticalSection(&list_cs); NotifyEventHooks(reload_event_handle, 0, 0); return 0; } // wParam is address of a PINGLIST structure to replace the current one // lParam is zero int SetPingList(WPARAM wParam, LPARAM lParam) { PINGLIST *pli = (PINGLIST *)wParam; EnterCriticalSection(&list_cs); list_items = *pli; LeaveCriticalSection(&list_cs); NotifyEventHooks(reload_event_handle, 0, 0); return 0; } // wParam is address of a PINGLIST structure to replace the current one // lParam is zero int SetAndSavePingList(WPARAM wParam, LPARAM lParam) { PINGLIST *pli = (PINGLIST *)wParam; EnterCriticalSection(&list_cs); // delete items that aren't in the new list bool found; for(PINGLIST::iterator i = list_items.begin(); i != list_items.end(); i++) { found = false; for(PINGLIST::iterator j = pli->begin(); j != pli->end(); j++) { if(i->hContact == j->hContact) { found = true; break; } } if(!found) { //MessageBox(0, "Deleting contact", "Ping", MB_OK); // remove prot first, so that our contact deleted event handler isn't activated CallService(MS_PROTO_REMOVEFROMCONTACT, (WPARAM)i->hContact, (LPARAM)PROTO); CallService(MS_DB_CONTACT_DELETE, (WPARAM)i->hContact, 0); } } // set new list if(pli->size()) list_items = *pli; else list_items.clear(); write_ping_addresses(); LeaveCriticalSection(&list_cs); NotifyEventHooks(reload_event_handle, 0, 0); return 0; } int ClearPingList(WPARAM wParam, LPARAM lParam) { EnterCriticalSection(&list_cs); list_items.clear(); LeaveCriticalSection(&list_cs); NotifyEventHooks(reload_event_handle, 0, 0); return 0; }
[ [ [ 1, 249 ] ] ]
dc0d9191b5344d5516871e31f1b27af6b516bcfd
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/_统计专用/C++Primer中文版(第4版)/第一次-代码集合-20090414/第十四章 重载操作符与转换/20090221_习题14.26_为CheckedPtr类定义加法和减法操作符.cpp
959241158116f4eea1955f917ee81176b9acfd8a
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
547
cpp
CheckedPtr operator+(const CheckedPtr& lhs, const size_t n) { CheckedPtr temp(lhs); temp.curr += n; if (temp.curr > temp.end) throw out_of_range("too large n"); return temp; } CheckedPtr operator-(const CheckedPtr& lhs, const size_t n) { CheckedPtr temp(lhs); temp.curr -= n; if (temp.curr < temp.beg) throw out_of_range("too large n"); return temp; } ptrdiff_t operator-(CheckedPtr& lhs, CheckedPtr& rhs) { if (!(lhs.beg == rhs.beg && lhs.end == rhs.end)) throw out_of_range("too large n"); return temp; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 24 ] ] ]
43dd90fc4794076887b32fdd99748fde89ad196e
54319da8732c447b8f196de5e98293083d3acf10
/qt4_src/src/fxEncrypt.cpp
3b3248ec339d7c8a0eef8febff09a358d0894712
[ "curl" ]
permissive
libfetion/libfetion-gui
6c0ed30f9b31669048347352b292fbe02e5505f3
a5912c7ac301830c2953378e58a4d923bc0a0a8d
refs/heads/master
2021-01-13T02:16:46.031301
2010-09-19T10:42:37
2010-09-19T10:42:37
32,465,618
2
0
null
null
null
null
UTF-8
C++
false
false
20,202
cpp
#include <string.h> #include <stdlib.h> #include "fxEncrypt.h" #include "fxdb.h" enum { ENCRYPT = 0, DECRYPT }; /* Type:ENCRYPT, DECRYPT * the length of the output buffer isn't smaller * than ((datalen+7)/8)*8 * input buffer and output buffer may be the same. * encrypt plain text by 3DES when keylen > 8 */ bool DES(char *Out, char *In, long datalen, const char *Key, int keylen, bool Type); /* initial permutation IP */ const static char IP_Table[64] = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 }; /* final permutation IP^-1 */ const static char IPR_Table[64] = { 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 }; /* expansion operation matrix */ static const char E_Table[48] = { 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 }; /* 32-bit permutation function P used on the output of the S-boxes */ const static char P_Table[32] = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; /* permuted choice table (key) */ const static char PC1_Table[56] = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 }; /* permuted choice key (table) */ const static char PC2_Table[48] = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 }; /* number left rotations of pc1 */ const static char LOOP_Table[16] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; /* The (in)famous S-boxes */ const static char S_Box[8][4][16] = { {// S1 {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13} }, {// S2 {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9} }, {// S3 {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12} }, {// S4 {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14} }, {// S5 {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3} }, {// S6 {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13} }, {// S7 {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12} }, { // S8 {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11} } }; typedef bool(*PSubKey)[16][48]; static void Des(char Out[8], char In[8], const PSubKey pSubKey, bool Type); /* standard DES */ static void SetKey(const char *Key, int len); static void SetSubKey(PSubKey pSubKey, const char Key[8]); /* F function */ static void F_func(bool In[32], const bool Ki[48]); /* S box function */ static void S_func(bool Out[32], const bool In[48]); static void Transform(bool *Out, bool *In, const char *Table, int len); static void Xor(bool *InA, const bool *InB, int len); static void RotateL(bool *In, int len, int loop); /* compose byte to bits */ static void ByteToBit(bool *Out, const char *In, int bits); static void BitToByte(char *Out, const bool *In, int bits); static bool SubKey[2][16][48]; /* triple DES */ static bool Is3DES; static char Tmp[256], deskey[16]; bool DES(char *Out, char *In, long datalen, const char *Key, int keylen, bool Type) { if (!(Out && In && Key && (datalen = (datalen + 7) &0xfffffff8))) { return false; } SetKey(Key, keylen); if (!Is3DES) { /* DES */ for (long i = 0, j = datalen >> 3; i < j; ++i, Out += 8, In += 8) { Des(Out, In, &SubKey[0], Type); } } else { /* triple DES: EDE-DED */ for (long i = 0, j = datalen >> 3; i < j; ++i, Out += 8, In += 8) { Des(Out, In, &SubKey[0], Type); Des(Out, Out, &SubKey[1], !Type); Des(Out, Out, &SubKey[0], Type); } } return 0; } /**************************************************************************/ /* */ /**************************************************************************/ void SetKey(const char *Key, int len) { memset(deskey, 0, 16); memcpy(deskey, Key, len > 16 ? 16 : len); SetSubKey(&SubKey[0], &deskey[0]); Is3DES = len > 8 ? (SetSubKey(&SubKey[1], &deskey[8]), 0): - 1; } /**************************************************************************/ /* */ /**************************************************************************/ void Des(char Out[8], char In[8], const PSubKey pSubKey, bool Type) { static bool M[64], tmp[32], *Li = &M[0], *Ri = &M[32]; ByteToBit(M, In, 64); Transform(M, M, IP_Table, 64); if (Type == ENCRYPT) { for (int i = 0; i < 16; ++i) { memcpy(tmp, Ri, 32); F_func(Ri, (*pSubKey)[i]); Xor(Ri, Li, 32); memcpy(Li, tmp, 32); } } else { for (int i = 15; i >= 0; --i) { memcpy(tmp, Li, 32); F_func(Li, (*pSubKey)[i]); Xor(Li, Ri, 32); memcpy(Ri, tmp, 32); } } Transform(M, M, IPR_Table, 64); BitToByte(Out, M, 64); } /**************************************************************************/ /* */ /**************************************************************************/ void SetSubKey(PSubKey pSubKey, const char Key[8]) { static bool K[64], *KL = &K[0], *KR = &K[28]; ByteToBit(K, Key, 64); Transform(K, K, PC1_Table, 56); for (int i = 0; i < 16; ++i) { RotateL(KL, 28, LOOP_Table[i]); RotateL(KR, 28, LOOP_Table[i]); Transform((*pSubKey)[i], K, PC2_Table, 48); } } /**************************************************************************/ /* */ /**************************************************************************/ void F_func(bool In[32], const bool Ki[48]) { static bool MR[48]; Transform(MR, In, E_Table, 48); Xor(MR, Ki, 48); S_func(In, MR); Transform(In, In, P_Table, 32); } /**************************************************************************/ /* */ /**************************************************************************/ void S_func(bool Out[32], const bool In[48]) { for (quint32 i = 0, j, k; i < 8; ++i, In += 6, Out += 4) { j = (In[0] << 1) + In[5]; k = (In[1] << 3) + (In[2] << 2) + (In[3] << 1) + In[4]; ByteToBit(Out, &S_Box[i][j][k], 4); } } /**************************************************************************/ /* */ /**************************************************************************/ void Transform(bool *Out, bool *In, const char *Table, int len) { for (int i = 0; i < len; ++i) { Tmp[i] = In[Table[i] - 1]; } memcpy(Out, Tmp, len); } /**************************************************************************/ /* */ /**************************************************************************/ void Xor(bool *InA, const bool *InB, int len) { for (int i = 0; i < len; ++i) { InA[i] ^= InB[i]; } } /**************************************************************************/ /* */ /**************************************************************************/ void RotateL(bool *In, int len, int loop) { memcpy(Tmp, In, loop); memcpy(In, In + loop, len - loop); memcpy(In + len - loop, Tmp, loop); } /**************************************************************************/ /* */ /**************************************************************************/ void ByteToBit(bool *Out, const char *In, int bits) { for (int i = 0; i < bits; ++i) { Out[i] = (In[i >> 3] >> (i &7)) &1; } } /**************************************************************************/ /* */ /**************************************************************************/ void BitToByte(char *Out, const bool *In, int bits) { memset(Out, 0, bits >> 3); for (int i = 0; i < bits; ++i) { Out[i >> 3] |= In[i] << (i &7); } } /**************************************************************************/ /* */ /**************************************************************************/ static char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int base64_encode(const void *data, int size, char **str) { char *s, *p; int i; int c; const unsigned char *q; p = s = (char*)malloc(size *4 / 3+4); if (p == NULL) { return - 1; } q = (const unsigned char*)data; i = 0; for (i = 0; i < size;) { c = q[i++]; c *= 256; if (i < size) { c += q[i]; } i++; c *= 256; if (i < size) { c += q[i]; } i++; p[0] = base64_chars[(c &0x00fc0000) >> 18]; p[1] = base64_chars[(c &0x0003f000) >> 12]; p[2] = base64_chars[(c &0x00000fc0) >> 6]; p[3] = base64_chars[(c &0x0000003f) >> 0]; if (i > size) { p[3] = '='; } if (i > size + 1) { p[2] = '='; } p += 4; } *p = 0; *str = s; return strlen(s); } /**************************************************************************/ /* */ /**************************************************************************/ static int pos(char c) { char *p; for (p = base64_chars; *p; p++) if (*p == c) { return p - base64_chars; } return - 1; } /**************************************************************************/ /* */ /**************************************************************************/ #define DECODE_ERROR 0xffffffff static unsigned int token_decode(const char *token) { int i; unsigned int val = 0; int marker = 0; if (strlen(token) < 4) { return DECODE_ERROR; } for (i = 0; i < 4; i++) { val *= 64; if (token[i] == '=') { marker++; } else if (marker > 0) { return DECODE_ERROR; } else { val += pos(token[i]); } } if (marker > 2) { return DECODE_ERROR; } return (marker << 24) | val; } /**************************************************************************/ /* */ /**************************************************************************/ int base64_decode(const char *str, void *data) { const char *p; unsigned char *q; q = (unsigned char*)data; for (p = str; *p && (*p == '=' || strchr(base64_chars, *p)); p += 4) { unsigned int val = token_decode(p); unsigned int marker = (val >> 24) &0xff; if (val == DECODE_ERROR) { return - 1; } *q++ = (val >> 16) &0xff; if (marker < 2) { *q++ = (val >> 8) &0xff; } if (marker < 1) { *q++ = val &0xff; } } return q - (unsigned char*)data; } /**************************************************************************/ /* */ /**************************************************************************/ char *decryptXOR(const char *str, unsigned int str_len, const char *key) { if (!str || !key) { return NULL; } char *data = (char*)malloc(sizeof(char) *str_len); if (!data) { return NULL; } //no memory if (base64_decode(str, data) == - 1) { free(data); return NULL; } char *res = (char*)malloc(str_len + 1); unsigned int i, j; for (i = 0; i < str_len; i++) { for (j = 0; j < strlen(key); j++) { res[i] = key[j] ^ data[i]; } } res[str_len] = '\0'; free(data); return res; } /**************************************************************************/ /* */ /**************************************************************************/ char *encryptXOR(const char *str, unsigned int str_len, const char *key) { if (!str || !key) { return NULL; } char *XOR = NULL; char *res = (char*)malloc(str_len); unsigned int i, j; for (i = 0; i < str_len; i++) { for (j = 0; j < strlen(key); j++) { res[i] = str[i] ^ key[j]; } } int len = base64_encode(res, str_len, &XOR); XOR[len] = '\0'; free(res); return XOR; } /**************************************************************************/ /* */ /**************************************************************************/ char *fillcode(const char *str) { char *base64 = NULL; int str_len = strlen(str); int len = (((str_len + 7) >> 3) << 3); char *res = (char*)malloc(sizeof(char) *len); if (!res) { return NULL; } memcpy(res, str, len); //fix a bug of windows... for (int i = len - (str_len + 1); i >= 0; i--) { res[str_len + i] = 'A' - 66; } base64_encode(res, len, &base64); if (res) { free(res); } return base64; } /**************************************************************************/ /* */ /**************************************************************************/ char *resolvecode(const char *str) { int i; int len = strlen(str); char *base64 = (char*)malloc(sizeof(char) *len + 1); if (!base64) { return NULL; } //no memory int base_res = base64_decode(str, base64); if (base_res == - 1) { free(base64); return NULL; } base64[base_res] = '\0'; //printf("getNu is len is %d,base64 [%s]\n",len, base64); for (i = 0; i < len; i++) { if (base64[i] == 'A' - 66) { base64[i] = '\0'; return base64; } } base64[i] = '\0'; return base64; } /**************************************************************************/ /* */ /**************************************************************************/ char *DES_3(const char *data, long datalen, bool isEncry) { char *encry_data = (char*)data; char *tmp = NULL; char *res = NULL; if (!isEncry) { if (!(tmp = (char*)malloc(sizeof(char) *datalen))) { return NULL; } //no memory if (base64_decode(data, tmp) == - 1) { free(tmp); return NULL; } encry_data = tmp; } //int outLen = ((datalen+ 7)>>3)<<3; int outLen = ((strlen(encry_data) + 7) >> 3) << 3; char *out = (char*)malloc(sizeof(char) *outLen); if (!out) //fprintf(stderr, "out of the memory\n"); { return NULL; } //DES(out, encry_data, datalen, KEY, strlen(KEY), isEncry); DES(out, encry_data, strlen(encry_data), KEY, strlen(KEY), isEncry); //out[outLen] = '\0'; if (isEncry) { base64_encode(out, outLen, &res); } else { if (tmp) { free(tmp); } res = out; } return res; } /**************************************************************************/ /* */ /**************************************************************************/ char *encryPWD(const char *data, long datalen, bool isEncry) { if (isEncry) { return encryptXOR(data, (unsigned int)datalen, (const char*)KEY); } else { return decryptXOR(data, (unsigned int)datalen, (const char*)KEY); } } /**************************************************************************/ /* */ /**************************************************************************/ #if 0 int main() { char str[] = "你好中国 <> // // \\!!@! \" sadasd"; //char str[] = "sdfsdfsdf"; char *key = "www.libfetion.cn"; char *res = encryptXOR(str, strlen(str), key); printf("res is %s !!!!\n", res); printf("decode %s \n", decryptXOR(res, strlen(res), key)); return 0; } #endif
[ "alsor.zhou@3dff0f8e-6350-0410-ad39-8374e07577ec", "libfetion@3dff0f8e-6350-0410-ad39-8374e07577ec" ]
[ [ [ 1, 76 ], [ 136, 164 ], [ 166, 676 ], [ 678, 680 ], [ 682, 703 ] ], [ [ 77, 135 ], [ 165, 165 ], [ 677, 677 ], [ 681, 681 ] ] ]
a8c2eca3144a95b798573b2ba13dd958a062c2dd
9ef88cf6a334c82c92164c3f8d9f232d07c37fc3
/Libraries/QuickGUI/include/QuickGUIBrush.h
1a810161270d807bcecebbaf397fa3e371bfd97a
[]
no_license
Gussoh/bismuthengine
eba4f1d6c2647d4b73d22512405da9d7f4bde88a
4a35e7ae880cebde7c557bd8c8f853a9a96f5c53
refs/heads/master
2016-09-05T11:28:11.194130
2010-01-10T14:09:24
2010-01-10T14:09:24
33,263,368
0
0
null
null
null
null
UTF-8
C++
false
false
7,463
h
#ifndef QUICKGUIBRUSH_H #define QUICKGUIBRUSH_H #include "QuickGUIBrushEnums.h" #include "QuickGUIException.h" #include "QuickGUIExportDLL.h" #include "QuickGUIRect.h" #include "QuickGUIUVRect.h" #include "QuickGUIOgreEquivalents.h" #include "OgreColourValue.h" #include "OgreHardwareBufferManager.h" #include "OgreHardwarePixelBuffer.h" #include "OgreHardwareVertexBuffer.h" #include "OgreRenderOperation.h" #include "OgreRenderSystem.h" #include "OgreRoot.h" #include "OgreSingleton.h" #include "OgreTexture.h" #include "OgreTextureManager.h" #include "OgreTextureUnitState.h" #include <vector> namespace QuickGUI { // forward declarations class Root; class SkinElement; struct Vertex; // 2730 = 65536 bytes / 24 bytes per vertex. (~64kb allocated for vertex buffer) //const int DEFAULT_VERTEX_BUFFER_SIZE = 2730; const int VERTEX_COUNT = 3072; /* * The brush class represents the tool required to draw 2d textures to the screen. */ class _QuickGUIExport Brush : public Ogre::Singleton<Brush>, public Ogre::GeneralAllocatedObject { public: friend class Root; public: static Brush& getSingleton(void); static Brush* getSingletonPtr(void); /** * Allows Lines to be Queued for drawing all at once. */ void beginLineQueue(); /** * Allows Rects to be Queued for drawing all at once. */ void beginRectQueue(); /** * Clears the current target using the current color */ void clear(); /** * Draws a line */ void drawLine(const Point& p1, const Point& p2); /** * Draws a line */ void drawLine(const Point& p1, const Point& p2, const ColourValue& cv); /** * Draws a rectangle made of lines */ void drawLineRectangle(const Rect& r); /** * Draws the currently set texture to the Render Target. The uv coordinates define * the portion of the currently set texture to draw to the rectangle area. Texture * is stretched to fit the dimensions. */ void drawRectangle(Rect r, UVRect ur, int rotationInDegrees = 0, Point origin = Point::ZERO); /** * Draws the SkinElement to the Render Target. The texture drawn is supplied by the * Skin Element. The Skin Element also defines border thickness, which is drawn as expected. */ void drawSkinElement(Rect r, SkinElement* e, int rotationInDegrees = 0, Point origin = Point::ZERO); /** * Draws a tiled texture, defined by the uv coordinates, within the provided rectangle area. */ void drawTiledRectangle(Rect r, UVRect ur, int rotationInDegrees = 0, Point origin = Point::ZERO); /** * Renders all lines queued for drawing. (1 batch) */ void endLineQueue(); /** * Renders all rects queued for drawing. (1 batch) */ void endRectQueue(); /** * Gets the blend mode to use. (See BrushBlendMode) */ BrushBlendMode getBlendMode(); /** * Gets the current clip region rectangle, in pixels */ Rect getClipRegion(); /** * Gets the current color used for drawing operations. */ ColourValue getColour(); /** * Gets filtering mode used for drawing. */ BrushFilterMode getFilterMode(); /** * Gets the opacity used to draw future elements on the render target. */ float getOpacity(); /** * Gets the target currently being drawn to. */ Ogre::Viewport* getRenderTarget(); /** * Retrieves the current texture used for drawing operations. */ Ogre::TexturePtr getTexture(); /** * Configures the Rendering system preparing it to draw in 2D. Must be called * every frame, before any 2D drawing is done. */ void prepareToDraw(); /** * Queues a line for drawing. */ void queueLine(Point p1, Point p2); /** * Queues a line for drawing. */ void queueLine(Point p1, Point p2, const ColourValue& cv); /** * Queues a non-tiled rectangle for drawing. All Queued rects * will have the same texture. */ void queueRect(Rect r, UVRect ur, int rotationInDegrees = 0, Point origin = Point::ZERO); /** * Restores rendering system configuration. Called after all drawing operations * for the given frame. */ void restore(); /** * Sets the blend mode to use. (See BrushBlendMode) */ void setBlendMode(BrushBlendMode m); /** * Sets the current color to draw with */ void setColor(const ColourValue& cv); /** * Sets the current clip region rectangle, in pixels */ void setClipRegion(const Rect& r); /** * Sets the filtering mode to use (See BrushFilterMode) */ void setFilterMode(BrushFilterMode m); /** * Sets the opacity of future elements drawn on the render target. */ void setOpacity(float opacity); /** * This function specifies where to draw to. */ void setRenderTarget(Ogre::TexturePtr p); /** * This function specifies where to draw to. If NULL is passed in, the * default viewport is written to. */ void setRenderTarget(Ogre::Viewport* vp); /** * Sets the current texture to draw with */ void setTexture(const Ogre::String& textureName); /** * Sets the current texture to draw with */ void setTexture(Ogre::TexturePtr p); /** * Updates the SceneManager, used to render any Materials. */ void updateSceneManager(Ogre::SceneManager* sceneManager); /** * Updates the viewport initially drawn to at the beginning of every frame. */ void updateViewport(Ogre::Viewport* viewport); protected: Ogre::RenderSystem* mRenderSystem; Ogre::SceneManager* mSceneManager; Ogre::Viewport* mDefaultViewport; // Used to set the pass before rendering. Ogre::Pass* mGUIPass; Ogre::MaterialPtr mGUIMaterial; Ogre::Viewport* mRenderTarget; float mTargetWidth; float mTargetHeight; Ogre::HardwareVertexBufferSharedPtr mVertexBuffer; Ogre::RenderOperation mRenderOperation; Ogre::TexturePtr mDefaultTexture; /// Texture used for draw operations. Ogre::TexturePtr mTexture; ColourValue mColourValue; Rect mClipRegion; /// Cache Data Ogre::TextureUnitState::UVWAddressingMode mTextureAddressMode; //we cache this to save cpu time bool mUsingOpenGL; float mHorizontalTexelOffset; float mVerticalTexelOffset; /// member to keep track of whether or not we are queuing rects or lines for rendering bool mQueuedItems; Vertex* mBufferPtr; private: Brush(); ~Brush(); BrushFilterMode mFilterMode; BrushBlendMode mBrushBlendMode; void _createVertexBuffer(); /* * Define the size and data types that form a *Vertex*, to be used in the VertexBuffer. * NOTE: For ease of use, we define a structure QuickGUI::Vertex, with the same exact data types. */ void _declareVertexStructure(); void _destroyVertexBuffer(); // Vertex functions /** * Populates and fills vertex information for rendering. * NOTE: verts should be arrays of size 2. */ void _buildLineVertices(const Point& p1, const Point& p2, Vector3* verts); /* * Populates and fills vertex and uv information for rendering. * NOTE: verts and uv should be arrays of size 6. */ void _buildQuadVertices(const Rect& dimensions, const UVRect& uvCoords, Vector3* verts, Vector2* uv, int rotationInDegrees = 0, Point origin = Point::ZERO); void _rotatePoint(Vector3& v3, int rotationInDegrees, const Point& origin); }; } #endif
[ "rickardni@aefdbfa2-c794-11de-8410-e5b1e99fc78e" ]
[ [ [ 1, 272 ] ] ]
2a7a755bd027eb61457dda0b4df0304f10afa901
2b80036db6f86012afcc7bc55431355fc3234058
/src/cube/TransportController.cpp
46e0635d3eb7da42b335e3f2bcfca53bcf131155
[ "BSD-3-Clause" ]
permissive
leezhongshan/musikcube
d1e09cf263854bb16acbde707cb6c18b09a0189f
e7ca6a5515a5f5e8e499bbdd158e5cb406fda948
refs/heads/master
2021-01-15T11:45:29.512171
2011-02-25T14:09:21
2011-02-25T14:09:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,183
cpp
////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright 2007, musikCube team // // Sources and Binaries of: mC2, win32cpp // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "pch.hpp" #include <cube/TransportController.hpp> #include <cube/TransportView.hpp> #include <core/PlaybackQueue.h> #include <win32cpp/ApplicationThread.hpp> #include <win32cpp/Trackbar.hpp> #include <win32cpp/Button.hpp> #include <win32cpp/Label.hpp> #include <boost/format.hpp> ////////////////////////////////////////////////////////////////////////////// using namespace musik::cube; ////////////////////////////////////////////////////////////////////////////// /*ctor*/ TransportController::TransportController(TransportView& transportView) : transportView(transportView) , playbackSliderTimer(100) , playbackSliderMouseDown(false) , paused(false) , playing(false) { this->transportView.Created.connect( this, &TransportController::OnViewCreated); this->transportView.Resized.connect( this, &TransportController::OnViewResized); } void TransportController::OnViewCreated(Window* window) { this->transportView.playButton->Pressed.connect( this, &TransportController::OnPlayPressed); this->transportView.stopButton->Pressed.connect( this, &TransportController::OnStopPressed); this->transportView.nextButton->Pressed.connect( this, &TransportController::OnNextPressed); this->transportView.prevButton->Pressed.connect( this, &TransportController::OnPreviousPressed); this->transportView.volumeSlider->Repositioned.connect( this, &TransportController::OnVolumeSliderChange); this->transportView.volumeSlider->SetPosition( (short)(musik::core::PlaybackQueue::Instance().Transport().Volume()*(double)100)); musik::core::PlaybackQueue::Instance().CurrentTrackChanged.connect(this,&TransportController::OnTrackChange); this->transportView.playbackSlider->Repositioned.connect( this, &TransportController::OnPlaybackSliderChange); this->transportView.playbackSlider->MouseButtonDown.connect( this, &TransportController::OnPlaybackSliderMouseDown); this->transportView.playbackSlider->MouseButtonUp.connect( this, &TransportController::OnPlaybackSliderMouseUp); musik::core::PlaybackQueue::Instance().Transport().PlaybackStarted.connect(this, &TransportController::OnPlaybackStarted); musik::core::PlaybackQueue::Instance().Transport().PlaybackEnded.connect(this, &TransportController::OnPlaybackStopped); musik::core::PlaybackQueue::Instance().Transport().PlaybackPause.connect(this, &TransportController::OnPlaybackPaused); musik::core::PlaybackQueue::Instance().Transport().PlaybackResume.connect(this, &TransportController::OnPlaybackResumed); this->playbackSliderTimer.ConnectToWindow(&this->transportView); this->playbackSliderTimer.OnTimeout.connect(this, &TransportController::OnPlaybackSliderTimerTimedOut); this->playbackSliderTimer.Start(); // In case playback has already started if(musik::core::PlaybackQueue::Instance().CurrentTrack()){ this->OnPlaybackStarted(); } } void TransportController::OnViewResized(Window* window, Size size) { } void TransportController::OnPlayPressed(Button* button) { if (!this->playing) musik::core::PlaybackQueue::Instance().Play(); else if (this->paused) musik::core::PlaybackQueue::Instance().Resume(); else musik::core::PlaybackQueue::Instance().Pause(); } void TransportController::OnStopPressed(Button* button) { musik::core::PlaybackQueue::Instance().Stop(); this->transportView.playbackSlider->SetPosition(0); } void TransportController::OnNextPressed(Button* button) { musik::core::PlaybackQueue::Instance().Next(); } void TransportController::OnPreviousPressed(Button* button) { musik::core::PlaybackQueue::Instance().Previous(); } void TransportController::OnVolumeSliderChange(Trackbar* trackbar) { musik::core::PlaybackQueue::Instance().Transport().SetVolume( ((double)transportView.volumeSlider->Position())/100.0 ); } void TransportController::OnTrackChange(musik::core::TrackPtr track){ if(!win32cpp::ApplicationThread::InMainThread()){ win32cpp::ApplicationThread::Call1(this,&TransportController::OnTrackChange,track); return; } if(track == musik::core::PlaybackQueue::Instance().CurrentTrack()){ win32cpp::uistring title(_T("-")); win32cpp::uistring artist(_T("-")); if(track){ if(track->GetValue("title")) title.assign( track->GetValue("title") ); if(track->GetValue("visual_artist")) artist.assign( track->GetValue("visual_artist") ); this->transportView.timeDurationLabel->SetCaption(this->FormatTime(this->CurrentTrackLength())); }else{ this->transportView.timeElapsedLabel->SetCaption(_T("0:00")); this->transportView.timeDurationLabel->SetCaption(_T("0:00")); } this->transportView.titleLabel->SetCaption(title); this->transportView.artistLabel->SetCaption(artist); } } void TransportController::OnPlaybackSliderChange(Trackbar *trackBar) { if(this->playbackSliderMouseDown){ // Get the length from the track double trackLength = this->CurrentTrackLength(); if (trackLength>0){ double relativePosition = (double)trackBar->Position() / (double)trackBar->Range(); double newPosition = trackLength * relativePosition; musik::core::PlaybackQueue::Instance().Transport().SetPosition(newPosition); } } } void TransportController::OnPlaybackSliderTimerTimedOut() { if(!musik::core::PlaybackQueue::Instance().CurrentTrack()){ return; } // Get the length from the track double trackLength = this->CurrentTrackLength(); // Move the slider double position = musik::core::PlaybackQueue::Instance().Transport().Position(); if (!this->playbackSliderMouseDown){ if(trackLength>0){ this->transportView.playbackSlider->SetPosition( (short)((double)this->transportView.playbackSlider->Range()*(position/trackLength)) ); } this->transportView.timeElapsedLabel->SetCaption(this->FormatTime(position)); return; } if (!this->playbackSliderMouseDown){ this->transportView.playbackSlider->SetPosition(0); }else{ // Lets show what position to jump to // double newPosition = trackLength*(double)this->transportView.playbackSlider->Position()/(double)this->transportView.playbackSlider->Range(); // this->transportView.timeElapsedLabel->SetCaption(this->FormatTime(newPosition)); } } double TransportController::CurrentTrackLength(){ musik::core::TrackPtr track = musik::core::PlaybackQueue::Instance().CurrentTrack(); if(track){ const utfchar *totalPositionString = track->GetValue("duration"); if(totalPositionString){ try{ double totalPosition = boost::lexical_cast<double>(totalPositionString); return totalPosition; }catch(...){ } } } return 0; } void TransportController::OnPlaybackSliderMouseDown(Window* windows, MouseEventFlags flags, Point point) { this->playbackSliderMouseDown = true; } void TransportController::OnPlaybackSliderMouseUp(Window* windows, MouseEventFlags flags, Point point) { this->playbackSliderMouseDown = false; } void TransportController::OnPlaybackStarted() { if(!win32cpp::ApplicationThread::InMainThread()) { win32cpp::ApplicationThread::Call0(this, &TransportController::OnPlaybackStarted); return; } musik::core::TrackPtr currentTrack = musik::core::PlaybackQueue::Instance().CurrentTrack(); this->playing = true; this->transportView.playButton->SetCaption(_T("Pause")); this->transportView.timeDurationLabel->SetCaption(this->FormatTime(this->CurrentTrackLength())); this->transportView.playbackSlider->SetPosition(0); this->playbackSliderTimer.Start(); this->displayedTrack = currentTrack; } void TransportController::OnPlaybackStopped() { if(!win32cpp::ApplicationThread::InMainThread()) { win32cpp::ApplicationThread::Call0(this, &TransportController::OnPlaybackStopped); return; } this->displayedTrack.reset(); this->playing = false; this->paused = false; this->transportView.playButton->SetCaption(_T("Play")); this->transportView.playbackSlider->SetPosition(0); this->OnTrackChange(musik::core::TrackPtr()); this->transportView.timeElapsedLabel->SetCaption(_T("0:00")); } void TransportController::OnPlaybackPaused() { if(!win32cpp::ApplicationThread::InMainThread()) { win32cpp::ApplicationThread::Call0(this, &TransportController::OnPlaybackPaused); return; } this->paused = true; this->transportView.playButton->SetCaption(_(_T("Resume"))); } void TransportController::OnPlaybackResumed() { if(!win32cpp::ApplicationThread::InMainThread()) { win32cpp::ApplicationThread::Call0(this, &TransportController::OnPlaybackResumed); return; } this->paused = false; this->transportView.playButton->SetCaption(_(_T("Pause"))); } win32cpp::uistring TransportController::FormatTime(double seconds) { if(seconds>=0){ unsigned long second = (unsigned long)seconds % 60; unsigned long minutes = (unsigned long)seconds / 60; boost::basic_format<uichar> format(_T("%1%:%2$02d")); format % minutes; format % second; return format.str(); } return _(_T("Unknown")); } /* win32cpp::uistring TransportController::FormatTime(const utfchar *seconds){ if(seconds){ try{ double sec = boost::lexical_cast<double>(utfstring(seconds)); return this->FormatTime(sec); }catch(...){ } } return UTF("0:00"); }*/
[ "onnerby@6a861d04-ae47-0410-a6da-2d49beace72e", "[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e", "bjorn.olievier@6a861d04-ae47-0410-a6da-2d49beace72e", "[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e" ]
[ [ [ 1, 4 ], [ 6, 57 ], [ 62, 71 ], [ 78, 84 ], [ 86, 87 ], [ 89, 90 ], [ 109, 109 ], [ 116, 119 ], [ 122, 122 ], [ 129, 129 ], [ 131, 131 ], [ 133, 142 ], [ 145, 145 ], [ 149, 155 ], [ 159, 159 ], [ 161, 161 ], [ 164, 164 ], [ 167, 167 ], [ 173, 173 ], [ 177, 178 ], [ 327, 327 ] ], [ [ 5, 5 ], [ 58, 58 ], [ 88, 88 ], [ 101, 102 ], [ 104, 105 ], [ 107, 107 ], [ 110, 115 ], [ 147, 147 ], [ 156, 158 ], [ 160, 160 ], [ 162, 163 ], [ 165, 166 ], [ 168, 172 ], [ 174, 176 ], [ 181, 190 ], [ 195, 218 ], [ 220, 220 ], [ 222, 232 ], [ 234, 234 ], [ 247, 247 ], [ 251, 251 ], [ 255, 256 ], [ 260, 260 ], [ 266, 266 ], [ 269, 269 ], [ 273, 273 ], [ 277, 287 ], [ 314, 314 ], [ 316, 326 ], [ 328, 338 ] ], [ [ 59, 61 ], [ 72, 77 ], [ 85, 85 ], [ 91, 100 ], [ 103, 103 ], [ 106, 106 ], [ 108, 108 ], [ 120, 121 ], [ 123, 128 ], [ 130, 130 ], [ 132, 132 ], [ 143, 144 ], [ 146, 146 ], [ 148, 148 ], [ 179, 180 ], [ 191, 194 ], [ 219, 219 ], [ 221, 221 ], [ 233, 233 ], [ 235, 246 ], [ 248, 250 ], [ 252, 254 ], [ 257, 259 ], [ 261, 265 ], [ 267, 268 ], [ 270, 272 ], [ 274, 276 ], [ 288, 298 ], [ 300, 310 ], [ 312, 313 ], [ 315, 315 ] ], [ [ 299, 299 ], [ 311, 311 ] ] ]
0abcf87e4dc725a2b5463944196eec735d8407c4
971b000b9e6c4bf91d28f3723923a678520f5bcf
/doc/Xsltqt5/main.cpp
6e62643bd7e0113b4d53f8ba3ac04cdfda2bbd4d
[]
no_license
google-code-export/fop-miniscribus
14ce53d21893ce1821386a94d42485ee0465121f
966a9ca7097268c18e690aa0ea4b24b308475af9
refs/heads/master
2020-12-24T17:08:51.551987
2011-09-02T07:55:05
2011-09-02T07:55:05
32,133,292
2
0
null
null
null
null
UTF-8
C++
false
false
1,847
cpp
#include <QtCore> #include <QString> #include <QtDebug> #include <QApplication> #include <QXmlQuery> #include <QtGui> class StreamBuf { public: StreamBuf() :d(new QBuffer()) { d->open(QIODevice::ReadWrite); } ~StreamBuf() { d->close(); } bool clear() { d->write(QByteArray()); return d->bytesAvailable() == 0 ? true : false; } QIODevice *device() { return d; } QByteArray stream() { return d->data(); } /* <?xml version="1.0" encoding="utf-8"?> */ QString data() { return QString::fromUtf8(stream()); } QBuffer *d; }; /* 1. Subclass QAbstractMessageHandler 2. Call QXmlQuery::setMessageHandler(&yourMessageHandler); */ int main(int argc, char *argv[]) { QApplication a( argc, argv ); qDebug() << "### init main void Extract, Transform "; QDateTime timer1( QDateTime::currentDateTime() ); const QString localoutfile = "outresult.html"; StreamBuf *buf = new StreamBuf(); QXmlQuery xquery(QXmlQuery::XSLT20); xquery.setFocus(QUrl("http://fop-miniscribus.googlecode.com/svn/trunk/doc/Xsltqt5/doc/odtdoc.xml")); /* variable <xsl:param name="unixtime" select="'0000000'" /> on style */ /////xquery.bindVariable("unixtime", QVariant(timer1.toTime_t())); /* other variable */ xquery.setQuery(QUrl("http://fop-miniscribus.googlecode.com/svn/trunk/doc/odt-fo/ooo2xslfo-writer.xsl")); xquery.evaluateTo(buf->device()); qDebug() << "### close file Extract, Transform end "; /////QTextDocument *d = new QTextDocument(); //////d->setHtml ( buf->data() ); delete buf; QTextEdit t; t.show(); /////t.setDocument ( d ); t.setPlainText ( const QString & text ); a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) ); return a.exec(); };
[ "ppkciz@9af58faf-7e3e-0410-b956-55d145112073" ]
[ [ [ 1, 66 ] ] ]
0ebfe3ff272ec1589b8a2db9ed385653e07317c0
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/luabind/iterator_policy.hpp
b6324fe5db02fcf7986b736bb6ff2f8225e23401
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
2,758
hpp
// Copyright Daniel Wallin 2007. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_ITERATOR_POLICY__071111_HPP # define LUABIND_ITERATOR_POLICY__071111_HPP # include <luabind/config.hpp> # include <luabind/detail/policy.hpp> # include <luabind/detail/convert_to_lua.hpp> namespace luabind { namespace detail { template <class Iterator> struct iterator { static int next(lua_State* L) { iterator* self = static_cast<iterator*>( lua_touserdata(L, lua_upvalueindex(1))); if (self->first != self->last) { convert_to_lua(L, *self->first); ++self->first; } else { lua_pushnil(L); } return 1; } static int destroy(lua_State* L) { iterator* self = static_cast<iterator*>( lua_touserdata(L, lua_upvalueindex(1))); self->~iterator(); return 0; } iterator(Iterator first, Iterator last) : first(first) , last(last) {} Iterator first; Iterator last; }; template <class Iterator> int make_range(lua_State* L, Iterator first, Iterator last) { void* storage = lua_newuserdata(L, sizeof(iterator<Iterator>)); lua_newtable(L); lua_pushcclosure(L, iterator<Iterator>::destroy, 0); lua_setfield(L, -2, "__gc"); lua_setmetatable(L, -2); lua_pushcclosure(L, iterator<Iterator>::next, 1); new (storage) iterator<Iterator>(first, last); return 1; } template <class Container> int make_range(lua_State* L, Container& container) { return make_range(L, container.begin(), container.end()); } struct iterator_converter { typedef iterator_converter type; template <class Container> void apply(lua_State* L, Container& container) { make_range(L, container); } template <class Container> void apply(lua_State* L, Container const& container) { make_range(L, container); } }; struct iterator_policy : conversion_policy<0> { static void precall(lua_State*, index_map const&) {} static void postcall(lua_State*, index_map const&) {} template <class T, class Direction> struct apply { typedef iterator_converter type; }; }; }} // namespace luabind::detail namespace luabind { namespace { LUABIND_ANONYMOUS_FIX detail::policy_cons< detail::iterator_policy, detail::null_type> return_stl_iterator; }} // namespace luabind::unnamed #endif // LUABIND_ITERATOR_POLICY__071111_HPP
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 113 ] ] ]
66e1748bb90cada5409df1680ac37565c12ec663
e02fa80eef98834bf8a042a09d7cb7fe6bf768ba
/MyGUIEngine/src/MyGUI_MultiListFactory.cpp
e353ee3e1d0a9c3814c3d6e34a0dbcf31439ccb2
[]
no_license
MyGUI/mygui-historical
fcd3edede9f6cb694c544b402149abb68c538673
4886073fd4813de80c22eded0b2033a5ba7f425f
refs/heads/master
2021-01-23T16:40:19.477150
2008-03-06T22:19:12
2008-03-06T22:19:12
22,805,225
2
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,070
cpp
/*! @file @author Albert Semenov @date 04/2008 @module */ #include "MyGUI_MultiListFactory.h" #include "MyGUI_MultiList.h" #include "MyGUI_SkinManager.h" #include "MyGUI_WidgetManager.h" namespace MyGUI { namespace factory { MultiListFactory::MultiListFactory() { // регестрируем себя MyGUI::WidgetManager & manager = MyGUI::WidgetManager::getInstance(); manager.registerFactory(this); } MultiListFactory::~MultiListFactory() { // удаляем себя MyGUI::WidgetManager & manager = MyGUI::WidgetManager::getInstance(); manager.unregisterFactory(this); } const Ogre::String& MultiListFactory::getType() { return MultiList::_getType(); } WidgetPtr MultiListFactory::createWidget(const Ogre::String& _skin, const IntCoord& _coord, Align _align, CroppedRectanglePtr _parent, const Ogre::String& _name) { return new MultiList(_coord, _align, SkinManager::getInstance().getSkin(_skin), _parent, _name); } } // namespace factory } // namespace MyGUI
[ [ [ 1, 42 ] ] ]
22d28a0c8eb450a644a70fbd82625d78d21f3463
6d9c58ba709bace54d85a9d8665288c81fd57aac
/riskyBsns/random.cpp
5c8670d16f14c473fb99e2210c04a8df8fe2d77f
[]
no_license
pandademonlord/gsp360midtermrisk4-28-2010
3136db1767285eb812a97bc9f3bbc4c4b645ea52
f44fe4c87a41adb7216d6775f1bf67569c81e691
refs/heads/master
2021-01-10T20:38:19.707191
2010-06-26T21:14:47
2010-06-26T21:14:47
32,240,040
0
0
null
null
null
null
UTF-8
C++
false
false
922
cpp
#include "random.h" static const int g_MAX_RAND = 32767; // our initial starting seed is 5323 static unsigned int nSeed = 5323; void seedRandom(const int & a_seed) { nSeed = a_seed; } /** * custom random method to avoid reliance on stdlib.h * @return random (linear congruential) number between 0 and 32767 */ int random() { // Take the current seed and generate a new value // from it. Due to our use of large constants and // overflow, it would be very hard for someone to // predict what the next number is going to be from // the previous one. nSeed = (8253729 * nSeed + 2396403); // return a value between 0 and 32767 return nSeed % g_MAX_RAND; } float randomFloat(const float & a_min, const float & a_max) { int randomInt = random(); float range = a_max-a_min; float number = (float)randomInt * range / (float)g_MAX_RAND; number += a_min; return number; }
[ "jparks.gsp@01c8a8da-d48b-78e0-b892-dcd36b50181e" ]
[ [ [ 1, 36 ] ] ]
5d9951d6e3b327e957f3ec51acc0cd55f4015d8b
acf0e8a6d8589532d5585b28ec61b44b722bf213
/new_gp_daemon/log_req_proc.cpp
75ba59522feba23ab6367748726c84e58bc7bc5c
[]
no_license
mchouza/ngpd
0f0e987a95db874b3cde4146364bf1d69cf677cb
5cca5726910bfc97844689f1f40c94b27e0fb9f9
refs/heads/master
2016-09-06T02:09:32.007855
2008-04-06T14:17:55
2008-04-06T14:17:55
35,064,755
0
0
null
null
null
null
ISO-8859-2
C++
false
false
4,788
cpp
// // Copyright (c) 2008, Mariano M. Chouza // 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. // // * The names of the contributors 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 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. // //============================================================================= // log_req_proc.cpp //----------------------------------------------------------------------------- // Creado por Mariano M. Chouza | Empezado el 31 de marzo de 2008 //============================================================================= #include "log_req_proc.h" #include "template_utils.h" #include <fstream> #include <sstream> #include <port.h> // El orden importa, debe ser anterior a 'template.h' #include <google/template.h> #include <Poco/StreamConverter.h> #include <Poco/UTF8Encoding.h> #include <Poco/Windows1252Encoding.h> #include <Poco/Net/HTTPServerRequest.h> using namespace WebInterface; namespace { /// Rellena el diccionario para procesar los templates void fillTemplateDict(google::TemplateDictionary& dict, const std::string& logData) { // FIXME: Ver como centralizar mejor el manejo de las constantes de // cadena. using Utils::Template::fillFooter; using Utils::Template::fillHeader; using Utils::Template::fillMenu; using Utils::Template::fillPageHeader; // Relleno las distintas partes del template fillHeader(dict, "NGPD::Log"); fillPageHeader(dict); fillMenu(dict); fillFooter(dict); // Relleno "a mano" los datos del log dict.SetValue("LOG_DATA", logData); } } void LogReqProc::process(const Poco::Net::HTTPServerRequest& procReq, Poco::Net::HTTPServerResponse& resp) { using google::DO_NOT_STRIP; using google::Template; using google::TemplateDictionary; using google::TemplateString; using Poco::OutputStreamConverter; using Poco::UTF8Encoding; using Poco::Windows1252Encoding; using std::ifstream; using std::ios; using std::ostringstream; using std::string; using std::vector; // FIXME: Manejar errores en el pedido o por ausencia de log // FIXME: Sacar el path del archivo de log por la configuración, no ponerlo // "hardcoded". // FIXME: Sacar el path de los templates por la configuración, no ponerlo // "hardcoded". Ponerlo en la configuración del subsistema WebServer. // FIXME: Cargar los templates al arrancar el subsistema WebServer. // Trato de abrir el archivo ifstream logFile("NGPD.log", ios::in); // Diccionario TemplateDictionary dict("log"); // Configuro el directorio raíz Template::SetTemplateRootDirectory("./templates"); // Me fijo si está abierto el archivo de log if (logFile.is_open()) { // Stream para leer el archivo ostringstream oss; // Covierto el log a UTF-8 OutputStreamConverter(oss, Windows1252Encoding(), UTF8Encoding()) << logFile.rdbuf(); // Relleno el diccionario fillTemplateDict(dict, oss.str()); } else { // Relleno el diccionario indicando error fillTemplateDict(dict, "-- ERROR NO SE CARGÓ EL LOG --"); } // Salida string outStr; // Cargo y expando el template Template* pTemplate = Template::GetTemplate("log.tpl", DO_NOT_STRIP); pTemplate->Expand(&outStr, &dict); // Mando un archivo HTML resp.setContentType("text/html"); // Copio el template expandido a la salida resp.send() << outStr; }
[ "mchouza@b858013c-4649-0410-a850-dde43e08a396" ]
[ [ [ 1, 139 ] ] ]
b8da7f33c3b92e1b1f291410663702757fb2249b
fe122f81ca7d6dff899945987f69305ada995cd7
/files parse/XMLDOMFromVC/XMLDOMFromVC.h
cc3cb5cfd0d7d1e3a00215760a03d8ddca0700bc
[]
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,390
h
// XMLDOMFromVC.h : main header file for the XMLDOMFROMVC application // #if !defined(AFX_XMLDOMFROMVC_H__DA4EAB41_6DF3_11D4_ABD3_000102378429__INCLUDED_) #define AFX_XMLDOMFROMVC_H__DA4EAB41_6DF3_11D4_ABD3_000102378429__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CXMLDOMFromVCApp: // See XMLDOMFromVC.cpp for the implementation of this class // class CXMLDOMFromVCApp : public CWinApp { public: CXMLDOMFromVCApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CXMLDOMFromVCApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CXMLDOMFromVCApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_XMLDOMFROMVC_H__DA4EAB41_6DF3_11D4_ABD3_000102378429__INCLUDED_)
[ "robustwell@bd7e636a-136b-06c9-ecb0-b59307166256" ]
[ [ [ 1, 49 ] ] ]
823c07911e11ab964ed15e9e2b1ed63f8aa2d44b
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/numeric/interval/test/det.cpp
b0ffaaad32ef3950750c6bc6308b550a5eae5ec8
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
2,736
cpp
/* Boost test/det.cpp * test protected and unprotected rounding on an unstable determinant * * Copyright 2002-2003 Guillaume Melquiond * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or * copy at http://www.boost.org/LICENSE_1_0.txt) */ #include <boost/numeric/interval.hpp> #include <boost/test/minimal.hpp> #include "bugs.hpp" #define size 8 template<class I> void det(I (&mat)[size][size]) { for(int i = 0; i < size; i++) for(int j = 0; j < size; j++) mat[i][j] = I(1) / I(i + j + 1); for(int i = 0; i < size - 1; i++) { int m = i, n = i; typename I::base_type v = 0; for(int a = i; a < size; a++) for(int b = i; b < size; b++) { typename I::base_type w = abs(mat[a][b]).lower(); if (w > v) { m = a; n = b; v = w; } } if (n != i) for(int a = 0; a < size; a++) { I t = mat[a][n]; mat[a][n] = mat[a][i]; mat[a][i] = t; } if (m != i) for(int b = i; b < size; b++) { I t = mat[m][b]; mat[m][b] = mat[m][i]; mat[m][i] = t; } if (((m + n) & 1) == 1) { }; I c = mat[i][i]; for(int j = i + 1; j < size; j++) { I f = mat[j][i] / c; for(int k = i; k < size; k++) mat[j][k] -= f * mat[i][k]; } if (in_zero(c)) return; } } namespace my_namespace { using namespace boost; using namespace numeric; using namespace interval_lib; template<class T> struct variants { typedef interval<T> I_op; typedef typename change_rounding<I_op, save_state<rounded_arith_std<T> > >::type I_sp; typedef typename unprotect<I_op>::type I_ou; typedef typename unprotect<I_sp>::type I_su; typedef T type; }; } template<class T> bool test() { typedef my_namespace::variants<double> types; types::I_op mat_op[size][size]; types::I_sp mat_sp[size][size]; types::I_ou mat_ou[size][size]; types::I_su mat_su[size][size]; det(mat_op); det(mat_sp); { types::I_op::traits_type::rounding rnd; det(mat_ou); } { types::I_sp::traits_type::rounding rnd; det(mat_su); } for(int i = 0; i < size; i++) for(int j = 0; j < size; j++) { typedef types::I_op I; I d_op = mat_op[i][j]; I d_sp = mat_sp[i][j]; I d_ou = mat_ou[i][j]; I d_su = mat_su[i][j]; if (!(equal(d_op, d_sp) && equal(d_sp, d_ou) && equal(d_ou, d_su))) return false; } return true; } int test_main(int, char *[]) { BOOST_TEST(test<float>()); BOOST_TEST(test<double>()); BOOST_TEST(test<long double>()); # ifdef __BORLANDC__ ::detail::ignore_warnings(); # endif return 0; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 103 ] ] ]
a84f83529ad92faa4b8dc6f9f17d158acb5affe7
58ef4939342d5253f6fcb372c56513055d589eb8
/SimulateMessage/Client/source/SMS/inc/SMSDatagramService.h
b7ba38fdaa5dc5f02e22297b3107ba7365c300a4
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
UTF-8
C++
false
false
1,091
h
// SMSDatagramService.h // // Copyright (c) 2003 Symbian Ltd. All rights reserved. // #ifndef __SMSDATAGRAMSERVICE_H__ #define __SMSDATAGRAMSERVICE_H__ #include "Datagram.h" // Forward Declarations class CSMSSender; class CSMSReceiver; class CSMSDatagramService : public CBase /** @publishedAll An SMS Specific Datagram Service API. CSMSDatagramSerive provides a simple way of sending SMS in 7Bit format most universally recognised. Sending binary data is not possible without first encoding the data in a method which will survive being 7Bit encoded. */ { public: ~CSMSDatagramService(); static CSMSDatagramService* NewL(); // from CDatagramService void SendL(CDatagram* aDatagram, TRequestStatus& aStatus); void ReceiveL(CDatagram* aDatagram, const TDesC8& aRecvParams, TRequestStatus& aStatus); private: CSMSDatagramService(); void ConstructL(); private: /** Encapsulating Socket based send*/ CSMSSender* iSender; /** Active object encapsulating Socket based receive*/ CSMSReceiver* iReceiver; }; #endif
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 46 ] ] ]
397c8c36294a75eb11abaed86aa3f7940e581fd0
a96faf238d7d30a64b3cff7d8c7532074123f3be
/src/clpanel.h
ac27ea781168a408146ecab21be4927fbb19948e
[]
no_license
RangelReale/chordlive
0c93a8bd0a29c44ba0c7c206e353c2c77bbe8164
5529f61bdd10deed1cd5c8070f9bd9557f318719
refs/heads/master
2023-06-12T18:14:35.768988
2009-06-22T23:58:31
2009-06-22T23:58:31
37,156,240
0
0
null
null
null
null
UTF-8
C++
false
false
709
h
#ifndef H__CLPANEL__H #define H__CLPANEL__H #include <wx/wx.h> #include <wx/dcbuffer.h> #include <wx/image.h> #include "clsong.h" class CLPanel : public wxPanel { DECLARE_CLASS(CLPanel) DECLARE_EVENT_TABLE() private: CLSong *song_; int startpos_; void onPaint(wxPaintEvent &event); void onEraseBackground(wxEraseEvent &event); void onKeyDown(wxKeyEvent &event); public: CLPanel(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL, const wxString& name = wxT("panel")); ~CLPanel(); CLSong &GetSong() { return *song_; } }; #endif // H__CLPANEL__H
[ "hitnrun@82bcaf60-b05e-4c88-ae40-7279958f80f4" ]
[ [ [ 1, 29 ] ] ]
85c346b4f9d61d049e73885327cb3082dcb3ffb0
aa5491d8b31750da743472562e85dd4987f1258a
/Main/server/playerpool.cpp
e75a7baea213c8f99d9b4d13ee0a0d8565118407
[]
no_license
LBRGeorge/jmnvc
d841ad694eaa761d0a45ab95b210758c50750d17
064402f0a9f1536229b99cf45f6e7536e1ae7bb5
refs/heads/master
2016-08-04T03:12:18.402941
2009-05-31T18:40:42
2009-05-31T18:40:42
39,416,169
2
0
null
null
null
null
UTF-8
C++
false
false
4,261
cpp
#include "netgame.h" #include "rcon.h" extern CNetGame *pNetGame; extern CRcon *pRcon; #ifndef WIN32 # define stricmp strcasecmp #endif CPlayerPool::CPlayerPool() { BYTE bytePlayerID = 0; while(bytePlayerID != MAX_PLAYERS) { m_bPlayerSlotState[bytePlayerID] = FALSE; m_pPlayers[bytePlayerID] = NULL; bytePlayerID++; } } CPlayerPool::~CPlayerPool() { BYTE bytePlayerID = 0; while(bytePlayerID != MAX_PLAYERS) { Delete(bytePlayerID,0); bytePlayerID++; } } BOOL CPlayerPool::New(BYTE bytePlayerID, PCHAR szPlayerName) { m_pPlayers[bytePlayerID] = new CPlayer(); if(m_pPlayers[bytePlayerID]) { strcpy(m_szPlayerName[bytePlayerID],szPlayerName); m_pPlayers[bytePlayerID]->SetID(bytePlayerID); m_bPlayerSlotState[bytePlayerID] = TRUE; m_iPlayerScore[bytePlayerID] = 0; m_bIsAnAdmin[bytePlayerID] = FALSE; // Notify all the other players of a newcommer with // a 'ServerJoin' join RPC RakNet::BitStream bsSend; bsSend.Write(bytePlayerID); bsSend.Write(strlen(szPlayerName)); bsSend.Write(szPlayerName,strlen(szPlayerName)); bsSend.Write((BYTE)1); pNetGame->GetRakServer()->RPC("ServerJoin",&bsSend,HIGH_PRIORITY,RELIABLE_ORDERED,0, pNetGame->GetRakServer()->GetPlayerIDFromIndex(bytePlayerID),TRUE,FALSE); pRcon->ConsolePrintf("[join] %u %s",bytePlayerID,szPlayerName); return TRUE; } else { return FALSE; } } BOOL CPlayerPool::Delete(BYTE bytePlayerID, BYTE byteReason) { if(!GetSlotState(bytePlayerID) || !m_pPlayers[bytePlayerID]) { return FALSE; } m_bPlayerSlotState[bytePlayerID] = FALSE; delete m_pPlayers[bytePlayerID]; m_pPlayers[bytePlayerID] = NULL; // Notify all the other players that this client is quiting. RakNet::BitStream bsSend; bsSend.Write(bytePlayerID); bsSend.Write(byteReason); pNetGame->GetRakServer()->RPC("ServerQuit",&bsSend,HIGH_PRIORITY,RELIABLE_ORDERED,0, pNetGame->GetRakServer()->GetPlayerIDFromIndex(bytePlayerID),TRUE,FALSE); pRcon->ConsolePrintf("[part] %u %s %u",bytePlayerID,m_szPlayerName[bytePlayerID],byteReason); return TRUE; } void CPlayerPool::Process() { BYTE bytePlayerID = 0; while(bytePlayerID != MAX_PLAYERS) { if(TRUE == m_bPlayerSlotState[bytePlayerID]) { m_pPlayers[bytePlayerID]->Process(); } bytePlayerID++; } } BYTE CPlayerPool::AddResponsibleDeath(BYTE byteWhoKilled, BYTE byteWhoDied) { CPlayer *pWhoKilled; CPlayer *pWhoDied; if( byteWhoKilled != INVALID_PLAYER_ID && byteWhoKilled < MAX_PLAYERS && byteWhoDied < MAX_PLAYERS ) { if(m_bPlayerSlotState[byteWhoKilled] && m_bPlayerSlotState[byteWhoDied]) { pWhoKilled = m_pPlayers[byteWhoKilled]; pWhoDied = m_pPlayers[byteWhoDied]; if( (pWhoKilled->GetTeam() == 255) || (pWhoKilled->GetTeam() != pWhoDied->GetTeam()) ) { m_iPlayerScore[byteWhoKilled]++; pRcon->OutputDeathMessage(VALID_KILL,byteWhoDied,byteWhoKilled); return VALID_KILL; } else { m_iPlayerScore[byteWhoKilled]--; pRcon->OutputDeathMessage(TEAM_KILL,byteWhoDied,byteWhoKilled); return TEAM_KILL; } } return SELF_KILL; } if(byteWhoKilled == INVALID_PLAYER_ID && byteWhoDied < MAX_PLAYERS) { if(m_bPlayerSlotState[byteWhoDied]) { pRcon->OutputDeathMessage(SELF_KILL,byteWhoDied,0); return SELF_KILL; } } pRcon->OutputDeathMessage(SELF_KILL,byteWhoDied,0); return SELF_KILL; } float CPlayerPool::GetDistanceFromPlayerToPlayer(BYTE bytePlayer1, BYTE bytePlayer2) { VECTOR *vecFromPlayer; VECTOR *vecThisPlayer; float fSX,fSY; CPlayer * pPlayer1 = GetAt(bytePlayer1); CPlayer * pPlayer2 = GetAt(bytePlayer2); vecFromPlayer = &pPlayer1->m_vecPos; vecThisPlayer = &pPlayer2->m_vecPos; fSX = (vecThisPlayer->X - vecFromPlayer->X) * (vecThisPlayer->X - vecFromPlayer->X); fSY = (vecThisPlayer->Y - vecFromPlayer->Y) * (vecThisPlayer->Y - vecFromPlayer->Y); return (float)sqrt(fSX + fSY); } BOOL CPlayerPool::IsNickInUse(PCHAR szNick) { int x=0; while(x!=MAX_PLAYERS) { if(GetSlotState((BYTE)x)) { if(!stricmp(GetPlayerName((BYTE)x),szNick)) { return TRUE; } } x++; } return FALSE; }
[ "jacks.mini.net@45e629aa-34f5-11de-82fb-7f665ef830f7" ]
[ [ [ 1, 176 ] ] ]
9236a4fa2a9c1b93ba41d72b3256a9e93494cc31
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/UILayer/DlgMaintabDownload.cpp
996d2db57a9631ae0f8ba91a4814a2986e396e5d
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
GB18030
C++
false
false
18,550
cpp
// DlgMaintabDownload.cpp : 实现文件 // #include "stdafx.h" #include "DlgMaintabDownload.h" #include "TabItem_Normal.h" #include "eMule.h" #include "eMuleDlg.h" #include "TransferWnd.h" #include "UserMsgs.h" #include "WndMgr.h" #include "DropDownButton.h" #include "CmdFuncs.h" #include "TabItem_Cake.h" #include "PageTabBkDraw.h" #include "HttpClient.h" #include "FileMgr.h" #include "DownloadedListCtrl.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define SPLITTER_MARGIN 1 // CDlgMaintabDownload 对话框 IMPLEMENT_DYNAMIC(CDlgMaintabDownload, CDialog) CDlgMaintabDownload::CDlgMaintabDownload(CWnd* pParent /*=NULL*/) : CResizableDialog(CDlgMaintabDownload::IDD, pParent) { m_pwebUserComment = 0; int i; for (i = 0; i < TI_MAX; i++) m_aposTabs[i] = NULL; m_plcDownloading = NULL; m_dwShowListIDC = 0; } CDlgMaintabDownload::~CDlgMaintabDownload() { } void CDlgMaintabDownload::DoDataExchange(CDataExchange* pDX) { CResizableDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CDlgMaintabDownload, CResizableDialog) ON_NOTIFY(UM_SPN_SIZED, IDC_SPLITTER_DOWNLOAD, OnSplitterMoved) ON_NOTIFY(UM_SPLITTER_CLICKED, IDC_SPLITTER_DOWNLOAD, OnSplitterClicked) ON_WM_DESTROY() ON_MESSAGE(UM_MTDD_CUR_SEL_FILE, OnCurSelFile) ON_MESSAGE(UM_MTDD_CUR_SEL_FILE_TASK,OnCurSelFileTask) ON_MESSAGE(UM_MTDD_CUR_SEL_PEER, OnCurSelPeer) ON_NOTIFY(NMC_TW_ACTIVE_TAB_CHANDED, IDC_TAB_INFO, OnNM_TabInfo_ActiveTabChanged) ON_NOTIFY(NMC_TW_ACTIVE_TAB_CHANDED, IDC_TAB_LIST, OnNM_TabList_ActiveTabChanged) END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // Added by thilon on 2007.02.03, for Resize //BEGIN_ANCHOR_MAP(CDlgMaintabDownload) // ANCHOR_MAP_ENTRY(m_tabwndDlList.GetSafeHwnd(), ANF_TOPLEFT | ANF_BOTTOMRIGHT) // ANCHOR_MAP_ENTRY(m_wndSplitter.GetSafeHwnd(), ANF_AUTOMATIC) // ANCHOR_MAP_ENTRY(m_tabwndInfo.GetSafeHwnd(),ANF_AUTOMATIC) //END_ANCHOR_MAP() CKnownFile* CDlgMaintabDownload::GetCurrentSelectedFile( CFileTaskItem* &pFileTask ) { POSITION pos; int iSelectedItem = -1; CListCtrl *pListCtrl = NULL; DWORD_PTR dwItemData; if (m_DownloadTabWnd.GetActiveTab() == m_aposTabs[TI_DOWNLOADING]) pListCtrl = m_plcDownloading; else if (m_DownloadTabWnd.GetActiveTab() == m_aposTabs[TI_DOWNLOADED]) pListCtrl = &m_lcDownloaded; else return NULL; if (NULL == pListCtrl) return NULL; pos = pListCtrl->GetFirstSelectedItemPosition(); if (pos == NULL) return NULL; iSelectedItem = pListCtrl->GetNextSelectedItem(pos); dwItemData = pListCtrl->GetItemData(iSelectedItem); if (m_DownloadTabWnd.GetActiveTab() == m_aposTabs[TI_DOWNLOADING]) { CtrlItem_Struct *pcis = (CtrlItem_Struct*) dwItemData; if (FILE_TYPE == pcis->type) return (CKnownFile*)pcis->value; else return NULL; } else if (m_DownloadTabWnd.GetActiveTab() == m_aposTabs[TI_DOWNLOADED]) { ItemData *pItemData = (ItemData*)dwItemData; if( FILE_TYPE==pItemData->type ) { CKnownFile* pmyfile =(CKnownFile *)pItemData->pItem; return pmyfile; } else if( FILE_TASK==pItemData->type ) { pFileTask = (CFileTaskItem*)pItemData->pItem; } return NULL; } else return NULL; } void CDlgMaintabDownload::InitTabs(void) { CClientRect rtClient(this); CRect rtDownload; GetDlgItem(IDC_TAB_LIST)->GetWindowRect(&rtDownload); ScreenToClient(&rtDownload); m_DownloadTabWnd.Create(WS_CHILD | WS_VISIBLE, rtDownload, this, IDC_TAB_LIST); //m_tabwndDlList.SetBkColor(GetSysColor(COLOR_3DFACE), FALSE); CPageTabBkDraw *pBarBkDraw = new CPageTabBkDraw; m_DownloadTabWnd.SetBarBkDraw(pBarBkDraw); CRect rcSpl; GetDlgItem(IDC_STATIC_SPLITER)->GetWindowRect(&rcSpl); ScreenToClient(&rcSpl); rcSpl.top = rtDownload.bottom; rcSpl.bottom = rcSpl.top; m_wndSplitter.Create(WS_CHILD | WS_VISIBLE, rcSpl, this, IDC_SPLITTER_DOWNLOAD); m_wndSplitter.SetNormalDraw(FALSE); CRect rtTabInfo; GetDlgItem(IDC_TAB_INFO)->GetWindowRect(&rtTabInfo); ScreenToClient(&rtTabInfo); rtTabInfo.top = rcSpl.top + m_wndSplitter.GetHBreadth(); m_tabwndInfo.Create(WS_CHILD | WS_VISIBLE, rtTabInfo, this, IDC_TAB_INFO); m_lcDownloaded.Create(WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_OWNERDRAWFIXED, CRect(0, 0, 0, 0), this, IDC_DOWNLOADED_LISTCTRL); m_plcDownloading = (CListCtrl*) theApp.emuledlg->transferwnd->GetDlgItem(IDC_DOWNLOADLIST); m_aposTabs[TI_DOWNLOADING] = CmdFuncs::TabWnd_AddNormalTab(&m_DownloadTabWnd, GetResString(IDS_DLTAB_DOWNLOADING), m_plcDownloading->GetSafeHwnd()); m_aposTabs[TI_DOWNLOADED] = CmdFuncs::TabWnd_AddNormalTab(&m_DownloadTabWnd, GetResString(IDS_DLTAB_COMPLETED), m_lcDownloaded.GetSafeHwnd()); CTabItem_Cake *pTiCake = NULL; if(! m_dlgDetailInfo.GetSafeHwnd()) { m_dlgDetailInfo.Create(m_dlgDetailInfo.IDD, this); } //添加日志页 if(!m_dlgPeerLog.GetSafeHwnd()) { m_dlgPeerLog.Create(m_dlgPeerLog.IDD, this); } //添加上传页 /*if (!m_dlgUpLoading.GetSafeHwnd()) { m_dlgUpLoading.Create(m_dlgUpLoading.IDD, this); }*/ //m_aposTabs[TI_DETAIL] = CmdFuncs::TabWnd_AddNormalTab(&m_tabwndInfo, GetResString(IDS_DETAIL_INFO), m_dlgDetailInfo.GetSafeHwnd()); pTiCake = new CTabItem_Cake; pTiCake->SetCaption(GetResString(IDS_DETAIL_INFO)); pTiCake->SetRelativeWnd(m_dlgDetailInfo.GetSafeHwnd()); pTiCake->SetIcon(_T("PNG_DETAILINFO")); m_posInfo = m_aposTabs[TI_DETAIL] = m_tabwndInfo.AddTab(pTiCake); pTiCake = NULL; if(! m_pwebUserComment) { // don't delete it, auto-deleted m_pwebUserComment = new CHtmlCtrl; CRect rect(0,0,1,1); // tab will resize it m_pwebUserComment->Create(NULL, NULL ,WS_CHILD | WS_VISIBLE &~WS_BORDER, rect,this, 34345,NULL); m_pwebUserComment->SetSilent(true); //m_webUserComment.Create(IDD_WEBBROWSER); } pTiCake = new CTabItem_Cake; pTiCake->SetCaption(GetResString(IDS_USER_COMMENT)); pTiCake->SetRelativeWnd(m_pwebUserComment->GetSafeHwnd()); pTiCake->SetIcon(_T("PNG_DETAILCOMMENT")); m_aposTabs[TI_REMARK] = m_tabwndInfo.AddTab(pTiCake); pTiCake = NULL; //添加日志标签 pTiCake = new CTabItem_Cake; pTiCake->SetCaption(GetResString(IDS_TASK_LOG)); pTiCake->SetRelativeWnd(m_dlgPeerLog.GetSafeHwnd()); pTiCake->SetIcon(_T("PNG_PEERLOG")); m_posPeerLog = m_aposTabs[TI_PEERLOG] = m_tabwndInfo.AddTab(pTiCake); pTiCake = NULL; //添加上传标签 pTiCake = new CTabItem_Cake; pTiCake->SetCaption(GetResString(IDS_UPLOADING)); pTiCake->SetRelativeWnd(((CListCtrl*) theApp.emuledlg->transferwnd->GetDlgItem(IDC_UPLOADLIST))->GetSafeHwnd()); pTiCake->SetIcon(_T("PNG_DETAILUPLOAD")); m_posUploading = m_aposTabs[TI_UPLOADING] = m_tabwndInfo.AddTab(pTiCake); pTiCake = NULL; } void CDlgMaintabDownload::RefreshLowerPannel(CKnownFile * file) { //[10/17/2007 VC-huby] 和void CUserComment::Refresh(CKnownFile * file) 重复代码,由于UI层没有规划好,暂复制一份.. if( !m_pwebUserComment || !file ) return; CString strFileEd2k = CreateED2kLink(file, false); if( strFileEd2k.IsEmpty() ) { // m_pwebUserComment->Navigate2(_T("about:blank"), 0, NULL); theApp.emuledlg->transferwnd->downloadlistctrl.OnNoComment(m_pwebUserComment); return; } bool bFileisFinished = true; if( file->IsKindOf(RUNTIME_CLASS(CPartFile)) ) { if( ((CPartFile*)file)->GetStatus()!=PS_COMPLETE ) bFileisFinished = false; } CString strCommentUrl = bFileisFinished ? thePrefs.m_strFinishedFileCommentUrl : thePrefs.m_strPartFileCommentUrl; strCommentUrl.Replace(_T("[ed2k]"),strFileEd2k); strCommentUrl.Replace(_T("|"), _T("%7C")); m_pwebUserComment->Navigate2(strCommentUrl, 0, NULL); } void CDlgMaintabDownload::RefreshLowerPannel(CFileTaskItem * pFileTask) { if( !m_pwebUserComment || !pFileTask ) return; if( pFileTask->m_strEd2kLink.IsEmpty() || pFileTask->m_strEd2kLink.Left(7)!=_T("ed2k://") ) { theApp.emuledlg->transferwnd->downloadlistctrl.OnNoComment(m_pwebUserComment); } else { bool bFileisFinished = (pFileTask->m_nFileState>=2 && pFileTask->m_nFileState<=6); CString strCommentUrl = bFileisFinished ? thePrefs.m_strFinishedFileCommentUrl : thePrefs.m_strPartFileCommentUrl; strCommentUrl.Replace(_T("[ed2k]"),pFileTask->m_strEd2kLink); strCommentUrl.Replace(_T("|"), _T("%7C")); m_pwebUserComment->Navigate2(strCommentUrl, 0, NULL); } } // CDlgMaintabDownload 消息处理程序 BOOL CDlgMaintabDownload::OnInitDialog() { CResizableDialog::OnInitDialog(); ModifyStyle(0, WS_CLIPCHILDREN); theWndMgr.SetWndHandle(CWndMgr::WI_MAINTAB_DOWNLOAD_DLG, m_hWnd); InitTabs(); AddAnchor(m_DownloadTabWnd, TOP_LEFT, CSize(100, thePrefs.GetSplitterbarPosition())); AddAnchor(m_wndSplitter, CSize(0, thePrefs.GetSplitterbarPosition()), BOTTOM_RIGHT); AddAnchor(m_tabwndInfo, CSize(0, thePrefs.GetSplitterbarPosition()), BOTTOM_RIGHT); m_wndSplitter.m_nflag = 1; return TRUE; } BOOL CDlgMaintabDownload::PreTranslateMessage(MSG* pMsg) { if (pMsg->message == WM_KEYDOWN) { // Don't handle Ctrl+Tab in this window. It will be handled by main window. if (pMsg->wParam == VK_TAB && GetAsyncKeyState(VK_CONTROL) < 0) return FALSE; if (VK_RETURN == pMsg->wParam || VK_ESCAPE == pMsg->wParam) return FALSE; } if (pMsg->message == WM_MBUTTONUP) { if (m_plcDownloading) { ((CDownloadListCtrl*)m_plcDownloading)->ShowSelectedFileDetails(); return TRUE; } } return CResizableDialog::PreTranslateMessage(pMsg); } void CDlgMaintabDownload::DoResize(int delta) { CSplitterControl::ChangeHeight((CWnd*)&m_DownloadTabWnd, delta); CSplitterControl::ChangeHeight((CWnd*)&m_tabwndInfo, -delta, CW_BOTTOMALIGN); UpdateSplitterRange(); m_plcDownloading->Invalidate(); m_plcDownloading->UpdateWindow(); } LRESULT CDlgMaintabDownload::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_PAINT: if (m_wndSplitter) { CRect rcWnd; GetWindowRect(rcWnd); if (rcWnd.Height() > 0) { CRect rcDown; m_DownloadTabWnd.GetWindowRect(rcDown); ScreenToClient(rcDown); // splitter paint update CRect rcSpl; rcSpl.left = rcDown.left; rcSpl.right = rcDown.right; rcSpl.top = rcDown.bottom; rcSpl.bottom = rcSpl.top + m_wndSplitter.GetHBreadth(); m_wndSplitter.MoveWindow(rcSpl, TRUE); UpdateSplitterRange(); } } //// Workaround to solve a glitch with WM_SETTINGCHANGE message //if (m_btnWnd1 && m_btnWnd1->m_hWnd && m_btnWnd1->GetBtnWidth(IDC_DOWNLOAD_ICO) != WND1_BUTTON_WIDTH) // m_btnWnd1->SetBtnWidth(IDC_DOWNLOAD_ICO, WND1_BUTTON_WIDTH); break; } return CResizableDialog::DefWindowProc(message, wParam, lParam); } void CDlgMaintabDownload::OnDestroy() { CResizableDialog::OnDestroy(); // TODO: 在此处添加消息处理程序代码 theWndMgr.SetWndHandle(CWndMgr::WI_MAINTAB_DOWNLOAD_DLG, NULL); } LRESULT CDlgMaintabDownload::OnCurSelFile(WPARAM wParam, LPARAM lParam) { if (!lParam) { theApp.emuledlg->m_mainTabWnd.m_dlgDownload.m_dlgPeerLog.m_LogListCtrl.DeleteAllItems(); theApp.emuledlg->m_mainTabWnd.m_dlgDownload.m_dlgDetailInfo.m_ListDetail.DeleteAllItems(); return 0; } if (wParam == 1) { CKnownFile* pKnownFile= (CKnownFile*)lParam; if( pKnownFile->HasNullHash() ) { CFileTaskItem* pFileTaskItem = CGlobalVariable::filemgr.GetFileTaskItem(pKnownFile->GetPartFileURL()); ASSERT(pFileTaskItem); if(pFileTaskItem) m_dlgDetailInfo.FileInfo(pFileTaskItem); } else { m_dlgDetailInfo.UpdateInfo((CPartFile*)lParam, CDetailInfo::IM_COMBINE_DOWNLOADED); } return 0; } CPartFile *pFile = (CPartFile*) lParam; if (IsRemarkTabActived()) { RefreshLowerPannel(pFile); } else if( IsLogTabActived() ) { m_dlgPeerLog.m_LogListCtrl.ShowSelectedFileLogs(pFile); } else { if ( IsDownloadingActived() && pFile->GetStatus() != PS_COMPLETE && pFile->GetFileSize() != (uint64)0) { m_dlgDetailInfo.UpdateInfo(pFile, CDetailInfo::IM_COMBINE_DOWNLOAD); } else if (IsDownloadingActived() && pFile->GetFileSize() == (uint64)0) { CFileTaskItem* pFileTaskItem = CGlobalVariable::filemgr.GetFileTaskItem(pFile->GetPartFileURL()); ASSERT(pFileTaskItem); if(pFileTaskItem) m_dlgDetailInfo.FileInfo(pFileTaskItem); } else { m_dlgDetailInfo.UpdateInfo(pFile, CDetailInfo::IM_COMBINE_DOWNLOADED); } } return 0; } LRESULT CDlgMaintabDownload::OnCurSelFileTask(WPARAM /*wParam*/, LPARAM lParam) { //CKnownFile *pFile = (CKnownFile*) lParam; CFileTaskItem *pFile =(CFileTaskItem *)lParam; m_dlgDetailInfo.FileInfo(pFile); return 0; } LRESULT CDlgMaintabDownload::OnCurSelPeer(WPARAM /*wParam*/, LPARAM lParam) { m_tabwndInfo.SetActiveTab(m_posPeerLog); CtrlItem_Struct* content = (CtrlItem_Struct*) lParam; if(content == NULL) { return 0; } CUpDownClient* pUpDownClient = (CUpDownClient*)content->value; if( pUpDownClient == NULL) { return 0; } m_dlgPeerLog.m_LogListCtrl.ShowSelectedPeerLogs(pUpDownClient); return 0; } void CDlgMaintabDownload::OnNM_TabInfo_ActiveTabChanged(NMHDR* pNMHDR, LRESULT *pResult) { __try { NMTW_TABOP *pTabOp = reinterpret_cast<NMTW_TABOP*>(pNMHDR); CKnownFile* pFile = NULL; if (pTabOp->posTab == m_aposTabs[TI_REMARK]) { CFileTaskItem *pFileTask=NULL; pFile = GetCurrentSelectedFile(pFileTask); if ( NULL!= pFile ) RefreshLowerPannel(pFile); else if( NULL!=pFileTask ) RefreshLowerPannel(pFileTask); } *pResult = 0; } __except( EXCEPTION_EXECUTE_HANDLER ) { } } void CDlgMaintabDownload::OnNM_TabList_ActiveTabChanged(NMHDR* /*pNMHDR*/, LRESULT *pResult) { if (m_DownloadTabWnd.GetActiveTab() == m_aposTabs[TI_DOWNLOADING]) { m_DownloadTabWnd.m_Toolbar.SetOwner(m_plcDownloading); m_DownloadTabWnd.m_Toolbar.EnableButton(MP_OPENFOLDER, ( FALSE )); m_tabwndInfo.SetActiveTab(m_posInfo); m_dlgDetailInfo.m_ListDetail.DeleteAllItems(); theApp.emuledlg->transferwnd->downloadlistctrl.UpdateToolBarItem(); } if (m_DownloadTabWnd.GetActiveTab() == m_aposTabs[TI_DOWNLOADED]) { theApp.emuledlg->m_mainTabWnd.m_dlgDownload.m_dlgPeerLog.m_LogListCtrl.DeleteAllItems(); m_DownloadTabWnd.m_Toolbar.SetOwner( &m_lcDownloaded); m_tabwndInfo.SetActiveTab(m_posInfo); m_dlgDetailInfo.m_ListDetail.DeleteAllItems(); m_DownloadTabWnd.m_Toolbar.EnableButton(MP_PAUSE, FALSE); m_DownloadTabWnd.m_Toolbar.EnableButton(MP_RESUME, FALSE); m_DownloadTabWnd.m_Toolbar.EnableButton(MP_STOP, FALSE); //Toolbar int iSelectedItems = m_lcDownloaded.GetSelectedCount(); if(iSelectedItems) { m_DownloadTabWnd.m_Toolbar.EnableButton(MP_CANCEL, TRUE); if (iSelectedItems == 1) { m_DownloadTabWnd.m_Toolbar.EnableButton(MP_OPENFOLDER, TRUE); } else { m_DownloadTabWnd.m_Toolbar.EnableButton(MP_OPENFOLDER, FALSE); } } else { m_DownloadTabWnd.m_Toolbar.EnableButton(MP_OPENFOLDER, FALSE); m_DownloadTabWnd.m_Toolbar.EnableButton(MP_CANCEL, FALSE); m_dlgDetailInfo.m_ListDetail.DeleteAllItems(); } } *pResult = 0; } void CDlgMaintabDownload::Localize() { m_DownloadTabWnd.SetTabText(m_aposTabs[TI_DOWNLOADING], GetResString(IDS_DLTAB_DOWNLOADING)); m_DownloadTabWnd.SetTabText(m_aposTabs[TI_DOWNLOADED], GetResString(IDS_DLTAB_COMPLETED)); m_tabwndInfo.SetTabText(m_aposTabs[TI_DETAIL], GetResString(IDS_DETAIL_INFO)); m_tabwndInfo.SetTabText(m_aposTabs[TI_REMARK], GetResString(IDS_USER_COMMENT)); } void CDlgMaintabDownload::ShowList(int nflag) { if(nflag) { CRect rcWnd; GetWindowRect(rcWnd); ScreenToClient(rcWnd); CRect rcTabList; m_DownloadTabWnd.GetWindowRect(rcTabList); ScreenToClient(rcTabList); pos = (rcTabList.bottom * 100) / rcWnd.Height(); rcTabList.bottom = rcWnd.bottom - 5;// - 30; //rcTabList.top = 28; RemoveAnchor(m_DownloadTabWnd); CRect rcTabInfo; m_tabwndInfo.GetWindowRect(rcTabInfo); ScreenToClient(rcTabInfo); rcTabInfo.bottom = rcWnd.bottom;// - 20; rcTabInfo.top = rcWnd.bottom;// - 23; RemoveAnchor(m_tabwndInfo); m_DownloadTabWnd.MoveWindow(rcTabList); m_tabwndInfo.MoveWindow(rcTabInfo); AddAnchor(m_DownloadTabWnd, TOP_LEFT, BOTTOM_RIGHT); AddAnchor(m_tabwndInfo, TOP_LEFT, BOTTOM_RIGHT); m_wndSplitter.m_nflag = 0; } else { CRect rcWnd; GetWindowRect(rcWnd); ScreenToClient(rcWnd); LONG splitpos = (pos * rcWnd.Height()) / 100; CRect rcTabList; m_DownloadTabWnd.GetWindowRect(rcTabList); ScreenToClient(rcTabList); rcTabList.bottom = splitpos - 5; RemoveAnchor(m_DownloadTabWnd); CRect rcTabInfo; m_tabwndInfo.GetWindowRect(rcTabInfo); ScreenToClient(rcTabInfo); rcTabInfo.top = splitpos; RemoveAnchor(m_tabwndInfo); m_DownloadTabWnd.MoveWindow(rcTabList); m_tabwndInfo.MoveWindow(rcTabInfo); AddAnchor(m_DownloadTabWnd, TOP_LEFT, CSize(100, thePrefs.GetSplitterbarPosition())); AddAnchor(m_tabwndInfo, CSize(0, thePrefs.GetSplitterbarPosition()), BOTTOM_RIGHT); m_wndSplitter.m_nflag = 1; } } void CDlgMaintabDownload::UpdateSplitterRange(void) { CRect rcWnd; GetWindowRect(rcWnd); CRect rcDown; m_DownloadTabWnd.GetWindowRect(rcDown); ScreenToClient(rcDown); CRect rcUp; m_tabwndInfo.GetWindowRect(rcUp); ScreenToClient(rcUp); thePrefs.SetSplitterbarPosition((rcDown.bottom * 100) / rcWnd.Height()); RemoveAnchor(m_DownloadTabWnd); RemoveAnchor(m_DownloadTabWnd); RemoveAnchor(m_tabwndInfo); AddAnchor(m_DownloadTabWnd, TOP_LEFT, CSize(100, thePrefs.GetSplitterbarPosition())); AddAnchor(m_tabwndInfo, CSize(0, thePrefs.GetSplitterbarPosition()), BOTTOM_RIGHT); m_wndSplitter.SetRange(rcDown.top + 50, rcUp.bottom - 40); } void CDlgMaintabDownload::OnSplitterMoved(NMHDR* pNMHDR, LRESULT* /*pResult*/) { SPC_NMHDR* pHdr = (SPC_NMHDR*)pNMHDR; DoResize(pHdr->delta); } void CDlgMaintabDownload::OnSplitterClicked(NMHDR* pNMHDR, LRESULT* /*pResult*/) { SPCEX_NMHDR* pHdr = (SPCEX_NMHDR*)pNMHDR; theApp.emuledlg->m_mainTabWnd.m_dlgDownload.ShowList(pHdr->flag); }
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 650 ] ] ]
48a9756b7d633da06ba5791dada53e1ac928db0f
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/upd7759.cpp
b82cfebda888d94bf2b6f2acb939cdd6ef57db5f
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
15,245
cpp
#include "burnint.h" #include "burn_sound.h" #include "upd7759.h" #define FRAC_BITS 20 #define FRAC_ONE (1 << FRAC_BITS) #define FRAC_MASK (FRAC_ONE - 1) static int SlaveMode; /* chip states */ enum { STATE_IDLE, STATE_DROP_DRQ, STATE_START, STATE_FIRST_REQ, STATE_LAST_SAMPLE, STATE_DUMMY1, STATE_ADDR_MSB, STATE_ADDR_LSB, STATE_DUMMY2, STATE_BLOCK_HEADER, STATE_NIBBLE_COUNT, STATE_NIBBLE_MSN, STATE_NIBBLE_LSN }; struct upd7759_chip { /* internal clock to output sample rate mapping */ UINT32 pos; /* current output sample position */ UINT32 step; /* step value per output sample */ /* I/O lines */ UINT8 fifo_in; /* last data written to the sound chip */ UINT8 reset; /* current state of the RESET line */ UINT8 start; /* current state of the START line */ UINT8 drq; /* current state of the DRQ line */ void (*drqcallback)(int param); /* drq callback */ /* internal state machine */ INT8 state; /* current overall chip state */ INT32 clocks_left; /* number of clocks left in this state */ UINT16 nibbles_left; /* number of ADPCM nibbles left to process */ UINT8 repeat_count; /* number of repeats remaining in current repeat block */ INT8 post_drq_state; /* state we will be in after the DRQ line is dropped */ INT32 post_drq_clocks; /* clocks that will be left after the DRQ line is dropped */ UINT8 req_sample; /* requested sample number */ UINT8 last_sample; /* last sample number available */ UINT8 block_header; /* header byte */ UINT8 sample_rate; /* number of UPD clocks per ADPCM nibble */ UINT8 first_valid_header; /* did we get our first valid header yet? */ UINT32 offset; /* current ROM offset */ UINT32 repeat_offset; /* current ROM repeat offset */ /* ADPCM processing */ INT8 adpcm_state; /* ADPCM state index */ UINT8 adpcm_data; /* current byte of ADPCM data */ INT16 sample; /* current sample value */ /* ROM access */ UINT8 * rom; /* pointer to ROM data or NULL for slave mode */ UINT8 * rombase; /* pointer to ROM data or NULL for slave mode */ UINT32 romoffset; /* ROM offset to make save/restore easier */ }; static struct upd7759_chip *Chips[2]; // more? static struct upd7759_chip *Chip = NULL; static const int upd7759_step[16][16] = { { 0, 0, 1, 2, 3, 5, 7, 10, 0, 0, -1, -2, -3, -5, -7, -10 }, { 0, 1, 2, 3, 4, 6, 8, 13, 0, -1, -2, -3, -4, -6, -8, -13 }, { 0, 1, 2, 4, 5, 7, 10, 15, 0, -1, -2, -4, -5, -7, -10, -15 }, { 0, 1, 3, 4, 6, 9, 13, 19, 0, -1, -3, -4, -6, -9, -13, -19 }, { 0, 2, 3, 5, 8, 11, 15, 23, 0, -2, -3, -5, -8, -11, -15, -23 }, { 0, 2, 4, 7, 10, 14, 19, 29, 0, -2, -4, -7, -10, -14, -19, -29 }, { 0, 3, 5, 8, 12, 16, 22, 33, 0, -3, -5, -8, -12, -16, -22, -33 }, { 1, 4, 7, 10, 15, 20, 29, 43, -1, -4, -7, -10, -15, -20, -29, -43 }, { 1, 4, 8, 13, 18, 25, 35, 53, -1, -4, -8, -13, -18, -25, -35, -53 }, { 1, 6, 10, 16, 22, 31, 43, 64, -1, -6, -10, -16, -22, -31, -43, -64 }, { 2, 7, 12, 19, 27, 37, 51, 76, -2, -7, -12, -19, -27, -37, -51, -76 }, { 2, 9, 16, 24, 34, 46, 64, 96, -2, -9, -16, -24, -34, -46, -64, -96 }, { 3, 11, 19, 29, 41, 57, 79, 117, -3, -11, -19, -29, -41, -57, -79, -117 }, { 4, 13, 24, 36, 50, 69, 96, 143, -4, -13, -24, -36, -50, -69, -96, -143 }, { 4, 16, 29, 44, 62, 85, 118, 175, -4, -16, -29, -44, -62, -85, -118, -175 }, { 6, 20, 36, 54, 76, 104, 144, 214, -6, -20, -36, -54, -76, -104, -144, -214 }, }; static const int upd7759_state[16] = { -1, -1, 0, 0, 1, 2, 2, 3, -1, -1, 0, 0, 1, 2, 2, 3 }; static inline void UpdateAdpcm(int Data) { Chip->sample += upd7759_step[Chip->adpcm_state][Data]; Chip->adpcm_state += upd7759_state[Data]; /* clamp the state to 0..15 */ if (Chip->adpcm_state < 0) Chip->adpcm_state = 0; else if (Chip->adpcm_state > 15) Chip->adpcm_state = 15; } static void UPD7759AdvanceState() { switch (Chip->state) { /* Idle state: we stick around here while there's nothing to do */ case STATE_IDLE: Chip->clocks_left = 4; break; /* drop DRQ state: update to the intended state */ case STATE_DROP_DRQ: Chip->drq = 0; Chip->clocks_left = Chip->post_drq_clocks; Chip->state = Chip->post_drq_state; break; /* Start state: we begin here as soon as a sample is triggered */ case STATE_START: Chip->req_sample = Chip->rom ? Chip->fifo_in : 0x10; /* 35+ cycles after we get here, the /DRQ goes low * (first byte (number of samples in ROM) should be sent in response) * * (35 is the minimum number of cycles I found during heavy tests. * Depending on the state the chip was in just before the /MD was set to 0 (reset, standby * or just-finished-playing-previous-sample) this number can range from 35 up to ~24000). * It also varies slightly from test to test, but not much - a few cycles at most.) */ Chip->clocks_left = 70; /* 35 - breaks cotton */ Chip->state = STATE_FIRST_REQ; break; /* First request state: issue a request for the first byte */ /* The expected response will be the index of the last sample */ case STATE_FIRST_REQ: Chip->drq = 1; /* 44 cycles later, we will latch this value and request another byte */ Chip->clocks_left = 44; Chip->state = STATE_LAST_SAMPLE; break; /* Last sample state: latch the last sample value and issue a request for the second byte */ /* The second byte read will be just a dummy */ case STATE_LAST_SAMPLE: Chip->last_sample = Chip->rom ? Chip->rom[0] : Chip->fifo_in; Chip->drq = 1; /* 28 cycles later, we will latch this value and request another byte */ Chip->clocks_left = 28; /* 28 - breaks cotton */ Chip->state = (Chip->req_sample > Chip->last_sample) ? STATE_IDLE : STATE_DUMMY1; break; /* First dummy state: ignore any data here and issue a request for the third byte */ /* The expected response will be the MSB of the sample address */ case STATE_DUMMY1: Chip->drq = 1; /* 32 cycles later, we will latch this value and request another byte */ Chip->clocks_left = 32; Chip->state = STATE_ADDR_MSB; break; /* Address MSB state: latch the MSB of the sample address and issue a request for the fourth byte */ /* The expected response will be the LSB of the sample address */ case STATE_ADDR_MSB: Chip->offset = (Chip->rom ? Chip->rom[Chip->req_sample * 2 + 5] : Chip->fifo_in) << 9; Chip->drq = 1; /* 44 cycles later, we will latch this value and request another byte */ Chip->clocks_left = 44; Chip->state = STATE_ADDR_LSB; break; /* Address LSB state: latch the LSB of the sample address and issue a request for the fifth byte */ /* The expected response will be just a dummy */ case STATE_ADDR_LSB: Chip->offset |= (Chip->rom ? Chip->rom[Chip->req_sample * 2 + 6] : Chip->fifo_in) << 1; Chip->drq = 1; /* 36 cycles later, we will latch this value and request another byte */ Chip->clocks_left = 36; Chip->state = STATE_DUMMY2; break; /* Second dummy state: ignore any data here and issue a request for the the sixth byte */ /* The expected response will be the first block header */ case STATE_DUMMY2: Chip->offset++; Chip->first_valid_header = 0; Chip->drq = 1; /* 36?? cycles later, we will latch this value and request another byte */ Chip->clocks_left = 36; Chip->state = STATE_BLOCK_HEADER; break; /* Block header state: latch the header and issue a request for the first byte afterwards */ case STATE_BLOCK_HEADER: /* if we're in a repeat loop, reset the offset to the repeat point and decrement the count */ if (Chip->repeat_count) { Chip->repeat_count--; Chip->offset = Chip->repeat_offset; } Chip->block_header = Chip->rom ? Chip->rom[Chip->offset++ & 0x1ffff] : Chip->fifo_in; Chip->drq = 1; /* our next step depends on the top two bits */ switch (Chip->block_header & 0xc0) { case 0x00: /* silence */ Chip->clocks_left = 1024 * ((Chip->block_header & 0x3f) + 1); Chip->state = (Chip->block_header == 0 && Chip->first_valid_header) ? STATE_IDLE : STATE_BLOCK_HEADER; Chip->sample = 0; Chip->adpcm_state = 0; break; case 0x40: /* 256 nibbles */ Chip->sample_rate = (Chip->block_header & 0x3f) + 1; Chip->nibbles_left = 256; Chip->clocks_left = 36; /* just a guess */ Chip->state = STATE_NIBBLE_MSN; break; case 0x80: /* n nibbles */ Chip->sample_rate = (Chip->block_header & 0x3f) + 1; Chip->clocks_left = 36; /* just a guess */ Chip->state = STATE_NIBBLE_COUNT; break; case 0xc0: /* repeat loop */ Chip->repeat_count = (Chip->block_header & 7) + 1; Chip->repeat_offset = Chip->offset; Chip->clocks_left = 36; /* just a guess */ Chip->state = STATE_BLOCK_HEADER; break; } /* set a flag when we get the first non-zero header */ if (Chip->block_header != 0) Chip->first_valid_header = 1; break; /* Nibble count state: latch the number of nibbles to play and request another byte */ /* The expected response will be the first data byte */ case STATE_NIBBLE_COUNT: Chip->nibbles_left = (Chip->rom ? Chip->rom[Chip->offset++ & 0x1ffff] : Chip->fifo_in) + 1; Chip->drq = 1; /* 36?? cycles later, we will latch this value and request another byte */ Chip->clocks_left = 36; /* just a guess */ Chip->state = STATE_NIBBLE_MSN; break; /* MSN state: latch the data for this pair of samples and request another byte */ /* The expected response will be the next sample data or another header */ case STATE_NIBBLE_MSN: Chip->adpcm_data = Chip->rom ? Chip->rom[Chip->offset++ & 0x1ffff] : Chip->fifo_in; UpdateAdpcm(Chip->adpcm_data >> 4); Chip->drq = 1; /* we stay in this state until the time for this sample is complete */ Chip->clocks_left = Chip->sample_rate * 4; if (--Chip->nibbles_left == 0) Chip->state = STATE_BLOCK_HEADER; else Chip->state = STATE_NIBBLE_LSN; break; /* LSN state: process the lower nibble */ case STATE_NIBBLE_LSN: UpdateAdpcm(Chip->adpcm_data & 15); /* we stay in this state until the time for this sample is complete */ Chip->clocks_left = Chip->sample_rate * 4; if (--Chip->nibbles_left == 0) Chip->state = STATE_BLOCK_HEADER; else Chip->state = STATE_NIBBLE_MSN; break; } /* if there's a DRQ, fudge the state */ if (Chip->drq) { Chip->post_drq_state = Chip->state; Chip->post_drq_clocks = Chip->clocks_left - 21; Chip->state = STATE_DROP_DRQ; Chip->clocks_left = 21; } } static void UPD7759SlaveModeUpdate() { UINT8 OldDrq = Chip->drq; UPD7759AdvanceState(); if (OldDrq != Chip->drq && Chip->drqcallback) { (*Chip->drqcallback)(Chip->drq); } } void UPD7759Update(int chip, short *pSoundBuf, int nLength) { Chip = Chips[chip]; INT32 ClocksLeft = Chip->clocks_left; INT16 Sample = Chip->sample; UINT32 Step = Chip->step; UINT32 Pos = Chip->pos; /* loop until done */ if (Chip->state != STATE_IDLE) while (nLength != 0) { /* store the current sample */ pSoundBuf[0] += Sample << 7; pSoundBuf[1] += Sample << 7; pSoundBuf += 2; nLength--; /* advance by the number of clocks/output sample */ Pos += Step; /* handle clocks, but only in standalone mode */ while (Chip->rom && Pos >= FRAC_ONE) { int ClocksThisTime = Pos >> FRAC_BITS; if (ClocksThisTime > ClocksLeft) ClocksThisTime = ClocksLeft; /* clock once */ Pos -= ClocksThisTime * FRAC_ONE; ClocksLeft -= ClocksThisTime; /* if we're out of clocks, time to handle the next state */ if (ClocksLeft == 0) { /* advance one state; if we hit idle, bail */ UPD7759AdvanceState(); if (Chip->state == STATE_IDLE) break; /* reimport the variables that we cached */ ClocksLeft = Chip->clocks_left; Sample = Chip->sample; } } } if (SlaveMode && ClocksLeft > 0) UPD7759SlaveModeUpdate(); Chip->clocks_left = ClocksLeft; Chip->pos = Pos; } void UPD7759Reset() { for (int i = 0; i < 2; i++) { Chip = Chips[i]; if (Chip == NULL) { continue; } Chip->pos = 0; Chip->fifo_in = 0; Chip->drq = 0; Chip->state = STATE_IDLE; Chip->clocks_left = 0; Chip->nibbles_left = 0; Chip->repeat_count = 0; Chip->post_drq_state = STATE_IDLE; Chip->post_drq_clocks = 0; Chip->req_sample = 0; Chip->last_sample = 0; Chip->block_header = 0; Chip->sample_rate = 0; Chip->first_valid_header = 0; Chip->offset = 0; Chip->repeat_offset = 0; Chip->adpcm_state = 0; Chip->adpcm_data = 0; Chip->sample = 0; } } void UPD7759Init(int chip, int clock, unsigned char* pSoundData) { Chips[chip] = (struct upd7759_chip*)malloc(sizeof(*Chip)); Chip = Chips[chip]; memset(Chip, 0, sizeof(*Chip)); SlaveMode = 0; float Rate = (float)clock / 4 / nBurnSoundRate; Chip->step = (int)(4 * FRAC_ONE * Rate); Chip->state = STATE_IDLE; if (pSoundData) { Chip->rom = pSoundData; } else { SlaveMode = 1; } Chip->reset = 1; Chip->start = 1; UPD7759Reset(); } void UPD7759SetDrqCallback(int chip, drqcallback Callback) { Chip = Chips[chip]; Chip->drqcallback = Callback; } int UPD7759BusyRead(int chip) { Chip = Chips[chip]; return (Chip->state == STATE_IDLE); } void UPD7759ResetWrite(int chip, UINT8 Data) { Chip = Chips[chip]; UINT8 Oldreset = Chip->reset; Chip->reset = (Data != 0); if (Oldreset && !Chip->reset) { UPD7759Reset(); } } void UPD7759StartWrite(int chip, UINT8 Data) { Chip = Chips[chip]; UINT8 Oldstart = Chip->start; Chip->start = (Data != 0); if (Chip->state == STATE_IDLE && !Oldstart && Chip->start && Chip->reset) { Chip->state = STATE_START; if (SlaveMode) UPD7759SlaveModeUpdate(); } } void UPD7759PortWrite(int chip, UINT8 Data) { Chip = Chips[chip]; Chip->fifo_in = Data; } int UPD7759Scan(int chip, int nAction,int *pnMin) { struct BurnArea ba; char szName[16]; if ((nAction & ACB_DRIVER_DATA) == 0) { return 1; } if (pnMin != NULL) { *pnMin = 0x029680; } Chip = Chips[chip]; sprintf(szName, "UPD7759 %d", chip); ba.Data = &Chip; ba.nLen = sizeof(struct upd7759_chip); ba.nAddress = 0; ba.szName = szName; BurnAcb(&ba); return 0; } void UPD7759Exit() { if (Chips[0]) { free(Chips[0]); Chips[0] = NULL; } if (Chips[1]) { free(Chips[1]); Chips[1] = NULL; } SlaveMode = 0; }
[ [ [ 1, 497 ] ] ]
c04e74d7a7d5a16cbcde49aa61400ccd2bba7bc9
9e4b72c504df07f6116b2016693abc1566b38310
/back/ProcessController.h
8e2d51275629d1672c3c8c39c9799910f2ac5a66
[ "MIT" ]
permissive
mmeeks/rep-snapper
73311cadd3d8753462cf87a7e279937d284714aa
3a91de735dc74358c0bd2259891f9feac7723f14
refs/heads/master
2016-08-04T08:56:55.355093
2010-12-05T19:03:03
2010-12-05T19:03:03
704,101
0
1
null
null
null
null
UTF-8
C++
false
false
6,856
h
/* -------------------------------------------------------- * * * ProcessController.h * * Copyright 2009+ Michael Holm - www.kulitorum.com * * This file is part of RepSnapper and is made available under * the terms of the GNU General Public License, version 2, or at your * option, any later version, incorporated herein by reference. * * ------------------------------------------------------------------------- */ #pragma once #include "stdafx.h" #include "Printer.h" #include "xml/XML.H" #include <vmmlib/vmmlib.h> #include "UI.h" #include "stl.h" #include "gcode.h" #include "RFO.h" class GCode; struct lua_State; using namespace std; class ProcessController { public: ProcessController(){ m_iSerialSpeed = 19200; // default parameters (are overwritten by the xml loading) RaftSize = 1.33f; RaftBaseLayerCount = 1; RaftMaterialPrDistanceRatio = 1.8f; RaftRotation = 90.0f; RaftBaseDistance = 2.0f; RaftBaseThickness = 1.0f; RaftBaseTemperature = 1.10f; RaftInterfaceLayerCount = 2; RaftInterfaceMaterialPrDistanceRatio = 1.0f; RaftRotationPrLayer = 90.0f; RaftInterfaceDistance = 2.0f; RaftInterfaceThickness = 1.0f; RaftInterfaceTemperature = 1.0f; m_Filename = "./repsnapper"; // Printer m_fVolume = Vector3f(200,200,140); PrintMargin = Vector3f(10,10,0); ExtrudedMaterialWidth = 0.7f; // 0.7 KeepLines = 1000; //GCode GCodeDrawStart = 0.0f;; GCodeDrawEnd = 1.0f; MinPrintSpeedXY = 1000.0f; MaxPrintSpeedXY = 4000.0f; MinPrintSpeedZ = 50.0f; MaxPrintSpeedZ = 150.0f; DistanceToReachFullSpeed= 1.5f; extrusionFactor = 1.0f; UseIncrementalEcode = false; Use3DGcode = false; LayerThickness = 0.4f; CuttingPlaneValue = 0.5f; PolygonOpasity = 0.5f; DisplayEndpoints = false; DisplayNormals = false; DisplayBBox = false; DisplayWireframe = false; DisplayWireframeShaded = true; DisplayPolygons = false; DisplayAllLayers = false; DisplayinFill = false; InfillDistance = 2.0f; InfillRotation = 45.0f; InfillRotationPrLayer = 90.0f; Examine = 0.5f; DisplayDebuginFill = false; DisplayDebug = false; DisplayCuttingPlane = true; DrawVertexNumbers=false; DrawLineNumbers=false; ShellOnly = false; ShellCount = 1; EnableAcceleration = true; DisplayDebuginFill = true; DisplayCuttingPlane = true; FileLogginEnabled = true; TempReadingEnabled = true; ClearLogfilesWhenPrintStarts = true; Min = Vector3f(0, 0, 0); Max = Vector3f(200,200,200); Center.x = Center.y = 100.0f; Center.z = 0.0f; gui = 0; CustomButtonGcode.resize(20); CustomButtonLabel.resize(20); }; // ProcessController::~ProcessController(); void SetFilename(string filename) { m_Filename = filename;} void Draw(Flu_Tree_Browser::Node *selected_node); // STL Functions bool ReadStl(string filename, STL &newstl) { return newstl.Read(filename);}; void OptimizeRotation(); void RotateObject(Vector3f axis, float a); Matrix4f GetSTLTransformationMatrix(int object=-1, int file=-1) const ; void CalcBoundingBoxAndZoom(); void ConvertToGCode(string &GcodeTxt, const string &GcodeStart, const string &GcodeLayer, const string &GcodeEnd); // GCode Functions void ReadGCode(string filename) {gcode.Read(filename);}; void WriteGCode(string &GcodeTxt, const string &GcodeStart, const string &GcodeLayer, const string &GcodeEnd, string filename); void MakeRaft(float &z); //Printer void SetVolume(float x, float y, float z) { m_fVolume = Vector3f(x,y,z);} // Load and save settings void LoadXML(); void SaveXML(); void SaveXML(string filename); void LoadXML(XMLElement *e); void SaveXML(XMLElement *e); // LUA // void BindLua(lua_State *myLuaState); // Process functions string m_Filename; // Start, layer, end GCode string GCodeStartText; string GCodeLayerText; string GCodeEndText; /*--------------Models-------------------*/ Printer printer; // Printer settings and functions string m_sPortName; int m_iSerialSpeed; int KeepLines; // STL stl; // A STL file RFO rfo; GCode gcode; // Gcode as binary data string GcodeTxt; // Final GCode as text // Raft float RaftSize; uint RaftBaseLayerCount; float RaftMaterialPrDistanceRatio; float RaftRotation; float RaftBaseDistance; float RaftBaseThickness; float RaftBaseTemperature; uint RaftInterfaceLayerCount; float RaftInterfaceMaterialPrDistanceRatio; float RaftRotationPrLayer; float RaftInterfaceDistance; float RaftInterfaceThickness; float RaftInterfaceTemperature; // GCode float GCodeDrawStart; float GCodeDrawEnd; float MinPrintSpeedXY; float MaxPrintSpeedXY; float MinPrintSpeedZ; float MaxPrintSpeedZ; float DistanceToReachFullSpeed; float extrusionFactor; // Printer Vector3f m_fVolume; // Max print volume Vector3f PrintMargin; Vector3f printOffset; // Summed up margin+raft+Apron etc. float ExtrudedMaterialWidth; // Width of extruded material bool UseIncrementalEcode; bool Use3DGcode; // STL float LayerThickness; float CuttingPlaneValue; float PolygonOpasity; // CuttingPlane float InfillDistance; float InfillRotation; float InfillRotationPrLayer; float Examine; bool ShellOnly; uint ShellCount; bool EnableAcceleration; bool FileLogginEnabled; bool TempReadingEnabled; bool ClearLogfilesWhenPrintStarts; // GUI... ? bool DisplayEndpoints; bool DisplayNormals; bool DisplayBBox; bool DisplayWireframe; bool DisplayWireframeShaded; bool DisplayPolygons; bool DisplayAllLayers; bool DisplayinFill; bool DisplayDebuginFill; bool DisplayDebug; bool DisplayCuttingPlane; bool DrawVertexNumbers; bool DrawLineNumbers; string Notes; // Rendering float PolygonVal; float PolygonSat; float PolygonHue; float WireframeVal; float WireframeSat; float WireframeHue; float NormalsSat; float NormalsVal; float NormalsHue; float EndpointsSat; float EndpointsVal; float EndpointsHue; float GCodeExtrudeHue; float GCodeExtrudeSat; float GCodeExtrudeVal; float GCodeMoveHue; float GCodeMoveSat; float GCodeMoveVal; float Highlight; float NormalsLength; float EndPointSize; float TempUpdateSpeed; bool LuminanceShowsSpeed; bool DisplayGCode; bool ApronEnable; bool ApronPreview; bool RaftEnable; float ApronSize; float ApronHeight; float ApronCoverageX; float ApronCoverageY; float ApronDistanceToObject; float ApronInfillDistance; int m_ShrinkQuality; // Bounding box info Vector3f Center; Vector3f Min; Vector3f Max; vector<string>CustomButtonGcode; vector<string>CustomButtonLabel; // Maybe a pointer to the gui GUI *gui; };
[ [ [ 1, 289 ] ] ]