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
77fae60d395b5f7f4b879f044f1d0621fbc1b183
9907be749dc7553f97c9e51c5f35e69f55bd02c0
/Login/user.cpp
2554b787e9cb882e42e39020337f9cba49358471
[]
no_license
jdeering/csci476winthrop
bc8907b9cc0406826de76aca05e6758810377813
2bc485781f819c8fd82393ac86de33404e7ad6d3
refs/heads/master
2021-01-10T19:53:14.853438
2009-04-24T14:26:36
2009-04-24T14:26:36
32,223,762
0
0
null
null
null
null
UTF-8
C++
false
false
12,942
cpp
#include "user.h" int createUser(string username, string password, string verpass) // createUser // Arguments: username - username for new user // password - password for new user // verpass - ensures password accuracy // Attempts to create a new user with the username and password given. // Checks to see if the password and verpass match and if a user with // the given username already exists. // Returns: An integer that represents the success of the user creation. // -1 = failed user creation (user with username already exists) // 0 = failed user creation (mismatched password and verpass) // 1 = successful user creation { md5wrapper md5; // Used for password encryption/decryption if (password != verpass) //If password and verpass do not match return 0; //Return failed user creation (mismatched password and verpass) ifstream inp, loginFileIn; ofstream loginFileOut; inp.open("data\\users.dat", ios::in); inp.close(); if(!inp.fail()) // If users data file exists { loginFileIn.open("data\\users.dat"); // File containing usernames and passwords string tempuser; // Used for iterating over usernames in file loginFileIn >> tempuser; while(!loginFileIn.eof()) { if(tempuser == username) //If the username already exists { loginFileIn.close(); // Close user data file return -1; //Return failed user creation (user with username already exists) } loginFileIn >> tempuser >> tempuser; //Else, keep iterating over the file } loginFileIn.close(); // Close user data file after end of iteration } else inp.clear(ios::failbit); //Else, clear failure bit // Open the data file for appending loginFileOut.open("data\\users.dat", ios::out | ios::app); // User credentials written to file loginFileOut << username << "\t" << md5.getHashFromString(password + username) << endl; loginFileOut.close(); // Close user data file return 1; // Return successful user creation! } vector<string> showScores(string module) // showScores // Arguments: module - a string representing the name of the module from where // the scores are retrieved // // Pushes all users' scores from a given module to a string vector // // Returns: A string vector containing usernames in the format: // [username],[score],...,[username],[score] { vector<string> scores; // Vector for storing usernames and scores CMarkup xmlscores; // Declares an XML object for reading in scores.xml ifstream inp; string scoreFileStream = "modules\\" + module + "\\users\\scores.xml"; inp.open( scoreFileStream.c_str(), ios::in); inp.close(); if(inp.fail()) // Tests to see if the module's scores.xml file exists // If it does not exist... { inp.clear(ios::failbit); return scores; // Return empty vector } else // Else, if scores.xml does exist { xmlscores.Load( StringToWString(scoreFileStream) ); //Load the XML document into memory xmlscores.FindElem( MCD_T("SCORES") ); // Find the SCORES element in the document xmlscores.IntoElem(); // Go inside the SCORES tags while(xmlscores.FindElem()) // While there are still SCORES { scores.push_back(WStringToString(xmlscores.GetData())); // Push score onto vector scores.push_back(WStringToString(xmlscores.GetAttrib(MCD_T ("name") ))); // Push user name onto vector } } return scores; // Return the vector of usernames and scores } wstring StringToWString(const string& s) // StringToWString // Arguments: s - standard string // Converts an std string to an std wstring // Returns: An std wstring { wstring temp(s.length(),L' '); copy(s.begin(), s.end(), temp.begin()); return temp; } string WStringToString(const wstring& s) // WStringToString // Arguments: s - standard wide string // Converts an std wstring to an std string // Returns: An std string { string temp(s.length(),' '); copy(s.begin(),s.end(),temp.begin()); return temp; } string IntToString(int i) // IntToString // Arguments: i - integer to be converted // Converts an integer to an std string // Returns: A string converted from i { string s; stringstream out; out << i; s = out.str(); return s; } //********************************* // USER CLASS METHODS //********************************* User::User(string usr, string pwd) // User class constructor // Arguments: usr - username for user instance // pwd - password for user instance // Creates a user with the username and password in the arguments // and attempts to log this user in. If unsuccessful, the constructor // throws an exception to be caught by the caller of the function. // Values of the exception described in the login function. // Returns: Nothing (constructor) { username = usr; int success = login(pwd); cout << success << endl; if(!success) throw success; } // Sets the default value of the static variable isLoggedIn to false // (no one is logged in at first) bool User::isLoggedIn = false; int User::login(string password) // User::login // Arguments: password - password used for the login process // Attempts to login a user with its username and the password argument. // Checks to see if a user is already logged in and if the correct password/username // combination was used. // Returns: An integer that represents the success of the login. // 0 = failed login // 1 = successful login { md5wrapper md5; // Used for encrypting and decrypting passwords if(User::getIsLoggedIn()) return 0; // If a user is already logged in // Return failed login value ifstream loginFile; string tempuser, temppass; // Temporary strings used to iterate through user file loginFile.open("data\\users.dat"); // File containing usernames and passwords loginFile >> tempuser; while(!loginFile.eof()) { if(tempuser == username) //If the username matches { loginFile >> temppass; if(temppass == md5.getHashFromString(password+username)) //Check the MD5 encrypted password { // Logs the user in if the passwords match // and sets the users isUserLoggedIn value to true // as well ast the static isLoggedIn variable to true loginFile.close(); User::isLoggedIn = true; isUserLoggedIn = true; return 1; // Return login success! } } else // Continue iterating the file { loginFile >> temppass; } loginFile >> tempuser; } loginFile.close(); // Close user file return 0; // Return failed login value (no matching entries) } int User::setScore(string module, int score) /** XML FILE PARSER **/ { ifstream userInp, scoreInp; string userFileStream = "modules\\" + module + "\\users\\" + username + ".xml"; string scoreFileStream = "modules\\" + module + "\\users\\scores.xml"; userInp.open(userFileStream.c_str(), ifstream::in); userInp.close(); if(userInp.fail()) //if user's xml file does not exist { userInp.clear(ios::failbit); //write xml heading and structure for new user //with first, last, and average score = score //set number of times played to 1 //write closure tags ofstream newxml; newxml.open(userFileStream.c_str()); newxml << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" << endl; newxml << "<USER name = \"" << username << "\">" << endl; newxml << "\t<FIRSTSCORE>" << score << "</FIRSTSCORE>" << endl; newxml << "\t<LASTSCORE>" << score << "</LASTSCORE>" << endl; newxml << "\t<PLAYS>1</PLAYS>" << endl; newxml << "\t<AVERAGESCORE>" << score << "</AVERAGESCORE>" << endl; newxml << "\t<BESTSCORE>" << score << "</BESTSCORE>" << endl; newxml << "</USER>"; newxml.close(); // close xml file scoreInp.open(scoreFileStream.c_str(), ifstream::in); scoreInp.close(); if(scoreInp.fail()) // if module's xml file does not exist { // add xml heading and current users information scoreInp.clear(ios::failbit); newxml.open(scoreFileStream.c_str()); newxml << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" << endl; newxml << "<SCORES>" << endl; newxml << "\t<USER name = \"" << username << "\">" << score << "<\USER>" << endl; newxml << "</SCORES>" << endl; newxml.close(); //close xml file } else // module's xml file already exists { CMarkup scorexml; wstring currscore, curruser; cout << "reallyhere" << endl; //load the module's xml file scorexml.Load( StringToWString(scoreFileStream) ); scorexml.FindElem( MCD_T("SCORES") ); scorexml.IntoElem(); while(scorexml.FindElem()) //iterate through all scores { currscore = scorexml.GetData(); if(atoi(WStringToString(currscore).c_str()) > score) //if current score is greater than user's score continue; // continue down the list else // user's score is greater than current score { // insert user's name and score above current record // and break from loop scorexml.InsertElem( MCD_T("USER"), StringToWString(IntToString(score)) ); scorexml.AddAttrib( MCD_T("name"), StringToWString(username) ); scorexml.SetData( StringToWString(IntToString(score)) ); break; } } scorexml.Save(StringToWString(scoreFileStream)); } return 0; } else { CMarkup userxml, scorexml; int plays; int average; wstring tempWstring, currscore; //load user's xml file userxml.Load(StringToWString(userFileStream)); //find last score userxml.FindElem( MCD_T("USER") ); userxml.IntoElem(); userxml.FindElem( MCD_T("LASTSCORE") ); //replace last score userxml.SetData( StringToWString(IntToString(score)) ); //find and increment number of plays userxml.FindElem( MCD_T("PLAYS") ); tempWstring = userxml.GetData(); plays = (atoi(WStringToString(tempWstring).c_str())); plays++; userxml.SetData( StringToWString(IntToString(plays)) ); //find and recalculate average userxml.FindElem( MCD_T("AVERAGESCORE") ); tempWstring = userxml.GetData(); string tempAvgstring(tempWstring.begin(), tempWstring.end()); average = (atoi(tempAvgstring.c_str()) + score)/plays; userxml.SetData( StringToWString(IntToString(average)) ); userxml.FindElem( MCD_T("BESTSCORE") ); currscore = userxml.GetData(); if(score > atoi(WStringToString(currscore).c_str())) { userxml.SetData( StringToWString(IntToString(score)) ); //open scores.xml file scorexml.Load( StringToWString(scoreFileStream)); //find user scorexml.FindElem( MCD_T("SCORES") ); scorexml.IntoElem(); //find score while(scorexml.FindElem()) // iterate through all scores { currscore = scorexml.GetData(); if(atoi(WStringToString(currscore).c_str()) > score) continue; else // if current score is less than user's score, insert // user's name and score, and break out of loop { scorexml.InsertElem( MCD_T("USER"), StringToWString(IntToString(score)) ); scorexml.AddAttrib( MCD_T("name"), StringToWString(username) ); scorexml.SetData( StringToWString(IntToString(score)) ); break; } } scorexml.Save(StringToWString(scoreFileStream)); } userxml.Save(StringToWString(userFileStream)); return 1; } } string User::getUserName() { return username; } bool User::getIsLoggedIn() { return isLoggedIn; } bool User::getIsUserLoggedIn() { return isUserLoggedIn; } int User::logout() { if(isLoggedIn) { isLoggedIn = false; isUserLoggedIn = false; return 1; } else return 0; // logout failed } vector<string> User::getProgressReport(string module) { /** XML FILE PARSER **/ CMarkup userxml; vector<string> progressVec; wstring currWscore; string userFileStream = "modules\\" + module + "\\users\\" + username + ".xml"; progressVec.push_back("User"); progressVec.push_back(username); userxml.Load( StringToWString(userFileStream) ); userxml.FindElem(MCD_T("USER")); userxml.IntoElem(); userxml.FindElem(MCD_T("FIRSTSCORE")); progressVec.push_back("First Score"); currWscore = userxml.GetData(); progressVec.push_back(WStringToString(currWscore)); userxml.FindElem(MCD_T("LASTSCORE")); progressVec.push_back("Last Score"); currWscore = userxml.GetData(); progressVec.push_back(WStringToString(currWscore)); userxml.FindElem(MCD_T("PLAYS")); progressVec.push_back("Plays"); currWscore = userxml.GetData(); progressVec.push_back(WStringToString(currWscore)); userxml.FindElem(MCD_T("AVERAGESCORE")); progressVec.push_back("Average Score"); currWscore = userxml.GetData(); progressVec.push_back(WStringToString(currWscore)); userxml.FindElem(MCD_T("BESTSCORE")); progressVec.push_back("Best Score"); currWscore = userxml.GetData(); progressVec.push_back(WStringToString(currWscore)); return progressVec; }
[ "lcairco@2656ef14-ecf4-11dd-8fb1-9960f2a117f8" ]
[ [ [ 1, 414 ] ] ]
07efba4549c8bee054f66aab01ee47206554a1cc
26706a661c23f5c2c1f97847ba09f44b7b425cf6
/TaskManager/TaskManagerDlg.h
31710d373c73a4d3f95af6c8cc37f6e35e9e8cb7
[]
no_license
124327288/nativetaskmanager
96a54dbe150f855422d7fd813d3631eaac76fadd
e75b3d9d27c902baddbb1bef975c746451b1b8bb
refs/heads/master
2021-05-29T05:18:26.779900
2009-02-10T13:23:28
2009-02-10T13:23:28
null
0
0
null
null
null
null
GB18030
C++
false
false
1,559
h
// TaskManagerDlg.h : 头文件 // #pragma once #include "afxcmn.h" #include "DlgApplication.h" #include "DlgService.h" #include "DlgProcess.h" #include "DlgModule.h" #include "DlgDriver.h" #include "XTabCtrl.h" #include <vector> using namespace std; // CTaskManagerDlg 对话框 class CTaskManagerDlg : public CDialog { // 构造 public: CTaskManagerDlg(CWnd* pParent = NULL); // 标准构造函数 // 对话框数据 enum { IDD = IDD_TASKMANAGER_DIALOG ,MAX_DLG=6}; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 virtual BOOL OnInitDialog(); private: CXTabCtrl m_wndTabMain; CDlgApplication m_wndDlgApp; // Application CDlgService m_wndDlgService; // Service CDlgProcess m_wndDlgProcess; // Process CDlgModule m_wndDlgModule; // Module CDlgDriver m_wndDlgDrive; // Drive vector<TabInfo> m_vecTabInfo; // Tab Infomation private: void InitTab(); // 初始化Tab // 实现 protected: HICON m_hIcon; public: DECLARE_EASYSIZE // 生成的消息映射函数 DECLARE_MESSAGE_MAP() afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnTcnSelchangeTab(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnTcnSelchangingTab(NMHDR *pNMHDR, LRESULT *pResult); afx_msg LRESULT OnTabSelChange(WPARAM wParam,LPARAM lParam); };
[ "[email protected]@97a26042-f463-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 69 ] ] ]
bb26c8173820d931f7f23609f75edeb6d8ad073e
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/MeshLoadPolicyXFile.cpp
5682146e698afd5cb6641dec5e6fb9ffc753a36d
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
10,070
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: MeshLoadPolicyXFile.cpp Version: 0.10 --------------------------------------------------------------------------- */ #include "PrecompiledHeaders.h" #include "MeshLoadPolicyXFile.h" #include "DeviceRender.h" #include "DX9Mapping.h" #include "Surface.h" #include "Vertex.h" #include "VertexBufferManager.h" #include "VertexDeclaration.h" #include "AABB.h" namespace nGENE { // Initialize static members TypeInfo MeshLoadPolicyXFile::Type(L"MeshLoadPolicyXFile", NULL); MeshLoadPolicyXFile::MeshLoadPolicyXFile() { } //---------------------------------------------------------------------- vector <Surface> MeshLoadPolicyXFile::loadMesh(const wstring& _fileName, const Matrix4x4& _transform, bool _moveToCentre) { m_matTransform = _transform; m_bMoveToCentre = _moveToCentre; vector <Surface> vPolicySurfaces; // Mesh surfaces ID3DXMesh* pStartMesh = NULL; ID3DXMesh* pMesh = NULL; dword dwMaterialNum = 0; HRESULT hr = 0; IDirect3DDevice9* pDevice = reinterpret_cast<IDirect3DDevice9*>(Renderer::getSingleton().getDeviceRender().getDevicePtr()); // Open file FileManager& mgr = FileManager::getSingleton(); IFile* pFile = mgr.openFile(_fileName, OPEN_READ | OPEN_BINARY, FT_NORMAL); uint size = pFile->getSize(); void* buffer = new char[size]; pFile->read((char*)buffer, size); mgr.closeFile(_fileName); // Load ID3DXMesh if(FAILED(hr = D3DXLoadMeshFromXInMemory(buffer, size, D3DXMESH_MANAGED, pDevice, NULL, NULL, NULL, &dwMaterialNum, &pStartMesh))) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"%ls .x file loading failed. Reason: %ls", _fileName.c_str(), DX9Mapping::getDXErrorDescription(hr).c_str()); NGENE_DELETE_ARRAY(buffer); return vPolicySurfaces; } NGENE_DELETE_ARRAY(buffer); // Clone mesh if necessary pMesh = cloneMesh(pStartMesh, pDevice); // Optimize mesh optimizeMesh(pMesh); // Get attributes table dword dwAttributesNum = 0; D3DXATTRIBUTERANGE* pAttrTable = NULL; getAttributesTable(pMesh, dwAttributesNum, &pAttrTable); // Process attributes table and mesh itself processMesh(pMesh, dwAttributesNum, pAttrTable, vPolicySurfaces); NGENE_RELEASE(pMesh); return vPolicySurfaces; } //---------------------------------------------------------------------- ID3DXMesh* MeshLoadPolicyXFile::cloneMesh(ID3DXMesh* _mesh, IDirect3DDevice9* _device) { VertexDeclaration* pDecl = VertexBufferManager::getSingleton().getVertexDeclaration(L"Default"); D3DVERTEXELEMENT9 elements[MAX_FVF_DECL_SIZE]; _mesh->GetDeclaration(elements); uint count = 0; while(elements[count++].Stream != 255); bool equal = true; if(--count == pDecl->getCount()) { for(uint i = 0; i < pDecl->getCount(); ++i) { D3DVERTEXELEMENT9 element = DX9Mapping::svertexElementToD3DVERTEXELEMENT9(*pDecl->getVertexElement(i)); if((elements[i].Method != element.Method) || (elements[i].Offset != element.Offset) || (elements[i].Stream != element.Stream) || (elements[i].Type != element.Type) || (elements[i].Usage != element.Usage) || (elements[i].UsageIndex != (elements[i].UsageIndex))) { equal = false; break; } } } else equal = false; ID3DXMesh* pMesh = NULL; if(!equal) { D3DVERTEXELEMENT9* pElements = new D3DVERTEXELEMENT9[pDecl->getCount() + 1]; for(uint i = 0; i < pDecl->getCount(); ++i) pElements[i] = DX9Mapping::svertexElementToD3DVERTEXELEMENT9(*pDecl->getVertexElement(i)); pElements[pDecl->getCount()].Method = 0; pElements[pDecl->getCount()].Offset = 0; pElements[pDecl->getCount()].Stream = 0xFF; pElements[pDecl->getCount()].Type = D3DDECLTYPE_UNUSED; pElements[pDecl->getCount()].Usage = 0; pElements[pDecl->getCount()].UsageIndex = 0; dword flags = D3DXMESH_MANAGED; if(_mesh->GetOptions() & D3DXMESH_32BIT) flags |= D3DXMESH_32BIT; HRESULT hr = _mesh->CloneMesh(flags, pElements, _device, &pMesh); if(hr != S_OK) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"Mesh format doesn't match. Reason: %ls", DX9Mapping::getDXErrorDescription(hr).c_str()); return NULL; } NGENE_RELEASE(_mesh); } else pMesh = _mesh; return pMesh; } //---------------------------------------------------------------------- void MeshLoadPolicyXFile::optimizeMesh(ID3DXMesh* _mesh) { ID3DXMesh* pMesh = _mesh; dword* pAdj = new dword[3 * pMesh->GetNumFaces() * sizeof(dword)]; HRESULT hr = 0; // Generate adjacency information if(FAILED(hr = pMesh->GenerateAdjacency(0.00001f, pAdj))) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"Adjacency information could not be generated. Reason: %ls", DX9Mapping::getDXErrorDescription(hr)); return; } // Optimize in-place if(FAILED(hr = pMesh->OptimizeInplace(D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT, pAdj, NULL, NULL, NULL))) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"Mesh could not be optimized. Reason: %ls", DX9Mapping::getDXErrorDescription(hr)); return; } } //---------------------------------------------------------------------- void MeshLoadPolicyXFile::getAttributesTable(ID3DXMesh* _mesh, dword& _numAttrs, D3DXATTRIBUTERANGE** _table) { ID3DXMesh* pMesh = _mesh; HRESULT hr = 0; if(FAILED(hr = pMesh->GetAttributeTable(NULL, &_numAttrs))) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"Attribute table data could not be obtained. Reason: %ls", DX9Mapping::getDXErrorDescription(hr)); return; } (*_table) = new D3DXATTRIBUTERANGE[_numAttrs * sizeof(D3DXATTRIBUTERANGE)]; if(FAILED(hr = pMesh->GetAttributeTable((*_table), NULL))) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"Attribute table data could not be obtained. Reason: %ls", DX9Mapping::getDXErrorDescription(hr)); return; } } //---------------------------------------------------------------------- void MeshLoadPolicyXFile::processMesh(ID3DXMesh* _mesh, dword _numAttributes, D3DXATTRIBUTERANGE* _table, vector <Surface>& _surfaces) { ID3DXMesh* pMesh = _mesh; IDirect3DVertexBuffer9* pVB = NULL; IDirect3DIndexBuffer9* pIVB = NULL; SVertex* pVertices = NULL; ushort* pIndices = NULL; pMesh->GetVertexBuffer(&pVB); pMesh->GetIndexBuffer(&pIVB); // Lock the buffers dword dwIndexSize = sizeof(ushort); if(pMesh->GetOptions() & D3DXMESH_32BIT) dwIndexSize = sizeof(dword); pVB->Lock(0, pMesh->GetNumVertices() * sizeof(SVertex), reinterpret_cast<void**>(&pVertices), 0); pIVB->Lock(0, pMesh->GetNumFaces() * 3 * dwIndexSize, reinterpret_cast<void**>(&pIndices), 0); // Process attributes for(uint i = 0; i < _numAttributes; ++i) { SVertex* pVertices2 = new SVertex[_table[i].VertexCount]; memcpy(pVertices2, pVertices + _table[i].VertexStart, _table[i].VertexCount * sizeof(SVertex)); void* pTemp = NULL; if(pMesh->GetOptions() & D3DXMESH_32BIT) { dword* pIndices2 = new dword[3 * _table[i].FaceCount]; pTemp = new dword[3 * _table[i].FaceCount]; memcpy(pIndices2, pIndices + 3 * _table[i].FaceStart, 3 * _table[i].FaceCount * dwIndexSize); for(dword j = 0; j < _table[i].FaceCount; ++j) pIndices2[j] -= _table[i].VertexStart; memcpy(pTemp, pIndices2, 3 * _table[i].FaceCount * dwIndexSize); NGENE_DELETE_ARRAY(pIndices2); } else { ushort* pIndices2 = new ushort[3 * _table[i].FaceCount]; pTemp = new dword[3 * _table[i].FaceCount]; memcpy(pIndices2, pIndices + 3 * _table[i].FaceStart, 3 * _table[i].FaceCount * dwIndexSize); for(dword j = 0; j < 3 * _table[i].FaceCount; ++j) pIndices2[j] -= _table[i].VertexStart; memcpy(pTemp, pIndices2, 3 * _table[i].FaceCount * dwIndexSize); NGENE_DELETE_ARRAY(pIndices2); } if(!m_matTransform.isIdentity()) { for(uint j = 0; j < _table[i].VertexCount; ++j) { Vector4 vecPos(pVertices2[j].vecPosition, 0.0f); vecPos.multiply(m_matTransform); pVertices2[j].vecPosition.set(vecPos.x, vecPos.y, vecPos.z); } } if(m_bMoveToCentre) { AABB box; box.construct(pVertices2, _table[i].VertexCount, sizeof(SVertex), 0); Vector3 vecCentre = box.getCentre(); for(uint j = 0; j < _table[i].VertexCount; ++j) { pVertices2[j].vecPosition -= vecCentre; } } VertexBufferManager& manager = VertexBufferManager::getSingleton(); VertexBuffer* vb; IndexedBuffer* ivb; VERTEXBUFFER_DESC vbDesc; vbDesc.vertices = pVertices2; vbDesc.verticesNum = _table[i].VertexCount; vbDesc.primitivesNum = _table[i].FaceCount; vbDesc.vertexDeclaration = manager.getVertexDeclaration(L"Default"); vb = manager.createVertexBuffer(vbDesc); INDEXEDBUFFER_DESC ivbDesc; ivbDesc.indices = pTemp; ivbDesc.indicesNum = 3 * _table[i].FaceCount; ivb = manager.createIndexedBuffer(ivbDesc); vb->setIndexedBuffer(ivb); wostringstream buffer; buffer << L"surface_" << i; Surface surface(buffer.str()); surface.setVertexBuffer(vb); _surfaces.push_back(surface); NGENE_DELETE_ARRAY(pVertices2); NGENE_DELETE_ARRAY(pTemp); } pVB->Unlock(); pIVB->Unlock(); NGENE_RELEASE(pIVB); NGENE_RELEASE(pVB); } //---------------------------------------------------------------------- }
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 331 ] ] ]
1caa393d7166d948f794003a3c7ee656ce0aa934
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/depends/ClanLib/src/Core/Math/vec4.cpp
d0b836df571240a79d128b94e5aa5888b9da9937
[]
no_license
ptrefall/smn6200fluidmechanics
841541a26023f72aa53d214fe4787ed7f5db88e1
77e5f919982116a6cdee59f58ca929313dfbb3f7
refs/heads/master
2020-08-09T17:03:59.726027
2011-01-13T22:39:03
2011-01-13T22:39:03
32,448,422
1
0
null
null
null
null
UTF-8
C++
false
false
6,498
cpp
/* ** ClanLib SDK ** Copyright (c) 1997-2010 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl ** Mark Page ** (if your name is missing here, please add it) */ #include "precomp.h" #include "API/Core/Math/vec4.h" #include "API/Core/Math/angle.h" template<typename Type> Type CL_Vec4<Type>::length3() const {return (Type) floor(sqrt(float(x*x+y*y+z*z))+0.5f);} template<> double CL_Vec4<double>::length3() const {return sqrt(x*x+y*y+z*z);} template<> float CL_Vec4<float>::length3() const {return sqrt(x*x+y*y+z*z);} template<typename Type> Type CL_Vec4<Type>::length4() const {return (Type) floor(sqrt(float(x*x+y*y+z*z+w*w))+0.5f);} template<> double CL_Vec4<double>::length4() const {return sqrt(x*x+y*y+z*z+w*w);} template<> float CL_Vec4<float>::length4() const {return sqrt(x*x+y*y+z*z+w*w);} template<typename Type> CL_Vec4<Type> &CL_Vec4<Type>::normalize3() { Type f = length3(); if (f!=0) { x /= f; y /= f; z /= f; } return *this; } template<typename Type> CL_Vec4<Type> CL_Vec4<Type>::normalize3(const CL_Vec4<Type>& vector) { CL_Vec4<Type> dest(vector); dest.normalize3(); return dest; } template<typename Type> CL_Vec4<Type> &CL_Vec4<Type>::normalize4() { Type f = length4(); if (f!=0) { x /= f; y /= f; z /= f; w /= f; } return *this; } template<typename Type> CL_Vec4<Type> CL_Vec4<Type>::normalize4(const CL_Vec4<Type>& vector) { CL_Vec4<Type> dest(vector); dest.normalize4(); return dest; } template<typename Type> CL_Angle CL_Vec4<Type>::angle3(const CL_Vec4<Type>& v) const { return CL_Angle(acosf(float(dot3(v)/(length3()*v.length3()))), cl_radians); } // For floats template<> float CL_Vec4f::distance3(const CL_Vec4f &vector) const { float value_x, value_y, value_z; value_x = x - vector.x; value_y = y - vector.y; value_z = z - vector.z; return sqrt(value_x*value_x + value_y*value_y+value_z*value_z); } // For doubles template<> double CL_Vec4d::distance3(const CL_Vec4d &vector) const { double value_x, value_y, value_z; value_x = x - vector.x; value_y = y - vector.y; value_z = z - vector.z; return sqrt(value_x*value_x + value_y*value_y+value_z*value_z); } // For integers template<typename Type> Type CL_Vec4<Type>::distance3(const CL_Vec4<Type>& vector) const { float value_x, value_y, value_z; value_x = x - vector.x; value_y = y - vector.y; value_z = z - vector.z; return (Type) floor(sqrt(value_x*value_x + value_y*value_y+value_z*value_z)+0.5f); } // For integers template<typename Type> Type CL_Vec4<Type>::distance4(const CL_Vec4<Type>& vector) const { float value_x, value_y, value_z, value_w; value_x = x - vector.x; value_y = y - vector.y; value_z = z - vector.z; value_w = w - vector.w; return (Type) floor(sqrt(value_x*value_x + value_y*value_y+value_z*value_z+value_w*value_w) + 0.5f); } // For double template<> double CL_Vec4d::distance4(const CL_Vec4d &vector) const { double value_x, value_y, value_z, value_w; value_x = x - vector.x; value_y = y - vector.y; value_z = z - vector.z; value_w = w - vector.w; return sqrt(value_x*value_x + value_y*value_y+value_z*value_z+value_w*value_w); } // For float template<> float CL_Vec4f::distance4(const CL_Vec4f &vector) const { float value_x, value_y, value_z, value_w; value_x = x - vector.x; value_y = y - vector.y; value_z = z - vector.z; value_w = w - vector.w; return sqrt(value_x*value_x + value_y*value_y+value_z*value_z+value_w*value_w); } template<typename Type> CL_Vec4<Type> CL_Vec4<Type>::cross3(const CL_Vec4<Type>& v1, const CL_Vec4<Type>& v2) { CL_Vec4<Type> tmp = CL_Vec4<Type>(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x, 0); return tmp; } template<typename Type> CL_Vec4<Type> &CL_Vec4<Type>::cross3(const CL_Vec4<Type>& v) { *this = cross3(*this, v); return *this; } // Same as glRotate[f/d](angle, a); template<typename Type> CL_Vec4<Type> &CL_Vec4<Type>::rotate3(const CL_Angle &angle, const CL_Vec4<Type>& a) { CL_Vec4<Type> tmp = CL_Vec4<Type>(); float s = sin(angle.to_radians()); float c = cos(angle.to_radians()); tmp.x = (Type) (x*(a.x*a.x*(1-c)+c) + y*(a.x*a.y*(1-c)-a.z*s) + z*(a.x*a.z*(1-c)+a.y*s)); tmp.y = (Type) (x*(a.y*a.x*(1-c)+a.z*s) + y*(a.y*a.y*(1-c)+c) + z*(a.y*a.z*(1-c)-a.x*s)); tmp.z = (Type) (x*(a.x*a.z*(1-c)-a.y*s) + y*(a.y*a.z*(1-c)+a.x*s) + z*(a.z*a.z*(1-c)+c)); *this = tmp; return *this; } template<typename Type> CL_Vec4<Type> CL_Vec4<Type>::rotate3(const CL_Vec4<Type>& vector, const CL_Angle &angle, const CL_Vec4<Type>& a) { CL_Vec4<Type> dest(vector); dest.rotate3(angle, a); return dest; } template<typename Type> CL_Vec4<Type> &CL_Vec4<Type>::round() { x = (Type) floorf(x+0.5f); y = (Type) floorf(y+0.5f); z = (Type) floorf(z+0.5f); w = (Type) floorf(w+0.5f); return *this; } template<typename Type> CL_Vec4<Type> CL_Vec4<Type>::round(const CL_Vec4<Type>& vector) { CL_Vec4<Type> dest(vector); dest.round(); return dest; } // Explicit instantiate the versions we use: template class CL_Vec4<unsigned char>; template class CL_Vec4<char>; template class CL_Vec4<unsigned short>; template class CL_Vec4<short>; template class CL_Vec4<unsigned int>; template class CL_Vec4<int>; template class CL_Vec4<float>; template class CL_Vec4<double>;
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 237 ] ] ]
87c471b36dcb47495aed6b1a9b7b4a19e88fe091
0429e2b2a1a09254b5182e15835da188f7d44a3d
/MAIN/Reception/tests/filehandler/tfilehandler.cpp
a64da483d91288054f923a13c1460fb79561b356
[]
no_license
TheolZacharopoulos/tl2hotel
0b5af731aa022b04fc7b894b4fad6ce0b1121744
87ff9c75250d702c49d62f43e494cf549ea700b7
refs/heads/master
2020-03-30T05:41:55.498410
2011-04-25T22:24:44
2011-04-25T22:24:44
42,362,513
0
0
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
/** @file tfilehandler.cpp * @brief FileHandler Unit Test Implementation * @author Efstathios Xatzikiriakidis * * This is the unit test for the "FileHandler" class. */ #include "tfilehandler.h" /** * Filename of the test file. */ QString gFilename = QString ("fh-test.txt"); /** File Create Method * @brief This method tries to create a file for testing the "FileHandler" class. * @author Efstathios Xatzikiriakidis */ void TFileHandler::createFile () { QFile file (gFilename); if (!file.open (QIODevice::WriteOnly)) { QFAIL ("Fail: file cannot created."); } else { file.close (); } } /** File Exists Test Method * @brief This method tests if the "FileHandler" class can check that a file exists. * @author Efstathios Xatzikiriakidis */ void TFileHandler::isFileExist () { FileHandler fh; QVERIFY (fh.isFileExist (gFilename) == true); } /** Remove File Test Method * @brief This method tests if the "FileHandler" class can remove a file. * @author Efstathios Xatzikiriakidis */ void TFileHandler::removeFile () { FileHandler fh; QVERIFY (fh.removeFile(gFilename) == true); } QTEST_MAIN (TFileHandler)
[ "delis89@fb7cbe1a-da42-76e9-2caa-fedf319af631" ]
[ [ [ 1, 58 ] ] ]
245fa58c2ab101052e76220cab7d2e11c932a9e6
c2d3b2484afb98a6447dfacfe733b98e8778e0a9
/src/Tools/iPhone/SEiPhoneFileReader.h
213d8c79f67236efdd16e9f18be93b3bd0d3adf7
[]
no_license
soniccat/3dEngine
cfb73af5c9b25d61dd77e882a31f4a62fbd3f036
abf1d49a1756fb0217862f829b1ec7877a59eaf4
refs/heads/master
2020-05-15T07:07:22.751350
2010-03-27T13:05:38
2010-03-27T13:05:38
469,267
3
0
null
null
null
null
UTF-8
C++
false
false
447
h
#ifndef SEWindowsFileReader_H #define SEWindowsFileReader_H #include "SEIncludeLibrary.h" #include "SEFileReaderBase.h" class SEWindowsFileReader: public SEFileReaderBase { protected: //HANDLE mhFile; public: SEWindowsFileReader(void); virtual ~SEWindowsFileReader(void); virtual void Load(const SEPathBase* filePath); virtual void Close(); }; typedef SEWindowsFileReader EFileReader; #endif SEWindowsFileReader_H
[ "[email protected]", "ALEX@.(none)" ]
[ [ [ 1, 22 ] ], [ [ 23, 23 ] ] ]
0332e00ce864cb3d48ff8140dd7ed723946bc8f3
1585c7e187eec165138edbc5f1b5f01d3343232f
/Comic/ComicSrv1/math.cpp
506336079c4b69ef64e227968b15b04f2a663e67
[]
no_license
a-27m/vssdb
c8885f479a709dd59adbb888267a03fb3b0c3afb
d86944d4d93fd722e9c27cb134256da16842f279
refs/heads/master
2022-08-05T06:50:12.743300
2011-06-23T08:35:44
2011-06-23T08:35:44
82,612,001
1
0
null
2021-03-29T08:05:33
2017-02-20T23:07:03
C#
WINDOWS-1251
C++
false
false
3,219
cpp
// // Math.cpp // #include <stdafx.h> #include <windows.h> #include "math.h" // // Math class implementation // // Constructors Math::Math() { m_lRef = 0; // Увеличить значение внешнего счетчика объектов InterlockedIncrement( &g_lObjs ); } // The destructor Math::~Math() { // Уменьшить значение внешнего счетчика объектов InterlockedDecrement( &g_lObjs ); } STDMETHODIMP Math::QueryInterface( REFIID riid, void** ppv ) { *ppv = 0; if ( riid == IID_IUnknown || riid == IID_IMath ) *ppv = this; if ( *ppv ) { AddRef(); return( S_OK ); } return (E_NOINTERFACE); } STDMETHODIMP_(ULONG) Math::AddRef() { return InterlockedIncrement( &m_lRef ); } STDMETHODIMP_(ULONG) Math::Release() { if ( InterlockedDecrement( &m_lRef ) == 0 ) { delete this; return 0; } return m_lRef; } STDMETHODIMP Math::Add( long lOp1, long lOp2, long* pResult ) { *pResult = lOp1 + lOp2; return S_OK; } STDMETHODIMP Math::Subtract( long lOp1, long lOp2, long* pResult ) { *pResult = lOp1 - lOp2; return S_OK; } STDMETHODIMP Math::Multiply( long lOp1, long lOp2, long* pResult ) { *pResult = lOp1 * lOp2; return S_OK; } STDMETHODIMP Math::Divide( long lOp1, long lOp2, long* pResult ) { *pResult = lOp1 / lOp2; return S_OK; } STDMETHODIMP Math::Interpol(int n, float* xi, float* yi, float x, /*out*/ float* y) { // int n = sizeof(xi)/sizeof(xi[0]); double sum = 0; for (int k = 0; k <= n; k++) { double numerator = 1.0; double denominator = 1.0; for (int i = 0; i <= n; i++) { if (i == k) continue; if (xi[i] == xi[k]) continue; numerator *= (x - xi[i]); denominator *= (xi[k] - xi[i]); } sum += yi[k] * numerator / denominator; } *y = (float)sum; return S_OK; } MathClassFactory::MathClassFactory() { m_lRef = 0; } MathClassFactory::~MathClassFactory() { } STDMETHODIMP MathClassFactory::QueryInterface( REFIID riid, void** ppv ) { *ppv = 0; if ( riid == IID_IUnknown || riid == IID_IClassFactory ) *ppv = this; if ( *ppv ) { AddRef(); return S_OK; } return(E_NOINTERFACE); } STDMETHODIMP_(ULONG) MathClassFactory::AddRef() { return InterlockedIncrement( &m_lRef ); } STDMETHODIMP_(ULONG) MathClassFactory::Release() { if ( InterlockedDecrement( &m_lRef ) == 0 ) { delete this; return 0; } return m_lRef; } STDMETHODIMP MathClassFactory::CreateInstance ( LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj ) { Math* pMath; HRESULT hr; *ppvObj = 0; pMath = new Math; if ( pMath == 0 ) return( E_OUTOFMEMORY ); hr = pMath->QueryInterface( riid, ppvObj ); if ( FAILED( hr ) ) delete pMath; return hr; } STDMETHODIMP MathClassFactory::LockServer( BOOL fLock ) { if ( fLock ) InterlockedIncrement( &g_lLocks ); else InterlockedDecrement( &g_lLocks ); return S_OK; }
[ "Axell@bf672a44-3a04-1d4a-850b-c2a239875c8c" ]
[ [ [ 1, 182 ] ] ]
10da6677a42c392d30e1aa13f22a5967a135a56e
1ab9457b2e2183ec8275a9713d8c7cbb48c835d1
/Source/Common/BWAPI/include/BWAPI/UnitCommand.h
3613cb61f486a1b846c8055755924eeb357e118c
[]
no_license
ianfinley89/emapf-starcraft-ai
0f6ca09560092e798873b6b5dda01d463fa71518
b1bf992dff681a7feb618b7a781bacc61d2d477d
refs/heads/master
2020-05-19T20:52:17.080667
2011-03-04T11:59:46
2011-03-04T11:59:46
32,126,953
1
0
null
null
null
null
UTF-8
C++
false
false
3,631
h
#pragma once #include <BWAPI/UnitCommandType.h> #include <BWAPI/Position.h> #include <BWAPI/TilePosition.h> #include <BWAPI/TechType.h> #include <BWAPI/UpgradeType.h> #include <BWAPI/UnitType.h> namespace BWAPI { class Unit; class UnitCommand { public: UnitCommand(); UnitCommand(Unit* _unit, UnitCommandType _type, Unit* _target, int _x, int _y, int _extra); static UnitCommand attackMove(Unit* unit, Position target); static UnitCommand attackUnit(Unit* unit, Unit* target); static UnitCommand build(Unit* unit, TilePosition target, UnitType type); static UnitCommand buildAddon(Unit* unit, UnitType type); static UnitCommand train(Unit* unit, UnitType type); static UnitCommand morph(Unit* unit, UnitType type); static UnitCommand research(Unit* unit, TechType tech); static UnitCommand upgrade(Unit* unit, UpgradeType upgrade); static UnitCommand setRallyPoint(Unit* unit, Position target); static UnitCommand setRallyPoint(Unit* unit, Unit* target); static UnitCommand move(Unit* unit, Position target); static UnitCommand patrol(Unit* unit, Position target); static UnitCommand holdPosition(Unit* unit); static UnitCommand stop(Unit* unit); static UnitCommand follow(Unit* unit, Unit* target); static UnitCommand gather(Unit* unit, Unit* target); static UnitCommand returnCargo(Unit* unit); static UnitCommand repair(Unit* unit, Unit* target); static UnitCommand burrow(Unit* unit); static UnitCommand unburrow(Unit* unit); static UnitCommand cloak(Unit* unit); static UnitCommand decloak(Unit* unit); static UnitCommand siege(Unit* unit); static UnitCommand unsiege(Unit* unit); static UnitCommand lift(Unit* unit); static UnitCommand land(Unit* unit, TilePosition target); static UnitCommand load(Unit* unit, Unit* target); static UnitCommand unload(Unit* unit, Unit* target); static UnitCommand unloadAll(Unit* unit); static UnitCommand unloadAll(Unit* unit, Position target); static UnitCommand rightClick(Unit* unit, Position target); static UnitCommand rightClick(Unit* unit, Unit* target); static UnitCommand haltConstruction(Unit* unit); static UnitCommand cancelConstruction(Unit* unit); static UnitCommand cancelAddon(Unit* unit); static UnitCommand cancelTrain(Unit* unit, int slot = -2); static UnitCommand cancelMorph(Unit* unit); static UnitCommand cancelResearch(Unit* unit); static UnitCommand cancelUpgrade(Unit* unit); static UnitCommand useTech(Unit* unit,TechType tech); static UnitCommand useTech(Unit* unit,TechType tech, Position target); static UnitCommand useTech(Unit* unit,TechType tech, Unit* target); static UnitCommand placeCOP(Unit* unit, TilePosition target); UnitCommandType getType() const; Unit* getUnit() const; Unit* getTarget() const; Position getTargetPosition() const; TilePosition getTargetTilePosition() const; UnitType getUnitType() const; TechType getTechType() const; UpgradeType getUpgradeType() const; int getSlot() const; bool operator==(const UnitCommand& other) const; bool operator!=(const UnitCommand& other) const; bool operator<(const UnitCommand& other) const; bool operator>(const UnitCommand& other) const; Unit* unit; UnitCommandType type; Unit* target; int x; int y; int extra; }; }
[ "[email protected]@26a4d94b-85da-9150-e52c-6e401ef01510" ]
[ [ [ 1, 84 ] ] ]
e910a8d80bdea2bdf07877367ba65e5f520e05f0
53e5698f899750b717a1a3a4d205af422990b4a2
/core/common.h
3769a3351bc60b2dfdcdf7193d7ab3fac00fda9e
[]
no_license
kvantetore/PyProp
e25f07e670369ad774aee6f47115e1ec0ad680d0
0fcdd3d5944de5c54c43a5205eb6e830f5edbf4c
refs/heads/master
2016-09-10T21:17:56.054886
2011-05-30T08:52:44
2011-05-30T08:52:44
462,062
7
7
null
null
null
null
UTF-8
C++
false
false
1,539
h
#ifndef COMMON_H #define COMMON_H #include "utility/boostpythonhack.h" #include <complex> #include <cmath> #include <blitz/array.h> #include <blitz/tinyvec-et.h> #include <stdexcept> #include <boost/shared_ptr.hpp> #include "configuration.h" #define sqr(x) ((x)*(x)) using boost::shared_ptr; using boost::dynamic_pointer_cast; using std::cout; using std::endl; /* Complex */ typedef std::complex<double> cplx; const cplx I = cplx(0.0, 1.0); /* Equality operators for TinyVector */ template<class T, int Rank> inline bool operator==(const blitz::TinyVector<T,Rank> &v1, const blitz::TinyVector<T,Rank> &v2) { for (int i=0; i<Rank; i++) { if (v1(i) != v2(i)) { return false; } } return true; } template<class T, int Rank> inline bool operator!=(const blitz::TinyVector<T,Rank> &v1, const blitz::TinyVector<T,Rank> &v2) { return !(v1 == v2); } /* To/From string values */ template<class T> inline std::string ToString(const T &value) { std::ostringstream strm; strm << value << std::flush; return strm.str(); } template<class T> inline T FromString(const std::string &value) { throw std::runtime_error("Not implemented"); } template<class T> inline T max(const T& a, const T& b) { return a > b ? a : b; } template<class T> inline T min(const T& a, const T& b) { return a < b ? a : b; } #ifdef PYPROP_ROUND inline int round(double x) { return static_cast<int>( (x > 0.0) ? (x + 0.5) : (x - 0.5) ); } #endif #endif
[ "tore.birkeland@354cffb3-6528-0410-8d42-45ce437ad3c5" ]
[ [ [ 1, 89 ] ] ]
583a451e493ee6f95fb89e934122dd344fb88fb7
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/multi_index/test/test_range.cpp
277e1b548dfcf9951f24b193de2c3480b5b65290
[ "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
3,440
cpp
/* Boost.MultiIndex test for range(). * * Copyright 2003-2008 Joaquin M Lopez Munoz. * 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/multi_index for library home page. */ #include "test_range.hpp" #include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */ #include <algorithm> #include <functional> #include "pre_multi_index.hpp" #include <boost/multi_index_container.hpp> #include <boost/multi_index/identity.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/test/test_tools.hpp> using namespace boost::multi_index; typedef multi_index_container<int> int_set; typedef int_set::iterator int_set_iterator; #undef _ #define _ , #undef CHECK_RANGE #define CHECK_RANGE(p,check_range) \ {\ int v[]=check_range;\ std::size_t size_v=sizeof(v)/sizeof(int);\ BOOST_CHECK(std::size_t(std::distance((p).first,(p).second))==size_v);\ BOOST_CHECK(std::equal((p).first,(p).second,&v[0]));\ } #undef CHECK_VOID_RANGE #define CHECK_VOID_RANGE(p) BOOST_CHECK((p).first==(p).second) void test_range() { int_set is; for(int i=1;i<=10;++i)is.insert(i); std::pair<int_set::iterator,int_set::iterator> p; p=is.range(unbounded,unbounded); CHECK_RANGE(p,{1 _ 2 _ 3 _ 4 _ 5 _ 6 _ 7 _ 8 _ 9 _ 10}); p=is.range( std::bind1st(std::less<int>(),5), /* 5 < x */ unbounded); CHECK_RANGE(p,{6 _ 7 _ 8 _ 9 _ 10}); p=is.range( std::bind1st(std::less_equal<int>(),8), /* 8 <= x */ unbounded); CHECK_RANGE(p,{8 _ 9 _ 10}); p=is.range( std::bind1st(std::less_equal<int>(),11), /* 11 <= x */ unbounded); CHECK_VOID_RANGE(p); p=is.range( unbounded, std::bind2nd(std::less<int>(),8)); /* x < 8 */ CHECK_RANGE(p,{1 _ 2 _ 3 _ 4 _ 5 _ 6 _ 7}); p=is.range( unbounded, std::bind2nd(std::less_equal<int>(),4)); /* x <= 4 */ CHECK_RANGE(p,{1 _ 2 _ 3 _ 4}); p=is.range( unbounded, std::bind2nd(std::less_equal<int>(),0)); /* x <= 0 */ CHECK_VOID_RANGE(p); p=is.range( std::bind1st(std::less<int>(),6), /* 6 < x */ std::bind2nd(std::less_equal<int>(),9)); /* x <= 9 */ CHECK_RANGE(p,{7 _ 8 _ 9}); p=is.range( std::bind1st(std::less_equal<int>(),4), /* 4 <= x */ std::bind2nd(std::less<int>(),5)); /* x < 5 */ CHECK_RANGE(p,{4}); p=is.range( std::bind1st(std::less_equal<int>(),10), /* 10 <= x */ std::bind2nd(std::less_equal<int>(),10)); /* x <= 10 */ CHECK_RANGE(p,{10}); p=is.range( std::bind1st(std::less<int>(),0), /* 0 < x */ std::bind2nd(std::less<int>(),11)); /* x < 11 */ CHECK_RANGE(p,{1 _ 2 _ 3 _ 4 _ 5 _ 6 _ 7 _ 8 _ 9 _ 10}); p=is.range( std::bind1st(std::less<int>(),7), /* 7 < x */ std::bind2nd(std::less_equal<int>(),7)); /* x <= 7 */ CHECK_VOID_RANGE(p); BOOST_CHECK(p.first==is.upper_bound(7)); p=is.range( std::bind1st(std::less_equal<int>(),8), /* 8 <= x */ std::bind2nd(std::less<int>(),2)); /* x < 2 */ CHECK_VOID_RANGE(p); BOOST_CHECK(p.first==is.lower_bound(8)); p=is.range( std::bind1st(std::less<int>(),4), /* 4 < x */ std::bind2nd(std::less<int>(),5)); /* x < 5 */ CHECK_VOID_RANGE(p); BOOST_CHECK(p.first!=is.end()); }
[ "metrix@Blended.(none)" ]
[ [ [ 1, 120 ] ] ]
46f4e871feb892dd3365bc46d1e5161610fd27a6
f2b70f0f8d6f61899eb70b9f2626f1eb44f68cc7
/libs/qtutil/src/highlighter.cpp
c547d09641fb1e4b5e814ca4255be9fed93df7a6
[]
no_license
vikas100/VoxOx
cc36efcbb9a82da03c05ea76093426aafba3bd8c
d4fae14f3f5a4de29abad3b79f4903db01daa913
refs/heads/master
2020-05-18T06:57:08.968725
2011-05-14T01:56:29
2011-05-14T01:56:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,656
cpp
/**************************************************************************** ** ** Copyright (C) 2005-2008 Trolltech ASA. All rights reserved. ** ** This file is part of the example classes of the Qt Toolkit. ** ** This file may be used under the terms of the GNU General Public ** License versions 2.0 or 3.0 as published by the Free Software ** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Alternatively you may (at ** your option) use any later version of the GNU General Public ** License if such license has been publicly approved by Trolltech ASA ** (or its successors, if any) and the KDE Free Qt Foundation. In ** addition, as a special exception, Trolltech gives you certain ** additional rights. These rights are described in the Trolltech GPL ** Exception version 1.1, which can be found at ** http://www.trolltech.com/products/qt/gplexception/ and in the file ** GPL_EXCEPTION.txt in this package. ** ** Please review the following information to ensure GNU General ** Public Licensing requirements will be met: ** http://trolltech.com/products/qt/licenses/licensing/opensource/. If ** you are unsure which license is appropriate for your use, please ** review the following information: ** http://trolltech.com/products/qt/licenses/licensing/licensingoverview ** or contact the sales department at [email protected]. ** ** In addition, as a special exception, Trolltech, as the sole ** copyright holder for Qt Designer, grants users of the Qt/Eclipse ** Integration plug-in the right for the Qt/Eclipse Integration to ** link to functionality provided by Qt Designer and its related ** libraries. ** ** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, ** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly ** granted herein. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include <QtGui/QtGui> #include <iostream> #include <qtutil/highlighter.h> Highlighter::Highlighter(Hunspell * Checker,QTextDocument *parent,QString SpellDic,bool spellCheckState) : QSyntaxHighlighter(parent) { HighlightingRule rule; spellCheckFormat.setUnderlineColor(QColor(Qt::red)); spellCheckFormat.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline); //Settings for online spellchecking if(SpellDic!=""){ //mWords.clear(); spell_dic=SpellDic.left(SpellDic.length()-4); pChecker = Checker; spell_encoding=QString(pChecker->get_dic_encoding()); codec = QTextCodec::codecForName(spell_encoding.toLatin1()); //QFileInfo fi(SpellDic); //if (fi.exists() && fi.isReadable()) spellCheckActive=true; //else spellCheckActive=false; //// get user config dictionary //QString filePath=spell_dic.toLatin1()+".dic"; // //std::cout << qPrintable(filePath) << std::endl; //fi=QFileInfo(filePath); //if (fi.exists() && fi.isReadable()){ // pChecker->add_dic(filePath.toLatin1()); //} //else filePath=""; } else spellCheckActive=false; spellerError=!spellCheckActive; spellCheckActive=spellCheckActive && spellCheckState; } Highlighter::~Highlighter() { //delete pChecker; } void Highlighter::highlightBlock(const QString &text) { spellCheck(text); } void Highlighter::enableSpellChecking(const bool state) { bool old=spellCheckActive; if(!spellerError) spellCheckActive=state; if(old!=spellCheckActive) rehighlight(); } void Highlighter::spellCheck(const QString &text) { if (spellCheckActive) { // split text into words QString str = text.simplified(); if (!str.isEmpty()) { QStringList Checkliste = str.split(QRegExp("([^\\w,^\\\\]|(?=\\\\))+"), QString::SkipEmptyParts); int l,number; // check all words for (int i=0; i<Checkliste.size(); ++i) { str = Checkliste.at(i); if (str.length()>1 &&!str.startsWith('\\')) { if (!checkWord(str)) { number = text.count(QRegExp("\\b" + str + "\\b")); l=-1; // underline all incorrect occurences of misspelled word for (int j=0;j < number; ++j) { l = text.indexOf(QRegExp("\\b" + str + "\\b"),l+1); if (l>=0) setFormat(l, str.length(), spellCheckFormat); } // for j } // if spell chek error } // if str.length > 1 } // for } // if str.isEmpty } // initial check } bool Highlighter::checkWord(QString word) { int check; /*switch(check=mWords.value(word,-1)){ case -1: { QByteArray encodedString; encodedString = codec->fromUnicode(word); check = pChecker->spell(encodedString.data()); mWords[word]=check; break; } default: break; } */ QByteArray encodedString; encodedString = codec->fromUnicode(word); check = pChecker->spell(encodedString.data()); return bool(check); } bool Highlighter::setDict(const QString SpellDic) { bool spell; if(SpellDic!=""){ //mWords.clear(); spell_dic=SpellDic.left(SpellDic.length()-4); delete pChecker; pChecker = new Hunspell(spell_dic.toLatin1()+".aff",spell_dic.toLatin1()+".dic"); spell_encoding=QString(pChecker->get_dic_encoding()); codec = QTextCodec::codecForName(spell_encoding.toLatin1()); QFileInfo fi(SpellDic); if (fi.exists() && fi.isReadable()) spell=true; else spell=false; // get user config dictionary QString filePath=spell_dic.toLatin1()+".dic"; std::cout << qPrintable(filePath) << std::endl; fi=QFileInfo(filePath); if (fi.exists() && fi.isReadable()){ pChecker->add_dic(filePath.toLatin1()); } else filePath=""; spellCheckFormat.setForeground(Qt::red);//faster Cursoroperation ... //spellCheckFormat.setUnderlineColor(QColor(Qt::red)); //spellCheckFormat.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline); } else spell=false; spellerError=!spell; spellCheckActive=spellCheckActive && spell; rehighlight(); return spell; } void Highlighter::slot_addWord(QString word) { /*std::cout << qPrintable(word) << std::endl; QByteArray encodedString; QString spell_encoding=QString(pChecker->get_dic_encoding()); QTextCodec *codec = QTextCodec::codecForName(spell_encoding.toLatin1()); encodedString = codec->fromUnicode(word); pChecker->add(encodedString.data()); rehighlight();*/ }
[ [ [ 1, 199 ] ] ]
70ca5265486da9ca2ccbdf9f73f74269f03741c1
b739a332ba929e8c6951c4c686dc7992c4c38f40
/WonFW/Popupwnd/PopupWnd.cpp
0fa422a791b9316086f0a186fe3fac403c83c45d
[]
no_license
codingman/antiarp
ad8b6400c8efa086197912dc6d534db540333ba0
929987e23d5d3b31c9340e377c6455fc7139f610
refs/heads/master
2021-12-04T11:13:56.716565
2009-04-17T11:50:11
2009-04-17T11:50:11
null
0
0
null
null
null
null
GB18030
C++
false
false
15,035
cpp
// RaiseAlert.cpp : implementation file // #include "stdafx.h" #include "PopupWnd.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CPopupWnd CPopupWnd::CPopupWnd() { m_bAllSizeWnd = FALSE; m_bSetCaptured = FALSE; m_bAutoClose = FALSE; RegisterWindowClass(); DWORD dwStyle = WS_POPUP; DWORD dwExStyle = WS_EX_TOOLWINDOW | WS_EX_TOPMOST; CreateEx(dwExStyle, POPUPWND_CLASSNAME, NULL, dwStyle, 0, 0, 0, 0, NULL, NULL, NULL); } CPopupWnd::~CPopupWnd() { //必须调用 DestroyWindow(); } BOOL CPopupWnd::RegisterWindowClass() { // Register the window class if it has not already been registered. WNDCLASS wndcls; HINSTANCE hInst = AfxGetInstanceHandle(); if(!(::GetClassInfo(hInst, POPUPWND_CLASSNAME , &wndcls))) { // otherwise we need to register a new class wndcls.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW; // wndcls.lpfnWndProc = ::DefWindowProc; wndcls.cbClsExtra = wndcls.cbWndExtra = 0; wndcls.hInstance = hInst; wndcls.hIcon = NULL; wndcls.hCursor = LoadCursor(hInst, IDC_ARROW); wndcls.hbrBackground = NULL; wndcls.lpszMenuName = NULL; wndcls.lpszClassName = POPUPWND_CLASSNAME; if (!AfxRegisterClass(&wndcls)) AfxThrowResourceException(); } //if return TRUE; } BEGIN_MESSAGE_MAP(CPopupWnd, CWnd) //{{AFX_MSG_MAP(CPopupWnd) ON_WM_PAINT() ON_WM_TIMER() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_CLOSE() ON_WM_ERASEBKGND() ON_WM_HELPINFO() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPopupWnd message handlers void CPopupWnd::OnPaint() { CPaintDC dc(this); // device context for painting int iSave = dc.SaveDC(); dc.SetBkMode(TRANSPARENT); CRect rc; GetClientRect(&rc); TEXTMETRIC metric; dc.GetTextMetrics(&metric); CRect title_rc; title_rc.top = 0; title_rc.left = 0; title_rc.right = rc.right; title_rc.bottom = metric.tmHeight * 2; CRect body_rc; body_rc.top = metric.tmHeight * 2; body_rc.left = 0; body_rc.right = rc.right; body_rc.bottom = rc.bottom; CRect textrc; textrc.left = 0; textrc.right = rc.right; textrc.top = title_rc.top + metric.tmHeight/2; textrc.bottom = textrc.top + metric.tmHeight; CBrush titlebrush(RGB(0xfc,0x71,0x4d)); CBrush *pOldBrush = dc.SelectObject(&titlebrush); dc.Rectangle(&title_rc); dc.SetTextColor(RGB(255,255,255)); CString str = _T(" 用户禁止项目"); dc.DrawText(str,&textrc, DT_VCENTER | DT_LEFT); dc.SelectObject(pOldBrush); titlebrush.DeleteObject(); dc.Rectangle(&body_rc); dc.RestoreDC(iSave); } void CPopupWnd::OnTimer(UINT nIDEvent) { switch (nIDEvent) { case IDT_POP_WINDOW_TIMER: // When the window comes up { switch (m_nStatusBarPos) { case STP_BOTTOM: case STP_RIGHT: { m_nWndSize+=30; if (m_nWndSize > m_nWndHeight) { KillTimer(IDT_POP_WINDOW_TIMER); m_bAllSizeWnd = TRUE; //窗体已经最大化 SetTimer(IDT_SHOW_WINDOW_TIMER, m_nMsgTimeOut, NULL); } else { // Keep sizing the window, show it SetWindowPos( &wndTopMost, m_nWndLeft, m_nWndBottom - m_nWndSize, m_nWndWidth - 1, m_nWndSize, SWP_SHOWWINDOW ); } } break; case STP_TOP: { m_nWndSize+=30; if (m_nWndSize > m_nWndHeight) { KillTimer(IDT_POP_WINDOW_TIMER); m_bAllSizeWnd = TRUE; //窗体已经最大化 SetTimer(IDT_SHOW_WINDOW_TIMER, m_nMsgTimeOut, NULL); } else { // Keep sizing the window, collapse it SetWindowPos( &wndTop, m_nWndLeft, m_nWndTop, m_nWndWidth - 1, m_nWndSize, SWP_SHOWWINDOW ); } } break; case STP_LEFT: { m_nWndSize+=30; if (m_nWndSize > m_nWndHeight) { KillTimer(IDT_POP_WINDOW_TIMER); m_bAllSizeWnd = TRUE; SetTimer(IDT_SHOW_WINDOW_TIMER, m_nMsgTimeOut, NULL); } else { // Keep sizing the window, collpase it SetWindowPos( &wndTopMost, m_nWndLeft + 1, m_nWndBottom - m_nWndSize, m_nWndWidth, m_nWndSize, SWP_SHOWWINDOW ); } } break; } } break; case IDT_SHOW_WINDOW_TIMER: { KillTimer(IDT_SHOW_WINDOW_TIMER); if(m_bAutoClose) { OnClose(); } } break; default: break; } } void CPopupWnd::Popup(BOOL bAutoClose,int iDelayMiscSeconds,int nWidth,int nHeight,BOOL bShowCenter) { if(IsWindowVisible()) return; m_nWndWidth = nWidth; m_nWndHeight = nHeight; m_nWndSize = 0; if(iDelayMiscSeconds != 0) { m_nMsgTimeOut = iDelayMiscSeconds; } else m_nMsgTimeOut = 5000; m_nMsgWndCreationDelay = 10; m_bAutoClose = bAutoClose; if(!bShowCenter) { if (CheckIfStatusBarBottom()) // Most frequent case is status bar at bottom { PopWndForBottomStatusBar(); } else { if (CheckIfStatusBarTop()) { PopWndForTopStatusBar(); } else { if (CheckIfStatusBarLeft()) { PopWndForLeftStatusBar(); } else { m_nStatusBarPos = STP_RIGHT; // Force it, as no need for calling "CheckIfStatusBarRight() PopWndForRightStatusBar(); } } } } else { //将窗体置中 MoveChildCenter(); ShowCenter(); return; } //将窗体置中 MoveChildCenter(); } void CPopupWnd::PopWndForLeftStatusBar() { CRect rectDesktopWithoutTaskbar; // The desktop area // Get the desktop area ::SystemParametersInfo(SPI_GETWORKAREA, 0, &rectDesktopWithoutTaskbar, 0); // Calculate the actual width of the Window and its position m_nWndLeft = rectDesktopWithoutTaskbar.left; m_nWndTop = rectDesktopWithoutTaskbar.bottom - m_nWndHeight; m_nWndRight = m_nWndLeft + m_nWndWidth; m_nWndBottom = m_nWndTop + m_nWndHeight; m_nWndSize = 0; // The height of window is zero before showing SetTimer(IDT_POP_WINDOW_TIMER, m_nMsgWndCreationDelay, NULL); } void CPopupWnd::PopWndForRightStatusBar() { PopWndForBottomStatusBar(); } void CPopupWnd::PopWndForTopStatusBar() { CRect rectDesktopWithoutTaskbar; // The desktop area // Get the desktop area ::SystemParametersInfo(SPI_GETWORKAREA, 0, &rectDesktopWithoutTaskbar, 0); // Calculate the actual width of the Window and its position in screen co-ordinates m_nWndLeft = rectDesktopWithoutTaskbar.right - m_nWndWidth; m_nWndTop = rectDesktopWithoutTaskbar.top; m_nWndRight = m_nWndLeft + m_nWndWidth; m_nWndBottom = m_nWndTop + m_nWndHeight; m_nWndSize = 0; // The height of window is zero before showing SetTimer(IDT_POP_WINDOW_TIMER, m_nMsgWndCreationDelay, NULL); } void CPopupWnd::PopWndForBottomStatusBar() { CRect rectDesktopWithoutTaskbar; // The desktop area // Get the desktop area ::SystemParametersInfo(SPI_GETWORKAREA, 0, &rectDesktopWithoutTaskbar, 0); // Calculate the actual width of the Window and its position in screen co-ordinates m_nWndLeft = rectDesktopWithoutTaskbar.right - m_nWndWidth; m_nWndTop = rectDesktopWithoutTaskbar.bottom - m_nWndHeight; m_nWndRight = m_nWndLeft + m_nWndWidth; m_nWndBottom = m_nWndTop + m_nWndHeight; m_nWndSize = 0; // The height of window is zero before showing SetTimer(IDT_POP_WINDOW_TIMER, m_nMsgWndCreationDelay, NULL); } BOOL CPopupWnd::CheckIfStatusBarLeft() { unsigned int nAvailableScreenTop; unsigned int nAvailableScreenLeft; CRect rectDesktopWithoutTaskbar; // The desktop area without status bar // Get the desktop area minus the status ::SystemParametersInfo(SPI_GETWORKAREA, 0, &rectDesktopWithoutTaskbar, 0); nAvailableScreenLeft = rectDesktopWithoutTaskbar.left; nAvailableScreenTop = rectDesktopWithoutTaskbar.top; if ((nAvailableScreenLeft > 0) && (nAvailableScreenTop == 0)) { m_nStatusBarPos = STP_LEFT; return TRUE; } else { return FALSE; } } BOOL CPopupWnd::CheckIfStatusBarRight() { unsigned int nAvailableScreenWidth; unsigned int nAvailableScreenHeight; unsigned int nActualScreenWidth; unsigned int nActualScreenHeight; // Calculate the actual screen height and width nActualScreenWidth = ::GetSystemMetrics(SM_CXFULLSCREEN); nActualScreenHeight = ::GetSystemMetrics(SM_CYFULLSCREEN); CRect rectDesktopWithoutTaskbar; // The desktop area without status bar // Get the desktop area minus the status ::SystemParametersInfo(SPI_GETWORKAREA, 0, &rectDesktopWithoutTaskbar, 0); nAvailableScreenWidth = rectDesktopWithoutTaskbar.Width(); nAvailableScreenHeight = rectDesktopWithoutTaskbar.Height(); if ((nAvailableScreenWidth != nActualScreenWidth) && (nAvailableScreenHeight == nActualScreenHeight)) { m_nStatusBarPos = STP_RIGHT; return TRUE; } else { return FALSE; } } BOOL CPopupWnd::CheckIfStatusBarTop() { unsigned int nAvailableScreenTop; unsigned int nAvailableScreenLeft; CRect rectDesktopWithoutTaskbar; // The desktop area without status bar // Get the desktop area minus the status ::SystemParametersInfo(SPI_GETWORKAREA, 0, &rectDesktopWithoutTaskbar, 0); nAvailableScreenLeft = rectDesktopWithoutTaskbar.left; nAvailableScreenTop = rectDesktopWithoutTaskbar.top; if ((nAvailableScreenLeft == 0) && (nAvailableScreenTop > 0)) { m_nStatusBarPos = STP_TOP; return TRUE; } else { return FALSE; } } BOOL CPopupWnd::CheckIfStatusBarBottom() { unsigned int nAvailableScreenWidth; unsigned int nAvailableScreenBottom; unsigned int nActualScreenWidth; unsigned int nActualScreenBottom; // Calculate the actual screen height and width nActualScreenWidth = ::GetSystemMetrics(SM_CXSCREEN); nActualScreenBottom = ::GetSystemMetrics(SM_CYSCREEN); CRect rectDesktopWithoutTaskbar; // The desktop area without status bar // Get the desktop area minus the status ::SystemParametersInfo(SPI_GETWORKAREA, 0, &rectDesktopWithoutTaskbar, 0); nAvailableScreenWidth = rectDesktopWithoutTaskbar.Width(); nAvailableScreenBottom = rectDesktopWithoutTaskbar.bottom; if ((nAvailableScreenWidth == nActualScreenWidth) && (nAvailableScreenBottom < nActualScreenBottom)) { m_nStatusBarPos = STP_BOTTOM; return TRUE; } else { return FALSE; } } void CPopupWnd::MoveChildCenter() { CWnd *pChild = NULL; CClientDC dc(this); CRect rc(0,0,0,0); TEXTMETRIC metric; dc.GetTextMetrics(&metric); rc.top = metric.tmHeight * 2; rc.bottom = m_nWndHeight; CRect childrc; pChild->GetClientRect(&childrc); CRect new_rc; new_rc.left = (m_nWndWidth - childrc.right) /2; new_rc.right = new_rc.left + childrc.right - childrc.left; new_rc.top = metric.tmHeight + (m_nWndHeight - childrc.bottom)/2; new_rc.bottom = new_rc.top + childrc.bottom; pChild->MoveWindow(&new_rc); pChild->ShowWindow(SW_SHOW); } BOOL CPopupWnd::OnEraseBkgnd(CDC* pDC) { return TRUE; } BOOL CPopupWnd::CreateChildWnd(LPCTSTR text ) { return FALSE; } void CPopupWnd::OnLButtonDown(UINT nFlags, CPoint point) { if(m_bAllSizeWnd) { m_OldMousePoint = point; ClientToScreen(&m_OldMousePoint); SetCursor(LoadCursor(NULL,IDC_SIZEALL)); m_bSetCaptured = TRUE; SetCapture(); } } void CPopupWnd::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default if(m_bAllSizeWnd && m_bSetCaptured) { ReleaseCapture(); m_bSetCaptured = FALSE; SetCursor(LoadCursor(NULL,IDC_ARROW)); MoveWnd(); } } void CPopupWnd::MoveWnd() { CPoint pos; GetCursorPos(&pos); CRect clientrc; GetClientRect(&clientrc); ClientToScreen(&clientrc); CRect new_rc; new_rc.left = clientrc.left + (pos.x - m_OldMousePoint.x); new_rc.right = clientrc.right + (pos.x - m_OldMousePoint.x); new_rc.top = clientrc.top + (pos.y - m_OldMousePoint.y); new_rc.bottom = clientrc.bottom + (pos.y - m_OldMousePoint.y); MoveWindow(new_rc.left,new_rc.top,clientrc.right - clientrc.left,clientrc.bottom - clientrc.top); } void CPopupWnd::ShowCenter() { //高 m_nWndHeight //宽 m_nWndWidth; //左 m_nWndLeft //右 m_nWndRight //上 m_nWndTop //底 m_nWndBottom int iMaxScreenWidth = GetSystemMetrics(SM_CXFULLSCREEN); int iMaxScreenHeight = GetSystemMetrics(SM_CYFULLSCREEN); m_nWndLeft = (iMaxScreenWidth - m_nWndWidth) /2; m_nWndTop = (iMaxScreenHeight - m_nWndHeight) /2; SetWindowPos( &wndTopMost, m_nWndLeft, m_nWndTop, m_nWndWidth, m_nWndHeight, SWP_SHOWWINDOW ); m_bAllSizeWnd = TRUE; //窗体已经最大化 } void CPopupWnd::OnClose() { ShowWindow(SW_HIDE); return; delete this; } void CPopupWnd::ForceClose() { delete this; }
[ "antimezhang@91219e7a-2a93-11de-a435-ffa8d773f76a" ]
[ [ [ 1, 615 ] ] ]
0501c0966f88da3b52203aa12a74662279d1f859
1cc5720e245ca0d8083b0f12806a5c8b13b5cf98
/archive/ok/2759/c.cpp
d77de304d0c6d36209e5d2294b4552fda9487813
[]
no_license
Emerson21/uva-problems
399d82d93b563e3018921eaff12ca545415fd782
3079bdd1cd17087cf54b08c60e2d52dbd0118556
refs/heads/master
2021-01-18T09:12:23.069387
2010-12-15T00:38:34
2010-12-15T00:38:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
635
cpp
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; #define MAIOR(a,b) (a>b?a:b) #define MAXI (1001) int main() { char s1[MAXI],s2[MAXI]; int val[MAXI][MAXI]; int i,j,k,l1,l2; while((cin >> s1 >> s2)) { l1 = strlen(s1); l2 = strlen(s2); for(i=0;i<=l1;i++) val[i][0] = 0; for(i=0;i<=l2;i++) val[0][i] = 0; for(i=1;i<=l1;i++) { for(j=1;j<=l2;j++) { if(s1[i-1]==s2[j-1]) { val[i][j] = val[i-1][j-1] + 1; } else { val[i][j] = MAIOR(val[i][j-1],val[i-1][j]); } } } cout << val[l1][l2] << endl; } return 0; }
[ [ [ 1, 33 ] ] ]
cc7ba5df1da705b3e2a825be0808b4f4fc534a10
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/renaissance/rnsstates/src/rnsstates/rnsgamestate_net.cc
58d41c3793913fa342b206d7dbb45e2e02799ebe
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,155
cc
//------------------------------------------------------------------------------ // rnsgamestate_net.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "precompiled/pchrnsstates.h" #include "rnsstates/rnsgamestate.h" #include "nnetworkmanager/nnetworkmanager.h" #include "rnsgameplay/nrnsentitymanager.h" #include "ncgameplayplayer/ncgameplayplayer.h" #include "ncgamecamera/ncgamecamera.h" #include "gameplay/nmissionhandler.h" #include "gameplay/ngamemessagewindowproxy.h" #include "nmusictable/nmusictable.h" #include "ncsound/ncsound.h" #include "util/nstream.h" #include "rnsgameplay/ninventoryitem.h" #include "rnsgameplay/ninventorymanager.h" //------------------------------------------------------------------------------ /** */ void RnsGameState::InitConnectionWith( const nString &host, const nString & port ) { this->initClient = true; this->hostName = host; this->hostPort = port; } //------------------------------------------------------------------------------ /** */ void RnsGameState::InitNetwork() { // search for already created Network Manager this->network = nNetworkManager::Instance(); // if there is no Network Manager if( ! this->network ) { // Create an adecuated Network Manager this->network = (nNetworkManager*)kernelServer->New("nnetworkmanager", "/sys/servers/network"); } n_assert_if2( this->network, "The Network manager can't be created" ) { if( this->initClient ) { this->network->ConnectHost( this->hostName.Get(), this->hostPort.Get() ); } // bind with the Network Manager this->network->BindSignal( nNetworkManager::SignalOnNewClient, this, &RnsGameState::NewClientConnected, 0 ); this->network->BindSignal( nNetworkManager::SignalOnClientDisconnected, this, &RnsGameState::ClientDisconnected, 0 ); this->network->BindSignal( nNetworkManager::SignalOnConnected, this, &RnsGameState::Connected, 0 ); this->network->BindSignal( nNetworkManager::SignalOnDisconnected, this, &RnsGameState::Disconnected, 0 ); this->network->BindSignal( nNetworkManager::SignalOnRPC, this, &RnsGameState::RPCFromServer, 0 ); this->network->BindSignal( nNetworkManager::SignalOnRPCServer, this, &RnsGameState::RPCFromClient, 0 ); } } //------------------------------------------------------------------------------ /** */ void RnsGameState::EndNetwork() { if( this->network ) { // unbind from the Network Manager this->network->UnbindTargetObject( nNetworkManager::SignalOnNewClient.GetId(), this ); this->network->UnbindTargetObject( nNetworkManager::SignalOnClientDisconnected.GetId(), this ); this->network->UnbindTargetObject( nNetworkManager::SignalOnConnected.GetId(), this ); this->network->UnbindTargetObject( nNetworkManager::SignalOnDisconnected.GetId(), this ); this->network->UnbindTargetObject( nNetworkManager::SignalOnRPC.GetId(), this ); this->network->UnbindTargetObject( nNetworkManager::SignalOnRPCServer.GetId(), this ); this->network->Release(); this->network = 0; } } //------------------------------------------------------------------------------ /** @param client number of connected client */ void RnsGameState::NewClientConnected( int client ) { NLOG( network, ( nNetworkManager::NLOGAPPLICATION | 0, "client %d connected\n", client ) ); // create the player info n_assert( ! this->players[ client ] ); this->players[ client ] = n_new( PlayerInfo ); this->players[ client ]->clientEntity = 0; n_assert( this->players[ client ] ); } //------------------------------------------------------------------------------ /** @param client number of disconnected client */ void RnsGameState::ClientDisconnected( int client ) { NLOG( network, ( nNetworkManager::NLOGAPPLICATION | 0, "client %d disconnected [%s]\n", client, ( this->players[ client ] ? "full connection" : "failure connection" ) ) ); if( this->players[ client ] ) { // fix camera if point to deleted client if( this->gameCamera->GetAnchorPoint() == this->players[ client ]->clientEntity ) { this->ChangeCameraAnchor( 0 ); } if( this->players[ client ]->clientEntity ) { nEntityObject * playerEntity = this->players[ client ]->clientEntity; ncGameplayLiving * living = playerEntity->GetComponentSafe<ncGameplayLiving>(); if( living ) { // kill living entity living->SetDead(); } else { // delete client in the Entity Manager this->entityManager->DeleteEntity( playerEntity->GetId() ); } } n_delete( this->players[ client ] ); this->players[ client ] = 0; } } //------------------------------------------------------------------------------ /** */ void RnsGameState::Connected() { nstream data; nRnsEntityManager::PlayerData playerData; // initialice player data playerData.weapon = nRnsEntityManager::WEAPON_M4; playerData.flags = 0; data.SetWrite( true ); playerData.UpdateStream( data ); // tell server that create a player for you this->network->CallRPCServer( nRnsEntityManager::SPAWN_PLAYER, data.GetBufferSize(), data.GetBuffer() ); } //------------------------------------------------------------------------------ /** */ void RnsGameState::Disconnected() { if( this->savedState.IsEmpty() ) { this->app->SetQuitRequested(true); } else { this->app->SetState( this->savedState ); } } //------------------------------------------------------------------------------ /** @param rpcId Remote Procedure Call Identifier @param size size of the buffer with the parameters @param buffer buffer with the parameters */ void RnsGameState::RPCFromServer( char rpcId, int size, const char * buffer ) { int entityId = 0; nRnsEntityManager::PlayerData playerData; // initialize the strem with the parameters nstream data; data.SetExternBuffer( size, buffer ); data.SetWrite( false ); switch( rpcId ) { case nRnsEntityManager::SPAWN_PLAYER: playerData.UpdateStream( data ); this->SpawnPlayer( SERVER_PLAYER, playerData ); break; case nRnsEntityManager::SET_LOCAL_PLAYER: { data.UpdateInt( entityId ); this->SetLocalPlayer( entityId ); } break; case nRnsEntityManager::KILL_ENTITY: data.UpdateInt( entityId ); this->entityManager->KillEntity( entityId ); break; case nRnsEntityManager::SUICIDE_PLAYER: if( this->network->IsServer() ) { if( this->players[ SERVER_PLAYER ] && this->players[ SERVER_PLAYER ]->clientEntity ) { data.UpdateInt( entityId ); if( this->players[ SERVER_PLAYER ]->clientEntity->GetId() == unsigned(entityId) ) { this->entityManager->SuicidePlayer( this->players[ SERVER_PLAYER ]->clientEntity ); } } } break; case nRnsEntityManager::DELETE_ENTITY: data.UpdateInt( entityId ); this->entityManager->DeleteEntity( entityId ); break; case nRnsEntityManager::UPDATE_INVENTORY: { nInventoryManager * inventory = nInventoryManager::Instance(); if( inventory ) { inventory->NetworkUpdate( data ); } } break; case nRnsEntityManager::INVENTORY_ITEM: { nInventoryManager * inventory = nInventoryManager::Instance(); if( inventory ) { inventory->NewNetworkItem( data ); } } break; case nRnsEntityManager::SET_OBJECTIVE_STATE: nMissionHandler::Instance()->ReceiveObjectiveStateChange( &data ); break; case nRnsEntityManager::STOP_MUSIC: // @todo Make music table a singleton or get its NOH path from a constant static_cast<nMusicTable*>( nKernelServer::Instance()->Lookup("/usr/musictable") )->ReceiveStopMusic( &data ); break; case nRnsEntityManager::PLAY_MUSIC_PART: static_cast<nMusicTable*>( nKernelServer::Instance()->Lookup("/usr/musictable") )->ReceivePlayMusicPart( &data ); break; case nRnsEntityManager::PLAY_MUSIC_STINGER: static_cast<nMusicTable*>( nKernelServer::Instance()->Lookup("/usr/musictable") )->ReceivePlayMusicStinger( &data ); break; case nRnsEntityManager::SET_MUSIC_MOOD: static_cast<nMusicTable*>( nKernelServer::Instance()->Lookup("/usr/musictable") )->ReceiveMoodToPlay( &data ); break; case nRnsEntityManager::SET_MUSIC_STYLE: static_cast<nMusicTable*>( nKernelServer::Instance()->Lookup("/usr/musictable") )->ReceiveSetCurrentStyle( &data ); break; // @todo Remove this and use a network component to issue play/stop commands on the entity case nRnsEntityManager::PLAY_SOUND_EVENT: { data.UpdateInt( entityId ); nEntityObject* targetEntity( nEntityObjectServer::Instance()->GetEntityObject( entityId ) ); if ( targetEntity ) { ncSound* sound( targetEntity->GetComponent<ncSound>() ); if ( sound ) { sound->ReceiveEventToPlay( &data ); } } } break; case nRnsEntityManager::STOP_SOUND: { data.UpdateInt( entityId ); nEntityObject* targetEntity( nEntityObjectServer::Instance()->GetEntityObject( entityId ) ); if ( targetEntity ) { ncSound* sound( targetEntity->GetComponent<ncSound>() ); if ( sound ) { sound->StopSound(); } } } break; case nRnsEntityManager::WEAPON_TRIGGER: if( this->entityManager->GetLocalPlayer() ) { nEntityObject * player = this->entityManager->GetLocalPlayer(); bool weaponTrigger, weaponPressed; data.UpdateBool( weaponTrigger ); data.UpdateBool( weaponPressed ); ncGameplayPlayer * gameplay = player->GetComponentSafe<ncGameplayPlayer>(); if( gameplay ) { gameplay->SetWeaponTrigger( weaponTrigger, weaponPressed ); } } break; case nRnsEntityManager::WEAPON_BURST: { if( ! this->network->IsServer() ) { bool weaponTrigger; bool weaponPressed; data.UpdateInt( entityId ); data.UpdateBool( weaponTrigger ); data.UpdateBool( weaponPressed ); nEntityObject* entity = 0; entity = nEntityObjectServer::Instance()->GetEntityObject( entityId ); if( entity ) { ncGameplayPlayer * gameplay = entity->GetComponentSafe<ncGameplayPlayer>(); if( gameplay ) { gameplay->SetWeaponTrigger( weaponTrigger, weaponPressed ); } } } } break; case nRnsEntityManager::SHOW_GAME_MESSAGE: nGameMessageWindowProxy::Instance()->ReceiveGameMessage( &data ); break; } data.SetExternBuffer( 0, 0 ); } //------------------------------------------------------------------------------ /** @param client identifier of the client that request the call @param rpcId Remote Procedure Call Identifier @param size size of the buffer with the parameters @param buffer buffer with the parameters */ void RnsGameState::RPCFromClient( int client, char rpcId, int size, const char * buffer ) { nRnsEntityManager::PlayerData playerData; int entityId = 0; // initialize the strem with the parameters nstream data; data.SetExternBuffer( size, buffer ); data.SetWrite( false ); switch( rpcId ) { case nRnsEntityManager::SPAWN_PLAYER: playerData.UpdateStream( data ); this->SpawnPlayer( client, playerData ); break; case nRnsEntityManager::WEAPON_TRIGGER: if( this->players[ client ] && this->players[ client ]->clientEntity ) { nEntityObject * player = this->players[ client ]->clientEntity; bool weaponTrigger, weaponPressed; data.UpdateBool( weaponTrigger ); data.UpdateBool( weaponPressed ); ncGameplayPlayer * gameplay = player->GetComponent<ncGameplayPlayer>(); if( gameplay ) { gameplay->SetWeaponTrigger( weaponTrigger, weaponPressed ); } } break; case nRnsEntityManager::SUICIDE_PLAYER: if( this->players[ client ] && this->players[ client ]->clientEntity ) { data.UpdateInt( entityId ); if( this->players[ client ]->clientEntity->GetId() == unsigned(entityId) ) { this->entityManager->SuicidePlayer( this->players[ client ]->clientEntity ); } } break; } data.SetExternBuffer( 0, 0 ); } //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 425 ] ] ]
ce3d5250bf00535f01d8e7ebf8cd0a2988490b67
241c6a1683325fdae37f5cea2716e8e639dd09a4
/tdi.h
ebb50f19751ddcf034bc736a4f262e1ddcb1d49e
[]
no_license
awstanley/rpgtools-hg-tmp
060bb8abe19512b282bb04ec433a0158623afaf8
02b50dff4d80c32f12065b18390ea71bedb130df
refs/heads/master
2020-11-24T17:43:26.561364
2011-07-17T21:40:02
2011-07-17T21:40:02
228,278,083
0
0
null
null
null
null
UTF-8
C++
false
false
14,378
h
/****************************************************************************** * vim: set ts=4 : ****************************************************************************** * RPGTools Extension * Copyright (C) 2011 A.W. 'Swixel' Stanley. ****************************************************************************** * * Modified from Valve Code, and Predcrab's CBaseEntities * (with permission and under licence). * ****************************************************************************** * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. *****************************************************************************/ #ifndef TAKEDAMAGEINFO_H #define TAKEDAMAGEINFO_H #ifdef _WIN32 #pragma once #endif #include "extension.h" extern IServerGameEnts *gameents; // Used to initialize m_flBaseDamage to something that we know pretty much for sure // hasn't been modified by a user. #define BASEDAMAGE_NOT_SPECIFIED FLT_MAX class CBaseEntity; /* From Matt Woodrow's CEntity work: http://hg.alliedmods.net/users/pred_alliedmods.net/centity/ * Used with his permission, not to mention under valid licence. */ CEntity *pEntityData[MAX_EDICTS+1] = {NULL}; inline CEntity *Instance(CBaseEntity *pEnt); inline CEntity *Instance(int iEnt); inline CEntity *Instance(const edict_t *pEnt); inline CEntity *Instance(const CBaseHandle &hEnt); inline CEntity *Instance(edict_t *pEnt); inline CEntity *Instance(CBaseEntity *pEnt) { if (!pEnt) { return NULL; } edict_t *pEdict = gameents->BaseEntityToEdict(pEnt); if (!pEdict) { return NULL; } return Instance(pEdict); } inline CEntity *Instance(int iEnt) { return pEntityData[iEnt]; } inline CEntity *Instance(const edict_t *pEnt) { return Instance(engine->IndexOfEdict(pEnt)); } inline CEntity *Instance(const CBaseHandle &hEnt) { if (!hEnt.IsValid()) { return NULL; } int index = hEnt.GetEntryIndex(); edict_t *pStoredEdict; CBaseEntity *pStoredEntity; pStoredEdict = engine->PEntityOfEntIndex(index); if (!pStoredEdict || pStoredEdict->IsFree()) { return NULL; } IServerUnknown *pUnk; if ((pUnk = pStoredEdict->GetUnknown()) == NULL) { return NULL; } pStoredEntity = pUnk->GetBaseEntity(); if (pStoredEntity == NULL) { return NULL; } IServerEntity *pSE = pStoredEdict->GetIServerEntity(); if (pSE == NULL) { return NULL; } if (pSE->GetRefEHandle() != hEnt) { return NULL; } return Instance(index); } inline CEntity *Instance(edict_t *pEnt) { return Instance(engine->IndexOfEdict(pEnt)); } class CTakeDamageInfo { public: DECLARE_CLASS_NOBASE( CTakeDamageInfo ); CTakeDamageInfo(); CTakeDamageInfo( CBaseEntity *pInflictor, CBaseEntity *pAttacker, float flDamage, int bitsDamageType, int iKillType = 0 ); CTakeDamageInfo( CBaseEntity *pInflictor, CBaseEntity *pAttacker, CBaseEntity *pWeapon, float flDamage, int bitsDamageType, int iKillType = 0 ); CTakeDamageInfo( CBaseEntity *pInflictor, CBaseEntity *pAttacker, const Vector &damageForce, const Vector &damagePosition, float flDamage, int bitsDamageType, int iKillType = 0, Vector *reportedPosition = NULL ); CTakeDamageInfo( CBaseEntity *pInflictor, CBaseEntity *pAttacker, CBaseEntity *pWeapon, const Vector &damageForce, const Vector &damagePosition, float flDamage, int bitsDamageType, int iKillType = 0, Vector *reportedPosition = NULL ); // Inflictor is the weapon or rocket (or player) that is dealing the damage. CBaseEntity* GetInflictor() const; void SetInflictor( CBaseEntity *pInflictor ); // Weapon is the weapon that did the attack. // For hitscan weapons, it'll be the same as the inflictor. For projectile weapons, the projectile // is the inflictor, and this contains the weapon that created the projectile. CBaseEntity* GetWeapon() const; void SetWeapon( CBaseEntity *pWeapon ); // Attacker is the character who originated the attack (like a player or an AI). CBaseEntity* GetAttacker() const; void SetAttacker( CBaseEntity *pAttacker ); float GetDamage() const; void SetDamage( float flDamage ); float GetMaxDamage() const; void SetMaxDamage( float flMaxDamage ); void ScaleDamage( float flScaleAmount ); void AddDamage( float flAddAmount ); void SubtractDamage( float flSubtractAmount ); float GetBaseDamage() const; bool BaseDamageIsValid() const; Vector GetDamageForce() const; void SetDamageForce( const Vector &damageForce ); void ScaleDamageForce( float flScaleAmount ); Vector GetDamagePosition() const; void SetDamagePosition( const Vector &damagePosition ); Vector GetReportedPosition() const; void SetReportedPosition( const Vector &reportedPosition ); int GetDamageType() const; void SetDamageType( int bitsDamageType ); void AddDamageType( int bitsDamageType ); int GetDamageCustom( void ) const; void SetDamageCustom( int iDamageCustom ); int GetDamageStats( void ) const; void SetDamageStats( int iDamageStats ); int GetAmmoType() const; void SetAmmoType( int iAmmoType ); const char * GetAmmoName() const; void Set( CBaseEntity *pInflictor, CBaseEntity *pAttacker, float flDamage, int bitsDamageType, int iKillType = 0 ); void Set( CBaseEntity *pInflictor, CBaseEntity *pAttacker, CBaseEntity *pWeapon, float flDamage, int bitsDamageType, int iKillType = 0 ); void Set( CBaseEntity *pInflictor, CBaseEntity *pAttacker, const Vector &damageForce, const Vector &damagePosition, float flDamage, int bitsDamageType, int iKillType = 0, Vector *reportedPosition = NULL ); void Set( CBaseEntity *pInflictor, CBaseEntity *pAttacker, CBaseEntity *pWeapon, const Vector &damageForce, const Vector &damagePosition, float flDamage, int bitsDamageType, int iKillType = 0, Vector *reportedPosition = NULL ); void AdjustPlayerDamageInflictedForSkillLevel(); void AdjustPlayerDamageTakenForSkillLevel(); // Given a damage type (composed of the #defines above), fill out a string with the appropriate text. // For designer debug output. static void DebugGetDamageTypeString(unsigned int DamageType, char *outbuf, int outbuflength ); //private: void CopyDamageToBaseDamage(); protected: void Init( CBaseEntity *pInflictor, CBaseEntity *pAttacker, CBaseEntity *pWeapon, const Vector &damageForce, const Vector &damagePosition, const Vector &reportedPosition, float flDamage, int bitsDamageType, int iKillType ); Vector m_vecDamageForce; Vector m_vecDamagePosition; Vector m_vecReportedPosition; // Position players are told damage is coming from EHANDLE m_hInflictor; EHANDLE m_hAttacker; EHANDLE m_hWeapon; float m_flDamage; float m_flMaxDamage; float m_flBaseDamage; // The damage amount before skill leve adjustments are made. Used to get uniform damage forces. int m_bitsDamageType; int m_iDamageCustom; int m_iDamageStats; int m_iAmmoType; // AmmoType of the weapon used to cause this damage, if any int m_iUnknown1; DECLARE_SIMPLE_DATADESC(); }; //----------------------------------------------------------------------------- // Purpose: Multi damage. Used to collect multiple damages in the same frame (i.e. shotgun pellets) //----------------------------------------------------------------------------- class CMultiDamage : public CTakeDamageInfo { DECLARE_CLASS( CMultiDamage, CTakeDamageInfo ); public: CMultiDamage(); bool IsClear( void ) { return (m_hTarget == NULL); } CBaseEntity *GetTarget() const; void SetTarget( CBaseEntity *pTarget ); void Init( CBaseEntity *pTarget, CBaseEntity *pInflictor, CBaseEntity *pAttacker, CBaseEntity *pWeapon, const Vector &damageForce, const Vector &damagePosition, const Vector &reportedPosition, float flDamage, int bitsDamageType, int iKillType ); protected: EHANDLE m_hTarget; DECLARE_SIMPLE_DATADESC(); }; extern CMultiDamage g_MultiDamage; // Multidamage accessors void ClearMultiDamage( void ); void ApplyMultiDamage( void ); void AddMultiDamage( const CTakeDamageInfo &info, CBaseEntity *pEntity ); //----------------------------------------------------------------------------- // Purpose: Utility functions for physics damage force calculation //----------------------------------------------------------------------------- float ImpulseScale( float flTargetMass, float flDesiredSpeed ); void CalculateExplosiveDamageForce( CTakeDamageInfo *info, const Vector &vecDir, const Vector &vecForceOrigin, float flScale = 1.0 ); void CalculateBulletDamageForce( CTakeDamageInfo *info, int iBulletType, const Vector &vecBulletDir, const Vector &vecForceOrigin, float flScale = 1.0 ); void CalculateMeleeDamageForce( CTakeDamageInfo *info, const Vector &vecMeleeDir, const Vector &vecForceOrigin, float flScale = 1.0 ); void GuessDamageForce( CTakeDamageInfo *info, const Vector &vecForceDir, const Vector &vecForceOrigin, float flScale = 1.0 ); // -------------------------------------------------------------------------------------------------- // // Inlines. // -------------------------------------------------------------------------------------------------- // inline CBaseEntity* CTakeDamageInfo::GetInflictor() const { return Instance(m_hInflictor); } inline void CTakeDamageInfo::SetInflictor( CBaseEntity *pInflictor ) { m_hInflictor = pInflictor; } inline CBaseEntity* CTakeDamageInfo::GetAttacker() const { return Instance(m_hAttacker); } inline void CTakeDamageInfo::SetAttacker( CBaseEntity *pAttacker ) { m_hAttacker = pAttacker; } inline CBaseEntity* CTakeDamageInfo::GetWeapon() const { return Instance(m_hWeapon); } inline void CTakeDamageInfo::SetWeapon( CBaseEntity *pWeapon ) { m_hWeapon = pWeapon; } inline float CTakeDamageInfo::GetDamage() const { return m_flDamage; } inline void CTakeDamageInfo::SetDamage( float flDamage ) { m_flDamage = flDamage; } inline float CTakeDamageInfo::GetMaxDamage() const { return m_flMaxDamage; } inline void CTakeDamageInfo::SetMaxDamage( float flMaxDamage ) { m_flMaxDamage = flMaxDamage; } inline void CTakeDamageInfo::ScaleDamage( float flScaleAmount ) { m_flDamage *= flScaleAmount; } inline void CTakeDamageInfo::AddDamage( float flAddAmount ) { m_flDamage += flAddAmount; } inline void CTakeDamageInfo::SubtractDamage( float flSubtractAmount ) { m_flDamage -= flSubtractAmount; } inline float CTakeDamageInfo::GetBaseDamage() const { if( BaseDamageIsValid() ) return m_flBaseDamage; // No one ever specified a base damage, so just return damage. return m_flDamage; } inline bool CTakeDamageInfo::BaseDamageIsValid() const { return (m_flBaseDamage != BASEDAMAGE_NOT_SPECIFIED); } inline Vector CTakeDamageInfo::GetDamageForce() const { return m_vecDamageForce; } inline void CTakeDamageInfo::SetDamageForce( const Vector &damageForce ) { m_vecDamageForce = damageForce; } inline void CTakeDamageInfo::ScaleDamageForce( float flScaleAmount ) { m_vecDamageForce *= flScaleAmount; } inline Vector CTakeDamageInfo::GetDamagePosition() const { return m_vecDamagePosition; } inline void CTakeDamageInfo::SetDamagePosition( const Vector &damagePosition ) { m_vecDamagePosition = damagePosition; } inline Vector CTakeDamageInfo::GetReportedPosition() const { return m_vecReportedPosition; } inline void CTakeDamageInfo::SetReportedPosition( const Vector &reportedPosition ) { m_vecReportedPosition = reportedPosition; } inline int CTakeDamageInfo::GetDamageType() const { return m_bitsDamageType; } inline void CTakeDamageInfo::SetDamageType( int bitsDamageType ) { m_bitsDamageType = bitsDamageType; } inline void CTakeDamageInfo::AddDamageType( int bitsDamageType ) { m_bitsDamageType |= bitsDamageType; } inline int CTakeDamageInfo::GetDamageCustom() const { return m_iDamageCustom; } inline void CTakeDamageInfo::SetDamageCustom( int iDamageCustom ) { m_iDamageCustom = iDamageCustom; } inline int CTakeDamageInfo::GetDamageStats() const { return m_iDamageCustom; } inline void CTakeDamageInfo::SetDamageStats( int iDamageCustom ) { m_iDamageCustom = iDamageCustom; } inline int CTakeDamageInfo::GetAmmoType() const { return m_iAmmoType; } inline void CTakeDamageInfo::SetAmmoType( int iAmmoType ) { m_iAmmoType = iAmmoType; } inline void CTakeDamageInfo::CopyDamageToBaseDamage() { m_flBaseDamage = m_flDamage; } // -------------------------------------------------------------------------------------------------- // // Inlines. // -------------------------------------------------------------------------------------------------- // inline CBaseEntity *CMultiDamage::GetTarget() const { return m_hTarget; } inline void CMultiDamage::SetTarget( CBaseEntity *pTarget ) { m_hTarget = pTarget; } #endif // TAKEDAMAGEINFO_H
[ [ [ 1, 467 ] ] ]
6862771f74f5ded0283453ec6f8363c143557f02
c930acc7d855f5082dfc598437dacd7d73718787
/aiplayer.h
a789dbcd54cd2ef73ab4b3ed5bd26a69a6fe0d78
[]
no_license
giulianoxt/qassault
9db0c67c2122d41299e4f41e3bc5d985b8a7db7b
ff46426199e5336b64bd8eb70fce66d8e0212f83
refs/heads/master
2020-05-19T11:13:13.623501
2009-10-06T00:50:02
2009-10-06T00:50:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
915
h
#ifndef AIPLAYER_H #define AIPLAYER_H #include <QThread> #include <QAtomicInt> #include "util.h" #include "game.h" #include "minimax.h" class AIPlayer : public QThread { public: AIPlayer(PlayerType); Move getMove(); void reset(GameState*); public slots: void timeout(); protected: virtual void run() = 0; protected: Move chosen_move; GameState* state; PlayerType type; QAtomicInt done; }; class DummyPlayer : public AIPlayer { public: DummyPlayer(PlayerType); protected: virtual void run(); }; class GreedyPlayer : public AIPlayer { public: GreedyPlayer(PlayerType); protected: virtual void run(); }; class MinimaxPlayer : public AIPlayer { public: MinimaxPlayer(PlayerType, int); protected: virtual void run(); MinimaxAI minimaxAI; }; #endif // AIPLAYER_H
[ [ [ 1, 64 ] ] ]
ceb7e8e82d59e82d24fa3357ff9f2ed862395265
f313ed85887a5dace0e7be11300f88c206b0a2c1
/src/itkWeightMetricCalculator.h
ecfa6fe577f28bd26618617e3a02bc8495121360
[]
no_license
midas-journal/midas-journal-315
92a7f6adb309faac826bbd122d9c77c7884d04ea
178f63ee394d1f26703ab986b00c16e0880fc9bd
refs/heads/master
2021-01-18T19:27:59.656711
2011-08-22T13:24:38
2011-08-22T13:24:38
2,248,627
0
0
null
null
null
null
UTF-8
C++
false
false
2,989
h
/*========================================================================= Project: dijkstra Program: Insight Segmentation & Registration Toolkit Module: itkWeightMetricCalculator.h Language: C++ Date: 26/1/2009 Version: 1.0 Authors: Lior Weizman & Moti Freiman Portions of this code are covered under the ITK and VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __itkWeightMetricCalculator_h #define __itkWeightMetricCalculator_h #include "itkObject.h" #include "itkObjectFactory.h" #include "itkShapedNeighborhoodIterator.h" namespace itk { template <class TInputImageType> class ITK_EXPORT WeightMetricCalculator : public Object { public: /** Standard class typedefs. */ typedef WeightMetricCalculator Self; typedef Object Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; typedef ShapedNeighborhoodIterator< TInputImageType > itkShapedNeighborhoodIteratorType; /** Run-time type information (and related methods). */ itkTypeMacro(WeightMetricCalculator, Object); /** Type definition for the input image. */ typedef TInputImageType ImageType; /** Pointer type for the image. */ typedef typename TInputImageType::Pointer ImagePointer; /** Const Pointer type for the image. */ typedef typename TInputImageType::ConstPointer ImageConstPointer; /** Type definition for the input image pixel type. */ typedef typename TInputImageType::PixelType PixelType; /** Type definition for the input image index type. */ typedef const typename TInputImageType::IndexType IndexType; typedef typename ShapedNeighborhoodIterator< TInputImageType >::Iterator itkShapedNeighborhoodIteratorforIteratorType; /** Set the input image. */ itkSetConstObjectMacro(Image,ImageType); virtual double GetEdgeWeight (const itkShapedNeighborhoodIteratorType &it1,const itkShapedNeighborhoodIteratorforIteratorType &it2) = 0; virtual void Initialize () = 0; WeightMetricCalculator(); protected: virtual ~WeightMetricCalculator() {}; void PrintSelf(std::ostream& os, Indent indent) const; ImageConstPointer m_Image; private: WeightMetricCalculator(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkWeightMetricCalculator.txx" #endif #endif /* __itkLabels2EdgesImageCalculator_h */
[ [ [ 1, 98 ] ] ]
d6309621e405221d5c650638460638a7e2a49de4
5f28f9e0948b026058bafe651ba0ce03971eeafa
/LindsayAR Client MultiMulti/ARToolkitPlus/include/ARToolKitPlus/matrix.h
f86c196b1e27cc70934c856de356149796b70029
[]
no_license
TheProjecter/surfacetoar
cbe460d9f41a2f2d7a677a697114e4eea7516218
4ccba52e55b026b63473811319ceccf6ae3fbc1f
refs/heads/master
2020-05-17T15:41:31.087874
2010-11-08T00:09:25
2010-11-08T00:09:25
42,946,053
0
0
null
null
null
null
UTF-8
C++
false
false
1,611
h
/** * Copyright (C) 2010 ARToolkitPlus Authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authors: * Daniel Wagner */ #ifndef __ARTOOLKITMATRIX_HEADERFILE__ #define __ARTOOLKITMATRIX_HEADERFILE__ #include "config.h" /* === matrix definition === <---- clm ---> [ 10 20 30 ] ^ [ 20 10 15 ] | [ 12 23 13 ] row [ 20 10 15 ] | [ 13 14 15 ] v =========================== */ namespace ARToolKitPlus { struct ARMat { ARFloat *m; int row; int clm; }; namespace Matrix { /* 0 origin */ #define ARELEM0(mat,r,c) ((mat)->m[(r)*((mat)->clm)+(c)]) /* 1 origin */ #define ARELEM1(mat,row,clm) ARELEM0(mat,row-1,clm-1) ARMat *alloc(int row, int clm); int free(ARMat *m); int dup(ARMat *dest, ARMat *source); ARMat *allocDup(ARMat *source); int mul(ARMat *dest, ARMat *a, ARMat *b); int selfInv(ARMat *m); } // namespace Matrix } // namespace ARToolKitPlus #endif // __ARTOOLKITMATRIX_HEADERFILE__
[ [ [ 1, 67 ] ] ]
708f17174252affbbf2b806c07913134e03fdd20
67298ca8528b753930a3dc043972dceab5e45d6a
/FileSharing/src/ActiveObject.cpp
d3c458d9471906327592fc2fbb6689a84d60ef48
[]
no_license
WhyKay92/cs260assignment3
3cf28dd92b9956b2cd4f850652651cb11f25c753
77ad90cd2dc0b44f3ba0a396dc8399021de4faa5
refs/heads/master
2021-05-30T14:59:21.297733
2010-12-13T09:18:17
2010-12-13T09:18:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,121
cpp
/*! * @File ActiveObject.cpp * @Author Steven Liss and Westley Hennigh * @Date 25 Feb 2010, 20 Oct 2010 * @Brief Threads as objects, neat. */ #include "ActiveObject.hpp" ActiveObject::ActiveObject() : isDying( false ), #pragma warning(disable: 4355) // 4355 == 'this' used before initialized warning mythread( ThreadFunc, this ) #pragma warning(default: 4355) {} ActiveObject::~ActiveObject() {} // Wake is not virtual because any code that you would put in here really should go // in your constructor instead. All this does it resume the thread. void ActiveObject::Wake() { mythread.Resume(); } // Kill must be called to clean up the thread void ActiveObject::Kill() { isDying = true; FlushThread(); // Wait for the thread to die mythread.WaitForDeath(); } // The thread executes the run function of its handler DWORD WINAPI ActiveObject::ThreadFunc( void* pAO ) { ActiveObject* ActiveObj = static_cast<ActiveObject*>(pAO); ActiveObj->InitThread(); ActiveObj->Run(); return 0; // no one cares what we return in this case }
[ [ [ 1, 48 ] ] ]
95b9a4e2bf8d13a587deb85a6af0bcbba782510b
46653590825ea44df39c88f5e5e761122239b882
/EseObjects/Stdafx.cpp
6eb2ea79d62d3f612a91e196071d893dbc258ee7
[]
no_license
CADbloke/eselinq
e46e24d41a09ba467cc54a94b5ad803d00e6e2d1
e19f217a32b23b2fd71149653fe792086c798cb8
refs/heads/master
2021-01-13T01:00:48.817112
2010-08-26T01:50:39
2010-08-26T01:50:39
36,408,696
0
0
null
null
null
null
UTF-8
C++
false
false
1,859
cpp
/////////////////////////////////////////////////////////////////////////////// // Project : EseLinq http://code.google.com/p/eselinq/ // Copyright : (c) 2009 Christopher Smith // Maintainer : [email protected] // Module : stdafx.cpp - Exposes support for saving ESE keys /////////////////////////////////////////////////////////////////////////////// // //This software is licenced under the terms of the MIT License: // //Copyright (c) 2009 Christopher Smith // //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. // /////////////////////////////////////////////////////////////////////////////// // stdafx.cpp : source file that includes just the standard includes // EseObjects.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ [ [ 1, 36 ] ] ]
ecf5da8840dc9410df823dfedb3c433a2910a4c1
5e0422794380a8f3bf06d0c37ac2354f4b91fefb
/fastnetwork/default_filter_chain.h
cd6c2f324504e0bd49db7dcc8e9a5d756552cb44
[]
no_license
OrAlien/fastnetwork
1d8fb757b855b1f23cc844cda4d8dc7a568bc38e
792d28d8b5829c227aebe8378f60db17de4d6f14
refs/heads/master
2021-05-28T20:30:24.031458
2010-06-02T14:30:04
2010-06-02T14:30:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,650
h
#pragma once #include <vector> #include "session_filter_chain.h" namespace fastnetwork { using namespace std; using namespace boost; class default_filter_chain : public session_filter_chain { private: typedef void (session_filter::*session_fun)(shared_ptr<io_session>); public: default_filter_chain() : filters_() {} ~default_filter_chain(void) {} public: void add_filter( boost::shared_ptr<session_filter> filter ) { mutex::scoped_lock lock(mutex_); add_filter( filters_.size(), filter ); } void add_filter( size_t index, boost::shared_ptr<session_filter> filter ) { mutex::scoped_lock lock(mutex_); filters_.insert( filters_.begin() + index, filter ); } void remove_filter( boost::shared_ptr<session_filter> filter ) { mutex::scoped_lock lock(mutex_); for( size_t i = 0; i < filters_.size(); ++i ) { if( filters_[i] == filter ) { filters_.erase( filters_.begin() + i ); break; } } } void session_connected( shared_ptr<io_session> session ) { mutex::scoped_lock lock(mutex_); reverse_filters( session, &session_filter::session_connected ); session->get_handler()->session_connected( session ); } void session_closed( shared_ptr<io_session> session ) { mutex::scoped_lock lock(mutex_); session->get_handler()->session_closed( session ); do_filters( session, &session_filter::session_closed ); } void session_idle( shared_ptr<io_session> session ) { mutex::scoped_lock lock(mutex_); do_filters( session, &session_filter::session_idle ); session->get_handler()->session_idle( session ); } any filter_receive( shared_ptr<io_session> session, any packet ) { mutex::scoped_lock lock(mutex_); any p = packet; for( size_t i = filters_.size(); i > 0; --i ) { p = filters_[i - 1]->filter_receive( session, p ); } return p; } any filter_send( shared_ptr<io_session> session, any packet ) { mutex::scoped_lock lock(mutex_); any p = packet; for( size_t i = 0; i < filters_.size(); ++i ) { p = filters_[i]->filter_send( session, p ); } return p; } private: void do_filters( shared_ptr<io_session> session, session_fun fun ) { for( size_t i = 0; i < filters_.size(); ++i ) { (filters_[i].get()->*fun)( session ); } } void reverse_filters( shared_ptr<io_session> session, session_fun fun ) { for( size_t i = filters_.size(); i > 0; --i ) { (filters_[i - 1].get()->*fun)( session ); } } private: boost::mutex mutex_; vector<shared_ptr<session_filter>> filters_; }; }
[ "everwanna@8b0bd7a0-72c1-11de-90d8-1fdda9445408" ]
[ [ [ 1, 93 ] ] ]
cac101c7fa70f21dc199b3ec99c04fba9b007e7f
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_client/src/Skin/PrivateChatWindowBase.cpp
b89bc5ec3efed09d10a05d147daf4b9c544739f9
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
299
cpp
#include <wx/wx.h> #include "PrivateChatWindowBase.h" PrivateChatWindowBase::~PrivateChatWindowBase() { } void PrivateChatWindowBase::SetUserName(const wxString &name) { m_userName = name; } const wxString & PrivateChatWindowBase::GetUserName() const { return m_userName; }
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 18 ] ] ]
2f57c4b7b21e6810b7ee3efe5bcf769dbc2cdfb5
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Engine/Graphics/ShoulderCamera.cpp
d6229221d2e1b3595b95c7695460624b58f1c7bb
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
UTF-8
C++
false
false
1,151
cpp
#include "ShoulderCamera.h" #include "base.h" CShoulderCamera::CShoulderCamera(float zn, float zf, float fov, float aspect, CObject3D* object3D, float _fObjectDistance, float _fShoulderDistance, float _fShoulderHeight) : CThPSCamera(zn, zf, fov, aspect, object3D, _fObjectDistance), m_fShoulderDistance(_fShoulderDistance), m_fShoulderHeight(_fShoulderHeight) {} CShoulderCamera::CShoulderCamera() : CThPSCamera(), m_fShoulderDistance(1.0f) {} CShoulderCamera::~CShoulderCamera(void) { } Vect3f CShoulderCamera::GetLookAt () const { assert(m_pObject3D); Vect3f l_vPos(0.0f); float l_fYaw = m_pObject3D->GetYaw(); l_vPos.x = m_fShoulderDistance * sin(l_fYaw); l_vPos.y = m_fShoulderHeight; l_vPos.z = -m_fShoulderDistance * cos(l_fYaw); return m_pObject3D->GetPosition() + l_vPos; } Vect3f CShoulderCamera::GetEye() const { assert(m_pObject3D); Vect3f l_vPos(0.0f); float l_fYaw = m_pObject3D->GetYaw(); l_vPos.x = m_fShoulderDistance * sin(l_fYaw); l_vPos.y = m_fShoulderHeight; l_vPos.z = -m_fShoulderDistance * cos(l_fYaw); return (l_vPos + CThPSCamera::GetEye()); }
[ "sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485" ]
[ [ [ 1, 42 ] ] ]
39164b0308616ae6f082de11e3862c404b3ac623
ad00c3a132f75a71bf763ce0aa70742fcede5ce8
/DotnetServer/SDK/amxplugin.cpp
dfa4ac62b27f1c889fcd7cda3a7deeb953199a05
[]
no_license
Dracar/samp-dotnet-script-api
6975208c1beab28bed2480602c232f737f0bd86b
d88ddfcb9c52a807d3eb8e74607c0857f184d006
refs/heads/master
2021-01-22T03:57:49.952418
2011-12-22T15:40:12
2011-12-22T15:40:12
42,196,278
0
0
null
null
null
null
UTF-8
C++
false
false
12,845
cpp
//---------------------------------------------------------- // // SA-MP Multiplayer Modification For GTA:SA // Copyright 2004-2009 SA-MP Team // //---------------------------------------------------------- // // This provides an interface to call amx library functions // within samp-server. // //---------------------------------------------------------- #include "amx/amx.h" #include "plugincommon.h" //---------------------------------------------------------- void *pAMXFunctions; //---------------------------------------------------------- typedef uint16_t * AMXAPI (*amx_Align16_t)(uint16_t *v); uint16_t * AMXAPI amx_Align16(uint16_t *v) { amx_Align16_t fn = ((amx_Align16_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16]; return fn(v); } typedef uint32_t * AMXAPI (*amx_Align32_t)(uint32_t *v); uint32_t * AMXAPI amx_Align32(uint32_t *v) { amx_Align32_t fn = ((amx_Align32_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32]; return fn(v); } #if defined _I64_MAX || defined HAVE_I64 typedef uint64_t * AMXAPI (*amx_Align64_t)(uint64_t *v); uint64_t * AMXAPI amx_Align64(uint64_t *v) { amx_Align64_t fn = ((amx_Align64_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64]; return fn(v); } #endif typedef int AMXAPI (*amx_Allot_t)(AMX *amx, int cells, cell *amx_addr, cell **phys_addr); int AMXAPI amx_Allot(AMX *amx, int cells, cell *amx_addr, cell **phys_addr) { amx_Allot_t fn = ((amx_Allot_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Allot]; return fn(amx, cells, amx_addr, phys_addr); } typedef int AMXAPI (*amx_Callback_t)(AMX *amx, cell index, cell *result, cell *params); int AMXAPI amx_Callback(AMX *amx, cell index, cell *result, cell *params) { amx_Callback_t fn = ((amx_Callback_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback]; return fn(amx, index, result, params); } typedef int AMXAPI (*amx_Cleanup_t)(AMX *amx); int AMXAPI amx_Cleanup(AMX *amx) { amx_Cleanup_t fn = ((amx_Cleanup_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Cleanup]; return fn(amx); } typedef int AMXAPI (*amx_Clone_t)(AMX *amxClone, AMX *amxSource, void *data); int AMXAPI amx_Clone(AMX *amxClone, AMX *amxSource, void *data) { amx_Clone_t fn = ((amx_Clone_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Clone]; return fn(amxClone, amxSource, data); } typedef int AMXAPI (*amx_Exec_t)(AMX *amx, cell *retval, int index); int AMXAPI amx_Exec(AMX *amx, cell *retval, int index) { amx_Exec_t fn = ((amx_Exec_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec]; return fn(amx, retval, index); } typedef int AMXAPI (*amx_FindNative_t)(AMX *amx, const char *name, int *index); int AMXAPI amx_FindNative(AMX *amx, const char *name, int *index) { amx_FindNative_t fn = ((amx_FindNative_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_FindNative]; return fn(amx, name, index); } typedef int AMXAPI (*amx_FindPublic_t)(AMX *amx, const char *funcname, int *index); int AMXAPI amx_FindPublic(AMX *amx, const char *funcname, int *index) { amx_FindPublic_t fn = ((amx_FindPublic_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_FindPublic]; return fn(amx, funcname, index); } typedef int AMXAPI (*amx_FindPubVar_t)(AMX *amx, const char *varname, cell *amx_addr); int AMXAPI amx_FindPubVar(AMX *amx, const char *varname, cell *amx_addr) { amx_FindPubVar_t fn = ((amx_FindPubVar_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_FindPubVar]; return fn(amx, varname, amx_addr); } typedef int AMXAPI (*amx_FindTagId_t)(AMX *amx, cell tag_id, char *tagname); int AMXAPI amx_FindTagId(AMX *amx, cell tag_id, char *tagname) { amx_FindTagId_t fn = ((amx_FindTagId_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_FindTagId]; return fn(amx, tag_id, tagname); } typedef int AMXAPI (*amx_Flags_t)(AMX *amx,uint16_t *flags); int AMXAPI amx_Flags(AMX *amx,uint16_t *flags) { amx_Flags_t fn = ((amx_Flags_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Flags]; return fn(amx,flags); } typedef int AMXAPI (*amx_GetAddr_t)(AMX *amx,cell amx_addr,cell **phys_addr); int AMXAPI amx_GetAddr(AMX *amx,cell amx_addr,cell **phys_addr) { amx_GetAddr_t fn = ((amx_GetAddr_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetAddr]; return fn(amx,amx_addr,phys_addr); } typedef int AMXAPI (*amx_GetNative_t)(AMX *amx, int index, char *funcname); int AMXAPI amx_GetNative(AMX *amx, int index, char *funcname) { amx_GetNative_t fn = ((amx_GetNative_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetNative]; return fn(amx, index, funcname); } typedef int AMXAPI (*amx_GetPublic_t)(AMX *amx, int index, char *funcname); int AMXAPI amx_GetPublic(AMX *amx, int index, char *funcname) { amx_GetPublic_t fn = ((amx_GetPublic_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetPublic]; return fn(amx, index, funcname); } typedef int AMXAPI (*amx_GetPublic_tt)(AMX *amx, int index, char *funcname,unsigned int* retarddr); int AMXAPI amx_GetPublicc(AMX *amx, int index, char *funcname,unsigned int* retarddr) { amx_GetPublic_tt fn = ((amx_GetPublic_tt*)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetPublic]; return fn(amx, index, funcname,retarddr); } typedef int AMXAPI (*amx_GetPubVar_t)(AMX *amx, int index, char *varname, cell *amx_addr); int AMXAPI amx_GetPubVar(AMX *amx, int index, char *varname, cell *amx_addr) { amx_GetPubVar_t fn = ((amx_GetPubVar_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetPubVar]; return fn(amx, index, varname, amx_addr); } typedef int AMXAPI (*amx_GetString_t)(char *dest,const cell *source, int use_wchar, size_t size); int AMXAPI amx_GetString(char *dest,const cell *source, int use_wchar, size_t size) { amx_GetString_t fn = ((amx_GetString_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetString]; return fn(dest,source, use_wchar, size); } typedef int AMXAPI (*amx_GetTag_t)(AMX *amx, int index, char *tagname, cell *tag_id); int AMXAPI amx_GetTag(AMX *amx, int index, char *tagname, cell *tag_id) { amx_GetTag_t fn = ((amx_GetTag_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetTag]; return fn(amx, index, tagname, tag_id); } typedef int AMXAPI (*amx_GetUserData_t)(AMX *amx, long tag, void **ptr); int AMXAPI amx_GetUserData(AMX *amx, long tag, void **ptr) { amx_GetUserData_t fn = ((amx_GetUserData_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetUserData]; return fn(amx, tag, ptr); } typedef int AMXAPI (*amx_Init_t)(AMX *amx, void *program); int AMXAPI amx_Init(AMX *amx, void *program) { amx_Init_t fn = ((amx_Init_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Init]; return fn(amx, program); } typedef int AMXAPI (*amx_InitJIT_t)(AMX *amx, void *reloc_table, void *native_code); int AMXAPI amx_InitJIT(AMX *amx, void *reloc_table, void *native_code) { amx_InitJIT_t fn = ((amx_InitJIT_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_InitJIT]; return fn(amx, reloc_table, native_code); } typedef int AMXAPI (*amx_MemInfo_t)(AMX *amx, long *codesize, long *datasize, long *stackheap); int AMXAPI amx_MemInfo(AMX *amx, long *codesize, long *datasize, long *stackheap) { amx_MemInfo_t fn = ((amx_MemInfo_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_MemInfo]; return fn(amx, codesize, datasize, stackheap); } typedef int AMXAPI (*amx_NameLength_t)(AMX *amx, int *length); int AMXAPI amx_NameLength(AMX *amx, int *length) { amx_NameLength_t fn = ((amx_NameLength_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_NameLength]; return fn(amx, length); } typedef AMX_NATIVE_INFO * AMXAPI (*amx_NativeInfo_t)(const char *name, AMX_NATIVE func); AMX_NATIVE_INFO * AMXAPI amx_NativeInfo(const char *name, AMX_NATIVE func) { amx_NativeInfo_t fn = ((amx_NativeInfo_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_NativeInfo]; return fn(name, func); } typedef int AMXAPI (*amx_NumNatives_t)(AMX *amx, int *number); int AMXAPI amx_NumNatives(AMX *amx, int *number) { amx_NumNatives_t fn = ((amx_NumNatives_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_NumNatives]; return fn(amx, number); } typedef int AMXAPI (*amx_NumPublics_t)(AMX *amx, int *number); int AMXAPI amx_NumPublics(AMX *amx, int *number) { amx_NumPublics_t fn = ((amx_NumPublics_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_NumPublics]; return fn(amx, number); } typedef int AMXAPI (*amx_NumPubVars_t)(AMX *amx, int *number); int AMXAPI amx_NumPubVars(AMX *amx, int *number) { amx_NumPubVars_t fn = ((amx_NumPubVars_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_NumPubVars]; return fn(amx, number); } typedef int AMXAPI (*amx_NumTags_t)(AMX *amx, int *number); int AMXAPI amx_NumTags(AMX *amx, int *number) { amx_NumTags_t fn = ((amx_NumTags_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_NumTags]; return fn(amx, number); } typedef int AMXAPI (*amx_Push_t)(AMX *amx, cell value); int AMXAPI amx_Push(AMX *amx, cell value) { amx_Push_t fn = ((amx_Push_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Push]; return fn(amx, value); } typedef int AMXAPI (*amx_PushArray_t)(AMX *amx, cell *amx_addr, cell **phys_addr, const cell array[], int numcells); int AMXAPI amx_PushArray(AMX *amx, cell *amx_addr, cell **phys_addr, const cell array[], int numcells) { amx_PushArray_t fn = ((amx_PushArray_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_PushArray]; return fn(amx, amx_addr, phys_addr, array, numcells); } typedef int AMXAPI (*amx_PushString_t)(AMX *amx, cell *amx_addr, cell **phys_addr, const char *string, int pack, int use_wchar); int AMXAPI amx_PushString(AMX *amx, cell *amx_addr, cell **phys_addr, const char *string, int pack, int use_wchar) { amx_PushString_t fn = ((amx_PushString_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_PushString]; return fn(amx, amx_addr, phys_addr, string, pack, use_wchar); } typedef int AMXAPI (*amx_RaiseError_t)(AMX *amx, int error); int AMXAPI amx_RaiseError(AMX *amx, int error) { amx_RaiseError_t fn = ((amx_RaiseError_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_RaiseError]; return fn(amx, error); } typedef int AMXAPI (*amx_Register_t)(AMX *amx, const AMX_NATIVE_INFO *nativelist, int number); int AMXAPI amx_Register(AMX *amx, const AMX_NATIVE_INFO *nativelist, int number) { amx_Register_t fn = ((amx_Register_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Register]; return fn(amx, nativelist, number); } typedef int AMXAPI (*amx_Release_t)(AMX *amx, cell amx_addr); int AMXAPI amx_Release(AMX *amx, cell amx_addr) { amx_Release_t fn = ((amx_Release_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_Release]; return fn(amx, amx_addr); } typedef int AMXAPI (*amx_SetCallback_t)(AMX *amx, AMX_CALLBACK callback); int AMXAPI amx_SetCallback(AMX *amx, AMX_CALLBACK callback) { amx_SetCallback_t fn = ((amx_SetCallback_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_SetCallback]; return fn(amx, callback); } typedef int AMXAPI (*amx_SetDebugHook_t)(AMX *amx, AMX_DEBUG debug); int AMXAPI amx_SetDebugHook(AMX *amx, AMX_DEBUG debug) { amx_SetDebugHook_t fn = ((amx_SetDebugHook_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_SetDebugHook]; return fn(amx, debug); } typedef int AMXAPI (*amx_SetString_t)(cell *dest, const char *source, int pack, int use_wchar, size_t size); int AMXAPI amx_SetString(cell *dest, const char *source, int pack, int use_wchar, size_t size) { amx_SetString_t fn = ((amx_SetString_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_SetString]; return fn(dest, source, pack, use_wchar, size); } typedef int AMXAPI (*amx_SetUserData_t)(AMX *amx, long tag, void *ptr); int AMXAPI amx_SetUserData(AMX *amx, long tag, void *ptr) { amx_SetUserData_t fn = ((amx_SetUserData_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_SetUserData]; return fn(amx, tag, ptr); } typedef int AMXAPI (*amx_StrLen_t)(const cell *cstring, int *length); int AMXAPI amx_StrLen(const cell *cstring, int *length) { amx_StrLen_t fn = ((amx_StrLen_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_StrLen]; return fn(cstring, length); } typedef int AMXAPI (*amx_UTF8Check_t)(const char *string, int *length); int AMXAPI amx_UTF8Check(const char *string, int *length) { amx_UTF8Check_t fn = ((amx_UTF8Check_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_UTF8Check]; return fn(string, length); } typedef int AMXAPI (*amx_UTF8Get_t)(const char *string, const char **endptr, cell *value); int AMXAPI amx_UTF8Get(const char *string, const char **endptr, cell *value) { amx_UTF8Get_t fn = ((amx_UTF8Get_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_UTF8Get]; return fn(string, endptr, value); } typedef int AMXAPI (*amx_UTF8Len_t)(const cell *cstr, int *length); int AMXAPI amx_UTF8Len(const cell *cstr, int *length) { amx_UTF8Len_t fn = ((amx_UTF8Len_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_UTF8Len]; return fn(cstr, length); } typedef int AMXAPI (*amx_UTF8Put_t)(char *string, char **endptr, int maxchars, cell value); int AMXAPI amx_UTF8Put(char *string, char **endptr, int maxchars, cell value) { amx_UTF8Put_t fn = ((amx_UTF8Put_t*)pAMXFunctions)[PLUGIN_AMX_EXPORT_UTF8Put]; return fn(string, endptr, maxchars, value); } //---------------------------------------------------------- // EOF
[ [ [ 1, 340 ] ] ]
25189551d9fd0161ea395ccf140368492f1a3a92
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/geometries/scale_analysis_2/Scale_analysis_2.h
30e25ab580459c2ebef7c0f8101e992e4c9b8914
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,711
h
/* This source file is part of Mesecina, a software for visualization and studying of * the medial axis and related computational geometry structures. * More info: http://www.agg.ethz.ch/~miklosb/mesecina * Copyright Balint Miklos, Applied Geometry Group, ETH Zurich * * $Id: Union_of_balls_2.h 737 2009-05-16 15:40:46Z miklosb $ */ #ifndef MESECINA_SCALE_ANALYSIS_2_H #define MESECINA_SCALE_ANALYSIS_2_H #include <geometries/Geometry.h> #include <CGAL/Triangulation_face_base_with_info_2.h> #include <CGAL/Delaunay_triangulation_2.h> #include <list> #include <vector> #include <string> #ifdef MESECINA_GEOMETRY_LIBRARY #define MV_API __declspec( dllexport ) #else #define MV_API __declspec( dllimport ) #endif class MV_API Scale_analysis_2 : public Geometry { public: typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Triangulation_face_base_with_info_2<double, K> Fb; typedef CGAL::Triangulation_data_structure_2<CGAL::Triangulation_vertex_base_2<K>,Fb> Tds; typedef CGAL::Delaunay_triangulation_2<K, Tds> Delaunay_with_scale; typedef Delaunay_with_scale::Finite_faces_iterator Finite_faces_iterator; typedef K::Point_2 Point_2; typedef K::Circle_2 Circle_2; Scale_analysis_2(); virtual ~Scale_analysis_2(); //virtual Geometry* clone(); // methods to communicate with other geometries //virtual std::list<std::string> offer_structures(); //virtual void* give_structure(const std::string& name); virtual void receive_structure_changed(const std::string& name); // points communication with user interface //virtual void add_point(double x, double y); //virtual void add_points(std::list<QPointF>* points); //virtual std::list<QPointF>* get_points(); // ball communication with user interface //virtual void add_weighted_point(Point3D point); //virtual void add_weighted_points(std::list<Point3D>* points); //virtual std::list<Point3D>* get_weighted_points(); // directly handle file io //virtual void load_generic_file(const std::string&); //virtual void save_generic_file(const std::string&); // receive application settings changes // virtual void application_settings_changed(const QString&); // modification for evolutions // virtual void apply_modification(const std::string& ); Delaunay_with_scale* get_delaunay(); Delaunay_with_scale* get_sa_balls_delaunay(); Delaunay_with_scale* get_sa_ordered_balls_delaunay(); void invalidate_cache(); private: bool has_points; bool has_balls; bool has_ordered_balls; Delaunay_with_scale delaunay; }; #endif //MESECINA_SCALE_ANALYSIS_2_H
[ "balint.miklos@localhost" ]
[ [ [ 1, 83 ] ] ]
90c15f7f779e86c7cb9526d0275474ec1d0a911c
b9c9a4c5e7952e080a53c81a0781180a9bf80257
/src/net/NetServer.h
897513cde9cfc388e45e20a6b7a6b738c3eea78f
[]
no_license
kaelspencer/confero
296aa9cd87c0254a662be136a571ffb9675d9fe9
a41c71fe082017c316bc2f79e00c2b9e3a8ef7eb
refs/heads/master
2021-01-19T17:47:44.444616
2011-06-12T00:25:25
2011-06-12T00:25:25
1,777,702
0
1
null
null
null
null
UTF-8
C++
false
false
591
h
#ifndef NETSERVER_H #define NETSERVER_H #include <QTcpServer> #include <QTcpSocket> #include <QHostAddress> #include "NetClient.h" class NetManager; class NetClient; class NetServer : QObject { Q_OBJECT private: QTcpServer * m_server; quint16 m_port; const NetManager * m_parent; NetServer(); NetServer(const NetServer & rhs); NetServer & operator=(const NetServer & rhs); public: NetServer(quint16 port, const NetManager * parent); ~NetServer(); void Listen(); NetClient * OnConnection() const; }; #endif
[ "kael@euler" ]
[ [ [ 1, 33 ] ] ]
e13ae0872bf19195645dd51e4b7a58afd60aca9d
22b6d8a368ecfa96cb182437b7b391e408ba8730
/engine/include/qvCreateGameViewEventArgs.h
74c58627f9ad6db18e79cb26536936d9d89d7ab0
[ "MIT" ]
permissive
drr00t/quanticvortex
2d69a3e62d1850b8d3074ec97232e08c349e23c2
b780b0f547cf19bd48198dc43329588d023a9ad9
refs/heads/master
2021-01-22T22:16:50.370688
2010-12-18T12:06:33
2010-12-18T12:06:33
85,525,059
0
0
null
null
null
null
UTF-8
C++
false
false
3,396
h
/************************************************************************************************** //This code is part of QuanticVortex for latest information, see http://www.quanticvortex.org // //Copyright (c) 2009-2010 QuanticMinds Software Ltda. // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. **************************************************************************************************/ #ifndef __CREATE_GAME_VIEW_EVENT_ARGS_H_ #define __CREATE_GAME_VIEW_EVENT_ARGS_H_ #include "qvEventArgs.h" #include "qvEventTypes.h" #include "irrTypes.h" #include "irrString.h" namespace qv { namespace events { static const qv::events::ET_EVENT_TYPE ET_CREATE_GAME_VIEW("ET_CREATE_GAME_VIEW"); class _QUANTICVORTEX_API_ CreateGameViewEventArgs: public qv::events::EventArgs { public: CreateGameViewEventArgs() :qv::events::EventArgs(qv::events::ET_CREATE_GAME_VIEW.Hash) { } /// create a event argument with type virtual ~CreateGameViewEventArgs() { } qv::c8* getSceneFile() const; /// scene file to be displayed by human view void setSceneFile(qv::c8* sceneFile); qv::c8* getGameViewName() const; /// human view name void setGameViewName(qv::c8* gameViewName); /// set human view name qv::u32 getGameViewType() const; /// human view name void setGameViewType(qv::u32 gameViewHashType); /// set human view name private: qv::c8* mGameViewName; // human view name qv::u32 mGameViewHashType; // human view name qv::c8* mSceneFile; // scene file }; //inlines inline qv::c8* CreateGameViewEventArgs::getGameViewName() const { return mGameViewName; } inline void CreateGameViewEventArgs::setGameViewName( qv::c8* gameViewName) { mGameViewName = gameViewName; } inline qv::c8* CreateGameViewEventArgs::getSceneFile() const { return mSceneFile; } inline void CreateGameViewEventArgs::setSceneFile( qv::c8* sceneFile) { mSceneFile = sceneFile; } inline qv::u32 CreateGameViewEventArgs::getGameViewType() const { return mGameViewHashType; } inline void CreateGameViewEventArgs::setGameViewType( qv::u32 gameViewHashType) { mGameViewHashType = gameViewHashType; } } } #endif
[ [ [ 1, 120 ] ] ]
9ceafc7128754d3ab19a6dbac7d87b45960306af
0ce35229d1698224907e00f1fdfb34cfac5db1a2
/Emprunteur.h
d476780286547cea12730fd3ec2e604efdbecc81
[]
no_license
manudss/efreiloca
f7b1089b6ba74ff26e6320044f66f9401ebca21b
54e8c4af1aace11f35846e63880a893e412b3309
refs/heads/master
2020-06-05T17:34:02.234617
2007-06-04T19:12:15
2007-06-04T19:12:15
32,325,713
0
0
null
null
null
null
UTF-8
C++
false
false
1,453
h
#pragma once #include "stdafx.h" #include "Adresse.h" #include "Conducteur.h" #include "Date.h" #include <hash_map> class Emprunteur { public: Emprunteur(void); Emprunteur(std::string lenom, std::string leprenom, Date ladate_naissance, Adresse ladresseemprunteur, std::string lenumero_carte_identite="NULL"); public: ~Emprunteur(void); void setpermisauto(std::string le_num_permisauto, Date la_delivrance_permis_voiture, Date l_expiration_permis_voiture); void setpermismoto(std::string le_num_permismoto, Date la_delivrance_permis_moto, Date l_expiration_permis_moto); //setteur void set (int , std::string) ; void set_hash_TabLocation_insert(static int i_loc,Location* loc); //Getter: std::string get (int); Date getnaissance(); private: static int compt_id; int id; std::string nom; std::string prenom; Date date_naissance; std::string numero_carte_identite; Adresse adresseemprunteur; //num,rue, CP, ville bool permis_voiture; std::string numero_permisauto; Date delivrance_permis_voiture; Date expiration_permis_voiture; bool permis_moto; Date delivrance_permis_moto; Date expiration_permis_moto; std::string numero_permismoto; Conducteur* autre_conducteur[4]; stdext::hash_map< static int, Location* > TabLocation; stdext::hash_map< static int , Location* >:: iterator hash_iter; typedef pair <static int , Location* > Int_Pair; };
[ "manu.dss@65b228c9-682f-0410-abd1-c3b8cf015911", "pootoonet@65b228c9-682f-0410-abd1-c3b8cf015911" ]
[ [ [ 1, 1 ], [ 3, 12 ], [ 15, 17 ], [ 23, 23 ], [ 28, 31 ], [ 33, 36 ], [ 38, 38 ], [ 40, 44 ], [ 46, 46 ], [ 48, 50 ], [ 54, 54 ], [ 57, 57 ] ], [ [ 2, 2 ], [ 13, 14 ], [ 18, 22 ], [ 24, 27 ], [ 32, 32 ], [ 37, 37 ], [ 39, 39 ], [ 45, 45 ], [ 47, 47 ], [ 51, 53 ], [ 55, 56 ] ] ]
f681c08d857ec9538dd339688cc5835ee156551e
ea2ebb5e92b4391e9793c5a326d0a31758c2a0ec
/Bomberman/Bomberman/InputSystem.h
24b9a45d78a8f0c9be30557a65085758922db978
[]
no_license
weimingtom/bombman
d0f022541e9c550af7c6dbd26481771c94828460
d73ee4c680423a79826187013d343111a62f89b7
refs/heads/master
2021-01-10T01:36:39.712497
2011-05-01T07:03:16
2011-05-01T07:03:16
44,462,509
1
0
null
null
null
null
UTF-8
C++
false
false
1,026
h
#pragma once #include<Windows.h> #include"Keyboard.h" #include"Mouse.h" #define IS_USEKEYBOARD 1 #define IS_USEMOUSE 2 class InputSystem { public: InputSystem() { m_pKeyboard = NULL; m_pMouse = NULL;} ~InputSystem() {} bool Initialize(HWND hwnd, HINSTANCE appInstance, bool isExclusive, DWORD flags = 0); bool Shutdown(); void AcquireAll(); void UnacquireAll(); Keyboard* GetKeyboard() { return m_pKeyboard; } Mouse* GetMouse() { return m_pMouse; } bool Update(); bool KeyDown(char key) { return (m_pKeyboard && m_pKeyboard->KeyDown(key)); } bool KeyUp(char key) { return (m_pKeyboard && m_pKeyboard->KeyUp(key)); } bool ButtonDown(int button) { return (m_pMouse && m_pMouse->ButtonDown(button)); } bool ButtonUp(int button) { return (m_pMouse && m_pMouse->ButtonUp(button)); } void GetMouseMovement(int &dx, int &dy) { if (m_pMouse) m_pMouse->GetMovement(dx, dy); } private: Keyboard *m_pKeyboard; Mouse *m_pMouse; LPDIRECTINPUT8 m_pDI; };
[ "yvetterowe1116@d9104e88-05a6-3fce-0cda-3a6fd9c40cd8" ]
[ [ [ 1, 37 ] ] ]
a58f31906bf95ad9a894f00c929b58fb0b1594ef
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/multi_array/test/stl_interaction.cpp
4dcd0f844250e8daa35105ec5c740c9ef3324bbe
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,684
cpp
// Copyright 2002 The Trustees of Indiana University. // 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) // Boost.MultiArray Library // Authors: Ronald Garcia // Jeremy Siek // Andrew Lumsdaine // See http://www.boost.org/libs/multi_array for documentation. // // stl_interaction.cpp - Make sure multi_arrays work with STL containers. // #include "boost/test/minimal.hpp" #include "boost/multi_array.hpp" #include <algorithm> #include <vector> int test_main(int, char*[]) { using boost::extents; using boost::indices; typedef boost::multi_array_types::index_range range; typedef boost::multi_array<int,3> array3; typedef boost::multi_array<int,2> array2; typedef std::vector<array3> array3vec; int data[] = { 0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14,15, 16,17,18,19, 20,21,22,23 }; const int data_size = 24; int insert[] = { 99,98, 97,96, }; const int insert_size = 4; array3 myarray(extents[2][3][4]); myarray.assign(data,data+data_size); array3vec myvec(5,myarray); BOOST_TEST(myarray == myvec[1]); array3::array_view<2>::type myview = myarray[indices[1][range(0,2)][range(1,3)]]; array2 filler(extents[2][2]); filler.assign(insert,insert+insert_size); // Modify a portion of myarray through a view (myview) myview = filler; myvec.push_back(myarray); BOOST_TEST(myarray != myvec[1]); BOOST_TEST(myarray == myvec[5]); return boost::exit_success; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 72 ] ] ]
d41a0761c0126cf54dc5c64e55f6c9073e2ad666
ea2786bfb29ab1522074aa865524600f719b5d60
/MultimodalSpaceShooter/src/core/Game.h
3d694e85d9d7d015713ae90394867f382312662f
[]
no_license
jeremysingy/multimodal-space-shooter
90ffda254246d0e3a1e25558aae5a15fed39137f
ca6e28944cdda97285a2caf90e635a73c9e4e5cd
refs/heads/master
2021-01-19T08:52:52.393679
2011-04-12T08:37:03
2011-04-12T08:37:03
1,467,691
0
1
null
null
null
null
UTF-8
C++
false
false
1,491
h
#ifndef GAME_H #define GAME_H #include <SFML/Graphics.hpp> #include "core/AudioEngine.h" #include "input/EventManager.h" #include "input/MultimodalManager.h" #include "scenes/SceneManager.h" #include "entities/EntityManager.h" #include "loaders/ImageManager.h" #include "loaders/SoundManager.h" #include "loaders/LevelManager.h" ////////////////////////////////////////////////// /// Game skeleton that manages the game loop ////////////////////////////////////////////////// class Game { public: static Game& instance(); const sf::Vector2i& getScreenSize(); void run(); void quit(); private: Game(); sf::Vector2i myScreenSize; sf::RenderWindow myWindow; ImageManager myImageManager; SoundManager mySoundManager; AudioEngine myAudioEngine; EventManager myEventManager; MultimodalManager myMultimodalManager; EntityManager myEntityManager; SceneManager mySceneManager; // Declare managers as friends of the game main class friend ImageManager& imageManager(); friend SoundManager& soundManager(); friend AudioEngine& audioEngine(); friend EventManager& eventManager(); friend MultimodalManager& multimodalManager(); friend EntityManager& entityManager(); friend SceneManager& sceneManager(); }; #endif // GAME_H
[ [ [ 1, 12 ], [ 14, 56 ] ], [ [ 13, 13 ] ] ]
04d9a5648b7e810e8886b1bc7ae64eacad7eb2b6
f3f0f91a63558b803ec1f150165aa49e093808f9
/alignment/Alignment.h
06f26fa01568deeafdd9975f154f13874857c572
[]
no_license
kimmensjolander/bpg-sci-phy
5989c2030e6d83b304da2cf92e0e7f3eb327e3b4
fefecd3022383dc7bad55b050854e402600164ec
refs/heads/master
2020-03-29T12:26:33.422675
2010-10-18T21:46:41
2010-10-18T21:46:41
32,128,561
0
0
null
null
null
null
UTF-8
C++
false
false
1,017
h
#ifndef ALIGNMENT_H #define ALIGNMENT_H #include <vector> #include <string> #include <iomanip> #include "Sequence.h" #include "../general/Array2D.h" using namespace std; namespace sciphy { typedef std::vector<vector <int> > SeqArray; class Alignment { public: Alignment(); ~Alignment(); void addSequenceObj(Sequence* seq); void clearSeqArray(); vector<int>* getSequence(int index) {return &seqArray[index];} int residue(int i, int j) { return seqArray[i][j]; } void writeSequence(int i, ofstream* ptrToFile); string getName(int index); string getTitle(int index); int getLength() { return alnLength;} int getNumSeqs() { return numSeqs; } void calcConservation(); bool isConserved(int index); private: int numSeqs; int alnLength; SeqArray seqArray; vector<string> names; vector<string> titles; vector<bool> conservedFlags; //bitset conservedFlags; }; } #endif
[ "[email protected]@ed72bfb6-bbaa-95bc-2366-9432bd51d671" ]
[ [ [ 1, 51 ] ] ]
ff4f9277da7646aa52f629486a66d4eec90fda8d
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D10/D3D10EffectDepthStencilViewVariable.h
7002dd3e0ef3f73fa84eb440f979a5d0577eb811
[]
no_license
midnite8177/phever
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
45529e80ebf707e7299887165821ca360aa1907d
refs/heads/master
2020-05-16T21:59:24.201346
2010-07-12T23:51:53
2010-07-12T23:51:53
34,965,829
3
2
null
null
null
null
UTF-8
C++
false
false
2,968
h
//Copyright (c) Microsoft Corporation. All rights reserved. #pragma once #include "D3D10EffectVariable.h" namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct3D10 { using namespace System; using namespace System::Collections::Generic; ref class DepthStencilView; /// <summary> /// A depth-stencil-view-variable interface accesses a depth-stencil view. /// <para>(Also see DirectX SDK: ID3D10EffectDepthStencilViewVariable)</para> /// </summary> public ref class EffectDepthStencilViewVariable : public EffectVariable { public: /// <summary> /// Get a depth-stencil-view resource. /// <para>(Also see DirectX SDK: ID3D10EffectDepthStencilViewVariable::GetDepthStencil)</para> /// </summary> /// <returns>A depth-stencil-view object. See DepthStencilView Object.</returns> DepthStencilView^ GetDepthStencil(); /// <summary> /// Get a collection of depth-stencil-view resources. /// <para>(Also see DirectX SDK: ID3D10EffectDepthStencilViewVariable::GetDepthStencilArray)</para> /// </summary> /// <param name="offset">The zero-based array index to get the first object.</param> /// <param name="count">The number of elements requested in the collection.</param> /// <returns>A collection of depth-stencil-view interfaces.</returns> ReadOnlyCollection<DepthStencilView^>^ GetDepthStencilArray(UInt32 offset, UInt32 count); /// <summary> /// Set a depth-stencil-view resource. /// <para>(Also see DirectX SDK: ID3D10EffectDepthStencilViewVariable::SetDepthStencil)</para> /// </summary> /// <param name="resource">A depth-stencil-view object.</param> void SetDepthStencil(DepthStencilView^ resource); /// <summary> /// Set a collection of depth-stencil-view resources. /// <para>(Also see DirectX SDK: ID3D10EffectDepthStencilViewVariable::SetDepthStencilArray)</para> /// </summary> /// <param name="resources">A collection of depth-stencil-view interfaces.</param> /// <param name="offset">The zero-based index to set the first object in the collection.</param> void SetDepthStencilArray(IEnumerable<DepthStencilView^>^ resources, UInt32 offset); internal: EffectDepthStencilViewVariable() { } internal: EffectDepthStencilViewVariable(ID3D10EffectDepthStencilViewVariable* pNativeID3D10EffectDepthStencilViewVariable) : EffectVariable(pNativeID3D10EffectDepthStencilViewVariable) { } EffectDepthStencilViewVariable(ID3D10EffectDepthStencilViewVariable* pNativeID3D10EffectDepthStencilViewVariable, bool deletable): EffectVariable(pNativeID3D10EffectDepthStencilViewVariable, deletable) { } }; } } } }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 69 ] ] ]
fa0db04ebdeb53f863af9fe1b3410d03901f30a3
de98f880e307627d5ce93dcad1397bd4813751dd
/3libs/ut/include/OXWatchedDir.h
dfedef414ad55298dfc843a9c0382a5a54e6f0ad
[]
no_license
weimingtom/sls
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
refs/heads/master
2021-01-10T22:20:55.638757
2011-03-19T06:23:49
2011-03-19T06:23:49
44,464,621
2
0
null
null
null
null
UTF-8
C++
false
false
2,214
h
// ========================================================================== // Class Specification : COXWatchedDir // ========================================================================== // Header file : OXWatchedDir.h // Version: 9.3 // ////////////////////////////////////////////////////////////////////////// // Properties: // NO Abstract class (does not have any objects) // YES Derived from CObject // NO Is a CWnd. // NO Two stage creation (constructor & Create()) // NO Has a message map // NO Needs a resource // NO Persistent objects (saveable on disk) // NO Uses exceptions // ////////////////////////////////////////////////////////////////////////// // Desciption : // A helper class used to store information about the watched directories // Prerequisites (necessary conditions): ///////////////////////////////////////////////////////////////////////////// #ifndef __OXWATCHEDDIR_H__ #define __OXWATCHEDDIR_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "OXDllExt.h" class OX_CLASS_DECL COXWatchedDir : public CObject { friend class COXFileWatcher; // Data members ------------------------------------------------------------- public: protected: CString m_sPath; BOOL m_bWatchSubTree; DWORD m_dwWatchFilter; HWND m_hwndWindowToNotify; BOOL m_bPost; HANDLE m_hEvent; #if defined(_UNICODE) && (_WIN32_WINNT >= 0x400) // Extended info is supported BOOL m_bExtended; HANDLE m_hDirectory; LPVOID m_lpBuffer; DWORD m_nBufferLength; OVERLAPPED* m_pOverlapped; static DWORD dwBytesReturned; #endif // defined(_UNICODE) && (_WIN32_WINNT >= 0x400) protected: private: // Member functions --------------------------------------------------------- public: protected: COXWatchedDir(CString sPath, BOOL bWatchSubTree, DWORD dwWatchFilter, BOOL bExtended); virtual ~COXWatchedDir(); BOOL FindFirstHandle(HRESULT& rhrResult); BOOL FindNextHandle(HANDLE& hHandle); private: }; #endif // __OXWATCHEDDIR_H__ // ==========================================================================
[ [ [ 1, 84 ] ] ]
96cdd31dbb0f5b526be1f3516850fb263614b61f
155c4955c117f0a37bb9481cd1456b392d0e9a77
/Tessa/TessaInstructions/UnaryInstruction.h
9652c0e704af2b7b7f46af0a3f07abbd31fb8230
[]
no_license
zwetan/tessa
605720899aa2eb4207632700abe7e2ca157d19e6
940404b580054c47f3ced7cf8995794901cf0aaa
refs/heads/master
2021-01-19T19:54:00.236268
2011-08-31T00:18:24
2011-08-31T00:18:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
812
h
namespace TessaInstructions { class UnaryInstruction : public TessaInstruction { private: TessaUnaryOp opcode; TessaInstruction* operand; public: UnaryInstruction(TessaUnaryOp opcode, TessaInstruction* operand, TessaVM::BasicBlock* insertAtEnd); TessaInstruction* getOperand(); TessaUnaryOp getOpcode(); void setOperand(TessaInstruction* operand); void setOpcode(TessaUnaryOp op); bool isUnary(); void print(); void visit(TessaVisitorInterface* tessaVisitor); bool producesValue(); static TessaUnaryOp getUnaryOpcodeFromAbcOpcode(AbcOpcode opcode); UnaryInstruction* clone(MMgc::GC *gc, MMgc::GCHashtable* originalToCloneMap, TessaVM::BasicBlock* insertCloneAtEnd); List<TessaValue*, LIST_GCObjects>* getOperands(MMgc::GC* gc); }; }
[ [ [ 1, 22 ] ] ]
688dbbe22954b32e678d10e770d0623f4d27c697
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/gui/app/Settings_list_widget.cpp
af6673a837aef682caa4330fe19c7c80b65043cc
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,221
cpp
/* This source file is part of Mesecina, a software for visualization and studying of * the medial axis and related computational geometry structures. * More info: http://www.agg.ethz.ch/~miklosb/mesecina * Copyright Balint Miklos, Applied Geometry Group, ETH Zurich * * $Id: Settings_list_widget.cpp 737 2009-05-16 15:40:46Z miklosb $ */ #include <gui/app/Settings_list_widget.h> #include <QtGui/QColorGroup> #include <QtGui/QFileDialog> #include <QtCore//QSettings> #include <QtGui/QVBoxLayout> #include <QtGui/QHBoxLayout> #include <QtCore/QAbstractTableModel> #include <QtGui/QHeaderView> #include <QtGui/QPushButton> #include <QtGui/QLabel> #include <QtGui/QItemEditorFactory> #include <QtGui/QItemDelegate> #include <QtGui/QStandardItemEditorCreator> #include <gui/app/QSpinBoxEditor.h> #include <gui/app/Popup_animate_application_setting.h> #include <iostream> Settings_list_widget::Settings_list_widget(QWidget* parent, QString name): QFrame(parent) { setFrameStyle(QFrame::Panel | QFrame::Sunken); QVBoxLayout *layout = new QVBoxLayout(this); layout->setSpacing(2); layout->setMargin(0); QWidget* spacer = new QWidget(this); #ifdef Q_WS_WIN spacer->setMinimumWidth(2); spacer->setMaximumWidth(2); #else spacer->setMinimumWidth(3); spacer->setMaximumWidth(3); #endif //Q_WS_WIN layout->addWidget(spacer); QHBoxLayout *filter_layout = new QHBoxLayout(); filter_layout->setSpacing(2); filter_layout->setMargin(0); QWidget* spacer2 = new QWidget(this); spacer2->setMinimumWidth(2); spacer2->setMaximumWidth(2); filter_layout->addWidget(spacer2); QPushButton* filter_save_button = new QPushButton(); filter_save_button->setText("S"); filter_save_button->setToolTip("Save *filtered* (the ones currently displayed) settings to a file"); filter_save_button->setFlat(true); // filter_save_button->setFrameStyle(QFrame::Panel | QFrame::Sunken); #ifdef Q_WS_WIN filter_save_button->setMaximumWidth(20); #else filter_save_button->setMaximumWidth(30); #endif //Q_WS_WIN filter_layout->addWidget(filter_save_button); QPushButton* filter_load_button = new QPushButton(); filter_load_button->setText("L"); filter_load_button->setFlat(true); filter_load_button->setToolTip("Load some settings from a file"); // filter_load_button->setFrameStyle(QFrame::Panel | QFrame::Sunken); #ifdef Q_WS_WIN filter_load_button->setMaximumWidth(20); #else filter_load_button->setMaximumWidth(30); #endif //Q_WS_WIN filter_layout->addWidget(filter_load_button); filter_box = new QLineEdit(this); // filter_box->setFrameStyle(QFrame::Panel | QFrame::Sunken); filter_layout->addWidget(filter_box); QPushButton* filter_delete_button = new QPushButton(); filter_delete_button->setText("X"); filter_delete_button->setFlat(true); // filter_delete_button->setFrameStyle(QFrame::Panel | QFrame::Sunken); #ifdef Q_WS_WIN filter_delete_button->setMaximumWidth(20); #else filter_delete_button->setMaximumWidth(30); #endif //Q_WS_WIN filter_layout->addWidget(filter_delete_button); table_view = new Settings_table_view(); #ifdef Q_WS_WIN QFont bigger_font = table_view->font(); bigger_font.setPointSize(font().pointSize()+2); table_view->setFont(bigger_font); #endif //Q_WS_WIN table_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); table_model = new Settings_table_model(); connect(table_view->animate_popup, SIGNAL(application_variable_changed(const QString&)), this,SLOT(settings_changed(const QString&))); connect(table_model, SIGNAL(application_settings_changed(const QString&)), this, SLOT(settings_changed(const QString&))); table_view->setModel(table_model); table_view->setSelectionMode(QAbstractItemView::NoSelection); table_view->verticalHeader()->hide(); table_view->horizontalHeader()->hide(); table_view->setShowGrid(false); table_view->setRowHeight(0,3); table_view->setItemDelegate(new QSpinBoxEditor(table_model)); for (int i=1; i<150; i++) table_view->setRowHeight(i,18); layout->addLayout(filter_layout); layout->addWidget(table_view); setLayout(layout); connect(filter_delete_button, SIGNAL(clicked(bool)), this, SLOT(delete_filter_text(bool))); connect(filter_load_button, SIGNAL(clicked(bool)), this, SLOT(load_button(bool))); connect(filter_save_button, SIGNAL(clicked(bool)), this, SLOT(save_button(bool))); connect(filter_box, SIGNAL(textChanged(const QString&)), table_model, SLOT(filter_apply(const QString&))); connect(filter_box, SIGNAL(textChanged(const QString&)), this, SLOT(filter_changed(const QString&))); filter_box->setFocus(); } void Settings_list_widget::clear() { // table_model->clear(); filter_box->setFocus(); } void Settings_list_widget::settings_changed(const QString& settings_name) { emit application_settings_changed(settings_name); } void Settings_list_widget::delete_filter_text(bool) { filter_box->setText(""); } void Settings_list_widget::load_button(bool) { QSettings settings; QString file_name = QFileDialog::getOpenFileName( this, "Choose a filename to load settings", settings.value("last-data-directory",QString()).toString(), "Settings (*.ini)"); if (file_name=="") return; if (!file_name.endsWith(".ini")) file_name += ".ini"; QString save_directory = file_name; save_directory.truncate(file_name.lastIndexOf('/')); settings.setValue("last-data-directory",save_directory); Settings_table_model::load_current_settings(file_name); process_filter(); } void Settings_list_widget::load_settings_and_emit_change(const QString& file_name) { table_model->load_settings_and_emit_change(file_name); } void Settings_list_widget::save_button(bool) { QSettings settings; QString file_name = QFileDialog::getSaveFileName( this, "Choose a filename to save settings", settings.value("last-data-directory",QString()).toString(), "Settings (*.ini)"); if (file_name=="") return; if (!file_name.endsWith(".ini")) file_name += ".ini"; QString save_directory = file_name; save_directory.truncate(file_name.lastIndexOf('/')); settings.setValue("last-data-directory",save_directory); table_model->save_current_settings(file_name); } void Settings_list_widget::filter_changed(const QString& text) { table_model->filter_apply(text); table_view->setRowHeight(0,3); for (int i=1; i<150; i++) table_view->setRowHeight(i,18); } void Settings_list_widget::resizeEvent(QResizeEvent * e) { QFrame::resizeEvent(e); int width = e->size().width()-20; int number_width = 70; if (number_width < width / 4) number_width = width / 4; int name_width = width - number_width; table_view->horizontalHeader()->resizeSection ( 0, name_width > 0 ? name_width : 0 ); table_view->horizontalHeader()->resizeSection ( 1, number_width ); } void Settings_list_widget::process_filter() { table_model->process_filter(); table_view->setRowHeight(0,3); for (int i=1; i<150; i++) table_view->setRowHeight(i,18); }
[ "balint.miklos@localhost" ]
[ [ [ 1, 210 ] ] ]
e4bf88eb6e2ce64e7983764f94605a5cbdb5657a
741b36f4ddf392c4459d777930bc55b966c2111a
/incubator/dangerman/globalWrap.h
83a9289518eb931f63f4ef22b904b3b7e028b515
[]
no_license
BackupTheBerlios/lwpp-svn
d2e905641f60a7c9ca296d29169c70762f5a9281
fd6f80cbba14209d4ca639f291b1a28a0ed5404d
refs/heads/master
2021-01-17T17:01:31.802187
2005-10-16T22:12:52
2005-10-16T22:12:52
40,805,554
0
0
null
null
null
null
UTF-8
C++
false
false
18,042
h
#ifndef LWPP_GLOBALWRAP_H #define LWPP_GLOBALWRAP_H //============================================================================= /// /// \File globalWrap.h /// Declaration and definition of LWPPGlobal - the base class for /// LightWrap's globalTypes. /// /// Definition of a globalType: Any value returned by a call to /// LightWave's global function. /// /// Each globalType is derived from LWPPGlobal. /// /// Because SystemID, ProductInfo and LocaleInfo are captured in /// LWPPGlobal, there is no need to create these as separate globalTypes. /// /// CONTENTS: /// ~~~~~~~~ /// LWPPGlobal - the mother of all globalTypes /// /// LWPPFileRequester - contains all the functionality of LW's fileRequest /// globals and the utility functions that they use. /// /// LWPPColorActivate - an encapsulation of LWColorActivate. /// /// LWPPMessageFuncs - an encapsulation of LWMessageFuncs. /// /// \Author CWCunningham /// //============================================================================= #include <lwserver.h> // LW GlobalFunc #include <lwhost.h> // LW ProductInfo, SystemID, and LocaleInfo #include <lwtypes.h> // NULL /// The namespace for all LightWrap++ code. // namespace lwpp { //***************************************************************************** /// /// \class LWPPGlobal - This class must be constructed in your activate function /// in order for any globals derived from this class to work. It can be /// constructed as an automatic variable, or on the heap. Because the /// working values are static, they survive destruction /// //***************************************************************************** class LWPPGlobal { protected: //========================================================================= /// I made storage for these values static because it seems /// wasteful and useless for each global to have its own /// identical copy of these values that don't change during /// a session. Once the constructor is called, these values /// will live on, even after destruction. // /* @{ */ static GlobalFunc *GLOBAL; static unsigned long SystemID; static unsigned long ProductInfo; static unsigned long LocaleInfo; /* @} */ /// Other variables we capture /* @{ */ long pluginVersion; /// Should we capture this here, or does it rightly /// belong in the plugin wrapper? // // void *local; /* @} */ public: //========================================================================= /// Constructor, where all the magic happens. // LWPPGlobal(GlobalFunc* global, long version); //========================================================================= /// Do nothing default constructor. It's required for constructing derived /// objects, but if you haven't called the other constructor, your derived /// objects are dead in the water. // LWPPGlobal(){} //========================================================================= /// Destructor - does nothing. // virtual ~LWPPGlobal() {/* Nothing to do here */} //========================================================================= /// Copy constructor - Prevent explicit copies. /// You will get a linker error if you call this. // LWPPGlobal(LWPPGlobal&); //========================================================================= /// Assignment operator - Prevent explicit copies /// You will get a linker error if you call this. // LWPPGlobal & operator =(LWPPGlobal&); //========================================================================= /// isValid - Lets you know if a global call will work or fail. /// /// \todo - Check to see if any of the "info" values could /// be 0 under valid circumstances. /// virtual bool isValid() { return (GLOBAL != NULL && SystemID && ProductInfo && LocaleInfo); } //========================================================================= /// operator ! - A synonym for checking isValid() /// like this: /// LWPPGlobal myGlobal(global); /// if (!myGlobal) /// { /// return AFUNC_BADGLOBAL; /// } /// /// Be aware that if you construct one of these on the heap /// you'll have to change the syntax accordingly. I'm thinking /// "if (! *myGlobal)", but I haven't tested this. Otherwise /// you're just checking for a non-NULL address, and /// not actually calling isValid(). /// /// Another alternative for heap based construction would be: /// if (myGlobal->operator !()) /// but from that, you see the following is cleaner syntax: /// if (! myGlobal->isValid()) /// Tested OK // bool operator !() { // Because isValid() is a virtual call, you can use // "if (!anyGlobal) {}" with any derived type. // return !isValid(); } //========================================================================= /// application - possible return values are /// - LWSYS_LAYOUT /// - LWSYS_MODELER /// - LWSYS_SCREAMERNET /// Tested OK // unsigned long application() { // return (SystemID & LWSYS_TYPEBITS) >> 28; // /// Because LWSYS_ constants are before the value is shifted right /// I'm returning the value unshifted. User friendly functions /// should be added. // return SystemID & LWSYS_TYPEBITS; } //========================================================================= /// dongleID - returns the dongle number. If the application /// is screamernet, returns the node ID. /// Tested OK // unsigned long dongleID() { return SystemID & LWSYS_SERIALBITS; } //========================================================================= /// product - possible return values are /// - LWINF_PRODLWAV (1) /// - LWINF_INSP3D (2) /// - LWINF_PRODOTHER (4) /// Tested OK // unsigned long product() { return ProductInfo & LWINF_PRODUCT; } //========================================================================= /// build - returns the Build number of the product. /// /// Known build numbers - Special Thanks to Lynx3D for collecting these /// Windows & Mac /// /// 6.0: 429 /// 6.0b: 446 /// /// 6.5: 471, 484 (?) /// 6.5b: 508 /// /// 7.0: 537 /// 7.0b: 543 /// /// 7.5: 572 /// 7.5b: 582 /// 7.5c: 584 /// 7.5d: 598 /// /// 8.0: 690 /// 8.0.1: 734 /// /// If you know any build numbers for any platform which are not /// listed here, please report them to LightWrap++ /// Tested OK /// unsigned long build() { /// Using the macro defined in "lwhost.h" // return LWINF_GETBUILD(ProductInfo); } //========================================================================= /// revisionMinor - returns the minor revision number. /// Tested OK // unsigned long revisionMinor() { /// Using the macro defined in "lwhost.h" // return LWINF_GETMINOR(ProductInfo); } //========================================================================= /// revisionMajor - returns the major revision number. /// Tested OK // unsigned long revisionMajor() { /// Using the macro defined in "lwhost.h" // return LWINF_GETMAJOR(ProductInfo); } //========================================================================= /// version - returns the version number passed to the constructor. /// /// I would like to convert this to an unsigned long, but existing code /// may depend on it's original type. /// /// Tested OK // long version() { /// The version variable passed to the activate function. // return pluginVersion; } //========================================================================= /// revision - returns a user friendly string. // const char *revision(); //========================================================================= /// locale - returns the language ID. // unsigned long locale() { return LocaleInfo & LWLOC_LANGID; } }; // End - class LWPPGlobal //***************************************************** // /// \class LWPPFileRequester - /// encapsulates the following globals: /// LWFileReqFunc /// LWFileActivateFunc /// LWFileTypeFunc /// LWDirInfoFunc /// /// \todo - Create easy to use calls like /// "loadAnimation(...)", "saveObject(...)" // //***************************************************** class LWPPFileRequester : public LWPPGlobal { /// Pointers to the functions returned from GLOBAL // /* @{ */ LWFileReqFunc *fileRequestFunc; LWFileActivateFunc *fileActivateFunc; LWFileTypeFunc *fileTypeFunc; LWDirInfoFunc *dirInfoFunc; /* @} */ public: //========================================================================= /// Constructor, make sure the GLOBAL func is good, /// then acquire each of the fileRequest functions. // LWPPFileRequester() { fileRequestFunc = NULL; fileActivateFunc = NULL; fileTypeFunc = NULL; dirInfoFunc = NULL; if (GLOBAL != NULL) { fileRequestFunc = (LWFileReqFunc*)GLOBAL(LWFILEREQFUNC_GLOBAL, GFUSE_ACQUIRE); fileActivateFunc = (LWFileActivateFunc*)GLOBAL(LWFILEACTIVATEFUNC_GLOBAL, GFUSE_ACQUIRE); fileTypeFunc = (LWFileTypeFunc*)GLOBAL(LWFILETYPEFUNC_GLOBAL, GFUSE_ACQUIRE); dirInfoFunc = (LWDirInfoFunc*)GLOBAL(LWDIRINFOFUNC_GLOBAL, GFUSE_ACQUIRE); } } //========================================================================= /// Destructor, if any of the fileRequest functions is non-NULL, /// then we know that GLOBAL must be good, so just release the /// non-NULL functions. // virtual ~LWPPFileRequester() { if (fileRequestFunc) GLOBAL(LWFILEREQFUNC_GLOBAL, GFUSE_RELEASE); if (fileActivateFunc) (LWFILEACTIVATEFUNC_GLOBAL, GFUSE_RELEASE); if (fileTypeFunc) GLOBAL(LWFILETYPEFUNC_GLOBAL, GFUSE_RELEASE); if (dirInfoFunc) GLOBAL(LWDIRINFOFUNC_GLOBAL, GFUSE_RELEASE); } //========================================================================= /// isValid - verifies that all fileRequest functions /// were properly initialized. It seems a little extreme that if /// one fails, they're all invalid, but they're typically used /// together. /// /// They could be broken up into separate globalTypes. // bool isValid() { return (fileRequestFunc && fileActivateFunc && fileTypeFunc && dirInfoFunc); } //========================================================================= /// LW's basic "File Request" global. /// friendly overrides will be added later. // int fileRequest(const char *title, char *filter, char *path, char *returnedFileName, int buflen) { // typedef int LWFileReqFunc (const char *hail, char *name, // char *path, char *fullName, int buflen); if (fileRequestFunc) return fileRequestFunc(title, filter, path, returnedFileName, buflen); return AFUNC_BADGLOBAL; } //========================================================================= /// LW's basic "File Request 2" global. /// user friendly overrides will be added later. // int fileRequest2(int version, LWFileReqLocal *requestLocal) { // int LWFileActivateFunc (int version, LWFileReqLocal *requestLocal); if (fileActivateFunc) return fileActivateFunc(version, requestLocal); return AFUNC_BADGLOBAL; } //========================================================================= /// LW's basic dirInfoFunc, seems user friendly enough. // const char *directoryInfo(const char *directoryType) { // const char * LWDirInfoFunc (const char *directoryType); if (dirInfoFunc) return dirInfoFunc(directoryType); return NULL; } //========================================================================= /// LW's basic fileTypeFunc, returns a filter for use in fileRequests. // const char *fileType(const char *type) { // const char * LWFileTypeFunc (const char *type); if (fileTypeFunc) return fileTypeFunc(type); return NULL; } /// \todo Add user friendly file requesters }; // End - class LWPPFileRequester. //***************************************************** // /// \class - LWPPColorActivate, encapsulates /// Lightwave's LWColorActivateFunc. /// /// \todo Couldn't there be a user friendly version? // //***************************************************** class LWPPColorActivate : public LWPPGlobal { LWColorActivateFunc *colorActivateFunc; public: //========================================================================= /// Acquire on construction // LWPPColorActivate() : colorActivateFunc(NULL) { if (GLOBAL) { colorActivateFunc = (LWColorActivateFunc*) GLOBAL(LWCOLORACTIVATEFUNC_GLOBAL, GFUSE_ACQUIRE); } } //========================================================================= /// Release on destruction // virtual ~LWPPColorActivate() { if (colorActivateFunc) GLOBAL(LWCOLORACTIVATEFUNC_GLOBAL, GFUSE_RELEASE ); } //========================================================================= /// isValid() - Basic test for non-dangling pointer // bool isValid() { return (colorActivateFunc != NULL); } //========================================================================= /// Since there is only one function associated with this global /// it seemed a nicety to simplify the syntax to: /// "LWPPColorActivate colorActivate;" /// "colorActivate(...);" int operator ()(int version, LWColorPickLocal *colorPickLocal) { if (isValid()) { return colorActivateFunc(version, colorPickLocal); } else { return AFUNC_BADGLOBAL; } } }; //***************************************************** // /// \class - LWPPMessageFuncs /// /// Encapsulates the LWMessageFuncs global type /// The basic syntax is preserved, but one return /// value has been added to the interactive /// functions: -1 is returned in case of a bad /// global since AFUNC_BADGLOBAL would duplicate /// a normal return value. // //***************************************************** class LWPPMessageFuncs : public LWPPGlobal { /// The globalType pointer. // LWMessageFuncs *messageFuncs; public: //========================================================================= /// Acquire on construction. /// Tested OK // LWPPMessageFuncs() : messageFuncs(NULL) { if (GLOBAL) { messageFuncs = (LWMessageFuncs*) GLOBAL(LWMESSAGEFUNCS_GLOBAL, GFUSE_ACQUIRE); } } //========================================================================= /// Release on destruction. // virtual ~LWPPMessageFuncs() { if (messageFuncs) GLOBAL(LWMESSAGEFUNCS_GLOBAL, GFUSE_RELEASE); } //========================================================================= /// isValid() - Basic test for non-dangling pointer /// Tested OK // bool isValid() { return (messageFuncs != NULL); } //========================================================================= /// Basic call to info(...) /// Tested OK // void info(const char *firstLine, const char *secondLine = NULL) { if (isValid()) messageFuncs->info(firstLine, secondLine); } //========================================================================= /// Basic call to error(...) /// Tested OK // void error(const char *firstLine, const char *secondLine = NULL) { if (isValid()) messageFuncs->error(firstLine, secondLine); } //========================================================================= /// Basic call to warning(...) /// Tested OK // void warning(const char *firstLine, const char *secondLine = NULL) { if (isValid()) messageFuncs->warning(firstLine, secondLine); } //========================================================================= /// okCancel() - Returning AFUNC_BADGLOBAL would appear to be /// a user response, so in case of a bad global, this function returns -1 // int okCancel(const char *title, const char *firstLine, const char *secondLine = NULL) { if (isValid()) { return messageFuncs->okCancel(title != NULL ? title : "OK ?", firstLine, secondLine); } else return -1; } //========================================================================= /// yesNo() - Returning AFUNC_BADGLOBAL would appear to be /// a user response, so in case of a bad global, this function returns -1 /// Tested OK // int yesNo(const char *title, const char *firstLine, const char *secondLine = NULL) { if (isValid()) { messageFuncs->yesNo(title != NULL ? title : "OK ?", firstLine, secondLine); } else return -1; } //========================================================================= /// yesNoCan() - Returning AFUNC_BADGLOBAL would appear to be /// a user response, so in case of a bad global, this function returns -1 // int yesNoCan(const char *title, const char *firstLine, const char *secondLine = NULL) { if (isValid()) { messageFuncs->yesNoCan(title != NULL ? title : "OK ?", firstLine, secondLine); } else return -1; } //========================================================================= /// yesNoAll() - Returning AFUNC_BADGLOBAL would appear to be /// a user response, so in case of a bad global, this function returns -1 // int yesNoAll(const char *title, const char *firstLine, const char *secondLine = NULL) { if (isValid()) { messageFuncs->yesNoAll(title != NULL ? title : "OK ?", firstLine, secondLine); } else return -1; } }; } // End - namespace lwpp #endif // LWPP_GLOBALWRAP
[ "dangerman@dac1304f-7ce9-0310-a59f-f2d444f72a61" ]
[ [ [ 1, 614 ] ] ]
064bdd343421bda6d4941d52911f9208dbb94c20
96fefafdfbb413a56e0a2444fcc1a7056afef757
/MQ2AutoSize/ISXEQAutoSize.cpp
bd4787645b1d824726e6832a7839b7ffb3ee68e0
[]
no_license
kevrgithub/peqtgc-mq2-sod
ffc105aedbfef16060769bb7a6fa6609d775b1fa
d0b7ec010bc64c3f0ac9dc32129a62277b8d42c0
refs/heads/master
2021-01-18T18:57:16.627137
2011-03-06T13:05:41
2011-03-06T13:05:41
32,849,784
1
3
null
null
null
null
UTF-8
C++
false
false
12,066
cpp
// // ISXEQAutoSize // #pragma warning(disable:4996) #include "../ISXEQClient.h" #include "ISXEQAutoSize.h" // The mandatory pre-setup function. Our name is "ISXEQAutoSize", and the class is ISXEQAutoSize. // This sets up a "ModulePath" variable which contains the path to this module in case we want it, // and a "PluginLog" variable, which contains the path and filename of what we should use for our // debug logging if we need it. It also sets up a variable "pExtension" which is the pointer to // our instanced class. ISXPreSetup("ISXEQAutoSize",ISXEQAutoSize); // Basic LavishScript datatypes, these get retrieved on startup by our initialize function, so we can // use them in our Top-Level Objects or custom datatypes LSType *pStringType=0; LSType *pIntType=0; LSType *pBoolType=0; LSType *pFloatType=0; LSType *pTimeType=0; LSType *pByteType=0; ISInterface *pISInterface=0; HISXSERVICE hPulseService=0; HISXSERVICE hMemoryService=0; HISXSERVICE hServicesService=0; HISXSERVICE hEQChatService=0; HISXSERVICE hEQUIService=0; HISXSERVICE hEQGamestateService=0; HISXSERVICE hEQSpawnService=0; HISXSERVICE hEQZoneService=0; unsigned int ISXEQAutoSizeXML=0; // Forward declarations of callbacks void __cdecl PulseService(bool Broadcast, unsigned int MSG, void *lpData); void __cdecl MemoryService(bool Broadcast, unsigned int MSG, void *lpData); void __cdecl ServicesService(bool Broadcast, unsigned int MSG, void *lpData); // Initialize is called by Inner Space when the extension should initialize. bool ISXEQAutoSize::Initialize(ISInterface *p_ISInterface) { pISInterface=p_ISInterface; // retrieve basic ISData types pStringType=pISInterface->FindLSType("string"); pIntType=pISInterface->FindLSType("int"); pBoolType=pISInterface->FindLSType("bool"); pFloatType=pISInterface->FindLSType("float"); pTimeType=pISInterface->FindLSType("time"); pByteType=pISInterface->FindLSType("byte"); pISInterface->OpenSettings(XMLFileName); LoadSettings(); ConnectServices(); RegisterCommands(); RegisterAliases(); RegisterDataTypes(); RegisterTopLevelObjects(); RegisterServices(); WriteChatf("ISXEQAutoSize Loaded"); return true; } // shutdown sequence void ISXEQAutoSize::Shutdown() { // save settings, if you changed them and want to save them now. You should normally save // changes immediately. //pISInterface->ExportSet(ISXEQAutoSizeXML,XMLFileName); pISInterface->UnloadSet(ISXEQAutoSizeXML); DisconnectServices(); UnRegisterServices(); UnRegisterTopLevelObjects(); UnRegisterDataTypes(); UnRegisterAliases(); UnRegisterCommands(); } void ISXEQAutoSize::ConnectServices() { // connect to any services. Here we connect to "Pulse" which receives a // message every frame (after the frame is displayed) and "Memory" which // wraps "detours" and memory modifications hPulseService=pISInterface->ConnectService(this,"Pulse",PulseService); hMemoryService=pISInterface->ConnectService(this,"Memory",MemoryService); hServicesService=pISInterface->ConnectService(this,"Services",ServicesService); } void ISXEQAutoSize::RegisterCommands() { // add any commands // pISInterface->AddCommand("MyCommand",MyCommand,true,false); } void ISXEQAutoSize::RegisterAliases() { // add any aliases } void ISXEQAutoSize::RegisterDataTypes() { // add any datatypes // pMyType = new MyType; // pISInterface->AddLSType(*pMyType); } void ISXEQAutoSize::RegisterTopLevelObjects() { // add any Top-Level Objects // pISInterface->AddTopLevelObject("MapSpawn",tloMapSpawn); } void ISXEQAutoSize::RegisterServices() { // register any services. Here we demonstrate a service that does not use a // callback // set up a 1-way service (broadcast only) // hISXEQAutoSizeService=pISInterface->RegisterService(this,"ISXEQAutoSize Service",0); // broadcast a message, which is worthless at this point because nobody will receive it // (nobody has had a chance to connect) // pISInterface->ServiceBroadcast(this,hISXEQAutoSizeService,ISXSERVICE_MSG+1,0); } void ISXEQAutoSize::DisconnectServices() { // gracefully disconnect from services if (hPulseService) pISInterface->DisconnectService(this,hPulseService); if (hMemoryService) { pISInterface->DisconnectService(this,hMemoryService); // memory modifications are automatically undone when disconnecting // also, since this service accepts messages from clients we should reset our handle to // 0 to make sure we dont try to continue using it hMemoryService=0; } if (hServicesService) pISInterface->DisconnectService(this,hServicesService); } void ISXEQAutoSize::UnRegisterCommands() { // remove commands // pISInterface->RemoveCommand("MyCommand"); } void ISXEQAutoSize::UnRegisterAliases() { // remove aliases } void ISXEQAutoSize::UnRegisterDataTypes() { // remove data types //if (pMyType) //{ // pISInterface->RemoveLSType(*pMyType); // delete pMyType; //} } void ISXEQAutoSize::UnRegisterTopLevelObjects() { // remove Top-Level Objects // pISInterface->RemoveTopLevelObject("MapSpawn"); } void ISXEQAutoSize::UnRegisterServices() { // shutdown our own services // if (hISXEQAutoSizeService) // pISInterface->ShutdownService(this,hISXEQAutoSizeService); } void ISXEQAutoSize::LoadSettings() { bool bChanged=false; // open the settings file, and store the ID number in ISXEQAutoSizeXML ISXEQAutoSizeXML=pISInterface->OpenSettings(XMLFileName); // This ID is used to refer to the base set of the loaded settings /* Here is an example settings hierarchy: base set ..settings .."General" set .."Characters" set ...."Server A" set ......"Character A" set ........settings ......"Character B" set ........settings ...."Server B" set ......"Character A" set ........settings ...."Server C" set ......"Character A" set ........settings ......"Character B" set ........settings ......"Character C" set ........settings As you can see, there can be any number of nested sets, which can contain sets, settings, and comments. Any set can be referred to by its ID. The base set is stored in ISXEQAutoSizeXML. Note that the settings are NOT "xml" after loading them, they are simply settings stored in memory! */ // Get General set ID, which can be a child of the base set if (unsigned int GeneralGUID=pISInterface->FindSet(ISXEQAutoSizeXML,"General")) { // retrieve a text setting from the General set char Text[512]; if (pISInterface->GetSetting(GeneralGUID,"Name of setting",Text,512)) { // success } unsigned int IntSetting; if (pISInterface->GetSetting(GeneralGUID,"Name of int setting",IntSetting)) { // success } } /* Deeper sets and settings are accessed in exactly the same way. If a sub-set of General was to be used, accessing it would work like so: if (unsigned int SubSetGUID=pISInterface->FindSet(GeneralGUID,"Sub-set name")) { // got the sub-set } */ // save settings if we changed them if (bChanged) pISInterface->ExportSet(ISXEQAutoSizeXML,XMLFileName); // Note: ExportSet can save ANY set and its settings, sets, and comments as ANY filename. The "General" set // could be stored as "General.XML" simply by doing pISInterface->ExportSet(GeneralGUID,"General.XML"); } void __cdecl PulseService(bool Broadcast, unsigned int MSG, void *lpData) { if (MSG==PULSE_PULSE) { // Same as OnPulse } } void __cdecl MemoryService(bool Broadcast, unsigned int MSG, void *lpData) { // no messages are currently associated with this service (other than // system messages such as client disconnect), so do nothing. } void __cdecl EQUIService(bool Broadcast, unsigned int MSG, void *lpData) { switch(MSG) { case UISERVICE_CLEANUP: // same as OnCleanUI break; case UISERVICE_RELOAD: // same as OnReloadUI break; } } void __cdecl EQGamestateService(bool Broadcast, unsigned int MSG, void *lpData) { #define GameState ((unsigned int)lpData) if (MSG==GAMESTATESERVICE_CHANGED) { // same as SetGameState } #undef GameState } void __cdecl EQSpawnService(bool Broadcast, unsigned int MSG, void *lpData) { switch(MSG) { #define pSpawn ((PSPAWNINFO)lpData) case SPAWNSERVICE_ADDSPAWN: // same as OnAddSpawn break; case SPAWNSERVICE_REMOVESPAWN: // same as OnRemoveSpawn break; #undef pSpawn #define pGroundItem ((PGROUNDITEM)lpData) case SPAWNSERVICE_ADDITEM: // same as OnAddGroundItem break; case SPAWNSERVICE_REMOVEITEM: // same as OnRemoveGroundItem break; #undef pGroundItem } } void __cdecl EQZoneService(bool Broadcast, unsigned int MSG, void *lpData) { switch(MSG) { case ZONESERVICE_BEGINZONE: // same as OnBeginZone break; case ZONESERVICE_ENDZONE: // same as OnEndZone break; case ZONESERVICE_ZONED: // same as OnZoned break; } } void __cdecl EQChatService(bool Broadcast, unsigned int MSG, void *lpData) { #define pChat ((_EQChat*)lpData) switch(MSG) { case CHATSERVICE_OUTGOING: // same as OnWriteChatColor break; case CHATSERVICE_INCOMING: // same as OnIncomingChat break; } #undef pChat } // This uses the Services service to connect to ISXEQ services void __cdecl ServicesService(bool Broadcast, unsigned int MSG, void *lpData) { #define Name ((char*)lpData) switch(MSG) { case SERVICES_ADDED: if (!stricmp(Name,"EQ UI Service")) { hEQUIService=pISInterface->ConnectService(pExtension,Name,EQUIService); } else if (!stricmp(Name,"EQ Gamestate Service")) { hEQGamestateService=pISInterface->ConnectService(pExtension,Name,EQGamestateService); } else if (!stricmp(Name,"EQ Spawn Service")) { hEQSpawnService=pISInterface->ConnectService(pExtension,Name,EQSpawnService); } else if (!stricmp(Name,"EQ Zone Service")) { hEQZoneService=pISInterface->ConnectService(pExtension,Name,EQZoneService); } else if (!stricmp(Name,"EQ Chat Service")) { hEQChatService=pISInterface->ConnectService(pExtension,Name,EQChatService); } break; case SERVICES_REMOVED: if (!stricmp(Name,"EQ UI Service")) { if (hEQUIService) { pISInterface->DisconnectService(pExtension,hEQUIService); hEQUIService=0; } } else if (!stricmp(Name,"EQ Gamestate Service")) { if (hEQGamestateService) { pISInterface->DisconnectService(pExtension,hEQGamestateService); hEQGamestateService=0; } } else if (!stricmp(Name,"EQ Spawn Service")) { if (hEQSpawnService) { pISInterface->DisconnectService(pExtension,hEQSpawnService); hEQSpawnService=0; } } else if (!stricmp(Name,"EQ Zone Service")) { if (hEQZoneService) { pISInterface->DisconnectService(pExtension,hEQZoneService); hEQZoneService=0; } } else if (!stricmp(Name,"EQ Chat Service")) { if (hEQChatService) { pISInterface->DisconnectService(pExtension,hEQChatService); hEQChatService=0; } } break; } #undef Name } int MyCommand(int argc, char *argv[]) { // IS Commands work just like console programs. argc is the argument (aka parameter) count, // argv is an array containing them. The name of the command is always the first argument. if (argc<2) { // This command requires arguments WriteChatf("Syntax: %s <text>",argv[0]); return 0; } char FullText[8192]={0}; pISInterface->GetArgs(1,argc,argv,FullText); // this gets the rest of the arguments, from 1 to argc WriteChatf("You passed the following text to the command:"); WriteChatf("%s",FullText); // For most commands, you need to deal with only one argument at a time, instead of the entire line. for (int i = 1 ; i < argc ; i++) { WriteChatf("argv[%d]=\"%s\"",i,argv[i]); } // return 0 or greater for normal conditions, or return -1 for an error that should stop // a script. return 0; }
[ "[email protected]@39408780-f958-9dab-a28b-4b240efc9052" ]
[ [ [ 1, 440 ] ] ]
87978271d0165555afdf23714484a804ca94f960
ecad3fd828aed1aa8b7703a3631e0d37bf5d4cbf
/operators.hpp
64ca4412c0f11761d704e95ade3f617633f14cc7
[]
no_license
Fadis/TinyFM
2b1c2b241a28f89b188a931fd8f41b4284fb6e2a
b2940ca1166ccb1e7a0cdfae7e97f6da3bfa2da4
refs/heads/master
2016-09-05T17:06:54.086871
2011-09-23T05:06:54
2011-09-23T05:06:54
2,361,667
4
0
null
null
null
null
UTF-8
C++
false
false
10,635
hpp
#ifndef TINYFM_OPERATORS_HPP #define TINYFM_OPERATORS_HPP #include "config.hpp" #include "clock.hpp" #include "note.hpp" #define BEGIN_0OP( name ) \ class name { \ public: \ inline SampleType operator()( Clock &_clock, Note &_note ) { #define END_0OP( name ) \ } \ }; #define BEGIN_1OP( name ) \ template< typename Type0 > \ class name { \ public: \ inline SampleType operator()( Clock &_clock, Note &_note ) { #define END_1OP( name ) \ } \ private: \ Type0 _0; \ }; #define BEGIN_2OP( name ) \ template< typename Type0, typename Type1 > \ class name { \ public: \ inline SampleType operator()( Clock &_clock, Note &_note ) { #define END_2OP( name ) \ } \ private: \ Type0 _0; \ Type1 _1; \ }; #define BEGIN_3OP( name ) \ template< typename Type0, typename Type1, typename Type2 > \ class name { \ public: \ inline SampleType operator()( Clock &_clock, Note &_note ) { #define END_3OP( name ) \ } \ private: \ Type0 _0; \ Type1 _1; \ Type2 _2; \ }; template< typename Level, typename Source > class Scale { public: Scale() : prev_shift( 0.0f ), prev_tangent( 1.0f ) {} inline SampleType operator()( Clock &_clock, Note &_note ) { const TimeType old_tangent = _clock.getTangent(); const TimeType old_shift = _clock.getShift(); const TimeType new_tangent = old_tangent * level( _clock, _note ); const TimeType new_shift = ( new_tangent - prev_tangent ) * _clock.getGlobal() + prev_shift; _clock.setTangent( new_tangent ); _clock.setShift( new_shift ); const SampleType result = source( _clock, _note ); _clock.setTangent( old_tangent ); _clock.setShift( old_shift ); prev_tangent = new_tangent; prev_shift = new_shift; return result; } private: TimeType prev_shift; TimeType prev_tangent; Level level; Source source; }; template< typename Attack, typename Decay, typename Sustain, typename Release > class Envelope { public: Envelope() : prev_level( 0.0f ) {} inline SampleType operator()( Clock &_clock, Note &_note ) { TimeType current_time = _clock.getGlobal(); if( _note.getStatus() == Note::NOTE_ON ) { current_time -= _clock.getNoteOnTime(); const TimeType attack_time = attack( _clock, _note ); if( current_time < attack_time ) { const TimeType tangent = 1/attack_time; prev_level = tangent * current_time; return prev_level; } const TimeType decay_time = decay( _clock, _note ); current_time -= attack_time; if( current_time < decay_time ) { const TimeType sustain_level = sustain( _clock, _note ); const TimeType tangent = ( sustain_level - 1 )/decay_time; const TimeType shift = 1; prev_level = tangent * current_time + shift; return prev_level; } const TimeType sustain_level = sustain( _clock, _note ); prev_level = sustain_level; return prev_level; } else { current_time -= _clock.getNoteOffTime(); const TimeType tangent = -release( _clock, _note ); const TimeType shift = prev_level; SampleType level = tangent * current_time + shift; if( level <= 0 ) { level = 0; _note.endRequest(); } else _note.contRequest(); return level; } } private: SampleType prev_level; Attack attack; Decay decay; Sustain sustain; Release release; }; template< typename Attack, typename Decay, typename Sustain > class ConstEnvelopeTable { public: SampleType get( SampleType _pos ) const { const SampleType scaled_pos = _pos / total_length; if( scaled_pos < 0 ) return 0; else if( scaled_pos < 1 ) return table[ static_cast<int>( scaled_pos << 8 ) ]; else return Sustain::value; } inline static const ConstEnvelopeTable< Attack, Decay, Sustain > &getInstance() { static const ConstEnvelopeTable< Attack, Decay, Sustain > table; return table; } private: ConstEnvelopeTable() : total_length( Attack::value + Decay::value ) { if( Decay::value > 0.0001f ) { const SampleType ratio = Attack::value / Decay::value; const int attack_size = ( 128 * ratio ); const int decay_size = 256 - attack_size; int index; for( index = 0; index != attack_size; ++index ) set( index, static_cast< SampleType >( index ) / attack_size ); for( index = 0; index != decay_size; ++index ) set( index + attack_size, static_cast< SampleType >( Sustain::value - 1.0f ) * index / decay_size + 1 ); } else { for( int index = 0; index != 256; ++index ) set( index, static_cast< SampleType >( index ) / 256 ); } } void set( int _pos, SampleType _value ) { table[ _pos ] = _value; } SampleType table[ 256 ]; const SampleType total_length; }; template< typename Attack, typename Decay, typename Sustain, typename Release > class ConstEnvelope { public: ConstEnvelope() : prev_level( 0.0f ) { } inline SampleType operator()( Clock &_clock, Note &_note ) { TimeType current_time = _clock.getGlobal(); if( _note.getStatus() == Note::NOTE_ON ) { current_time -= _clock.getNoteOnTime(); prev_level = ConstEnvelopeTable< Attack, Decay, Sustain >::getInstance().get( current_time ); return prev_level; } else { current_time -= _clock.getNoteOffTime(); const TimeType tangent = -Release::value; const TimeType shift = prev_level; SampleType level = tangent * current_time + shift; if( level <= 0 ) { level = 0; _note.endRequest(); } else _note.contRequest(); return level; } } private: SampleType prev_level; Attack attack; Decay decay; }; template< typename Source, typename Modulator, typename Effect, typename Attack, typename Decay, typename Sustain, typename Release > class FM { public: typedef Envelope< Attack, Decay, Sustain, Release > InternalEnvelope; FM() {} inline SampleType operator()( Clock &_clock, Note &_note ) { return sint( ( source( _clock, _note ) + effect( _clock, _note) * modulator( _clock, _note ) ) ) * envelope( _clock, _note ); } private: Source source; Modulator modulator; Effect effect; InternalEnvelope envelope; }; template< typename Source, typename Modulator, typename Effect, typename Attack, typename Decay, typename Sustain, typename Release > class ConstFM { public: typedef ConstEnvelope< Attack, Decay, Sustain, Release > InternalEnvelope; ConstFM() {} inline SampleType operator()( Clock &_clock, Note &_note ) { return sint( ( source( _clock, _note ) + static_cast< SampleType >( Effect::value ) * modulator( _clock, _note ) ) ) * envelope( _clock, _note ); } private: Source source; Modulator modulator; InternalEnvelope envelope; }; template< typename Source > class Wave { public: Wave() {} inline SampleType operator()( Clock &_clock, Note &_note ) { return get( source( _clock, _note ) ); } virtual SampleType get( SampleType ) = 0; private: Source source; }; template< typename Source, typename Traits > class Hammond { public: Hammond(){} fixed32< 16 > operator()( Clock &_clock, Note &_note ) { static const fixed32< 16 > scale_16 = 0.5f; static const fixed32< 16 > scale_8 = 1.0f; static const fixed32< 16 > scale_513 = 1.5f; static const fixed32< 16 > scale_4 = 2.0f; static const fixed32< 16 > scale_223 = 3.0f; static const fixed32< 16 > scale_2 = 4.0f; static const fixed32< 16 > scale_135 = 5.0f; static const fixed32< 16 > scale_113 = 6.0f; static const fixed32< 16 > scale_1 = 8.0f; SampleType time = source( _clock, _note ); fixed32< 16 > sum = 0.0f; sum += sint( time * scale_16 ) * Traits::level_16; sum += sint( time * scale_8 ) * Traits::level_8; sum += sint( time * scale_513 ) * Traits::level_513; sum += sint( time * scale_4 ) * Traits::level_4; sum += sint( time * scale_223 ) * Traits::level_223; sum += sint( time * scale_2 ) * Traits::level_2; sum += sint( time * scale_135 ) * Traits::level_135; sum += sint( time * scale_113 ) * Traits::level_113; sum += sint( time * scale_1) * Traits::level_1; fixed32< 16 > max = 0.0f; max += Traits::level_16; max += Traits::level_8; max += Traits::level_513; max += Traits::level_4; max += Traits::level_223; max += Traits::level_2; max += Traits::level_135; max += Traits::level_113; max += Traits::level_1; sum /= max; return sum; } private: Source source; }; BEGIN_0OP( NoteNumber ) return _note.getNumber(); END_0OP( NoteNumber ) BEGIN_0OP( NoteFrequency ) return _note.getFrequency(); END_0OP( NoteFrequency ) BEGIN_0OP( Time ) return _clock() - static_cast<int>( _clock() ); END_0OP( Time ) BEGIN_1OP( Const ) static const SampleType value = Type0::value; return value; END_1OP( Const ) BEGIN_1OP( Sin ) return sint( _0( _clock, _note ) ); END_1OP( Sin ) BEGIN_1OP( Triangle ) return triangle( _0( _clock, _note ) ); END_1OP( Triangle ) BEGIN_2OP( Rectangle ) static const SampleType duty = Type0::value; const SampleType value = _1( _clock, _note ); if( duty < value ) return static_cast< SampleType >( 1 ); else return static_cast< SampleType >( 0 ); END_2OP( Rectangle ) BEGIN_2OP( Add ) return _0( _clock, _note ) + _1( _clock, _note ); END_2OP( Add ) BEGIN_2OP( Sub ) return _0( _clock, _note ) - _1( _clock, _note ); END_2OP( Sub ) BEGIN_2OP( Mul ) return _0( _clock, _note ) * _1( _clock, _note ); END_2OP( Mul ) BEGIN_2OP( Div ) return _0( _clock, _note ) / _1( _clock, _note ); END_2OP( Div ) BEGIN_2OP( Less ) return _0( _clock, _note ) < _1( _clock, _note ); END_2OP( Less ) BEGIN_2OP( More ) return _0( _clock, _note ) > _1( _clock, _note ); END_2OP( More ) BEGIN_2OP( Equal ) return _0( _clock, _note ) == _1( _clock, _note ); END_2OP( Equal ) BEGIN_2OP( NotEqual ) return _0( _clock, _note ) != _1( _clock, _note ); END_2OP( NotEqual ) BEGIN_3OP( Branch ) if( _0( _clock, _note ) != 0.0f ) return _1( _clock, _note ); else return _2( _clock, _note ); END_3OP( Branch ) BEGIN_1OP( Fuzz ) return exp2t( _0( _clock, _note ) ); END_1OP( Fuzz ) #endif
[ [ [ 1, 365 ] ] ]
3cd4b62b9934e40b4cd6f6b43028cab0d9bf9199
3f0690333762888c26c6fe4d5e9034d3b494440e
/Todo en c/Sources/SensorAdaptador_cpp/SensorAdaptador.cpp
b85390b843540368b37c3ff0e609b76f20001e4d
[]
no_license
jonyMarino/dhacel-micro-prog-vieja
56ecdcc6ca2940be7a0c319c8daa6210a876e655
1f8f8b1fd08aced557b870e716427d0b5e00618a
refs/heads/master
2021-01-21T14:12:03.692649
2011-08-08T11:36:24
2011-08-08T11:36:24
34,534,048
0
0
null
null
null
null
UTF-8
C++
false
false
1,111
cpp
#include "SensorAdaptador.hpp" #include "Mydefines.h" #include "str_lib.h" #include "Sensores.h" #include "cnfbox.h" extern volatile const int PRom[R_ATA+1]; TSensorState SensorAdaptador::getState(){ extern word Result[4]; return Result[numSensor]; } int SensorAdaptador::getValue(){ extern int ValFinal[4]; return ValFinal[numSensor]; } void SensorAdaptador::imprimirValor(OutputStream& os){ byte decimales= getDecimalesMostrados(); int Val= getValue(); if(cartel){ // os.write("\n"); os.write(cartel); os.write(" "); } switch (getState()){ case SENSOR_OK: if(Val>9999) os.write(" OF "); else{ char str[7]; FloatToStr(Val,str,6,decimales); os.write(str); } break; case SENSOR_OF: os.write(" OF "); break; case SENSOR_UF: os.write(" UF "); break; } } int SensorAdaptador::getDecimalesMostrados(){ t_sensor sensor=PRom[R_Sensor+numSensor]; return SENSOR_Decimales_Mostrar(sensor); }
[ "nicopimen@9c8ba4ec-7dbd-852f-d911-916fdc55f737" ]
[ [ [ 1, 60 ] ] ]
66fe3c0ddf6c72f1fa5cda2f503c20f9e57db3d5
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/FlwLib/SparseSlv/Indirect/include/comprow_double.h
76bbfd1363a6331a83d603e569602a01b89d8083
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,315
h
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /* ******** *** SparseLib++ */ /* ******* ** *** *** *** */ /* ***** *** ******** ******** */ /* ***** *** ******** ******** R. Pozo */ /* ** ******* *** ** *** *** K. Remington */ /* ******** ******** A. Lumsdaine */ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /* */ /* */ /* SparseLib++ : Sparse Matrix Library */ /* */ /* National Institute of Standards and Technology */ /* University of Notre Dame */ /* Authors: R. Pozo, K. Remington, A. Lumsdaine */ /* */ /* NOTICE */ /* */ /* Permission to use, copy, modify, and distribute this software and */ /* its documentation for any purpose and without fee is hereby granted */ /* provided that the above notice appear in all copies and supporting */ /* documentation. */ /* */ /* Neither the Institutions (National Institute of Standards and Technology, */ /* University of Notre Dame) nor the Authors make any representations about */ /* the suitability of this software for any purpose. This software is */ /* provided ``as is'' without expressed or implied warranty. */ /* */ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /* Compressed row sparse matrix (0-based, Fortran) */ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ #ifndef CompRow_Mat_double_H #define CompRow_Mat_double_H #include "..\mv\include\vecdefs.h" #include "..\mv\include\mvv.h" class CompCol_Mat_double; class Coord_Mat_double; class CompRow_Mat_double { private: VECTOR_double val_; // data values (nz_ elements) VECTOR_int rowptr_; // row_ptr (dim_[0]+1 elements) VECTOR_int colind_; // col_ind (nz_ elements) int base_; // index base: offset of first element int nz_; // number of nonzeros int dim_[2]; // number of rows, cols public: CompRow_Mat_double(void); CompRow_Mat_double(const CompRow_Mat_double &S); CompRow_Mat_double(const CompCol_Mat_double &C); CompRow_Mat_double(const Coord_Mat_double &CO); CompRow_Mat_double(int M, int N, int nz, double *val, int *r, int *c, int base=0); CompRow_Mat_double(int M, int N, int nz, const VECTOR_double &val, const VECTOR_int &r, const VECTOR_int &c, int base=0); ~CompRow_Mat_double() {}; /*******************************/ /* Access and info functions */ /*******************************/ double& val(int i) { return val_(i); } int& row_ptr(int i) { return rowptr_(i); } int& col_ind(int i) { return colind_(i);} const double& val(int i) const { return val_(i); } const int& row_ptr(int i) const { return rowptr_(i); } const int& col_ind(int i) const { return colind_(i);} int dim(int i) const {return dim_[i];}; int size(int i) const {return dim_[i];}; int NumNonzeros() const {return nz_;}; int base() const {return base_;} /*******************************/ /* Assignment operator */ /*******************************/ CompRow_Mat_double& operator=(const CompRow_Mat_double &R); CompRow_Mat_double& newsize(int M, int N, int nz); /***********************************/ /* General access function (slow) */ /***********************************/ double operator() (int i, int j) const; double& set(int i, int j); /***********************************/ /* Matrix/Vector multiply */ /***********************************/ VECTOR_double operator*(const VECTOR_double &x) const; VECTOR_double trans_mult(const VECTOR_double &x) const; }; std::ostream& operator << (std::ostream & os, const CompRow_Mat_double & mat); #endif /* CompRow_Mat_double_H */
[ [ [ 1, 113 ] ] ]
deb7a70012c485066d44e18ac4a5443e97e7aa99
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit2/Shared/WebEvent.h
bb44aeb5c12ff982aaae7b60bf573ebc686ea90f
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,470
h
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. 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. */ #ifndef WebEvent_h #define WebEvent_h // FIXME: We should probably move to makeing the WebCore/PlatformFooEvents trivial classes so that // we can use them as the event type. #include "ArgumentDecoder.h" #include "ArgumentEncoder.h" #include "WebCoreArgumentCoders.h" #include <wtf/text/WTFString.h> namespace WebKit { class WebEvent { public: enum Type { // WebMouseEvent MouseDown, MouseUp, MouseMove, // WebWheelEvent Wheel, // WebKeyboardEvent KeyDown, KeyUp, RawKeyDown, Char #if ENABLE(TOUCH_EVENTS) , TouchStart, TouchMove, TouchEnd, TouchCancel #endif }; enum Modifiers { ShiftKey = 1 << 0, ControlKey = 1 << 1, AltKey = 1 << 2, MetaKey = 1 << 3, }; Type type() const { return (Type)m_type; } bool shiftKey() const { return m_modifiers & ShiftKey; } bool controlKey() const { return m_modifiers & ControlKey; } bool altKey() const { return m_modifiers & AltKey; } bool metaKey() const { return m_modifiers & MetaKey; } double timestamp() const { return m_timestamp; } protected: WebEvent() { } WebEvent(Type type, Modifiers modifiers, double timestamp) : m_type(type) , m_modifiers(modifiers) , m_timestamp(timestamp) { } void encode(CoreIPC::ArgumentEncoder* encoder) const { encoder->encode(m_type); encoder->encode(m_modifiers); encoder->encode(m_timestamp); } static bool decode(CoreIPC::ArgumentDecoder* decoder, WebEvent& t) { if (!decoder->decode(t.m_type)) return false; if (!decoder->decode(t.m_modifiers)) return false; if (!decoder->decode(t.m_timestamp)) return false; return true; } private: uint32_t m_type; // Type uint32_t m_modifiers; // Modifiers double m_timestamp; }; class WebMouseEvent : public WebEvent { public: enum Button { NoButton = -1, LeftButton, MiddleButton, RightButton }; WebMouseEvent() { } WebMouseEvent(Type type, Button button, int x, int y, int globalX, int globalY, float deltaX, float deltaY, float deltaZ, int clickCount, Modifiers modifiers, double timestamp) : WebEvent(type, modifiers, timestamp) , m_button(button) , m_positionX(x) , m_positionY(y) , m_globalPositionX(globalX) , m_globalPositionY(globalY) , m_deltaX(deltaX) , m_deltaY(deltaY) , m_deltaZ(deltaZ) , m_clickCount(clickCount) { ASSERT(isMouseEventType(type)); } Button button() const { return m_button; } int positionX() const { return m_positionX; } int positionY() const { return m_positionY; } int globalPositionX() const { return m_globalPositionX; } int globalPositionY() const { return m_globalPositionY; } float deltaX() const { return m_deltaX; } float deltaY() const { return m_deltaY; } float deltaZ() const { return m_deltaZ; } int clickCount() const { return m_clickCount; } void encode(CoreIPC::ArgumentEncoder* encoder) const { encoder->encodeBytes(reinterpret_cast<const uint8_t*>(this), sizeof(*this)); } static bool decode(CoreIPC::ArgumentDecoder* decoder, WebMouseEvent& t) { return decoder->decodeBytes(reinterpret_cast<uint8_t*>(&t), sizeof(t)); } private: static bool isMouseEventType(Type type) { return type == MouseDown || type == MouseUp || type == MouseMove; } Button m_button; int m_positionX; int m_positionY; int m_globalPositionX; int m_globalPositionY; float m_deltaX; float m_deltaY; float m_deltaZ; int m_clickCount; }; class WebWheelEvent : public WebEvent { public: enum Granularity { ScrollByPageWheelEvent, ScrollByPixelWheelEvent }; WebWheelEvent() { } WebWheelEvent(Type type, int x, int y, int globalX, int globalY, float deltaX, float deltaY, float wheelTicksX, float wheelTicksY, Granularity granularity, Modifiers modifiers, double timestamp) : WebEvent(type, modifiers, timestamp) , m_positionX(x) , m_positionY(y) , m_globalPositionX(globalX) , m_globalPositionY(globalY) , m_deltaX(deltaX) , m_deltaY(deltaY) , m_wheelTicksX(wheelTicksX) , m_wheelTicksY(wheelTicksY) , m_granularity(granularity) { ASSERT(isWheelEventType(type)); } int positionX() const { return m_positionX; } int positionY() const { return m_positionY; } int globalPositionX() const { return m_globalPositionX; } int globalPositionY() const { return m_globalPositionY; } float deltaX() const { return m_deltaX; } float deltaY() const { return m_deltaY; } float wheelTicksX() const { return m_wheelTicksX; } float wheelTicksY() const { return m_wheelTicksY; } Granularity granularity() const { return (Granularity)m_granularity; } void encode(CoreIPC::ArgumentEncoder* encoder) const { encoder->encodeBytes(reinterpret_cast<const uint8_t*>(this), sizeof(*this)); } static bool decode(CoreIPC::ArgumentDecoder* decoder, WebWheelEvent& t) { return decoder->decodeBytes(reinterpret_cast<uint8_t*>(&t), sizeof(t)); } private: static bool isWheelEventType(Type type) { return type == Wheel; } int m_positionX; int m_positionY; int m_globalPositionX; int m_globalPositionY; float m_deltaX; float m_deltaY; float m_wheelTicksX; float m_wheelTicksY; unsigned m_granularity; // Granularity }; class WebKeyboardEvent : public WebEvent { public: WebKeyboardEvent() { } WebKeyboardEvent(Type type, const WTF::String& text, const WTF::String& unmodifiedText, const WTF::String& keyIdentifier, int windowsVirtualKeyCode, int nativeVirtualKeyCode, bool isAutoRepeat, bool isKeypad, bool isSystemKey, Modifiers modifiers, double timestamp) : WebEvent(type, modifiers, timestamp) , m_text(text) , m_unmodifiedText(unmodifiedText) , m_keyIdentifier(keyIdentifier) , m_windowsVirtualKeyCode(windowsVirtualKeyCode) , m_nativeVirtualKeyCode(nativeVirtualKeyCode) , m_isAutoRepeat(isAutoRepeat) , m_isKeypad(isKeypad) , m_isSystemKey(isSystemKey) { ASSERT(isKeyboardEventType(type)); } const WTF::String& text() const { return m_text; } const WTF::String& unmodifiedText() const { return m_unmodifiedText; } const WTF::String& keyIdentifier() const { return m_keyIdentifier; } int32_t windowsVirtualKeyCode() const { return m_windowsVirtualKeyCode; } int32_t nativeVirtualKeyCode() const { return m_nativeVirtualKeyCode; } bool isAutoRepeat() const { return m_isAutoRepeat; } bool isKeypad() const { return m_isKeypad; } bool isSystemKey() const { return m_isSystemKey; } void encode(CoreIPC::ArgumentEncoder* encoder) const { WebEvent::encode(encoder); encoder->encode(m_text); encoder->encode(m_unmodifiedText); encoder->encode(m_keyIdentifier); encoder->encode(m_windowsVirtualKeyCode); encoder->encode(m_nativeVirtualKeyCode); encoder->encode(m_isAutoRepeat); encoder->encode(m_isKeypad); encoder->encode(m_isSystemKey); } static bool decode(CoreIPC::ArgumentDecoder* decoder, WebKeyboardEvent& t) { if (!WebEvent::decode(decoder, t)) return false; WTF::String text; if (!decoder->decode(text)) return false; t.m_text = text; WTF::String unmodifiedText; if (!decoder->decode(unmodifiedText)) return false; t.m_unmodifiedText = unmodifiedText; WTF::String keyIdentifier; if (!decoder->decode(keyIdentifier)) return false; t.m_keyIdentifier = keyIdentifier; if (!decoder->decode(t.m_windowsVirtualKeyCode)) return false; if (!decoder->decode(t.m_nativeVirtualKeyCode)) return false; if (!decoder->decode(t.m_isAutoRepeat)) return false; if (!decoder->decode(t.m_isKeypad)) return false; if (!decoder->decode(t.m_isSystemKey)) return false; return true; } private: static bool isKeyboardEventType(Type type) { return type == RawKeyDown || type == KeyDown || type == KeyUp || type == Char; } WTF::String m_text; WTF::String m_unmodifiedText; WTF::String m_keyIdentifier; int32_t m_windowsVirtualKeyCode; int32_t m_nativeVirtualKeyCode; bool m_isAutoRepeat; bool m_isKeypad; bool m_isSystemKey; }; #if ENABLE(TOUCH_EVENTS) class WebPlatformTouchPoint { public: enum TouchPointState { TouchReleased, TouchPressed, TouchMoved, TouchStationary, TouchCancelled }; WebPlatformTouchPoint() { } WebPlatformTouchPoint(unsigned id, TouchPointState state, int screenPosX, int screenPosY, int posX, int posY) : m_id(id) , m_state(state) , m_screenPosX(screenPosX) , m_screenPosY(screenPosY) , m_posX(posX) , m_posY(posY) { } unsigned id() const { return m_id; } TouchPointState state() const { return m_state; } int screenPosX() const { return m_screenPosX; } int screenPosY() const { return m_screenPosY; } int32_t posX() const { return m_posX; } int32_t posY() const { return m_posY; } void setState(TouchPointState state) { m_state = state; } void encode(CoreIPC::ArgumentEncoder* encoder) const { encoder->encodeBytes(reinterpret_cast<const uint8_t*>(this), sizeof(*this)); } static bool decode(CoreIPC::ArgumentDecoder* decoder, WebPlatformTouchPoint& t) { return decoder->decodeBytes(reinterpret_cast<uint8_t*>(&t), sizeof(t)); } private: unsigned m_id; TouchPointState m_state; int m_screenPosX, m_screenPosY; int32_t m_posX, m_posY; }; class WebTouchEvent : public WebEvent { public: WebTouchEvent() { } WebTouchEvent(WebEvent::Type type, Vector<WebPlatformTouchPoint> touchPoints, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, Modifiers modifiers, double timestamp) : WebEvent(type, modifiers, timestamp) , m_type(type) , m_touchPoints(touchPoints) , m_ctrlKey(ctrlKey) , m_altKey(altKey) , m_shiftKey(shiftKey) , m_metaKey(metaKey) { ASSERT(isTouchEventType(type)); } const Vector<WebPlatformTouchPoint> touchPoints() const { return m_touchPoints; } void encode(CoreIPC::ArgumentEncoder* encoder) const { WebEvent::encode(encoder); encoder->encode(m_touchPoints); } static bool decode(CoreIPC::ArgumentDecoder* decoder, WebTouchEvent& t) { if (!WebEvent::decode(decoder, t)) return false; if (!decoder->decode(t.m_touchPoints)) return false; return true; } private: static bool isTouchEventType(Type type) { return type == TouchStart || type == TouchMove || type == TouchEnd; } Type m_type; Vector<WebPlatformTouchPoint> m_touchPoints; bool m_ctrlKey; bool m_altKey; bool m_shiftKey; bool m_metaKey; double m_timestamp; }; #endif } // namespace WebKit #endif // WebEvent_h
[ [ [ 1, 447 ] ] ]
bc4762988173f9fa9ddc5e78832cf13d50776bec
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Utilities/Serialize/Display/hkpSerializedDisplayMarker.inl
d41c3c0f92c411486c14082a5458e1f62b3064d2
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
1,263
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ hkpSerializedDisplayMarker::hkpSerializedDisplayMarker() { m_transform.setIdentity(); } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 27 ] ] ]
b90af729116de6db79261fd3359b3b7e5adfaf8a
0043aea568b672f34df4e80015a14f6b03f33ef1
/source/src/JsonParser.cpp
f8d603b9a9454bfd9797d02f33e3e2a4a96b643d
[]
no_license
gosuwachu/s60-json-library
300d5c0428ab3b0e45e12bb821464a3dd351e2d1
fb0074abe3b225f1974c04ecd9dcda72e710c1fa
refs/heads/master
2021-01-01T17:27:58.266546
2010-08-06T11:42:35
2010-08-06T11:42:35
32,650,647
0
0
null
null
null
null
UTF-8
C++
false
false
5,274
cpp
/* Copyright (c) 2009, Piotr Wach, Polidea 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 Polidea 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 PIOTR WACH, POLIDEA ''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 PIOTR WACH, POLIDEA 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 "JsonParser.h" #include "JsonUtil.h" CJsonParser::CJsonParser(MJsonContentHandler& aContentHandler) : iContentHandler(aContentHandler), iString(0, 0) { // No implementation required } CJsonParser::~CJsonParser() { iParserStateStack.Close(); if( iTokener ) delete iTokener; iLastString.Close(); } CJsonParser* CJsonParser::NewLC(MJsonContentHandler& aContentHandler) { CJsonParser* self = new (ELeave) CJsonParser(aContentHandler); CleanupStack::PushL(self); self->ConstructL(); return self; } CJsonParser* CJsonParser::NewL(MJsonContentHandler& aContentHandler) { CJsonParser* self = CJsonParser::NewLC(aContentHandler); CleanupStack::Pop(); // self; return self; } void CJsonParser::ConstructL() { iLastString.Create(256); iTokener = new (ELeave) CJsonTokener; } void CJsonParser::ParseL(const TDesC& aString) { iTokener->SetJsonString( aString ); TText previous = 0; TText next = 0; for(;;) { // If key string without quotes if ((previous == ',' || previous == '{') && iTokener->Current() != '\"' && iTokener->Current() != ' ') { TPtrC string = iTokener->NextTo( ':' ); iLastString.Zero(); ConvertJsonFormatToUnicodeL(string, iLastString); if( iParserStateStack.TopL() != EParseArray && iParserStateStack.TopL() != EParseValue) { iContentHandler.OnKey( iLastString ); } else { if( iParserStateStack.TopL() == EParseValue ) iParserStateStack.Pop(); iContentHandler.OnValue( iLastString ); } } // Then next = iTokener->NextClean(); switch( next ) { case 0: return; case '{': iParserStateStack.PushL( EParseObject ); iContentHandler.OnBeginObject(); break; case '}': if( iParserStateStack.TopL() == EParseValue ) iParserStateStack.Pop(); if( iParserStateStack.TopL() != EParseObject ) { iContentHandler.OnError(KErrNotSupported); return; } iParserStateStack.Pop(); iContentHandler.OnEndObject(); break; case '[': iParserStateStack.PushL( EParseArray ); iContentHandler.OnBeginArray(); break; case ']': if( iParserStateStack.TopL() == EParseValue ) iParserStateStack.Pop(); if( iParserStateStack.TopL() != EParseArray ) { iContentHandler.OnError(KErrNotSupported); return; } iParserStateStack.Pop(); iContentHandler.OnEndArray(); break; case ':': iParserStateStack.PushL( EParseValue ); break; case ',': if( iParserStateStack.TopL() == EParseValue ) iParserStateStack.Pop(); break; case '\"': { TPtrC string = iTokener->NextString( '\"' ); iLastString.Zero(); ConvertJsonFormatToUnicodeL(string, iLastString); if( iParserStateStack.TopL() != EParseArray && iParserStateStack.TopL() != EParseValue) { iContentHandler.OnKey( iLastString ); } else { if( iParserStateStack.TopL() == EParseValue ) iParserStateStack.Pop(); iContentHandler.OnValue( iLastString ); } } break; default: { iTokener->Back(); TPtrC string = iTokener->NextTo( _L(",}]") ); iLastString.Zero(); ConvertJsonFormatToUnicodeL(string, iLastString); iContentHandler.OnValue( iLastString ); if( iParserStateStack.TopL() == EParseValue ) iParserStateStack.Pop(); } break; } // Store processed symbol but skip whitespaces if (next != ' ') previous = next; } } TPtrC CJsonParser::LastString() { return iLastString; }
[ "wach.piotrek@b73fb3d4-a2a3-11de-a23d-972bf86d3223", "vital.vinahradau@b73fb3d4-a2a3-11de-a23d-972bf86d3223" ]
[ [ [ 1, 71 ], [ 74, 75 ], [ 98, 100 ], [ 102, 105 ], [ 107, 117 ], [ 119, 122 ], [ 124, 134 ], [ 136, 138 ], [ 140, 143 ], [ 145, 149 ], [ 151, 163 ], [ 165, 170 ], [ 172, 177 ], [ 182, 189 ] ], [ [ 72, 73 ], [ 76, 97 ], [ 101, 101 ], [ 106, 106 ], [ 118, 118 ], [ 123, 123 ], [ 135, 135 ], [ 139, 139 ], [ 144, 144 ], [ 150, 150 ], [ 164, 164 ], [ 171, 171 ], [ 178, 181 ] ] ]
430d17d378990eb5f6bca034e25ad246cb93ae69
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleMaths/TOblong.h
bc05c109995def7f811de54547c4c8b06d73a26a
[]
no_license
SoylentGraham/Tootle
4ae4e8352f3e778e3743e9167e9b59664d83b9cb
17002da0936a7af1f9b8d1699d6f3e41bab05137
refs/heads/master
2021-01-24T22:44:04.484538
2010-11-03T22:53:17
2010-11-03T22:53:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,410
h
/*------------------------------------------------------ 3D and 2D oblong (non axis-aligned box) shapes -------------------------------------------------------*/ #pragma once #include <TootleCore/TLMaths.h> #include <TootleCore/TLMathsMisc.h> #include <TootleCore/TFixedArray.h> namespace TLMaths { class TOblong; // 3D orientated box - this is an oblong (though perhaps not square). 8 points in space class TOblong2D; // 2D orientated box - this is essentially just a quad. 4 points in space class TSphere; class TSphere2D; class TCapsule; class TMatrix; class TTransform; }; //------------------------------------------------------------------- // 3D orientated box //------------------------------------------------------------------- class TLMaths::TOblong { public: TOblong(); static TRef GetTypeRef() { return TLMaths_ShapeRef(TOblong); } /* const float* GetData() const { return m_MinMax[0].GetData(); } float3& GetMin() { return m_Min; } float3& GetMax() { return m_Max; } const float3& GetMin() const { return m_Min; } const float3& GetMax() const { return m_Max; } float3 GetCenter() const; // get the center of the box float3 GetSize() const { return (m_Max - m_Min); } */ TFixedArray<float3,8>& GetBoxCorners() { return m_Corners; } const TFixedArray<float3,8>& GetBoxCorners() const { return m_Corners; } /* void Set(const float3& Min,const float3& Max) { m_Min = Min; m_Max = Max; m_IsValid = TRUE; } void Set(const float3& MinMax) { m_Min = MinMax; m_Max = MinMax; m_IsValid = TRUE; } void SetMin(const float3& Min) { m_Min = Min; m_IsValid = TRUE; } void SetMax(const float3& Max) { m_Max = Max; m_IsValid = TRUE; } */ void SetInvalid() { m_IsValid = FALSE; } void SetValid(Bool Valid=TRUE) { m_IsValid = Valid; } Bool IsValid() const { return m_IsValid; } /* void Accumulate(const TBox& Box); // accumulate other box. copies other box if this is invalid void Accumulate(const TSphere& Sphere); // accumulate sphere void Accumulate(const TCapsule& Capsule); // accumulate capsule void Accumulate(const float3& Point); // grow the box to these extents void Accumulate(const TArray<float3>& Points); // get the extents of all these points void Transform(const TLMaths::TMatrix& Matrix,const float3& Scale); // transform this shape by this matrix void Transform(const TLMaths::TTransform& Transform); // transform this shape void Transform(const float3& Move) { m_Min += Move; m_Max += Move; } void Untransform(const TLMaths::TTransform& Transform); // untransform box // "intersection" is just a bool version of the distance check. (negative distance is an intersection) Bool GetIntersection(const TLine& Line) const; Bool GetIntersection(const float3& Pos) const; Bool GetIntersection(const TSphere& Sphere) const; Bool GetIntersection(const TCapsule& Capsule) const; Bool GetIntersection(const TBox& Box) const; // if a distance returns negative then it's overlapping by that amount - otherwise it's the distance from the edge of each shape float GetDistance(const TLine& Line) const { return TLMaths::Sqrtf( GetDistanceSq( Line ) ); } float GetDistance(const float3& Pos) const { return TLMaths::Sqrtf( GetDistanceSq( Pos ) ); } float GetDistanceSq(const TLine& Line) const; float GetDistanceSq(const float3& Pos) const; void operator+=(const float3& v) { m_Min += v; m_Max += v; } void operator-=(const float3& v) { m_Min -= v; m_Max -= v; } void operator*=(const float3& v) { m_Min *= v; m_Max *= v; } void operator/=(const float3& v) { m_Min /= v; m_Max /= v; } */ protected: TFixedArray<float3,8> m_Corners; Bool m_IsValid; // validity of bounding box is stored on the box... much easier for us }; //------------------------------------------------------------------- // 2D orientated box //------------------------------------------------------------------- class TLMaths::TOblong2D { public: TOblong2D() : m_IsValid ( FALSE ), m_Corners ( 4, float2(0,0) ) { } TOblong2D(const TLMaths::TBox2D& Box,const TLMaths::TTransform& Transform) : m_IsValid( FALSE ), m_Corners ( 4, float2(0,0) ) { Set( Box, Transform ); } static TRef GetTypeRef() { return TLMaths_ShapeRef(TOblong2D); } float2 GetCenter() const; // get the center of the box TFixedArray<float2,4>& GetBoxCorners() { return m_Corners; } const TFixedArray<float2,4>& GetBoxCorners() const { return m_Corners; } void Set(const TLMaths::TBox2D& Box,const TLMaths::TTransform& Transform); // construct oblong from a transformed box /* void Set(const float3& Min,const float3& Max) { m_Min = Min; m_Max = Max; m_IsValid = TRUE; } void Set(const float3& MinMax) { m_Min = MinMax; m_Max = MinMax; m_IsValid = TRUE; } void SetMin(const float3& Min) { m_Min = Min; m_IsValid = TRUE; } void SetMax(const float3& Max) { m_Max = Max; m_IsValid = TRUE; } */ void SetInvalid() { m_IsValid = FALSE; } void SetValid(Bool Valid=TRUE) { m_IsValid = Valid; } Bool& IsValid() { return m_IsValid; } Bool IsValid() const { return m_IsValid; } /* void Accumulate(const TBox& Box); // accumulate other box. copies other box if this is invalid void Accumulate(const TSphere& Sphere); // accumulate sphere void Accumulate(const TCapsule& Capsule); // accumulate capsule void Accumulate(const float3& Point); // grow the box to these extents void Accumulate(const TArray<float3>& Points); // get the extents of all these points void Transform(const TLMaths::TMatrix& Matrix,const float3& Scale); // transform this shape by this matrix */ void Transform(const TLMaths::TTransform& Transform); // transform this shape /* void Transform(const float3& Move) { m_Min += Move; m_Max += Move; } void Untransform(const TLMaths::TTransform& Transform); // untransform box // "intersection" is just a bool version of the distance check. (negative distance is an intersection) Bool GetIntersection(const TLine& Line) const; Bool GetIntersection(const float3& Pos) const; Bool GetIntersection(const TSphere& Sphere) const; Bool GetIntersection(const TCapsule& Capsule) const; Bool GetIntersection(const TBox& Box) const; // if a distance returns negative then it's overlapping by that amount - otherwise it's the distance from the edge of each shape float GetDistance(const TLine& Line) const { return TLMaths::Sqrtf( GetDistanceSq( Line ) ); } float GetDistance(const float3& Pos) const { return TLMaths::Sqrtf( GetDistanceSq( Pos ) ); } float GetDistanceSq(const TLine& Line) const; float GetDistanceSq(const float3& Pos) const; void operator+=(const float3& v) { m_Min += v; m_Max += v; } void operator-=(const float3& v) { m_Min -= v; m_Max -= v; } void operator*=(const float3& v) { m_Min *= v; m_Max *= v; } void operator/=(const float3& v) { m_Min /= v; m_Max /= v; } */ protected: TFixedArray<float2,4> m_Corners; // the corners are in quad/outline-format. TopLeft,TopRight,BottomRight,BottomLeft. Bool m_IsValid; // validity of bounding box is stored on the box... much easier for us };
[ [ [ 1, 7 ], [ 9, 155 ] ], [ [ 8, 8 ] ] ]
fb28cfe81d3ef6451f2c14132b9e4e32b1a31701
b4bff7f61d078e3dddeb760e21174a781ed7f985
/Source/Contrib/UserInterface/src/Component/Tree/Selection/OSGTreeSelectionListener.h
2bb110216ae8bd62657cf456437ed7320038fe68
[]
no_license
Langkamp/OpenSGToolbox
8283edb6074dffba477c2c4d632e954c3c73f4e3
5a4230441e68f001cdf3e08e9f97f9c0f3c71015
refs/heads/master
2021-01-16T18:15:50.951223
2010-05-19T20:24:52
2010-05-19T20:24:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,951
h
/*---------------------------------------------------------------------------*\ * OpenSGUserInterface * * * * * * * * * * Authors: David Kabala, Alden Peterson, Lee Zaniewski, Jonathan Flory * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ #ifndef _OSG_UI_TREE_SELECTION_LISTENER_H_ #define _OSG_UI_TREE_SELECTION_LISTENER_H_ #ifdef __sgi #pragma once #endif #include "OSGConfig.h" #include "OSGContribUserInterfaceDef.h" #include "OSGTreeSelectionEvent.h" #include "OSGEventListener.h" OSG_BEGIN_NAMESPACE class OSG_CONTRIBUSERINTERFACE_DLLMAPPING TreeSelectionListener : public EventListener { /*========================= PUBLIC ===============================*/ public: //Called whenever elements are added to the selection virtual void selectionAdded(const TreeSelectionEventUnrecPtr e) = 0; //Called whenever elements are removed to the selection virtual void selectionRemoved(const TreeSelectionEventUnrecPtr e) = 0; }; typedef TreeSelectionListener* TreeSelectionListenerPtr; OSG_END_NAMESPACE #endif /* _OSG_UI_TREE_SELECTION_LISTENER_H_ */
[ [ [ 1, 58 ] ] ]
3010d31c98203e59805ea1ffb159409526d0d5e1
ea72aac3344f9474a0ba52c90ed35e24321b025d
/PathFinding/PathFinding/Node.h
e389949eda8ae71141be4d9415914797f66a8931
[]
no_license
nlelouche/ia-2009
3bd7f1e42280001024eaf7433462b2949858b1c2
44c07567c3b74044e59313532b5829f3a3466a32
refs/heads/master
2020-05-17T02:21:02.137224
2009-03-31T01:12:44
2009-03-31T01:12:44
32,657,337
0
0
null
null
null
null
UTF-8
C++
false
false
1,044
h
#pragma once //------------------------------------------------------------------------- #include <list> using namespace std; //------------------------------------------------------------------------- class Node{ //------------------------------------------------------------------------- public: //------------------------------- Node(int _cost,int _x, int _y); ~Node(); //------------------------------- Node* GetParent(); void SetParent(Node * _node); //------------------------------- int GetTotalCost(); void SetTotalCost(int _parentCost); //------------------------------------------------------------------------- private: Node * m_pkParent; bool m_bIsOpen; bool m_bIsClosed; int m_Cost; int m_TotalCost; int m_x; int m_y; public: struct NodePosition{ int Initial_X; int Initial_Y; int Ending_X; int Ending_Y; }; //------------------------------------------------------------------------- }; //-------------------------------------------------------------------------
[ "calaverax@bb2752b8-1d7e-11de-9d52-39b120432c5d" ]
[ [ [ 1, 41 ] ] ]
c264388057f10a6c39a599728fc095742827c0b7
5bc5d779cacf86327d641a588b59a446aa535ba5
/Hurtownia/hurtownia.cpp
0bb3b94d3080542291bac486bbd3304938ada7a1
[]
no_license
korredMS/projekt
03dceae447e05bf6d2cd9da3791ab7b627569083
d5d1f7702018dee4cb78fdb172b2c6ca36d59514
refs/heads/master
2020-04-16T04:23:14.650709
2010-06-15T06:59:08
2010-06-15T06:59:08
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
19,178
cpp
#include "hurtownia.h" #include "ui_hurtownia.h" #include "edycjasklep.h" #include "edycjatowar.h" #include "edycjakategoria.h" #include "szczegolyzamowienia.h" using namespace DBProxyNS; OknoHurtownia::OknoHurtownia(QWidget *parent) : QMainWindow(parent), ui(new Ui::Hurtownia), db(this,"localhost","Hurtownia","root","") { ui->setupUi(this); db.polacz(); pobierzSklepy(); pobierzTowary(); pobierzKategorie(); pobierzZamowienia(); } OknoHurtownia::~OknoHurtownia() { delete ui; } void OknoHurtownia::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } /************************** OBSŁUGA OKNA HURTOWNI **************************/ void OknoHurtownia::on_koniecButton_clicked() { unsigned int ret = QMessageBox::question( this, "Uwaga", "<Center>Czy na pewno chcesz opuścić aplikację?</CENTER>", QMessageBox::Yes | QMessageBox::No ); if ( ret & QMessageBox::Yes ){ this->close(); } } /************************** OBSŁUGA SKLEPÓW **************************/ void OknoHurtownia::pobierzSklepy() // wyświetlanie sklepów { modelSklepy.clear(); sklep = db.pobierz< DBProxy::Sklep >(); for ( int i = 0; i < sklep.length() ; i++) { Sklep towar = sklep.at( i ); modelSklepy.setItem( i, 0, new QStandardItem (sklep[i].nazwa )); modelSklepy.setItem( i, 1, new QStandardItem (sklep[i].REGON)); modelSklepy.setItem( i, 2, new QStandardItem (DBProxy::liczbaNaString(sklep[i].upust))); modelSklepy.setItem( i, 3, new QStandardItem (sklep[i].ulica)); modelSklepy.setItem( i, 4, new QStandardItem (sklep[i].miejscowosc)); modelSklepy.setItem( i, 5, new QStandardItem (sklep[i].kodPocztowy)); modelSklepy.setItem( i, 6, new QStandardItem (sklep[i].telefon)); modelSklepy.setItem( i, 7, new QStandardItem (sklep[i].fax)); modelSklepy.setItem( i, 8, new QStandardItem (sklep[i].email)); modelSklepy.setItem( i, 9, new QStandardItem (sklep[i].login)); modelSklepy.setItem( i, 10, new QStandardItem (sklep[i].haslo)); } modelSklepy.setHeaderData( 0, Qt::Horizontal, "Nazwa" ); modelSklepy.setHeaderData( 1, Qt::Horizontal, "Regon" ); modelSklepy.setHeaderData( 2, Qt::Horizontal, "Upust" ); modelSklepy.setHeaderData( 3, Qt::Horizontal, "Ulica" ); modelSklepy.setHeaderData( 4, Qt::Horizontal, "Miejscowość" ); modelSklepy.setHeaderData( 5, Qt::Horizontal, "Kod Pocztowy" ); modelSklepy.setHeaderData( 6, Qt::Horizontal, "Telefon" ); modelSklepy.setHeaderData( 7, Qt::Horizontal, "Fax" ); modelSklepy.setHeaderData( 8, Qt::Horizontal, "Email" ); modelSklepy.setHeaderData( 9, Qt::Horizontal, "Login" ); modelSklepy.setHeaderData( 10, Qt::Horizontal, "Hasło" ); ui->tableListaSklepow->setModel( &modelSklepy); ui->tableListaSklepow->setColumnWidth( 0, 80 ); ui->tableListaSklepow->setColumnWidth( 1, 50 ); ui->tableListaSklepow->setColumnWidth( 2, 20 ); ui->tableListaSklepow->setColumnWidth( 3, 80 ); ui->tableListaSklepow->setColumnWidth( 4, 80 ); ui->tableListaSklepow->setColumnWidth( 5, 20 ); ui->tableListaSklepow->setColumnWidth( 6, 20 ); ui->tableListaSklepow->setColumnWidth( 7, 20 ); ui->tableListaSklepow->setColumnWidth( 8, 50 ); ui->tableListaSklepow->setColumnWidth( 9, 50 ); ui->tableListaSklepow->setColumnWidth( 10, 50 ); ui->tableListaSklepow->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableListaSklepow->resizeColumnsToContents(); // ui->tableListaSklepow->selectRow(0); ui->modyfikujButton->setEnabled( false ); ui->usunButton->setEnabled(false); } void OknoHurtownia::on_dodajButton_clicked() { EdycjaSklep *edycja = new EdycjaSklep(this,db); connect(edycja, SIGNAL(odswiezTabeleSklepu()), this, SLOT(pobierzSklepy())); edycja->show(); } void OknoHurtownia::on_tableListaSklepow_clicked(QModelIndex index) { idxSklepu = index.row(); ui->tableListaSklepow->selectRow( idxSklepu); ui->modyfikujButton->setEnabled( true ); ui->usunButton->setEnabled(true); } void OknoHurtownia::on_usunButton_clicked() // sprawdzić czy działa ( bedzie usuwać z lisy ale nie z bazy) { unsigned int ret = QMessageBox::question( this, "Uwaga", "<CENTER>Czy na pewno chcesz usunąć wybrany sklep z bazy danych?</CENTER>", QMessageBox::Yes | QMessageBox::No ); if ( ret & QMessageBox::Yes ){ if(db.usunRekord( &sklep.at(idxSklepu)) ){ //sprawdź czy usunął! sklep.removeAt(idxSklepu); modelSklepy.removeRow( idxSklepu , QModelIndex() ); pobierzSklepy(); return; }else{ QMessageBox::information( this, "Uwaga","<CENTER>Nie można usunąć slepu składajacego zamównienie</CENTER>",QMessageBox::Ok ); return; } } if ( ret & QMessageBox::No ){ pobierzSklepy(); return; } } void OknoHurtownia::on_modyfikujButton_clicked() { int wiersz = ui->tableListaSklepow->currentIndex().row(); EdycjaSklep *edycja = new EdycjaSklep(this,db, &sklep[wiersz], false); connect(edycja, SIGNAL(odswiezTabeleSklepu()), this, SLOT(pobierzSklepy())); edycja->show(); } /************************** OBSŁUGA TOWARÓW **************************/ void OknoHurtownia::pobierzTowary() //wyświetlenie towarow { modelTowary.clear(); towaryH = db.pobierz< DBProxy::TowarHurtownia >(); for (int i = 0; i < towaryH.length(); i++) { modelTowary.setItem( i, 0, new QStandardItem( db.pobierz< DBProxy::Kategoria >(DBProxy::Kategoria::Id, DBProxy::Filtr(towaryH[i].idKategorii ) ).first().nazwa ) ); modelTowary.setItem( i, 1, new QStandardItem( towaryH[i].nazwa ) ); modelTowary.setItem( i, 2, new QStandardItem( towaryH[i].opis ) ); modelTowary.setItem( i, 3, new QStandardItem( DBProxy::liczbaNaString( towaryH[i].cena ) ) ); modelTowary.setItem( i, 4, new QStandardItem( DBProxy::liczbaNaString( towaryH[i].ilosc ) ) ); modelTowary.setItem( i, 5, new QStandardItem( QString::number( towaryH[i].vat ) + "%" ) ); } modelTowary.setHeaderData( 0, Qt::Horizontal, "Kategoria" ); modelTowary.setHeaderData( 1, Qt::Horizontal, "Nazwa" ); modelTowary.setHeaderData( 2, Qt::Horizontal, "Opis" ); modelTowary.setHeaderData( 3, Qt::Horizontal, "Cena" ); modelTowary.setHeaderData( 4, Qt::Horizontal, "Ilość" ); modelTowary.setHeaderData( 5, Qt::Horizontal, "VAT" ); ui->tableListaTowarow->setModel( &modelTowary ); ui->tableListaTowarow->setColumnWidth( 0, 100 ); ui->tableListaTowarow->setColumnWidth( 1, 100 ); ui->tableListaTowarow->setColumnWidth( 2, 115 ); ui->tableListaTowarow->setColumnWidth( 3, 40 ); ui->tableListaTowarow->setColumnWidth( 4, 35 ); ui->tableListaTowarow->setColumnWidth( 5, 40 ); ui->tableListaTowarow->setEditTriggers( QAbstractItemView::NoEditTriggers); ui->buttonModyfikujTowar->setEnabled( false ); ui->buttonUsunTowar->setEnabled(false); } void OknoHurtownia::on_buttonDodajTowar_clicked() { EdycjaTowar *edycjaTowar = new EdycjaTowar(this,db); connect( edycjaTowar, SIGNAL(odswiezTabeleTowarow()), this, SLOT(pobierzTowary())); edycjaTowar->show(); } void OknoHurtownia::on_tableListaTowarow_clicked(QModelIndex index) { ui->buttonModyfikujTowar->setEnabled( true ); ui->buttonUsunTowar->setEnabled(true); } void OknoHurtownia::on_buttonUsunTowar_clicked() // usuwa z listy i z bazy { towaryH = db.pobierz< DBProxy::TowarHurtownia >(); int idxTowaru = ui->tableListaTowarow->currentIndex().row(); unsigned int ret = QMessageBox::question( this, "Uwaga", "<CENTER>Czy na pewno chcesz usunąć ?</CENTER>" + towaryH[ idxTowaru].nazwa, QMessageBox::Yes | QMessageBox::No ); if ( ret & QMessageBox::Yes ){ if(!db.usunRekord( &towaryH.at( idxTowaru ) )){ QMessageBox::warning( this, "Uwaga","<CENTER>Nie można usunąć towaru bedącego częścią zamówienia</CENTER>",QMessageBox::Ok ); pobierzTowary(); return; }else { towaryH.removeAt(idxTowaru); modelTowary.removeRow( idxTowaru , QModelIndex() ); QMessageBox::information(this, "Uwaga","<CENTER>Towar został usunięty</CENTER>",QMessageBox::Ok ); pobierzTowary(); return; } } if ( ret & QMessageBox::No ){ pobierzZamowienia(); pobierzTowary(); return; } } void OknoHurtownia::on_buttonModyfikujTowar_clicked() { int wiersz = ui->tableListaTowarow->currentIndex().row(); EdycjaTowar *edycjaTowar = new EdycjaTowar(this, db, &towaryH[wiersz], false); connect(edycjaTowar, SIGNAL(odswiezTabeleTowarow()), this, SLOT(pobierzTowary())); edycjaTowar->show(); } /************************* OBSŁUGA KATEGORII *************************/ void OknoHurtownia::pobierzKategorie() { modelKategorie.clear(); kH = db.pobierz< DBProxy::Kategoria >(); for (int i = 0; i < kH.size(); i++) { modelKategorie.setItem( i, 0, new QStandardItem( kH[i].nazwa ) ); modelKategorie.setItem( i, 1, new QStandardItem( DBProxy::liczbaNaString( kH[i].id ) ) ); } modelKategorie.setHeaderData( 0, Qt::Horizontal, "Kategoria" ); modelKategorie.setHeaderData( 1, Qt::Horizontal, "Id kategorii" ); ui->tableListakategorii->setModel( &modelKategorie ); ui->tableListakategorii->setColumnWidth( 0, 100 ); ui->tableListakategorii->setColumnWidth( 1, 80 ); ui->tableListakategorii->setEditTriggers( QAbstractItemView::NoEditTriggers); ui->buttonModyfikujKat->setEnabled( false ); ui->buttonUsunKat->setEnabled(false); } void OknoHurtownia::on_buttonDodajKat_clicked() { EdycjaKategoria *kategoria = new EdycjaKategoria(this,db); connect(kategoria, SIGNAL(odswiezTabeleKategoria()), this, SLOT(pobierzKategorie())); kategoria->show(); } void OknoHurtownia::on_tableListakategorii_clicked(QModelIndex index) { idxKategori = index.row(); ui->tableListakategorii->selectRow( idxKategori); ui->buttonModyfikujKat->setEnabled( true ); ui->buttonUsunKat->setEnabled(true); } void OknoHurtownia::on_buttonUsunKat_clicked() { kH = db.pobierz< DBProxy::Kategoria >(); int wiersz = ui->tableListakategorii->currentIndex().row(); unsigned int ret = QMessageBox::question( this, "Uwaga", "<CENTER>Czy na pewno chcesz usunąć ?</CENTER>" + kH[ wiersz].nazwa, QMessageBox::Yes | QMessageBox::No ); if ( ret & QMessageBox::Yes ){ if(!db.usunRekord( &kH.at( wiersz ) )){ QMessageBox::warning( this, "Uwaga","<CENTER>Nie można usunąć kategorii,<BR> do której przypisany jeste towar</CENTER>",QMessageBox::Ok ); pobierzKategorie(); pobierzZamowienia(); return; }else { kH.removeAt(wiersz); modelKategorie.removeRow( wiersz , QModelIndex() ); QMessageBox::information(this, "Uwaga","<CENTER>Kategoria została usunięta</CENTER>",QMessageBox::Ok ); pobierzKategorie(); pobierzZamowienia(); pobierzTowary(); return; } } if ( ret & QMessageBox::No ){ pobierzKategorie(); pobierzZamowienia(); pobierzTowary(); return; } } void OknoHurtownia::on_buttonModyfikujKat_clicked() { int wiersz = ui->tableListakategorii->currentIndex().row(); EdycjaKategoria *kategoria = new EdycjaKategoria(this, db, &kH[wiersz], false); connect(kategoria, SIGNAL(odswiezTabeleKategoria()), this, SLOT(pobierzKategorie())); connect(kategoria, SIGNAL(odswiezTabelaTowarow()), this, SLOT(pobierzTowary())); kategoria->show(); } /************************* OBSŁUGA ZAMÓWIEŃ **************************/ void OknoHurtownia::pobierzZamowienia() //lista zamowien { modelZamowienia.clear(); zamowienieH = db.pobierz< DBProxy::ZamowienieHurtownia >(); for (int i = 0; i < zamowienieH.size(); i++) { modelZamowienia.setItem( i, 0, new QStandardItem( zamowienieH[i].nrFaktury ) ); modelZamowienia.setItem( i, 1, new QStandardItem( DBProxy::dataNaString( zamowienieH[i].dataZlozenia ) ) ); //rzutowanie nie działa modelZamowienia.setItem( i, 2, new QStandardItem( DBProxy::dataNaString( zamowienieH[i].dataRealizacji ) ) );//rzutowanie nie działa modelZamowienia.setItem( i, 3, new QStandardItem( DBProxy::liczbaNaString( zamowienieH[i].upust ) ) );//rzutowanie nie działa modelZamowienia.setItem( i, 4, new QStandardItem( DBProxy::statusNaString( zamowienieH[i].status ) ) );//rzutowanie nie działa } modelZamowienia.setHeaderData( 0, Qt::Horizontal, "Nr faktury" ); modelZamowienia.setHeaderData( 1, Qt::Horizontal, "Data złożenia" ); modelZamowienia.setHeaderData( 2, Qt::Horizontal, "Data realizacji" ); modelZamowienia.setHeaderData( 3, Qt::Horizontal, "Upust" ); modelZamowienia.setHeaderData( 4, Qt::Horizontal, "Status" ); ui->tableZamowienia->setModel( &modelZamowienia ); ui->tableZamowienia->setColumnWidth( 0, 90 ); ui->tableZamowienia->setColumnWidth( 1, 100 ); ui->tableZamowienia->setColumnWidth( 2, 100 ); ui->tableZamowienia->setColumnWidth( 3, 50 ); ui->tableZamowienia->setColumnWidth( 4, 85 ); ui->tableZamowienia->setEditTriggers( QAbstractItemView::NoEditTriggers); ui->buttonRealizujZamowieni->setEnabled(false); ui->buttonAnulujZamowienie->setEnabled(false); ui->szczegolyButton->setEnabled(false); } void OknoHurtownia::on_tableZamowienia_clicked(QModelIndex index) { idxZamowienia = index.row(); ui->tableZamowienia->selectRow( idxZamowienia); ui->buttonRealizujZamowieni->setEnabled(true); ui->buttonAnulujZamowienie->setEnabled(true); ui->szczegolyButton->setEnabled(true); } void OknoHurtownia::on_buttonRealizujZamowieni_clicked() { int wiersz = ui->tableZamowienia->currentIndex().row(); ZamowienieHurtownia &zamowienie = zamowienieH[ wiersz ]; modelPozycjeZamowienia.clear(); pozycjeZamowienia = db.pobierz <DBProxy::PozycjaZamowienia>(); modelTowary.clear(); towaryH = db.pobierz< DBProxy::TowarHurtownia >(); bool sprawdz = false; if( zamowienie.status == DBProxy::Oczekujace ) { for( int i = 0 ; i < pozycjeZamowienia.length() ; ++i) if(pozycjeZamowienia[i].idZamowienia == zamowienie.id) for( int j = 0 ; j < towaryH.length() ; ++j) if(pozycjeZamowienia[i].idTowaru == towaryH[j].id) if( pozycjeZamowienia[i].ilosc > towaryH[j].ilosc) sprawdz = true; if(!sprawdz){ { zamowienie.status = DBProxy::DoRealizacji; zamowienie.dataRealizacji = QDate::currentDate(); db.uaktualnij( zamowienie ); } for( int i = 0 ; i < pozycjeZamowienia.length() ; ++i) if(pozycjeZamowienia[i].idZamowienia == zamowienie.id) for( int j = 0 ; j < towaryH.length() ; ++j) if(pozycjeZamowienia[i].idTowaru == towaryH[j].id) if( pozycjeZamowienia[i].ilosc <= towaryH[j].ilosc){ //zamówienie zawiera nie całkowitą ilośc towaru towaryH[j].ilosc = towaryH[j].ilosc - pozycjeZamowienia[i].ilosc; db.uaktualnij( towaryH.at(j) ); } QString nrFaktury; QDate data = QDate::currentDate(); nrFaktury += DBProxy::liczbaNaString(zamowienie.id) + "/" + DBProxy::liczbaNaString (data.day()) + "/" + DBProxy::liczbaNaString(data.month() )+ "/" + DBProxy::liczbaNaString(data.year()) ; zamowienie.nrFaktury = nrFaktury; db.uaktualnij(zamowienie); qDebug( ) << nrFaktury; qDebug() << zamowienie.nrFaktury; QMessageBox::information( this, "Komunikat","<CENTER>Zamówienie przyjete do realizacji</CENTER>", QMessageBox::Yes ); pobierzZamowienia(); pobierzTowary(); } else { QMessageBox::information( this, "Komunikat","<CENTER>Zamówienie nie moze byc zrealizowane - <BR>brak towarow w bazie hurtowni</CENTER>", QMessageBox::Yes ); zamowienie.status = DBProxy::Anulowane; zamowienie.dataRealizacji = QDate::currentDate(); db.uaktualnij( zamowienie ); pobierzZamowienia(); pobierzTowary(); } } pobierzTowary(); pobierzZamowienia(); } void OknoHurtownia::on_buttonAnulujZamowienie_clicked() { int wiersz = ui->tableZamowienia->currentIndex().row(); ZamowienieHurtownia &zamowienie = zamowienieH[ wiersz ]; if( zamowienie.status == DBProxy::Oczekujace ) { zamowienie.status = DBProxy::Anulowane; zamowienie.dataRealizacji = QDate::currentDate(); db.uaktualnij( zamowienie ); } pobierzZamowienia(); } void OknoHurtownia::pobierzSzczegoly(){ { modelPozycjeZamowienia.clear(); pozycjeZamowienia = db.pobierz< DBProxy::PozycjaZamowienia >(); for (int i = 0; i < zamowienieH.size(); i++) { modelPozycjeZamowienia.setItem( i, 0, new QStandardItem( DBProxy::liczbaNaString( pozycjeZamowienia[i].idZamowienia ) ) ); modelPozycjeZamowienia.setItem( i, 1, new QStandardItem( DBProxy::liczbaNaString( pozycjeZamowienia[i].idTowaru ) ) ); modelPozycjeZamowienia.setItem( i, 2, new QStandardItem( pozycjeZamowienia[i].ilosc ) ); } modelPozycjeZamowienia.setHeaderData( 0, Qt::Horizontal, "Id Zamówienia" ); modelPozycjeZamowienia.setHeaderData( 1, Qt::Horizontal, "Id Towaru" ); modelPozycjeZamowienia.setHeaderData( 2, Qt::Horizontal, "Ilośź" ); ui->tableZamowienia->setModel( &modelPozycjeZamowienia ); ui->tableZamowienia->setColumnWidth( 0, 50 ); ui->tableZamowienia->setColumnWidth( 1, 50 ); ui->tableZamowienia->setColumnWidth( 2, 30 ); } } void OknoHurtownia::on_szczegolyButton_clicked() { int wiersz = ui->tableZamowienia->currentIndex().row(); SzczegolyZamowienia *pozZamowienia = new SzczegolyZamowienia(this,db, &zamowienieH[wiersz]); pozZamowienia ->show(); } void OknoHurtownia::on_odswiezButton_clicked() { pobierzZamowienia(); }
[ [ [ 1, 516 ] ] ]
5c0dc14d6e3e83751edf6cf40bf2ec09d1571d07
16ba8e891c084c827148d9c6cd6981a29772cb29
/KaraokeMachine/trunk/src/KMDefs.h
e84400848ee49ca6009a1317663bf8e6538df180
[]
no_license
RangelReale/KaraokeMachine
efa1d5d23d0759762f3d6f590e114396eefdb28a
abd3b05d7af8ebe8ace15e888845f1ca8c5e481f
refs/heads/master
2023-06-29T20:32:56.869393
2008-09-16T18:09:40
2008-09-16T18:09:40
37,156,415
1
0
null
null
null
null
UTF-8
C++
false
false
2,355
h
#ifndef H_KMDEFS_H #define H_KMDEFS_H namespace KaraokeMachine { typedef long kmtime_t; // time in ms #pragma pack(push, 1) #define KMSONGPACKAGE_SIG "KMSP" #define KMSONGPACKAGE_SIG_SIZE 4 #define KMSONGPACKAGE_VERSION 1 #define KMSONGPACKAGE_MAXTEXT 100 #define KMSONGPACKAGE_MAXPATH 255 #define KMSONGPACKAGE_MAXGENRE 40 #define KMSONGPACKAGE_MAXTAGS 255 #define KMSONGPACKAGE_MAGIC_SONG "KMSS" #define KMSONGPACKAGE_MAGIC_SONG_SIZE 4 #define KMIMAGEPACKAGE_SIG "KMIP" #define KMIMAGEPACKAGE_SIG_SIZE 4 #define KMIMAGEPACKAGE_VERSION 1 #define KMIMAGEPACKAGE_MAXTEXT 100 #define KMIMAGEPACKAGE_MAXPATH 255 #define KMIMAGEPACKAGE_MAXTAGS 255 #define KMIMAGEPACKAGE_MAGIC_IMAGE "KMII" #define KMIMAGEPACKAGE_MAGIC_IMAGE_SIZE 4 typedef struct __attribute__ ((__packed__)) kmsongpackage_header_t { char sig[KMSONGPACKAGE_SIG_SIZE]; unsigned short version; unsigned int packageid; char title[KMSONGPACKAGE_MAXTEXT]; char author[KMSONGPACKAGE_MAXTEXT]; unsigned short songcount; unsigned short descriptionsize; }; typedef struct __attribute__ ((__packed__)) kmsongpackage_song_t { char magic[4]; unsigned short id; char filename[KMSONGPACKAGE_MAXPATH]; char title[KMSONGPACKAGE_MAXTEXT]; char artist[KMSONGPACKAGE_MAXTEXT]; char artist2[KMSONGPACKAGE_MAXTEXT]; char genre[KMSONGPACKAGE_MAXGENRE]; char subgenre[KMSONGPACKAGE_MAXGENRE]; char startlyrics[KMSONGPACKAGE_MAXTEXT]; char melodytrack; char transpose; char tags[KMSONGPACKAGE_MAXTAGS]; unsigned int filesize; }; typedef struct __attribute__ ((__packed__)) kmimagepackage_header_t { char sig[KMIMAGEPACKAGE_SIG_SIZE]; unsigned short version; char title[KMIMAGEPACKAGE_MAXTEXT]; char author[KMIMAGEPACKAGE_MAXTEXT]; unsigned short imagecount; unsigned short descriptionsize; }; typedef struct __attribute__ ((__packed__)) kmimagepackage_image_t { char magic[4]; unsigned short id; char filename[KMSONGPACKAGE_MAXPATH]; char title[KMSONGPACKAGE_MAXTEXT]; unsigned char iswide; char tags[KMIMAGEPACKAGE_MAXTAGS]; unsigned int filesize; }; #pragma pack(pop) }; #endif //H_KMDEFS_H
[ "hitnrun@6277c508-b546-0410-9041-f9c9960c1249" ]
[ [ [ 1, 85 ] ] ]
026a2692ffd8b3d3d9f06a7cbe2013ea9357848d
d9bf74086d94169f0e0c9e976965662f6639a9ae
/src/playercar.cpp
39c640d323bb51adb366f8d354c1f15a315d37ba
[]
no_license
th0m/projet-genie-logiciel-gstl
75e77387b95c328f7e34428ca4f4b74198774d10
c2d283897d36ba2e5bf4ec0bf3dbea6ab65884a8
refs/heads/master
2021-01-25T09:00:30.529804
2011-04-19T21:22:12
2011-04-19T21:22:12
32,145,361
0
0
null
null
null
null
ISO-8859-1
C++
false
false
9,848
cpp
#include "playercar.hpp" #include "game.hpp" #include "iacar.hpp" #include <SDL/SDL_image.h> #include <cmath> #include <list> PlayerCar::PlayerCar(float x, float y, SDL_Surface *window) : Shape(x, y, std::string("playercarg"), window), m_fwdspeed(Game::getFwdSpeed()), m_revspeed(m_fwdspeed / 2), m_state(Normal), m_blocked(false), m_flaque(false) { /* # On veut contrôler completement la destruction de l'objet */ m_free = false; /* # On charge les differentes sprites */ m_up = IMG_Load("sprites/playercarh"); SDL_SetColorKey(m_up, SDL_SRCCOLORKEY, SDL_MapRGB(m_up->format, 0xff, 0xff, 0xff)); m_down = IMG_Load("sprites/playercarb"); SDL_SetColorKey(m_down, SDL_SRCCOLORKEY, SDL_MapRGB(m_down->format, 0xff, 0xff, 0xff)); m_right = IMG_Load("sprites/playercard"); SDL_SetColorKey(m_right, SDL_SRCCOLORKEY, SDL_MapRGB(m_right->format, 0xff, 0xff, 0xff)); m_northwest = IMG_Load("sprites/playercarno"); SDL_SetColorKey(m_northwest, SDL_SRCCOLORKEY, SDL_MapRGB(m_right->format, 0xff, 0xff, 0xff)); m_northeast = IMG_Load("sprites/playercarne"); SDL_SetColorKey(m_northeast, SDL_SRCCOLORKEY, SDL_MapRGB(m_right->format, 0xff, 0xff, 0xff)); m_southwest = IMG_Load("sprites/playercarso"); SDL_SetColorKey(m_southwest, SDL_SRCCOLORKEY, SDL_MapRGB(m_right->format, 0xff, 0xff, 0xff)); m_southeast = IMG_Load("sprites/playercarse"); SDL_SetColorKey(m_southeast, SDL_SRCCOLORKEY, SDL_MapRGB(m_right->format, 0xff, 0xff, 0xff)); m_left = m_img; m_currentPos = Left; } PlayerCar::~PlayerCar() { /* # On decharge proprement les images */ SDL_FreeSurface(m_up); SDL_FreeSurface(m_down); SDL_FreeSurface(m_right); SDL_FreeSurface(m_left); SDL_FreeSurface(m_northwest); SDL_FreeSurface(m_northeast); SDL_FreeSurface(m_southwest); SDL_FreeSurface(m_southeast); } void PlayerCar::loadAnotherPosition(SDLKey key) { /* # Ici on est charge de blitter le nouveau sprite de position selon la touche appuyee */ switch(m_currentPos) { case Left : { if(key == SDLK_LEFT) m_img = m_southwest, m_currentPos = SouthWest; else m_img = m_northwest, m_currentPos = NorthWest; break; } case NorthWest : { if(key == SDLK_LEFT) m_img = m_left, m_currentPos = Left; else m_img = m_up, m_currentPos = Up; break; } case Up : { if(key == SDLK_LEFT) m_img = m_northwest, m_currentPos = NorthWest; else m_img = m_northeast, m_currentPos = NorthEast; break; } case NorthEast : { if(key == SDLK_LEFT) m_img = m_up, m_currentPos = Up; else m_img = m_right, m_currentPos = Right; break; } case Right : { if(key == SDLK_LEFT) m_img = m_northeast, m_currentPos = NorthEast; else m_img = m_southeast, m_currentPos = SouthEast; break; } case SouthEast : { if(key == SDLK_LEFT) m_img = m_right, m_currentPos = Right; else m_img = m_down, m_currentPos = Down; break; } case Down : { if(key == SDLK_LEFT) m_img = m_southeast, m_currentPos = SouthEast; else m_img = m_southwest, m_currentPos = SouthWest; break; } case SouthWest : { if(key == SDLK_LEFT) m_img = m_down, m_currentPos = Down; else m_img = m_left, m_currentPos = Left; break; } default : break; } } template <typename T> bool isMoveAllowed (float x, float y, std::list<T*> &lists) { /* # On prepare les coordonnees des limites : limxg : limite x gauche, limxd : limite x droite, limyh : limite y haut, limyb : limite y bas */ float limxg = 0, limxd = 0, limyh = 0, limyb = 0; /* # On prepare les coordonnes du vehicule : vxg : x gauche, vxd : x droite, vyh : y haut, vyb : y bas */ float vxg = x, vxd = x + Game::getShapeSize(), vyh = y, vyb = y + Game::getShapeSize(); /* # On test si on est dans une limite le mouvement n'est pas autorisé */ for(typename std::list<T*>::iterator it = lists.begin(); it != lists.end();it++) { limxg = (*it)->getX(); limxd = (*it)->getX() + Game::getShapeSize(); limyh = (*it)->getY(); limyb = (*it)->getY() + Game::getShapeSize(); if(vxg < limxd && vxd > limxg && vyh < limyb && vyb > limyh) return false; } return true; } float PlayerCar::getWantedX(SDLKey key, float& fwdlatspeed, float& revlatspeed) { /* # Suivant la position actuelle notre deplacement s'affichera differement */ switch(key) { case SDLK_UP : { switch(m_currentPos) { case Left : return m_x - m_fwdspeed; break; case Right : return m_x + m_fwdspeed; break; case NorthWest: case SouthWest: return m_x - fwdlatspeed; break; case NorthEast : case SouthEast : return m_x + fwdlatspeed; break; } break; } case SDLK_DOWN : { switch(m_currentPos) { case Left : return m_x + m_revspeed; break; case Right : return m_x - m_revspeed; break; case NorthWest : case SouthWest : return m_x + revlatspeed; break; case SouthEast : case NorthEast : return m_x - revlatspeed; break; } break; } default : break; } return m_x; } float PlayerCar::getWantedY(SDLKey key, float& fwdlatspeed, float& revlatspeed) { /* # Suivant la position actuelle notre deplacement s'affichera differement */ switch(key) { case SDLK_UP : { switch(m_currentPos) { case Up : return m_y - m_fwdspeed; break; case Down : return m_y + m_fwdspeed; break; case NorthWest : case NorthEast : return m_y - fwdlatspeed; break; case SouthWest : case SouthEast : return m_y + fwdlatspeed; break; } break; } case SDLK_DOWN : { switch(m_currentPos) { case Up : return m_y + m_revspeed; break; case Down : return m_y - m_revspeed; break; case NorthWest : case NorthEast : return m_y + revlatspeed; break; case SouthEast : case SouthWest : return m_y - revlatspeed; break; } break; } default : break; } return m_y; } void PlayerCar::move(SDLKey key, std::list<Limit*> &limits, std::list<Flaque*> &flaques, std::list<IACar*> &iacars) { /* # On calcule les vecteurs de deplacement lateraux */ float fwdlatspeed = sqrt((m_fwdspeed*m_fwdspeed)/2.0), revlatspeed = sqrt((m_revspeed*m_revspeed)/2.0); /* # On prend les coordonnees souhaitees du vehicule -> vxg : vehicule x gauche, vxd : vehicule x droite, vyh : vehicule y haut, vyb : vehicule y bas */ float vxg = getWantedX(key,fwdlatspeed,revlatspeed), vxd = vxg + Game::getShapeSize(), vyh = getWantedY(key,fwdlatspeed,revlatspeed), vyb = vyh + Game::getShapeSize(); /* # On test si on roule dans une flaque */ m_flaque = !isMoveAllowed(vxg,vyh,flaques); /* # On test si on fonce dans une ia ou une limite */ m_blocked = !(isMoveAllowed(vxg,vyh,iacars) && isMoveAllowed(vxg,vyh,limits)); /* # Si on ne fonce pas dans une bordure on bouge le vehicule */ if(!m_blocked) m_x = vxg, m_y = vyh; } void PlayerCar::setTurboMode() { m_state = TurboMode; } void PlayerCar::setCollisionRecovering() { m_state = CollisionRecovering; } void PlayerCar::setFlaqueState() { m_state = FlaqueState; } void PlayerCar::setNormalState() { m_state = Normal; } void PlayerCar::setSpeed() { m_fwdspeed = getSpeed(); } float PlayerCar::getSpeed() { if(m_state == TurboMode) { return Game::getFwdSpeed() * 3; } else if(m_state == FlaqueState || m_state == CollisionRecovering) { return Game::getFwdSpeed() / 2; } else { return Game::getFwdSpeed(); } } bool PlayerCar::isBlocked() { return m_blocked; } bool PlayerCar::isFlaque() { return m_flaque; } bool PlayerCar::isTurbo() { return m_state == TurboMode; }
[ "axelscht@468702e1-5092-14fc-779a-dee4b53e0e13", "[email protected]@468702e1-5092-14fc-779a-dee4b53e0e13" ]
[ [ [ 1, 2 ], [ 4, 5 ], [ 7, 9 ], [ 12, 25 ], [ 38, 57 ], [ 60, 60 ], [ 62, 62 ], [ 70, 70 ], [ 77, 80 ], [ 87, 87 ], [ 90, 90 ], [ 92, 92 ], [ 97, 100 ], [ 102, 102 ], [ 107, 110 ], [ 117, 117 ], [ 120, 120 ], [ 122, 122 ], [ 130, 130 ], [ 137, 144 ], [ 147, 147 ], [ 158, 158 ], [ 171, 172 ], [ 174, 175 ], [ 177, 177 ], [ 179, 181 ], [ 183, 184 ], [ 188, 189 ], [ 193, 193 ], [ 220, 221 ], [ 227, 227 ], [ 279, 279 ], [ 294, 294 ], [ 304, 305 ], [ 307, 310 ], [ 331, 332 ], [ 345, 346 ], [ 358, 358 ], [ 360, 360 ] ], [ [ 3, 3 ], [ 6, 6 ], [ 10, 11 ], [ 26, 37 ], [ 58, 59 ], [ 61, 61 ], [ 63, 69 ], [ 71, 76 ], [ 81, 86 ], [ 88, 89 ], [ 91, 91 ], [ 93, 96 ], [ 101, 101 ], [ 103, 106 ], [ 111, 116 ], [ 118, 119 ], [ 121, 121 ], [ 123, 129 ], [ 131, 136 ], [ 145, 146 ], [ 148, 157 ], [ 159, 170 ], [ 173, 173 ], [ 176, 176 ], [ 178, 178 ], [ 182, 182 ], [ 185, 187 ], [ 190, 192 ], [ 194, 219 ], [ 222, 226 ], [ 228, 278 ], [ 280, 293 ], [ 295, 303 ], [ 306, 306 ], [ 311, 330 ], [ 333, 344 ], [ 347, 357 ], [ 359, 359 ] ] ]
6613bfec6d085984ab1650789a2f17d861192f85
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/ContentTools/Max/MaxFpInterfaces/ConversionUtil/hctConversionUtilGUPInterface.h
bbfa65d00d11d627aab330a9867d29df76afe3e3
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
2,373
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef INC_CONVERSIONUTILGUPINTERFACE #define INC_CONVERSIONUTILGUPINTERFACE #include <iFnPub.h> // Class ID #define HK_CONVERSION_UTIL_GUP_CLASS_ID Class_ID(0x5fcd3256, 0x46f60d66) /* ** FUNCTION PUBLISHING */ #define HK_CONVERSION_UTIL_GUP_FPINTERFACE_ID Interface_ID(0x32881fdd, 0x34e953ee) enum { FPI_ConvertSelectionToVertexChannel, FPI_ConvertVertexChannelToSelection, FPI_AssignVertexColors }; /* ** C++ Interface to the Havok Content Tools Conversion Utilities. ** ** Exposed to MAXScript as hctConversionUtilGUP ** ** The methods here correspond to the methods exposed to MaxScript. ** */ class hctConversionUtilGUPInterface : public FPStaticInterface { public: virtual void iConvertSelectionToVertexChannel( INode* selectedNode, ReferenceTarget* vpModifier, FLOAT selectedValue, FLOAT unselectedValue ) = 0; virtual void iConvertVertexChannelToSelection( INode* selectedNode, ReferenceTarget* vpModifier, FLOAT thresholdValue, BOOL invert, TCHAR* selectionName ) = 0; virtual void iAssignVertexColors( INode* selectedNode, ReferenceTarget* vpModifier, INT channelID, BOOL byVertex ) = 0; }; #endif //INC_CONVERSIONUTILGUPINTERFACE /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 62 ] ] ]
fa81b320a221613339d6b11c75114b5d6b46457d
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/calomega.h
6c263beaf74e10f2dfbdae6a97b64bb1d2b0f65f
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
564
h
class calomega_state : public driver_device { public: calomega_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } UINT8 m_tx_line; UINT8 m_rx_line; int m_s903_mux_data; int m_s905_mux_data; UINT8 *m_videoram; UINT8 *m_colorram; tilemap_t *m_bg_tilemap; }; /*----------- defined in video/calomega.c -----------*/ WRITE8_HANDLER( calomega_videoram_w ); WRITE8_HANDLER( calomega_colorram_w ); PALETTE_INIT( calomega ); VIDEO_START( calomega ); SCREEN_UPDATE( calomega );
[ "Mike@localhost" ]
[ [ [ 1, 23 ] ] ]
fd0ec1cd6b98fdb6d37151ddc4471214e18df5c0
974a20e0f85d6ac74c6d7e16be463565c637d135
/trunk/coreLibrary_200/contributions/hacd/src/HACD_Lib/inc/hacdManifoldMesh.h
f962a305542027d0c25e500b998ebeeeee827ea1
[]
no_license
Naddiseo/Newton-Dynamics-fork
cb0b8429943b9faca9a83126280aa4f2e6944f7f
91ac59c9687258c3e653f592c32a57b61dc62fb6
refs/heads/master
2021-01-15T13:45:04.651163
2011-11-12T04:02:33
2011-11-12T04:02:33
2,759,246
0
0
null
null
null
null
UTF-8
C++
false
false
11,183
h
/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com) 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 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com) 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 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #ifndef HACD_MANIFOLD_MESH_H #define HACD_MANIFOLD_MESH_H #include <iostream> #include <fstream> #include <hacdVersion.h> #include <hacdCircularList.h> #include <hacdVector.h> #include <set> namespace HACD { class TMMTriangle; class TMMEdge; class TMMesh; class ICHull; class HACD; class DPoint { public: DPoint(double dist=0.0, bool computed=false, bool distOnly=false) :m_dist(dist), m_computed(computed), m_distOnly(distOnly){}; ~DPoint(){}; private: double m_dist; bool m_computed; bool m_distOnly; friend class TMMTriangle; friend class TMMesh; friend class GraphVertex; friend class GraphEdge; friend class Graph; friend class ICHull; friend class HACD; }; //! Vertex data structure used in a triangular manifold mesh (TMM). class TMMVertex { public: TMMVertex(void); ~TMMVertex(void); private: Vec3<double> m_pos; long m_name; size_t m_id; CircularListElement<TMMEdge> * m_duplicate; // pointer to incident cone edge (or NULL) bool m_onHull; bool m_tag; TMMVertex(const TMMVertex & rhs); friend class HACD; friend class ICHull; friend class TMMesh; friend class TMMTriangle; friend class TMMEdge; }; //! Edge data structure used in a triangular manifold mesh (TMM). class TMMEdge { public: TMMEdge(void); ~TMMEdge(void); private: size_t m_id; CircularListElement<TMMTriangle> * m_triangles[2]; CircularListElement<TMMVertex> * m_vertices[2]; CircularListElement<TMMTriangle> * m_newFace; TMMEdge(const TMMEdge & rhs); friend class HACD; friend class ICHull; friend class TMMTriangle; friend class TMMVertex; friend class TMMesh; }; //! Triangle data structure used in a triangular manifold mesh (TMM). class TMMTriangle { public: TMMTriangle(void); ~TMMTriangle(void); private: size_t m_id; CircularListElement<TMMEdge> * m_edges[3]; CircularListElement<TMMVertex> * m_vertices[3]; bool m_visible; std::set<long> m_incidentPoints; TMMTriangle(const TMMTriangle & rhs); friend class HACD; friend class ICHull; friend class TMMesh; friend class TMMVertex; friend class TMMEdge; }; class Material { public: Material(void); ~Material(void){} // private: Vec3<double> m_diffuseColor; double m_ambientIntensity; Vec3<double> m_specularColor; Vec3<double> m_emissiveColor; double m_shininess; double m_transparency; friend class TMMesh; friend class HACD; }; //! triangular manifold mesh data structure. class TMMesh { public: //! Returns the number of vertices> inline size_t GetNVertices() const { return m_vertices.GetSize();} //! Returns the number of edges inline size_t GetNEdges() const { return m_edges.GetSize();} //! Returns the number of triangles inline size_t GetNTriangles() const { return m_triangles.GetSize();} //! Returns the vertices circular list inline const CircularList<TMMVertex> & GetVertices() const { return m_vertices;} //! Returns the edges circular list inline const CircularList<TMMEdge> & GetEdges() const { return m_edges;} //! Returns the triangles circular list inline const CircularList<TMMTriangle> & GetTriangles() const { return m_triangles;} //! Returns the vertices circular list inline CircularList<TMMVertex> & GetVertices() { return m_vertices;} //! Returns the edges circular list inline CircularList<TMMEdge> & GetEdges() { return m_edges;} //! Returns the triangles circular list inline CircularList<TMMTriangle> & GetTriangles() { return m_triangles;} //! Add vertex to the mesh CircularListElement<TMMVertex> * AddVertex() {return m_vertices.Add();} //! Add vertex to the mesh CircularListElement<TMMEdge> * AddEdge() {return m_edges.Add();} //! Add vertex to the mesh CircularListElement<TMMTriangle> * AddTriangle() {return m_triangles.Add();} //! Print mesh information void Print(); //! void GetIFS(Vec3<double> * const points, Vec3<long> * const triangles); //! Save mesh bool Save(const char *fileName); //! Save mesh to VRML 2.0 format bool SaveVRML2(std::ofstream &fout); //! Save mesh to VRML 2.0 format bool SaveVRML2(std::ofstream &fout, const Material & material); //! void Clear(); //! void Copy(TMMesh & mesh); //! bool CheckConsistancy(); //! bool Normalize(); //! bool Denormalize(); //! Constructor TMMesh(void); //! Destructor virtual ~TMMesh(void); private: CircularList<TMMVertex> m_vertices; CircularList<TMMEdge> m_edges; CircularList<TMMTriangle> m_triangles; double m_diag; //>! length of the BB diagonal Vec3<double> m_barycenter; //>! barycenter of the mesh // not defined TMMesh(const TMMesh & rhs); friend class ICHull; friend class HACD; }; //! IntersectRayTriangle(): intersect a ray with a 3D triangle //! Input: a ray R, and a triangle T //! Output: *I = intersection point (when it exists) //! 0 = disjoint (no intersect) //! 1 = intersect in unique point I1 long IntersectRayTriangle( const Vec3<double> & P0, const Vec3<double> & dir, const Vec3<double> & V0, const Vec3<double> & V1, const Vec3<double> & V2, double &t); /* Calculate the line segment PaPb that is the shortest route between two lines P1P2 and P3P4. Calculate also the values of mua and mub where Pa = P1 + mua (P2 - P1) Pb = P3 + mub (P4 - P3) Return FALSE if no solution exists. */ bool IntersectLineLine(const Vec3<double> & p1, const Vec3<double> & p2, const Vec3<double> & p3, const Vec3<double> & p4, Vec3<double> & pa, Vec3<double> & pb, double & mua, double &mub); } #endif
[ "[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692" ]
[ [ [ 1, 238 ] ] ]
0112847587f2ad0eecfaa960251df2af231f64d9
979e53d80e9389bc8b750743a19651764f5c25bd
/baseport/syborg/pointer/syborg_pointer.cpp
348d1073aaf7469185fe0721ad0d0ded78e8b339
[]
no_license
SymbianSource/oss.FCL.interim.QEMU
a46ab50b3c1783fbbbe21119d6ebb3268542d8c1
27314f44d508ef89270ca0f43a24a0e5e7fc047b
refs/heads/master
2021-01-19T06:46:29.018585
2010-05-17T17:37:02
2010-05-17T17:37:02
65,377,884
1
1
null
null
null
null
UTF-8
C++
false
false
9,649
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Minimalistic pointer driver * */ //#define DEBUG #include <syborg_priv.h> #include "syborg_pointer.h" _LIT(KPointerDfcQNamePre,"PointDFC"); const TInt KDfcQuePriority = 27; TPointerRv::TPointerRv() //sosco : // iRxDfc(RxDfc,this,Kern::DfcQue0(),1) { __DEBUG_PRINT("TPointerRv::TPointerRv()"); TInt err = Kern::DfcQInit(&iDfcQue, KDfcQuePriority, &KPointerDfcQNamePre); if (err) { __KTRACE_OPT(KPANIC, Kern::Printf("TPointerRv::TPointerRv() Error creating dfcq (%d)", err)); } iRxDfc = new TDfc(RxDfc,this,&iDfcQue,1); __ASSERT_ALWAYS(iRxDfc!=NULL,Kern::Printf("Failed to create DFC")); TInt r = Interrupt::Bind(EIntPointer,Isr,this); if(r != KErrNone) __KTRACE_OPT(KPANIC, Kern::Printf("TPointerRv::TPointerRv() Interrupt::Bind(%d)=%d", EIntPointer, r)); iPointerOn = ETrue; iLastBut = 0; Interrupt::Enable(EIntPointer); } TPointerRv::~TPointerRv() { } struct TPointerRv::PData* TPointerRv::FifoPop(void) { struct TPointerRv::PData* val = &iPDataFifo[iFifoPos]; iFifoPos++; iFifoCount--; if (iFifoPos == FIFO_SIZE) iFifoPos = 0; return val; } void TPointerRv::FifoPush(struct TPointerRv::PData* val) { TInt slot; if (iFifoCount == FIFO_SIZE) return; slot = iFifoPos + iFifoCount; if (slot >= FIFO_SIZE) slot -= FIFO_SIZE; iPDataFifo[slot] = *val; iFifoCount++; // __DEBUG_PRINT("TPointerRv::FifoPush %d %d %d %d",val->x, val->y, val->z, val->but); // __DEBUG_PRINT("TPointerRv::FifoPush %d %d %d %d",iPDataFifo[slot].x, iPDataFifo[slot].y, iPDataFifo[slot].z, iPDataFifo[slot].but); } void TPointerRv::Init3() { __DEBUG_PRINT("TPointerRv::Init3"); TInt reg = ReadReg(KHwBaseKmiPointer,POINTER_ID); WriteReg(KHwBaseKmiPointer,POINTER_INT_ENABLE,1); TInt r = Kern::AddHalEntry(EHalGroupMouse,DoPointerHalFunction,this); if(r != KErrNone) __KTRACE_OPT(KPANIC, Kern::Printf("TPointerRv::Init3(): Kern::AddHalEntry()=%d", r)); // Get information about the screen display mode TPckgBuf<TVideoInfoV01> buf; TVideoInfoV01& videoInfo = buf(); r = Kern::HalFunction(EHalGroupDisplay, EDisplayHalCurrentModeInfo, (TAny*)&buf, NULL); if(r != KErrNone) __KTRACE_OPT(KPANIC, Kern::Printf("TPointerRv::Init3(): Kern::HalFunction(EDisplayHalCurrentModeInfo)=%d", r)); iScreenWidth = videoInfo.iSizeInPixels.iWidth; iScreenHeight = videoInfo.iSizeInPixels.iHeight; iDisplayMode = videoInfo.iDisplayMode; iVideoMem = videoInfo.iVideoAddress + videoInfo.iOffsetToFirstPixel; iOffSetBetweenEachLine = 640; ix = iy = 0; iXFactor = Fixed(iScreenWidth) / Fixed(0x8000); iYFactor = Fixed(iScreenHeight) / Fixed(0x8000); iFifoPos = iFifoCount = 0; iFirstTime= ETrue; } void TPointerRv::Process(TPointerRv *i, struct TPointerRv::PData *pd) { TRawEvent e; // __DEBUG_PRINT("Event: X=%d Y=%d Point %d", pd->x, pd->y, pd->but); // __DEBUG_PRINT(" Last X=%d Y=%d Point %d", i->ix, i->iy, i->iLastBut); // i->ix += pd->x; // i->iy += pd->y; i->ix = int(Fixed(pd->x) * i->iXFactor); i->iy = int(Fixed(pd->y) * i->iYFactor); switch(pd->but) { case 0: // Button released switch(i->iLastBut) { case 0: if( (pd->x!=0) || (pd->y!=0) ) { e.Set(TRawEvent::EPointerMove, i->ix, i->iy); __DEBUG_PRINT("1 EPointerMove (x:%d y:%d)", i->ix, i->iy); } goto fin; case 1: // Left e.Set(TRawEvent::EButton1Up, i->ix, i->iy); __DEBUG_PRINT("2 EButton1UP (x:%d y:%d)", i->ix, i->iy); goto fin; case 2: // Right e.Set(TRawEvent::EButton2Up, i->ix, i->iy); __DEBUG_PRINT("3 EButton2UP (x:%d y:%d)", i->ix, i->iy); goto fin; } case 1: // Left if (i->iLastBut == 0) { e.Set(TRawEvent::EButton1Down, i->ix, i->iy); __DEBUG_PRINT("4 EButton1Down (x:%d y:%d)", i->ix, i->iy); } else if( (pd->x!=0) || (pd->y!=0) ) { e.Set(TRawEvent::EPointerMove, i->ix, i->iy); __DEBUG_PRINT("5 EPointerMove (x:%d y:%d)", i->ix, i->iy); } break; case 2: // Right if (i->iLastBut == 0) { e.Set(TRawEvent::EButton2Down, i->ix, i->iy); __DEBUG_PRINT("6 EButton2Down (x:%d y:%d)", i->ix, i->iy); } else if( (pd->x!=0) || (pd->y!=0) ) { e.Set(TRawEvent::EPointerMove, i->ix, i->iy); __DEBUG_PRINT("7 EPointerMove (x:%d y:%d)", i->ix, i->iy); } break; } fin: // i->DisplayPointer(); Kern::AddEvent(e); i->iLastBut = pd->but; } void TPointerRv::DisplayPointer() { TUint32 *pMem =0; TInt k=0; if(!iFirstTime) { //restore old pointer position pMem = (TUint32 *)iVideoMem; pMem+= iYtop* iOffSetBetweenEachLine; pMem+= iXleft; for(TInt i=0;i<(iYbottom-iYtop);i++) { for(TInt j=0;j<(iXright-iXleft);j++) { *pMem = iImageStore[k]; pMem++; k++; } pMem+= (iOffSetBetweenEachLine - iXright) + iXleft; } } iFirstTime = EFalse; //10*10 pixel pointer centered around position and check are within allowed bounds of screen iXleft = ix - 5; if(iXleft<0) iXleft=0; iXright = ix + 5; if(iXright>iScreenWidth) iXright = iScreenWidth; iYtop = iy - 5; if(iYtop<0) iYtop=0; iYbottom = iy +5; if(iYbottom> iScreenHeight) iYbottom=iScreenHeight; pMem = (TUint32 *)iVideoMem; k=0; pMem+= iYtop* iOffSetBetweenEachLine; pMem+= iXleft; for(TInt i=0;i<(iYbottom-iYtop);i++) { for(TInt j=0;j<(iXright-iXleft);j++) { iImageStore[k] = *pMem; *pMem = 0; pMem++; k++; } pMem+= (iOffSetBetweenEachLine - iXright) + iXleft; } } void TPointerRv::RxDfc(TAny* aPtr) { __DEBUG_PRINT("TPointerRv::RxDfc"); TPointerRv* i = static_cast<TPointerRv*>(aPtr); while(i->iFifoCount>0) { struct TPointerRv::PData *pd= i->FifoPop(); Process(i,pd); } } void TPointerRv::Isr(TAny* aPtr) { __DEBUG_PRINT("TPointerRv::Isr"); TPointerRv& k = *(TPointerRv*)aPtr; // interrupts are now auto clear while(ReadReg(KHwBaseKmiPointer, POINTER_FIFO_COUNT)!=0) { WriteReg(KHwBaseKmiPointer,POINTER_LATCH,1); // SOSCO: moved to here, as the buffer seems to be running one notch out, // writing to the pointer latch first seems to return the correct FIFO entry. struct TPointerRv::PData pd; pd.x = ReadReg(KHwBaseKmiPointer,POINTER_X); pd.y = ReadReg(KHwBaseKmiPointer,POINTER_Y); pd.z = ReadReg(KHwBaseKmiPointer,POINTER_Z); pd.but = ReadReg(KHwBaseKmiPointer,POINTER_BUTTONS); k.FifoPush(&pd); // SOSCO - moved WriteReg(KHwBaseKmiPointer,POINTER_LATCH,1); } // WriteReg(KHwBaseKmiPointer,POINTER_CLEAR_INT,0); Interrupt::Clear(EIntPointer); k.iRxDfc->Add(); } TInt TPointerRv::DoPointerHalFunction(TAny* aThis, TInt aFunction, TAny* a1, TAny* a2) { return static_cast<TPointerRv*>(aThis)->PointerHalFunction(aFunction,a1,a2); } TInt TPointerRv::PointerHalFunction(TInt aFunction, TAny* a1, TAny* /*a2*/) { __DEBUG_PRINT("TPointerRv::PointerHalFunction"); TInt r=KErrNone; switch(aFunction) { case EMouseHalMouseState: { kumemput32(a1, (TBool*)&iPointerOn, sizeof(TBool)); break; } case EMouseHalSetMouseState: { /* SOSCO - removed, causes platsec error __SECURE_KERNEL( if(!Kern::CurrentThreadHasCapability(ECapabilityMultimediaDD, __PLATSEC_DIAGNOSTIC_STRING("Checked by Hal function EMouseHalSetMouseState"))) return KErrPermissionDenied; ); */ if(((TBool)a1 == HAL::EMouseState_Visible) && (iPointerOn == (TBool)EFalse)) { iPointerOn=(TBool)ETrue; } else if(((TBool)a1 == HAL::EMouseState_Invisible) && (iPointerOn==(TBool)ETrue)) { iPointerOn=(TBool)EFalse; } break; } case EMouseHalMouseInfo: { TPckgBuf<TMouseInfoV01> vPckg; TMouseInfoV01& xyinfo = vPckg(); xyinfo.iMouseButtons = 2; xyinfo.iMouseAreaSize.iWidth = iScreenWidth; xyinfo.iMouseAreaSize.iHeight = iScreenHeight; xyinfo.iOffsetToDisplay.iX = 0; xyinfo.iOffsetToDisplay.iY = 0; Kern::InfoCopy(*(TDes8*)a1,vPckg); break; } case EMouseHalSetMouseSpeed: { /* SOSCO - removed, causes platsec error __SECURE_KERNEL( if(!Kern::CurrentThreadHasCapability(ECapabilityMultimediaDD, __PLATSEC_DIAGNOSTIC_STRING("Checked by Hal function EMouseHalSetMouseSpeed"))) return KErrPermissionDenied; ); */ // fall thru to NotSupported } case EMouseHalSetMouseAcceleration: { /* SOSCO - removed, causes platsec error __SECURE_KERNEL( if(!Kern::CurrentThreadHasCapability(ECapabilityMultimediaDD, __PLATSEC_DIAGNOSTIC_STRING("Checked by Hal function EMouseHalSetMouseAcceleration"))) return KErrPermissionDenied; ); */ // fall thru to NotSupported } default: { r = KErrNotSupported; break; } } return r; } DECLARE_STANDARD_EXTENSION() { __DEBUG_PRINT("DECLARE_STANDARD_EXTENSION"); TPointerRv *d = new TPointerRv; d->Init3(); return KErrNone; }
[ [ [ 1, 409 ] ] ]
37f95c7a37eeb078b132376126b969115e1f30fd
5dc6c87a7e6459ef8e832774faa4b5ae4363da99
/vis_avs/rlib.cpp
d85063d51b671947702c1759e3119524d4f6e77d
[]
no_license
aidinabedi/avs4unity
407603d2fc44bc8b075b54cd0a808250582ee077
9b6327db1d092218e96d8907bd14d68b741dcc4d
refs/heads/master
2021-01-20T15:27:32.449282
2010-12-24T03:28:09
2010-12-24T03:28:09
90,773,183
5
2
null
null
null
null
UTF-8
C++
false
false
12,202
cpp
/* LICENSE ------- Copyright 2005 Nullsoft, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Nullsoft nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <windows.h> #include "r_defs.h" #include "r_unkn.h" #include "r_list.h" #include "rlib.h" #include "ape.h" #include "avs_eelif.h" #define PUT_INT(y) data[pos]=(y)&255; data[pos+1]=(y>>8)&255; data[pos+2]=(y>>16)&255; data[pos+3]=(y>>24)&255 #define GET_INT() (data[pos]|(data[pos+1]<<8)|(data[pos+2]<<16)|(data[pos+3]<<24)) void C_RBASE::load_string(RString &s,unsigned char *data, int &pos, int len) // read configuration of max length "len" from data. { int size=GET_INT(); pos += 4; if (size > 0 && len-pos >= size) { s.resize(size); memcpy(s.get(), data+pos, size); pos+=size; } else { s.resize(1); s.get()[0]=0; } } void C_RBASE::save_string(unsigned char *data, int &pos, RString &text) { if (text.get() && text.get()[0]) { char *p=text.get(); int x=32768; while (x-- && *p) p++; if (*p) { MessageBox(NULL,"Yo, this is some long ass shit","FUCK!",MB_OK); //FUCKO } int l=(strlen(text.get())+1); PUT_INT(l); pos+=4; memcpy(data+pos, text.get(), strlen(text.get())+1); pos+=strlen(text.get())+1; } else { PUT_INT(0); pos+=4; } } void C_RLibrary::add_dofx(void *rf, int has_r2) { if ((NumRetrFuncs&7)==0||!RetrFuncs) { void *newdl=(void *)GlobalAlloc(GMEM_FIXED,sizeof(rfStruct)*(NumRetrFuncs+8)); if (!newdl) { MessageBox(NULL,"Out of memory","AVS Critical Error",MB_OK); ExitProcess(0); } memset(newdl,0,sizeof(rfStruct)*(NumRetrFuncs+8)); if (RetrFuncs) { memcpy(newdl,RetrFuncs,NumRetrFuncs*sizeof(rfStruct)); GlobalFree(RetrFuncs); } RetrFuncs=(rfStruct*)newdl; } RetrFuncs[NumRetrFuncs].is_r2=has_r2; *((void**)&RetrFuncs[NumRetrFuncs].rf) = rf; NumRetrFuncs++; } // declarations for built-in effects #define DECLARE_EFFECT(name) extern C_RBASE *(name)(char *desc); add_dofx((void*)name,0); #define DECLARE_EFFECT2(name) extern C_RBASE *(name)(char *desc); add_dofx((void*)name,1); void C_RLibrary::initfx(void) { DECLARE_EFFECT(R_SimpleSpectrum); DECLARE_EFFECT(R_DotPlane); DECLARE_EFFECT(R_OscStars); DECLARE_EFFECT(R_FadeOut); DECLARE_EFFECT(R_BlitterFB); DECLARE_EFFECT(R_NFClear); DECLARE_EFFECT2(R_Blur); DECLARE_EFFECT(R_BSpin); DECLARE_EFFECT(R_Parts); DECLARE_EFFECT(R_RotBlit); DECLARE_EFFECT(R_SVP); DECLARE_EFFECT2(R_ColorFade); DECLARE_EFFECT(R_ContrastEnhance); DECLARE_EFFECT(R_RotStar); DECLARE_EFFECT(R_OscRings); DECLARE_EFFECT2(R_Trans); DECLARE_EFFECT(R_Scat); DECLARE_EFFECT(R_DotGrid); DECLARE_EFFECT(R_Stack); DECLARE_EFFECT(R_DotFountain); DECLARE_EFFECT2(R_Water); DECLARE_EFFECT(R_Comment); DECLARE_EFFECT2(R_Brightness); DECLARE_EFFECT(R_Interleave); DECLARE_EFFECT(R_Grain); DECLARE_EFFECT(R_Clear); DECLARE_EFFECT(R_Mirror); DECLARE_EFFECT(R_StarField); DECLARE_EFFECT(R_Text); DECLARE_EFFECT(R_Bump); DECLARE_EFFECT(R_Mosaic); DECLARE_EFFECT(R_WaterBump); DECLARE_EFFECT(R_AVI); DECLARE_EFFECT(R_Bpm); DECLARE_EFFECT(R_Picture); DECLARE_EFFECT(R_DDM); DECLARE_EFFECT(R_SScope); DECLARE_EFFECT(R_Invert); DECLARE_EFFECT(R_Onetone); DECLARE_EFFECT(R_Timescope); DECLARE_EFFECT(R_LineMode); DECLARE_EFFECT(R_Interferences); DECLARE_EFFECT(R_Shift); DECLARE_EFFECT2(R_DMove); DECLARE_EFFECT(R_FastBright); DECLARE_EFFECT(R_DColorMod); } static const struct { char id[33]; int newidx; } NamedApeToBuiltinTrans[] = { {"Winamp Brightness APE v1", 22}, {"Winamp Interleave APE v1", 23}, {"Winamp Grain APE v1", 24 }, {"Winamp ClearScreen APE v1", 25}, {"Nullsoft MIRROR v1", 26}, {"Winamp Starfield v1", 27}, {"Winamp Text v1", 28 }, {"Winamp Bump v1", 29 }, {"Winamp Mosaic v1", 30 }, {"Winamp AVIAPE v1", 32}, {"Nullsoft Picture Rendering v1", 34}, {"Winamp Interf APE v1", 41} }; void C_RLibrary::initbuiltinape(void) { #define ADD(sym) extern C_RBASE * sym(char *desc); _add_dll(0,sym,"Builtin_" #sym, 0) #define ADD2(sym,name) extern C_RBASE * sym(char *desc); _add_dll(0,sym,name, 0) #ifdef LASER ADD(RLASER_Cone); ADD(RLASER_BeatHold); ADD(RLASER_Line); ADD(RLASER_Bren); // not including it for now ADD(RLASER_Transform); #else ADD2(R_ChannelShift,"Channel Shift"); ADD2(R_ColorReduction,"Color Reduction"); ADD2(R_Multiplier,"Multiplier"); ADD2(R_VideoDelay,"Holden04: Video Delay"); ADD2(R_MultiDelay,"Holden05: Multi Delay"); #endif #undef ADD #undef ADD2 } void C_RLibrary::_add_dll(HINSTANCE hlib,class C_RBASE *(__cdecl *cre)(char *),char *inf, int is_r2) { if ((NumDLLFuncs&7)==0||!DLLFuncs) { DLLInfo *newdl=(DLLInfo *)GlobalAlloc(GMEM_FIXED,sizeof(DLLInfo)*(NumDLLFuncs+8)); if (!newdl) { MessageBox(NULL,"Out of memory","AVS Critical Error",MB_OK); ExitProcess(0); } memset(newdl,0,sizeof(DLLInfo)*(NumDLLFuncs+8)); if (DLLFuncs) { memcpy(newdl,DLLFuncs,NumDLLFuncs*sizeof(DLLInfo)); GlobalFree(DLLFuncs); } DLLFuncs=newdl; } DLLFuncs[NumDLLFuncs].hDllInstance=hlib; DLLFuncs[NumDLLFuncs].createfunc=cre; DLLFuncs[NumDLLFuncs].idstring=inf; DLLFuncs[NumDLLFuncs].is_r2=is_r2; NumDLLFuncs++; } static APEinfo ext_info= { 3, 0, &g_line_blend_mode, NSEEL_VM_alloc, AVS_EEL_IF_VM_free, AVS_EEL_IF_resetvars, NSEEL_VM_regvar, NSEEL_code_compile, AVS_EEL_IF_Execute, NSEEL_code_free, NULL, getGlobalBuffer, }; void C_RLibrary::initdll() { ext_info.global_registers=NSEEL_getglobalregs(); HANDLE h; WIN32_FIND_DATA d; char dirmask[MAX_PATH*2]; #ifdef LASER wsprintf(dirmask,"%s\\*.lpe",g_path); #else wsprintf(dirmask,"%s\\*.ape",g_path); #endif h = FindFirstFile(dirmask,&d); if (h != INVALID_HANDLE_VALUE) { do { char s[MAX_PATH]; HINSTANCE hlib; wsprintf(s,"%s\\%s",g_path,d.cFileName); hlib=LoadLibrary(s); if (hlib) { int cre; char *inf; void (*sei)(HINSTANCE hDllInstance, APEinfo *ptr); *(void**)&sei = (void *) GetProcAddress(hlib,"_AVS_APE_SetExtInfo"); if (sei) sei(hlib,&ext_info); #ifdef LASER int (*retr)(HINSTANCE hDllInstance, char **info, int *create, C_LineListBase *linelist); retr = (int (*)(HINSTANCE, char ** ,int *, C_LineListBase*)) GetProcAddress(hlib,"_AVS_LPE_RetrFunc"); if (retr && retr(hlib,&inf,&cre,g_laser_linelist)) { _add_dll(hlib,(class C_RBASE *(__cdecl *)(char *))cre,inf,0); } else FreeLibrary(hlib); #else int (*retr)(HINSTANCE hDllInstance, char **info, int *create); retr = (int (*)(HINSTANCE, char ** ,int *)) GetProcAddress(hlib,"_AVS_APE_RetrFuncEXT2"); if (retr && retr(hlib,&inf,&cre)) { _add_dll(hlib,(class C_RBASE *(__cdecl *)(char *))cre,inf,1); } else { retr = (int (*)(HINSTANCE, char ** ,int *)) GetProcAddress(hlib,"_AVS_APE_RetrFunc"); if (retr && retr(hlib,&inf,&cre)) { _add_dll(hlib,(class C_RBASE *(__cdecl *)(char *))cre,inf,0); } else FreeLibrary(hlib); } #endif } } while (FindNextFile(h,&d)); FindClose(h); } } int C_RLibrary::GetRendererDesc(int which, char *str) { *str=0; if (which >= 0 && which < NumRetrFuncs) { RetrFuncs[which].rf(str); return 1; } if (which >= DLLRENDERBASE) { which-=DLLRENDERBASE; if (which < NumDLLFuncs) { DLLFuncs[which].createfunc(str); return (int)DLLFuncs[which].idstring; } } return 0; } C_RBASE *C_RLibrary::CreateRenderer(int *which, int *has_r2) { if (has_r2) *has_r2=0; if (*which >= 0 && *which < NumRetrFuncs) { if (has_r2) *has_r2 = RetrFuncs[*which].is_r2; return RetrFuncs[*which].rf(NULL); } if (*which == LIST_ID) return (C_RBASE *) new C_RenderListClass(); if (*which >= DLLRENDERBASE) { int x; char *p=(char *)*which; for (x = 0; x < NumDLLFuncs; x ++) { if (!DLLFuncs[x].createfunc) break; if (DLLFuncs[x].idstring) { if (!strncmp(p,DLLFuncs[x].idstring,32)) { *which=(int)DLLFuncs[x].idstring; return DLLFuncs[x].createfunc(NULL); } } } for (x = 0; x < sizeof(NamedApeToBuiltinTrans)/sizeof(NamedApeToBuiltinTrans[0]); x ++) { if (!strncmp(p,NamedApeToBuiltinTrans[x].id,32)) { *which=NamedApeToBuiltinTrans[x].newidx; if (has_r2) *has_r2 = RetrFuncs[*which].is_r2; return RetrFuncs[*which].rf(NULL); } } } int r=*which; *which=UNKN_ID; C_UnknClass *p=new C_UnknClass(); p->SetID(r,(r >= DLLRENDERBASE)?(char*)r:""); return (C_RBASE *)p; } C_RLibrary::C_RLibrary() { DLLFuncs=NULL; NumDLLFuncs=0; RetrFuncs=0; NumRetrFuncs=0; initfx(); initdll(); initbuiltinape(); } C_RLibrary::~C_RLibrary() { if (RetrFuncs) GlobalFree(RetrFuncs); RetrFuncs=0; NumRetrFuncs=0; if (DLLFuncs) { int x; for (x = 0; x < NumDLLFuncs; x ++) { if (DLLFuncs[x].hDllInstance) FreeLibrary(DLLFuncs[x].hDllInstance); } GlobalFree(DLLFuncs); } DLLFuncs=NULL; NumDLLFuncs=0; } HINSTANCE C_RLibrary::GetRendererInstance(int which, HINSTANCE hThisInstance) { if (which < DLLRENDERBASE || which == UNKN_ID || which == LIST_ID) return hThisInstance; int x; char *p=(char *)which; for (x = 0; x < NumDLLFuncs; x ++) { if (DLLFuncs[x].idstring) { if (!strncmp(p,DLLFuncs[x].idstring,32)) { if (DLLFuncs[x].hDllInstance) return DLLFuncs[x].hDllInstance; break; } } } return hThisInstance; } void *g_n_buffers[NBUF]; int g_n_buffers_w[NBUF],g_n_buffers_h[NBUF]; void *getGlobalBuffer(int w, int h, int n, int do_alloc) { if (n < 0 || n >= NBUF) return 0; if (!g_n_buffers[n] || g_n_buffers_w[n] != w || g_n_buffers_h[n] != h) { if (g_n_buffers[n]) GlobalFree(g_n_buffers[n]); if (do_alloc) { g_n_buffers_w[n]=w; g_n_buffers_h[n]=h; return g_n_buffers[n]=GlobalAlloc(GPTR,sizeof(int)*w*h); } g_n_buffers[n]=NULL; g_n_buffers_w[n]=0; g_n_buffers_h[n]=0; return 0; } return g_n_buffers[n]; }
[ [ [ 1, 452 ] ] ]
9c01a1d56a5468bf1e1329acb97e6b35ba01d2d4
299a1b0fca9e1de3858a5ebeaf63be6dc3a02b48
/tags/ic2005demo/ic2005/src/system/System.cpp
32b2c388352f0d4a8d604a20e1fe8456ed74d8bf
[]
no_license
BackupTheBerlios/dingus-svn
331d7546a6e7a5a3cb38ffb106e57b224efbf5df
1223efcf4c2079f58860d7fa685fa5ded8f24f32
refs/heads/master
2016-09-05T22:15:57.658243
2006-09-02T10:10:47
2006-09-02T10:10:47
40,673,143
0
0
null
null
null
null
UTF-8
C++
false
false
4,355
cpp
#include "stdafx.h" #include "System.h" #include <dingus/lua/LuaSingleton.h> #include <dingus/gfx/gui/Gui.h> #include <dingus/gfx/geometry/DynamicVBManager.h> #include <dingus/gfx/geometry/DynamicIBManager.h> #include <dingus/console/W32StdConsoleRenderingContext.h> #include <dingus/console/WDebugConsoleRenderingContext.h> #include <dingus/input/DIKeyboard.h> #include <dingus/input/DIMouse.h> const bool DEV_MODE = false; SAppStartupParams CSystem::getStartupParams() { SAppStartupParams sp; sp.windowTitle = "in.out.side: the shell"; sp.dataPath = "data/"; sp.windowWidth = 640; sp.windowHeight = 480; sp.minColorBits = 8; sp.minAlphaBits = 8; sp.minZBits = 16; sp.minStencilBits = 0; sp.usesZBuffer = true; sp.startFullscreen = !DEV_MODE; sp.showCursorFullscreen = true; sp.vsyncFullscreen = !DEV_MODE; sp.debugTimer = false; sp.selectDeviceAtStartup = !DEV_MODE; return sp; } IConsoleRenderingContext* CSystem::createStdConsoleCtx( HWND hwnd ) { if( DEV_MODE ) return new CW32StdConsoleRenderingContext(); else return NULL; } void CSystem::setupBundles( const std::string& dataPath, dingus::CReloadableBundleManager& reloadManager ) { CLuaSingleton::init( "" ); CTextureBundle::getInstance().addDirectory( dataPath + "tex/" ); CCubeTextureBundle::getInstance().addDirectory( dataPath + "tex/" ); CMeshBundle::getInstance().addDirectory( dataPath + "mesh/" ); CSkeletonInfoBundle::getInstance().addDirectory( dataPath + "mesh/" ); CEffectBundle::getInstance().addDirectory( dataPath + "fx/" ); CAnimationBundle::getInstance().addDirectory( dataPath + "anim/" ); CModelDescBundle::getInstance().addDirectory( dataPath + "model/" ); CDynamicVBManager::initialize( 3 * 1024 * 1024 ); CDynamicVBManager& vbManager = CDynamicVBManager::getInstance(); CDynamicIBManager::initialize( (1024+512) * 1024 ); CDynamicIBManager& ibManager = CDynamicIBManager::getInstance(); // // device dependant resources CDeviceResourceManager& deviceManager = CDeviceResourceManager::getInstance(); deviceManager.addListener( CVertexDeclBundle::getInstance() ); deviceManager.addListener( CSharedTextureBundle::getInstance() ); deviceManager.addListener( CSharedSurfaceBundle::getInstance() ); deviceManager.addListener( vbManager ); deviceManager.addListener( ibManager ); deviceManager.addListener( CTextureBundle::getInstance() ); deviceManager.addListener( CCubeTextureBundle::getInstance() ); deviceManager.addListener( CSharedMeshBundle::getInstance() ); deviceManager.addListener( CMeshBundle::getInstance() ); deviceManager.addListener( CSkinMeshBundle::getInstance() ); deviceManager.addListener( CEffectBundle::getInstance() ); deviceManager.addListener( CIndexBufferBundle::getInstance() ); CUIResourceManager::initialize( GUI_X, GUI_Y ); deviceManager.addListener( CUIResourceManager::getInstance() ); } void CSystem::setupContexts( HWND hwnd ) { mHwnd = hwnd; // renderer assert( !G_RENDERCTX ); G_RENDERCTX = new CRenderContext( *RGET_FX("lib/global") ); // input devices assert( !G_INPUTCTX ); G_INPUTCTX = new CInputContext(); HRESULT hr; IDirectInput8* directInput8 = NULL; hr = DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&directInput8, NULL ); assert( SUCCEEDED( hr ) ); assert( directInput8 ); G_INPUTCTX->addDevice( *(new CDIKeyboard(hwnd,*directInput8)) ); G_INPUTCTX->addDevice( *(new CDIMouse(hwnd,*directInput8)) ); } void CSystem::destroyContexts() { assert( G_RENDERCTX ); safeDelete( G_RENDERCTX ); assert( G_INPUTCTX ); stl_utils::wipe( G_INPUTCTX->getDevices() ); safeDelete( G_INPUTCTX ); } void CSystem::destroyBundles() { CDynamicVBManager::finalize(); CDynamicIBManager::finalize(); CAnimationBundle::finalize(); CCubeTextureBundle::finalize(); CEffectBundle::finalize(); CIndexBufferBundle::finalize(); CMeshBundle::finalize(); CSkinMeshBundle::finalize(); CModelDescBundle::finalize(); CSharedMeshBundle::finalize(); CSharedTextureBundle::finalize(); CSharedSurfaceBundle::finalize(); CSkeletonInfoBundle::finalize(); CTextureBundle::finalize(); CVertexDeclBundle::finalize(); CLuaSingleton::finalize(); CUIResourceManager::finalize(); }
[ "nearaz@73827abb-88f4-0310-91e6-a2b8c1a3e93d" ]
[ [ [ 1, 139 ] ] ]
834ea977a6e7933b985c0fffb48ec39255ccd371
95a3e8914ddc6be5098ff5bc380305f3c5bcecb2
/src/FusionForever_lib/Deterer.cpp
3330889059c2e3a70f327f529a02afe833fb3d27
[]
no_license
danishcake/FusionForever
8fc3b1a33ac47177666e6ada9d9d19df9fc13784
186d1426fe6b3732a49dfc8b60eb946d62aa0e3b
refs/heads/master
2016-09-05T16:16:02.040635
2010-04-24T11:05:10
2010-04-24T11:05:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,057
cpp
#include "StdAfx.h" #include "Deterer.h" #include "MiniBolt.h" #include "SVGParser.h" #include "Triangulate.h" //Initialise all static class members bool Deterer::initialised_ = false; int Deterer::outline_dl_ = 0; int Deterer::outline_verts_index_ = 0; int Deterer::fill_dl_ = 0; int Deterer::fill_verts_index_ = 0; Deterer::Deterer(void) : FiringSection() { if(!initialised_) { InitialiseGraphics(); initialised_ = true; } //Get the cached vertices outline_.GetOutlineVerts() = Datastore::Instance().GetVerts(outline_verts_index_); outline_.SetDisplayList(outline_dl_); fill_.GetFillVerts() = Datastore::Instance().GetVerts(fill_verts_index_); fill_.SetDisplayList(fill_dl_); findRadius(); health_ = FlexFloat(1500, 1500); cooldown_time_ = 1.25f; default_sub_section_position_ = Vector3f(0, 0, 0); mass_ = 450; section_type_ = "Deterer"; } Deterer::~Deterer(void) { } void Deterer::InitialiseGraphics() { //Initialise outline and fill from embedded SVG from Inkscape boost::shared_ptr<std::vector<Vector3f>> temp_outline = boost::shared_ptr<std::vector<Vector3f>>(new std::vector<Vector3f>()); *temp_outline = SVGParser::ParsePath("M 0,-3 L 1,-2 L 2,-3 L 3,-2 L 2,-1 L 3,0 L 2,1 L 3,2 L 2,3 L 1,2 L 0,3 L -1,2 L -2,3 L -3,2 L -2,1 L -3,0 L -2,-1 L -3,-2 L -2,-3 L -1,-2 L 0,-3 z"); temp_outline->pop_back(); outline_verts_index_ = Datastore::Instance().AddVerts(temp_outline); outline_dl_ = Outlined::CreateOutlinedDisplayList(temp_outline); boost::shared_ptr<std::vector<Vector3f>> temp_fill = boost::shared_ptr<std::vector<Vector3f>>(new std::vector<Vector3f>()); Triangulate::Process(temp_outline, temp_fill); fill_verts_index_ = Datastore::Instance().AddVerts(temp_fill); fill_dl_ = Filled::CreateFillDisplayList(temp_fill); } void Deterer::Tick(float _timespan, std::vector<Projectile_ptr>& _spawn_prj, std::vector<Decoration_ptr>& _spawn_dec, Matrix4f _transform, std::vector<Core_ptr>& _enemies, ICollisionManager* _collision_manager) { Section::Tick(_timespan, _spawn_prj, _spawn_dec, _transform, _enemies, _collision_manager); cooldown_ -= _timespan; if(firing_) { if(cooldown_ <= 0.0f && PowerRequirement(50)) { Projectile_ptr p1 = new MiniBolt(Vector3f(Random::RandomRange(-2, 2), Random::RandomRange(-2, 2), 0)); p1->SetVelocity(Vector3f(1, 0, 0) * 200); Projectile_ptr p2 = new MiniBolt(Vector3f(Random::RandomRange(-2, 2), Random::RandomRange(-2, 2), 0)); p2->SetVelocity(Vector3f(1, 1, 0) * 200); Projectile_ptr p3 = new MiniBolt(Vector3f(Random::RandomRange(-2, 2), Random::RandomRange(-2, 2), 0)); p3->SetVelocity(Vector3f(0, 1, 0) * 200); Projectile_ptr p4 = new MiniBolt(Vector3f(Random::RandomRange(-2, 2), Random::RandomRange(-2, 2), 0)); p4->SetVelocity(Vector3f(-1, 1, 0) * 200); Projectile_ptr p5 = new MiniBolt(Vector3f(Random::RandomRange(-2, 2), Random::RandomRange(-2, 2), 0)); p5->SetVelocity(Vector3f(-1, 0, 0) * 200); Projectile_ptr p6 = new MiniBolt(Vector3f(Random::RandomRange(-2, 2), Random::RandomRange(-2, 2), 0)); p6->SetVelocity(Vector3f(-1, -1, 0) * 200); Projectile_ptr p7 = new MiniBolt(Vector3f(Random::RandomRange(-2, 2), Random::RandomRange(-2, 2), 0)); p7->SetVelocity(Vector3f(0, -1, 0) * 200); Projectile_ptr p8 = new MiniBolt(Vector3f(Random::RandomRange(-2, 2), Random::RandomRange(-2, 2), 0)); p8->SetVelocity(Vector3f(1, -1, 0) * 200); fire_projectile(p1, _spawn_prj); fire_projectile(p2, _spawn_prj); fire_projectile(p3, _spawn_prj); fire_projectile(p4, _spawn_prj); fire_projectile(p5, _spawn_prj); fire_projectile(p6, _spawn_prj); fire_projectile(p7, _spawn_prj); fire_projectile(p8, _spawn_prj); cooldown_ = cooldown_time_; PowerTick(-35); } } } void Deterer::RegisterMetadata() { FiringSection::RegisterMetadata(); SectionMetadata::RegisterSectionKeyValue(section_type_, "Range", 1920); SectionMetadata::RegisterSectionTag(section_type_, "Nondirectional"); }
[ "EdwardDesktop@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7", "[email protected]" ]
[ [ [ 1, 3 ], [ 6, 42 ], [ 44, 45 ], [ 48, 52 ], [ 54, 98 ] ], [ [ 4, 5 ], [ 43, 43 ], [ 46, 47 ], [ 53, 53 ], [ 99, 105 ] ] ]
7d06aad42434b9937727a2a83fe0f1535ca3c85e
de1e5905af557c6155ee50f509758a549e458ef3
/src/v1/FeatureLibrary.h
604779806d49e22385529c0a3e01ecdb06ae0b3c
[]
no_license
alltom/taps
f15f0a5b234db92447a581f3777dbe143d78da6c
a3c399d932314436f055f147106d41a90ba2fd02
refs/heads/master
2021-01-13T01:46:24.766584
2011-09-03T23:20:12
2011-09-03T23:20:12
2,486,969
1
0
null
null
null
null
UTF-8
C++
false
false
1,080
h
#ifndef FEATURE_LIB__H #define FEATURE_LIB__H #include <vector> class FeatureLibrary { protected: int numFeats; std::vector<char*> featureNames; std::vector<float*> featureVals; float *weights; std::vector<char*> fileNames; std::vector<bool> tapsFile; float distance(const float *v1, const float *v2); public: FeatureLibrary(char *libName); ~FeatureLibrary(); void addFile(const char *filename, const float *features, bool isTemplate = 0); void setWeights(float *newWeights); int size() { return featureVals.size(); } int getNumFeats() { return numFeats; } const char* getFeatureName(int featnum) { return featureNames[featnum]; } const float* getFeatureVec(int filenum) { return featureVals[filenum]; } const char* getFileName(int filenum) { return fileNames[filenum]; } const bool isTemplate(int filenum) { return tapsFile[filenum]; } void rankClosestFiles(const float *targetVals, int *indices, float *distances = 0); void writeFLIFile(const char *filename); }; #endif
[ [ [ 1, 42 ] ] ]
6d346540b1abeb750d3321f92ef1ed597be87e85
563e71cceb33a518f53326838a595c0f23d9b8f3
/v3/ProcCity/ProcCity/Util/VBOSquare.cpp
6bb6cff2fda1b163b2e7db283990754102ceecf7
[]
no_license
fabio-miranda/procedural
3d937037d63dd16cd6d9e68fe17efde0688b5a0a
e2f4b9d34baa1315e258613fb0ea66d1235a63f0
refs/heads/master
2021-05-28T18:13:57.833985
2009-10-07T21:09:13
2009-10-07T21:09:13
39,636,279
1
1
null
null
null
null
UTF-8
C++
false
false
8,247
cpp
#include "VBOSquare.h" VBOSquare::VBOSquare(){ Init(); } VBOSquare::VBOSquare(float size){ Init(); m_size = size; } VBOSquare::VBOSquare(Vector3<float> position, float size, int numDivisions) { Init(); m_position = position; m_size = size; m_numDivisions = numDivisions; //m_vboMesh = new VBO(); int numVertices = 4 + (m_numDivisions-1)*4 + (m_numDivisions-1)*(m_numDivisions-1); int numIndices = m_numDivisions*m_numDivisions*6; m_vertices = new Vertex[numVertices]; m_indices = new GLushort[numIndices]; //float sizeby2 = m_size/2.0f; m_divisionSize = m_size/m_numDivisions; //Consider only the first decimals //m_divisionSize = floor(m_divisionSize * 1000.0f) / 1000.0f; int cont = 0; for(float i=0; i<=m_divisionSize * m_numDivisions; i+=m_divisionSize){ for(float j=0; j<=m_divisionSize * m_numDivisions; j+=m_divisionSize){ m_vertices[cont].x = m_position.GetX() +i; m_vertices[cont].y = m_position.GetY() +j ; m_vertices[cont].z = m_position.GetZ(); m_vertices[cont].v = (i) / m_size; m_vertices[cont].u = (j) / m_size; cont++; } } cont = 0; //counts the number of squares rendered int coluns = 0; //counts the coluns rendered //numIndices = 18; //numVertices = 8; for(int i=0; i<numIndices; i+=6){ m_indices[i] = cont + coluns; m_indices[i+1] = cont + coluns + 1 + m_numDivisions; m_indices[i+2] = cont + coluns + 2 + m_numDivisions; m_indices[i+3] = cont + coluns + 2 + m_numDivisions; m_indices[i+4] = cont + coluns + 1; m_indices[i+5] = cont + coluns; cont++; //If it reaches the limit of the square, it adds two to the count if(cont % m_numDivisions == 0) coluns++; } /* m_indices[0] = 0; m_indices[1] = 2; m_indices[2] = 3; m_indices[3] = 3; m_indices[4] = 1; m_indices[5] = 0; */ m_vboMesh = new VBO(m_vertices, numVertices, m_indices, numIndices); } VBOSquare::~VBOSquare(){ m_vboMesh->DeleteBuffer(); delete [] m_vertices; delete [] m_indices; } void VBOSquare::Init(){ m_isSplit = false; /* for(int i=0; i<4; i++){ m_vertices[i] = new Vertex(); m_indices[i] = new GLuint(); } */ } void VBOSquare::Render(){ m_vboMesh->Render(); /* glBegin( GL_TRIANGLES ); glTexCoord2d(m_vertices[0].u,m_vertices[0].v); glVertex3f(m_vertices[0].x, m_vertices[0].y, 0.0f); // Top Left glTexCoord2d(m_vertices[2].u,m_vertices[2].v); glVertex3f( m_vertices[2].x, m_vertices[2].y, 0.0f); // Top Right glTexCoord2d(m_vertices[3].u,m_vertices[3].v); glVertex3f( m_vertices[3].x,m_vertices[3].y, 0.0f); // Bottom Right glTexCoord2d(m_vertices[3].u,m_vertices[3].v); glVertex3f( m_vertices[3].x,m_vertices[3].y, 0.0f); glTexCoord2d(m_vertices[1].u,m_vertices[1].v); glVertex3f(m_vertices[1].x,m_vertices[1].y, 0.0f); glTexCoord2d(m_vertices[0].u,m_vertices[0].v); glVertex3f(m_vertices[0].x,m_vertices[0].y, 0.0f); glEnd(); */ /* glBegin( GL_TRIANGLES ); glTexCoord2d(0.0,0.0); glVertex3f(-25, -25, 0.0f); glTexCoord2d(0.0,1.0); glVertex3f( 25, -25, 0.0f); glTexCoord2d(1.0,1.0); glVertex3f( 25,25, 0.0f); glTexCoord2d(1.0,1.0); glVertex3f( 25,25, 0.0f); glTexCoord2d(1.0,0); glVertex3f( -25,25, 0.0f); glTexCoord2d(0.0,0.0); glVertex3f(-25, -25, 0.0f); glEnd(); */ } /* void Square::FillArray(VBO* m_vboMesh){ //int vertexSize = m_vboMesh->m_listVertex.size(); int indexSize = m_vboMesh->m_listIndex.size(); for(int i=0; i<4; i++){ if(*m_indices[i] >= m_vboMesh->m_listVertex.size()) m_vboMesh->m_listVertex.push_back(*m_vertices[i]); } if(m_isSplit){ for(int i=0; i<4; i++){ m_squares[i]->FillArray(m_vboMesh); } } else{ //We only draw the ones in the bottom of the graph for(int i=0; i<4; i++){ m_vboMesh->m_listIndex.push_back(*m_indices[i]); } } } */ /* void Square::SplitSquareIn4(){ //m_parentCube->IncreaseDivisions(4); //num_divisions *=4; m_isSplit = true; for(int i=0; i<4; i++){ m_squares[i] = new Square(m_size / 2.0f); m_squares[i]->m_parent = this; } */ //Delete the positions on the index array /* advance(m_listIndexEndPosition, -4); advance(m_listVertexEndPosition, -4); for(int i=0; i<4; i++){ m_listIndexEndPosition = m_vboMesh->m_listIndex.erase(m_listIndexEndPosition); m_listVertexEndPosition = m_vboMesh->m_listVertex.erase(m_listVertexEndPosition); } */ ///////////// // 3------2 // | | // | | // 0------1 //////////// /* //0 m_squares[0]->m_vertices[0] = m_vertices[0]; m_vboMesh->m_listVertex.push_back(*m_squares[0]->m_vertices[0]); m_squares[0]->m_indices[0] = m_indices[0]; m_vboMesh->m_listIndex.push_back(*m_squares[0]->m_indices[0]); m_squares[0]->m_vertices[1] = MidPoint(*(m_squares[0]->m_vertices[0]), *(m_vertices[1])); m_vboMesh->m_listVertex.push_back(*m_squares[0]->m_vertices[1]); *m_squares[0]->m_indices[1] = m_vboMesh->m_listVertex.size() -1; m_vboMesh->m_listIndex.push_back(*m_squares[0]->m_indices[1]); m_squares[0]->m_vertices[2] = MidPoint(*(m_vertices[0]), *(m_vertices[2])); m_vboMesh->m_listVertex.push_back(*m_squares[0]->m_vertices[2]); *m_squares[0]->m_indices[2] = m_vboMesh->m_listVertex.size() -1; m_vboMesh->m_listIndex.push_back(*m_squares[0]->m_indices[2]); m_squares[0]->m_vertices[3] = MidPoint(*(m_vertices[0]), *(m_vertices[3])); m_vboMesh->m_listVertex.push_back(*m_squares[0]->m_vertices[3]); *m_squares[0]->m_indices[3] = m_vboMesh->m_listVertex.size()-1; m_vboMesh->m_listIndex.push_back(*m_squares[0]->m_indices[3]); //1 m_squares[1]->m_vertices[0] = m_squares[0]->m_vertices[1]; m_squares[1]->m_indices[0] = m_squares[0]->m_indices[1]; m_vboMesh->m_listIndex.push_back(*m_squares[1]->m_indices[0]); m_squares[1]->m_vertices[1] = m_vertices[1]; m_vboMesh->m_listVertex.push_back(*m_squares[1]->m_vertices[1]); m_squares[1]->m_indices[1] = m_indices[1]; m_vboMesh->m_listIndex.push_back(*m_squares[1]->m_indices[1]); m_squares[1]->m_vertices[2] = MidPoint(*(m_vertices[1]), *(m_vertices[2])); m_vboMesh->m_listVertex.push_back(*m_squares[1]->m_vertices[2]); *m_squares[1]->m_indices[2] = m_vboMesh->m_listVertex.size()-1; m_vboMesh->m_listIndex.push_back(*m_squares[1]->m_indices[2]); m_squares[1]->m_vertices[3] = m_squares[0]->m_vertices[2]; m_squares[1]->m_indices[3] = m_squares[0]->m_indices[2]; m_vboMesh->m_listIndex.push_back(*m_squares[1]->m_indices[3]); //2 m_squares[2]->m_vertices[0] = m_squares[0]->m_vertices[2]; m_squares[2]->m_indices[0] = m_squares[0]->m_indices[2]; m_vboMesh->m_listIndex.push_back(*m_squares[2]->m_indices[0]); m_squares[2]->m_vertices[1] = m_squares[1]->m_vertices[2]; m_squares[2]->m_indices[1] = m_squares[1]->m_indices[2]; m_vboMesh->m_listIndex.push_back(*m_squares[2]->m_indices[1]); m_squares[2]->m_vertices[2] = m_vertices[2]; m_vboMesh->m_listVertex.push_back(*m_squares[2]->m_vertices[2]); m_squares[2]->m_indices[2] = m_indices[2]; m_vboMesh->m_listIndex.push_back(*m_squares[2]->m_indices[2]); m_squares[2]->m_vertices[3] = MidPoint(*(m_vertices[2]), *(m_vertices[3])); m_vboMesh->m_listVertex.push_back(*m_squares[2]->m_vertices[3]); *m_squares[2]->m_indices[3] = m_vboMesh->m_listVertex.size()-1; m_vboMesh->m_listIndex.push_back(*m_squares[2]->m_indices[3]); //3 m_squares[3]->m_vertices[0] = m_squares[0]->m_vertices[3]; m_squares[3]->m_indices[0] = m_squares[0]->m_indices[3]; m_vboMesh->m_listIndex.push_back(*m_squares[3]->m_indices[0]); m_squares[3]->m_vertices[1] = m_squares[0]->m_vertices[2]; m_squares[3]->m_indices[1] = m_squares[0]->m_indices[2]; m_vboMesh->m_listIndex.push_back(*m_squares[3]->m_indices[1]); m_squares[3]->m_vertices[2] = m_squares[2]->m_vertices[3]; m_squares[3]->m_indices[2] = m_squares[2]->m_indices[3]; m_vboMesh->m_listIndex.push_back(*m_squares[3]->m_indices[2]); m_squares[3]->m_vertices[3] = m_vertices[3]; m_vboMesh->m_listVertex.push_back(*m_squares[3]->m_vertices[3]); m_squares[3]->m_indices[3] = m_indices[3]; m_vboMesh->m_listIndex.push_back(*m_squares[3]->m_indices[3]); } */
[ "fabiom@01b71de8-32d4-11de-96ab-f16d9912eac9" ]
[ [ [ 1, 276 ] ] ]
5875908415011680c3132f796e2ac70caf438449
559770fbf0654bc0aecc0f8eb33843cbfb5834d9
/haina/codes/beluga/client/moblie/InfoInterceptor/InfoInterceptorTest/stdafx.cpp
863e04106bab1c949b57815e6cd85a656bd43d13
[]
no_license
CMGeorge/haina
21126c70c8c143ca78b576e1ddf352c3d73ad525
c68565d4bf43415c4542963cfcbd58922157c51a
refs/heads/master
2021-01-11T07:07:16.089036
2010-08-18T09:25:07
2010-08-18T09:25:07
49,005,284
1
0
null
null
null
null
UTF-8
C++
false
false
304
cpp
// stdafx.cpp : source file that includes just the standard includes // InfoInterceptorTest.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ [ [ 1, 7 ] ] ]
4aeb7f3f699b96b5509dc769ee30836614438963
299a1b0fca9e1de3858a5ebeaf63be6dc3a02b48
/tags/051101/dingus/dingus/app/DingusSystem.cpp
bac3ad434374a8bd0b6b1dea5e8e6fb133dcecda
[]
no_license
BackupTheBerlios/dingus-svn
331d7546a6e7a5a3cb38ffb106e57b224efbf5df
1223efcf4c2079f58860d7fa685fa5ded8f24f32
refs/heads/master
2016-09-05T22:15:57.658243
2006-09-02T10:10:47
2006-09-02T10:10:47
40,673,143
0
0
null
null
null
null
UTF-8
C++
false
false
8,697
cpp
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #include "stdafx.h" #include "DingusSystem.h" #include "../kernel/D3DDevice.h" #include "../resource/DeviceResource.h" #include "../resource/ReloadableBundle.h" #include "../renderer/RenderContext.h" #include "../renderer/EffectParamsNotifier.h" #include "../dxutils/D3DFont.h" #include "../console/D3DConsoleRenderingContext.h" #define APP_CHANNEL CConsole::getChannel("app") using namespace dingus; CDingusSystem::CDingusSystem( IDingusApplication& application ) : mApplication( &application ), mAppInited( false ), mStdConsoleCtx(0), mFont(0), mD3DConsoleCtx(0) { SAppStartupParams params = mApplication->getStartupParams(); mCreationWidth = params.windowWidth; mCreationHeight = params.windowHeight; mWindowTitle = params.windowTitle; mStartFullscreen = params.startFullscreen; mShowCursorWhenFullscreen = params.showCursorFullscreen; mVSyncFullscreen = params.vsyncFullscreen; mDebugTimer = params.debugTimer; mEnumeration.mUsesDepthBuffer = params.usesZBuffer; mEnumeration.mMinColorChannelBits = params.minColorBits; mEnumeration.mMinAlphaChannelBits = params.minAlphaBits; mEnumeration.mMinDepthBits = params.minZBits; mEnumeration.mMinStencilBits = params.minStencilBits; mEnumeration.mUsesMixedVP = true; mEnumeration.mConfigDBFileName = params.dxConfigFile; mDataPath = params.dataPath; mSelectDeviceAtStartup = params.selectDeviceAtStartup; mFont = new CD3DFont( "Arial", 10, CD3DFont::BOLD ); }; CDingusSystem::~CDingusSystem() { delete mFont; } /** * Initialization. Paired with shutdown(). * The window has been created and the IDirect3D9 interface has been * created, but the device has not been created yet. Here you can * perform application-related initialization and cleanup that does * not depend on a device. */ HRESULT CDingusSystem::initialize() { assert( mApplication ); // // init console mStdConsoleCtx = mApplication->createStdConsoleCtx( mHWnd ); CConsole::getInstance().setDefaultRenderingContext( *mStdConsoleCtx ); mD3DConsoleCtx = new CD3DTextBoxConsoleRenderingContext( *mFont, 2, 2, 0xc0FFFF20, 0xc0000000 ); CConsole::getChannel( "system" ).setRenderingContext( *mD3DConsoleCtx ); APP_CHANNEL << "creating device resource manager" << endl; CDeviceResourceManager::getInstance(); APP_CHANNEL << "creating reloadable resources manager" << endl; mReloadableManager = new CReloadableBundleManager(); return S_OK; } bool CDingusSystem::checkDevice( const CD3DDeviceCaps& caps, CD3DDeviceCaps::eVertexProcessing vproc, CD3DEnumErrors& errors ) { return mApplication->checkDevice( caps, vproc, errors ); } HRESULT CDingusSystem::createDeviceObjects() { mFont->createDeviceObjects(); if( !mAppInited ) { APP_CHANNEL << "setup resource bundles" << endl; mApplication->setupBundles( mDataPath, *mReloadableManager ); } APP_CHANNEL << "create d3d resources" << endl; CDeviceResourceManager::getInstance().createResource(); CEffectParamsNotifier::getInstance().notify(); return S_OK; } HRESULT CDingusSystem::activateDeviceObjects() { APP_CHANNEL << "activate d3d resources" << endl; mFont->activateDeviceObjects(); CDeviceResourceManager::getInstance().activateResource(); if( !mAppInited ) { APP_CHANNEL << "setup app contexts" << endl; mApplication->setupContexts( mHWnd ); APP_CHANNEL << "initialize app" << endl; mApplication->initialize( *this ); APP_CHANNEL << "app initialized" << endl; mAppInited = true; } return S_OK; } /** * Called once per frame, the call is the entry point for 3d rendering. This * function sets up render states, clears the viewport, and renders the scene. */ HRESULT CDingusSystem::performOneTime() { CD3DDevice& device = CD3DDevice::getInstance(); // // pipeline device.getStats().reset(); device.getStats().setFPS( mFPS ); // needs to reset device cache; otherwise we can get funky things with // render targets device.resetCachedState(); mApplication->perform(); // // stats if( mApplication->shouldShowStats() ) { CConsoleChannel& cc = CConsole::getChannel( "system" ); cc.write( mFrameStats ); cc.write( mDeviceStats ); const dingus::CRenderStats& stats = device.getStats(); char buf[300]; sprintf( buf, "draws %i, fx %i, prims %i (%.1fM/s), verts %i", stats.getDrawCalls(), stats.getEffectChanges(), stats.getPrimsRendered(), stats.getPrimsRendered() * mFPS * 1.0e-6f, stats.getVerticesRendered() ); cc.write( buf ); const dingus::CRenderStats::SStateStats& ssc = stats.changes; const dingus::CRenderStats::SStateStats& ssf = stats.filtered; sprintf( buf, "vb:%i/%i ib:%i/%i dcl:%i/%i rt:%i/%i zs:%i/%i vs:%i/%i ps:%i/%i tr:%i lit:%i/%i", ssc.vbuffer, ssf.vbuffer, ssc.ibuffer, ssf.ibuffer, ssc.declarations, ssf.declarations, ssc.renderTarget, ssf.renderTarget, ssc.zStencil, ssf.zStencil, ssc.vsh, ssf.vsh, ssc.psh, ssf.psh, ssc.transforms, ssc.lighting, ssf.lighting ); cc.write( buf ); sprintf( buf, "t:%i/%i rs:%i/%i tss:%i/%i smp:%i/%i const:%i", ssc.textures, ssf.textures, ssc.renderStates, ssf.renderStates, ssc.textureStages, ssf.textureStages, ssc.samplers, ssf.samplers, ssc.vshConst+ssf.pshConst ); cc.write( buf ); dingus::CD3DDevice::getInstance().getDevice().BeginScene(); mD3DConsoleCtx->flush(); dingus::CD3DDevice::getInstance().getDevice().EndScene(); } // // poll for close if( mApplication->shouldFinish() ) { doClose(); } return S_OK; } /** * Overrrides the main WndProc, so the sample can do custom message handling * (e.g. processing mouse, keyboard, or menu commands). */ LRESULT CDingusSystem::msgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { /* static bool reloadKeyPressed = false; switch( msg ) { case WM_KEYDOWN: if( wParam == VK_F5 ) reloadKeyPressed = true; break; case WM_KEYUP: if( wParam == VK_F5 ) { if( reloadKeyPressed ) { mReloadableManager->reload(); CEffectParamsNotifier::getInstance().notify(); } reloadKeyPressed = false; } } */ if( mApplication && mAppInited ) { bool processed = mApplication->msgProc( hWnd, msg, wParam, lParam ); //if( processed ) // return; } return CD3DApplication::msgProc( hWnd, msg, wParam, lParam ); } /** * Invalidates device objects. Paired with activateDeviceObjects(). */ HRESULT CDingusSystem::passivateDeviceObjects() { APP_CHANNEL << "passivate d3d resources" << endl; mFont->passivateDeviceObjects(); CDeviceResourceManager::getInstance().passivateResource(); return S_OK; } /** * Paired with createDeviceObjects(). * Called when the app is exiting, or the device is being changed, * this function deletes any device dependent objects. */ HRESULT CDingusSystem::deleteDeviceObjects() { APP_CHANNEL << "delete d3d resources" << endl; mFont->deleteDeviceObjects(); CDeviceResourceManager::getInstance().deleteResource(); return S_OK; } /** * Paired with initialize(). * Called before the app exits, this function gives the app the chance * to cleanup after itself. */ HRESULT CDingusSystem::shutdown() { APP_CHANNEL << "shutdown app" << endl; mApplication->shutdown(); APP_CHANNEL << "shutdown device resource manager" << endl; CDeviceResourceManager::getInstance().clearListeners(); CDeviceResourceManager::finalize(); mReloadableManager->clearListeners(); delete mReloadableManager; APP_CHANNEL << "destroy contexts" << endl; mApplication->destroyContexts(); APP_CHANNEL << "destroy resource bundles" << endl; mApplication->destroyBundles(); delete mD3DConsoleCtx; delete mStdConsoleCtx; CConsole::finalize(); return S_OK; } const CD3DEnumeration& CDingusSystem::getD3DEnumeration() const { return mEnumeration; } const CD3DSettings& CDingusSystem::getD3DSettings() const { return mSettings; } void CDingusSystem::applyD3DSettings( const CD3DSettings& s ) { mSettings = s; applySettings(); } HRESULT CDingusSystem::chooseInitialD3DSettings() { APP_CHANNEL << "choose initial d3d settings" << endl; assert( mApplication ); mApplication->initD3DSettingsPref( mSettingsPref ); return CD3DApplication::chooseInitialD3DSettings(); }
[ "nearaz@73827abb-88f4-0310-91e6-a2b8c1a3e93d" ]
[ [ [ 1, 313 ] ] ]
67ed2a3e0a73517e721dd3f193c670fe5968f5fe
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Pilot/Lokapala_Communication/Raptor/RaptorDlg.cpp
75352f7450da68118a40350ac114efb2b6fac530
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UHC
C++
false
false
4,083
cpp
// RaptorDlg.cpp : implementation file // #include "stdafx.h" #include "Raptor.h" #include "RaptorDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CRaptorDlg dialog CRaptorDlg::CRaptorDlg(CWnd* pParent /*=NULL*/) : CDialog(CRaptorDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CRaptorDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CRaptorDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_BUTTONTEST, &CRaptorDlg::OnBnClickedButtontest) ON_BN_CLICKED(IDC_CONNECTBUTTON, &CRaptorDlg::OnBnClickedConnectbutton) END_MESSAGE_MAP() // CRaptorDlg message handlers BOOL CRaptorDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CCBFMediator::Instance()->SetMainDlg(this); //CCBFMediator::Instance()->InitiallizeCommunication(); return TRUE; // return TRUE unless you set the focus to a control } void CRaptorDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CRaptorDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CRaptorDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } /**@brief 테스트용 문자 전송 버튼 클릭 */ void CRaptorDlg::OnBnClickedButtontest() { // TODO: Add your control notification handler code here CString message; this->GetDlgItemTextW(IDC_EDITTEST,message); CCBFMediator::Instance()->SendTextMessage(message); } /**@brief 오퍼레이터로 접속 버튼 클릭 */ void CRaptorDlg::OnBnClickedConnectbutton() { // TODO: Add your control notification handler code here CIPAddressCtrl *pIpControl = (CIPAddressCtrl *)(this->GetDlgItem(IDC_SERVERIP)); DWORD serverIp; pIpControl->GetAddress(serverIp); CCBFMediator::Instance()->InitiallizeCommunication(serverIp); }
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
[ [ [ 1, 175 ] ] ]
6bd5b12e133753762fa7303fe32b42b8cd274a09
3a065db43da01abd27d37d3775c64317d9a4e74a
/thesisSourceCode/Fixed/fixedFloorplanning/floorPlanning.cpp
6f5da798074af68903b2bbbee6e66dfaa0fbf87e
[]
no_license
bonrix/an-algorithm-floorplanning
c75263105a297b95a4668b68e2b2da9c3c969e59
0429bf4818dbac0507ad5d2e68fcb07cd9a05489
refs/heads/master
2020-06-05T06:13:17.920682
2011-07-16T18:40:50
2011-07-16T18:40:50
38,099,628
1
1
null
null
null
null
UTF-8
C++
false
false
3,663
cpp
#include <vector> //#include <string.h> #include <iostream> // standard streams #include <fstream> // file streams #include <sstream> // string streams #include <map> #include "floorPlanning.h" using namespace std; double floorPlanning(FloorPlan &fp) { fp.setInOrder(); //fp.list_information(); fp.show_modules(); SuperModules superModules; /* for(int i=0; i < fp.modules.size();i++){ if((i % 4) == 0) { SuperModule dummy_mod; if( i+4 > fp.modules.size()) dummy_mod.setChild(fp.modules,i,fp.modules.size()%4,true); else dummy_mod.setChild(fp.modules,i,4,true); superModules.push_back(dummy_mod); } }*/ for(int i=0; i < fp.modules.size();i++){ SuperModule dummy_mod; dummy_mod.setChild(fp.modules,i,1,true); superModules.push_back(dummy_mod); } /*for(int i=0; i < fp.modules.size();i++){ SuperModule dummy_mod; dummy_mod.setChild(fp.modules,fp.modules.size()-i-1,1,true); superModules.push_back(dummy_mod); }*/ for( i=0; i < superModules.size();i++){ superModules[i].arrangeBlocks(); //superModules[i].showModules(); } recursiveBottomUp(superModules); //for( i=0; i < superModules.size();i++)/ // superModules[i].setChildCordinates(); //} for( i=0; i < superModules.size();i++){ //newSuperModules[i].setChildCordinates(); //superModules[i].showXYZModules(); } for( i=0; i < superModules.size();i++){ if(!superModules[i].isRotation) { fp.modules_info[i].x = superModules[i].x; fp.modules_info[i].y = superModules[i].y; fp.modules_info[i].rx = superModules[i].x + superModules[i].width; fp.modules_info[i].ry = superModules[i].y + superModules[i].height; //cout << "x===" << superModules[i].x << endl; //cout << "y===" << superModules[i].y << endl; } else { fp.modules_info[i].x = superModules[i].x; fp.modules_info[i].y = superModules[i].y; fp.modules_info[i].rx = superModules[i].x + superModules[i].height; fp.modules_info[i].ry = superModules[i].y + superModules[i].width; //cout << "x===" << superModules[i].x << endl; //cout << "y===" << superModules[i].y << endl; } } fp.Width = finalWidth; fp.Height= finalHeight; fp.Area = fp.Width * fp.Height; double time=seconds(); return time; } void recursiveBottomUp(SuperModules &superModules) { SuperModules newSuperModules; for(int i=0; i < superModules.size();i++){ if((i % 4) == 0) { SuperModule dummy_mod; if( i+4 > superModules.size()) dummy_mod.setChildComposite(superModules,i,superModules.size()%4,false); else dummy_mod.setChildComposite(superModules,i,4,false); newSuperModules.push_back(dummy_mod); } } for( i=0; i < newSuperModules.size();i++){ newSuperModules[i].arrangeBlocks(); //newSuperModules[i].showXYModules(); } setInOrder(newSuperModules); if (newSuperModules.size() == 1) { // cout << " final area ---- >>>>>> " << newSuperModules[0].area << endl; finalWidth = newSuperModules[0].width; finalHeight = newSuperModules[0].height; // cout << " final width ---- >>>>>> " << finalWidth << endl; // cout << " final width ---- >>>>>> " << finalHeight << endl; newSuperModules[0].isRotation = false; newSuperModules[0].setCordinates(0,0); //newSuperModules[0].showXYModules(); newSuperModules[0].setChildCordinates(); return; } else { recursiveBottomUp(newSuperModules); if( newSuperModules.size() != 1) { for( i=0; i < newSuperModules.size();i++){ newSuperModules[i].setChildCordinates(); //newSuperModules[i].showXYModules(); } } return; } }
[ [ [ 1, 130 ] ] ]
d9bf5ca1016bdd769205a035c8c8fa582db760e3
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/opcode/OPC_Random.cc
1dd3f1ea94fba99eb8844e8e40fcf4bc2ab8e7b1
[]
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
1,163
cc
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Contains code for random generators. * \file IceRandom.cpp * \author Pierre Terdiman * \date August, 9, 2001 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Precompiled Header #include "opcode/opcodedef.h" using namespace IceCore; void IceCore:: SRand(udword seed) { srand(seed); } udword IceCore::Rand() { return rand(); } static BasicRandom gRandomGenerator(42); udword IceCore::GetRandomIndex(udword max_index) { // We don't use rand() since it's limited to RAND_MAX udword Index = gRandomGenerator.Randomize(); return Index % max_index; }
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 35 ] ] ]
15cee6d43f41825c087e27459157f1a318bee321
41371839eaa16ada179d580f7b2c1878600b718e
/UVa/Volume C/10050.cpp
018c0d3123ccf76bcf51bf3605c62a4a8a9a2517
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
508
cpp
///////////////////////////////// // 10050 - Hartals ///////////////////////////////// #include<cstdio> bool h[3655]; int cases,hp,hi,i,j,N,hartals; int main(void){ scanf("%d",&cases); while(cases){ cases--; scanf("%d",&N); N++; scanf("%d",&hp); for(i = 0; i < N; h[i] = 0,i++); for(hartals = i = 0; i < hp; i++){ scanf("%d",&hi); for(j = hi; j < N; j+=hi) if(!h[j] && j%7 != 6 && j%7){ h[j] = 1; hartals++; } } printf("%d\n",hartals); } }
[ [ [ 1, 25 ] ] ]
a4d233142841a32354b8593ed0fe5add6aac2ab1
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctesteh/src/bctestehview.cpp
4e569e909950958d544e87f9e7c0892b7dc9bb51
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
3,896
cpp
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: view class * */ #include <aknviewappui.h> #include "bctesteh.hrh" #include <bctesteh.rsg> #include "bctestehview.h" #include "bctestehcontainer.h" #include "bctestutil.h" #include "bctestehcase.h" // constant _LIT( KBctestCase, "BCTest Error UI and Hotkeys case" ); // ======== MEMBER FUNCTIONS ======== // --------------------------------------------------------------------------- // Symbian 2nd static Constructor // --------------------------------------------------------------------------- // CBCTestEHView* CBCTestEHView::NewL() { CBCTestEHView* self = new( ELeave ) CBCTestEHView(); CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop( self ); return self; } // --------------------------------------------------------------------------- // C++ default Constructor // --------------------------------------------------------------------------- // CBCTestEHView::CBCTestEHView() { } // --------------------------------------------------------------------------- // Symbian 2nd Constructor // --------------------------------------------------------------------------- // void CBCTestEHView::ConstructL() { BaseConstructL( R_BCTESTEH_VIEW ); iContainer = new( ELeave ) CBCTestEHContainer(); iContainer->SetMopParent( this ); iContainer->ConstructL( ClientRect() ); AppUi()->AddToStackL( *this, iContainer ); iContainer->MakeVisible( ETrue ); iTestUtil = CBCTestUtil::NewL(); // Add test case here. iTestUtil->AddTestCaseL( CBCTestEHCase::NewL( iContainer ), KBctestCase ); } // --------------------------------------------------------------------------- // Destructor // --------------------------------------------------------------------------- // CBCTestEHView::~CBCTestEHView() { if ( iContainer ) { AppUi()->RemoveFromStack( iContainer ); } delete iContainer; delete iTestUtil; } // --------------------------------------------------------------------------- // CBCTestEHView::Id // --------------------------------------------------------------------------- // TUid CBCTestEHView::Id() const { return KBCTestEHViewId; } // --------------------------------------------------------------------------- // CBCTestEHView::DoActivateL // --------------------------------------------------------------------------- // void CBCTestEHView::DoActivateL( const TVwsViewId&, TUid, const TDesC8& ) { } // --------------------------------------------------------------------------- // CBCTestEHView::DoDeactivate // --------------------------------------------------------------------------- // void CBCTestEHView::DoDeactivate() { } // --------------------------------------------------------------------------- // CBCTestEHView::HandleCommandL // --------------------------------------------------------------------------- // void CBCTestEHView::HandleCommandL( TInt aCommand ) { switch ( aCommand ) { case EProgCmdAutoTest: iTestUtil->RunL(); break; default: if ( aCommand > EBCTestCmdEmptyOutline && aCommand < EBCTestCmdMaxOutline ) { iTestUtil->RunL( aCommand ); } break; } }
[ "none@none" ]
[ [ [ 1, 134 ] ] ]
5b0565cd245a567265114698143b0798071944ef
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/inc/tinyxml/tinyxml.h
cba2e99e20bf745545c334b7e6e3bce24bd7728e
[ "Zlib" ]
permissive
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
61,494
h
/* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier)copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef TINYXML_INCLUDED #define TINYXML_INCLUDED #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4530) #pragma warning(disable : 4786) #endif #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> // Help out windows: #if defined(_DEBUG) && !defined(DEBUG) #define DEBUG #endif #ifdef TIXML_USE_STL #include <string> #include <iostream> #define TIXML_STRING std::string #define TIXML_ISTREAM std::istream #define TIXML_OSTREAM std::ostream #else #include "tinystr.h" #define TIXML_STRING TiXmlString #define TIXML_OSTREAM TiXmlOutStream #endif // Deprecated library function hell. Compilers want to use the // new safe versions. This probably doesn't fully address the problem, // but it gets closer. There are too many compilers for me to fully // test. If you get compilation troubles, undefine TIXML_SAFE #define TIXML_SAFE // TinyXml isn't fully buffer overrun protected, safe code. This is work in progress. #ifdef TIXML_SAFE #if defined(_MSC_VER) && (_MSC_VER >= 1400) // Microsoft visual studio, version 2005 and higher. #define TIXML_SNPRINTF _snprintf_s #define TIXML_SNSCANF _snscanf_s #elif defined(_MSC_VER) && (_MSC_VER >= 1200) // Microsoft visual studio, version 6 and higher. //#pragma message("Using _sn* functions.") #define TIXML_SNPRINTF _snprintf #define TIXML_SNSCANF _snscanf #elif defined(__GNUC__) && (__GNUC__ >= 3) // GCC version 3 and higher.s //#warning("Using sn* functions.") #define TIXML_SNPRINTF snprintf #define TIXML_SNSCANF snscanf #endif #endif class TiXmlDocument; class TiXmlElement; class TiXmlComment; class TiXmlUnknown; class TiXmlAttribute; class TiXmlText; class TiXmlDeclaration; class TiXmlParsingData; const int TIXML_MAJOR_VERSION = 2; const int TIXML_MINOR_VERSION = 4; const int TIXML_PATCH_VERSION = 3; /* Internal structure for tracking location of items in the XML file. */ struct TiXmlCursor { TiXmlCursor() { Clear(); } void Clear() { row = col = -1; } int row; // 0 based. int col; // 0 based. }; // Only used by Attribute::Query functions enum { TIXML_SUCCESS, TIXML_NO_ATTRIBUTE, TIXML_WRONG_TYPE }; // Used by the parsing routines. enum TiXmlEncoding { TIXML_ENCODING_UNKNOWN, TIXML_ENCODING_UTF8, TIXML_ENCODING_LEGACY }; const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN; /** TiXmlBase is a base class for every class in TinyXml. It does little except to establish that TinyXml classes can be printed and provide some utility functions. In XML, the document and elements can contain other elements and other types of nodes. @verbatim A Document can contain: Element (container or leaf) Comment (leaf) Unknown (leaf) Declaration(leaf) An Element can contain: Element (container or leaf) Text (leaf) Attributes (not on tree) Comment (leaf) Unknown (leaf) A Decleration contains: Attributes (not on tree) @endverbatim */ class TiXmlBase { friend class TiXmlNode; friend class TiXmlElement; friend class TiXmlDocument; public: TiXmlBase() : userData(0) {} virtual ~TiXmlBase() {} /** All TinyXml classes can print themselves to a filestream. This is a formatted print, and will insert tabs and newlines. (For an unformatted stream, use the << operator.) */ virtual void Print(FILE* cfile, int depth) const = 0; /** The world does not agree on whether white space should be kept or not. In order to make everyone happy, these global, static functions are provided to set whether or not TinyXml will condense all white space into a single space or not. The default is to condense. Note changing this values is not thread safe. */ static void SetCondenseWhiteSpace(bool condense) { condenseWhiteSpace = condense; } /// Return the current white space setting. static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; } /** Return the position, in the original source file, of this node or attribute. The row and column are 1-based. (That is the first row and first column is 1,1). If the returns values are 0 or less, then the parser does not have a row and column value. Generally, the row and column value will be set when the TiXmlDocument::Load(), TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set when the DOM was created from operator>>. The values reflect the initial load. Once the DOM is modified programmatically (by adding or changing nodes and attributes) the new values will NOT update to reflect changes in the document. There is a minor performance cost to computing the row and column. Computation can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. @sa TiXmlDocument::SetTabSize() */ int Row() const { return location.row + 1; } int Column() const { return location.col + 1; } ///< See Row() void SetUserData(void* user) { userData = user; } void* GetUserData() { return userData; } // Table that returs, for a given lead byte, the total number of bytes // in the UTF-8 sequence. static const int utf8ByteTable[256]; virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */) = 0; enum { TIXML_NO_ERROR = 0, TIXML_ERROR, TIXML_ERROR_OPENING_FILE, TIXML_ERROR_OUT_OF_MEMORY, TIXML_ERROR_PARSING_ELEMENT, TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, TIXML_ERROR_READING_ELEMENT_VALUE, TIXML_ERROR_READING_ATTRIBUTES, TIXML_ERROR_PARSING_EMPTY, TIXML_ERROR_READING_END_TAG, TIXML_ERROR_PARSING_UNKNOWN, TIXML_ERROR_PARSING_COMMENT, TIXML_ERROR_PARSING_DECLARATION, TIXML_ERROR_DOCUMENT_EMPTY, TIXML_ERROR_EMBEDDED_NULL, TIXML_ERROR_PARSING_CDATA, TIXML_ERROR_STRING_COUNT }; protected: // See STL_STRING_BUG // Utility class to overcome a bug. class StringToBuffer { public: StringToBuffer(const TIXML_STRING& str); ~StringToBuffer(); char* buffer; }; static const char* SkipWhiteSpace(const char*, TiXmlEncoding encoding); inline static bool IsWhiteSpace(char c) { return (isspace((unsigned char) c) || c == '\n' || c == '\r'); } inline static bool IsWhiteSpace(int c) { if (c < 256) return IsWhiteSpace((char) c); return false; // Again, only truly correct for English/Latin...but usually works. } virtual void StreamOut (TIXML_OSTREAM *) const = 0; #ifdef TIXML_USE_STL static bool StreamWhiteSpace(TIXML_ISTREAM * in, TIXML_STRING * tag); static bool StreamTo(TIXML_ISTREAM * in, int character, TIXML_STRING * tag); #endif /* Reads an XML name into the string provided. Returns a pointer just past the last character of the name, or 0 if the function has an error. */ static const char* ReadName(const char* p, TIXML_STRING* name, TiXmlEncoding encoding); /* Reads text. Returns a pointer past the given end tag. Wickedly complex options, but it keeps the (sensitive) code in one place. */ static const char* ReadText( const char* in, // where to start TIXML_STRING* text, // the string read bool ignoreWhiteSpace, // whether to keep the white space const char* endTag, // what ends this text bool ignoreCase, // whether to ignore case in the end tag TiXmlEncoding encoding); // the current encoding // If an entity has been found, transform it into a character. static const char* GetEntity(const char* in, char* value, int* length, TiXmlEncoding encoding); // Get a character, while interpreting entities. // The length can be from 0 to 4 bytes. inline static const char* GetChar(const char* p, char* _value, int* length, TiXmlEncoding encoding) { assert(p); if (encoding == TIXML_ENCODING_UTF8) { *length = utf8ByteTable[ *((unsigned char*)p) ]; assert(*length >= 0 && *length < 5); } else { *length = 1; } if (*length == 1) { if (*p == '&') return GetEntity(p, _value, length, encoding); *_value = *p; return p+1; } else if (*length) { //strncpy(_value, p, *length); // lots of compilers don't like this function (unsafe), // and the null terminator isn't needed for (int i = 0; p[i] && i < *length; ++i) { _value[i] = p[i]; } return p + (*length); } else { // Not valid text. return 0; } } // Puts a string to a stream, expanding entities as it goes. // Note this should not contian the '<', '>', etc, or they will be transformed into entities! static void PutString(const TIXML_STRING& str, TIXML_OSTREAM* out); static void PutString(const TIXML_STRING& str, TIXML_STRING* out); // Return true if the next characters in the stream are any of the endTag sequences. // Ignore case only works for english, and should only be relied on when comparing // to English words: StringEqual(p, "version", true) is fine. static bool StringEqual( const char* p, const char* endTag, bool ignoreCase, TiXmlEncoding encoding); static const char* errorString[ TIXML_ERROR_STRING_COUNT ]; TiXmlCursor location; /// Field containing a generic user pointer void* userData; // None of these methods are reliable for any language except English. // Good for approximation, not great for accuracy. static int IsAlpha(unsigned char anyByte, TiXmlEncoding encoding); static int IsAlphaNum(unsigned char anyByte, TiXmlEncoding encoding); inline static int ToLower(int v, TiXmlEncoding encoding) { if (encoding == TIXML_ENCODING_UTF8) { if (v < 128) return tolower(v); return v; } else { return tolower(v); } } static void ConvertUTF32ToUTF8(unsigned long input, char* output, int* length); private: TiXmlBase(const TiXmlBase&); // not implemented. void operator=(const TiXmlBase& base); // not allowed. struct Entity { const char* str; unsigned int strLength; char chr; }; enum { NUM_ENTITY = 5, MAX_ENTITY_LENGTH = 6 }; static Entity entity[ NUM_ENTITY ]; static bool condenseWhiteSpace; }; /** The parent class for everything in the Document Object Model. (Except for attributes). Nodes have siblings, a parent, and children. A node can be in a document, or stand on its own. The type of a TiXmlNode can be queried, and it can be cast to its more defined type. */ class TiXmlNode : public TiXmlBase { friend class TiXmlDocument; friend class TiXmlElement; public: #ifdef TIXML_USE_STL /** An input stream operator, for every class. Tolerant of newlines and formatting, but doesn't expect them. */ friend std::istream& operator >> (std::istream& in, TiXmlNode& base); /** An output stream operator, for every class. Note that this outputs without any newlines or formatting, as opposed to Print(), which includes tabs and new lines. The operator<< and operator>> are not completely symmetric. Writing a node to a stream is very well defined. You'll get a nice stream of output, without any extra whitespace or newlines. But reading is not as well defined. (As it always is.) If you create a TiXmlElement (for example) and read that from an input stream, the text needs to define an element or junk will result. This is true of all input streams, but it's worth keeping in mind. A TiXmlDocument will read nodes until it reads a root element, and all the children of that root element. */ friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base); /// Appends the XML node or attribute to a std::string. friend std::string& operator<< (std::string& out, const TiXmlNode& base); #else // Used internally, not part of the public API. friend TIXML_OSTREAM& operator<< (TIXML_OSTREAM& out, const TiXmlNode& base); #endif /** The types of XML nodes supported by TinyXml. (All the unsupported types are picked up by UNKNOWN.) */ enum NodeType { DOCUMENT, ELEMENT, COMMENT, UNKNOWN, TEXT, DECLARATION, TYPECOUNT }; virtual ~TiXmlNode(); /** The meaning of 'value' changes for the specific type of TiXmlNode. @verbatim Document: filename of the xml file Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string @endverbatim The subclasses will wrap this function. */ const char *Value() const { return value.c_str (); } #ifdef TIXML_USE_STL /** Return Value() as a std::string. If you only use STL, this is more efficient than calling Value(). Only available in STL mode. */ const std::string& ValueStr() const { return value; } #endif /** Changes the value of the node. Defined as: @verbatim Document: filename of the xml file Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string @endverbatim */ void SetValue(const char * _value) { value = _value;} #ifdef TIXML_USE_STL /// STL std::string form. void SetValue(const std::string& _value) { value = _value; } #endif /// Delete all the children of this node. Does not affect 'this'. void Clear(); /// One step up the DOM. TiXmlNode* Parent() { return parent; } const TiXmlNode* Parent() const { return parent; } const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children. TiXmlNode* FirstChild() { return firstChild; } const TiXmlNode* FirstChild(const char * value) const; ///< The first child of this node with the matching 'value'. Will be null if none found. TiXmlNode* FirstChild(const char * value); ///< The first child of this node with the matching 'value'. Will be null if none found. const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children. TiXmlNode* LastChild() { return lastChild; } const TiXmlNode* LastChild(const char * value) const; /// The last child of this node matching 'value'. Will be null if there are no children. TiXmlNode* LastChild(const char * value); #ifdef TIXML_USE_STL const TiXmlNode* FirstChild(const std::string& _value) const { return FirstChild (_value.c_str ()); } ///< STL std::string form. TiXmlNode* FirstChild(const std::string& _value) { return FirstChild (_value.c_str ()); } ///< STL std::string form. const TiXmlNode* LastChild(const std::string& _value) const { return LastChild (_value.c_str ()); } ///< STL std::string form. TiXmlNode* LastChild(const std::string& _value) { return LastChild (_value.c_str ()); } ///< STL std::string form. #endif /** An alternate way to walk the children of a node. One way to iterate over nodes is: @verbatim for (child = parent->FirstChild(); child; child = child->NextSibling()) @endverbatim IterateChildren does the same thing with the syntax: @verbatim child = 0; while (child = parent->IterateChildren(child)) @endverbatim IterateChildren takes the previous child as input and finds the next one. If the previous child is null, it returns the first. IterateChildren will return null when done. */ const TiXmlNode* IterateChildren(const TiXmlNode* previous) const; TiXmlNode* IterateChildren(TiXmlNode* previous); /// This flavor of IterateChildren searches for children with a particular 'value' const TiXmlNode* IterateChildren(const char * value, const TiXmlNode* previous) const; TiXmlNode* IterateChildren(const char * value, TiXmlNode* previous); #ifdef TIXML_USE_STL const TiXmlNode* IterateChildren(const std::string& _value, const TiXmlNode* previous) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. TiXmlNode* IterateChildren(const std::string& _value, TiXmlNode* previous) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. #endif /** Add a new node related to this. Adds a child past the LastChild. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertEndChild(const TiXmlNode& addThis); /** Add a new node related to this. Adds a child past the LastChild. NOTE: the node to be added is passed by pointer, and will be henceforth owned (and deleted) by tinyXml. This method is efficient and avoids an extra copy, but should be used with care as it uses a different memory model than the other insert functions. @sa InsertEndChild */ TiXmlNode* LinkEndChild(TiXmlNode* addThis); /** Add a new node related to this. Adds a child before the specified child. Returns a pointer to the new object or NULL if an error occurred. */ TiXmlNode* InsertBeforeChild(TiXmlNode* beforeThis, const TiXmlNode& addThis); /** Add a new node related to this. Adds a child after the specified child. Returns a pointer to the new object or NULL if an error occurred. */ TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis); /** Replace a child of this node. Returns a pointer to the new object or NULL if an error occurred. */ TiXmlNode* ReplaceChild(TiXmlNode* replaceThis, const TiXmlNode& withThis); /// Delete a child of this node. bool RemoveChild(TiXmlNode* removeThis); /// Navigate to a sibling node. const TiXmlNode* PreviousSibling() const { return prev; } TiXmlNode* PreviousSibling() { return prev; } /// Navigate to a sibling node. const TiXmlNode* PreviousSibling(const char *) const; TiXmlNode* PreviousSibling(const char *); #ifdef TIXML_USE_STL const TiXmlNode* PreviousSibling(const std::string& _value) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. TiXmlNode* PreviousSibling(const std::string& _value) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. const TiXmlNode* NextSibling(const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form. TiXmlNode* NextSibling(const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form. #endif /// Navigate to a sibling node. const TiXmlNode* NextSibling() const { return next; } TiXmlNode* NextSibling() { return next; } /// Navigate to a sibling node with the given 'value'. const TiXmlNode* NextSibling(const char *) const; TiXmlNode* NextSibling(const char *); /** Convenience function to get through elements. Calls NextSibling and ToElement. Will skip all non-Element nodes. Returns 0 if there is not another element. */ const TiXmlElement* NextSiblingElement() const; TiXmlElement* NextSiblingElement(); /** Convenience function to get through elements. Calls NextSibling and ToElement. Will skip all non-Element nodes. Returns 0 if there is not another element. */ const TiXmlElement* NextSiblingElement(const char *) const; TiXmlElement* NextSiblingElement(const char *); #ifdef TIXML_USE_STL const TiXmlElement* NextSiblingElement(const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. TiXmlElement* NextSiblingElement(const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. #endif /// Convenience function to get through elements. const TiXmlElement* FirstChildElement() const; TiXmlElement* FirstChildElement(); /// Convenience function to get through elements. const TiXmlElement* FirstChildElement(const char * value) const; TiXmlElement* FirstChildElement(const char * value); #ifdef TIXML_USE_STL const TiXmlElement* FirstChildElement(const std::string& _value) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. TiXmlElement* FirstChildElement(const std::string& _value) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. #endif /** Query the type (as an enumerated value, above) of this node. The possible types are: DOCUMENT, ELEMENT, COMMENT, UNKNOWN, TEXT, and DECLARATION. */ int Type() const { return type; } /** Return a pointer to the Document this node lives in. Returns null if not in a document. */ const TiXmlDocument* GetDocument() const; TiXmlDocument* GetDocument(); /// Returns true if this node has no children. bool NoChildren() const { return !firstChild; } virtual const TiXmlDocument* ToDocument() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual const TiXmlElement* ToElement() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual const TiXmlComment* ToComment() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual const TiXmlUnknown* ToUnknown() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual const TiXmlText* ToText() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual const TiXmlDeclaration* ToDeclaration() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlDocument* ToDocument() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlElement* ToElement() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlComment* ToComment() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlUnknown* ToUnknown() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlText* ToText() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlDeclaration* ToDeclaration() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. /** Create an exact duplicate of this node and return it. The memory must be deleted by the caller. */ virtual TiXmlNode* Clone() const = 0; protected: TiXmlNode(NodeType _type); // Copy to the allocated object. Shared functionality between Clone, Copy constructor, // and the assignment operator. void CopyTo(TiXmlNode* target) const; #ifdef TIXML_USE_STL // The real work of the input operator. virtual void StreamIn(TIXML_ISTREAM* in, TIXML_STRING* tag) = 0; #endif // Figure out what is at *p, and parse it. Returns null if it is not an xml node. TiXmlNode* Identify(const char* start, TiXmlEncoding encoding); TiXmlNode* parent; NodeType type; TiXmlNode* firstChild; TiXmlNode* lastChild; TIXML_STRING value; TiXmlNode* prev; TiXmlNode* next; private: TiXmlNode(const TiXmlNode&); // not implemented. void operator=(const TiXmlNode& base); // not allowed. }; /** An attribute is a name-value pair. Elements have an arbitrary number of attributes, each with an unique name. @note The attributes are not TiXmlNodes, since they are not part of the tinyXML document object model. There are other suggested ways to look at this problem. */ class TiXmlAttribute : public TiXmlBase { friend class TiXmlAttributeSet; public: /// Construct an empty attribute. TiXmlAttribute() : TiXmlBase() { document = 0; prev = next = 0; } #ifdef TIXML_USE_STL /// std::string constructor. TiXmlAttribute(const std::string& _name, const std::string& _value) { name = _name; value = _value; document = 0; prev = next = 0; } #endif /// Construct an attribute with a name and value. TiXmlAttribute(const char * _name, const char * _value) { name = _name; value = _value; document = 0; prev = next = 0; } const char* Name() const { return name.c_str (); } ///< Return the name of this attribute. const char* Value() const { return value.c_str (); } ///< Return the value of this attribute. int IntValue() const; ///< Return the value of this attribute, converted to an integer. double DoubleValue() const; ///< Return the value of this attribute, converted to a double. // Get the tinyxml string representation const TIXML_STRING& NameTStr() const { return name; } /** QueryIntValue examines the value string. It is an alternative to the IntValue() method with richer error checking. If the value is an integer, it is stored in 'value' and the call returns TIXML_SUCCESS. If it is not an integer, it returns TIXML_WRONG_TYPE. A specialized but useful call. Note that for success it returns 0, which is the opposite of almost all other TinyXml calls. */ int QueryIntValue(int* _value) const; /// QueryDoubleValue examines the value string. See QueryIntValue(). int QueryDoubleValue(double* _value) const; void SetName(const char* _name) { name = _name; } ///< Set the name of this attribute. void SetValue(const char* _value) { value = _value; } ///< Set the value. void SetIntValue(int _value); ///< Set the value from an integer. void SetDoubleValue(double _value); ///< Set the value from a double. #ifdef TIXML_USE_STL /// STL std::string form. void SetName(const std::string& _name) { name = _name; } /// STL std::string form. void SetValue(const std::string& _value) { value = _value; } #endif /// Get the next sibling attribute in the DOM. Returns null at end. const TiXmlAttribute* Next() const; TiXmlAttribute* Next(); /// Get the previous sibling attribute in the DOM. Returns null at beginning. const TiXmlAttribute* Previous() const; TiXmlAttribute* Previous(); bool operator==(const TiXmlAttribute& rhs) const { return rhs.name == name; } bool operator<(const TiXmlAttribute& rhs) const { return name < rhs.name; } bool operator>(const TiXmlAttribute& rhs) const { return name > rhs.name; } /* Attribute parsing starts: first letter of the name returns: the next char after the value end quote */ virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); // Prints this Attribute to a FILE stream. virtual void Print(FILE* cfile, int depth) const; virtual void StreamOut(TIXML_OSTREAM * out) const; // [internal use] // Set the document pointer so the attribute can report errors. void SetDocument(TiXmlDocument* doc) { document = doc; } private: TiXmlAttribute(const TiXmlAttribute&); // not implemented. void operator=(const TiXmlAttribute& base); // not allowed. TiXmlDocument* document; // A pointer back to a document, for error reporting. TIXML_STRING name; TIXML_STRING value; TiXmlAttribute* prev; TiXmlAttribute* next; }; /* A class used to manage a group of attributes. It is only used internally, both by the ELEMENT and the DECLARATION. The set can be changed transparent to the Element and Declaration classes that use it, but NOT transparent to the Attribute which has to implement a next() and previous() method. Which makes it a bit problematic and prevents the use of STL. This version is implemented with circular lists because: - I like circular lists - it demonstrates some independence from the (typical) doubly linked list. */ class TiXmlAttributeSet { public: TiXmlAttributeSet(); ~TiXmlAttributeSet(); void Add(TiXmlAttribute* attribute); void Remove(TiXmlAttribute* attribute); const TiXmlAttribute* First() const { return (sentinel.next == &sentinel) ? 0 : sentinel.next; } TiXmlAttribute* First() { return (sentinel.next == &sentinel) ? 0 : sentinel.next; } const TiXmlAttribute* Last() const { return (sentinel.prev == &sentinel) ? 0 : sentinel.prev; } TiXmlAttribute* Last() { return (sentinel.prev == &sentinel) ? 0 : sentinel.prev; } const TiXmlAttribute* Find(const TIXML_STRING& name) const; TiXmlAttribute* Find(const TIXML_STRING& name); private: //*ME: Because of hidden/disabled copy-constructor in TiXmlAttribute (sentinel-element), //*ME: this class must be also use a hidden/disabled copy-constructor !!! TiXmlAttributeSet(const TiXmlAttributeSet&); // not allowed void operator=(const TiXmlAttributeSet&); // not allowed (as TiXmlAttribute) TiXmlAttribute sentinel; }; /** The element is a container class. It has a value, the element name, and can contain other elements, text, comments, and unknowns. Elements also contain an arbitrary number of attributes. */ class TiXmlElement : public TiXmlNode { public: /// Construct an element. TiXmlElement (const char * in_value); #ifdef TIXML_USE_STL /// std::string constructor. TiXmlElement(const std::string& _value); #endif TiXmlElement(const TiXmlElement&); void operator=(const TiXmlElement& base); virtual ~TiXmlElement(); /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. */ const char* Attribute(const char* name) const; /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. If the attribute exists and can be converted to an integer, the integer value will be put in the return 'i', if 'i' is non-null. */ const char* Attribute(const char* name, int* i) const; /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. If the attribute exists and can be converted to an double, the double value will be put in the return 'd', if 'd' is non-null. */ const char* Attribute(const char* name, double* d) const; /** QueryIntAttribute examines the attribute - it is an alternative to the Attribute() method with richer error checking. If the attribute is an integer, it is stored in 'value' and the call returns TIXML_SUCCESS. If it is not an integer, it returns TIXML_WRONG_TYPE. If the attribute does not exist, then TIXML_NO_ATTRIBUTE is returned. */ int QueryIntAttribute(const char* name, int* _value) const; /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). int QueryDoubleAttribute(const char* name, double* _value) const; /// QueryFloatAttribute examines the attribute - see QueryIntAttribute(). int QueryFloatAttribute(const char* name, float* _value) const { double d; int result = QueryDoubleAttribute(name, &d); if (result == TIXML_SUCCESS) { *_value = (float)d; } return result; } /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetAttribute(const char* name, const char * _value); #ifdef TIXML_USE_STL const char* Attribute(const std::string& name) const { return Attribute(name.c_str()); } const char* Attribute(const std::string& name, int* i) const { return Attribute(name.c_str(), i); } const char* Attribute(const std::string& name, double* d) const { return Attribute(name.c_str(), d); } int QueryIntAttribute(const std::string& name, int* _value) const { return QueryIntAttribute(name.c_str(), _value); } int QueryDoubleAttribute(const std::string& name, double* _value) const { return QueryDoubleAttribute(name.c_str(), _value); } /// STL std::string form. void SetAttribute(const std::string& name, const std::string& _value); ///< STL std::string form. void SetAttribute(const std::string& name, int _value); #endif /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetAttribute(const char * name, int value); /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetDoubleAttribute(const char * name, double value); /** Deletes an attribute with the given name. */ void RemoveAttribute(const char * name); #ifdef TIXML_USE_STL void RemoveAttribute(const std::string& name) { RemoveAttribute (name.c_str ()); } ///< STL std::string form. #endif const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element. TiXmlAttribute* FirstAttribute() { return attributeSet.First(); } const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element. TiXmlAttribute* LastAttribute() { return attributeSet.Last(); } /** Convenience function for easy access to the text inside an element. Although easy and concise, GetText() is limited compared to getting the TiXmlText child and accessing it directly. If the first child of 'this' is a TiXmlText, the GetText() returns the character string of the Text node, else null is returned. This is a convenient method for getting the text of simple contained text: @verbatim <foo>This is text</foo> const char* str = fooElement->GetText(); @endverbatim 'str' will be a pointer to "This is text". Note that this function can be misleading. If the element foo was created from this XML: @verbatim <foo><b>This is text</b></foo> @endverbatim then the value of str would be null. The first child node isn't a text node, it is another element. From this XML: @verbatim <foo>This is <b>text</b></foo> @endverbatim GetText() will return "This is ". WARNING: GetText() accesses a child node - don't become confused with the similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are safe type casts on the referenced node. */ const char* GetText() const; /// Creates a new Element and returns it - the returned element is a copy. virtual TiXmlNode* Clone() const; // Print the Element to a FILE stream. virtual void Print(FILE* cfile, int depth) const; /* Attribtue parsing starts: next char past '<' returns: next char past '>' */ virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); virtual const TiXmlElement* ToElement() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlElement* ToElement() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. protected: void CopyTo(TiXmlElement* target) const; void ClearThis(); // like clear, but initializes 'this' object as well // Used to be public [internal use] #ifdef TIXML_USE_STL virtual void StreamIn(TIXML_ISTREAM * in, TIXML_STRING * tag); #endif virtual void StreamOut(TIXML_OSTREAM * out) const; /* [internal use] Reads the "value" of the element -- another element, or text. This should terminate with the current end tag. */ const char* ReadValue(const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding); private: TiXmlAttributeSet attributeSet; }; /** An XML comment. */ class TiXmlComment : public TiXmlNode { public: /// Constructs an empty comment. TiXmlComment() : TiXmlNode(TiXmlNode::COMMENT) {} TiXmlComment(const TiXmlComment&); void operator=(const TiXmlComment& base); virtual ~TiXmlComment() {} /// Returns a copy of this Comment. virtual TiXmlNode* Clone() const; /// Write this Comment to a FILE stream. virtual void Print(FILE* cfile, int depth) const; /* Attribtue parsing starts: at the ! of the !-- returns: next char past '>' */ virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); virtual const TiXmlComment* ToComment() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlComment* ToComment() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. protected: void CopyTo(TiXmlComment* target) const; // used to be public #ifdef TIXML_USE_STL virtual void StreamIn(TIXML_ISTREAM * in, TIXML_STRING * tag); #endif virtual void StreamOut(TIXML_OSTREAM * out) const; private: }; /** XML text. A text node can have 2 ways to output the next. "normal" output and CDATA. It will default to the mode it was parsed from the XML file and you generally want to leave it alone, but you can change the output mode with SetCDATA() and query it with CDATA(). */ class TiXmlText : public TiXmlNode { friend class TiXmlElement; public: /** Constructor for text element. By default, it is treated as normal, encoded text. If you want it be output as a CDATA text element, set the parameter _cdata to 'true' */ TiXmlText (const char * initValue) : TiXmlNode (TiXmlNode::TEXT) { SetValue(initValue); cdata = false; } virtual ~TiXmlText() {} #ifdef TIXML_USE_STL /// Constructor. TiXmlText(const std::string& initValue) : TiXmlNode (TiXmlNode::TEXT) { SetValue(initValue); cdata = false; } #endif TiXmlText(const TiXmlText& copy) : TiXmlNode(TiXmlNode::TEXT) { copy.CopyTo(this); } void operator=(const TiXmlText& base) { base.CopyTo(this); } /// Write this text object to a FILE stream. virtual void Print(FILE* cfile, int depth) const; /// Queries whether this represents text using a CDATA section. bool CDATA() { return cdata; } /// Turns on or off a CDATA representation of text. void SetCDATA(bool _cdata) { cdata = _cdata; } virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); virtual const TiXmlText* ToText() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlText* ToText() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. protected : /// [internal use] Creates a new Element and returns it. virtual TiXmlNode* Clone() const; void CopyTo(TiXmlText* target) const; virtual void StreamOut (TIXML_OSTREAM * out) const; bool Blank() const; // returns true if all white space and new lines // [internal use] #ifdef TIXML_USE_STL virtual void StreamIn(TIXML_ISTREAM * in, TIXML_STRING * tag); #endif private: bool cdata; // true if this should be input and output as a CDATA style text element }; /** In correct XML the declaration is the first entry in the file. @verbatim <?xml version="1.0" standalone="yes"?> @endverbatim TinyXml will happily read or write files without a declaration, however. There are 3 possible attributes to the declaration: version, encoding, and standalone. Note: In this version of the code, the attributes are handled as special cases, not generic attributes, simply because there can only be at most 3 and they are always the same. */ class TiXmlDeclaration : public TiXmlNode { public: /// Construct an empty declaration. TiXmlDeclaration() : TiXmlNode(TiXmlNode::DECLARATION) {} #ifdef TIXML_USE_STL /// Constructor. TiXmlDeclaration( const std::string& _version, const std::string& _encoding, const std::string& _standalone); #endif /// Construct. TiXmlDeclaration( const char* _version, const char* _encoding, const char* _standalone); TiXmlDeclaration(const TiXmlDeclaration& copy); void operator=(const TiXmlDeclaration& copy); virtual ~TiXmlDeclaration() {} /// Version. Will return an empty string if none was found. const char *Version() const { return version.c_str (); } /// Encoding. Will return an empty string if none was found. const char *Encoding() const { return encoding.c_str (); } /// Is this a standalone document? const char *Standalone() const { return standalone.c_str (); } /// Creates a copy of this Declaration and returns it. virtual TiXmlNode* Clone() const; /// Print this declaration to a FILE stream. virtual void Print(FILE* cfile, int depth) const; virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); virtual const TiXmlDeclaration* ToDeclaration() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlDeclaration* ToDeclaration() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. protected: void CopyTo(TiXmlDeclaration* target) const; // used to be public #ifdef TIXML_USE_STL virtual void StreamIn(TIXML_ISTREAM * in, TIXML_STRING * tag); #endif virtual void StreamOut (TIXML_OSTREAM * out) const; private: TIXML_STRING version; TIXML_STRING encoding; TIXML_STRING standalone; }; /** Any tag that tinyXml doesn't recognize is saved as an unknown. It is a tag of text, but should not be modified. It will be written back to the XML, unchanged, when the file is saved. DTD tags get thrown into TiXmlUnknowns. */ class TiXmlUnknown : public TiXmlNode { public: TiXmlUnknown() : TiXmlNode(TiXmlNode::UNKNOWN) {} virtual ~TiXmlUnknown() {} TiXmlUnknown(const TiXmlUnknown& copy) : TiXmlNode(TiXmlNode::UNKNOWN) { copy.CopyTo(this); } void operator=(const TiXmlUnknown& copy) { copy.CopyTo(this); } /// Creates a copy of this Unknown and returns it. virtual TiXmlNode* Clone() const; /// Print this Unknown to a FILE stream. virtual void Print(FILE* cfile, int depth) const; virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); virtual const TiXmlUnknown* ToUnknown() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlUnknown* ToUnknown() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. protected: void CopyTo(TiXmlUnknown* target) const; #ifdef TIXML_USE_STL virtual void StreamIn(TIXML_ISTREAM * in, TIXML_STRING * tag); #endif virtual void StreamOut (TIXML_OSTREAM * out) const; private: }; class nFile; /** Always the top level node. A document binds together all the XML pieces. It can be saved, loaded, and printed to the screen. The 'value' of a document node is the xml file name. */ class TiXmlDocument : public TiXmlNode { public: /// Create an empty document, that has no name. TiXmlDocument(); /// Create a document with a name. The name of the document is also the filename of the xml. TiXmlDocument(const char * documentName); #ifdef TIXML_USE_STL /// Constructor. TiXmlDocument(const std::string& documentName); #endif TiXmlDocument(const TiXmlDocument& copy); void operator=(const TiXmlDocument& copy); virtual ~TiXmlDocument() {} /** Load a file using the current document value. Returns true if successful. Will delete any existing document data before loading. */ bool LoadFile(TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING); /// Save a file using the current document value. Returns true if successful. bool SaveFile() const; /// Load a file using the given filename. Returns true if successful. bool LoadFile(const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING); /// Save a file using the given filename. Returns true if successful. bool SaveFile(const char * filename) const; /** Load a file using the given FILE*. Returns true if successful. Note that this method doesn't stream - the entire object pointed at by the FILE* will be interpreted as an XML file. TinyXML doesn't stream in XML from the current file location. Streaming may be added in the future. */ bool LoadFile(nFile*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING); /// Save a file using the given FILE*. Returns true if successful. bool SaveFile(FILE*) const; #ifdef TIXML_USE_STL bool LoadFile(const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING) ///< STL std::string version. { StringToBuffer f(filename); return (f.buffer && LoadFile(f.buffer, encoding)); } bool SaveFile(const std::string& filename) const ///< STL std::string version. { StringToBuffer f(filename); return (f.buffer && SaveFile(f.buffer)); } #endif /** Parse the given null terminated block of xml data. Passing in an encoding to this method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml to use that encoding, regardless of what TinyXml might otherwise try to detect. */ virtual const char* Parse(const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING); /** Get the root element -- the only top level element -- of the document. In well formed XML, there should only be one. TinyXml is tolerant of multiple elements at the document level. */ const TiXmlElement* RootElement() const { return FirstChildElement(); } TiXmlElement* RootElement() { return FirstChildElement(); } /** If an error occurs, Error will be set to true. Also, - The ErrorId() will contain the integer identifier of the error (not generally useful) - The ErrorDesc() method will return the name of the error. (very useful) - The ErrorRow() and ErrorCol() will return the location of the error (if known) */ bool Error() const { return error; } /// Contains a textual (english) description of the error if one occurs. const char * ErrorDesc() const { return errorDesc.c_str (); } /** Generally, you probably want the error string (ErrorDesc()). But if you prefer the ErrorId, this function will fetch it. */ int ErrorId() const { return errorId; } /** Returns the location (if known) of the error. The first column is column 1, and the first row is row 1. A value of 0 means the row and column wasn't applicable (memory errors, for example, have no row/column) or the parser lost the error. (An error in the error reporting, in that case.) @sa SetTabSize, Row, Column */ int ErrorRow() { return errorLocation.row+1; } int ErrorCol() { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow() /** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol()) to report the correct values for row and column. It does not change the output or input in any way. By calling this method, with a tab size greater than 0, the row and column of each node and attribute is stored when the file is loaded. Very useful for tracking the DOM back in to the source file. The tab size is required for calculating the location of nodes. If not set, the default of 4 is used. The tabsize is set per document. Setting the tabsize to 0 disables row/column tracking. Note that row and column tracking is not supported when using operator>>. The tab size needs to be enabled before the parse or load. Correct usage: @verbatim TiXmlDocument doc; doc.SetTabSize(8); doc.Load("myfile.xml"); @endverbatim @sa Row, Column */ void SetTabSize(int _tabsize) { tabsize = _tabsize; } int TabSize() const { return tabsize; } /** If you have handled the error, it can be reset with this call. The error state is automatically cleared if you Parse a new XML block. */ void ClearError() { error = false; errorId = 0; errorDesc = ""; errorLocation.row = errorLocation.col = 0; //errorLocation.last = 0; } /** Dump the document to standard out. */ void Print() const { Print(stdout, 0); } /// Print this Document to a FILE stream. virtual void Print(FILE* cfile, int depth = 0) const; // [internal use] void SetError(int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding); virtual const TiXmlDocument* ToDocument() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlDocument* ToDocument() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. protected : virtual void StreamOut (TIXML_OSTREAM * out) const; // [internal use] virtual TiXmlNode* Clone() const; #ifdef TIXML_USE_STL virtual void StreamIn(TIXML_ISTREAM * in, TIXML_STRING * tag); #endif private: void CopyTo(TiXmlDocument* target) const; bool error; int errorId; TIXML_STRING errorDesc; int tabsize; TiXmlCursor errorLocation; bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write. }; /** A TiXmlHandle is a class that wraps a node pointer with null checks; this is an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml DOM structure. It is a separate utility class. Take an example: @verbatim <Document> <Element attributeA = "valueA"> <Child attributeB = "value1" /> <Child attributeB = "value2" /> </Element> <Document> @endverbatim Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very easy to write a *lot* of code that looks like: @verbatim TiXmlElement* root = document.FirstChildElement("Document"); if (root) { TiXmlElement* element = root->FirstChildElement("Element"); if (element) { TiXmlElement* child = element->FirstChildElement("Child"); if (child) { TiXmlElement* child2 = child->NextSiblingElement("Child"); if (child2) { // Finally do something useful. @endverbatim And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity of such code. A TiXmlHandle checks for null pointers so it is perfectly safe and correct to use: @verbatim TiXmlHandle docHandle(&document); TiXmlElement* child2 = docHandle.FirstChild("Document").FirstChild("Element").Child("Child", 1).Element(); if (child2) { // do something useful @endverbatim Which is MUCH more concise and useful. It is also safe to copy handles - internally they are nothing more than node pointers. @verbatim TiXmlHandle handleCopy = handle; @endverbatim What they should not be used for is iteration: @verbatim int i=0; while (true) { TiXmlElement* child = docHandle.FirstChild("Document").FirstChild("Element").Child("Child", i).Element(); if (!child) break; // do something ++i; } @endverbatim It seems reasonable, but it is in fact two embedded while loops. The Child method is a linear walk to find the element, so this code would iterate much more than it needs to. Instead, prefer: @verbatim TiXmlElement* child = docHandle.FirstChild("Document").FirstChild("Element").FirstChild("Child").Element(); for (child; child; child = child->NextSiblingElement()) { // do something } @endverbatim */ class TiXmlHandle { public: /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. TiXmlHandle(TiXmlNode* _node) { this->node = _node; } /// Copy constructor TiXmlHandle(const TiXmlHandle& ref) { this->node = ref.node; } TiXmlHandle operator=(const TiXmlHandle& ref) { this->node = ref.node; return *this; } /// Return a handle to the first child node. TiXmlHandle FirstChild() const; /// Return a handle to the first child node with the given name. TiXmlHandle FirstChild(const char * value) const; /// Return a handle to the first child element. TiXmlHandle FirstChildElement() const; /// Return a handle to the first child element with the given name. TiXmlHandle FirstChildElement(const char * value) const; /** Return a handle to the "index" child with the given name. The first child is 0, the second 1, etc. */ TiXmlHandle Child(const char* value, int index) const; /** Return a handle to the "index" child. The first child is 0, the second 1, etc. */ TiXmlHandle Child(int index) const; /** Return a handle to the "index" child element with the given name. The first child element is 0, the second 1, etc. Note that only TiXmlElements are indexed: other types are not counted. */ TiXmlHandle ChildElement(const char* value, int index) const; /** Return a handle to the "index" child element. The first child element is 0, the second 1, etc. Note that only TiXmlElements are indexed: other types are not counted. */ TiXmlHandle ChildElement(int index) const; #ifdef TIXML_USE_STL TiXmlHandle FirstChild(const std::string& _value) const { return FirstChild(_value.c_str()); } TiXmlHandle FirstChildElement(const std::string& _value) const { return FirstChildElement(_value.c_str()); } TiXmlHandle Child(const std::string& _value, int index) const { return Child(_value.c_str(), index); } TiXmlHandle ChildElement(const std::string& _value, int index) const { return ChildElement(_value.c_str(), index); } #endif /// Return the handle as a TiXmlNode. This may return null. TiXmlNode* Node() const { return node; } /// Return the handle as a TiXmlElement. This may return null. TiXmlElement* Element() const { return ((node && node->ToElement()) ? node->ToElement() : 0); } /// Return the handle as a TiXmlText. This may return null. TiXmlText* Text() const { return ((node && node->ToText()) ? node->ToText() : 0); } /// Return the handle as a TiXmlUnknown. This may return null; TiXmlUnknown* Unknown() const { return ((node && node->ToUnknown()) ? node->ToUnknown() : 0); } private: TiXmlNode* node; }; #ifdef _MSC_VER #pragma warning(pop) #endif #endif
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 1520 ] ] ]
cf34ad6710ca0f5dda632ce0636aa40c122318d7
3e1e78cd64328f947fdd721213f75b47a810d68c
/windows/UpdaterUI/IpUpdatesLog.cpp
236a665b7ec0b4729ee668a7ec65c890e410aa39
[]
no_license
phuonglelephuong/dynamicipupdate
daeb10b891a06da80d345ced677cd96bdaa62d8f
58eb721427f132900d81ee95acf3cb09ea133f59
refs/heads/master
2021-01-15T20:53:17.046848
2011-12-06T18:41:32
2011-12-06T18:45:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,431
cpp
#include "stdafx.h" #include "IpUpdatesLog.h" #include "MiscUtil.h" #include "StrUtil.h" // When we reach that many updates, we'll trim the ip updates log #define IP_UPDATES_PURGE_LIMIT 1000 // After we reach IP_UPDATES_PURGE_LIMIT, we'll only write out // IP_UPDATES_AFTER_PURGE_SIZE items, so that we don't have to purge every // time once we reach purge limit #define IP_UPDATES_SIZE_AFTER_PURGE 500 // Linked list of ip updates. Newest are at the front. IpUpdate * g_ipUpdates = NULL; static FILE * gIpUpdatesLogFile; CString IpUpdatesLogFileName() { CString fileName = AppDataDir(); fileName += _T("\\ipupdateslog.txt"); return fileName; } static void str_append(char **dstInOut, char *s) { char *dst = *dstInOut; size_t len = strlen(s); memcpy(dst, s, len); dst += len; *dstInOut = dst; } char *IpUpdatesAsText(IpUpdate *head, size_t *sizeOut) { IpUpdate *curr = head; char *s = NULL; size_t sizeNeeded = 0; while (curr) { if (curr->ipAddress && curr->time) { sizeNeeded += strlen(curr->ipAddress); sizeNeeded += strlen(curr->time); sizeNeeded += 3; // space + '\r\n' } curr = curr->next; } s = (char*)malloc(sizeNeeded+1); // +1 for terminating zero char *tmp = s; curr = head; while (curr) { if (curr->ipAddress && curr->time) { str_append(&tmp, curr->ipAddress); str_append(&tmp, " "); str_append(&tmp, curr->time); str_append(&tmp, "\r\n"); } curr = curr->next; } *tmp = 0; *sizeOut = sizeNeeded + 1; return s; } static void FreeIpUpdate(IpUpdate *ipUpdate) { assert(ipUpdate); if (!ipUpdate) return; free(ipUpdate->ipAddress); free(ipUpdate->time); free(ipUpdate); } static void FreeIpUpdatesFromElement(IpUpdate *curr) { while (curr) { IpUpdate *next = curr->next; FreeIpUpdate(curr); curr = next; } } static void InsertIpUpdate(const char *ipAddress, const char *time, bool ok) { assert(ipAddress); assert(time); if (!ipAddress || !time) return; IpUpdate *ipUpdate = SA(IpUpdate); if (!ipUpdate) return; ipUpdate->ipAddress = strdup(ipAddress); ipUpdate->time = strdup(time); ipUpdate->ok = ok; if (!ipUpdate->ipAddress || !ipUpdate->time) { FreeIpUpdate(ipUpdate); return; } ipUpdate->next = g_ipUpdates; g_ipUpdates = ipUpdate; } static inline bool is_newline_char(char c) { return (c == '\r') || (c == '\n'); } // at this point <*dataStartInOut> points at the beginning of the log file, // which consists of lines in format: // $ipaddr $time\r\n static bool ExtractIpAddrAndTime(char **dataStartInOut, uint64_t *dataSizeLeftInOut, char **ipAddrOut, char **timeOut, bool *okOut) { char *curr = *dataStartInOut; uint64_t dataSizeLeft = *dataSizeLeftInOut; char *time = NULL; char *ipAddr = curr; bool ok = true; if (0 == dataSizeLeft) return false; if (*curr == '!') { ok = false; --dataSizeLeft; ++ipAddr; ++curr; } // first space separates $ipaddr from $time while ((dataSizeLeft > 0) && (*curr != ' ')) { --dataSizeLeft; ++curr; } // didn't find the space => something's wrong if (0 == dataSizeLeft) return false; assert(*curr == ' '); // replace space with 0 to make ipAddr a null-terminated string *curr = 0; --dataSizeLeft; ++curr; time = curr; // find "\r\n' at the end while ((dataSizeLeft > 0) && !is_newline_char(*curr)) { --dataSizeLeft; ++curr; } // replace '\r\n' with 0, to make time a null-terminated string while ((dataSizeLeft > 0) && is_newline_char(*curr)) { *curr++ = 0; --dataSizeLeft; } *ipAddrOut = ipAddr; *timeOut = time; *dataSizeLeftInOut = dataSizeLeft; *dataStartInOut = curr; *okOut = ok; return true; } // load up to IP_UPDATES_HISTORY_MAX latest entries from ip updates log // When we finish g_ipUpdates is a list of ip updates with the most recent // at the beginning of the list static void ParseIpLogHistory(char *data, uint64_t dataSize) { char *ipAddr = NULL; char *time = NULL; bool updateOk; while (dataSize != 0) { bool ok = ExtractIpAddrAndTime(&data, &dataSize, &ipAddr, &time, &updateOk); if (!ok) { assert(0); break; } InsertIpUpdate(ipAddr, time, updateOk); } } static void LogIpUpdateEntry(FILE *log, const char *ipAddress, const char *time, bool ok) { assert(log && ipAddress && time); if (!log || !ipAddress || !time) return; size_t slen = strlen(ipAddress); if (!ok) { fwrite("!", 1, 1, log); } fwrite(ipAddress, slen, 1, log); fwrite(" ", 1, 1, log); slen = strlen(time); fwrite(time, slen, 1, log); fwrite("\r\n", 2, 1, log); fflush(log); } static void LoadAndParseHistory(const TCHAR *logFileName) { uint64_t dataSize; char *data = FileReadAll(logFileName, &dataSize); if (!data) return; ParseIpLogHistory(data, dataSize); free(data); } void LoadIpUpdatesHistory() { assert(!gIpUpdatesLogFile); CString logFileName = IpUpdatesLogFileName(); LoadAndParseHistory(logFileName); gIpUpdatesLogFile = _tfopen(logFileName, _T("ab")); } static void LogIpUpdate(const char *ipAddress, bool ok) { char timeBuf[256]; __time64_t ltime; struct tm *today; _time64(&ltime); today = _localtime64(&ltime); strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M", today); assert(gIpUpdatesLogFile); LogIpUpdateEntry(gIpUpdatesLogFile, ipAddress, timeBuf, ok); InsertIpUpdate(ipAddress, timeBuf, ok); } void LogIpUpdateOk(const char *ipAddress) { LogIpUpdate(ipAddress, true); } void LogIpUpdateNotYours(const char *ipAddress) { LogIpUpdate(ipAddress, false); } static void CloseIpUpdatesLog() { if (gIpUpdatesLogFile) { fclose(gIpUpdatesLogFile); gIpUpdatesLogFile = NULL; } } // reverse g_ipUpdates and return size of the list size_t ReverseIpUpdateList() { size_t size = 0; IpUpdate *newHead = NULL; IpUpdate *curr = g_ipUpdates; while (curr) { IpUpdate *next = curr->next; curr->next = newHead; newHead = curr; curr = next; size++; } g_ipUpdates = newHead; return size; } static void WriteIpLogHistory(IpUpdate *head) { CString logFileName = IpUpdatesLogFileName(); FILE *log = _tfopen(logFileName, _T("wb")); IpUpdate *curr = head; while (curr) { LogIpUpdateEntry(log, curr->ipAddress, curr->time, curr->ok); curr = curr->next; } fclose(log); } // if we have more than IP_UPDATES_HISTORY_MAX entries, over-write // the log with only the recent entries static void OverwriteLogIfReachedLimit() { // in order to (possibly) write out log entries, we have to write from // the end, so we need to reverse the list. We combine this with // calculating the size because we need to know the size to decide // if we need to overwrite the log size_t size = ReverseIpUpdateList(); if (size < IP_UPDATES_PURGE_LIMIT) return; // skip the entries we don't want to write out assert(size > IP_UPDATES_SIZE_AFTER_PURGE); size_t toSkip = size - IP_UPDATES_SIZE_AFTER_PURGE; IpUpdate *curr = g_ipUpdates; while (curr && (toSkip != 0)) { curr = curr->next; toSkip--; } // write the rest to the new log WriteIpLogHistory(curr); } void FreeIpUpdatesHistory() { CloseIpUpdatesLog(); OverwriteLogIfReachedLimit(); FreeIpUpdatesFromElement(g_ipUpdates); g_ipUpdates = NULL; }
[ [ [ 1, 323 ] ] ]
563c078edb2e8f325777e8385bd460c02f5b10f6
df238aa31eb8c74e2c208188109813272472beec
/BCGInclude/BCGPVisualManagerVS2008.h
68503f0df5ae50614c30a370959de38f244d9c0c
[]
no_license
myme5261314/plugin-system
d3166f36972c73f74768faae00ac9b6e0d58d862
be490acba46c7f0d561adc373acd840201c0570c
refs/heads/master
2020-03-29T20:00:01.155206
2011-06-27T15:23:30
2011-06-27T15:23:30
39,724,191
0
0
null
null
null
null
UTF-8
C++
false
false
3,523
h
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of BCGControlBar Library Professional Edition // Copyright (C) 1998-2008 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // // BCGPVisualManagerVS2008.cpp: implementation of the CBCGPVisualManagerVS2008 class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_BCGPVISUALMANAGERVS2008_H__F2994064_A72E_4AF2_A8DD_3799EF9D4199__INCLUDED_) #define AFX_BCGPVISUALMANAGERVS2008_H__F2994064_A72E_4AF2_A8DD_3799EF9D4199__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "bcgpvisualmanagervs2005.h" class BCGCBPRODLLEXPORT CBCGPVisualManagerVS2008 : public CBCGPVisualManagerVS2005 { DECLARE_DYNCREATE(CBCGPVisualManagerVS2008) public: CBCGPVisualManagerVS2008(); virtual ~CBCGPVisualManagerVS2008(); virtual void OnUpdateSystemColors (); // Menubar support: virtual void OnFillBarBackground (CDC* pDC, CBCGPBaseControlBar* pBar, CRect rectClient, CRect rectClip, BOOL bNCArea = FALSE); virtual void OnHighlightRarelyUsedMenuItems (CDC* pDC, CRect rectRarelyUsed); virtual void OnHighlightMenuItem (CDC*pDC, CBCGPToolbarMenuButton* pButton, CRect rect, COLORREF& clrText); virtual COLORREF OnDrawControlBarCaption (CDC* pDC, CBCGPDockingControlBar* pBar, BOOL bActive, CRect rectCaption, CRect rectButtons); virtual CRect GetMenuImageFrameOffset () const { return CRect (4, 2, 0, 2); } virtual void OnDrawButtonBorder (CDC* pDC, CBCGPToolbarButton* pButton, CRect rect, CBCGPVisualManager::BCGBUTTON_STATE state); virtual void OnFillButtonInterior (CDC* pDC, CBCGPToolbarButton* pButton, CRect rect, CBCGPVisualManager::BCGBUTTON_STATE state); // Tabs support: virtual void OnDrawTab (CDC* pDC, CRect rectTab, int iTab, BOOL bIsActive, const CBCGPBaseTabWnd* pTabWnd); virtual void OnEraseTabsArea (CDC* pDC, CRect rect, const CBCGPBaseTabWnd* pTabWnd); virtual void OnEraseTabsButton (CDC* pDC, CRect rect, CBCGPButton* pButton, CBCGPBaseTabWnd* pWndTab); virtual BOOL OnEraseTabsFrame (CDC* pDC, CRect rect, const CBCGPBaseTabWnd* pTabWnd); virtual int GetMDITabsBordersSize () { return 4; } virtual BOOL IsMDITabsTopEdge () { return FALSE; } virtual BOOL AlwaysHighlight3DTabs () const { return TRUE; } virtual void GetTabFrameColors (const CBCGPBaseTabWnd* pTabWnd, COLORREF& clrDark, COLORREF& clrBlack, COLORREF& clrHighlight, COLORREF& clrFace, COLORREF& clrDarkShadow, COLORREF& clrLight, CBrush*& pbrFace, CBrush*& pbrBlack); virtual void OnDrawTabResizeBar (CDC* pDC, CBCGPBaseTabWnd* pWndTab, BOOL bIsVert, CRect rect, CBrush* pbrFace, CPen* pPen); // Auto-hide buttons: virtual void OnDrawAutoHideButtonBorder (CDC* pDC, CRect rectBounds, CRect rectBorderSize, CBCGPAutoHideButton* pButton); virtual COLORREF OnFillCommandsListBackground (CDC* pDC, CRect rect, BOOL bIsSelected = FALSE); protected: BOOL m_bOSColors; }; #endif // !defined(AFX_BCGPVISUALMANAGERVS2008_H__F2994064_A72E_4AF2_A8DD_3799EF9D4199__INCLUDED_)
[ "myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5" ]
[ [ [ 1, 99 ] ] ]
f30c7c37a2c655c6d39579eb92a531dbfbc98eb3
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/ModelsC/ClevLand/FLOT.H
ebde95699fea9e30cbacabd41ef1780777903238
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,869
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #ifndef __FLOT_H #define __FLOT_H #ifndef __SC_DEFS_H #include "sc_defs.h" #endif #define BASIC1 #define SIZEDST1 #include "models.h" #ifndef __M_SURGE_H #include "m_surge.h" #endif #ifndef __2D_FN_H #include "2d_fn.h" #endif #ifdef __FLOT_CPP #define DllImportExport DllExport #elif !defined(CLEVLAND) #define DllImportExport DllImport #else #define DllImportExport #endif //=========================================================================== DEFINE_TAGOBJ(Flot); /*#C: Flotation Cell - Multiple Inputs and Outputs */ class DllImportExport Flot : public MN_Surge { protected: SzPartCrv1 SizeRec;//1, SizeRec2, SizeRec3; public: double SS_Lvl, Eff, Rec, Grd, Grade; byte nAbove, nBelow; long iFlot, iSec; byte iColl, RM, Fine; byte SecFlot; SpConduit QFd; double QmSIn, QmLIn, Factor; double TlSol, TlLiq, FlSol, FlLiq; double TotRecover, Grade2; C2DFn FlotFn; Flot(pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach); virtual ~Flot (){}; virtual void BuildDataDefn(DataDefnBlk & DDB); virtual flag DataXchg(DataChangeBlk & DCB); virtual flag ValidateData(ValidateDataBlk & VDB); virtual void StartSolution(); virtual void EvalSteadyState(); virtual void EvalJoinPressures(); virtual void EvalJoinFlows(int JoinNo); virtual void EvalProducts(); private: }; //=========================================================================== #undef DllImportExport #endif
[ [ [ 1, 73 ] ] ]
26b660d7435041e621d078a26329b78048e791f0
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.6/cbear.berlios.de/windows/security_attributes.hpp
fb7c20d4045c5688dd885fdcbf7fa1c7c30f5200
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
2,020
hpp
/* The MIT License Copyright (c) 2005 C Bear (http://cbear.berlios.de) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CBEAR_BERLIOS_DE_WINDOWS_SECURITY_ATTRIBUTES_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_SECURITY_ATTRIBUTES_HPP_INCLUDED #include <cbear.berlios.de/policy/main.hpp> #include <cbear.berlios.de/windows/base.hpp> namespace cbear_berlios_de { namespace windows { /* // Security descriptor. class security_attributes: public policy::wrap<security_attributes, ::SECURITY_ATTRIBUTES *> { public: typedef policy::wrap<security_attributes, ::SECURITY_ATTRIBUTES *> wrap_type; security_attributes() {} explicit security_attributes(internal_type X): wrap_type(X) {} }; */ // Security descriptor. class security_attributes: public base::initialized< ::SECURITY_ATTRIBUTES *> { public: typedef base::initialized< ::SECURITY_ATTRIBUTES *> base_t; security_attributes() {} explicit security_attributes(value_t X): base_t(X) {} }; } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 59 ] ] ]
37d427811068c6f79bbc31d884649eef2998e50d
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Tutorials/Tutorial_2_3/App.cpp
c24303f5377a728e78b0edf5d68f15e741523dbd
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
3,759
cpp
#include "App.h" #include "nGENE.h" void App::createApplication() { FrameworkWin32::createApplication(); m_pMouse->setSensitivity(0.02f); m_pPartitioner = new ScenePartitionerQuadTree(); SceneManager* sm = Engine::getSingleton().getSceneManager(0); sm->setScenePartitioner(m_pPartitioner); Renderer& renderer = Renderer::getSingleton(); renderer.setClearColour(0); renderer.setCullingMode(CULL_CW); uint anisotropy = 0; renderer.getDeviceRender().testCapabilities(CAPS_MAX_ANISOTROPY, &anisotropy); for(uint i = 0; i < 8; ++i) renderer.setAnisotropyLevel(i, anisotropy); CameraFirstPerson* cam; cam = (CameraFirstPerson*)sm->createCamera(L"CameraFirstPerson", L"Camera"); cam->setVelocity(10.0f); cam->setPosition(Vector3(0.0f, 5.0f, -10.0f)); sm->getRootNode()->addChild(L"Camera", cam); Engine::getSingleton().setActiveCamera(cam); NodeMesh <MeshLoadPolicyXFile>* pSculp = sm->createMesh <MeshLoadPolicyXFile>(L"statue.x"); pSculp->setPosition(0.0f, 0.0f, 7.0f); pSculp->setScale(0.25f, 0.25f, 0.25f); Surface* pSurface = pSculp->getSurface(L"surface_2"); pSurface->flipWindingOrder(); Material* matstone = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"dotCel"); pSurface->setMaterial(matstone); sm->getRootNode()->addChild(L"Sculpture", *pSculp); PrefabBox* pBox = sm->createBox(100.0f, 0.5f, 100.0f, Vector2(80.0f, 80.0f)); pBox->setPosition(0.0f, 1.2, 0.0f); pSurface = pBox->getSurface(L"Base"); Material* matGround = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"normalMap"); pSurface->setMaterial(matGround); sm->getRootNode()->addChild(L"Plane", pBox); NodeLight* pLight = sm->createLight(LT_DIRECTIONAL); pLight->setPosition(-4.0f, 5.0f, 0.0f); pLight->setDirection(Vector3(0.7f, -0.5f, 1.0f)); pLight->setDrawDebug(false); Colour clrWorld(204, 204, 0); pLight->setColour(clrWorld); pLight->setRadius(180.0f); sm->getRootNode()->addChild(L"WorldLight", *pLight); renderer.addLight(pLight); m_pInputListener = new MyInputListener(); m_pInputListener->setApp(this); InputSystem::getSingleton().addInputListener(m_pInputListener); PhysicsWorld* pWorld = Physics::getSingleton().createWorld(L"MyPhysicsWorld"); PhysicsMaterial* physMat = pWorld->createPhysicsMaterial(L"DefaultMaterial"); physMat->setRestitution(0.5f); physMat->setDynamicFriction(0.5f); physMat->setStaticFriction(0.5f); pWorld->setGravity(Vector3(0.0f, -9.8f, 0.0f)); PhysicsActor* pActor = pWorld->createPhysicsActorMesh(pSculp->getScale(), *pSculp->getSurface(L"surface_2")->getVertexBuffer()); pActor->attachNode(pSculp); pActor->setShapeMaterial(0, *physMat); pActor = pWorld->createPhysicsActor(L"Box", Vector3(100.0f, 0.5f, 100.0f)); pActor->attachNode(pBox); pActor->setShapeMaterial(0, *physMat); pWorld->addPhysicsActor(L"Plane", pActor); CONTROLLER_DESC charDesc; charDesc.height = 2.0f; charDesc.obstacleLimit = 0.7f; charDesc.radius = 0.8f; m_pController = pWorld->createController(charDesc); m_pController->attachNode(cam); pWorld->addController(L"Player", m_pController); MaterialLibrary* pMatLib = MaterialManager::getSingleton().getLibrary(L"default"); Material* pMaterial = pMatLib->getMaterial(L"inverse"); postEffect.priority = 0; postEffect.material = pMaterial; postEffect.material->setEnabled(true); PostStage* postStage = ((PostStage*)Renderer::getSingleton().getRenderStage(L"PostProcess")); postStage->addToRender(&postEffect); } CharacterController* App::getController() const { return m_pController; } int main() { App app; app.createApplication(); app.run(); app.shutdown(); return 0; }
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 114 ] ] ]
3fab2cdfa45135795036a3b78ea46f9a08d194f6
3d560d0b4772580943946c78e2612ac0589c7958
/id2type_cast/detail/switch_impl.hpp
7a9aef2a298569e252a969e531173fc44435d0d9
[]
no_license
black-square/id2type-cast
b792f9d9c00afebba856494db58a4151dcfd2b33
1a313b55c1dac2ea388c943fa4bf326eaa1957c3
refs/heads/master
2020-05-30T13:03:58.304192
2011-11-01T09:46:58
2011-11-01T09:46:58
32,418,189
0
0
null
null
null
null
UTF-8
C++
false
false
2,380
hpp
#ifndef ID2TYPE_CAST_TYPE_SWITCH_IMPL_HPP #define ID2TYPE_CAST_TYPE_SWITCH_IMPL_HPP #include <cassert> #include "./pp_repeat.hpp" #ifndef ID2TYPE_CAST_SWICTH_IMPL_MAX_TYPES //BOOST_VARIANT_LIMIT_TYPES = BOOST_MPL_LIMIT_LIST_SIZE = 20 #define ID2TYPE_CAST_SWICTH_IMPL_MAX_TYPES 20 #endif namespace i2tc { namespace detail { template<class Functor, class TypeList, class Base> class switch_impl { public: typedef Functor &functor_ref; typedef typename Functor::return_value return_value; typedef Base *base_type_ptr; enum { types_count = type_list::size<TypeList>::value }; static return_value cast( id_type n, base_type_ptr type, functor_ref functor ) { assert( n >= 0 && n <= types_count ); #define INT2TYPE_CAST_PP_DEF( n ) case (n): return cast_impl<(n)>( functor, type ); switch(n) { ID2TYPE_CAST_PP_REPEAT( ID2TYPE_CAST_SWICTH_IMPL_MAX_TYPES, INT2TYPE_CAST_PP_DEF ) default: return error_func(); } #undef INT2TYPE_CAST_PP_DEF } private: static return_value error_func() { assert(false); return return_value(); } template<id_type N> static return_value cast_impl_impl( functor_ref functor, base_type_ptr type, detail::int2type<true> ) { typedef typename type_list::at<TypeList, N>::type list_type; typedef typename detail::select<detail::is_const<Base>::value, const list_type, list_type>::result cast_type; return functor( static_cast<cast_type *>(type) ); } template<id_type N> static return_value cast_impl_impl( functor_ref functor, base_type_ptr type, detail::int2type<false> ) { (void)functor; (void)type; return error_func(); } template<id_type N> static return_value cast_impl( functor_ref functor, base_type_ptr type ) { return cast_impl_impl<N>( functor, type, typename detail::select< (N < types_count) && type_list::is_valid<TypeList, N>::value, detail::int2type<true>, detail::int2type<false> >::result() ); } }; }} #endif
[ [ [ 1, 79 ] ] ]
869fbcb07d9c16f73aab1cf7748afa579c2bd935
9e2c39ce4b2a226a6db1f5a5d361dea4b2f02345
/tools/LePlatz/Widgets/FocusSpinBox.cpp
3a7b4da5cd651f9abd7259deb415e0e434ed5515
[]
no_license
gonzalodelgado/uzebox-paul
38623933e0fb34d7b8638b95b29c4c1d0b922064
c0fa12be79a3ff6bbe70799f2e8620435ce80a01
refs/heads/master
2016-09-05T22:24:29.336414
2010-07-19T07:37:17
2010-07-19T07:37:17
33,088,815
0
0
null
null
null
null
UTF-8
C++
false
false
390
cpp
#include "FocusSpinBox.h" FocusSpinBox::FocusSpinBox(QWidget *parent) : QSpinBox(parent) { setFocusPolicy(Qt::StrongFocus); } void FocusSpinBox::focusInEvent (QFocusEvent *event) { emit receivedFocus(); QSpinBox::focusInEvent(event); } void FocusSpinBox::focusOutEvent (QFocusEvent *event) { emit focusLost(); QSpinBox::focusOutEvent(event); }
[ "[email protected]@08aac7ea-4340-11de-bfec-d9b18e096ff9" ]
[ [ [ 1, 19 ] ] ]
c0898ab7e7ee856246ffec655e8096e43ca0b599
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/ModelEditor/ArnView.cpp
16c274ccaa112ddad92baa8330fc328cd3804d38
[]
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
12,423
cpp
// ArnView.cpp : implementation file // #include "stdafx.h" #include "ModelEditor.h" #include "ArnView.h" #include "ModelEditorDoc.h" // Rendering thread UINT __cdecl RenderingThreadProc(LPVOID lParam) { CArnView* pView; pView = (CArnView*)lParam; while (pView->m_bReady && pView->m_bRunningThread) { pView->Render(); } return 0; } ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// // CArnView IMPLEMENT_DYNCREATE(CArnView, CFormView) CArnView::CArnView() : CFormView(CArnView::IDD), m_bReady(FALSE), m_bRunningThread(FALSE), m_bIsNowRendering(FALSE), m_bIsOpeningFile(FALSE) , m_cstrSelGroupName(_T("")) , m_cstrTestField(_T("")) , m_iAnimTime(0) { } CArnView::~CArnView() { m_pSmallImage->DeleteImageList(); SAFE_DELETE(m_pSmallImage); } void CArnView::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); DDX_Control(pDX, IDC_NODELIST, m_listNodes); DDX_Control(pDX, IDC_ANIMLIST, m_listAnim); DDX_Control(pDX, IDC_EDIT_SEL_GROUP_NAME, m_editSelGroupName); DDX_Text(pDX, IDC_EDIT1, m_cstrTestField); DDV_MaxChars(pDX, m_cstrTestField, 128); DDX_Control(pDX, IDC_BTN_CHANGE_GROUP_NAME, m_btnChangeGroupName); DDX_Slider(pDX, IDC_SLIDER_ANIM_TIME, m_iAnimTime); DDX_Control(pDX, IDC_SLIDER_ANIM_TIME, m_animSliderTime); DDX_Control(pDX, IDC_TAB1, m_tcTest); } BEGIN_MESSAGE_MAP(CArnView, CFormView) ON_WM_DESTROY() ON_EN_CHANGE(IDC_EDIT1, &CArnView::OnEnChangeEdit1) ON_NOTIFY(LVN_ITEMCHANGED, IDC_NODELIST, &CArnView::OnLvnItemchangedNodelist) ON_NOTIFY(LVN_ITEMCHANGED, IDC_ANIMLIST, &CArnView::OnLvnItemchangedAnimlist) ON_BN_CLICKED(IDC_BTN_CHANGE_GROUP_NAME, &CArnView::OnBnClickedBtnChangeGroupName) ON_BN_CLICKED(IDC_BTN_SPLIT_ANIM, &CArnView::OnBnClickedBtnSplitAnim) ON_WM_HSCROLL() ON_BN_CLICKED(IDC_BUTTON1, &CArnView::OnBnClickedButton1) END_MESSAGE_MAP() // CArnView diagnostics #ifdef _DEBUG void CArnView::AssertValid() const { CFormView::AssertValid(); } #ifndef _WIN32_WCE void CArnView::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } #endif #endif //_DEBUG void CArnView::Render() { if (!m_bIsOpeningFile) { m_bIsNowRendering = TRUE; m_videoMan.DrawAtEditor(m_bReady, m_bRunningThread); m_bIsNowRendering = FALSE; } } void CArnView::OnInitialUpdate() { CFormView::OnInitialUpdate(); // TODO: Add your specialized code here and/or call the base class if (m_dxStatic.GetSafeHwnd() == NULL) { // Nodes list icon registration m_pSmallImage = new CImageList; m_pSmallImage->Create(16, 16, ILC_COLOR4, 3, 3); CBitmap cBitmap; cBitmap.LoadBitmap(IDB_REDCIRCLE); m_pSmallImage->Add(&cBitmap, RGB(255, 255, 255)); cBitmap.DeleteObject(); cBitmap.LoadBitmap(IDB_GREENCIRCLE); m_pSmallImage->Add(&cBitmap, RGB(255, 255, 255)); cBitmap.DeleteObject(); cBitmap.LoadBitmap(IDB_BLUECIRCLE); m_pSmallImage->Add(&cBitmap, RGB(255, 255, 255)); cBitmap.DeleteObject(); m_listNodes.SetImageList(m_pSmallImage, LVSIL_SMALL); // Direct3D area init RECT rect1 = { 500, 10, 500 + 400, 10 + 300 }; m_dxStatic.Create(_T("TestView"), SS_NOTIFY | SS_SUNKEN | WS_BORDER, rect1, this); m_dxStatic.ShowWindow(SW_SHOW); m_videoMan.SetHwnd(m_dxStatic.GetSafeHwnd()); m_videoMan.SetWindowSize(400, 300); m_videoMan.InitD3D(TRUE); m_videoMan.InitAnimationController(); m_videoMan.InitMainCamera(); m_videoMan.InitLight(); m_videoMan.InitShader(); m_videoMan.InitModelsAtEditor(); // all rendering devices and data are prepared! okay to run the thread m_bReady = TRUE; // run thread initially m_bRunningThread = TRUE; AfxBeginThread(RenderingThreadProc, (LPVOID)this); int i; LV_COLUMN lvColumn; // init node list columns TCHAR* columnName[4] = { _T("Type"), _T("Name"), _T("Chunk Offset"), _T("Chunk Size") }; int columnWidth[4] = { 130, 130, 80, 80 }; lvColumn.mask = LVCF_FMT | LVCF_SUBITEM | LVCF_TEXT | LVCF_WIDTH; lvColumn.fmt = LVCFMT_LEFT; for (i = 0; i < 4; i++) { lvColumn.pszText = columnName[i]; lvColumn.iSubItem = i; lvColumn.cx = columnWidth[i]; m_listNodes.InsertColumn(i, &lvColumn); } m_listNodes.SetExtendedStyle(LVS_EX_FULLROWSELECT); // init animation list columns TCHAR* columnName2[5] = { _T("Seq"), _T("Time"), _T("Rotation"), _T("Scale"), _T("Translation") }; int columnWidth2[5] = { 60, 80, 160, 140, 180 }; lvColumn.mask = LVCF_FMT | LVCF_SUBITEM | LVCF_TEXT | LVCF_WIDTH; lvColumn.fmt = LVCFMT_LEFT; for (i = 0; i < 5; i++) { lvColumn.pszText = columnName2[i]; lvColumn.iSubItem = i; lvColumn.cx = columnWidth2[i]; m_listAnim.InsertColumn(i, &lvColumn); } m_listAnim.SetExtendedStyle(LVS_EX_FULLROWSELECT); // init animation list groups m_listAnim.EnableGroupView(TRUE); LVGROUP grp; ZeroMemory(&grp, sizeof(grp)); grp.cbSize = sizeof(LVGROUP); grp.mask = LVGF_HEADER | LVGF_GROUPID | LVGF_ALIGN; grp.uAlign = LVGA_HEADER_LEFT; TCHAR label[128]; _tcscpy_s(label, 128, _T("Group 0")); grp.pszHeader = label; //_T("Group 0"); grp.cchHeader = 128; //_tcslen(grp.pszHeader); grp.iGroupId = 0; m_listAnim.InsertGroup(grp.iGroupId, &grp); m_editSelGroupName.EnableWindow(FALSE); m_btnChangeGroupName.EnableWindow(FALSE); } } void CArnView::OnDestroy() { CFormView::OnDestroy(); // TODO: Add your message handler code here m_bReady = FALSE; m_bRunningThread = FALSE; // should wait while D3D ends its rendering routine while (TRUE) { if (m_bIsNowRendering == FALSE) break; } } void CArnView::OnEnChangeEdit1() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CFormView::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here GetDocument()->SetModifiedFlag(TRUE); } void CArnView::OnLvnItemchangedNodelist(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); // TODO: Add your control notification handler code here NM_LISTVIEW* p = (NM_LISTVIEW*)pNMHDR; if (p->uOldState == 0) { int selected = p->iItem; CModelEditorDoc* pDoc = (CModelEditorDoc*)GetDocument(); ModelReader* pMR = pDoc->m_pMR; static wchar_t nodeName[128]; size_t length = pMR->GetArnNodeHeader(selected).uniqueName.length(); int j; for (j = 0; j < (int)length; j++) nodeName[j] = std::cin.widen(pMR->GetArnNodeHeader(selected).uniqueName.c_str()[j]); nodeName[length] = L'\0'; //AfxMessageBox(nodeName); RST_DATA* pRST = pMR->GetAnimQuat(selected); if (pRST == NULL) { m_listAnim.DeleteAllItems(); return; // does not have anim data } int rstSize = pMR->GetAnimQuatSize(selected); LV_ITEM lvItem; ZeroMemory(&lvItem, sizeof(lvItem)); int i; m_listAnim.SetRedraw(FALSE); m_listAnim.DeleteAllItems(); CString cstr; for (i = 0; i < rstSize; i++) { lvItem.iItem = i; // Sequence lvItem.mask = LVIF_TEXT | LVIF_GROUPID; lvItem.iGroupId = 0; lvItem.iSubItem = 0; cstr.Format(_T("%d"), i); lvItem.pszText = (LPWSTR)cstr.GetString(); m_listAnim.InsertItem(&lvItem); // Time lvItem.mask = LVIF_TEXT; lvItem.iSubItem = 1; cstr.Format(_T("%d"), i*4800); lvItem.pszText = (LPWSTR)cstr.GetString(); m_listAnim.SetItem(&lvItem); // Rotation lvItem.mask = LVIF_TEXT; lvItem.iSubItem = 2; cstr.Format(_T("(%.3f, %.3f, %.3f; %.3f)"), pRST->x, pRST->y, pRST->z, pRST->w); lvItem.pszText = (LPWSTR)cstr.GetString(); m_listAnim.SetItem(&lvItem); // Scale lvItem.mask = LVIF_TEXT; lvItem.iSubItem = 3; cstr.Format(_T("(%.3f, %.3f, %.3f)"), pRST->sx, pRST->sy, pRST->sz); lvItem.pszText = (LPWSTR)cstr.GetString(); m_listAnim.SetItem(&lvItem); // Translation lvItem.mask = LVIF_TEXT; lvItem.iSubItem = 4; cstr.Format(_T("(%.3f, %.3f, %.3f)"), pRST->tx, pRST->ty, pRST->tz); lvItem.pszText = (LPWSTR)cstr.GetString(); m_listAnim.SetItem(&lvItem); pRST++; } pRST = NULL; m_listAnim.SetRedraw(TRUE); m_listAnim.Invalidate(); m_animSliderTime.SetRange(0, rstSize-1, TRUE); } *pResult = 0; } void CArnView::OnLvnItemchangedAnimlist(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); // TODO: Add your control notification handler code here NM_LISTVIEW* p = (NM_LISTVIEW*)pNMHDR; if (p->uOldState == 0) { int selected = p->iItem; TCHAR szBuffer[1024]; DWORD cchBuf(1024); LV_ITEM item; ZeroMemory(&item, sizeof(item)); item.mask = LVIF_TEXT | LVIF_GROUPID; item.iItem = selected; item.iSubItem = 0; item.pszText = szBuffer; item.cchTextMax = cchBuf; m_listAnim.GetItem(&item); LVGROUP grp; ZeroMemory(&grp, sizeof(grp)); grp.cbSize = sizeof(grp); grp.mask = LVGF_HEADER | LVGF_GROUPID | LVGF_ALIGN; grp.pszHeader = szBuffer; grp.cchHeader = cchBuf; m_listAnim.GetGroupInfo(item.iGroupId, &grp); m_editSelGroupName.SetWindowText(grp.pszHeader); m_cstrTestField = _T("Group selected"); m_editSelGroupName.EnableWindow(TRUE); m_btnChangeGroupName.EnableWindow(TRUE); m_iSelAnimGroupID = item.iGroupId; m_iSelAnimItemIndex = selected; } else { m_editSelGroupName.EnableWindow(FALSE); m_btnChangeGroupName.EnableWindow(FALSE); m_iSelAnimGroupID = -1; } *pResult = 0; } void CArnView::OnBnClickedBtnChangeGroupName() { // TODO: Add your control notification handler code here LVGROUP grp; ZeroMemory(&grp, sizeof(grp)); grp.cbSize = sizeof(grp); grp.mask = LVGF_HEADER | LVGF_GROUPID | LVGF_ALIGN; grp.pszHeader = NULL; grp.cchHeader = 0; m_listAnim.GetGroupInfo(m_iSelAnimGroupID, &grp); CString cstr; m_editSelGroupName.GetWindowText(cstr); grp.pszHeader = (LPTSTR)cstr.GetString(); grp.cchHeader = (int)_tcslen(grp.pszHeader); m_listAnim.SetRedraw(FALSE); //m_listAnim.RemoveGroup(m_iSelAnimGroupID); //m_listAnim.InsertGroup(m_iSelAnimGroupID, &grp); m_listAnim.SetGroupInfo(m_iSelAnimGroupID, &grp); m_listAnim.SetRedraw(TRUE); } void CArnView::OnBnClickedBtnSplitAnim() { // TODO: Add your control notification handler code here LVGROUP grp; ZeroMemory(&grp, sizeof(grp)); grp.cbSize = sizeof(LVGROUP); grp.mask = LVGF_HEADER | LVGF_GROUPID | LVGF_ALIGN; grp.uAlign = LVGA_HEADER_LEFT; int i = 0; while (m_listAnim.HasGroup(i) == TRUE) { i++; } grp.iGroupId = i; CString cstr; cstr.Format(_T("Group %d"), grp.iGroupId); grp.pszHeader = (LPTSTR)cstr.GetString(); //_T("Group 0"); grp.cchHeader = (int)_tcslen(grp.pszHeader); m_listAnim.SetRedraw(FALSE); m_listAnim.InsertGroup(grp.iGroupId, &grp); TCHAR szBuffer[1024]; DWORD cchBuf(1024); LV_ITEM item; ZeroMemory(&item, sizeof(item)); item.mask = LVIF_TEXT | LVIF_GROUPID; item.iSubItem = 0; item.pszText = szBuffer; item.cchTextMax = cchBuf; for (i = m_iSelAnimItemIndex; i < m_listAnim.GetItemCount(); i++) { item.iItem = i; m_listAnim.GetItem(&item); item.iGroupId = grp.iGroupId; m_listAnim.SetItem(&item); } m_listAnim.SetRedraw(TRUE); m_listAnim.Invalidate(); } //void CArnView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) //{ // // TODO: Add your message handler code here and/or call default // // CFormView::OnVScroll(nSBCode, nPos, pScrollBar); //} void CArnView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { // TODO: Add your message handler code here and/or call default // Animation slider shoots WM_HSCROLL when set by TBS_BOTTOM or TBS_TOP m_videoMan.SetCurrentFrameIndex(m_animSliderTime.GetPos()); CFormView::OnHScroll(nSBCode, nPos, pScrollBar); } void CArnView::OnBnClickedButton1() { // TODO: Add your control notification handler code here }
[ [ [ 1, 477 ] ] ]
faed1983b4662d1f15f6e391628a7201605aa84e
0c62a303659646fa06db4d5d09c44ecb53ce619a
/Kickapoo/Mouse.h
ef48522619dfb7d02dee7d7c423ac005bb2bbffa
[]
no_license
gosuwachu/igk-game
60dcdd8cebf7a25faf60a5cc0f5acd6f698c1c25
faf2e6f3ec6cfe8ddc7cb1f3284f81753f9745f5
refs/heads/master
2020-05-17T21:51:18.433505
2010-04-12T12:42:01
2010-04-12T12:42:01
32,650,596
0
0
null
null
null
null
UTF-8
C++
false
false
385
h
#pragma once #include "Common.h" class Mouse : public Singleton<Mouse> { float x, y; float size; Texture cursor; public: Mouse(void); ~Mouse(void); void create(); void update(); void drawCursor(); void setPos(float x_, float y_) { x = x_; y = y_; } float getX() { return x; } float getY() { return y; } }; DefineAccessToSingleton(Mouse);
[ "[email protected]@d16c65a5-d515-2969-3ec5-0ec16041161d", "[email protected]@d16c65a5-d515-2969-3ec5-0ec16041161d" ]
[ [ [ 1, 17 ], [ 23, 27 ] ], [ [ 18, 22 ] ] ]
6252029d75a0386e1dc005b389ea25f504cad04f
1a61f65e8baa4936b00c992b01babef108393d2f
/BlobContour.h
2c36253f59002be9ea9597e1a1846d3c4fac599e
[]
no_license
aaronsung/cvBlobsLib-iOS
aaec16f6c82b1015a35c0b33a6ba5a266119d83a
6f9397bf62d5fe5423d8afe86ae9dc1223d3d976
refs/heads/master
2020-05-30T12:25:06.416030
2011-05-03T11:20:49
2011-05-03T11:20:49
1,695,787
1
0
null
null
null
null
UTF-8
C++
false
false
1,912
h
#ifndef BLOBCONTOUR_H_INCLUDED #define BLOBCONTOUR_H_INCLUDED #include "list" #include "opencv/cv.h" #include "cxtypes.h" //! Type of chain codes typedef unsigned char t_chainCode; //! Type of list of chain codes typedef CvSeq* t_chainCodeList; //! Type of list of points typedef CvSeq* t_PointList; //! Max order of calculated moments #define MAX_MOMENTS_ORDER 3 //! Blob contour class (in crack code) class CBlobContour { friend class CBlob; public: //! Constructors CBlobContour(); CBlobContour(CvPoint startPoint, CvMemStorage *storage ); //! Copy constructor CBlobContour( CBlobContour *source ); ~CBlobContour(); //! Assigment operator CBlobContour& operator=( const CBlobContour &source ); //! Add chain code to contour void AddChainCode(t_chainCode code); //! Return freeman chain coded contour t_chainCodeList GetChainCode() { return m_contour; } bool IsEmpty() { return m_contour == NULL || m_contour->total == 0; } //! Return all contour points t_chainCodeList GetContourPoints(); protected: CvPoint GetStartPoint() const { return m_startPoint; } //! Clears chain code contour void ResetChainCode(); //! Computes area from contour double GetArea(); //! Computes perimeter from contour double GetPerimeter(); //! Get contour moment (p,q up to MAX_CALCULATED_MOMENTS) double GetMoment(int p, int q); //! Crack code list t_chainCodeList m_contour; private: //! Starting point of the contour CvPoint m_startPoint; //! All points from the contour t_PointList m_contourPoints; //! Computed area from contour double m_area; //! Computed perimeter from contour double m_perimeter; //! Computed moments from contour CvMoments m_moments; //! Pointer to storage CvMemStorage *m_parentStorage; }; #endif //!BLOBCONTOUR_H_INCLUDED
[ [ [ 1, 97 ] ] ]
bb92da290e3fcc0b42ee4a29e81e987e9397abb5
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nanimation/src/animcomp/nccharacter_main.cc
e75738235f8b15bcb175631a905096290218da86
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,073
cc
#include "precompiled/pchnanimation.h" //------------------------------------------------------------------------------ // nccharacter_main.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "animcomp/ncharacterserver.h" #include "animcomp/nccharacter.h" #include "animcomp/nccharacterclass.h" #include "animcomp/ncskeletonclass.h" #include "animcomp/nchumragdoll.h" #include "ncragdoll/ncragdoll.h" #include "animcomp/ncfourleggedragdoll.h" #include "nragdollmanager/nragdollmanager.h" //------------------------------------------------------------------------------ #include "entity/nentityobjectserver.h" #include "entity/nentityclassserver.h" #include "nscene/ncscenelod.h" //------------------------------------------------------------------------------ #include "zombieentity/ncdictionary.h" #include "nspatial/ncspatial.h" #include "kernel/nlogclass.h" //------------------------------------------------------------------------------ int ncCharacter::nextKey = 0; //------------------------------------------------------------------------------ nNebulaComponentObject(ncCharacter,nComponentObject); //------------------------------------------------------------------------------ /** */ ncCharacter::ncCharacter() : character(0,2), lastUpdatedCharacter(0), lastUpdatedTime(0), key(nextKey++), activeStates(0,1), persistedStates(0,1), currentStates(0,1), previousStates(0,1), attachJointName(0,1), entityObjId(0,1), pause(false), dirtyMorphState(true), activeMorphState(-1), ragdollActive(false), dynamicAttachmentPool(0,0), fpersonAttachmentPool(0,0), firstpersonCharIdx(-1), fpersonCurrentStates(0,1), fpersonPreviousStates(0,1), fpersonActiveStates(0,1), fpersonPersistedStates(0,1), firstpersonActive(false), humanoidRagdoll(false), updateAttachments(true), jointLookAtIndex(-1) { //empty } //------------------------------------------------------------------------------ /** */ ncCharacter::~ncCharacter() { if (this->IsValid()) { this->Unload(); } } //------------------------------------------------------------------------------ /** */ void ncCharacter::InitInstance(nObject::InitInstanceMsg N_IFNDEF_NGAME(initType)) { #ifndef NGAME if (initType != nObject::ReloadedInstance) { // Register to EnterLimbo and ExitLimbo signals this->entityObject->BindSignal(NSIGNAL_OBJECT(nEntityObject, EnterLimbo), this, &ncCharacter::DoEnterLimbo, 0); this->entityObject->BindSignal(NSIGNAL_OBJECT(nEntityObject, ExitLimbo), this, &ncCharacter::DoExitLimbo, 0); } #endif } //------------------------------------------------------------------------------ /** */ bool ncCharacter::UpdateCharacter(int charIndex, nTime curTime) { NLOG(character, (NLOG1|1 , "---------------------------------------------------------------------------------")); NLOG(character, (NLOG1|1 , "UpdateCharacter entityobject: %s\t charIndex: %d curTime: %f", this->GetEntityClass()->GetName(), charIndex, (float) curTime)); if ( charIndex < 0 || charIndex >= this->character.Size() ) return false; if (!this->pause) { if (!this->GetRagdollActive()) { // animate character //n_assert(charIndex < this->character.Size()); // store last updated character (will be physics one or the good one) this->lastUpdatedCharacter = charIndex; this->lastUpdatedTime = curTime; n_assert(this->character[charIndex]); //REMOVEME ma.garcias- active states automatically updated at all SetActiveState*** methods //this->UpdateActiveStates(curTime); // evaluate the current state of the character skeleton nVariableContext *varContext = &this->GetComponent<ncDictionary>()->VarContext(); #if __NEBULA_STATS__ nCharacterServer::Instance()->profAnim.StartAccum(); #endif // choose which states must be used if (this->firstpersonCharIdx == charIndex) { this->character[charIndex]->EvaluateFullSkeleton((float) curTime, varContext, this->fpersonCurrentStates, this->fpersonPreviousStates); } else { this->UpdateActiveStatesLookAt(this->currentStates); this->character[charIndex]->EvaluateFullSkeleton((float) curTime, varContext, this->currentStates, this->previousStates); } #if __NEBULA_STATS__ nCharacterServer::Instance()->profAnim.StopAccum(); #endif } else { // animate ragdoll if (this->humanoidRagdoll) { this->refRagdoll->GetComponent<ncHumRagdoll>()->PhysicsAnimate(); } else { this->refRagdoll->GetComponent<ncFourLeggedRagdoll>()->PhysicsAnimate(); } } // update spatial box if necessary this->SetSpatialBBox(); } // update attached entities this->UpdateAttachments(); return true; } //------------------------------------------------------------------------------ /** first person together with third person data is only loaded when the entityclass is a necharacter. */ bool ncCharacter::Load() { //skeleton data ncCharacterClass *charClass = this->GetClassComponent<ncCharacterClass>(); //it is a necharacter if (charClass) { this->LoadCharacters(this->GetEntityClass()); } //it is a neskeleton else { this->LoadCharactersFromSkeletonClass(); } this->Register(); // create ragdoll instance this->LoadRagdoll(); //initialize StatesArrays this->LoadStatesArrays(); this->SetSpatialBBox(); this->LoadAttachedData(); /// return false it not all skeletons have the same animations /// @todo ma.garcias - display message for that and do not render anything (change level checkings) /// now -> changing to a non correct animation state will crash. return this->CorrectAnimations(); } //------------------------------------------------------------------------------ /** */ void ncCharacter::Unload() { this->UnRegister(); for (int i=0; i< this->character.Size(); i++) { n_delete(this->character[i]); } this->character.Clear(); this->activeStates.Clear(); this->currentStates.Clear(); this->previousStates.Clear(); this->fpersonActiveStates.Clear(); this->fpersonCurrentStates.Clear(); this->fpersonPreviousStates.Clear(); this->dynamicAttachmentPool.Clear(); this->fpersonAttachmentPool.Clear(); this->persistedStates.Clear(); this->fpersonPersistedStates.Clear(); this->attachJointName.Clear(); this->entityObjId.Clear(); if (this->refRagdoll.isvalid()) { nRagDollManager::Instance()->PushRagDoll( this->GetClassComponent<ncCharacterClass>()->GetRagDollManagerId(), this->refRagdoll->GetComponent<ncRagDoll>()); ncRagDoll *ragComp = this->refRagdoll->GetComponent<ncRagDoll>(); ragComp->GetEntityObject()->GetComponent<ncPhysicsObj>()->MoveToSpace(0); } } //------------------------------------------------------------------------------ /** */ bool ncCharacter::IsValid() { return (!this->character.Empty() && (this->character[0] != 0)); } //------------------------------------------------------------------------------ /** */ int ncCharacter::GetPhysicsSkelIndex() const { const ncCharacterClass* charClass = this->GetClassComponent<ncCharacterClass>(); // if comes from a necharacterclass if (charClass) { return charClass->GetPhysicsSkeletonIndex(); } //no fperson if (this->firstpersonCharIdx == -1) { return this->character.Size()-1; //the last one (minimum lod) } return this->character.Size()-2; //the minimum lod (ordered as lod0, lod1, lod2, fperson) } //------------------------------------------------------------------------------ /** */ bool ncCharacter::CorrectAnimations() { // if no lod if (this->character.Size() == 1) { return true; } // lod //get first skeleton ncCharacterClass *charClass = this->GetClassComponent<ncCharacterClass>(); if (charClass) { ncSkeletonClass *skelComp = charClass->GetSkeletonClassPointer(0); //for other skeletons int numThirdPersonSkeletons = charClass->GetNumberLevelSkeletons(); if (this->firstpersonCharIdx != -1) { numThirdPersonSkeletons--;//-1 coz 1person doesn't have to be tested } for (int skelIndex = 1; skelIndex < numThirdPersonSkeletons; skelIndex++) { ncSkeletonClass *nextSkelComp = charClass->GetSkeletonClassPointer(skelIndex); //check if same states number if (skelComp->GetNumStates() != nextSkelComp->GetNumStates()) { return false; } //for each animation for (int statesIndex = 0; statesIndex < skelComp->GetNumStates(); statesIndex++) { //check names if (0 != strcmp(skelComp->GetStateName(statesIndex),nextSkelComp->GetStateName(statesIndex))) { //different state names return false; } } } } return true; } //------------------------------------------------------------------------------ /** */ void ncCharacter::Register() { nCharacterServer::Instance()->Register(this->GetEntityObject()); } //------------------------------------------------------------------------------ /** */ void ncCharacter::UnRegister() { nCharacterServer::Instance()->Unregister(this->GetEntityObject()); } //------------------------------------------------------------------------------ /** */ void ncCharacter::DoEnterLimbo() { this->UnRegister(); //unregister local ragdoll entity object from spatial server this->GetComponentSafe<ncSpatial>()->RemoveFromSpaces(); } //------------------------------------------------------------------------------ /** */ void ncCharacter::DoExitLimbo() { this->Register(); //register local ragdoll entity object to spatial server } //------------------------------------------------------------------------------ /** */ void ncCharacter::LoadCharacters(nEntityClass* eClass, int firstCharacterPlace) { //skeleton data ncCharacterClass *charClass = eClass->GetComponent<ncCharacterClass>(); ncSkeletonClass *skelComp = 0; // load all characters for (int i=0; i< charClass->GetNumberLevelSkeletons(); i++) { skelComp = charClass->GetSkeletonClassPointer(i); n_assert(skelComp); this->SetCharacter(i+firstCharacterPlace, n_new(nCharacter2(skelComp->GetCharacter()))); n_assert(this->character[i]); //load animations //skelComp->LoadResources(); if( i != 0 && i != charClass->GetFirstPersonLevel()) { skelComp->LoadUpperLevelResources(); } // get attachemtns array nArray<nDynamicAttachment> attachments = skelComp->GetDynAttachments(); if (i== 0) { this->dynamicAttachmentPool = attachments; } else { if (i!= charClass->GetFirstPersonLevel()) { for (int attachIdx=0; attachIdx<attachments.Size(); attachIdx++) { this->dynamicAttachmentPool[attachIdx].SetJointIndex(i, attachments[attachIdx].GetJointIndex()); } } else { attachments = skelComp->GetDynAttachments(); this->fpersonAttachmentPool = attachments; } } } this->firstpersonCharIdx = charClass->GetFirstPersonLevel(); } //------------------------------------------------------------------------------ /** */ void ncCharacter::LoadCharactersFromSkeletonClass() { ncSkeletonClass *skelComp = 0; skelComp = this->GetClassComponent<ncSkeletonClass>(); n_assert(skelComp); this->SetCharacter(0, n_new(nCharacter2(skelComp->GetCharacter()))); n_assert(this->character[0]); //load animations skelComp->LoadResources(); // get attachemnts array nArray<nDynamicAttachment> attachments = skelComp->GetDynAttachments(); this->dynamicAttachmentPool = attachments; for (int i=1; i<3; i++) { nString lowLevelSklName = this->GetEntityClass()->GetName(); lowLevelSklName = lowLevelSklName.ExtractRange(0, lowLevelSklName.Length() - 1); lowLevelSklName += i; nEntityClass* entityClass = nEntityClassServer::Instance()->GetEntityClass(lowLevelSklName.Get()); if (entityClass) { skelComp = entityClass->GetComponent<ncSkeletonClass>(); n_assert(skelComp); this->SetCharacter(i, n_new(nCharacter2(skelComp->GetCharacter()))); n_assert(this->character[i]); skelComp->LoadResources(); skelComp->LoadUpperLevelResources(); attachments = skelComp->GetDynAttachments(); for (int attachIdx=0; attachIdx<attachments.Size(); attachIdx++) { this->dynamicAttachmentPool[attachIdx].SetJointIndex(i,attachments[attachIdx].GetJointIndex()); } } } } //------------------------------------------------------------------------------ /** */ void ncCharacter::SetFirstPersonActive(bool fpersonActive) { if (this->firstpersonCharIdx != -1) { this->firstpersonActive = fpersonActive; this->GetComponentSafe<ncSceneLod>()->SetLockedLevel(fpersonActive, this->firstpersonCharIdx); } } //------------------------------------------------------------------------------ /** */ bool ncCharacter::GetFirstPersonActive() const { return this->firstpersonActive; } //------------------------------------------------------------------------------ /** */ nCharacter2* ncCharacter::UpdateAndGetCharacter(int charIndex, nTime curTime) { // update skeleton only if not update yet (ie. if not updated when nanimationserver::trigger) if (nCharacterServer::Instance()->DoUpdate()) { if (this->GetLastUpdatedCharacterIndex() != charIndex || this->GetLastUpdatedTime() < curTime) { this->UpdateCharacter(charIndex, curTime); } } if (!this->GetRagdollActive()) { return this->GetCharacter(charIndex); } return this->GetRagdollCharacter(); } //------------------------------------------------------------------------------ /** */ int ncCharacter::GetFPersonSkelIndex() const { return this->firstpersonCharIdx; } //------------------------------------------------------------------------------ /** */ int ncCharacter::GetJointGroup(int stateIndex, bool fperson) const { int jointGroup = this->character[this->GetPhysicsSkelIndex()]->GetAnimStateArray()->GetStateAt(stateIndex).GetJointGroup(); if (fperson) { jointGroup = this->character[this->firstpersonCharIdx]->GetAnimStateArray()->GetStateAt(stateIndex).GetJointGroup(); } return jointGroup; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 536 ] ] ]
a2aaaf46306e5db474e5c1ddc42e5666322de9d9
2fb8c63d1ee7108c00bc9af656cd6ecf7174ae1b
/src/decomp/lzham_polar_codes.cpp
96c1e3f0b303fe22557e4ef7dcad7e5b7392b40a
[ "MIT" ]
permissive
raedwulf/liblzham
542aca151a21837c14666f1d16957e61ba9c095d
01ce0ec2d78f4fda767122baa02ba612ed966440
refs/heads/master
2021-01-10T19:58:22.981658
2011-08-24T11:55:26
2011-08-24T11:55:26
2,227,012
3
0
null
null
null
null
UTF-8
C++
false
false
13,228
cpp
// File: polar_codes.cpp // See Copyright Notice and license at the end of include/lzham.h // // Andrew Polar's prefix code algorithm: // http://ezcodesample.com/prefixer/prefixer_article.html // // Also implements Fyffe's approximate codelength generation method, which is // very similar but operates directly on codelengths vs. symbol frequencies: // Fyffe Codes for Fast Codelength Approximation, Graham Fyffe, 1999 // http://code.google.com/p/lzham/wiki/FyffeCodes #include "lzham_core.h" #include "lzham_polar_codes.h" #define LZHAM_USE_SHANNON_FANO_CODES 0 #define LZHAM_USE_FYFFE_CODES 0 namespace lzham { struct sym_freq { uint16 m_freq; uint16 m_sym; }; static inline sym_freq* radix_sort_syms(uint num_syms, sym_freq* syms0, sym_freq* syms1) { const uint cMaxPasses = 2; uint hist[256 * cMaxPasses]; memset(hist, 0, sizeof(hist[0]) * 256 * cMaxPasses); sym_freq* p = syms0; sym_freq* q = syms0 + (num_syms >> 1) * 2; for ( ; p != q; p += 2) { const uint freq0 = p[0].m_freq; const uint freq1 = p[1].m_freq; hist[ freq0 & 0xFF]++; hist[256 + ((freq0 >> 8) & 0xFF)]++; hist[ freq1 & 0xFF]++; hist[256 + ((freq1 >> 8) & 0xFF)]++; } if (num_syms & 1) { const uint freq = p->m_freq; hist[ freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } sym_freq* pCur_syms = syms0; sym_freq* pNew_syms = syms1; const uint total_passes = (hist[256] == num_syms) ? 1 : cMaxPasses; for (uint pass = 0; pass < total_passes; pass++) { const uint* pHist = &hist[pass << 8]; uint offsets[256]; uint cur_ofs = 0; for (uint i = 0; i < 256; i += 2) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; offsets[i+1] = cur_ofs; cur_ofs += pHist[i+1]; } const uint pass_shift = pass << 3; sym_freq* p = pCur_syms; sym_freq* q = pCur_syms + (num_syms >> 1) * 2; for ( ; p != q; p += 2) { uint c0 = p[0].m_freq; uint c1 = p[1].m_freq; if (pass) { c0 >>= 8; c1 >>= 8; } c0 &= 0xFF; c1 &= 0xFF; // Cut down on LHS's on console platforms by processing two at a time. if (c0 == c1) { uint dst_offset0 = offsets[c0]; offsets[c0] = dst_offset0 + 2; pNew_syms[dst_offset0] = p[0]; pNew_syms[dst_offset0 + 1] = p[1]; } else { uint dst_offset0 = offsets[c0]++; uint dst_offset1 = offsets[c1]++; pNew_syms[dst_offset0] = p[0]; pNew_syms[dst_offset1] = p[1]; } } if (num_syms & 1) { uint c = ((p->m_freq) >> pass_shift) & 0xFF; uint dst_offset = offsets[c]; offsets[c] = dst_offset + 1; pNew_syms[dst_offset] = *p; } sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } #if LZHAM_ASSERTS_ENABLED uint prev_freq = 0; for (uint i = 0; i < num_syms; i++) { LZHAM_ASSERT(!(pCur_syms[i].m_freq < prev_freq)); prev_freq = pCur_syms[i].m_freq; } #endif return pCur_syms; } struct polar_work_tables { sym_freq syms0[cPolarMaxSupportedSyms]; sym_freq syms1[cPolarMaxSupportedSyms]; }; uint get_generate_polar_codes_table_size() { return sizeof(polar_work_tables); } void generate_polar_codes(uint num_syms, sym_freq* pSF, uint8* pCodesizes, uint& max_code_size_ret) { int tmp_freq[cPolarMaxSupportedSyms]; uint orig_total_freq = 0; uint cur_total = 0; for (uint i = 0; i < num_syms; i++) { uint sym_freq = pSF[num_syms - 1 - i].m_freq; orig_total_freq += sym_freq; uint sym_len = math::total_bits(sym_freq); uint adjusted_sym_freq = 1 << (sym_len - 1); tmp_freq[i] = adjusted_sym_freq; cur_total += adjusted_sym_freq; } uint tree_total = 1 << (math::total_bits(orig_total_freq) - 1); if (tree_total < orig_total_freq) tree_total <<= 1; uint start_index = 0; while ((cur_total < tree_total) && (start_index < num_syms)) { for (uint i = start_index; i < num_syms; i++) { uint freq = tmp_freq[i]; if ((cur_total + freq) <= tree_total) { tmp_freq[i] += freq; if ((cur_total += freq) == tree_total) break; } else { start_index = i + 1; } } } LZHAM_ASSERT(cur_total == tree_total); uint max_code_size = 0; const uint tree_total_bits = math::total_bits(tree_total); for (uint i = 0; i < num_syms; i++) { uint codesize = (tree_total_bits - math::total_bits(tmp_freq[i])); max_code_size = LZHAM_MAX(codesize, max_code_size); pCodesizes[pSF[num_syms-1-i].m_sym] = static_cast<uint8>(codesize); } max_code_size_ret = max_code_size; } #if LZHAM_USE_FYFFE_CODES void generate_fyffe_codes(uint num_syms, sym_freq* pSF, uint8* pCodesizes, uint& max_code_size_ret) { int tmp_codesizes[cPolarMaxSupportedSyms]; uint cur_total = 0; uint orig_total = 0; for (uint i = 0; i < num_syms; i++) { uint sym_freq = pSF[i].m_freq; orig_total += sym_freq; // Compute the nearest power of 2 lower or equal to the symbol's frequency. // This is equivalent to codesize=ceil(-log2(sym_prob)). uint floor_sym_freq = sym_freq; if (!math::is_power_of_2(floor_sym_freq)) { uint sym_freq_bits = math::total_bits(sym_freq); floor_sym_freq = 1 << (sym_freq_bits - 1); } // Compute preliminary codesizes. tmp_freq's will always be <= the input frequencies. tmp_codesizes[i] = math::total_bits(floor_sym_freq); cur_total += floor_sym_freq; } // Desired_total is a power of 2, and will always be >= the adjusted frequency total. uint desired_total = cur_total; if (!math::is_power_of_2(desired_total)) desired_total = math::next_pow2(desired_total); LZHAM_ASSERT(cur_total <= desired_total); // Compute residual and initial symbol codesizes. uint desired_total_bits = math::total_bits(desired_total); int r = desired_total; for (uint i = 0; i < num_syms; i++) { uint codesize = desired_total_bits - tmp_codesizes[i]; tmp_codesizes[i] = static_cast<uint8>(codesize); r -= (desired_total >> codesize); } LZHAM_ASSERT(r >= 0); int sym_freq_scale = (desired_total << 7) / orig_total; // Promote codesizes from most probable to lowest, as needed. bool force_unhappiness = false; while (r > 0) { for (int i = num_syms - 1; i >= 0; i--) { uint codesize = tmp_codesizes[i]; if (codesize == 1) continue; int sym_freq = pSF[i].m_freq; int f = desired_total >> codesize; if (f > r) continue; // A code is "unhappy" when it is assigned more bits than -log2(sym_prob). // It's too expensive to compute -log2(sym_freq/total_freq), so instead this directly compares the symbol's original // frequency vs. the effective/adjusted frequency. sym_freq >= f is an approximation. //bool unhappy = force_unhappiness || (sym_freq >= f); // Compare the symbol's original probability vs. its effective probability at its current codelength. //bool unhappy = force_unhappiness || ((sym_freq * ((float)desired_total / orig_total)) > f); bool unhappy = force_unhappiness || ((sym_freq * sym_freq_scale) > (f << 7)); if (unhappy) { tmp_codesizes[i]--; r -= f; if (r <= 0) break; } } // Occasionally, a second pass is required to reduce the residual to 0. // Subsequent passes ignore unhappiness. This is not discussed in Fyffe's original article. force_unhappiness = true; } LZHAM_ASSERT(!r); uint max_code_size = 0; for (uint i = 0; i < num_syms; i++) { uint codesize = tmp_codesizes[i]; max_code_size = LZHAM_MAX(codesize, max_code_size); pCodesizes[pSF[i].m_sym] = static_cast<uint8>(codesize); } max_code_size_ret = max_code_size; } #endif //LZHAM_USE_FYFFE_CODES #if LZHAM_USE_SHANNON_FANO_CODES // Straightforward recursive Shannon-Fano implementation, for comparison purposes. static void generate_shannon_fano_codes_internal(uint num_syms, sym_freq* pSF, uint8* pCodesizes, int l, int h, uint total_freq) { LZHAM_ASSERT((h - l) >= 2); uint left_total = total_freq; uint right_total = 0; int best_diff = INT_MAX; int best_split_index = 0; for (int i = h - 1; i > l; i--) { uint freq = pSF[i].m_freq; uint next_left_total = left_total - freq; uint next_right_total = right_total + freq; LZHAM_ASSERT((next_left_total + next_right_total) == total_freq); int diff = labs(next_left_total - next_right_total); if (diff >= best_diff) break; left_total = next_left_total; right_total = next_right_total; best_split_index = i; best_diff = diff; if (!best_diff) break; } for (int i = l; i < h; i++) pCodesizes[i]++; if ((best_split_index - l) > 1) generate_shannon_fano_codes_internal(num_syms, pSF, pCodesizes, l, best_split_index, left_total); if ((h - best_split_index) > 1) generate_shannon_fano_codes_internal(num_syms, pSF, pCodesizes, best_split_index, h, right_total); } void generate_shannon_fano_codes(uint num_syms, sym_freq* pSF, uint total_freq, uint8* pCodesizes, uint& max_code_size_ret) { LZHAM_ASSERT(num_syms >= 2); uint8 tmp_codesizes[cPolarMaxSupportedSyms]; memset(tmp_codesizes, 0, num_syms); generate_shannon_fano_codes_internal(num_syms, pSF, tmp_codesizes, 0, num_syms, total_freq); uint max_code_size = 0; for (uint i = 0; i < num_syms; i++) { uint codesize = tmp_codesizes[i]; max_code_size = LZHAM_MAX(codesize, max_code_size); pCodesizes[pSF[i].m_sym] = static_cast<uint8>(codesize); } max_code_size_ret = max_code_size; } #endif // LZHAM_USE_SHANNON_FANO_CODES bool generate_polar_codes(void* pContext, uint num_syms, const uint16* pFreq, uint8* pCodesizes, uint& max_code_size, uint& total_freq_ret) { if ((!num_syms) || (num_syms > cPolarMaxSupportedSyms)) return false; polar_work_tables& state = *static_cast<polar_work_tables*>(pContext);; uint max_freq = 0; uint total_freq = 0; uint num_used_syms = 0; for (uint i = 0; i < num_syms; i++) { uint freq = pFreq[i]; if (!freq) pCodesizes[i] = 0; else { total_freq += freq; max_freq = math::maximum(max_freq, freq); sym_freq& sf = state.syms0[num_used_syms]; sf.m_sym = static_cast<uint16>(i); sf.m_freq = static_cast<uint16>(freq); num_used_syms++; } } total_freq_ret = total_freq; if (num_used_syms == 1) { pCodesizes[state.syms0[0].m_sym] = 1; } else { sym_freq* syms = radix_sort_syms(num_used_syms, state.syms0, state.syms1); #if LZHAM_USE_SHANNON_FANO_CODES generate_shannon_fano_codes(num_syms, syms, total_freq, pCodesizes, max_code_size); #elif LZHAM_USE_FYFFE_CODES generate_fyffe_codes(num_syms, syms, pCodesizes, max_code_size); #else generate_polar_codes(num_syms, syms, pCodesizes, max_code_size); #endif } return true; } } // namespace lzham
[ [ [ 1, 412 ] ] ]
16cc9913465362804d78d450583526f20e248b63
6027fd920827293ab00346989eef9a3d0e4690ad
/src/epsilon/wm/win32/internal.h
2700849337e908a9541fee264bc2e6a25c9a01c9
[]
no_license
andyfriesen/epsilon
6f67ec0ee5e832c19580da0376730a2022c9c237
073011e1c549ae3d1f591365abe2357612ce1f0b
refs/heads/master
2016-09-06T07:30:15.809710
2009-11-10T02:45:30
2009-11-10T02:45:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
782
h
/* * win32 specific wm things. * This must only ever be included from source files, not headers. */ #ifndef EPS_WM_WIN32_INTERNAL_H #define EPS_WM_WIN32_INTERNAL_H #if !defined(__cplusplus) || !defined(EPS_WIN32) # error "You shouldn't be here!" #endif #include "epsilon.h" #include "epsilon/event/event.h" #include <vector> // not do this? #define WIN32_LEAN_AND_MEAN #include <windows.h> struct _eps_Window { _eps_Window() : handle(0), mouseCaptureCount(0) { } /// Win32 window handle. HWND handle; /// State of the mouse pointer. struct _eps_MouseEvent mouseState; /// Number of mouse captures initiated. int mouseCaptureCount; std::vector<eps_Event> events; }; #endif
[ "andy@malaria.(none)" ]
[ [ [ 1, 41 ] ] ]
fce4ffab0085cf0f2ed2f6c3444ff1ff0cc8209e
554a3b859473dc4dfebc6a31b16dfd14c84ffd09
/ui/sxgo_label_window.cpp
21bb887139d51b661d1092aa40d8c88ec2c71e3b
[ "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
2,169
cpp
// 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) #include "sxgo_label_window.hpp" #include "sxgo_doc.hpp" #include "listing_parser.hpp" DEFINE_EVENT_TYPE( EVT_JUMPTO_LABEL_LINE) BEGIN_EVENT_TABLE(sxgo_label_window, wxTreeCtrl) EVT_TREE_ITEM_ACTIVATED( wxID_ANY, sxgo_label_window::LabelActivated) END_EVENT_TABLE() struct item_data : public wxTreeItemData { item_data( int line_) :line( line_) { } int get_line() const { return line; } private: int line; }; // // someone doubleclicked on a label in the // label window. // void sxgo_label_window::LabelActivated(wxTreeEvent& event) { wxTreeItemId itemId = event.GetItem(); item_data *item = (item_data *)GetItemData(itemId); wxCommandEvent new_event( EVT_JUMPTO_LABEL_LINE, GetId() ); new_event.SetEventObject( this ); new_event.SetInt( item->get_line()); GetEventHandler()->ProcessEvent( new_event); } void sxgo_label_window::Update( const sxgo_document *doc) { if ( doc != m_last_document || doc->GetId() != m_last_id) { DoUpdate(doc); m_last_document = doc; m_last_id = doc->GetId(); } } /// /// Completely recreate the label tree from a document /// void sxgo_label_window::DoUpdate( const sxgo_document *doc) { DeleteAllItems(); listing_info info = doc->GetListing(); wxTreeItemId root = AddRoot( wxString( "labels", wxConvUTF8)); for ( listing_info::jumplabel_container_type::const_iterator i = info.jump_labels.begin(); i != info.jump_labels.end(); ++i) { wxTreeItemId id = AppendItem( root, wxString( i->name.c_str(),wxConvUTF8), -1, -1, new item_data(i->line) ); for ( listing_info::rom_label_container_type::const_iterator j = i->minor_labels.begin(); j != i->minor_labels.end(); ++j) { AppendItem( id, wxString( j->first.c_str(), wxConvUTF8), -1, -1, new item_data( j->second)); } } }
[ "danny@3a7aa2ed-2c50-d14e-a1b9-f07bebb4988c" ]
[ [ [ 1, 85 ] ] ]
2eb9fdb139f918a6778b061481448c8bd4e8ed63
12ea67a9bd20cbeed3ed839e036187e3d5437504
/tpl/codemodel/src/CodeModel.h
ae23956e7a8331f7346d320d8edbee0ccf228c29
[]
no_license
cnsuhao/winxgui
e0025edec44b9c93e13a6c2884692da3773f9103
348bb48994f56bf55e96e040d561ec25642d0e46
refs/heads/master
2021-05-28T21:33:54.407837
2008-09-13T19:43:38
2008-09-13T19:43:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,378
h
// src\CodeModel.h : Declaration of the CCodeModel #ifndef __CODEMODEL_H_ #define __CODEMODEL_H_ #include "resource.h" // main symbols #include "codemodel_i.h" ///////////////////////////////////////////////////////////////////////////// // CCodeModel class ATL_NO_VTABLE CCodeModel : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CCodeModel, &CLSID_CCodeModel>, public IDispatchImpl<CodeModel, &IID_CodeModel, &LIBID_CODEMODELLib> { public: CCodeModel() { } DECLARE_REGISTRY_RESOURCEID(IDR_CODEMODEL) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CCodeModel) COM_INTERFACE_ENTRY(CodeModel) COM_INTERFACE_ENTRY(IDispatch) END_COM_MAP() // CodeModel public: STDMETHODIMP get_CodeElements( /* [retval][out] */ CodeElements __RPC_FAR *__RPC_FAR *ppCodeElements); STDMETHODIMP get_IsCaseSensitive( /* [retval][out] */ VARIANT_BOOL __RPC_FAR *pSensitive); STDMETHODIMP Remove( /* [in] */ VARIANT Element); STDMETHODIMP AddNamespace( /* [in] */ BSTR Name, /* [in] */ VARIANT Location, /* [in] */ VARIANT Position, /* [retval][out] */ CodeNamespace __RPC_FAR *__RPC_FAR *ppCodeNamespace); STDMETHODIMP AddClass( /* [in] */ BSTR Name, /* [in] */ VARIANT Location, /* [in] */ VARIANT Position, /* [in] */ VARIANT Bases, /* [in] */ VARIANT ImplementedInterfaces, /* [retval][out] */ CodeClass __RPC_FAR *__RPC_FAR *ppCodeClass); STDMETHODIMP AddFunction( /* [in] */ BSTR Name, /* [in] */ VARIANT Location, /* [in] */ enum vsCMFunction Kind, /* [in] */ VARIANT Type, /* [in] */ VARIANT Position, /* [in] */ enum vsCMAccess Access, /* [retval][out] */ CodeFunction __RPC_FAR *__RPC_FAR *ppCodeFunction); STDMETHODIMP AddVariable( /* [in] */ BSTR Name, /* [in] */ VARIANT Location, /* [in] */ VARIANT Type, /* [in] */ VARIANT Position, /* [in] */ enum vsCMAccess Access, /* [retval][out] */ CodeVariable __RPC_FAR *__RPC_FAR *ppCodeVariable); STDMETHODIMP IsValidID( /* [in] */ BSTR Name, /* [retval][out] */ VARIANT_BOOL __RPC_FAR *pValid); }; #endif //__CODEMODEL_H_
[ "xushiweizh@86f14454-5125-0410-a45d-e989635d7e98" ]
[ [ [ 1, 77 ] ] ]
a1537315c5a27d7d7d48415640188e18ed8f85ce
c8ab6c440f0e70e848c5f69ccbbfd9fe2913fbad
/bowling/include/cyclone/collide_coarse.h
7a7de3e429f600bf722914aed66176835b3e4ccb
[]
no_license
alyshamsy/power-bowling
2b6426cfd4feb355928de95f1840bd39eb88de0b
dd650b2a8e146f6cdf7b6ce703801b96360a90fe
refs/heads/master
2020-12-24T16:50:09.092801
2011-05-12T14:37:15
2011-05-12T14:37:15
32,115,585
0
0
null
null
null
null
UTF-8
C++
false
false
13,248
h
/* * Interface file for the coarse collision detection system. * * Part of the Cyclone physics system. * * Copyright (c) Icosagon 2003. All Rights Reserved. * * This software is distributed under licence. Use of this software * implies agreement with all terms and conditions of the accompanying * software licence. */ /** * @file * * This file contains the coarse collision detection system. It is * used to return pairs of objects that may be in contact, which can * then be tested using fined grained methods. */ #ifndef CYCLONE_COLLISION_COARSE_H #define CYCLONE_COLLISION_COARSE_H #include <vector> #include "contacts.h" namespace cyclone { ///>SphereBVHOverlap /** * Represents a bounding sphere that can be tested for overlap. */ struct BoundingSphere { Vector3 centre; real radius; public: /** * Creates a new bounding sphere at the given centre and radius. */ BoundingSphere(const Vector3 &centre, real radius); /** * Creates a bounding sphere to enclose the two given bounding * spheres. */ BoundingSphere(const BoundingSphere &one, const BoundingSphere &two); /** * Checks if the bounding sphere overlaps with the other given * bounding sphere. */ bool overlaps(const BoundingSphere *other) const; ///<SphereBVHOverlap /** * Reports how much this bounding sphere would have to grow * by to incorporate the given bounding sphere. Note that this * calculation returns a value not in any particular units (i.e. * its not a volume growth). In fact the best implementation * takes into account the growth in surface area (after the * Goldsmith-Salmon algorithm for tree construction). */ real getGrowth(const BoundingSphere &other) const; /** * Returns the volume of this bounding volume. This is used * to calculate how to recurse into the bounding volume tree. * For a bounding sphere it is a simple calculation. */ real getSize() const { return ((real)1.333333) * R_PI * radius * radius * radius; } ///>SphereBVHOverlap }; ///<SphereBVHOverlap ///>QueryBVH /** * Stores a potential contact to check later. */ struct PotentialContact { /** * Holds the bodies that might be in contact. */ RigidBody* body[2]; }; ///>BVH /** * A base class for nodes in a bounding volume hierarchy. * * This class uses a binary tree to store the bounding * volumes. */ template<class BoundingVolumeClass> class BVHNode { public: ///<BVH /** * Holds the child nodes of this node. */ BVHNode * children[2]; /** * Holds a single bounding volume encompassing all the * descendents of this node. */ BoundingVolumeClass volume; /** * Holds the rigid body at this node of the hierarchy. * Only leaf nodes can have a rigid body defined (see isLeaf). * Note that it is possible to rewrite the algorithms in this * class to handle objects at all levels of the hierarchy, * but the code provided ignores this vector unless firstChild * is NULL. */ RigidBody * body; ///<QueryBVH ///>BVH;Omit // ... other BVHNode code as before ... ///<BVH;Omit ///>BVHParent /** * Holds the node immediately above us in the tree. */ BVHNode * parent; ///>BVHParent /** * Creates a new node in the hierarchy with the given parameters. */ BVHNode(BVHNode *parent, const BoundingVolumeClass &volume, RigidBody* body=NULL) : parent(parent), volume(volume), body(body) { children[0] = children[1] = NULL; } ///>QueryBVH /** * Checks if this node is at the bottom of the hierarchy. */ bool isLeaf() const { return (body != NULL); } /** * Checks the potential contacts from this node downwards in * the hierarchy, writing them to the given array (up to the * given limit). Returns the number of potential contacts it * found. */ unsigned getPotentialContacts(PotentialContact* contacts, unsigned limit) const; ///<QueryBVH ///>BVHInsert /** * Inserts the given rigid body, with the given bounding volume, * into the hierarchy. This may involve the creation of * further bounding volume nodes. */ void insert(RigidBody* body, const BoundingVolumeClass &volume); ///<BVHInsert ///>BVHRemove /** * Deltes this node, removing it first from the hierarchy, along * with its associated * rigid body and child nodes. This method deletes the node * and all its children (but obviously not the rigid bodies). This * also has the effect of deleting the sibling of this node, and * changing the parent node so that it contains the data currently * in that sibling. Finally it forces the hierarchy above the * current node to reconsider its bounding volume. */ ~BVHNode(); ///<BVHRemove protected: /** * Checks for overlapping between nodes in the hierarchy. Note * that any bounding volume should have an overlaps method implemented * that checks for overlapping with another object of its own type. */ bool overlaps(const BVHNode<BoundingVolumeClass> *other) const; /** * Checks the potential contacts between this node and the given * other node, writing them to the given array (up to the * given limit). Returns the number of potential contacts it * found. */ unsigned getPotentialContactsWith( const BVHNode<BoundingVolumeClass> *other, PotentialContact* contacts, unsigned limit) const; /** * For non-leaf nodes, this method recalculates the bounding volume * based on the bounding volumes of its children. */ void recalculateBoundingVolume(bool recurse = true); ///>QueryBVH }; ///<QueryBVH // Note that, because we're dealing with a template here, we // need to have the implementations accessible to anything that // imports this header. ///>QueryBVH template<class BoundingVolumeClass> bool BVHNode<BoundingVolumeClass>::overlaps( const BVHNode<BoundingVolumeClass> * other ) const { return volume->overlaps(other->volume); } ///<QueryBVH ///>BVHInsert template<class BoundingVolumeClass> void BVHNode<BoundingVolumeClass>::insert( RigidBody* newBody, const BoundingVolumeClass &newVolume ) { // If we are a leaf, then the only option is to spawn two // new children and place the new body in one. if (isLeaf()) { // Child one is a copy of us. children[0] = new BVHNode<BoundingVolumeClass>( this, volume, body ); // Child two holds the new body children[1] = new BVHNode<BoundingVolumeClass>( this, newVolume, newBody ); // And we now loose the body (we're no longer a leaf) this->body = NULL; // We need to recalculate our bounding volume recalculateBoundingVolume(); } // Otherwise we need to work out which child gets to keep // the inserted body. We give it to whoever would grow the // least to incorporate it. else { if (children[0]->volume.getGrowth(newVolume) < children[1]->volume.getGrowth(newVolume)) { children[0]->insert(newBody, newVolume); } else { children[1]->insert(newBody, newVolume); } } } ///<BVHInsert ///>BVHRemove template<class BoundingVolumeClass> cyclone::BVHNode<BoundingVolumeClass>::~BVHNode() { // If we don't have a parent, then we ignore the sibling // processing if (parent) { // Find our sibling BVHNode<BoundingVolumeClass> *sibling; if (parent->children[0] == this) sibling = parent->children[1]; else sibling = parent->children[0]; // Write its data to our parent parent->volume = sibling->volume; parent->body = sibling->body; parent->children[0] = sibling->children[0]; parent->children[1] = sibling->children[1]; // Delete the sibling (we blank its parent and // children to avoid processing/deleting them) sibling->parent = NULL; sibling->body = NULL; sibling->children[0] = NULL; sibling->children[1] = NULL; delete sibling; // Recalculate the parent's bounding volume parent->recalculateBoundingVolume(); } // Delete our children (again we remove their // parent data so we don't try to process their siblings // as they are deleted). if (children[0]) { children[0]->parent = NULL; delete children[0]; } if (children[1]) { children[1]->parent = NULL; delete children[0]; } } ///<BVHRemove template<class BoundingVolumeClass> void BVHNode<BoundingVolumeClass>::recalculateBoundingVolume( bool recurse ) { if (isLeaf()) return; // Use the bounding volume combining constructor. volume = BoundingVolumeClass( children[0]->volume, children[1]->volume ); // Recurse up the tree if (parent) parent->recalculateBoundingVolume(true); } ///>QueryBVH template<class BoundingVolumeClass> unsigned BVHNode<BoundingVolumeClass>::getPotentialContacts( PotentialContact* contacts, unsigned limit ) const { // Early out if we don't have the room for contacts, or // if we're a leaf node. if (isLeaf() || limit == 0) return 0; // Get the potential contacts of one of our children with // the other return children[0]->getPotentialContactsWith( children[1], contacts, limit ); } template<class BoundingVolumeClass> unsigned BVHNode<BoundingVolumeClass>::getPotentialContactsWith( const BVHNode<BoundingVolumeClass> *other, PotentialContact* contacts, unsigned limit ) const { // Early out if we don't overlap or if we have no room // to report contacts if (!overlaps(other) || limit == 0) return 0; // If we're both at leaf nodes, then we have a potential contact if (isLeaf() && other->isLeaf()) { contacts->body[0] = body; contacts->body[1] = other->body; return 1; } // Determine which node to descend into. If either is // a leaf, then we descend the other. If both are branches, // then we use the one with the largest size. if (other->isLeaf() || (!isLeaf() && volume->getSize() >= other->volume->getSize())) { // Recurse into ourself unsigned count = children[0]->getPotentialContactsWith( other, contacts, limit ); // Check we have enough slots to do the other side too if (limit > count) { return count + children[1]->getPotentialContactsWith( other, contacts+count, limit-count ); } else { return count; } } else { // Recurse into the other node unsigned count = getPotentialContactsWith( other->children[0], contacts, limit ); // Check we have enough slots to do the other side too if (limit > count) { return count + getPotentialContactsWith( other->children[1], contacts+count, limit-count ); } else { return count; } } } ///<QueryBVH } // namespace cyclone #endif // CYCLONE_COLLISION_FINE_H
[ "aly.shamsy@71b57f4a-8c0b-a9ba-d1fe-6729e2c2215a" ]
[ [ [ 1, 415 ] ] ]
d9dc73a9ae0e3a6671ef93830f845313ac85d58b
dca366f7f7597c87e3b7936c5f4f8dbc612a7fec
/BotNet/client/CrazyUncleBurton/c/officers/RandomOfficer.cpp
6fa06fb56409da8a00b0683471daa173ac83972a
[]
no_license
mojomojomojo/MegaMinerAI
6e0183b45f20e57af90e31a412c303f9b3e508d7
4457c8255583c10da3ed683ec352f32e1b35295a
refs/heads/master
2020-05-18T10:44:16.037341
2011-12-12T17:13:46
2011-12-12T17:13:46
2,779,888
0
0
null
null
null
null
UTF-8
C++
false
false
2,895
cpp
#include "RandomOfficer.h" #include "Point.h" #include "strutil.h" #include "EnumsH.h" #include <stdlib.h> // rand() #include <time.h> #include <algorithm> using namespace std; // bool RandomOfficer::spawnMore() // { // NotifySuperiors("Preparing to deploy more troops."); // vector<int> randomOrder; // for (int i=0; i<_ai->bases.size(); i++) { // randomOrder.push_back(rand()%10000 * 100 + i); // } // sort(randomOrder.begin(),randomOrder.end()); // for(int i=0;i<_ai->bases.size();i++) // { // int b = randomOrder[i]%100; // // check if you own that base // if(_ai->bases[b].owner() == _ai->playerID()) // { // // check to see if you have enough cycles to spawn a level 0 virus // if(_ai->baseCost() <= _ai->players[_ai->playerID()].cycles()) // { // // spawn a level 0 virus at that base // _ai->bases[b].spawn(0); // CLEAR_DEBUG_STREAM; // _DS("Spawning level 0 virus from "); // _DS(Point(_ai->bases[b].x(),_ai->bases[b].y()));_DS(":");_DS(b); // NotifySuperiors(DEBUG_STRING); // } // } // } // Officer::spawnMore(); // } bool RandomOfficer::advance() { NotifySuperiors("Issuing orders for troops."); for (vector<int>::iterator u = _employedUnits.begin(); u != _employedUnits.end(); u++) { _TakeNotes("Determining orders for virus ID "<<(*u)); Virus *v = _ai->locateVirus(*u); if (!v) { NotifySuperiors(string("Bad employee id: ")+int_str(*u)); continue; } int x = v->x(); int y = v->y(); int dir = rand()%2; int dist = (rand()%3)-1; if (dir == 0) { x += dist; } else { y += dist; } // Keep choosing until you get one that's not off the map. // getTileAtLocation() doesn't do any bounds checking. // if the tile you want to move to is NOT a wall or a base. int rand_limit = 100; int tries = 0; while (!( (x >= 0 && x<_ai->width()) && (y >= 0 && y<_ai->height()) && (_ai->getTileAtLocation(x,y).owner() != 3) && (_ai->_map.at(x,y) != OPBASE) && (_ai->_map.at(x,y) != MYBASE) ) ) { if (tries++ > rand_limit) break; int dir = rand()%2; int dist = (rand()%3)-1; if (dir == 0) { x = v->x() + dist; } else { y = v->y() + dist; } } if (tries > rand_limit) continue; // Don't try anything if this happens. _NotifySuperiors("Sending virus to "<<Point(x,y)<<":"<<v); // Move the virus (if it's going somewhere--the game complains if you // attempt to move() it to the same location). if ( x != v->x() || y != v->y() ) v->move(x,y); } return Officer::advance(); }
[ [ [ 1, 108 ] ] ]
ccb34d2a54b439f287442c106d1bf4e8c2470369
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_media3/CodecConfig.h
c4467d49f53998a398897a6b2407288e769d191d
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
1,599
h
#ifndef CODEC_CONFIG_H #define CODEC_CONFIG_H #include "dscscript.h" #include <string> #include <deque> #define MEDIA_CONF_PANEL "profile_av_media_conf_panel" class _SEMAPHORE; class CodecConfig { private: static unsigned uInstances; static bool luaCfgInitialized; protected: CodecConfig(); virtual ~CodecConfig()= 0; unsigned GetTableParam(std::string _transmission, std::string _network, std::string _bitrate, std::string _type, std::string _codec, DsCScriptValue & _tableParam); unsigned GetTableParam(unsigned char _type, DsCScriptValue & _tableParam); unsigned GetTableParam(std::string _index, DsCScriptValue & _tableParam); bool luaCfgOk() {return luaCfgInitialized; } }; class MediaList { protected: unsigned char m_ListToken; MediaList() { m_ListToken = ' '; } }; class MediaCodecsList : MediaList, private CodecConfig { private: unsigned GetClientCodecs(DsCScriptValue & _tableParam); public: unsigned GetAudioCodecs(std::deque<std::string> & _audioCodecs); unsigned GetVideoCodecs(std::deque<std::string> & _videoCodecs, std::deque<std::string> & _bitrates); }; class MediaNetworkList : MediaList, private CodecConfig { private: unsigned GetClientNetwork(DsCScriptValue & _tableParam); public: unsigned GetAvailableNetworks(std::deque<std::string> & _networks); }; #endif
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 74 ] ] ]
6e85767d04486e9355ede5dd97072feb6521772d
49d4b13f55f09359560d0b9111455d08c6b43625
/stvs/trunk/inc/STA_Interact.hpp
9a078f620d95c60ea03ad66a8ed1f3ea43ac1cb2
[]
no_license
aniskhan25/stvs
6c53c27a6dbfa6b4105576ef9ecdae4b8a467a19
457fcf9393417d1a3b4aa963dc215a13d8f296a3
refs/heads/master
2016-09-11T06:37:25.202638
2011-09-22T06:28:14
2011-09-22T06:28:14
32,129,030
0
0
null
null
null
null
UTF-8
C++
false
false
1,123
hpp
#ifndef _INTERACT_H #define _INTERACT_H #include "../inc/struct.hpp" /// <summary> /// This namespace wraps the static pathway's functionality. /// </summary> namespace Static { /// <summary> /// A class with functions to compute the interactions among the feature maps. /// </summary> class Interact { private: /// <summary> /// Source image size. /// </summary> siz_t im_size_; /// <summary> /// No. of pixels in source image. /// </summary> unsigned int size_; void Init(); void Clean(); public: /// <summary> /// Default contructor for Interact class. /// </summary> inline Interact( siz_t const & im_size) { im_size_ = im_size; size_ = im_size.w*im_size.h; Init(); } /// <summary> /// Destructor for Interact class. /// </summary> inline ~Interact(){ Clean();} void Apply( float* out , complex_t* in , siz_t im_size ); }; __global__ void KernelInteractionShort( float* out , complex_t* in , siz_t im_size ); } // namespace Static #endif // _INTERACT_H
[ "[email protected]@9aaba9b0-769e-e9e7-77e3-716b6806c03d" ]
[ [ [ 1, 66 ] ] ]
bbfed33c8b42c22cdb140ebe0c2379d29d60f9a4
a04058c189ce651b85f363c51f6c718eeb254229
/Src/Forms/AmazonSearchForm.hpp
627eb68b28d9fd130fd1226e178ee76f6b34e921
[]
no_license
kjk/moriarty-palm
090f42f61497ecf9cc232491c7f5351412fba1f3
a83570063700f26c3553d5f331968af7dd8ff869
refs/heads/master
2016-09-05T19:04:53.233536
2006-04-04T06:51:31
2006-04-04T06:51:31
18,799
4
1
null
null
null
null
UTF-8
C++
false
false
1,038
hpp
#ifndef __AMAZON_SEARCH_FORM_HPP__ #define __AMAZON_SEARCH_FORM_HPP__ #include "MoriartyForm.hpp" #include <TextRenderer.hpp> #include <DynStr.hpp> class AmazonSearchForm: public MoriartyForm { TextRenderer textRenderer_; Field searchField_; Control okButton_; Control cancelButton_; FormObject graffitiState_; // holds a pointer to requestString given in constructor. Doesn't make a copy // so don't free it. We assume requestString will be valid through the form // lifetime const ArsLexis::char_t *request_; void handleControlSelect(const EventType& data); void afterFormOpen(); protected: void attachControls(); void resize(const ArsRectangle& screenBounds); bool handleEvent(EventType& event); bool handleOpen(); public: AmazonSearchForm(MoriartyApplication& app, const char_t* requestString, const char_t* displayText); ~AmazonSearchForm(); }; #endif
[ "andrzejc@a75a507b-23da-0310-9e0c-b29376b93a3c" ]
[ [ [ 1, 44 ] ] ]
01378b2447a728a12553dade3801f1894d18df64
0c62a303659646fa06db4d5d09c44ecb53ce619a
/Box2D/Testbed/Tests/TimeOfImpact.h
7b30807cbdc037702c3da36eaf0c548c6dcd5d95
[ "Zlib" ]
permissive
gosuwachu/igk-game
60dcdd8cebf7a25faf60a5cc0f5acd6f698c1c25
faf2e6f3ec6cfe8ddc7cb1f3284f81753f9745f5
refs/heads/master
2020-05-17T21:51:18.433505
2010-04-12T12:42:01
2010-04-12T12:42:01
32,650,596
0
0
null
null
null
null
UTF-8
C++
false
false
3,965
h
/* * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef TIME_OF_IMPACT_H #define TIME_OF_IMPACT_H class TimeOfImpact : public Test { public: TimeOfImpact() { { //m_shapeA.SetAsEdge(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); m_shapeA.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); } { m_shapeB.SetAsBox(2.0f, 0.1f); } } static Test* Create() { return new TimeOfImpact; } void Step(Settings* settings) { Test::Step(settings); b2Sweep sweepA; sweepA.c0.SetZero(); sweepA.a0 = 0.0f; sweepA.c = sweepA.c0; sweepA.a = sweepA.a0; sweepA.localCenter.SetZero(); b2Sweep sweepB; sweepB.c0.Set(-0.20382018f, 2.1368704f); sweepB.a0 = -3.1664171f; sweepB.c.Set(-0.26699525f, 2.3552670f); sweepB.a = -3.3926492f; sweepB.localCenter.SetZero(); b2TOIInput input; input.proxyA.Set(&m_shapeA); input.proxyB.Set(&m_shapeB); input.sweepA = sweepA; input.sweepB = sweepB; input.tMax = 1.0f; b2TOIOutput output; b2TimeOfImpact(&output, &input); m_debugDraw.DrawString(5, m_textLine, "toi = %g", output.t); m_textLine += 15; extern int32 b2_toiMaxIters, b2_toiMaxRootIters; m_debugDraw.DrawString(5, m_textLine, "max toi iters = %d, max root iters = %d", b2_toiMaxIters, b2_toiMaxRootIters); m_textLine += 15; b2Vec2 vertices[b2_maxPolygonVertices]; b2Transform transformA; sweepA.GetTransform(&transformA, 0.0f); for (int32 i = 0; i < m_shapeA.m_vertexCount; ++i) { vertices[i] = b2Mul(transformA, m_shapeA.m_vertices[i]); } m_debugDraw.DrawPolygon(vertices, m_shapeA.m_vertexCount, b2Color(0.9f, 0.9f, 0.9f)); b2Transform transformB; sweepB.GetTransform(&transformB, 0.0f); b2Vec2 localPoint(2.0f, -0.1f); b2Vec2 rB = b2Mul(transformB, localPoint) - sweepB.c0; float32 wB = sweepB.a - sweepB.a0; b2Vec2 vB = sweepB.c - sweepB.c0; b2Vec2 v = vB + b2Cross(wB, rB); for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) { vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); } m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.5f, 0.9f, 0.5f)); sweepB.GetTransform(&transformB, output.t); for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) { vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); } m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.5f, 0.7f, 0.9f)); sweepB.GetTransform(&transformB, 1.0f); for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) { vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); } m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.9f, 0.5f, 0.5f)); #if 0 for (float32 t = 0.0f; t < 1.0f; t += 0.1f) { sweepB.GetTransform(&transformB, t); for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) { vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); } m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.9f, 0.5f, 0.5f)); } #endif } b2PolygonShape m_shapeA; b2PolygonShape m_shapeB; }; #endif
[ "[email protected]@d16c65a5-d515-2969-3ec5-0ec16041161d" ]
[ [ [ 1, 134 ] ] ]
e0018d95240aa23c22e9bb1874d4fd4bbde2e7d0
b143d3766a4ff51320c211850bda2b290d0e6d32
/PolygonalMesh.cpp
e42033d357aa51ac78371874b247cd4333e2a0af
[]
no_license
jimbok8/MPUReconstruction
676274b046e7d10efc9af20c833a688aeca74462
8cd814a2eadb2a448dec428bc2ac76b5269daf6c
refs/heads/master
2021-05-26T23:03:23.479191
2010-03-17T14:03:53
2010-03-17T14:03:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,813
cpp
// PolygonalMesh.cpp: PolygonalMesh // ////////////////////////////////////////////////////////////////////// //#include "stdafx.h" #include "PolygonalMesh.h" #include <stdio.h> ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// PolygonalMesh::PolygonalMesh() { face_N = 0; vertex_N = 0; vertex = NULL; face = NULL; //vertex_link_v = NULL; //vertex_link_f = NULL; //degree_v = NULL; //degree_f = NULL; //isBound = NULL; normal_f = NULL; normal = NULL; center = NULL; value = NULL; } PolygonalMesh::~PolygonalMesh() { if(vertex != NULL) delete[] vertex; if(face != NULL){ for(int i=0; i<face_N; i++){ if(poly_N != 0) delete[] face[i]; } delete[] face; } delete[] poly_N; if(normal != NULL) delete[] normal; if(normal_f != NULL) delete[] normal_f; if(center != NULL) delete[] center; if(value != NULL) delete[] value; } void PolygonalMesh::setVertexCount(int vertex_N) { if(vertex != NULL) delete[] vertex; this->vertex_N = vertex_N; vertex = new float[vertex_N][3]; } void PolygonalMesh::setFaceCount(int face_N) { if(face != NULL){ delete[] face; delete[] poly_N; } this->face_N = face_N; face = new int*[face_N]; poly_N = new int[face_N]; } void PolygonalMesh::setPolygonCount(int index, int n) { poly_N[index] = n; face[index] = new int[n]; face[index][0] = -1; } void PolygonalMesh::computeFaceNormal() { if(normal_f == NULL) normal_f = new float[face_N][3]; for(int i=0; i<face_N; i++){ int n = poly_N[i]; int *f = face[i]; if(f[0] < 0) continue; double nor[3]; nor[0] = nor[1] = nor[2] = 0; for(int j=0; j<n; j++){ int i1 = f[j]; int i2 = f[(j+1)%n]; nor[0] += (vertex[i1][1] - vertex[i2][1])*(vertex[i1][2] + vertex[i2][2]); nor[1] += (vertex[i1][2] - vertex[i2][2])*(vertex[i1][0] + vertex[i2][0]); nor[2] += (vertex[i1][0] - vertex[i2][0])*(vertex[i1][1] + vertex[i2][1]); } double len = LENGTH(nor); if((float)len != 0){ normal_f[i][0] = (float)(nor[0]/len); normal_f[i][1] = (float)(nor[1]/len); normal_f[i][2] = (float)(nor[2]/len); } else{ normal_f[i][0] = normal_f[i][1] = normal_f[i][2] = 0; } } } void PolygonalMesh::computeNormal() { if(normal == NULL) normal = new float[vertex_N][3]; for(int i=0; i<vertex_N; i++) normal[i][0] = normal[i][1] = normal[i][2] = 0; for(int i=0; i<face_N; i++){ int n = poly_N[i]; int *f = face[i]; double nor[3]; nor[0] = nor[1] = nor[2] = 0; if(f[0] < 0) continue; for(int j=0; j<n; j++){ int i1 = f[j]; int i2 = f[(j+1)%n]; nor[0] += (vertex[i1][1] - vertex[i2][1])*(vertex[i1][2] + vertex[i2][2]); nor[1] += (vertex[i1][2] - vertex[i2][2])*(vertex[i1][0] + vertex[i2][0]); nor[2] += (vertex[i1][0] - vertex[i2][0])*(vertex[i1][1] + vertex[i2][1]); } for(int j=0; j<n; j++){ int v = face[i][j]; normal[v][0] += (float)nor[0]; normal[v][1] += (float)nor[1]; normal[v][2] += (float)nor[2]; } } for(int i=0; i<vertex_N; i++){ double len = LENGTH(normal[i]); if((float)len != 0){ normal[i][0] /= (float)len; normal[i][1] /= (float)len; normal[i][2] /= (float)len; } } } void PolygonalMesh::computeCenter() { if(center == NULL) center = new float[face_N][3]; for(int i=0; i<face_N; i++){ center[i][0] = center[i][1] = center[i][2] = 0; int m = poly_N[i]; for(int j=0; j<m; j++){ center[i][0] += vertex[face[i][j]][0]; center[i][1] += vertex[face[i][j]][1]; center[i][2] += vertex[face[i][j]][2]; } center[i][0] /= m; center[i][1] /= m; center[i][2] /= m; } }
[ [ [ 1, 172 ] ] ]
825a98aca9fb6482805a0e9b27ae2208d011907a
27b8c57bef3eb26b5e7b4b85803a8115e5453dcb
/trunk/lib/include/Control/InverseDynamics/RLControl.h
a57319356d5919efd65eebb127bfc53c08f57359
[]
no_license
BackupTheBerlios/walker-svn
2576609a17eab7a08bb2437119ef162487444f19
66ae38b2c1210ac2f036e43b5f0a96013a8e3383
refs/heads/master
2020-05-30T11:30:48.193275
2011-03-24T17:10:17
2011-03-24T17:10:17
40,819,670
0
0
null
null
null
null
UTF-8
C++
false
false
7,148
h
#ifndef __WALKER_YARD_CONTROL_INVERSE_DYNAMICS_RL_CONTROL_H__ #define __WALKER_YARD_CONTROL_INVERSE_DYNAMICS_RL_CONTROL_H__ #include "../../Learning/linear_function.hpp" #include "../../Learning/neural_network.hpp" #include "../../Learning/radial_basis_function.hpp" #include "../../Learning/reinforcement_learning_wrapper.hpp" #include "../../Learning/scalar_neural_network.hpp" #include "../../Learning/vector_function.hpp" #include "../../Plot/DrawLinePlot.h" #include "../../Statistics/NumActionsPlot.h" #include "../../Statistics/ValueFunctionPlot.h" #include "../Utility/DirectControl.h" #include "Control.h" namespace ctrl { namespace id { class RLControl : public Control { public: enum RL_FUNCTION_TYPE { FT_NEURAL_NETWORK, FT_RADIAL_BASIS, FT_LINEAR, FT_MIXED }; public: // reinforcement learning typedef environment_wrapper<environment_type> rl_environment_type; typedef learn::neural_network< float, learn::generic_function<float> > generic_neural_network_type; typedef learn::neural_network< float, learn::hyperbolic_tangent<float> > htangent_neural_network_type; typedef learn::scalar_neural_network<generic_neural_network_type> scalar_neural_network_type; typedef learn::linear_function< float, learn::generic_multi_function<float> > linear_radial_basis_function_type; typedef learn::vector_function< float, scalar_neural_network_type > vector_neural_network_function_type; typedef learn::vector_function< float, linear_radial_basis_function_type > vector_linear_radial_basis_function_type; typedef learn::radial_basis_function<float> radial_basis_function_type; typedef learn::vector_function< float, radial_basis_function_type > vector_radial_basis_function_type; //typedef radial_basis_function_type scalar_function_type; //typedef linear_radial_basis_function_type scalar_function_type; typedef scalar_neural_network_type scalar_function_type; //typedef vector_radial_basis_function_type vector_function_type; //typedef vector_linear_radial_basis_function_type vector_function_type; typedef htangent_neural_network_type vector_function_type; //typedef vector_neural_network_function_type vector_function_type; enum RL_TYPE { RL_TD_LAMBDA, RL_DIRECT }; typedef learn::abstract_reinforcement_learning<float> reinforcement_learning; typedef boost::shared_ptr<reinforcement_learning> reinforcement_learning_ptr; // statistics typedef stats::Statistics<reinforcement_learning> rl_statistics; typedef boost::intrusive_ptr<rl_statistics> rl_statistics_ptr; typedef std::vector<rl_statistics_ptr> rl_statistics_vector; /* typedef stats::ValueFunctionPlot<reinforcement_learning> value_function_plot; typedef stats::NumActionsPlot<reinforcement_learning> num_actions_plot; */ typedef DirectControl<environment_type, vector_function_type> direct_control_type; public: RLControl(const loose_timer_ptr& timer); ~RLControl(); /** Attach RL statistics to the control. */ void addRLStatistics(rl_statistics* statistics); /** Remove RL statistics from the control. */ bool removeRLStatistics(rl_statistics* statistics); // Override Control void loadConfig(const std::string& configFile); rl_environment_type getEnvironmentWrapper() const { return rl_environment_type(environment); } const vector_function_type& getActionFunction() const { return vectorFunction; } double getTimeInterval() const { return timeInterval; } private: // Override ChainControl void initialize(); // Override PhysicsControl void acquire_safe(); void unacquire_safe(); double pre_sync(); void run(); void dumpFunctions(); void loadFunctions(); void initFunctions(radial_basis_function_type& scalarFunction, htangent_neural_network_type& vectorFunction, size_t stateSize, size_t actionSize); void initFunctions(scalar_neural_network_type& scalarFunction, htangent_neural_network_type& vectorFunction, size_t stateSize, size_t actionSize); void initFunctions(radial_basis_function_type& scalarFunction, vector_radial_basis_function_type& vectorFunction, size_t stateSize, size_t actionSize); void initFunctions(linear_radial_basis_function_type& scalarFunction, vector_linear_radial_basis_function_type& vectorFunction, size_t stateSize, size_t actionSize); void initFunctions(scalar_neural_network_type& scalarFunction, vector_neural_network_function_type& vectorFunction, size_t stateSize, size_t actionSize); private: // settings RL_TYPE rlType; std::string rlConfig; bool dumpFuncsOnExit; bool loadFuncsOnStartup; std::string scalarFunctionDump; std::string vectorFunctionDump; bool autosave; double autosaveTime; bool episodic; double episodeLength; // flow bool needRestart; bool complete; double startTime; double lastAutosave; double lastUpdate; double timeInterval; // sync boost::mutex sceneReadyMutex; boost::condition_variable sceneReadyCondition; // control scalar_function_type scalarFunction; vector_function_type vectorFunction; reinforcement_learning_ptr chainLearner; // statistics rl_statistics_vector statistics; plot::draw_line_plot_2d_ptr valueFunctionPlotter; plot::draw_line_plot_2d_ptr numActionsPlotter; rl_statistics_ptr valueFunctionPlot; rl_statistics_ptr numActionsPlot; }; typedef boost::intrusive_ptr<RLControl> rl_control_ptr; typedef boost::intrusive_ptr<const RLControl> const_rl_control_ptr; } // nmaespace id } // namespace ctrl #endif // __WALKER_YARD_CONTROL_INVERSE_DYNAMICS_RL_CONTROL_H__
[ "dikobraz@9454499b-da03-4d27-8628-e94e5ff957f9" ]
[ [ [ 1, 181 ] ] ]
1ff19702cdf87dd91d13fa90cce47bbf4fefd792
8a223ca4416c60f4ad302bc045a182af8b07c2a5
/Orders-ListeningFakeProblem-Cpp/Orders-Untouchable-Cpp/include/ShippingOption.h
51df026ff8fda1d9513269715f17a6b6e65cc27e
[]
no_license
sinojelly/sinojelly
8a773afd0fcbae73b1552a217ed9cee68fc48624
ee40852647c6a474a7add8efb22eb763a3be12ff
refs/heads/master
2016-09-06T18:13:28.796998
2010-03-06T13:22:12
2010-03-06T13:22:12
33,052,404
0
0
null
null
null
null
UTF-8
C++
false
false
1,044
h
/// *************************************************************************** /// Copyright (c) 2009, Industrial Logic, Inc., All Rights Reserved. /// /// This code is the exclusive property of Industrial Logic, Inc. It may ONLY be /// used by students during Industrial Logic's workshops or by individuals /// who are being coached by Industrial Logic on a project. /// /// This code may NOT be copied or used for any other purpose without the prior /// written consent of Industrial Logic, Inc. /// **************************************************************************** #ifndef SHIPPING_OPTION_H_ #define SHIPPING_OPTION_H_ #include "Money.h" #include "Weight.h" #include "counted_ptr.h" class ShippingOption { public: static const ShippingOption AIR; static const ShippingOption GROUND; static const ShippingOption SUPER_SAVER; static const ShippingOption NEXT_DAY; Money rate(const Weight& weight) const; private: Money m_rate; ShippingOption(const Money& rate); }; #endif
[ "chenguodong@localhost" ]
[ [ [ 1, 35 ] ] ]
0046ffc51dcb1fc304110cd6a90955a9cf161204
6dac9369d44799e368d866638433fbd17873dcf7
/src/branches/26042005/include/graphics/Pixel.h
3235d19cce45396b70f1245d6bddef1bf2061b89
[]
no_license
christhomas/fusionengine
286b33f2c6a7df785398ffbe7eea1c367e512b8d
95422685027bb19986ba64c612049faa5899690e
refs/heads/master
2020-04-05T22:52:07.491706
2006-10-24T11:21:28
2006-10-24T11:21:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,776
h
// Pixel.h: interface for the Pixel class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PIXEL_H__8610A637_AFCF_4415_8BBC_3DEF80C54C83__INCLUDED_) #define AFX_PIXEL_H__8610A637_AFCF_4415_8BBC_3DEF80C54C83__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <cstdlib> #include <cmath> struct RGB{ unsigned char r, g, b, a; }; //===================== // Base Pixel Class //===================== class Pixel { protected: RGB *m_pixel_in; RGB m_pixel_out; unsigned char *buffer; public: Pixel(unsigned char *buf) { buffer = buf; m_pixel_in = NULL; }; virtual ~Pixel(){}; virtual RGB * ReadPixel (unsigned int offset) = 0; virtual void WritePixel (unsigned int offset) = 0; virtual RGB * GetOutput (void) = 0; virtual void SetInput (RGB *pixel_in) = 0; }; //===================== // 8-Bit derived class //===================== class Pixel8Bit: public Pixel { protected: unsigned char *palette; public: inline Pixel8Bit(unsigned char *buf, unsigned char *pal): Pixel(buf) { palette = pal; } inline virtual ~Pixel8Bit(){} inline virtual RGB * ReadPixel(unsigned int offset) { unsigned char *ptr = &palette[(buffer[offset] * 3)]; m_pixel_out.r = *ptr++; m_pixel_out.g = *ptr++; m_pixel_out.b = *ptr++; m_pixel_out.a = 0; return &m_pixel_out; } inline virtual void WritePixel(unsigned int offset){} // writing to 8bit surfaces is not allowed, use 32bit instead inline virtual RGB * GetOutput(void) { return &m_pixel_out; } inline virtual void SetInput(RGB *pixel_in){} // writing to 8bit surfaces is not allowed, use 32bit instead }; //====================== // 16-Bit derived class //====================== class Pixel16Bit: public Pixel { private: char m_NumBit_r, m_NumBit_g, m_NumBit_b; char shift_r, shift_g, shift_b; char pixel_mask_r,pixel_mask_g,pixel_mask_b; public: inline Pixel16Bit(unsigned char *buf, int num_r, int num_g, int num_b): Pixel(buf) { m_NumBit_r = num_r; m_NumBit_g = num_g; m_NumBit_b = num_b; shift_r = 16 - m_NumBit_r; shift_g = shift_r - m_NumBit_g; shift_b = shift_g - m_NumBit_b; pixel_mask_r = ((int)(pow(2,m_NumBit_r))-1) << shift_r; pixel_mask_g = ((int)(pow(2,m_NumBit_g))-1) << shift_g; pixel_mask_b = ((int)(pow(2,m_NumBit_b))-1) << shift_b; } inline virtual ~Pixel16Bit(){} inline virtual RGB * ReadPixel(unsigned int offset) { short pixelvalue = (unsigned short)buffer[offset*2]; m_pixel_out.r = (pixelvalue >> shift_r) & pixel_mask_r; m_pixel_out.g = (pixelvalue >> shift_g) & pixel_mask_g; m_pixel_out.b = (pixelvalue >> shift_b) & pixel_mask_b; m_pixel_out.a = 0; return &m_pixel_out; } inline virtual void WritePixel(unsigned int offset){} // writing to 16bit surfaces is not allowed, use 32bit instead inline virtual RGB * GetOutput(void){ return &m_pixel_out; } inline virtual void SetInput(RGB *pixel_in){} // writing to 16bit surfaces is not allowed, use 32bit instead }; //====================== // 24-Bit derived class //====================== class Pixel24Bit: public Pixel { public: Pixel24Bit(unsigned char *buf): Pixel(buf){} inline virtual ~Pixel24Bit(){} inline virtual RGB * ReadPixel(unsigned int offset) { unsigned char *ptr = &buffer[offset*3]; m_pixel_out.r = *ptr++; m_pixel_out.g = *ptr++; m_pixel_out.b = *ptr++; m_pixel_out.a = 0; return &m_pixel_out; } inline virtual void WritePixel(unsigned int offset) { unsigned char *ptr = &buffer[offset*3]; ptr[0] = m_pixel_in->r; ptr[1] = m_pixel_in->g; ptr[2] = m_pixel_in->b; } inline virtual RGB * GetOutput(void) { return &m_pixel_out; } inline virtual void SetInput(RGB *pixel_in) { m_pixel_in = pixel_in; } }; class Pixel32Bit: public Pixel { public: Pixel32Bit(unsigned char *buf): Pixel(buf){} inline virtual ~Pixel32Bit(){} inline virtual RGB * ReadPixel(unsigned int offset) { unsigned char *ptr = &buffer[offset*4]; m_pixel_out.r = *ptr++; m_pixel_out.g = *ptr++; m_pixel_out.b = *ptr++; m_pixel_out.a = *ptr++; return &m_pixel_out; } inline virtual void WritePixel(unsigned int offset) { unsigned char *ptr = &buffer[offset*4]; ptr[0] = m_pixel_in->r; ptr[1] = m_pixel_in->g; ptr[2] = m_pixel_in->b; ptr[3] = m_pixel_in->a; } inline virtual RGB * GetOutput(void) { return &m_pixel_out; } inline virtual void SetInput(RGB *pixel_in) { m_pixel_in = pixel_in; } }; #endif // !defined(AFX_PIXEL_H__8610A637_AFCF_4415_8BBC_3DEF80C54C83__INCLUDED_)
[ "chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7" ]
[ [ [ 1, 212 ] ] ]
e8a2fcca709f77156a5ee21b8bbba09c39ec95f2
00dc01cc668101fa47dccdd0c930e5a5ae1e62a3
/DirectX/DxDevice.h
7d48a30cb13a4239cf42258667bd1f0a8f5d8116
[ "MIT" ]
permissive
jtilander/unittestcg
3f18265a4bd6bf4b1d66623ad9b1b13e9fda9512
d56910eb75c6c3d4673a3bf465ab8e21169aaec5
refs/heads/master
2021-01-25T03:40:43.035650
2008-01-15T06:45:38
2008-01-15T06:45:38
32,777,280
0
0
null
null
null
null
UTF-8
C++
false
false
691
h
#ifndef aurora_directx_dxdevice_h #define aurora_directx_dxdevice_h #include "../UnitTestCgConfig.h" #ifdef UNITTESTCG_ENABLE_DIRECTX #include "../Device.h" namespace aurora { class DxDevice : public Device { public: DxDevice(); virtual ~DxDevice(); private: virtual bool initialize( int width, int height ); public: virtual Shader* createShader( const std::string& code, const std::string& name, const DefinesMap& defines, const IncludeSet& includes ); virtual Mesh* createSimpleMesh(); virtual void begin(); virtual void end(); virtual bool getLastRGBA( float (&rgba)[4] ) const; private: struct Pimpl; Pimpl& m; }; } #endif #endif
[ "jim.tilander@e486c63a-db1d-0410-a17c-a9b5b17689e2" ]
[ [ [ 1, 35 ] ] ]
929ff41ddd67f4459381b78f5c07aa188fd7ed34
cb9967f3c1349124878d5769d1ecd16500f60a08
/TaskbarNativeCode/PipeCommunicationStructures.h
13ad2823b83303dbcbbdb4bc69a549f123d40f30
[]
no_license
josiahdecker/TaskbarExtender
b71ab2439e6844060e6b41763b23ace6c00ccad2
3977192ba85d48bd8caf543bfc3a0f6d0df9efc9
refs/heads/master
2020-05-30T17:11:14.543553
2011-03-20T14:08:46
2011-03-20T14:08:46
1,503,110
0
0
null
null
null
null
UTF-8
C++
false
false
1,025
h
#include "Windows.h" #pragma once #define TASKBAR_MESSAGE_WINDOW_MOVED 1 #define TASKBAR_MESSAGE_WINDOW_OPENED 2 #define TASKBAR_MESSAGE_WINDOW_CLOSED 3 namespace TaskbarExtender { namespace NativeMethods { //from SocketDll.h public enum class TaskbarMessage : int { MSG_WINDOW_MOVED = 1, MSG_WINDOW_OPENED = 2, MSG_WINDOW_CLOSED = 3, MSG_SIZEMOVE_EXIT = 4, MSG_SIZEMOVE_ENTER = 5, MSG_SIZE_MAXIMIZED = 6, MSG_SIZE_MINIMIZED = 7, MSG_SIZE_RESTORED = 8, MSG_WINDOW_ACTIVATED = 9, MSG_WINDOW_DEACTIVATED = 10, MSG_WINDOW_DESTROYED = 11 }; //from SocketDll.h class WindowMessage { public: DWORD64 handle; int message_type; int x; int y; }; public ref class ClrWindowMessage{ public: ClrWindowMessage(const WindowMessage& msg) : hwnd(msg.handle), message_type((TaskbarMessage)msg.message_type), x(msg.x), y(msg.y) {} System::UInt64 hwnd; TaskbarMessage message_type; int x; int y; }; } }
[ [ [ 1, 49 ] ] ]
0915aea8029fd93b021db1a365c88525c28f2d61
ed9ecdcba4932c1adacac9218c83e19f71695658
/CJEngine/trunk/CJEngine/main.cpp
1c456cd131f9c79a6082b0a43c96ea610f0ac35a
[]
no_license
karansapra/futurattack
59cc71d2cc6564a066a8e2f18e2edfc140f7c4ab
81e46a33ec58b258161f0dd71757a499263aaa62
refs/heads/master
2021-01-10T08:47:01.902600
2010-09-20T20:25:04
2010-09-20T20:25:04
45,804,375
0
0
null
null
null
null
UTF-8
C++
false
false
459
cpp
/* * main.cpp * * Created on: 27 oct. 2009 * Author: Clement */ #include <stdio.h> #include <windows.h> #include "Engine.h" #include "GameLogic.h" using namespace CJEngine; int main(int argc, char ** argv) { Engine * engine = Engine::GetInstance(); engine->Init(640,480,"CJ Engine Demo",false); engine->ExitOnEscape(false); GameLogic logic; engine->SetCurrentGameLogic(logic); engine->Run(); return 0; }
[ "clems71@52ecbd26-af3e-11de-a2ab-0da4ed5138bb" ]
[ [ [ 1, 29 ] ] ]
8225994830b824c36ad54b29fc2a3854b76b8877
01fa6f43ad536f4c9656be0f2c7da69c6fc9dc1c
/stringex.h
8616ff93c858ab5ba9844747792a72db6fdeda49
[]
no_license
akavel/wed-editor
76a22b7ff1bb4b109cfe5f3cc630e18ebb91cd51
6a10c167e46bfcb65adb514a1278634dfcb384c1
refs/heads/master
2021-01-19T19:33:18.124144
2010-04-16T20:32:17
2010-04-16T20:32:17
10,511,499
1
0
null
null
null
null
UTF-8
C++
false
false
2,101
h
////////////////////////////////////////////////////////////////////// // StringEx.h // #ifndef __STRINGEX_H_ #define __STRINGEX_H_ class CStringEx : public CString { public: CStringEx() : CString( ){}; CStringEx( const CString& stringSrc) : CString( stringSrc ){}; CStringEx( const CStringEx& stringSrc) : CString( stringSrc ){}; CStringEx( TCHAR ch, int nRepeat = 1 ) : CString( ch, nRepeat ){}; CStringEx( LPCTSTR lpch, int nLength ) : CString( lpch, nLength ){}; CStringEx( const unsigned char* psz ) : CString( psz ){}; CStringEx( LPCWSTR lpsz ) : CString( lpsz ){}; CStringEx( LPCSTR lpsz ) : CString( lpsz ){}; CStringEx& Insert(int pos, LPCTSTR s); CStringEx& Insert(int pos, TCHAR c); CStringEx& Delete(int pos, int len); CStringEx& Replace(int pos, int len, LPCTSTR s); int Find( TCHAR ch, int startpos = 0 ) const; int Find( LPCTSTR lpszSub, int startpos = 0 ) const; int FindNoCase( TCHAR ch, int startpos = 0 ) const; int FindNoCase( LPCTSTR lpszSub, int startpos = 0 ) const; int FindReplace( LPCTSTR lpszSub, LPCTSTR lpszReplaceWith, BOOL bGlobal = TRUE ); int FindReplaceNoCase( LPCTSTR lpszSub, LPCTSTR lpszReplaceWith, BOOL bGlobal = TRUE ); int ReverseFind( TCHAR ch ) const{ return CString::ReverseFind(ch);}; int ReverseFind( LPCTSTR lpszSub, int startpos = -1 ) const; int ReverseFindNoCase( TCHAR ch, int startpos = -1 ) const; int ReverseFindNoCase( LPCTSTR lpszSub, int startpos = -1 ) const; CStringEx GetField( LPCTSTR delim, int fieldnum); CStringEx GetField( TCHAR delim, int fieldnum); int GetFieldCount( LPCTSTR delim ); int GetFieldCount( TCHAR delim ); CStringEx GetDelimitedField( LPCTSTR delimStart, LPCTSTR delimEnd, int fieldnum = 0); }; #endif /////////////////////////////////////////////////////////////////////
[ "none@none" ]
[ [ [ 1, 54 ] ] ]
102fa3256a7efb0364a262f3c7dac96c2b97da8c
7f4230cae41e0712d5942960674bfafe4cccd1f1
/code/ColladaExporter.cpp
f7dc569dd40d8784d0a87aeac5c5d26caf130c1a
[ "BSD-3-Clause" ]
permissive
tonttu/assimp
c6941538b3b3c3d66652423415dea098be21f37a
320a7a7a7e0422e4d8d9c2a22b74cb48f74b14ce
refs/heads/master
2021-01-16T19:56:09.309754
2011-06-07T20:00:41
2011-06-07T20:00:41
1,295,427
1
0
null
null
null
null
UTF-8
C++
false
false
13,257
cpp
/* Open Asset Import Library (ASSIMP) ---------------------------------------------------------------------- Copyright (c) 2006-2010, ASSIMP Development Team All rights reserved. Redistribution and use of this software 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 ASSIMP team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the ASSIMP Development Team. 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 "AssimpPCH.h" #ifndef ASSIMP_BUILD_NO_EXPORT #include "ColladaExporter.h" using namespace Assimp; namespace Assimp { // ------------------------------------------------------------------------------------------------ // Worker function for exporting a scene to Collada. Prototyped and registered in Exporter.cpp void ExportSceneCollada(const char* pFile,IOSystem* pIOSystem, const aiScene* pScene) { // invoke the exporter ColladaExporter iDoTheExportThing( pScene); // we're still here - export successfully completed. Write result to the given IOSYstem boost::scoped_ptr<IOStream> outfile (pIOSystem->Open(pFile,"wt")); // XXX maybe use a small wrapper around IOStream that behaves like std::stringstream in order to avoid the extra copy. outfile->Write( iDoTheExportThing.mOutput.str().c_str(), iDoTheExportThing.mOutput.tellp(),1); } } // end of namespace Assimp // ------------------------------------------------------------------------------------------------ // Constructor for a specific scene to export ColladaExporter::ColladaExporter( const aiScene* pScene) { mScene = pScene; // set up strings endstr = "\n"; // std::endl is too complicated for me to insert here. // start writing WriteFile(); } // ------------------------------------------------------------------------------------------------ // Starts writing the contents void ColladaExporter::WriteFile() { // write the DTD mOutput << "<?xml version=\"1.0\"?>" << endstr; // COLLADA element start mOutput << "<COLLADA xmlns=\"http://www.collada.org/2005/11/COLLADASchema\" version=\"1.4.1\">" << endstr; PushTag(); WriteHeader(); WriteGeometryLibrary(); WriteSceneLibrary(); // useless Collada bullshit at the end, just in case we haven't had enough indirections, yet. mOutput << startstr << "<scene>" << endstr; PushTag(); mOutput << startstr << "<instance_visual_scene url=\"#myScene\" />" << endstr; PopTag(); mOutput << startstr << "</scene>" << endstr; PopTag(); mOutput << "</COLLADA>" << endstr; } // ------------------------------------------------------------------------------------------------ // Writes the asset header void ColladaExporter::WriteHeader() { // Dummy stuff. Nobody actually cares for it anyways mOutput << startstr << "<asset>" << endstr; PushTag(); mOutput << startstr << "<contributor>" << endstr; PushTag(); mOutput << startstr << "<author>Someone</author>" << endstr; mOutput << startstr << "<authoring_tool>Assimp Collada Exporter</authoring_tool>" << endstr; PopTag(); mOutput << startstr << "</contributor>" << endstr; mOutput << startstr << "<unit meter=\"1.0\" name=\"meter\" />" << endstr; mOutput << startstr << "<up_axis>Y_UP</up_axis>" << endstr; PopTag(); mOutput << startstr << "</asset>" << endstr; } // ------------------------------------------------------------------------------------------------ // Writes the geometry library void ColladaExporter::WriteGeometryLibrary() { mOutput << startstr << "<library_geometries>" << endstr; PushTag(); for( size_t a = 0; a < mScene->mNumMeshes; ++a) WriteGeometry( a); PopTag(); mOutput << startstr << "</library_geometries>" << endstr; } // ------------------------------------------------------------------------------------------------ // Writes the given mesh void ColladaExporter::WriteGeometry( size_t pIndex) { const aiMesh* mesh = mScene->mMeshes[pIndex]; std::string idstr = GetMeshId( pIndex); // opening tag mOutput << startstr << "<geometry id=\"" << idstr << "\" name=\"" << idstr << "_name\" >" << endstr; PushTag(); mOutput << startstr << "<mesh>" << endstr; PushTag(); // Positions WriteFloatArray( idstr + "-positions", FloatType_Vector, (float*) mesh->mVertices, mesh->mNumVertices); // Normals, if any if( mesh->HasNormals() ) WriteFloatArray( idstr + "-normals", FloatType_Vector, (float*) mesh->mNormals, mesh->mNumVertices); // texture coords for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) { if( mesh->HasTextureCoords( a) ) { WriteFloatArray( idstr + "-tex" + boost::lexical_cast<std::string> (a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2, (float*) mesh->mTextureCoords[a], mesh->mNumVertices); } } // vertex colors for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) { if( mesh->HasVertexColors( a) ) WriteFloatArray( idstr + "-color" + boost::lexical_cast<std::string> (a), FloatType_Color, (float*) mesh->mColors[a], mesh->mNumVertices); } // assemble vertex structure mOutput << startstr << "<vertices id=\"" << idstr << "-vertices" << "\">" << endstr; PushTag(); mOutput << startstr << "<input semantic=\"POSITION\" source=\"#" << idstr << "-positions\" />" << endstr; if( mesh->HasNormals() ) mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << idstr << "-normals\" />" << endstr; for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a ) { if( mesh->HasTextureCoords( a) ) mOutput << startstr << "<input semantic=\"TEXCOORD\" source=\"#" << idstr << "-tex" << a << "\" set=\"" << a << "\" />" << endstr; } for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a ) { if( mesh->HasVertexColors( a) ) mOutput << startstr << "<input semantic=\"COLOR\" source=\"#" << idstr << "-color" << a << "\" set=\"" << a << "\" />" << endstr; } PopTag(); mOutput << startstr << "</vertices>" << endstr; // write face setup mOutput << startstr << "<polylist count=\"" << mesh->mNumFaces << "\" material=\"tellme\">" << endstr; PushTag(); mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstr << "-vertices\" />" << endstr; mOutput << startstr << "<vcount>"; for( size_t a = 0; a < mesh->mNumFaces; ++a ) mOutput << mesh->mFaces[a].mNumIndices << " "; mOutput << "</vcount>" << endstr; mOutput << startstr << "<p>"; for( size_t a = 0; a < mesh->mNumFaces; ++a ) { const aiFace& face = mesh->mFaces[a]; for( size_t b = 0; b < face.mNumIndices; ++b ) mOutput << face.mIndices[b] << " "; } mOutput << "</p>" << endstr; PopTag(); mOutput << startstr << "</polylist>" << endstr; // closing tags PopTag(); mOutput << startstr << "</mesh>" << endstr; PopTag(); mOutput << startstr << "</geometry>" << endstr; } // ------------------------------------------------------------------------------------------------ // Writes a float array of the given type void ColladaExporter::WriteFloatArray( const std::string& pIdString, FloatDataType pType, const float* pData, size_t pElementCount) { size_t floatsPerElement = 0; switch( pType ) { case FloatType_Vector: floatsPerElement = 3; break; case FloatType_TexCoord2: floatsPerElement = 2; break; case FloatType_TexCoord3: floatsPerElement = 3; break; case FloatType_Color: floatsPerElement = 3; break; default: return; } std::string arrayId = pIdString + "-array"; mOutput << startstr << "<source id=\"" << pIdString << "\" name=\"" << pIdString << "\">" << endstr; PushTag(); // source array mOutput << startstr << "<float_array id=\"" << arrayId << "\" count=\"" << pElementCount * floatsPerElement << "\"> "; PushTag(); if( pType == FloatType_TexCoord2 ) { for( size_t a = 0; a < pElementCount; ++a ) { mOutput << pData[a*3+0] << " "; mOutput << pData[a*3+1] << " "; } } else if( pType == FloatType_Color ) { for( size_t a = 0; a < pElementCount; ++a ) { mOutput << pData[a*4+0] << " "; mOutput << pData[a*4+1] << " "; mOutput << pData[a*4+2] << " "; } } else { for( size_t a = 0; a < pElementCount * floatsPerElement; ++a ) mOutput << pData[a] << " "; } mOutput << "</float_array>" << endstr; PopTag(); // the usual Collada bullshit. Let's bloat it even more! mOutput << startstr << "<technique_common>" << endstr; PushTag(); mOutput << startstr << "<accessor count=\"" << pElementCount << "\" offset=\"0\" source=\"#" << arrayId << "\" stride=\"" << floatsPerElement << "\">" << endstr; PushTag(); switch( pType ) { case FloatType_Vector: mOutput << startstr << "<param name=\"X\" type=\"float\" />" << endstr; mOutput << startstr << "<param name=\"Y\" type=\"float\" />" << endstr; mOutput << startstr << "<param name=\"Z\" type=\"float\" />" << endstr; break; case FloatType_TexCoord2: mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr; mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr; break; case FloatType_TexCoord3: mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr; mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr; mOutput << startstr << "<param name=\"P\" type=\"float\" />" << endstr; break; case FloatType_Color: mOutput << startstr << "<param name=\"R\" type=\"float\" />" << endstr; mOutput << startstr << "<param name=\"G\" type=\"float\" />" << endstr; mOutput << startstr << "<param name=\"B\" type=\"float\" />" << endstr; break; } PopTag(); mOutput << startstr << "</accessor>" << endstr; PopTag(); mOutput << startstr << "</technique_common>" << endstr; PopTag(); mOutput << startstr << "</source>" << endstr; } // ------------------------------------------------------------------------------------------------ // Writes the scene library void ColladaExporter::WriteSceneLibrary() { mOutput << startstr << "<library_visual_scenes>" << endstr; PushTag(); mOutput << startstr << "<visual_scene id=\"myScene\" name=\"myScene\">" << endstr; PushTag(); // start recursive write at the root node WriteNode( mScene->mRootNode); PopTag(); mOutput << startstr << "</visual_scene>" << endstr; PopTag(); mOutput << startstr << "</library_visual_scenes>" << endstr; } // ------------------------------------------------------------------------------------------------ // Recursively writes the given node void ColladaExporter::WriteNode( const aiNode* pNode) { mOutput << startstr << "<node id=\"" << pNode->mName.data << "\" name=\"" << pNode->mName.data << "\">" << endstr; PushTag(); // write transformation - we can directly put the matrix there // TODO: (thom) decompose into scale - rot - quad to allow adressing it by animations afterwards const aiMatrix4x4& mat = pNode->mTransformation; mOutput << startstr << "<matrix>"; mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " "; mOutput << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << " "; mOutput << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << " "; mOutput << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4; mOutput << "</matrix>" << endstr; // instance every geometry for( size_t a = 0; a < pNode->mNumMeshes; ++a ) { // const aiMesh* mesh = mScene->mMeshes[pNode->mMeshes[a]]; mOutput << startstr << "<instance_geometry url=\"#" << GetMeshId( a) << "\">" << endstr; PushTag(); PopTag(); mOutput << startstr << "</instance_geometry>" << endstr; } // recurse into subnodes for( size_t a = 0; a < pNode->mNumChildren; ++a ) WriteNode( pNode->mChildren[a]); PopTag(); mOutput << startstr << "</node>" << endstr; } #endif
[ "ulfjorensen@67173fc5-114c-0410-ac8e-9d2fd5bffc1f", "aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f", "[email protected]" ]
[ [ [ 1, 41 ], [ 44, 50 ], [ 52, 52 ], [ 54, 57 ], [ 63, 351 ], [ 353, 366 ] ], [ [ 42, 43 ], [ 51, 51 ], [ 53, 53 ], [ 58, 62 ], [ 367, 369 ] ], [ [ 352, 352 ] ] ]
514a29982d443de4b30b025ae23771e86285d46c
969a039a5499a68272539ace39a441844a1b5554
/VirtualKeyboard/main.cpp
09bf43045448c961190649bcc831d22d0b9b0e9f
[]
no_license
coolboy/qvirtual-keyboard
5c2533be66ac02425600e119062c09901a6b9e63
4057056ab7952e21fa206cceb434b454be56d0ec
refs/heads/master
2021-01-18T14:38:36.362242
2011-02-01T00:14:24
2011-02-01T00:14:24
32,131,754
0
0
null
null
null
null
UTF-8
C++
false
false
206
cpp
#include "stdafx.h" #include "virtualkeyboard.h" #include <QtGui/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); VirtualKeyboard w; w.show(); return a.exec(); }
[ "coolcute@30274b60-42cb-7143-5b13-851e6f7d0551" ]
[ [ [ 1, 11 ] ] ]
e45ae1cec9b476906ea11af83abe7b4b6d13a831
796752fe73b3a412031f82e9a7ef44a1d75b8406
/src/video.h
bd59f7b3919eaef7374c8a7e227231899b451fa8
[]
no_license
crempp/ima
db550a9dbcf4a2c5bdfe2a357e471944513de7d6
eda328cd96f89bf9c458072c3cb80dcd9476ff63
refs/heads/master
2021-01-22T07:32:49.589499
2009-07-08T06:57:48
2009-07-08T06:57:48
38,577,998
0
0
null
null
null
null
UTF-8
C++
false
false
1,983
h
/*************************************************************** * Name: video.h * Purpose: Code for grabbing the video * Author: Chad Rempp ([email protected]) * Created: 2008-10-28 * Copyright: Chad Rempp (http://www.tetractys.org) * License: **************************************************************/ #ifndef VIDEO_H_INCLUDED #define VIDEO_H_INCLUDED #include <unicap.h> #include <unicap_status.h> #include <algorithm> #include <list> #include <string> #include <vector> #define MAX_DEVICES 4 #define NUM_BUFFERS 10 #define MAX_FRAMES 15 /*struct cam_device{ int exists; wxString dev_name; unicap_handle_t handle; unicap_device_t device; int dev_number; unicap_data_buffer_t buffer; unicap_data_buffer_t* returned_buffer; };*/ void list_devices(void); void load_device(int dev_num); //static void new_frame(unicap_event_t event, unicap_handle_t handle, unicap_data_buffer_t *buffer, void *usr_data); class camDataBuffer{ public: camDataBuffer(); camDataBuffer( void *ptr ); camDataBuffer& operator= ( void *DataPtr ); void *get_ptr() { return (void *)m_unicap_buffer->data; }; bool operator== ( unicap_data_buffer_t *rhs ) { return m_unicap_buffer == rhs; } friend class camDevice; private: unicap_data_buffer_t *GetUnicapBuffer() { return m_unicap_buffer; } private: unicap_data_buffer_t *m_unicap_buffer; }; class camDevice { public: camDevice() { strcpy( m_device.identifier, "" ); } camDevice( wxString id ); static list<camDevice* > EnumerateDevices(); unicap_status_t Open(); unicap_status_t Close(); unicap_status_t StartCapture(); unicap_status_t StopCapture(); unicap_status_t QueueBuffer( CUnicapDataBuffer &b ); unicap_status_t WaitBuffer( CUnicapDataBuffer **b ); char *c_str() {return( m_device.identifier );} private: unicap_device_t m_device; unicap_handle_t m_handle; vector<CUnicapDataBuffer>m_queued_buffers; }; #endif // VIDEO_H_INCLUDED
[ "crempp@gauss" ]
[ [ [ 1, 86 ] ] ]
66a1ffff490065a1364cc52b4645d46afd2155f2
9f00cc73bdc643215425e6bc43ea9c6ef3094d39
/OOP/Project-Lines/MixedBall.cpp
8e75f1c7d96283c7fe08b568c2b6423dc757c4c2
[]
no_license
AndreyShamis/oopos
c0700e1d9d889655a52ad2bc58731934e968b1dd
0114233944c4724f242fd38ac443a925faf81762
refs/heads/master
2021-01-25T04:01:48.005423
2011-07-16T14:23:12
2011-07-16T14:23:12
32,789,875
0
0
null
null
null
null
UTF-8
C++
false
false
744
cpp
#include "MixedBall.h" //============================================================================= // Constructor MixedBall::MixedBall(const float &X,const float &Y, int natuX, int natuY) { _sprites.push_back(MIXED_BALL);// put the image to the cector of sprites // define the colors of the ball _colors.push_back(Blue); _colors.push_back(Yellow); _colors.push_back(White); _colors.push_back(Orange); _colors.push_back(Black); _colors.push_back(Red); _colors.push_back(Green); // set real and natural coords _cordX = X; _cordY = Y; _natuX = natuX; _natuY = natuY; } //============================================================================= // Destructor MixedBall::~MixedBall(void) { }
[ "[email protected]@c8aee422-7d7c-7b79-c2f1-0e09d0793d10" ]
[ [ [ 1, 29 ] ] ]