blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
sequencelengths
1
16
author_lines
sequencelengths
1
16
63e4c5b3be89f0e65b80526827d399fdcb82cd7c
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleCore/TLMessaging.cpp
166f399406ec1a92183418ce72f1d768f3f29d96
[]
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
58
cpp
#include "TLMessaging.h" #include "TEventChannel.h"
[ [ [ 1, 4 ] ] ]
59c88a8b0a6f958ee79573e38485513f620414e1
b144663dd43236066d70be6c09a3c4f8ab5541fd
/olds/v1/src/boost/os_services/detail/file_inode_info.hpp
6374ed6b40e7ad3ff0c0d9e7ab943ac1e9212586
[]
no_license
nkzxw/schwimmer-hund
a1ffbf9243fba148461d65b5ad9cee4519f70f9a
2d0e11efef9f401bbccbba838d516341bc9b3283
refs/heads/master
2021-01-10T05:41:38.207721
2011-02-03T14:57:10
2011-02-03T14:57:10
47,530,533
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
2,189
hpp
#ifndef BOOST_OS_SERVICES_DETAIL_FILE_INODE_INFO_HPP_INCLUDED #define BOOST_OS_SERVICES_DETAIL_FILE_INODE_INFO_HPP_INCLUDED #include <sstream> #include <cstring> // for strerror #include <sys/stat.h> #include <boost/filesystem/path.hpp> namespace boost { namespace os_services { namespace detail { class file_inode_info { public: file_inode_info() : device_id_(0), inode_number_(0) {} file_inode_info( dev_t device_id, ino_t inode_number ) : device_id_(device_id), inode_number_(inode_number) {} file_inode_info( const boost::filesystem::path& path ) { set( path ); } file_inode_info( const file_inode_info& other ) { this->device_id_ = other.device_id_; this->inode_number_ = other.inode_number_; } file_inode_info& operator=( const file_inode_info& other ) { if ( this != &other ) { this->device_id_ = other.device_id_; this->inode_number_ = other.inode_number_; } return *this; } void set( dev_t device_id, ino_t inode_number ) { this->device_id_ = device_id; this->inode_number_ = inode_number; } void set( const struct stat& st ) { this->device_id_ = st.st_dev; this->inode_number_ = st.st_ino; } void set( const boost::filesystem::path& path ) { struct stat st; int return_code = lstat( path.native_file_string().c_str(), &st); if ( return_code == -1) //TODO: pasar "-1" como una macro SYSTEM_CALL_ERROR o algo así... { //TODO: en todos los throw's usar un lexical_cast<>() en ves de un stream... std::ostringstream oss; oss << "lstat error - File: " << path.native_file_string() << " - Reason: " << std::strerror(errno); throw (std::runtime_error(oss.str())); } else { set( st ); } } bool operator==( const file_inode_info& other ) const { return ( this->device_id_ == other.device_id_ && this->inode_number_ == other.inode_number_ ); } bool operator==( const struct stat& other ) const { return ( this->device_id_ == other.st_dev && this->inode_number_ == other.st_ino ); } protected: dev_t device_id_; ino_t inode_number_; }; } // namespace detail } // namespace os_services } // namespace boost #endif // BOOST_OS_SERVICES_DETAIL_FILE_INODE_INFO_HPP_INCLUDED
[ "fpelliccioni@07e413c0-050a-11df-afc1-2de6fd616bef" ]
[ [ [ 1, 98 ] ] ]
c05f33b20115cd7ca456da81c121d4714da4912a
9773c3304eecc308671bcfa16b5390c81ef3b23a
/MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/AIPITreeDoc.cpp
f3a52e1bcc947facbf14bd976daa301c12485309
[]
no_license
15831944/AiPI-1
2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4
9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8
refs/heads/master
2021-12-02T20:34:03.136125
2011-10-27T00:07:54
2011-10-27T00:07:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,382
cpp
// AIPITreeDoc.cpp : implementation file // #include "stdafx.h" #include "AIPI.h" #include "AIPITreeDoc.h" #include "DocTemplateEx.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAIPITreeDoc IMPLEMENT_DYNCREATE(CAIPITreeDoc, CDocument) EXTENSION CAIPITreeDoc::m_apszExtension[] = { EXTENSION(_T("idt"), _T("Decision Tree Files")), EXTENSION(_T("tre"), _T("Aipi Tree Files")), EXTENSION(_T("csv"), _T("Comma Delimited Files")), EXTENSION(_T("apj"), _T("Aipi Project Files")), }; HINT_EXT CAIPITreeDoc::m_aheSave[] = { HINT_EXT(HINT_SAVE_INDENT_TYPE, FF_INDENT_TYPE), HINT_EXT(HINT_SAVE_TREE_TYPE, FF_TREE_TYPE), HINT_EXT(HINT_SAVE_CSV_TYPE, FF_CSV_TYPE), HINT_EXT(HINT_SAVE_PROJ_TYPE, FF_PROJ_TYPE), }; HINT_EXT CAIPITreeDoc::m_aheLoad[] = { HINT_EXT(HINT_LOAD_INDENT_TYPE, FF_INDENT_TYPE), HINT_EXT(HINT_LOAD_TREE_TYPE, FF_TREE_TYPE), HINT_EXT(HINT_LOAD_CSV_TYPE, FF_CSV_TYPE), HINT_EXT(HINT_LOAD_PROJ_TYPE, FF_PROJ_TYPE), }; CAIPITreeDoc::CAIPITreeDoc() { ASSERT(ARRAY_SIZE(m_aheLoad) == FF_MAX_TYPES); ASSERT(ARRAY_SIZE(m_aheSave) == FF_MAX_TYPES); ASSERT(ARRAY_SIZE(m_apszExtension) == FF_MAX_TYPES); GetCurrentDirectory(_MAX_PATH, m_ExamplesPath); _tcscat(m_ExamplesPath, _T("\\Examples")); _tcscpy(m_szDelimiter, _T(",")); // Default delimiter for *.csv type } BOOL CAIPITreeDoc::OnNewDocument() { UpdateAllViews(NULL, HINT_NEW); return TRUE; /* if (!CDocument::OnNewDocument()) return FALSE; return TRUE; */ } CAIPITreeDoc::~CAIPITreeDoc() { } BEGIN_MESSAGE_MAP(CAIPITreeDoc, CDocument) //{{AFX_MSG_MAP(CAIPITreeDoc) ON_COMMAND(ID_FILE_SAVE, OnFileSave) ON_COMMAND(ID_FILE_SAVE_AS, OnFileSaveAs) ON_COMMAND(ID_FILE_OPEN, OnFileOpen) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CAIPITreeDoc diagnostics #ifdef _DEBUG void CAIPITreeDoc::AssertValid() const { CDocument::AssertValid(); } void CAIPITreeDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CAIPITreeDoc serialization void CAIPITreeDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } ///////////////////////////////////////////////////////////////////////////// // CAIPITreeDoc commands void CAIPITreeDoc::OnFileSave() { if (m_strFileNamePath.IsEmpty()) OnFileSaveAs(); else SaveFile(); } void CAIPITreeDoc::GetFilter(TCHAR sFilter[], HINT_EXT ahe[]) { int k; const int MAX_TYPES = 3; //const int MAX_TYPES = 6; TCHAR *name[MAX_TYPES]; TCHAR *text[MAX_TYPES]; for (k = 0; k < MAX_TYPES; k++) { name[k] = m_apszExtension[ahe[k].m_ff].m_name; text[k] = m_apszExtension[ahe[k].m_ff].m_text; } _stprintf(sFilter, _T("%s (*.%s)|*.%s|") _T("Aipi Session File(*.ssn)|*.ssn|") _T("Aipi Knowledge File (*.knw)|*.knw|") _T("All Files (*.*)|*.*||"), name[FF_INDENT_TYPE], text[FF_INDENT_TYPE], text[FF_INDENT_TYPE] ); /* _stprintf(sFilter, _T("%s (*.%s)|*.%s|") _T("%s (*.%s)|*.%s|") _T("%s (*.%s)|*.%s|") _T("%s (*.%s)|*.%s|") _T("Aipi Session File(*.ssn)|*.ssn|") _T("Aipi Knowledge File (*.knw)|*.knw|") _T("All Files (*.*)|*.*||"), name[FF_AIPI_TYPE], text[FF_AIPI_TYPE], text[FF_AIPI_TYPE], name[FF_TREE_TYPE], text[FF_TREE_TYPE], text[FF_TREE_TYPE], name[FF_INDENT_TYPE], text[FF_INDENT_TYPE], text[FF_INDENT_TYPE], name[FF_CSV_TYPE], text[FF_CSV_TYPE], text[FF_CSV_TYPE]); */ for (k = 0; sFilter[k] != 0; k++) sFilter[k] = sFilter[k] == '|' ? '\0' : sFilter[k]; } void CAIPITreeDoc::SaveFile() { TCHAR dir[_MAX_DIR]; TCHAR drive[_MAX_DRIVE]; TCHAR ext[_MAX_EXT]; TCHAR fname[_MAX_FNAME]; int k; long lHint = HINT_LOAD_TREE_TYPE; if (!m_strFileNamePath.IsEmpty()) { _tsplitpath(m_strFileNamePath, drive, dir, fname, ext); for(k = 0; k < ARRAY_SIZE(m_aheSave); k++) { if (_tcscmp(m_apszExtension[m_aheSave[k].m_ff].m_text, ext + 1) == 0) { lHint = m_aheSave[k].m_hint; break; } } CString strName = (LPCTSTR)fname; CString strExt = (LPCTSTR)ext; m_strFileNameExt = strName + strExt; SetTitle((LPCTSTR)strName); UpdateAllViews(NULL, lHint); // Add to MRU file list AddToRecentFileList(m_strFileNamePath); } } // Checks if the modified flag is on. If so, it displays a warning message // (The file was changed. Do you want to save or to discard the modifications?) BOOL CAIPITreeDoc::SaveModified() { if (!IsModified()) return TRUE; // ok to continue CString prompt, sTitle; sTitle = GetTitle(); prompt.Format(_T("File %s has changed.\nDo you want to save the changes?"), sTitle); switch (AfxMessageBox(prompt, MB_YESNOCANCEL)) { case IDCANCEL: return FALSE; // don't continue case IDYES: // If so, either Save or Update, as appropriate OnFileSave(); break; case IDNO: // If not saving changes, revert the document SetModifiedFlag(false); break; default: ASSERT(FALSE); break; } return TRUE; // keep going } void CAIPITreeDoc::CreateNewFrame() { CAIPIApp* pApp = (CAIPIApp*)AfxGetApp(); CDocument *pDoc = NULL; CFrameWnd *pFrameWnd = NULL; CView *pView = NULL; CDocTemplate* pDocTemplate = pApp->m_pAIPITreeDocTemplate; //CDocTemplate* pDocTemplate = pDoc->GetDocTemplate(); pDoc = pApp->SearchDocument(m_strFileNamePath); if (pDoc != NULL) { // Document has already been opened, attach a new view to it pFrameWnd = pDocTemplate->CreateNewFrame(pDoc, NULL); if (pFrameWnd == NULL) { TRACE0("CAIPIApp::OpenDocument : Failed to create new frame for existing document.\n"); pDoc = NULL; return; } // ... Frame is initially visible, this is necessary to send // WM_INITIALUPDATE to the view pDocTemplate->InitialUpdateFrame(pFrameWnd, pDoc, TRUE); pView = pApp->GetFirstView(pFrameWnd); ASSERT(pView != NULL); } } void CAIPITreeDoc::OpenMDIDoc() { CString strExt = m_strFileNamePath.Right(3); if(!m_strFileNamePath.IsEmpty()) { if( strExt == _T("knw") || strExt == _T("txt") ) { CAIPIApp* pApp = (CAIPIApp*)AfxGetApp(); pApp->OpenDocumentFile(m_strFileNamePath); if( pApp == NULL ) { AfxMessageBox( _T("File was not found.")); } return; } else if( strExt == _T("ssn") || strExt == _T("rtf") ) { CAIPIApp* pApp = (CAIPIApp*)AfxGetApp(); pApp->m_pAIPIDocTemplate->OpenDocumentFile(m_strFileNamePath); if( pApp == NULL ) { AfxMessageBox( _T("File was not found.")); } return; } else if( strExt == _T("idt") || strExt == _T("csv") || strExt == _T("tre") ) { CAIPIApp* pApp = (CAIPIApp*)AfxGetApp(); pApp->m_pAIPITreeDocTemplate->OpenDocumentFile(m_strFileNamePath); if( pApp == NULL ) { AfxMessageBox( _T("File was not found.")); } return; } else { AfxMessageBox( _T("Unable to open file. The file type is not compatible.")); } } // Add to MRU file list AddToRecentFileList(m_strFileNamePath); } void CAIPITreeDoc::OpenFile() { TCHAR dir[_MAX_DIR]; TCHAR drive[_MAX_DRIVE]; TCHAR ext[_MAX_EXT]; TCHAR fname[_MAX_FNAME]; int k; long lHint = HINT_LOAD_INDENT_TYPE; CString strExt = m_strFileNamePath.Right(3); if(!m_strFileNamePath.IsEmpty()) { if( strExt == _T("knw") || strExt == _T("txt") ) { CAIPIApp* pApp = (CAIPIApp*)AfxGetApp(); pApp->OpenDocumentFile(m_strFileNamePath); if( pApp == NULL ) { AfxMessageBox( _T("File was not found.")); } return; } if( strExt == _T("ssn") || strExt == _T("rtf") ) { CAIPIApp* pApp = (CAIPIApp*)AfxGetApp(); pApp->m_pAIPIDocTemplate->OpenDocumentFile(m_strFileNamePath); if( pApp == NULL ) { AfxMessageBox( _T("File was not found.")); } return; } _tsplitpath((LPCTSTR)m_strFileNamePath, drive, dir, fname, ext); for(k = 0; k < ARRAY_SIZE(m_aheLoad); k++) { if (_tcscmp(m_apszExtension[m_aheLoad[k].m_ff].m_text, ext + 1) == 0) { lHint = m_aheLoad[k].m_hint; break; } } CString strName = (LPCTSTR)fname; CString strExt = (LPCTSTR)ext; m_strFileNameExt = strName + strExt; SetTitle((LPCTSTR)strName); UpdateAllViews(NULL, lHint); // Add to MRU file list AddToRecentFileList(m_strFileNamePath); } } void CAIPITreeDoc::OnFileSaveAs() { OPENFILENAME ofn; TCHAR szFile[MAX_PATH] = TEXT(""); TCHAR sFilter[256]; GetFilter(sFilter, m_aheLoad); ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; ofn.hInstance = GetModuleHandle(NULL); ofn.lpstrFilter = sFilter; ofn.lpstrCustomFilter = NULL; ofn.nMaxCustFilter = 0; ofn.nFilterIndex = 1; ofn.nMaxFile = _MAX_PATH; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = m_ExamplesPath; ofn.lpstrDefExt = m_apszExtension[m_aheSave[0].m_ff].m_text; ofn.lpstrTitle = TEXT("Save As"); ofn.lpTemplateName = MAKEINTRESOURCE(IDD_OPEN_DELIMITER_DLG); ofn.lpfnHook = (LPOFNHOOKPROC)DelimiterHookProc; ofn.lCustData = (DWORD)this; ofn.Flags = OFN_EXPLORER | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_ENABLEHOOK | OFN_ENABLETEMPLATE | 0; ofn.lpstrFile = szFile; if (GetSaveFileName(&ofn)) { m_strFileNamePath = ofn.lpstrFile; SaveFile(); } } void CAIPITreeDoc::OnFileOpen() { // Customize the common dialog: CFileDialog with a hook procedure to be able to ask // about the suitable delimiter. OPENFILENAME ofn; TCHAR sFilter[256]; TCHAR szFile[MAX_PATH] = TEXT(""); if (!SaveModified()) return; GetFilter(sFilter, m_aheLoad); ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; ofn.hInstance = GetModuleHandle(NULL); ofn.lpstrFilter = sFilter; ofn.lpstrCustomFilter = NULL; ofn.nMaxCustFilter = 0; ofn.nFilterIndex = 1; ofn.nMaxFile = _MAX_PATH; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = m_ExamplesPath; ofn.lpstrDefExt = m_apszExtension[m_aheLoad[0].m_ff].m_text; ofn.lpstrTitle = TEXT("Open"); ofn.lpTemplateName = MAKEINTRESOURCE(IDD_OPEN_DELIMITER_DLG); ofn.lpfnHook = (LPOFNHOOKPROC)DelimiterHookProc; ofn.lCustData = (DWORD)this; ofn.Flags = OFN_EXPLORER | OFN_OVERWRITEPROMPT | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_ENABLEHOOK | OFN_ENABLETEMPLATE | 0; ofn.lpstrFile = szFile; if (GetOpenFileName(&ofn)) { m_strFileNamePath = ofn.lpstrFile; OpenMDIDoc(); } } BOOL CALLBACK DelimiterHookProc(HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam) { static CAIPITreeDoc *pted = NULL; LPOFNOTIFY lpon; BOOL bIsCsvSelected; static int aid[] = { IDC_STATIC_GROUP, IDC_TAB, IDC_COMMA, IDC_OTHER, IDC_DELIMITER, }, k; static HWND ahCtrl[ARRAY_SIZE(aid)]; switch(uMessage) { case WM_INITDIALOG: for (k = 0; k < ARRAY_SIZE(aid); k++) { ahCtrl[k] = GetDlgItem(hWnd, aid[k]); EnableWindow(ahCtrl[k], false); } pted = (CAIPITreeDoc *)((LPOPENFILENAME)(lParam))->lCustData; SendDlgItemMessage(hWnd, IDC_DELIMITER, EM_LIMITTEXT, 1, 0); SendDlgItemMessage(hWnd, IDC_DELIMITER, WM_SETTEXT, 0,(LPARAM) pted->m_szDelimiter); CheckRadioButton(hWnd, IDC_TAB, IDC_OTHER, IDC_COMMA); break; case WM_COMMAND: if(HIWORD (wParam) == EN_CHANGE && LOWORD(wParam) == IDC_DELIMITER) { // Get the character SendDlgItemMessage(hWnd, IDC_DELIMITER, EM_GETLINE,0,(LPARAM) pted->m_szDelimiter); pted->m_szDelimiter[1] = 0; } if (HIWORD (wParam) == BN_CLICKED) EnableWindow(ahCtrl[4], LOWORD(wParam) == IDC_OTHER); break; case WM_NOTIFY: lpon = (LPOFNOTIFY) lParam; if (lpon->hdr.code == CDN_FILEOK) { if (IsDlgButtonChecked(hWnd, IDC_TAB)) _tcscpy(pted->m_szDelimiter, _T("\t")); else if (IsDlgButtonChecked(hWnd, IDC_COMMA)) _tcscpy(pted->m_szDelimiter, _T(",")); } if (lpon->hdr.code == CDN_TYPECHANGE) { bIsCsvSelected = lpon->lpOFN->nFilterIndex == FF_CSV_TYPE + 1; for (k = 0; aid[k] != IDC_DELIMITER; k++) EnableWindow(ahCtrl[k], bIsCsvSelected); } break; } return FALSE; } BOOL CAIPITreeDoc::OnOpenDocument(LPCTSTR lpszPathName) { if (SaveModified()) { m_strFileNamePath = lpszPathName; OpenFile(); } return TRUE; } void CAIPITreeDoc::OnDisplayDirectoryTree() { // Customize the common dialog: CFileDialog with a hook procedure to be able to ask // about the suitable delimiter. BROWSEINFO bi; LPMALLOC pMalloc = NULL; LPITEMIDLIST pidl = NULL; TCHAR szFileName[MAX_PATH]; long lHint = HINT_LOAD_DIRECTORY; BOOL bRC; CString str; ZeroMemory(&bi, sizeof(BROWSEINFO)); bi.ulFlags = BIF_RETURNONLYFSDIRS; if (!SaveModified()) return; pidl = SHBrowseForFolder(&bi); if (pidl != NULL) { bRC = SHGetPathFromIDList(pidl, szFileName); if (!bRC) { AfxMessageBox(_T("Invalid selection!")); return; } m_strFileNamePath = szFileName; SHGetMalloc(&pMalloc); pMalloc->Free(pidl); pMalloc->Release(); // When we read a directory, we dwr paths of the form: // X:\Subdirectory_1\...Subdirectory_n". Reading that is similar to reading CSV // files, where the delimiter is "\". _tcscpy(m_szDelimiter, _T("\\")); // Title is "Untitled" // >m_strFileName is used as the default file name , when the Save // function (Ctrl+S) is called. If Ctrl+D was called, we cannot, of course, // giving the tree name we built, the name of an existing directory. So, we reset // m_strFileName as soon as the directory is loaded, to force the user to choose a name, // when he saves the tree. See last instructions of function: // void CEditTreeCtrl::OnLoadEntireTree(FILE_FORMAT ff, CTreeType &tt) after // ...................... // if (ff == FF_DIRECTORY_TYPE) // { // } SetTitle(_T("Untitled")); UpdateAllViews(NULL, lHint); } } void CAIPITreeDoc::AddToRecentFileList(LPCTSTR lpszPathName) { ((CAIPIApp*)AfxGetApp())->AddToRecentFileList(lpszPathName); } void CAIPITreeDoc::SetPathName(LPCTSTR lpszPathName, BOOL bAddToMRU) { // TODO: Add your specialized code here and/or call the base class CDocument::SetPathName(lpszPathName, FALSE); CDocTemplateEx* pDocTemplate = (CDocTemplateEx *)GetDocTemplate(); pDocTemplate->AddToRecentFileList(lpszPathName); //CDocument::SetPathName(lpszPathName, bAddToMRU); }
[ [ [ 1, 630 ] ] ]
d8ec2b92e886102c393793c81eb232aa9dc77f72
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/kernelhwsrv/base/performance/f32/t_perf/inc/SeekFileStep.h
ec343de93ed8637655971ee1c33128557c55cebe
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,001
h
/* * Copyright (c) 2007 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: * */ #ifndef __SEEK_FILE_STEP_H__ #define __SEEK_FILE_STEP_H__ //User includes #include "BaseStep.h" /*@{*/ //Literals used _LIT(KT_SeekFileStep, "SeekFileStep"); /*@}*/ class CT_SeekFileStep:public CT_F32BaseStep /** @test @publishedPartner */ { public: CT_SeekFileStep(); ~CT_SeekFileStep(); TVerdict doTestStepPreambleL(); protected: virtual TInt ThreadFuncL(RFs& aSession); private: void SetSeekMode(TDesC& aSeekMode); protected: TSeek iSeekMode; }; #endif /* __SEEK_FILE_STEP_H__ */
[ "none@none" ]
[ [ [ 1, 57 ] ] ]
ed3ad5f17e4dfacc575357922315d73fc8423c60
cc946ca4fb4831693af2c6f252100b9a83cfc7d0
/uCash.Cybos/uCash.Cybos.FutureTradeData.cpp
7f8c7589dd4b793194fa4fc0ed0af0a8362b9bf9
[]
no_license
primespace/ucash-cybos
18b8b324689516e08cf6d0124d8ad19c0f316d68
1ccece53844fad0ef8f3abc8bbb51dadafc75ab7
refs/heads/master
2021-01-10T04:42:53.966915
2011-10-14T07:15:33
2011-10-14T07:15:33
52,243,596
7
0
null
null
null
null
UTF-8
C++
false
false
244
cpp
#include "stdafx.h" #include "uCash.Cybos.Export.h" #include "uCash.Cybos.FutureTradeData.h" namespace uCash { namespace Cybos { FutureTradeData::FutureTradeData(void) { } FutureTradeData::~FutureTradeData(void) { } }}
[ [ [ 1, 16 ] ] ]
6d0714a1522a474761d8264bada2d3da76e14a3a
216ae2fd7cba505c3690eaae33f62882102bd14a
/utils/nxogre/include/NxOgreArchive.h
0aae6c9fb833ca44c0fc78811cd0652178531c5e
[]
no_license
TimelineX/balyoz
c154d4de9129a8a366c1b8257169472dc02c5b19
5a0f2ee7402a827bbca210d7c7212a2eb698c109
refs/heads/master
2021-01-01T05:07:59.597755
2010-04-20T19:53:52
2010-04-20T19:53:52
56,454,260
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,620
h
/** File: NxOgreArchive.h Created on: 17-Nov-08 Author: Robin Southern "betajaen" SVN: $Id$ © Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org This file is part of NxOgre. NxOgre is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NxOgre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with NxOgre. If not, see <http://www.gnu.org/licenses/>. */ #ifndef NXOGRE_ARCHIVE_H #define NXOGRE_ARCHIVE_H #include "NxOgreStable.h" #include "NxOgreCommon.h" namespace NxOgre_Namespace { /** \brief An archive is a collection of resources in one place. It may be implemented as a directory, zip file or even a website. */ class NxOgrePublicClass Archive { public: // Functions Archive(String name, const UniformResourceIdentifier&, ResourceProtocol*); /** \brief Required virtual constructor. */ virtual ~Archive(void); /** \brief Open a new Resource based on an ArchiveResourceIdentifier, and Resource access permissions. \note Archive* should be the original SharedPointer to this archive. */ virtual Resource* open(const ArchiveResourceIdentifier&, NxOgre::Enums::ResourceAccess) = 0; /** \brief Close a Resource */ virtual void close(Resource*) = 0; /** \brief Get the name of the Archive. */ String getName(); /** \brief Get the hash of the name of the Archive. */ unsigned long getNameHash(); /** \brief Get the ResourceProtocol associated with the Archive. */ ResourceProtocol* getProtocol() const; /** \brief Get the UniformResourceIdentifier that identifies the Archive in the OS. */ UniformResourceIdentifier getURI(); protected: // Variables /** \brief Name of the Resource */ String mName; /** \brief Name of the Resource as a hash. */ unsigned long mNameHash; /** \brief Parent ResourceProtocol */ ResourceProtocol* mProtocol; /** \brief The UniformResourceIdentifier of this Archive; the protocol name and accessor of the archive. */ UniformResourceIdentifier mURI; /** \brief Current Resources that are in use by the archive */ Array<Resource*> mCurrentResources; }; // class Archive } // namespace NxOgre_Namespace #endif
[ "umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b" ]
[ [ [ 1, 108 ] ] ]
2c6cd5bfd5c722ff15c143c80d32218ebb5e20a8
611fc0940b78862ca89de79a8bbeab991f5f471a
/src/Teki/Boss/Ookami/ASOokamiJumpAttack.cpp
f53ed37ba1d8ee3a44dd27aee0e8a99dc0e64b98
[]
no_license
LakeIshikawa/splstage2
df1d8f59319a4e8d9375b9d3379c3548bc520f44
b4bf7caadf940773a977edd0de8edc610cd2f736
refs/heads/master
2021-01-10T21:16:45.430981
2010-01-29T08:57:34
2010-01-29T08:57:34
37,068,575
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,090
cpp
#include <string> #include <vector> #include <exception> using namespace std; #include "ASOokamiJumpAttack.h" #include "..\\..\\..\\Management\\GameControl.h" /************************************************************//** * 位置情報の作成 ****************************************************************/ void ASOokamiJumpAttack::BuildPosInfo(ActionState* rPrevState) { // 固定情報 ASOokamiBase::BuildPosInfo(rPrevState); // 初期以外のみ if( rPrevState ){ // 右側にいる場合 if( rPrevState->GetX() >= SP->SCRSZX ){ mMuki = 0; mY = GI("OOKAMI_STARTY"); } // 左側にいる場合 else if( rPrevState->GetX() <= 0 ){ mMuki = 1; mY = GI("OOKAMI_STARTY"); } } // X速度 mSpX = (mMuki?1:-1) * OOKAMI_STRATKSPX; } /************************************************************//** * アニメーションの作成 ****************************************************************/ void ASOokamiJumpAttack::BuildAnimation(ActionState* rPrevState) { mAnimation = Animation::ParseFromFile( "data\\animdata\\ookami\\JumpAttack.txt" ); } /************************************************************//** * OnEnter ****************************************************************/ void ASOokamiJumpAttack::OnEnter() { // SE GAMECONTROL->GetSoundController()->LoopSE("audio\\se\\se_boss2_move.wav"); } /************************************************************//** * ジャンプしながら攻撃してくる ****************************************************************/ bool ASOokamiJumpAttack::Update() { // ジャンプ if( mY >= OOKAMI_STARTY ){ mSpY = -OOKAMI_JMPSHOSOKUY; } else{ mSpY += SP->GRAVITY; } mY += mSpY; return ASOokamiStraightAttack::Update(); } /************************************************************//** * OnExit ****************************************************************/ void ASOokamiJumpAttack::OnExit() { // SE GAMECONTROL->GetSoundController()->StopSE("audio\\se\\se_boss2_move.wav"); }
[ "lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b", "cat2.silly.affection@c9935178-01ba-11df-8f7b-bfe16de6f99b" ]
[ [ [ 1, 42 ], [ 52, 70 ] ], [ [ 43, 51 ], [ 71, 78 ] ] ]
e5d560b2bf0a028108223f0ee285737407ac26f3
6c8c4728e608a4badd88de181910a294be56953a
/ProtocolUtilities/NetworkMessages/NetMessageManager.h
a5a9a3aa30a824f323ccea17ef5ed0b576954935
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,998
h
// For conditions of distribution and use, see copyright notice in license.txt #ifndef incl_ProtocolUtilities_NetMessageManager_h #define incl_ProtocolUtilities_NetMessageManager_h #include <list> #include <set> #include <boost/shared_ptr.hpp> #include "NetworkConnection.h" #include "NetInMessage.h" #include "NetOutMessage.h" #include "NetMessage.h" #include "Interfaces/INetMessageListener.h" #include "EventHistory.h" namespace ProtocolUtilities { /// Manages both in- and outbound UDP communication. Implements a packet queue, packet sequence numbering, ACKing, /// pinging, and reliable communications. reX-protocol specific. Used internally by OpenSimProtocolModule, external /// module users don't need to work on this. class NetMessageManager { public: /// The message manager starts in a disconnected state. /// @param The filename to take the message definitions from. NetMessageManager(const char *messageListFilename); ~NetMessageManager(); /// Connects to the given server. bool ConnectTo(const char *serverAddress, int port); /// Disconnets from the current server. void Disconnect(); /// To start building a new outbound message, call this. /// @return An empty message holder where the message can be built. NetOutMessage *StartNewMessage(NetMsgID msgId); /// To tell the manager that building the message is now finished and can be put into the outbound queue, call this. void FinishMessage(NetOutMessage *message); /// Reads in all inbound UDP messages and processes them forward to the application through the listener. /// Checks and resends any timed out reliable outbound messages. This could be moved into a separate thread, but not that timing specific so not necessary atm. void ProcessMessages(); /// Interprets the given byte stream as a message and dumps it contents out to the log. Useful only for diagnostics and such. void DumpNetworkMessage(NetMsgID id, NetInMessage *msg); /// @return The Message Info structure associated with the given message ID. const NetMessageInfo *GetMessageInfoByID(NetMsgID id) const; #ifndef RELEASE void DebugSendHardcodedTestPacket(); void DebugSendHardcodedRandomPacket(size_t numBytes); #endif /// Sets the object that receives the network packets. Replaces the old. Currently supports only one listener. /// \todo weakptr'ize. \todo delegate/event \todo pub/sub or something else. void RegisterNetworkListener(INetMessageListener *listener) { messageListener = listener; } void UnregisterNetworkListener(INetMessageListener *listener) { messageListener = 0; } #ifdef PROFILING EventHistory sentDatagrams; EventHistory sentDatabytes; EventHistory receivedDatagrams; EventHistory receivedDatabytes; /// A history of occurrences of when a packet has had to be resent. EventHistory resentPackets; /// A history of occurrences when we assume we have lost an incoming packet (we generate false positives when receiving data out-of-order, but that's not critical) EventHistory lostPackets; /// A history of occurrences of when we have received a duplicate packet and have discarded it. EventHistory duplicatesReceived; #endif private: /// Deallocates all memory used for outbound message structs. void ClearMessagePoolMemory(); /// @return A new sequence number for outbound UDP messages. size_t GetNewSequenceNumber() { return sequenceNumber++; } /// Queues acking the packet with the given packetID. void QueuePacketACK(uint32_t packetID); /// Sends pending acks to the server. void SendPendingACKs(); /// Processes a single raw datagram received from the network. void HandleInboundBytes(std::vector<uint8_t> &data); /// Processes a received PacketAck message. void ProcessPacketACK(NetInMessage *msg); /// Processes a received PacketAck ID. void ProcessPacketACK(uint32_t id); /// Responds to a ping check from the server with a CompletePingCheck message. void SendCompletePingCheck(uint8_t pingID); /// Called to send out a message that is already binary-mangled to the proper final format. (packet number, zerocoding, flags, ...) void SendProcessedMessage(NetOutMessage *msg); /// Adds message to the queue of reliable outbound messages. void AddMessageToResendQueue(NetOutMessage *msg); /// Removes message from the queue of reliable outbound messages. void RemoveMessageFromResendQueue(uint32_t packetID); /// @return True, if the resend queue is empty, false otherwise. bool ResendQueueIsEmpty() const { return messageResendQueue.empty(); } /// Checks each reliable message in outbound queue and resends any of the if an Ack was not received within a time-out period. void ProcessResendQueue(); NetMessageManager(const NetMessageManager &); void operator=(const NetMessageManager &); /// All incoming UDP packets are routed to this handler. INetMessageListener *messageListener; /// The socket for the UDP connection. boost::shared_ptr<NetworkConnection> connection; /// List of messages this manager can handle. boost::shared_ptr<NetMessageList> messageList; /// A pool of allocated unused NetOutMessage structures. Used to avoid unnecessary allocations at runtime. std::list<NetOutMessage*> unusedMessagePool; /// A pool of NetOutMessage structures, which have been handed out to the application and are currently being built. std::list<NetOutMessage*> usedMessagePool; /// Packet acks pending to be sent std::set<uint32_t> pendingACKs; typedef std::list<std::pair<time_t, NetOutMessage*> > MessageResendList; /// A pool of NetOutMessages that are in the outbound queue. Need to keep the unacked reliable messages in /// memory for possible resending. MessageResendList messageResendQueue; /// A running sequence number for outbound messages. size_t sequenceNumber; /// The sequence number of the most recent packet we received. Note that this can go up and down if we receive data out of order (or if we receive spoofed data) size_t lastReceivedSequenceNumber; /// A set of received messages' sequence numbers. std::set<uint32_t> receivedSequenceNumbers; }; } #endif // incl_ProtocolUtilities_NetMessageManager_h
[ "jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3", "jaakkoallander@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 13 ], [ 15, 18 ], [ 151, 154 ] ], [ [ 14, 14 ], [ 50, 52 ], [ 63, 75 ], [ 88, 91 ], [ 144, 146 ] ], [ [ 19, 49 ], [ 53, 62 ], [ 76, 87 ], [ 92, 143 ], [ 147, 150 ] ] ]
b09c8772ffa1a88376bb065510a1754e4830fa5e
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit2/Platform/mac/SharedMemoryMac.cpp
c702bb470d3c2088942adfcecd75476dd5947616
[]
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
5,246
cpp
/* * 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. */ #include "SharedMemory.h" #include "ArgumentDecoder.h" #include "ArgumentEncoder.h" #include "Arguments.h" #include "MachPort.h" #include <mach/mach_port.h> #include <mach/mach_vm.h> #include <mach/vm_map.h> #include <wtf/RefPtr.h> namespace WebKit { SharedMemory::Handle::Handle() : m_port(MACH_PORT_NULL) , m_size(0) { } SharedMemory::Handle::~Handle() { if (m_port) mach_port_deallocate(mach_task_self(), m_port); } void SharedMemory::Handle::encode(CoreIPC::ArgumentEncoder* encoder) const { ASSERT(m_port); ASSERT(m_size); encoder->encodeUInt64(m_size); encoder->encode(CoreIPC::MachPort(m_port, MACH_MSG_TYPE_COPY_SEND)); m_port = MACH_PORT_NULL; } bool SharedMemory::Handle::decode(CoreIPC::ArgumentDecoder* decoder, Handle& handle) { ASSERT(!handle.m_port); ASSERT(!handle.m_size); uint64_t size; if (!decoder->decodeUInt64(size)) return false; CoreIPC::MachPort machPort; if (!decoder->decode(CoreIPC::Out(machPort))) return false; handle.m_size = size; handle.m_port = machPort.port(); return true; } static inline void* toPointer(mach_vm_address_t address) { return reinterpret_cast<void*>(static_cast<uintptr_t>(address)); } static inline mach_vm_address_t toVMAddress(void* pointer) { return static_cast<mach_vm_address_t>(reinterpret_cast<uintptr_t>(pointer)); } PassRefPtr<SharedMemory> SharedMemory::create(size_t size) { mach_vm_address_t address; kern_return_t kr = mach_vm_allocate(mach_task_self(), &address, round_page(size), VM_FLAGS_ANYWHERE); if (kr != KERN_SUCCESS) return 0; RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory)); sharedMemory->m_size = size; sharedMemory->m_data = toPointer(address); return sharedMemory.release(); } static inline vm_prot_t machProtection(SharedMemory::Protection protection) { switch (protection) { case SharedMemory::ReadOnly: return VM_PROT_READ; case SharedMemory::ReadWrite: return VM_PROT_READ | VM_PROT_WRITE; } ASSERT_NOT_REACHED(); return VM_PROT_NONE; } PassRefPtr<SharedMemory> SharedMemory::create(const Handle& handle, Protection protection) { if (!handle.m_port) return 0; // Map the memory. vm_prot_t vmProtection = machProtection(protection); mach_vm_address_t mappedAddress; kern_return_t kr = mach_vm_map(mach_task_self(), &mappedAddress, handle.m_size, 0, VM_FLAGS_ANYWHERE, handle.m_port, 0, false, vmProtection, vmProtection, VM_INHERIT_NONE); if (kr != KERN_SUCCESS) return 0; RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory)); sharedMemory->m_size = handle.m_size; sharedMemory->m_data = toPointer(mappedAddress); return sharedMemory.release(); } SharedMemory::~SharedMemory() { if (!m_data) return; kern_return_t kr = mach_vm_deallocate(mach_task_self(), toVMAddress(m_data), round_page(m_size)); ASSERT_UNUSED(kr, kr == KERN_SUCCESS); } bool SharedMemory::createHandle(Handle& handle, Protection protection) { ASSERT(!handle.m_port); ASSERT(!handle.m_size); mach_vm_address_t address = toVMAddress(m_data); memory_object_size_t size = round_page(m_size); // Create a mach port that represents the shared memory. mach_port_t port; kern_return_t kr = mach_make_memory_entry_64(mach_task_self(), &size, address, machProtection(protection), &port, MACH_PORT_NULL); if (kr != KERN_SUCCESS) return false; handle.m_port = port; handle.m_size = size; return true; } unsigned SharedMemory::systemPageSize() { return vm_page_size; } } // namespace WebKit
[ [ [ 1, 169 ] ] ]
cd5b7886c8700bfd361038b6c185fe611601ba3d
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/Release/Client/stubs/corlib_native_System_Threading_ManualResetEvent_mshl.cpp
5b8dc8b3d9cb2b44528002c6f7edef96893bd026
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,866
cpp
//----------------------------------------------------------------------------- // // ** DO NOT EDIT THIS FILE! ** // This file was generated by a tool // re-running the tool will overwrite this file. // //----------------------------------------------------------------------------- #include "corlib_native.h" #include "corlib_native_System_Threading_ManualResetEvent.h" using namespace System::Threading; HRESULT Library_corlib_native_System_Threading_ManualResetEvent::_ctor___VOID__BOOLEAN( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT8 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT8( stack, 1, param0 ) ); ManualResetEvent::_ctor( pMngObj, param0, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_Threading_ManualResetEvent::Reset___BOOLEAN( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT8 retVal = ManualResetEvent::Reset( pMngObj, hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_INT8( stack, retVal ); } TINYCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_Threading_ManualResetEvent::Set___BOOLEAN( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT8 retVal = ManualResetEvent::Set( pMngObj, hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_INT8( stack, retVal ); } TINYCLR_NOCLEANUP(); }
[ [ [ 1, 63 ] ] ]
1a686eaabdd1d57021f7c7f00b7aff15d4d9db91
b07566e1ed4d9f8e049ede1e69794128836ebe20
/include/GewiSlider.h
2445eea1cce3b469d4f2aace1a05ee7c7ebcdf98
[]
no_license
jamesturk/zengine-gewi
f0bdcd62c59ba89d4ecd14046a4c786b1031176c
82d587994934c5b2407ec100b101b83936a2b5c4
refs/heads/master
2020-06-03T18:57:37.344168
2003-10-05T23:44:37
2003-10-05T23:44:37
117,120
1
0
null
null
null
null
UTF-8
C++
false
false
5,742
h
/******************************************************************************* This file is Part of the Gewi GUI Library for ZEngine. Gewi and ZEngine Copyright (C) 2002, 2003 James Turk Licensed under a BSD-style license. (see licensing.txt) The maintainer of this library is James Turk ([email protected]) this library is found at the home of ZEngine http://zengine.sourceforge.net *******************************************************************************/ /*! \file GewiSlider.h \brief Definition file for GSlider, GHorizSlider and GVertSlider. Definition file for GSlider, GHorizSlider and GVertSlider, the slide-select classes for Gewi. <br>$Id: GewiSlider.h,v 1.4 2003/06/07 05:41:18 cozman Exp $<br> \author James Turk **/ #ifndef __gewislider_h__ #define __gewislider_h__ #include "GewiEngine.h" #include "GewiWidget.h" namespace Gewi { /*! \brief GSlider (virtual) slider widget class. Framework for simple slider widget, virtual (fails to overload Show), derived from GWidget. **/ class GSlider : public GWidget { protected: //! Boolean value holding if slider is currently 'pressed' or active. bool rPressed; //! ID for background image for slider. ResourceID rBackground; //! Image ID for the sliding part of the slider. ResourceID rSlider; //! Minimum position for slider. float rMin; //! Maximum position for slider. float rMax; //! Current position of slider. float rPos; //! Movement snap increment. int rIncrement; public: /*! \brief Simple constructor for GSlider. Default constructor for GSlider, can take a parent. \param parent Pointer to GContainer derived class to be the parent. Default value is NULL which means no parent. **/ GSlider(GContainer *parent=NULL); /*! \brief GSlider's create function, must be called to set up actual slider. Every widget has a create function which must be called to define the button's appearance and settings. \param x X position of widget within it's container (entire screen if no parent) \param y Y position of widget within it's container (entire screen if no parent) \param width Width of widget. \param height Height of widget. \param backgroundImg Image for stationary portion of slider. \param sliderImg Image for moving portion of slider. \param min Minimum value on slider. \param max Maximum value on slider. \param increment Slider snap-to increment. **/ virtual void Create(float x, float y, float width, float height, ResourceID backgroundImg, ResourceID sliderImg, float min, float max, int increment); /*! \brief Set position of slider. Sets position of slider, will snap within bounds. \param pos Desired position. **/ void SetPos(float pos); /*! \brief Get position of slider. Access current position of slider. \return Slider position. **/ float GetPos(); }; /*! \brief GHorizSlider, horizontal slider widget class. Derived from GSlider, overloads message and show to complete the class. **/ class GHorizSlider : public GSlider { public: /*! \brief Overload of Message, used to recieve messages. Recieves and processes a message, required overload for all widgets. \param rawEvent SDL_Event of original message, may be needed if more information is available on event. (May be NULL). \param event GewiEvent enum, description of event recieved. \param mouseX Mouse x position in event, if not mouse event may be incorrect. \param mouseY Mouse y position in event, if not mouse event may be incorrect. \param ch Character pressed in event, may be 0 if not a keypress event. **/ virtual void Message(SDL_Event *rawEvent, GewiEvent event, Uint16 mouseX, Uint16 mouseY, char ch); /*! \brief Draws this slider to the screen. Draws widget to the screen, required overload for all widgets. **/ virtual void Show(); }; /*! \brief GHorizSlider, horizontal slider widget class Derived from GSlider, overloads message and show to complete the class. **/ class GVertSlider : public GSlider { public: /*! \brief Overload of Message, used to recieve messages. Recieves and processes a message, required overload for all widgets. \param rawEvent SDL_Event of original message, may be needed if more information is available on event. (May be NULL). \param event GewiEvent enum, description of event recieved. \param mouseX Mouse x position in event, if not mouse event may be incorrect. \param mouseY Mouse y position in event, if not mouse event may be incorrect. \param ch Character pressed in event, may be 0 if not a keypress event. **/ virtual void Message(SDL_Event *rawEvent, GewiEvent event, Uint16 mouseX, Uint16 mouseY, char ch); /*! \brief Draws this slider to the screen. Draws widget to the screen, required overload for all widgets. **/ virtual void Show(); }; } #endif //__gewislider_h__
[ "cozman" ]
[ [ [ 1, 153 ] ] ]
e8691c6f53a5392016beb221601a60bb1685d789
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/gcscontrol/gcscontrolgadget.cpp
d1b45b98d2af445fa4cd75f4d4f1515f39c2fea1
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,134
cpp
/** ****************************************************************************** * * @file GCSControlgadget.cpp * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup GCSControlGadgetPlugin GCSControl Gadget Plugin * @{ * @brief A gadget to control the UAV, either from the keyboard or a joystick *****************************************************************************/ /* * 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, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "gcscontrolgadget.h" #include "gcscontrolgadgetwidget.h" #include "extensionsystem/pluginmanager.h" #include "uavobjects/uavobjectmanager.h" #include "uavobjects/uavobject.h" #include <QDebug> GCSControlGadget::GCSControlGadget(QString classId, GCSControlGadgetWidget *widget, QWidget *parent) : IUAVGadget(classId, parent), m_widget(widget) { connect(getManualControlCommand(),SIGNAL(objectUpdated(UAVObject*)),this,SLOT(manualControlCommandUpdated(UAVObject*))); connect(widget,SIGNAL(sticksChanged(double,double,double,double)),this,SLOT(sticksChangedLocally(double,double,double,double))); connect(this,SIGNAL(sticksChangedRemotely(double,double,double,double)),widget,SLOT(updateSticks(double,double,double,double))); manualControlCommandUpdated(getManualControlCommand()); connect(this, SIGNAL(aboutToQuit()), &sdlGamepad, SLOT(quit())); if(sdlGamepad.init()) { qDebug() << "SDL Initialized"; sdlGamepad.start(); qRegisterMetaType<QListInt16>("QListInt16"); qRegisterMetaType<ButtonNumber>("ButtonNumber"); connect(&sdlGamepad,SIGNAL(gamepads(quint8)),this,SLOT(gamepads(quint8))); connect(&sdlGamepad,SIGNAL(buttonState(ButtonNumber,bool)),this,SLOT(buttonState(ButtonNumber,bool))); connect(&sdlGamepad,SIGNAL(axesValues(QListInt16)),this,SLOT(axesValues(QListInt16))); } } GCSControlGadget::~GCSControlGadget() { } void GCSControlGadget::loadConfiguration(IUAVGadgetConfiguration* config) { ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance(); UAVObjectManager *objManager = pm->getObject<UAVObjectManager>(); UAVDataObject* obj = dynamic_cast<UAVDataObject*>( objManager->getObject(QString("ManualControlCommand")) ); } ManualControlCommand* GCSControlGadget::getManualControlCommand() { ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance(); UAVObjectManager *objManager = pm->getObject<UAVObjectManager>(); return dynamic_cast<ManualControlCommand*>( objManager->getObject(QString("ManualControlCommand")) ); } void GCSControlGadget::manualControlCommandUpdated(UAVObject * obj) { double roll = obj->getField("Roll")->getDouble(); double pitch = obj->getField("Pitch")->getDouble(); double yaw = obj->getField("Yaw")->getDouble(); double throttle = obj->getField("Throttle")->getDouble(); emit sticksChangedRemotely(yaw,-pitch,roll,throttle); } void GCSControlGadget::sticksChangedLocally(double leftX, double leftY, double rightX, double rightY) { ManualControlCommand * obj = getManualControlCommand(); double oldRoll = obj->getField("Roll")->getDouble(); double oldPitch = obj->getField("Pitch")->getDouble(); double oldYaw = obj->getField("Yaw")->getDouble(); double oldThrottle = obj->getField("Throttle")->getDouble(); double newRoll = rightX; double newPitch = -leftY; double newYaw = leftX; double newThrottle = rightY; if((newThrottle != oldThrottle) || (newPitch != oldPitch) || (newYaw != oldYaw) || (newRoll != oldRoll)) { obj->getField("Roll")->setDouble(newRoll); obj->getField("Pitch")->setDouble(newPitch); obj->getField("Yaw")->setDouble(newYaw); obj->getField("Throttle")->setDouble(newThrottle); obj->updated(); } } void GCSControlGadget::gamepads(quint8 count) { sdlGamepad.setGamepad(0); sdlGamepad.setTickRate(40); } void GCSControlGadget::buttonState(ButtonNumber number, bool pressed) { } void GCSControlGadget::axesValues(QListInt16 values) { double leftX = values[0]; double leftY = values[1]; double rightX = values[2]; double rightY = values[3]; double max = 32767; sticksChangedLocally(leftX/max,-leftY/max,rightX/max,-rightY/max); }
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 124 ] ] ]
e57c71f55df64471d17f1ffd7077c9da88348ec8
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/QtGui/qgraphicsscene.h
59118da8ae03dd0080778986f54514bb8e8c763d
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,335
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QGRAPHICSSCENE_H #define QGRAPHICSSCENE_H #include <QtCore/qobject.h> #include <QtCore/qpoint.h> #include <QtCore/qrect.h> #include <QtGui/qbrush.h> #include <QtGui/qfont.h> #include <QtGui/qtransform.h> #include <QtGui/qmatrix.h> #include <QtGui/qpen.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW template<typename T> class QList; class QFocusEvent; class QFont; class QFontMetrics; class QGraphicsEllipseItem; class QGraphicsItem; class QGraphicsItemGroup; class QGraphicsLineItem; class QGraphicsPathItem; class QGraphicsPixmapItem; class QGraphicsPolygonItem; class QGraphicsProxyWidget; class QGraphicsRectItem; class QGraphicsSceneContextMenuEvent; class QGraphicsSceneDragDropEvent; class QGraphicsSceneEvent; class QGraphicsSceneHelpEvent; class QGraphicsSceneHoverEvent; class QGraphicsSceneMouseEvent; class QGraphicsSceneWheelEvent; class QGraphicsSimpleTextItem; class QGraphicsTextItem; class QGraphicsView; class QGraphicsWidget; class QHelpEvent; class QInputMethodEvent; class QKeyEvent; class QLineF; class QPainterPath; class QPixmap; class QPointF; class QPolygonF; class QRectF; class QSizeF; class QStyle; class QStyleOptionGraphicsItem; class QGraphicsScenePrivate; class Q_GUI_EXPORT QGraphicsScene : public QObject { Q_OBJECT Q_PROPERTY(QBrush backgroundBrush READ backgroundBrush WRITE setBackgroundBrush) Q_PROPERTY(QBrush foregroundBrush READ foregroundBrush WRITE setForegroundBrush) Q_PROPERTY(ItemIndexMethod itemIndexMethod READ itemIndexMethod WRITE setItemIndexMethod) Q_PROPERTY(QRectF sceneRect READ sceneRect WRITE setSceneRect) Q_PROPERTY(int bspTreeDepth READ bspTreeDepth WRITE setBspTreeDepth) Q_PROPERTY(QPalette palette READ palette WRITE setPalette) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(bool sortCacheEnabled READ isSortCacheEnabled WRITE setSortCacheEnabled) Q_PROPERTY(bool stickyFocus READ stickyFocus WRITE setStickyFocus) public: enum ItemIndexMethod { BspTreeIndex, NoIndex = -1 }; enum SceneLayer { ItemLayer = 0x1, BackgroundLayer = 0x2, ForegroundLayer = 0x4, AllLayers = 0xffff }; Q_DECLARE_FLAGS(SceneLayers, SceneLayer) QGraphicsScene(QObject *parent = 0); QGraphicsScene(const QRectF &sceneRect, QObject *parent = 0); QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject *parent = 0); virtual ~QGraphicsScene(); QRectF sceneRect() const; inline qreal width() const { return sceneRect().width(); } inline qreal height() const { return sceneRect().height(); } void setSceneRect(const QRectF &rect); inline void setSceneRect(qreal x, qreal y, qreal w, qreal h) { setSceneRect(QRectF(x, y, w, h)); } void render(QPainter *painter, const QRectF &target = QRectF(), const QRectF &source = QRectF(), Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio); ItemIndexMethod itemIndexMethod() const; void setItemIndexMethod(ItemIndexMethod method); bool isSortCacheEnabled() const; void setSortCacheEnabled(bool enabled); int bspTreeDepth() const; void setBspTreeDepth(int depth); QRectF itemsBoundingRect() const; QList<QGraphicsItem *> items() const; QList<QGraphicsItem *> items(const QPointF &pos) const; QList<QGraphicsItem *> items(const QRectF &rect, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const; QList<QGraphicsItem *> items(const QPolygonF &polygon, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const; QList<QGraphicsItem *> items(const QPainterPath &path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const; QList<QGraphicsItem *> collidingItems(const QGraphicsItem *item, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const; QGraphicsItem *itemAt(const QPointF &pos) const; inline QList<QGraphicsItem *> items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const { return items(QRectF(x, y, w, h), mode); } inline QGraphicsItem *itemAt(qreal x, qreal y) const { return itemAt(QPointF(x, y)); } QList<QGraphicsItem *> selectedItems() const; QPainterPath selectionArea() const; void setSelectionArea(const QPainterPath &path); void setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode); QGraphicsItemGroup *createItemGroup(const QList<QGraphicsItem *> &items); void destroyItemGroup(QGraphicsItemGroup *group); void addItem(QGraphicsItem *item); QGraphicsEllipseItem *addEllipse(const QRectF &rect, const QPen &pen = QPen(), const QBrush &brush = QBrush()); QGraphicsLineItem *addLine(const QLineF &line, const QPen &pen = QPen()); QGraphicsPathItem *addPath(const QPainterPath &path, const QPen &pen = QPen(), const QBrush &brush = QBrush()); QGraphicsPixmapItem *addPixmap(const QPixmap &pixmap); QGraphicsPolygonItem *addPolygon(const QPolygonF &polygon, const QPen &pen = QPen(), const QBrush &brush = QBrush()); QGraphicsRectItem *addRect(const QRectF &rect, const QPen &pen = QPen(), const QBrush &brush = QBrush()); QGraphicsTextItem *addText(const QString &text, const QFont &font = QFont()); QGraphicsSimpleTextItem *addSimpleText(const QString &text, const QFont &font = QFont()); QGraphicsProxyWidget *addWidget(QWidget *widget, Qt::WindowFlags wFlags = 0); inline QGraphicsEllipseItem *addEllipse(qreal x, qreal y, qreal w, qreal h, const QPen &pen = QPen(), const QBrush &brush = QBrush()) { return addEllipse(QRectF(x, y, w, h), pen, brush); } inline QGraphicsLineItem *addLine(qreal x1, qreal y1, qreal x2, qreal y2, const QPen &pen = QPen()) { return addLine(QLineF(x1, y1, x2, y2), pen); } inline QGraphicsRectItem *addRect(qreal x, qreal y, qreal w, qreal h, const QPen &pen = QPen(), const QBrush &brush = QBrush()) { return addRect(QRectF(x, y, w, h), pen, brush); } void removeItem(QGraphicsItem *item); QGraphicsItem *focusItem() const; void setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReason = Qt::OtherFocusReason); bool hasFocus() const; void setFocus(Qt::FocusReason focusReason = Qt::OtherFocusReason); void clearFocus(); void setStickyFocus(bool enabled); bool stickyFocus() const; QGraphicsItem *mouseGrabberItem() const; QBrush backgroundBrush() const; void setBackgroundBrush(const QBrush &brush); QBrush foregroundBrush() const; void setForegroundBrush(const QBrush &brush); virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const; QList <QGraphicsView *> views() const; inline void update(qreal x, qreal y, qreal w, qreal h) { update(QRectF(x, y, w, h)); } inline void invalidate(qreal x, qreal y, qreal w, qreal h, SceneLayers layers = AllLayers) { invalidate(QRectF(x, y, w, h), layers); } QStyle *style() const; void setStyle(QStyle *style); QFont font() const; void setFont(const QFont &font); QPalette palette() const; void setPalette(const QPalette &palette); QGraphicsWidget *activeWindow() const; void setActiveWindow(QGraphicsWidget *widget); public Q_SLOTS: void update(const QRectF &rect = QRectF()); void invalidate(const QRectF &rect = QRectF(), SceneLayers layers = AllLayers); void advance(); void clearSelection(); void clear(); protected: bool event(QEvent *event); bool eventFilter(QObject *watched, QEvent *event); virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); virtual void dragEnterEvent(QGraphicsSceneDragDropEvent *event); virtual void dragMoveEvent(QGraphicsSceneDragDropEvent *event); virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent *event); virtual void dropEvent(QGraphicsSceneDragDropEvent *event); virtual void focusInEvent(QFocusEvent *event); virtual void focusOutEvent(QFocusEvent *event); virtual void helpEvent(QGraphicsSceneHelpEvent *event); virtual void keyPressEvent(QKeyEvent *event); virtual void keyReleaseEvent(QKeyEvent *event); virtual void mousePressEvent(QGraphicsSceneMouseEvent *event); virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event); virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); virtual void wheelEvent(QGraphicsSceneWheelEvent *event); virtual void inputMethodEvent(QInputMethodEvent *event); virtual void drawBackground(QPainter *painter, const QRectF &rect); virtual void drawForeground(QPainter *painter, const QRectF &rect); virtual void drawItems(QPainter *painter, int numItems, QGraphicsItem *items[], const QStyleOptionGraphicsItem options[], QWidget *widget = 0); protected Q_SLOTS: bool focusNextPrevChild(bool next); Q_SIGNALS: void changed(const QList<QRectF> &region); void sceneRectChanged(const QRectF &rect); void selectionChanged(); private: void itemUpdated(QGraphicsItem *item, const QRectF &rect); Q_DECLARE_PRIVATE(QGraphicsScene) Q_DISABLE_COPY(QGraphicsScene) Q_PRIVATE_SLOT(d_func(), void _q_updateIndex()) Q_PRIVATE_SLOT(d_func(), void _q_emitUpdated()) Q_PRIVATE_SLOT(d_func(), void _q_removeItemLater(QGraphicsItem *item)) Q_PRIVATE_SLOT(d_func(), void _q_updateLater()) Q_PRIVATE_SLOT(d_func(), void _q_polishItems()) Q_PRIVATE_SLOT(d_func(), void _q_updateSortCache()) Q_PRIVATE_SLOT(d_func(), void _q_resetDirtyItems()) friend class QGraphicsItem; friend class QGraphicsItemPrivate; friend class QGraphicsView; friend class QGraphicsViewPrivate; friend class QGraphicsWidget; friend class QGraphicsWidgetPrivate; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QGraphicsScene::SceneLayers) #endif // QT_NO_GRAPHICSVIEW QT_END_NAMESPACE QT_END_HEADER #endif
[ "alon@rogue.(none)" ]
[ [ [ 1, 301 ] ] ]
785a99f6f56b8b7c32ef5504263f8caac6537e6b
b308f1edaab2be56eb66b7c03b0bf4673621b62f
/Code/CryEngine/CryCommon/CREMesh.h
b1baee95a953fe37d8cbe9d5a501f87eee0089cf
[]
no_license
blockspacer/project-o
14e95aa2692930ee90d098980a7595759a8a1f74
403ec13c10757d7d948eafe9d0a95a7f59285e90
refs/heads/master
2021-05-31T16:46:36.814786
2011-09-16T14:34:07
2011-09-16T14:34:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,961
h
#ifndef __CREOCLEAF_H__ #define __CREOCLEAF_H__ //============================================================= #define FCEF_CALCCENTER 0x10000 #define FCEF_DYNAMIC 0x20000 class CREMesh : public CRendElementBase { friend class CRenderer; public: struct CRenderChunk *m_pChunk; class CRenderMesh2 *m_pRenderMesh; // Copy of Chunk to avoid indirections int32 m_nFirstIndexId; int32 m_nNumIndices; uint16 m_nFirstVertId; uint16 m_nNumVerts; eRenderPrimitiveType m_nPrimetiveType : 8; CREMesh() { mfSetType(eDATA_Mesh); mfUpdateFlags(FCEF_TRANSFORM); m_pChunk = NULL; m_pRenderMesh = NULL; m_nPrimetiveType = (eRenderPrimitiveType)~0; m_nFirstIndexId = -1; m_nNumIndices = -1; m_nFirstVertId = 0; m_nNumVerts = 0; } virtual ~CREMesh() { } virtual struct CRenderChunk *mfGetMatInfo(); virtual PodArray<struct CRenderChunk> *mfGetMatInfoList(); virtual int mfGetMatId(); virtual bool mfPreDraw(SShaderPass *sl); virtual bool mfIsHWSkinned() { return ( m_Flags & FCEF_SKINNED ) != 0; } virtual void mfGetPlane(Plane& pl); virtual void mfPrepare(bool bCheckOverflow); virtual void mfReset(); virtual bool mfCullByClipPlane(CRenderObject *pObj); virtual void mfCenter(Vec3& Pos, CRenderObject*pObj); virtual bool mfDraw(CShader *ef, SShaderPass *sfm); virtual void *mfGetPointer(ESrcPointer ePT, int *Stride, EParamType Type, ESrcPointer Dst, int Flags); virtual float mfDistanceToCameraSquared(Matrix34& matInst); virtual bool mfUpdate(EVertexFormat eVertFormat, int Flags); virtual void mfGetBBox(Vec3& vMins, Vec3& vMaxs); virtual void mfPrecache(const SShaderItem& SH); virtual int Size() { int nSize = sizeof(*this); return nSize; } virtual void GetMemoryUsage(ICrySizer *pSizer) const { pSizer->AddObject(this, sizeof(*this)); } }; #endif // __CREOCLEAF_H__
[ [ [ 1, 72 ] ] ]
da8560e0b4b4fa123da08031902083f6e8ab4572
847cccd728e768dc801d541a2d1169ef562311cd
/src/Utils/Properties/PropertyList.h
fb17bbc193790acca82da735ffecb13f62d16ac4
[]
no_license
aadarshasubedi/Ocerus
1bea105de9c78b741f3de445601f7dee07987b96
4920b99a89f52f991125c9ecfa7353925ea9603c
refs/heads/master
2021-01-17T17:50:00.472657
2011-03-25T13:26:12
2011-03-25T13:26:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
464
h
/// @file /// A list for storing properties in their PropertyHolder. #ifndef PropertyList_h__ #define PropertyList_h__ #include "Base.h" namespace Reflection { /// A list for storing properties in their PropertyHolder. /// This trick had to be done to avoid circular include dependencies (I can forward declare this class, /// but not the typedef). class PropertyList : public list<PropertyHolder> { }; } #endif // PropertyList_h__
[ [ [ 1, 21 ] ] ]
ec4bab0f8e70c5e4eac8bf0c58108a2ad134ab61
5e61787e7adba6ed1c2b5e40d38098ebdf9bdee8
/sans/models/c_models/CCoreShellCylinderModel.cpp
8d1b33febcd4db4b8f3d4fe7f6638199d69a81dc
[]
no_license
mcvine/sansmodels
4dcba43d18c930488b0e69e8afb04139e89e7b21
618928810ee7ae58ec35bbb839eba2a0117c4611
refs/heads/master
2021-01-22T13:12:22.721492
2011-09-30T14:01:06
2011-09-30T14:01:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,855
cpp
/** This software was developed by the University of Tennessee as part of the Distributed Data Analysis of Neutron Scattering Experiments (DANSE) project funded by the US National Science Foundation. If you use DANSE applications to do scientific research that leads to publication, we ask that you acknowledge the use of the software with the following sentence: "This work benefited from DANSE software developed under NSF award DMR-0520547." copyright 2008, University of Tennessee */ /** CCoreShellCylinderModel * * C extension * * WARNING: THIS FILE WAS GENERATED BY WRAPPERGENERATOR.PY * DO NOT MODIFY THIS FILE, MODIFY core_shell_cylinder.h * AND RE-RUN THE GENERATOR SCRIPT * */ #define NO_IMPORT_ARRAY #define PY_ARRAY_UNIQUE_SYMBOL PyArray_API_sans extern "C" { #include <Python.h> #include <arrayobject.h> #include "structmember.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "core_shell_cylinder.h" } #include "models.hh" #include "dispersion_visitor.hh" /// Error object for raised exceptions static PyObject * CCoreShellCylinderModelError = NULL; // Class definition typedef struct { PyObject_HEAD /// Parameters PyObject * params; /// Dispersion parameters PyObject * dispersion; /// Underlying model object CoreShellCylinderModel * model; /// Log for unit testing PyObject * log; } CCoreShellCylinderModel; static void CCoreShellCylinderModel_dealloc(CCoreShellCylinderModel* self) { Py_DECREF(self->params); Py_DECREF(self->dispersion); Py_DECREF(self->log); delete self->model; self->ob_type->tp_free((PyObject*)self); } static PyObject * CCoreShellCylinderModel_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { CCoreShellCylinderModel *self; self = (CCoreShellCylinderModel *)type->tp_alloc(type, 0); return (PyObject *)self; } static int CCoreShellCylinderModel_init(CCoreShellCylinderModel *self, PyObject *args, PyObject *kwds) { if (self != NULL) { // Create parameters self->params = PyDict_New(); self->dispersion = PyDict_New(); self->model = new CoreShellCylinderModel(); // Initialize parameter dictionary PyDict_SetItemString(self->params,"scale",Py_BuildValue("d",1.000000000000)); PyDict_SetItemString(self->params,"axis_theta",Py_BuildValue("d",90.000000000000)); PyDict_SetItemString(self->params,"solvent_sld",Py_BuildValue("d",0.000001000000)); PyDict_SetItemString(self->params,"thickness",Py_BuildValue("d",10.000000000000)); PyDict_SetItemString(self->params,"axis_phi",Py_BuildValue("d",0.000000000000)); PyDict_SetItemString(self->params,"length",Py_BuildValue("d",400.000000000000)); PyDict_SetItemString(self->params,"core_sld",Py_BuildValue("d",0.000001000000)); PyDict_SetItemString(self->params,"radius",Py_BuildValue("d",20.000000000000)); PyDict_SetItemString(self->params,"background",Py_BuildValue("d",0.000000000000)); PyDict_SetItemString(self->params,"shell_sld",Py_BuildValue("d",0.000004000000)); // Initialize dispersion / averaging parameter dict DispersionVisitor* visitor = new DispersionVisitor(); PyObject * disp_dict; disp_dict = PyDict_New(); self->model->radius.dispersion->accept_as_source(visitor, self->model->radius.dispersion, disp_dict); PyDict_SetItemString(self->dispersion, "radius", disp_dict); disp_dict = PyDict_New(); self->model->thickness.dispersion->accept_as_source(visitor, self->model->thickness.dispersion, disp_dict); PyDict_SetItemString(self->dispersion, "thickness", disp_dict); disp_dict = PyDict_New(); self->model->length.dispersion->accept_as_source(visitor, self->model->length.dispersion, disp_dict); PyDict_SetItemString(self->dispersion, "length", disp_dict); disp_dict = PyDict_New(); self->model->axis_theta.dispersion->accept_as_source(visitor, self->model->axis_theta.dispersion, disp_dict); PyDict_SetItemString(self->dispersion, "axis_theta", disp_dict); disp_dict = PyDict_New(); self->model->axis_phi.dispersion->accept_as_source(visitor, self->model->axis_phi.dispersion, disp_dict); PyDict_SetItemString(self->dispersion, "axis_phi", disp_dict); // Create empty log self->log = PyDict_New(); } return 0; } static PyMemberDef CCoreShellCylinderModel_members[] = { {"params", T_OBJECT, offsetof(CCoreShellCylinderModel, params), 0, "Parameters"}, {"dispersion", T_OBJECT, offsetof(CCoreShellCylinderModel, dispersion), 0, "Dispersion parameters"}, {"log", T_OBJECT, offsetof(CCoreShellCylinderModel, log), 0, "Log"}, {NULL} /* Sentinel */ }; /** Read double from PyObject @param p PyObject @return double */ double CCoreShellCylinderModel_readDouble(PyObject *p) { if (PyFloat_Check(p)==1) { return (double)(((PyFloatObject *)(p))->ob_fval); } else if (PyInt_Check(p)==1) { return (double)(((PyIntObject *)(p))->ob_ival); } else if (PyLong_Check(p)==1) { return (double)PyLong_AsLong(p); } else { return 0.0; } } /** * Function to call to evaluate model * @param args: input numpy array q[] * @return: numpy array object */ static PyObject *evaluateOneDim(CoreShellCylinderModel* model, PyArrayObject *q){ PyArrayObject *result; // Check validity of array q , q must be of dimension 1, an array of double if (q->nd != 1 || q->descr->type_num != PyArray_DOUBLE) { //const char * message= "Invalid array: q->nd=%d,type_num=%d\n",q->nd,q->descr->type_num; //PyErr_SetString(PyExc_ValueError , message); return NULL; } result = (PyArrayObject *)PyArray_FromDims(q->nd, (int *)(q->dimensions), PyArray_DOUBLE); if (result == NULL) { const char * message= "Could not create result "; PyErr_SetString(PyExc_RuntimeError , message); return NULL; } for (int i = 0; i < q->dimensions[0]; i++){ double q_value = *(double *)(q->data + i*q->strides[0]); double *result_value = (double *)(result->data + i*result->strides[0]); *result_value =(*model)(q_value); } return PyArray_Return(result); } /** * Function to call to evaluate model * @param args: input numpy array [x[],y[]] * @return: numpy array object */ static PyObject * evaluateTwoDimXY( CoreShellCylinderModel* model, PyArrayObject *x, PyArrayObject *y) { PyArrayObject *result; int i,j, x_len, y_len, dims[1]; //check validity of input vectors if (x->nd != 1 || x->descr->type_num != PyArray_DOUBLE || y->nd != 1 || y->descr->type_num != PyArray_DOUBLE || y->dimensions[0] != x->dimensions[0]){ const char * message= "evaluateTwoDimXY expect 2 numpy arrays"; PyErr_SetString(PyExc_ValueError , message); return NULL; } if (PyArray_Check(x) && PyArray_Check(y)) { x_len = dims[0]= x->dimensions[0]; y_len = dims[0]= y->dimensions[0]; // Make a new double matrix of same dims result=(PyArrayObject *) PyArray_FromDims(1,dims,NPY_DOUBLE); if (result == NULL){ const char * message= "Could not create result "; PyErr_SetString(PyExc_RuntimeError , message); return NULL; } /* Do the calculation. */ for ( i=0; i< x_len; i++) { double x_value = *(double *)(x->data + i*x->strides[0]); double y_value = *(double *)(y->data + i*y->strides[0]); double *result_value = (double *)(result->data + i*result->strides[0]); *result_value = (*model)(x_value, y_value); } return PyArray_Return(result); }else{ PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.evaluateTwoDimXY couldn't run."); return NULL; } } /** * evalDistribution function evaluate a model function with input vector * @param args: input q as vector or [qx, qy] where qx, qy are vectors * */ static PyObject * evalDistribution(CCoreShellCylinderModel *self, PyObject *args){ PyObject *qx, *qy; PyArrayObject * pars; int npars ,mpars; // Get parameters // Reader parameter dictionary self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") ); self->model->axis_theta = PyFloat_AsDouble( PyDict_GetItemString(self->params, "axis_theta") ); self->model->solvent_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "solvent_sld") ); self->model->thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thickness") ); self->model->axis_phi = PyFloat_AsDouble( PyDict_GetItemString(self->params, "axis_phi") ); self->model->length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "length") ); self->model->core_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_sld") ); self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") ); self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") ); self->model->shell_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "shell_sld") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "radius"); self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thickness"); self->model->thickness.dispersion->accept_as_destination(visitor, self->model->thickness.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "length"); self->model->length.dispersion->accept_as_destination(visitor, self->model->length.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "axis_theta"); self->model->axis_theta.dispersion->accept_as_destination(visitor, self->model->axis_theta.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "axis_phi"); self->model->axis_phi.dispersion->accept_as_destination(visitor, self->model->axis_phi.dispersion, disp_dict); // Get input and determine whether we have to supply a 1D or 2D return value. if ( !PyArg_ParseTuple(args,"O",&pars) ) { PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.evalDistribution expects a q value."); return NULL; } // Check params if(PyArray_Check(pars)==1) { // Length of list should 1 or 2 npars = pars->nd; if(npars==1) { // input is a numpy array if (PyArray_Check(pars)) { return evaluateOneDim(self->model, (PyArrayObject*)pars); } }else{ PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.evalDistribution expect numpy array of one dimension."); return NULL; } }else if( PyList_Check(pars)==1) { // Length of list should be 2 for I(qx,qy) mpars = PyList_GET_SIZE(pars); if(mpars!=2) { PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.evalDistribution expects a list of dimension 2."); return NULL; } qx = PyList_GET_ITEM(pars,0); qy = PyList_GET_ITEM(pars,1); if (PyArray_Check(qx) && PyArray_Check(qy)) { return evaluateTwoDimXY(self->model, (PyArrayObject*)qx, (PyArrayObject*)qy); }else{ PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.evalDistribution expect 2 numpy arrays in list."); return NULL; } } PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.evalDistribution couln't be run."); return NULL; } /** * Function to call to evaluate model * @param args: input q or [q,phi] * @return: function value */ static PyObject * run(CCoreShellCylinderModel *self, PyObject *args) { double q_value, phi_value; PyObject* pars; int npars; // Get parameters // Reader parameter dictionary self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") ); self->model->axis_theta = PyFloat_AsDouble( PyDict_GetItemString(self->params, "axis_theta") ); self->model->solvent_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "solvent_sld") ); self->model->thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thickness") ); self->model->axis_phi = PyFloat_AsDouble( PyDict_GetItemString(self->params, "axis_phi") ); self->model->length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "length") ); self->model->core_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_sld") ); self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") ); self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") ); self->model->shell_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "shell_sld") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "radius"); self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thickness"); self->model->thickness.dispersion->accept_as_destination(visitor, self->model->thickness.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "length"); self->model->length.dispersion->accept_as_destination(visitor, self->model->length.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "axis_theta"); self->model->axis_theta.dispersion->accept_as_destination(visitor, self->model->axis_theta.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "axis_phi"); self->model->axis_phi.dispersion->accept_as_destination(visitor, self->model->axis_phi.dispersion, disp_dict); // Get input and determine whether we have to supply a 1D or 2D return value. if ( !PyArg_ParseTuple(args,"O",&pars) ) { PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.run expects a q value."); return NULL; } // Check params if( PyList_Check(pars)==1) { // Length of list should be 2 for I(q,phi) npars = PyList_GET_SIZE(pars); if(npars!=2) { PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.run expects a double or a list of dimension 2."); return NULL; } // We have a vector q, get the q and phi values at which // to evaluate I(q,phi) q_value = CCoreShellCylinderModel_readDouble(PyList_GET_ITEM(pars,0)); phi_value = CCoreShellCylinderModel_readDouble(PyList_GET_ITEM(pars,1)); // Skip zero if (q_value==0) { return Py_BuildValue("d",0.0); } return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value)); } else { // We have a scalar q, we will evaluate I(q) q_value = CCoreShellCylinderModel_readDouble(pars); return Py_BuildValue("d",(*(self->model))(q_value)); } } /** * Function to call to calculate_ER * @return: effective radius value */ static PyObject * calculate_ER(CCoreShellCylinderModel *self) { PyObject* pars; int npars; // Get parameters // Reader parameter dictionary self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") ); self->model->axis_theta = PyFloat_AsDouble( PyDict_GetItemString(self->params, "axis_theta") ); self->model->solvent_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "solvent_sld") ); self->model->thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thickness") ); self->model->axis_phi = PyFloat_AsDouble( PyDict_GetItemString(self->params, "axis_phi") ); self->model->length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "length") ); self->model->core_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_sld") ); self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") ); self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") ); self->model->shell_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "shell_sld") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "radius"); self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thickness"); self->model->thickness.dispersion->accept_as_destination(visitor, self->model->thickness.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "length"); self->model->length.dispersion->accept_as_destination(visitor, self->model->length.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "axis_theta"); self->model->axis_theta.dispersion->accept_as_destination(visitor, self->model->axis_theta.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "axis_phi"); self->model->axis_phi.dispersion->accept_as_destination(visitor, self->model->axis_phi.dispersion, disp_dict); return Py_BuildValue("d",(*(self->model)).calculate_ER()); } /** * Function to call to evaluate model in cartesian coordinates * @param args: input q or [qx, qy]] * @return: function value */ static PyObject * runXY(CCoreShellCylinderModel *self, PyObject *args) { double qx_value, qy_value; PyObject* pars; int npars; // Get parameters // Reader parameter dictionary self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") ); self->model->axis_theta = PyFloat_AsDouble( PyDict_GetItemString(self->params, "axis_theta") ); self->model->solvent_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "solvent_sld") ); self->model->thickness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thickness") ); self->model->axis_phi = PyFloat_AsDouble( PyDict_GetItemString(self->params, "axis_phi") ); self->model->length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "length") ); self->model->core_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "core_sld") ); self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") ); self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") ); self->model->shell_sld = PyFloat_AsDouble( PyDict_GetItemString(self->params, "shell_sld") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "radius"); self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thickness"); self->model->thickness.dispersion->accept_as_destination(visitor, self->model->thickness.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "length"); self->model->length.dispersion->accept_as_destination(visitor, self->model->length.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "axis_theta"); self->model->axis_theta.dispersion->accept_as_destination(visitor, self->model->axis_theta.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "axis_phi"); self->model->axis_phi.dispersion->accept_as_destination(visitor, self->model->axis_phi.dispersion, disp_dict); // Get input and determine whether we have to supply a 1D or 2D return value. if ( !PyArg_ParseTuple(args,"O",&pars) ) { PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.run expects a q value."); return NULL; } // Check params if( PyList_Check(pars)==1) { // Length of list should be 2 for I(qx, qy)) npars = PyList_GET_SIZE(pars); if(npars!=2) { PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.run expects a double or a list of dimension 2."); return NULL; } // We have a vector q, get the qx and qy values at which // to evaluate I(qx,qy) qx_value = CCoreShellCylinderModel_readDouble(PyList_GET_ITEM(pars,0)); qy_value = CCoreShellCylinderModel_readDouble(PyList_GET_ITEM(pars,1)); return Py_BuildValue("d",(*(self->model))(qx_value,qy_value)); } else { // We have a scalar q, we will evaluate I(q) qx_value = CCoreShellCylinderModel_readDouble(pars); return Py_BuildValue("d",(*(self->model))(qx_value)); } } static PyObject * reset(CCoreShellCylinderModel *self, PyObject *args) { return Py_BuildValue("d",0.0); } static PyObject * set_dispersion(CCoreShellCylinderModel *self, PyObject *args) { PyObject * disp; const char * par_name; if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) { PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.set_dispersion expects a DispersionModel object."); return NULL; } void *temp = PyCObject_AsVoidPtr(disp); DispersionModel * dispersion = static_cast<DispersionModel *>(temp); // Ugliness necessary to go from python to C // TODO: refactor this if (!strcmp(par_name, "radius")) { self->model->radius.dispersion = dispersion; } else if (!strcmp(par_name, "thickness")) { self->model->thickness.dispersion = dispersion; } else if (!strcmp(par_name, "length")) { self->model->length.dispersion = dispersion; } else if (!strcmp(par_name, "axis_theta")) { self->model->axis_theta.dispersion = dispersion; } else if (!strcmp(par_name, "axis_phi")) { self->model->axis_phi.dispersion = dispersion; } else { PyErr_SetString(CCoreShellCylinderModelError, "CCoreShellCylinderModel.set_dispersion expects a valid parameter name."); return NULL; } DispersionVisitor* visitor = new DispersionVisitor(); PyObject * disp_dict = PyDict_New(); dispersion->accept_as_source(visitor, dispersion, disp_dict); PyDict_SetItemString(self->dispersion, par_name, disp_dict); return Py_BuildValue("i",1); } static PyMethodDef CCoreShellCylinderModel_methods[] = { {"run", (PyCFunction)run , METH_VARARGS, "Evaluate the model at a given Q or Q, phi"}, {"runXY", (PyCFunction)runXY , METH_VARARGS, "Evaluate the model at a given Q or Qx, Qy"}, {"calculate_ER", (PyCFunction)calculate_ER , METH_VARARGS, "Evaluate the model at a given Q or Q, phi"}, {"evalDistribution", (PyCFunction)evalDistribution , METH_VARARGS, "Evaluate the model at a given Q or Qx, Qy vector "}, {"reset", (PyCFunction)reset , METH_VARARGS, "Reset pair correlation"}, {"set_dispersion", (PyCFunction)set_dispersion , METH_VARARGS, "Set the dispersion model for a given parameter"}, {NULL} }; static PyTypeObject CCoreShellCylinderModelType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "CCoreShellCylinderModel", /*tp_name*/ sizeof(CCoreShellCylinderModel), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)CCoreShellCylinderModel_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "CCoreShellCylinderModel objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ CCoreShellCylinderModel_methods, /* tp_methods */ CCoreShellCylinderModel_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)CCoreShellCylinderModel_init, /* tp_init */ 0, /* tp_alloc */ CCoreShellCylinderModel_new, /* tp_new */ }; //static PyMethodDef module_methods[] = { // {NULL} //}; /** * Function used to add the model class to a module * @param module: module to add the class to */ void addCCoreShellCylinderModel(PyObject *module) { PyObject *d; if (PyType_Ready(&CCoreShellCylinderModelType) < 0) return; Py_INCREF(&CCoreShellCylinderModelType); PyModule_AddObject(module, "CCoreShellCylinderModel", (PyObject *)&CCoreShellCylinderModelType); d = PyModule_GetDict(module); CCoreShellCylinderModelError = PyErr_NewException("CCoreShellCylinderModel.error", NULL, NULL); PyDict_SetItemString(d, "CCoreShellCylinderModelError", CCoreShellCylinderModelError); }
[ [ [ 1, 23 ], [ 26, 28 ], [ 30, 61 ], [ 66, 91 ], [ 102, 156 ], [ 187, 187 ], [ 320, 393 ], [ 429, 429 ], [ 434, 553 ], [ 559, 608 ], [ 612, 630 ] ], [ [ 24, 25 ], [ 29, 29 ], [ 92, 101 ], [ 157, 186 ], [ 188, 207 ], [ 209, 209 ], [ 211, 314 ], [ 319, 319 ], [ 394, 428 ], [ 430, 433 ], [ 554, 558 ], [ 609, 611 ] ], [ [ 62, 65 ], [ 208, 208 ], [ 210, 210 ], [ 315, 318 ] ] ]
8b6f6335988bd3072df40327ca0af482f929cefc
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/multi_index/detail/rnd_index_ptr_array.hpp
a5c476f4cc5a57fac05b55babad358c454c39761
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
ISO-8859-1
C++
false
false
2,870
hpp
/* Copyright 2003-2005 Joaquín M López Muñoz. * 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. */ #ifndef BOOST_MULTI_INDEX_DETAIL_RND_INDEX_PTR_ARRAY_HPP #define BOOST_MULTI_INDEX_DETAIL_RND_INDEX_PTR_ARRAY_HPP #if defined(_MSC_VER)&&(_MSC_VER>=1200) #pragma once #endif #include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */ #include <algorithm> #include <boost/multi_index/detail/auto_space.hpp> #include <boost/multi_index/detail/rnd_index_node.hpp> #include <boost/noncopyable.hpp> #include <cstddef> namespace boost{ namespace multi_index{ namespace detail{ /* pointer structure for use by random access indices */ template<typename Allocator> class random_access_index_ptr_array:private noncopyable { public: typedef random_access_index_node_impl* value_type; random_access_index_ptr_array( const Allocator& al,value_type end_,std::size_t size): size_(size), capacity_(size), spc(al,capacity_+1) { *end()=end_; end_->up()=end(); } std::size_t size()const{return size_;} std::size_t capacity()const{return capacity_;} void room_for_one() { if(size_==capacity_){ reserve(capacity_<=10?15:capacity_+capacity_/2); } } void reserve(std::size_t c) { if(c>capacity_){ auto_space<value_type,Allocator> spc1(spc.get_allocator(),c+1); random_access_index_node_impl::transfer(begin(),end()+1,spc1.data()); spc.swap(spc1); capacity_=c; } } value_type* begin()const{return &ptrs()[0];} value_type* end()const{return &ptrs()[size_];} value_type* at(std::size_t n)const{return &ptrs()[n];} void push_back(value_type x) { *(end()+1)=*end(); (*(end()+1))->up()=end()+1; *end()=x; (*end())->up()=end(); ++size_; } void erase(value_type x) { random_access_index_node_impl::extract(x->up(),end()+1); --size_; } void clear() { *begin()=*end(); (*begin())->up()=begin(); size_=0; } void swap(random_access_index_ptr_array& x) { std::swap(size_,x.size_); std::swap(capacity_,x.capacity_); spc.swap(x.spc); } private: std::size_t size_; std::size_t capacity_; auto_space<value_type,Allocator> spc; value_type* ptrs()const { return spc.data(); } }; template<typename Allocator> void swap( random_access_index_ptr_array<Allocator>& x, random_access_index_ptr_array<Allocator>& y) { x.swap(y); } } /* namespace multi_index::detail */ } /* namespace multi_index */ } /* namespace boost */ #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 125 ] ] ]
fa3c0a9950760862ed79cc32d67b664f5d86ab25
7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3
/src/MainFrame_OpenFile.cpp
9c568024281b39b93e268bf7e32f0552cd3b77c7
[]
no_license
plus7/DonutG
b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6
2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b
refs/heads/master
2020-06-01T15:30:31.747022
2010-08-21T18:51:01
2010-08-21T18:51:01
767,753
1
2
null
null
null
null
SHIFT_JIS
C++
false
false
22,424
cpp
/** * @file MainFrame_OpenFile.cpp * @brief CMainFrame の ファイルを開ける関係の処理. * @note * +++ MainFrame.cpp から分離. */ #include "stdafx.h" #include "MainFrame.h" #include "dialog/OpenURLDialog.h" #include "DonutScriptLoader.h" #if defined USE_ATLDBGMEM #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif bool CMainFrame::OnDDEOpenFile(const CString &strFileName) { //dmfTRACE(_T("CMainFrame::OnDDEOpenFile(%s)\n"), strFileName); #if 1 //+++ トレイ状態からの復帰でのバグ対策. IfTrayRestoreWindow(); //+++ トレイ状態だったら復活. DWORD flags = DonutGetStdOpenFlag(); OnUserOpenFile( strFileName, flags ); if (CStartUpOption::s_dwActivate) { MtlSetForegroundWindow(m_hWnd); } #else OnUserOpenFile( strFileName, DonutGetStdOpenFlag() ); if (CStartUpOption::s_dwActivate) { //+++ OnUserOpenFile()の時点で最大化/フルスクリーンだった場合の対策でnCmdShowを渡して考慮するように変更. MtlSetForegroundWindow(m_hWnd, m_OnUserOpenFile_nCmdShow); //+++ 実はこのnCmdShowは意味が違うものを持ってきてるような気がする...があとまわし. } #endif // UDT DGSTR ( added by dai return true; } //public: // Message handlers // alternates OpenFile #if 1 //+++ url別拡張プロパティの処理を追加 HWND CMainFrame::OnUserOpenFile(const CString& strUrl, DWORD dwOpenFlag) { #if 0 //+++ CChildFrame::OnBeforeNavigate2側で処理するように変更したので、これでok ...としたい... return UserOpenFile(strUrl, dwOpenFlag); #else //+++ CChildFrame::OnBeforeNavigate2側で処理するようにしたので、2重に検索がかかってしまうが、 //+++ オプション反映のタイミングの都合なるべく早くフラグを設定したほうがよさそうなので、速度犠牲にするなら、こちら CString str(strUrl); MtlRemoveStringHeaderAndFooter(str); #if 0 //+++ 仕様と思ったが、.url側の拡張プロパティの件があるので、ここではできない if ( MtlIsExt( str, _T(".url") ) ) { if (MTL::ParseInternetShortcutFile(str) == 0) return NULL; } #endif CString dotJS = str.Right(3); if(dotJS.CompareNoCase(_T(".js")) == 0){ nsCOMPtr<donutIScriptLoader> loader = do_GetService("@tnose.net/donut/loader-service;1"); nsCOMPtr<nsILocalFile> scriptFile; NS_NewLocalFile(nsEmbedString(str), PR_FALSE, getter_AddRefs(scriptFile)); nsresult rv = loader->LoadFile(scriptFile); return NULL; } DWORD dwExProp = 0xFFFFFFFF; DWORD dwExProp2 = 8; if ( (_check_flag(D_OPENFILE_NOCREATE, dwOpenFlag) == 0 || CUrlSecurityOption::activePageToo()) && CUrlSecurityOption::FindUrl(str, &dwExProp, &dwExProp2, 0) ) { return OpenUrlWithExProp(str, dwOpenFlag, dwExProp, dwExProp2); } else { return UserOpenFile(str, dwOpenFlag); } #endif } #endif //+++ url別拡張プロパティ対応で、本来のOnUserOpenFileをUserOpenFileに変名. 引数を末に追加. HWND CMainFrame::UserOpenFile(const CString& strFile0, DWORD openFlag, int dlCtrlFlag, int extededStyleFlags) { CString strFile (strFile0); MtlRemoveStringHeaderAndFooter(strFile); if ( MtlIsExt( strFile, _T(".url") ) ) { //+++ メモ:urlのときの処理. 拡張プロパティの取得とかあるので、専用のopen処理へ... return OpenInternetShortcut(strFile, openFlag); } if ( !MtlIsProtocol( strFile, _T("http") ) && !MtlIsProtocol( strFile, _T("https") ) ) { if ( MtlPreOpenFile(strFile) ) return NULL; // handled #if 1 //+++ タブがあるとき if (m_MDITab.GetItemCount() > 0) { if (strFile.Find(':') < 0 && strFile.Left(1) != _T("/") && strFile.Left(1) != _T("\\")) { // すでに具体的なパスでないとき、 HWND hWndChild = m_MDITab.GetTabHwnd(m_MDITab.GetCurSel()); CChildFrame* pChild = GetChildFrame(hWndChild); if (pChild) { //+++ アクティブページをみて CString strBase = pChild->GetLocationURL(); CString str7 = strBase.Left(7); if (str7 == "file://") { //+++ file://だったらば、ローカルでのディレクトリ移動だろうとみなして strFile = Misc::MakeFullPath( strBase, strFile ); //+++ フルパス化 } } } } #endif } if (strFile.GetLength() > INTERNET_MAX_PATH_LENGTH) return NULL; // UH (JavaScript dont create window) CString strJava = strFile.Left(11); strJava.MakeLower(); if ( strJava == _T("javascript:") ) { if ( strFile == _T("javascript:location.reload()") ) return NULL; openFlag |= D_OPENFILE_NOCREATE; } // dfg files if ( MtlIsExt( strFile, _T(".dfg") ) ) { if ( !(CMainOption::s_dwMainExtendedStyle & MAIN_EX_NOCLOSEDFG) ) _LoadGroupOption(strFile, true); else _LoadGroupOption(strFile, false); return NULL; } #ifndef USE_DIET //+++ サイタマ封印(about:blankの不具合修正で誤ってコメントアウト... //+++ だったがunDonut+より、ちゃんと機能していないようだし?、わざわざ復活する必要もないかな、と) //+++ ちょっと気が変わったので条件付の暫定復活 // minit(about:* pages) { CString strAbout = strFile.Left(6); if ( strAbout == _T("about:") && strFile != _T("about:blank") ) { HWND hWndAbout = _OpenAboutFile(strFile); if (hWndAbout) return hWndAbout; } } #endif HWND hWndActive = MDIGetActive(); int nCmdShow = _check_flag(D_OPENFILE_ACTIVATE, openFlag) ? -1 : SW_SHOWNOACTIVATE; if (hWndActive == NULL) { // no window yet nCmdShow = -1; // always default } if ( hWndActive != NULL && _check_flag(D_OPENFILE_NOCREATE, openFlag) ) { CGeckoBrowser browser = DonutGetNsIWebBrowser(hWndActive); if ( !browser.IsBrowserNull() ) { browser.Navigate2(strFile); if ( !_check_flag(D_OPENFILE_NOSETFOCUS, openFlag) ) { // reset focus ::SetFocus(NULL); MtlSendCommand(hWndActive, ID_VIEW_SETFOCUS); } return NULL; //return hWndActive; } } //+++ //x if (CMainOption::s_dwMainExtendedStyle & (/*MAIN_EX_NOACTIVATE_NEWWIN|*/MAIN_EX_NEWWINDOW)) { //+++ if (dlCtrlFlag < 0) //+++ dlCtrlFlag = CDLControlOption::s_dwDLControlFlags; CChildFrame* pChild = CChildFrame::NewWindow(m_hWndMDIClient, m_MDITab, m_AddressBar, false/*true*/, dlCtrlFlag, extededStyleFlags); if (pChild == NULL) return NULL; if ( !strFile.IsEmpty() ) { m_OnUserOpenFile_nCmdShow = pChild->ActivateFrame(nCmdShow); pChild->Navigate2(strFile); pChild->ForceMessageLoop(); //+++ 無理やり、この場でメッセージをさばく. もう不要のはずだが、あっても問題ないのなら、念のため残しておく... } else { m_OnUserOpenFile_nCmdShow = pChild->ActivateFrame(nCmdShow); } if ( !_check_flag(D_OPENFILE_NOSETFOCUS, openFlag) ) { if (MDIGetActive() == pChild->m_hWnd) { // a new window activated, so automatically set focus // reset focus ::SetFocus(NULL); MtlSendCommand(pChild->m_hWnd, ID_VIEW_SETFOCUS); } else { // It's reasonable not to touch a current focus. } } return pChild->m_hWnd; } } LRESULT CMainFrame::OnOpenWithExProp(_EXPROP_ARGS *pArgs) { if (!pArgs) return 0; HWND hWndNew = OpenUrlWithExProp(pArgs->strUrl, pArgs->dwOpenFlag, pArgs->strIniFile, pArgs->strSection); if (!hWndNew) hWndNew = MDIGetActive(); CChildFrame *pChild = GetChildFrame(hWndNew); if (pChild) { // 検索オプションを取得 DWORD dwStatus; { CIniFileI pr( g_szIniFileName, _T("Search") ); dwStatus = pr.GetValue( _T("Status"), 0 ); } CString str = pArgs->strSearchWord; // 「全角を半角に置換」がチェックされてたら変換して子ウィンドウに文字列を渡す。 if (dwStatus & STS_TEXT_FILTER) m_SearchBar.FilterString(str); //+++ 子窓に検索設定を反映 (関数化) #if 1 //defined USE_UNDONUT_G_SRC if (dwStatus & STS_AUTOHILIGHT) pChild->SetSearchWordAutoHilight( str, 1 ); #else pChild->SetSearchWordAutoHilight( str, (dwStatus & STS_AUTOHILIGHT) != 0 ); #endif } return (LRESULT) hWndNew; } HWND CMainFrame::OpenInternetShortcut(CString strUrlFile, DWORD dwOpenFlag) { CString strUrl = strUrlFile; if ( !MTL::ParseInternetShortcutFile(strUrl) ) return NULL; return OpenUrlWithExProp(strUrl, dwOpenFlag, strUrlFile); } HWND CMainFrame::OpenUrlWithExProp(CString strUrl, DWORD dwOpenFlag, DWORD dwExProp, DWORD dwExProp2) { if ( _check_flag(D_OPENFILE_NOCREATE, dwOpenFlag) ) { return OpenExPropertyActive(strUrl, dwExProp, dwExProp2, dwOpenFlag); //既存のタブで開く } else { return OpenExPropertyNew(strUrl, dwExProp, dwExProp2, dwOpenFlag); //新規に開く } } HWND CMainFrame::OpenUrlWithExProp(CString strUrl, DWORD dwOpenFlag, CString strIniFile, CString strSection /*= DONUT_SECTION*/) { DWORD dwExProp = 0xAAAAAA; //+++ 初期値変更 DWORD dwExProp2= 0x8; //+++ 拡張プロパティを増設. if ( CExProperty::CheckExPropertyFlag(dwExProp, dwExProp2, strIniFile, strSection) ) { if ( _check_flag(D_OPENFILE_NOCREATE, dwOpenFlag) ) { return OpenExPropertyActive(strUrl, dwExProp, dwExProp2, dwOpenFlag); //既存のタブで開く } else { return OpenExPropertyNew(strUrl, dwExProp, dwExProp2, dwOpenFlag); //新規に開く } } else { #if 1 //+++ URL別拡張プロパティのチェック&処理. // ...だったが、CChildFrame::OnBeforeNavigate2側で処理するように変更したので、ここはなし // ...にしたかったっが、どうも、dlオプション反映のタイミングにラグがあるようなんで、 // なるべく早く反映されるように、速度犠牲で反映. if ( (_check_flag(D_OPENFILE_NOCREATE, dwOpenFlag) == 0 || CUrlSecurityOption::activePageToo()) && CUrlSecurityOption::FindUrl(strUrl, &dwExProp, &dwExProp2, 0) ) { return OpenUrlWithExProp(strUrl, dwOpenFlag, dwExProp, dwExProp2); } #endif return OpenExPropertyNot(strUrl, dwOpenFlag); //標準オプションで開く } } //既存タブにナビゲートしたのちに拡張設定を適用する. //+++ dwExProp2増設. HWND CMainFrame::OpenExPropertyActive(CString &strUrl, DWORD dwExProp, DWORD dwExProp2, DWORD dwOpenFlag) { dwOpenFlag |= D_OPENFILE_NOCREATE; //アクティブなタブがナビゲートロックされているかを確認 HWND hWndActive = MDIGetActive(); if ( hWndActive && ::IsWindow(hWndActive) ) { CChildFrame *pChild = GetChildFrame(hWndActive); if (pChild) { DWORD dwExFlag = pChild->view().m_ViewOption.m_dwExStyle; if (dwExFlag & DVS_EX_OPENNEWWIN) return OpenExPropertyNew(strUrl, dwExProp, dwExProp2, dwOpenFlag); } } //+++ (dwExProp2増設でUserOpenFileの後にあったのを前に移動.) CExProperty ExProp(CDLControlOption::s_dwDLControlFlags, CDLControlOption::s_dwExtendedStyleFlags, 0, dwExProp, dwExProp2); //取得したURLをアクティブなタブで開かせる(標準処理に任せる) BOOL bOpened = FALSE; HWND hWndNew = UserOpenFile(strUrl, dwOpenFlag, ExProp.GetDLControlFlags(), ExProp.GetExtendedStyleFlags() ); if (hWndNew && !hWndActive) { hWndActive = hWndNew; //ウィンドウが無かったので新規に開いた bOpened = TRUE; } //拡張プロパティを適用する if (hWndActive == NULL) return NULL; CChildFrame* pChild = GetChildFrame(hWndActive); if (!pChild) return NULL; pChild->view().PutDLControlFlags( ExProp.GetDLControlFlags() ); pChild->SetViewExStyle(ExProp.GetExtendedStyleFlags(), TRUE); pChild->view().m_ViewOption.SetAutoRefreshStyle( ExProp.GetAutoRefreshFlag() ); if (bOpened) return hWndActive; return NULL; } //新規タブを開いたのち拡張設定を適用する HWND CMainFrame::OpenExPropertyNew(CString &strUrl, DWORD dwExProp, DWORD dwExProp2, DWORD dwOpenFlag) { #if 1 //+++ dwOpenFlag &= ~D_OPENFILE_NOCREATE; CExProperty ExProp(CDLControlOption::s_dwDLControlFlags, CDLControlOption::s_dwExtendedStyleFlags, 0, dwExProp, dwExProp2); int dlCtrlFlag = ExProp.GetDLControlFlags(); int extendedStyleFlag = ExProp.GetExtendedStyleFlags(); //URLで新規タブを開く HWND hWndNew = UserOpenFile(strUrl, dwOpenFlag, dlCtrlFlag, extendedStyleFlag); if ( hWndNew == 0 || !::IsWindow(hWndNew) ) return NULL; //拡張プロパティを適用する CChildFrame *pChild = GetChildFrame(hWndNew); if (!pChild) return NULL; pChild->view().PutDLControlFlags( dlCtrlFlag ); pChild->SetViewExStyle(ExProp.GetExtendedStyleFlags(), TRUE); pChild->view().m_ViewOption.SetAutoRefreshStyle( ExProp.GetAutoRefreshFlag() ); return hWndNew; #else dwOpenFlag &= ~D_OPENFILE_NOCREATE; //URLで新規タブを開く HWND hWndNew = UserOpenFile(strUrl, dwOpenFlag); if ( hWndNew == 0 || !::IsWindow(hWndNew) ) return NULL; //拡張プロパティを適用する CChildFrame *pChild = GetChildFrame(hWndNew); if (!pChild) return NULL; CExProperty ExProp(CDLControlOption::s_dwDLControlFlags, CDLControlOption::s_dwExtendedStyleFlags, 0, dwExProp); pChild->view().PutDLControlFlags( ExProp.GetDLControlFlags() ); pChild->SetViewExStyle(ExProp.GetExtendedStyleFlags(), TRUE); pChild->view().m_ViewOption.SetAutoRefreshStyle( ExProp.GetAutoRefreshFlag() ); return hWndNew; #endif } //タブを開いたのち、標準の設定を適用する HWND CMainFrame::OpenExPropertyNot(CString &strUrl, DWORD dwOpenFlag) { //アクティブなタブがナビゲートロックされているかを確認 HWND hWndActive = MDIGetActive(); if ( ::IsWindow(hWndActive) ) { CChildFrame *pChild = GetChildFrame(hWndActive); if (pChild) { DWORD dwExFlag = pChild->view().m_ViewOption.m_dwExStyle; if (dwExFlag & DVS_EX_OPENNEWWIN) dwOpenFlag &= ~D_OPENFILE_NOCREATE; //新規タブで開くように } } //取得したURLを開かせる HWND hWndNew = UserOpenFile(strUrl, dwOpenFlag); if (hWndNew) { //新規に開いたタブなので何もしなくてよい return hWndNew; } else { //オプションを標準のもので上書き CChildFrame *pChild = GetChildFrame( MDIGetActive() ); if (!pChild) return NULL; pChild->view().PutDLControlFlags(CDLControlOption::s_dwDLControlFlags); pChild->SetViewExStyle(CDLControlOption::s_dwExtendedStyleFlags, TRUE); pChild->view().m_ViewOption.SetAutoRefreshStyle(0); } return NULL; } LRESULT CMainFrame::OnFileRecent(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { // get file name from the MRU list if (ID_FILE_MRU_FIRST <= wID && wID <= ID_FILE_MRU_LAST) //旧範囲IDから新範囲IDへ変換 wID = wID - ID_FILE_MRU_FIRST + ID_RECENTDOCUMENT_FIRST; CRecentDocumentListFixed::RecentDocEntry Entry; if ( CMainOption::s_pMru->GetFromList(wID, &Entry) ) { DWORD dwOpenFlag = DonutGetStdOpenCreateFlag(); /*DonutGetStdOpenFlag()*/ // Force New Window // UDT DGSTR HWND hWndNew = OnUserOpenFile(Entry.szDocName, dwOpenFlag); if ( ::IsWindow(hWndNew) ) { if (CMainOption::s_bTravelLogClose) { CChildFrame *pChild = GetChildFrame(hWndNew); if (pChild) { _Load_OptionalData2(pChild, Entry.arrFore, Entry.arrBack); } } } CMainOption::s_pMru->RemoveFromList(wID); // UDT DGSTR } else { ::MessageBeep(MB_ICONERROR); } return 0; } //+++ メモ:複数起動無しで、別のプログラムから引数付きで起動された場合に、ここにくる。 //+++ 他の外部からの追加表示はDDE経由で行われるようで、こちらにくることはなさそう...? void CMainFrame::OnNewInstance(ATOM nAtom) // WM_NEWINSTANCE { enum { NAME_LEN = 0x4000 }; TCHAR szBuff[NAME_LEN+2]; szBuff[0] = 0; bool bActive = !(CMainOption::s_dwMainExtendedStyle & MAIN_EX_NOACTIVATE); if (::GlobalGetAtomName(nAtom, szBuff, NAME_LEN) != 0) { //dmfTRACE(_T("CMainFrame::OnNewInstance: %s\n"), szBuff); CString strPath; std::vector<CString> strs; Misc::SeptTextToWords(strs, szBuff); for (unsigned i = 0; i < strs.size(); ++i) { CString& str = strs[i]; int c = str[0]; if (c == _T('-') || c == _T('/')) { if (str.CompareNoCase(_T("-tray")) == 0 || str.CompareNoCase(_T("/tray"))) { bActive = false; } } else { if (strPath.IsEmpty()) strPath = str; else strPath += _T(' ') + str; } } OnUserOpenFile( strPath, DonutGetStdOpenFlag() ); ::GlobalDeleteAtom(nAtom); } if ( bActive ) { MtlSetForegroundWindow(m_hWnd); //ウインドウをアクティブにする IfTrayRestoreWindow(); //+++ トレイ状態だったら復活. if (m_bOldMaximized == 0 && m_bFullScreen == 0) //+++ ShowWindow_Restore(1); //ShowWindow(SW_RESTORE); //+++ サイズを戻す. } } //////////////////////////////////////////////////////////////////////////////// //ファイルメニュー // コマンドハンドラ //////////////////////////////////////////////////////////////////////////////// ////新規作成 //ポームページ void CMainFrame::OnFileNewHome(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/) { HWND hWndChild = OnUserOpenFile( CString(), DonutGetStdOpenActivateFlag() ); if (hWndChild) { CGeckoBrowser browser = DonutGetNsIWebBrowser(hWndChild); if (browser.m_spBrowser != NULL) browser.GoHome(); } } //現在のページ void CMainFrame::OnFileNewCopy(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/) { HWND hWndActive = MDIGetActive(); if (hWndActive) { CGeckoBrowser browser = DonutGetNsIWebBrowser(hWndActive); if (browser.m_spBrowser != NULL) { CString strURL = browser.GetLocationURL(); if ( !strURL.IsEmpty() ) OnUserOpenFile( strURL, DonutGetStdOpenActivateFlag() ); } } } LRESULT CMainFrame::OnFileNew(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { if (CFileNewOption::s_dwFlags == FILENEW_BLANK) { OnFileNewBlank(0, 0, 0); } else if (CFileNewOption::s_dwFlags == FILENEW_COPY) { if (MDIGetActive() != NULL) SendMessage(WM_COMMAND, MAKEWPARAM(ID_FILE_NEW_COPY, 0), 0); else OnFileNewBlank(0, 0, 0); } else if (CFileNewOption::s_dwFlags == FILENEW_HOME) { OnFileNewHome(0, 0, 0); } else if (CFileNewOption::s_dwFlags == FILENEW_USER) { //+++ ユーザー指定のページを開く //CIniFileI pr( g_szIniFileName, _T("Main") ); //CString str = pr.GetStringUW( _T("File_New_UsrPage") ); //pr.Close(); CString& str = CFileNewOption::s_strUsr; if ( !str.IsEmpty() ) OnUserOpenFile(str, 0); else OnFileNewBlank(0, 0, 0); } else { ATLASSERT(FALSE); OnFileNewBlank(0, 0, 0); } return 0; } //空白ページ void CMainFrame::OnFileNewBlank(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/) { OnUserOpenFile( _T("about:blank"), DonutGetStdOpenActivateFlag() ); SendMessage(WM_COMMAND, ID_SETFOCUS_ADDRESSBAR, 0); } //クリップボード void CMainFrame::OnFileNewClipBoard(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/) { CString strText = MtlGetClipboardText(); if ( strText.IsEmpty() ) return; OnUserOpenFile( strText, DonutGetStdOpenActivateFlag() ); } //Default.dfg // UDT DGSTR LRESULT CMainFrame::OnFileOpenDef(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { CString strPath = Misc::GetExeDirectory() + _T("Default.dfg"); ATLTRACE2( atlTraceGeneral, 4, _T("CMainFrame::OnFileOpenDef\n") ); OnUserOpenFile( strPath, DonutGetStdOpenCreateFlag() ); return 0; } // ENDE void CMainFrame::OnFileNewClipBoard2(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/) { CString strText = MtlGetClipboardText(); if ( strText.IsEmpty() ) return; OnUserOpenFile( strText, DonutGetStdOpenFlag() ); // allow the option } LRESULT CMainFrame::OnFileOpen(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { //dmfTRACE( _T("CMainFrame::OnFileOpen\n") ); COpenURLDlg dlg; if ( dlg.DoModal() == IDOK && !dlg.m_strEdit.IsEmpty() ) { OnUserOpenFile( dlg.m_strEdit, DonutGetStdOpenFlag() ); } return 0; } /// DonutG の配布サイトを開く LRESULT CMainFrame::OnJumpToWebSite(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { //CString strSite = _T("http://www5.ocn.ne.jp/~minute/tab/"); //unDonut古い方 //CString strSite = _T("http://undonut.sakura.ne.jp/"); // unDonut新しい方 //CString strSite = _T("http://tekito.genin.jp/undonut+.html"); //unDonut+ //CString strSite = _T("http://ichounonakano.sakura.ne.jp/64/undonut/"); //unDonut+mod. 旧 //CString strSite = _T("http://undonut.undo.jp/"); //unDonut+mod. CString strSite = _T("http://donut.tnose.net/"); //DonutG OnUserOpenFile( strSite, DonutGetStdOpenFlag() ); return 0; } ///+++ .exeのあるフォルダを開く LRESULT CMainFrame::OnOpenExeDir(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { CString progDir = Misc::GetExeDirectory(); ShellExecute(NULL, _T("open"), progDir, progDir, NULL, SW_SHOW); return 0; } #ifndef USE_DIET //+++ saitama専用だったのを外部ファイル読込にして汎用化. HWND CMainFrame::_OpenAboutFile(CString strFile) { if (strFile.Left(6) != _T("about:")) return NULL; strFile = strFile.Mid(6); // about: bool bWarn = (strFile == "warning"); if (bWarn == 0) { strFile = Misc::GetFullPath_ForExe( "help\\about\\" + strFile ); // if (Misc::IsExistFile(strFile) == 0) //ファイルがなかったらかえる return NULL; } //plus7: Geckoの場合は別の流儀でaboutプロトコルを提供することになる。よってこれ以降削除。あとで考える。 return 0; } #endif
[ [ [ 1, 678 ] ] ]
00a458d662ebd75934fef19f86861cc8f42c5c3e
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/graphics/core/win32/dxgitypedef.h
ad91fffd9cb12907ead2025682276a917a243cdb
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
6,904
h
/*! @file @brief DXGI 定義 */ #ifndef maid2_graphics_core_win32_dxgitypedef_h #define maid2_graphics_core_win32_dxgitypedef_h #include"../../../config/define.h" #include"../../../framework/win32/com_ptr.h" #include"../../pixelformat.h" #include"../createparam.h" #include"../iinputlayout.h" #include<dxgi.h> namespace Maid { namespace Graphics { typedef com_ptr<IDXGIFactory> SPDXGIFACTORY; typedef com_ptr<IDXGIFactory1> SPDXGIFACTORY1; typedef com_ptr<IDXGIAdapter> SPDXGIADAPTER; typedef com_ptr<IDXGIAdapter1> SPDXGIADAPTER1; typedef com_ptr<IDXGISwapChain> SPDXGISWAPCHAIN; typedef com_ptr<IDXGIOutput> SPDXGIOUTPUT; typedef com_ptr<IDXGISurface> SPDXGISURFACE; /*! @fn D3DFORMAT PIXELFORMATtoD3DFORMAT( PIXELFORMAT eFormat ) PIXELFORMAT を Direct3D10 で使用されている \n ピクセルフォーマットに変換します @param eFormat [i ] 変換したいフォーマット @return 変換後のフォーマット \n 判別できなかったら D3DFMT_UNKNOWN */ inline DXGI_FORMAT PIXELFORMATtoDXGI_FORMAT( PIXELFORMAT eFormat ) { switch( eFormat ) { case PIXELFORMAT_A08B08G08R08I: { return DXGI_FORMAT_R8G8B8A8_UNORM; }break; case PIXELFORMAT_A02B10G10R10I: { return DXGI_FORMAT_R10G10B10A2_UNORM; }break; case PIXELFORMAT_A16B16G16R16I: { return DXGI_FORMAT_R16G16B16A16_UNORM; }break; case PIXELFORMAT_A16B16G16R16F: { return DXGI_FORMAT_R16G16B16A16_FLOAT; }break; case PIXELFORMAT_A32B32G32R32F: { return DXGI_FORMAT_R32G32B32A32_FLOAT; }break; case PIXELFORMAT_DXT1: { return DXGI_FORMAT_BC1_UNORM; }break; case PIXELFORMAT_DXT2: { return DXGI_FORMAT_BC2_UNORM; }break; case PIXELFORMAT_DXT3: { return DXGI_FORMAT_BC3_UNORM; }break; case PIXELFORMAT_DXT4: { return DXGI_FORMAT_BC4_UNORM; }break; case PIXELFORMAT_DXT5: { return DXGI_FORMAT_BC5_UNORM; }break; case PIXELFORMAT_D16I: { return DXGI_FORMAT_D32_FLOAT; }break; case PIXELFORMAT_D24IS8: { return DXGI_FORMAT_D24_UNORM_S8_UINT; }break; // case PIXELFORMAT_D24IS8: { return DXGI_FORMAT_D32_FLOAT_S8X24_UINT; }break; } MAID_ASSERT( true, "識別できないPIXELFORMATです " << eFormat ); return DXGI_FORMAT_UNKNOWN; } /*! @fn PIXELFORMAT D3DFORMATtoPIXELFORMAT( D3DFORMAT eFormat ) DirectGraphic9 で使用されているピクセルフォーマットを PIXELFORMAT に変換します @param Format [i ] 変換したい頂点フォーマット @return 変換後のフォーマット \n 判別できなかったら PIXELFORMAT_NONE */ inline PIXELFORMAT DXGI_FORMATtoPIXELFORMAT( DXGI_FORMAT Format ) { switch( Format ) { case DXGI_FORMAT_R8G8B8A8_UNORM: { return PIXELFORMAT_A08B08G08R08I; }break; case DXGI_FORMAT_R10G10B10A2_UNORM: { return PIXELFORMAT_A02B10G10R10I; }break; case DXGI_FORMAT_R16G16B16A16_UNORM:{ return PIXELFORMAT_A16B16G16R16I; }break; case DXGI_FORMAT_R16G16B16A16_FLOAT:{ return PIXELFORMAT_A16B16G16R16F; }break; case DXGI_FORMAT_R32G32B32A32_FLOAT:{ return PIXELFORMAT_A32B32G32R32F; }break; case DXGI_FORMAT_BC1_UNORM: { return PIXELFORMAT_DXT1; }break; case DXGI_FORMAT_BC2_UNORM: { return PIXELFORMAT_DXT2; }break; case DXGI_FORMAT_BC3_UNORM: { return PIXELFORMAT_DXT3; }break; case DXGI_FORMAT_BC4_UNORM: { return PIXELFORMAT_DXT4; }break; case DXGI_FORMAT_BC5_UNORM: { return PIXELFORMAT_DXT5; }break; case DXGI_FORMAT_D16_UNORM: { return PIXELFORMAT_D16I; }break; case DXGI_FORMAT_D24_UNORM_S8_UINT: { return PIXELFORMAT_D24IS8; }break; } return PIXELFORMAT_NONE; } inline SWAPCHAINFORMAT::SCANLINEORDER DXGI_MODE_SCANLINE_ORDERtoSWAPCHAINFORMATSCANLINEORDER( DXGI_MODE_SCANLINE_ORDER type ) { SWAPCHAINFORMAT::SCANLINEORDER ret = SWAPCHAINFORMAT::SCANLINEORDER_PROGRESSIVE; switch( type ) { case DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED: { ret = SWAPCHAINFORMAT::SCANLINEORDER_UNSPECIFIED; }break; case DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE: { ret = SWAPCHAINFORMAT::SCANLINEORDER_PROGRESSIVE; }break; case DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST: { ret = SWAPCHAINFORMAT::SCANLINEORDER_INTERLACE_U; }break; case DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST: { ret = SWAPCHAINFORMAT::SCANLINEORDER_INTERLACE_L; }break; } return ret; } inline DXGI_MODE_SCANLINE_ORDER SWAPCHAINFORMATSCANLINEORDERtoDXGI_MODE_SCANLINE_ORDER( SWAPCHAINFORMAT::SCANLINEORDER type ) { DXGI_MODE_SCANLINE_ORDER ret = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE; switch( type ) { case SWAPCHAINFORMAT::SCANLINEORDER_UNSPECIFIED: { ret = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; }break; case SWAPCHAINFORMAT::SCANLINEORDER_PROGRESSIVE: { ret = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE; }break; case SWAPCHAINFORMAT::SCANLINEORDER_INTERLACE_U: { ret = DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST; }break; case SWAPCHAINFORMAT::SCANLINEORDER_INTERLACE_L: { ret = DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST; }break; } return ret; } inline SWAPCHAINFORMAT::SCALING DXGI_MODE_SCALINGtoDISPLAYMODESCALING( DXGI_MODE_SCALING type ) { SWAPCHAINFORMAT::SCALING ret = SWAPCHAINFORMAT::SCALING_STRETCHED; switch( type ) { case DXGI_MODE_SCALING_UNSPECIFIED: { ret = SWAPCHAINFORMAT::SCALING_UNSPECIFIED; }break; case DXGI_MODE_SCALING_CENTERED: { ret = SWAPCHAINFORMAT::SCALING_CENTERED; }break; case DXGI_MODE_SCALING_STRETCHED: { ret = SWAPCHAINFORMAT::SCALING_STRETCHED; }break; } return ret; } inline DXGI_MODE_SCALING SWAPCHAINFORMATSCALINGtoDXGI_MODE_SCALING( SWAPCHAINFORMAT::SCALING type ) { DXGI_MODE_SCALING ret = DXGI_MODE_SCALING_STRETCHED; switch( type ) { case SWAPCHAINFORMAT::SCALING_UNSPECIFIED:{ ret = DXGI_MODE_SCALING_UNSPECIFIED; }break; case SWAPCHAINFORMAT::SCALING_CENTERED: { ret = DXGI_MODE_SCALING_CENTERED; }break; case SWAPCHAINFORMAT::SCALING_STRETCHED: { ret = DXGI_MODE_SCALING_STRETCHED; }break; } return ret; } inline DXGI_FORMAT INPUT_ELEMENTTYPEtoDXGI_FORMAT( INPUT_ELEMENT::TYPE t ) { DXGI_FORMAT ret; switch( t ) { case INPUT_ELEMENT::TYPE_FLOAT1: { ret = DXGI_FORMAT_R32_FLOAT; }break; case INPUT_ELEMENT::TYPE_FLOAT2: { ret = DXGI_FORMAT_R32G32_FLOAT; }break; case INPUT_ELEMENT::TYPE_FLOAT3: { ret = DXGI_FORMAT_R32G32B32_FLOAT; }break; case INPUT_ELEMENT::TYPE_FLOAT4: { ret = DXGI_FORMAT_R32G32B32A32_FLOAT; }break; case INPUT_ELEMENT::TYPE_COLOR: { ret = DXGI_FORMAT_R8G8B8A8_UNORM; }break; } return ret; } }} #endif
[ "[email protected]", "renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00" ]
[ [ [ 1, 9 ], [ 14, 148 ], [ 165, 168 ] ], [ [ 10, 13 ], [ 149, 164 ] ] ]
57673dcd6081ae44039b5fe359cd3a96c21c2274
9ec40f3fefd91a67c0db1540ea75efd108727448
/main.cpp
84b700f13a5d932ffb70966ff5556b2a219ab492
[]
no_license
Google-Code-Fork/windows-tibia-ip-changer
33981fc8a8767799fc1f092aa54e6f8693a40a02
73bbf6b702d07cb85f2192f01c5be7c6e9f31e02
refs/heads/master
2020-04-29T17:03:22.694184
2011-03-06T17:23:55
2011-03-06T17:23:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
285
cpp
#include "main.h" #include "gui.h" int main(int argc, char **argv){ wxApp::SetInstance(new IPChanger()); return wxEntry(argc, argv); } bool IPChanger::OnInit() { Frame *frame = new Frame(NULL); SetTopWindow(frame); frame->Show(true); return true; }
[ "[email protected]@bf95fa01-938d-e325-26e9-0f436a35a645" ]
[ [ [ 1, 15 ] ] ]
b410250793c8c8e88c65328d1cb31d6d6ac2312f
8cf9b251e0f4a23a6ef979c33ee96ff4bdb829ab
/src-ginga-editing/ncl30-generator-cpp/include/GeneratorUtil.h
b8706eab3ed1c6c7f4ebb4947a61b0da812545f3
[]
no_license
BrunoSSts/ginga-wac
7436a9815427a74032c9d58028394ccaac45cbf9
ea4c5ab349b971bd7f4f2b0940f2f595e6475d6c
refs/heads/master
2020-05-20T22:21:33.645904
2011-10-17T12:34:32
2011-10-17T12:34:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,458
h
/****************************************************************************** Este arquivo eh parte da implementacao do ambiente declarativo do middleware Ginga (Ginga-NCL). Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free Software Foundation. Este programa eh distribuido na expectativa de que seja util, porem, SEM NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do GNU versao 2 para mais detalhes. Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto com este programa; se nao, escreva para a Free Software Foundation, Inc., no endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. Para maiores informacoes: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br ****************************************************************************** This file is part of the declarative environment of middleware Ginga (Ginga-NCL) Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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 version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA For further information contact: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br *******************************************************************************/ /** * @file GeneratorUtil.h * @author Caio Viel * @date 29-01-10 */ #ifndef _GENERATORUTIL_H #define _GENERATORUTIL_H #include "util/Color.h" #include "util/functions.h" using namespace ::br::pucrio::telemidia::util; #include "ncl/NclDocument.h" using namespace ::br::pucrio::telemidia::ncl; #include "ncl/reuse/ReferNode.h" using namespace ::br::pucrio::telemidia::ncl::reuse; #include "ncl/interfaces/PropertyAnchor.h" using namespace ::br::pucrio::telemidia::ncl::interfaces; #include <string> using namespace std; #include "PropertyAnchorGenerator.h" #include "AnchorGenerator.h" namespace br { namespace ufscar { namespace lince { namespace ncl { namespace generate { class GeneratorUtil { public: /** * Gera o código XML da entidade NCL Color. * @param color O objeto que representa a cor cujo código deve ser gerado. * @return Uma string contendo o código NCL gerado. */ static string getColorString(Color* color); /** * Gera o código XML de nós que referenciam outros nós. * @param referNode O nó de referência que cujo código será gerado. * @param nclDocument O documento NCL a que o nó de referência pertence. * @return Uma string contendo o código NCL gerado. */ static string referNodeCodeGenerate(ReferNode* referNode, NclDocument* nclDocument); }; } } } } } #endif //_GENERATORUTIL_H
[ [ [ 1, 111 ] ] ]
8625d1ac0239b64c72189875a31030192fc960bd
51d0aa420c539ad087ed1d32aa123d8fcefe2cb9
/src/luanode_datagram_udp.cpp
de46bfc3eb736ea1d163a8e2aba3b7fbafe80950
[ "MIT" ]
permissive
Sciumo/LuaNode
1aae81a44d9ff1948499b2103b56c175e97d89da
0611b4d5496bf67d336ac24e903a91e5d28f6f83
refs/heads/master
2021-01-18T00:01:13.841566
2011-08-01T22:15:50
2011-08-01T22:15:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,523
cpp
#include "stdafx.h" #include "luanode.h" #include "luanode_datagram_udp.h" #include "blogger.h" #include <boost/asio/read_until.hpp> #include <boost/asio/write.hpp> #include <boost/asio/placeholders.hpp> #include <boost/make_shared.hpp> #include <boost/bind.hpp> #include "shared_const_buffer.h" using namespace LuaNode::Datagram; static unsigned long s_nextSocketId = 0; static unsigned long s_socketCount = 0; ////////////////////////////////////////////////////////////////////////// /// void LuaNode::Datagram::RegisterFunctions(lua_State* L) { /*luaL_Reg methods[] = { //{ "isIP", LuaNode::Net::IsIP }, { 0, 0 } };*/ //luaL_register(L, "Datagram", methods); //lua_pop(L, 1); } ////////////////////////////////////////////////////////////////////////// /// const char* Socket::className = "UdpSocket"; const Socket::RegType Socket::methods[] = { {"setoption", &Socket::SetOption}, {"bind", &Socket::Bind}, {"close", &Socket::Close}, {"shutdown", &Socket::Shutdown}, {"sendto", &Socket::SendTo}, {"read", &Socket::Read}, {"connect", &Socket::Connect}, {"getsockname", &Socket::GetLocalAddress}, {"getpeername", &Socket::GetRemoteAddress}, {0} }; const Socket::RegType Socket::setters[] = { {0} }; const Socket::RegType Socket::getters[] = { {0} }; ////////////////////////////////////////////////////////////////////////// /// Socket::Socket(lua_State* L) : m_L( LuaNode::GetLuaVM() ), m_socketId(++s_nextSocketId), m_close_pending(false), //m_read_shutdown_pending(false), m_write_shutdown_pending(false), m_pending_writes(0), m_pending_reads(0) { s_socketCount++; LogDebug("Constructing Socket (%p) (id=%d). Current socket count = %d", this, m_socketId, s_socketCount); const char* kind = luaL_checkstring(L, 1); LogDebug("Socket::Socket(%s)", kind); if(strcmp(kind, "udp4") == 0) { m_socket = boost::make_shared<boost::asio::ip::udp::socket>(boost::ref(GetIoService()), boost::asio::ip::udp::v4()); } else if(strcmp(kind, "udp6") == 0) { m_socket = boost::make_shared<boost::asio::ip::udp::socket>(boost::ref(GetIoService()), boost::asio::ip::udp::v6()); } } ////////////////////////////////////////////////////////////////////////// /// This gets called when we accept a connection Socket::Socket(lua_State* L, boost::asio::ip::udp::socket* socket) : m_L( LuaNode::GetLuaVM() ), m_socketId(++s_nextSocketId), m_close_pending(false), //m_read_shutdown_pending(false), m_write_shutdown_pending(false), m_pending_writes(0), m_pending_reads(0), m_socket(socket) { s_socketCount++; LogDebug("Constructing Socket (%p) (id=%d). Current socket count = %d", this, m_socketId, s_socketCount); } Socket::~Socket(void) { s_socketCount--; LogDebug("Destructing Socket (%p) (id=%d). Current socket count = %d", this, m_socketId, s_socketCount); } ////////////////////////////////////////////////////////////////////////// /// /*static*/ int Socket::tostring_T(lua_State* L) { userdataType* ud = static_cast<userdataType*>(lua_touserdata(L, 1)); Socket* obj = ud->pT; lua_pushfstring(L, "%s (%p) (id=%d)", className, obj, obj->m_socketId); return 1; } ////////////////////////////////////////////////////////////////////////// /// int Socket::GetRemoteAddress(lua_State* L) { const boost::asio::ip::udp::endpoint& endpoint = m_socket->remote_endpoint(); lua_pushstring(L, endpoint.address().to_string().c_str()); lua_pushinteger(L, endpoint.port()); return 2; } ////////////////////////////////////////////////////////////////////////// /// int Socket::GetLocalAddress(lua_State* L) { const boost::asio::ip::udp::endpoint& endpoint = m_socket->local_endpoint(); lua_pushstring(L, endpoint.address().to_string().c_str()); lua_pushinteger(L, endpoint.port()); return 2; } ////////////////////////////////////////////////////////////////////////// /// int Socket::SetOption(lua_State* L) { const char* options[] = { "broadcast", "ttl", //"keepalive", "no_option", NULL }; const char* option = luaL_checkstring(L, 2); LogDebug("Socket::SetOption (id=%d) - %s", m_socketId, option); int chosen_option = luaL_checkoption(L, 2, "no_option", options); switch(chosen_option) { case 0: { // broadcast boost::system::error_code ec; bool value = lua_toboolean(L, 3) != 0; m_socket->set_option( boost::asio::socket_base::broadcast(value), ec ); return BoostErrorCodeToLua(L, ec); break; } case 1: { // ttl int newttl = luaL_checkinteger(L, 4); int result = setsockopt(m_socket->native(), IPPROTO_IP, IP_TTL, (const char*)&newttl, sizeof(newttl)); if(result != 0) { #ifdef _WIN32 luaL_error(L, "Socket::SetOption (%p) - Failed to set TTL on native socket - %d", this, WSAGetLastError()); #elif __linux__ luaL_error(L, "Socket::SetOption (%p) - Failed to set TTL on native socket - %d, s", this, errno, strerror(errno)); #endif } break; } } return 0; } ////////////////////////////////////////////////////////////////////////// /// int Socket::Bind(lua_State* L) { boost::asio::ip::udp::endpoint endpoint; if(lua_isnoneornil(L, 3) && lua_isnumber(L, 2)) { unsigned short port = luaL_checkinteger(L, 2); endpoint = boost::asio::ip::udp::endpoint( boost::asio::ip::udp::v4(), port ); } else { const char* ip = luaL_checkstring(L, 2); unsigned short port = luaL_checkinteger(L, 3); endpoint = boost::asio::ip::udp::endpoint( boost::asio::ip::address::from_string(ip), port ); } boost::system::error_code ec; m_socket->bind(endpoint, ec); return BoostErrorCodeToLua(L, ec); } ////////////////////////////////////////////////////////////////////////// /// int Socket::Close(lua_State* L) { // Q: should I do the same when there are pending reads? probably not. One tends to have always a pending read. if(m_pending_writes) { LogDebug("Socket::Close - Socket (%p) (id=%d) marked for closing", this, m_socketId); // can't close the socket right away, just flag it and close it when there are no more queued ops m_close_pending = true; lua_pushboolean(L, true); return 1; } // nothing is waiting, just close the socket right away LogDebug("Socket::Close - Socket (%p) (id=%d) closing now", this, m_socketId); boost::system::error_code ec; m_socket->shutdown(boost::asio::socket_base::shutdown_both, ec); m_socket->close(ec); return BoostErrorCodeToLua(L, ec); } ////////////////////////////////////////////////////////////////////////// /// int Socket::Shutdown(lua_State* L) { static const char* options[] = { "read", "write", "both", "no_option", NULL }; boost::system::error_code ec; if(lua_type(L, 2) == LUA_TSTRING) { const char* option = luaL_checkstring(L, 2); int chosen_option = luaL_checkoption(L, 2, "no_option", options); switch(chosen_option) { case 0: // read /*m_read_shutdown_pending = true; if(m_pending_reads > 0) { m_write_shutdown_pending = true; } else { m_socket->shutdown(boost::asio::socket_base::shutdown_send, ec); }*/ LogDebug("Socket::Shutdown (%p) (id=%d) - %s", this, m_socketId, option); m_socket->shutdown(boost::asio::socket_base::shutdown_receive, ec); break; case 1: // write if(m_pending_writes > 0) { m_write_shutdown_pending = true; LogDebug("Socket::Shutdown (%p) (id=%d) - Marked for shutdown - %s", this, m_socketId, option); } else { m_socket->shutdown(boost::asio::socket_base::shutdown_send, ec); } break; case 2: // both if(m_pending_writes > 0) { m_write_shutdown_pending = true; LogDebug("Socket::Shutdown (%p) (id=%d) - Marked for shutdown - write", this, m_socketId); } else { m_socket->shutdown(boost::asio::socket_base::shutdown_send, ec); } //m_write_shutdown_pending = true; //m_read_shutdown_pending = true; m_socket->shutdown(boost::asio::socket_base::shutdown_receive, ec); break; default: break; } } else { LogDebug("Socket::Shutdown (%p) (id=%d) - both", this, m_socketId); if(m_pending_writes > 0) { m_write_shutdown_pending = true; LogDebug("Socket::Shutdown (%p) (id=%d) - Marked for shutdown - write", this, m_socketId); } else { m_socket->shutdown(boost::asio::socket_base::shutdown_send, ec); } m_socket->shutdown(boost::asio::socket_base::shutdown_receive, ec); } return BoostErrorCodeToLua(L, ec); } ////////////////////////////////////////////////////////////////////////// /// sendto(self, buf, off, len, flags, destination port, destination address, [callback]); int Socket::SendTo(lua_State* L) { if(m_pending_writes > 0) { lua_pushboolean(L, false); return 1; } unsigned short port = luaL_checkinteger(L, 6); const char* address = luaL_checkstring(L, 7); boost::asio::ip::udp::endpoint endpoint( boost::asio::ip::address::from_string(address), port ); // store a reference in the registry lua_pushvalue(L, 1); int reference = luaL_ref(L, LUA_REGISTRYINDEX); int callback = LUA_NOREF; if(!lua_isnoneornil(L, 8)) { lua_pushvalue(L, 8); callback = luaL_ref(L, LUA_REGISTRYINDEX); } if(lua_type(L, 2) == LUA_TSTRING) { const char* data = lua_tostring(L, 2); size_t length = lua_objlen(L, 2); std::string d(data, length); shared_const_buffer buffer(d); LogDebug("Socket::Write (%p) (id=%d) - Length=%d, \r\n'%s'", this, m_socketId, length, data); m_pending_writes++; ////P /* boost::asio::async_write(*m_socket, buffer, boost::bind(&Socket::HandleWrite, this, reference, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) ); */ m_socket->async_send_to(buffer, endpoint, boost::bind(&Socket::HandleSendTo, this, reference, callback , boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { luaL_error(L, "Socket::Write, unhandled type '%s'", luaL_typename(L, 2)); } lua_pushboolean(L, true); return 1; } ////////////////////////////////////////////////////////////////////////// /// void Socket::HandleSendTo(int reference, int callback, const boost::system::error_code& error, size_t bytes_transferred) { lua_State* L = LuaNode::GetLuaVM(); lua_rawgeti(L, LUA_REGISTRYINDEX, reference); luaL_unref(L, LUA_REGISTRYINDEX, reference); if(callback != LUA_NOREF) { lua_rawgeti(L, LUA_REGISTRYINDEX, callback); luaL_unref(L, LUA_REGISTRYINDEX, callback); } // stack: self, [callback] m_pending_writes--; if(!error) { LogInfo("Socket::HandleSendTo (%p) (id=%d) - Bytes Transferred (%d)", this, m_socketId, bytes_transferred); if(lua_type(L, 2) == LUA_TFUNCTION) { lua_pushvalue(L, 1); LuaNode::GetLuaVM().call(1, LUA_MULTRET); } else { // do nothing? } } else { LogDebug("Socket::HandleSendTo with error (%p) (id=%d) - %s", this, m_socketId, error.message().c_str()); //m_callback.OnWriteCompletionError(shared_from_this(), bytes_transferred, error); //lua_getfield(L, 1, "write_callback"); if(lua_type(L, 2) == LUA_TFUNCTION) { lua_pushvalue(L, 1); lua_pushnil(L); switch(error.value()) { case boost::asio::error::eof: lua_pushliteral(L, "eof"); break; #ifdef _WIN32 case ERROR_CONNECTION_ABORTED: #endif case boost::asio::error::connection_aborted: lua_pushliteral(L, "aborted"); break; case boost::asio::error::operation_aborted: lua_pushliteral(L, "aborted"); break; case boost::asio::error::connection_reset: lua_pushliteral(L, "reset"); break; default: lua_pushstring(L, error.message().c_str()); break; } LuaNode::GetLuaVM().call(3, LUA_MULTRET); } else { LogError("Socket::HandleSendTo with error (%p) (id=%d) - %s", this, m_socketId, error.message().c_str()); } } lua_settop(L, 0); if(m_write_shutdown_pending && m_pending_writes == 0) { LogDebug("Socket::HandleSendTo - Applying delayed send shutdown (%p) (id=%d) (send)", this, m_socketId); boost::system::error_code ec; m_socket->shutdown(boost::asio::socket_base::shutdown_send, ec); if(ec) { LogError("Socket::HandleSendTo - Error shutting down socket (%p) (id=%d) (send) - %s", this, m_socketId, ec.message().c_str()); } } if(m_close_pending && m_pending_writes == 0 && m_pending_reads == 0) { boost::system::error_code ec; m_socket->close(ec); if(ec) { LogError("Socket::HandleSendTo - Error closing socket (%p) (id=%d) - %s", this, m_socketId, ec.message().c_str()); } } } ////////////////////////////////////////////////////////////////////////// /// int Socket::Read(lua_State* L) { // store a reference in the registry lua_pushvalue(L, 1); int reference = luaL_ref(L, LUA_REGISTRYINDEX); if(lua_isnoneornil(L, 2)) { LogDebug("Socket::Read (%p) (id=%d) - ReadSome", this, m_socketId); m_pending_reads++; m_socket->async_receive( boost::asio::buffer(m_inputArray), boost::bind(&Socket::HandleReceive, this, reference, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) ); ////P /*m_socket->async_read_some( boost::asio::buffer(m_inputArray), boost::bind(&Socket::HandleReadSome, this, reference, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) );*/ } else if(!lua_isnumber(L, 2)) { //const char* p = luaL_optstring(L, 2, "*l"); std::string delimiter = "\r\n"; LogDebug("Socket::Read (%p) (id=%d) - ReadLine", this, m_socketId); m_pending_reads++; ////P /* boost::asio::async_read_until( *m_socket, m_inputBuffer, delimiter, boost::bind(&Socket::HandleRead, this, reference, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) );*/ } else { luaL_error(L, "for the moment the read must be done with nil or a number"); } /*boost::asio::async_read(*m_socket, buffer, boost::bind(&Socket::HandleSendTo, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) );*/ return 0; } ////////////////////////////////////////////////////////////////////////// /// void Socket::HandleRead(int reference, const boost::system::error_code& error, size_t bytes_transferred) { lua_State* L = LuaNode::GetLuaVM(); lua_rawgeti(L, LUA_REGISTRYINDEX, reference); luaL_unref(L, LUA_REGISTRYINDEX, reference); m_pending_reads--; if(!error) { LogInfo("Socket::HandleRead (%p) (id=%d) - Bytes Transferred (%d)", this, m_socketId, bytes_transferred); lua_getfield(L, 1, "read_callback"); if(lua_type(L, 2) == LUA_TFUNCTION) { lua_pushvalue(L, 1); const char* data = (const char*)boost::asio::detail::buffer_cast_helper(m_inputBuffer.data()); lua_pushlstring(L, data, m_inputBuffer.size()); m_inputBuffer.consume(m_inputBuffer.size()); // its safe to consume, the string has already been interned LuaNode::GetLuaVM().call(2, LUA_MULTRET); } else { // do nothing? if(lua_type(L, 1) == LUA_TUSERDATA) { userdataType* ud = static_cast<userdataType*>(lua_touserdata(L, 1)); LogWarning("Socket::HandleRead (%p) (id=%d) - No read_callback set on %s (address: %p, possible obj: %p)", this, m_socketId, luaL_typename(L, 1), ud, ud->pT); } else { LogWarning("Socket::HandleRead (%p) (id=%d) - No read_callback set on %s", this, m_socketId, luaL_typename(L, 1)); } } } else { LogDebug("Socket::HandleRead with error (%p) (id=%d) - %s", this, m_socketId, error.message().c_str()); lua_getfield(L, 1, "read_callback"); if(lua_type(L, 2) == LUA_TFUNCTION) { lua_pushvalue(L, 1); lua_pushnil(L); switch(error.value()) { case boost::asio::error::eof: lua_pushliteral(L, "eof"); break; #ifdef _WIN32 case ERROR_CONNECTION_ABORTED: #endif case boost::asio::error::connection_aborted: lua_pushliteral(L, "aborted"); break; case boost::asio::error::operation_aborted: lua_pushliteral(L, "aborted"); break; case boost::asio::error::connection_reset: lua_pushliteral(L, "reset"); break; default: lua_pushstring(L, error.message().c_str()); break; } LuaNode::GetLuaVM().call(3, LUA_MULTRET); m_inputBuffer.consume(m_inputBuffer.size()); } else { LogError("Socket::HandleRead with error (%p) (id=%d) - %s", this, m_socketId, error.message().c_str()); } } lua_settop(L, 0); if(m_close_pending && m_pending_writes == 0 && m_pending_reads == 0) { boost::system::error_code ec; m_socket->close(ec); if(ec) { LogError("Socket::HandleRead - Error closing socket (%p) (id=%d) - %s", this, m_socketId, ec.message().c_str()); } } } ////////////////////////////////////////////////////////////////////////// /// void Socket::HandleReceive(int reference, const boost::system::error_code& error, size_t bytes_transferred) { lua_State* L = LuaNode::GetLuaVM(); lua_rawgeti(L, LUA_REGISTRYINDEX, reference); luaL_unref(L, LUA_REGISTRYINDEX, reference); m_pending_reads--; if(!error) { LogInfo("Socket::HandleReceive (%p) (id=%d) - Bytes Transferred (%d)", this, m_socketId, bytes_transferred); lua_getfield(L, 1, "read_callback"); if(lua_type(L, 2) == LUA_TFUNCTION) { lua_pushvalue(L, 1); const char* data = m_inputArray.c_array(); lua_pushlstring(L, data, bytes_transferred); LuaNode::GetLuaVM().call(2, LUA_MULTRET); } else { // do nothing? if(lua_type(L, 1) == LUA_TUSERDATA) { userdataType* ud = static_cast<userdataType*>(lua_touserdata(L, 1)); LogWarning("Socket::HandleReceive (%p) (id=%d) - No read_callback set on %s (address: %p, possible obj: %p)", this, m_socketId, luaL_typename(L, 1), ud, ud->pT); } else { LogWarning("Socket::HandleReceive (%p) (id=%d) - No read_callback set on %s", this, m_socketId, luaL_typename(L, 1)); } } } else { lua_getfield(L, 1, "read_callback"); if(lua_type(L, 2) == LUA_TFUNCTION) { lua_pushvalue(L, 1); lua_pushnil(L); switch(error.value()) { case boost::asio::error::eof: lua_pushliteral(L, "eof"); break; #ifdef _WIN32 case ERROR_CONNECTION_ABORTED: #endif case boost::asio::error::connection_aborted: lua_pushliteral(L, "aborted"); break; case boost::asio::error::operation_aborted: lua_pushliteral(L, "aborted"); break; case boost::asio::error::connection_reset: lua_pushliteral(L, "reset"); break; default: lua_pushstring(L, error.message().c_str()); break; } if(error.value() != boost::asio::error::eof && error.value() != boost::asio::error::operation_aborted) { LogError("Socket::HandleReceive with error (%p) (id=%d) - %s", this, m_socketId, error.message().c_str()); } LuaNode::GetLuaVM().call(3, LUA_MULTRET); } else { LogError("Socket::HandleReceive with error (%p) (id=%d) - %s", this, m_socketId, error.message().c_str()); if(lua_type(L, 1) == LUA_TUSERDATA) { userdataType* ud = static_cast<userdataType*>(lua_touserdata(L, 1)); LogWarning("Socket::HandleReceive (%p) (id=%d) - No read_callback set on %s (address: %p, possible obj: %p)", this, m_socketId, luaL_typename(L, 1), ud, ud->pT); } else { LogWarning("Socket::HandleReceive (%p) (id=%d) - No read_callback set on %s", this, m_socketId, luaL_typename(L, 1)); } } } lua_settop(L, 0); if(m_close_pending && m_pending_writes == 0 && m_pending_reads == 0) { boost::system::error_code ec; m_socket->close(ec); if(ec) { LogError("Socket::HandleReceive - Error closing socket (%p) (id=%d) - %s", this, m_socketId, ec.message().c_str()); } } } ////////////////////////////////////////////////////////////////////////// /// int Socket::Connect(lua_State* L) { const char* ip = luaL_checkstring(L, 2); unsigned short port = luaL_checkinteger(L, 3); LogDebug("Socket::Connect (%p) (id=%d) (%s:%d)", this, m_socketId, ip, port); boost::asio::ip::udp::endpoint endpoint( boost::asio::ip::address::from_string(ip), port ); // store a reference in the registry lua_pushvalue(L, 1); int reference = luaL_ref(L, LUA_REGISTRYINDEX); m_socket->async_connect(endpoint, boost::bind(&Socket::HandleConnect, this, reference, boost::asio::placeholders::error) ); lua_pushboolean(L, true); return 1; } ////////////////////////////////////////////////////////////////////////// /// void Socket::HandleConnect(int reference, const boost::system::error_code& error) { lua_State* L = LuaNode::GetLuaVM(); lua_rawgeti(L, LUA_REGISTRYINDEX, reference); luaL_unref(L, LUA_REGISTRYINDEX, reference); LogInfo("Socket::HandleConnect (%p) (id=%d)", this, m_socketId); lua_getfield(L, 1, "connect_callback"); if(lua_type(L, 2) == LUA_TFUNCTION) { lua_pushvalue(L, 1); if(!error) { lua_pushboolean(L, true); LuaNode::GetLuaVM().call(2, LUA_MULTRET); } else { lua_pushboolean(L, false); lua_pushstring(L, error.message().c_str()); LuaNode::GetLuaVM().call(3, LUA_MULTRET); } } else { LogError("Socket::HandleConnect with error (%p) (id=%d) - %s", this, m_socketId, error.message().c_str()); } lua_settop(L, 0); }
[ [ [ 1, 668 ] ] ]
48d0f0697906dc7093a25bbe4f310ded5daed0f8
a36d7a42310a8351aa0d427fe38b4c6eece305ea
/core_billiard/VertexBuffer.h
f323e1349e101cc3e40029c62b4eae7c8af11e27
[]
no_license
newpolaris/mybilliard01
ca92888373c97606033c16c84a423de54146386a
dc3b21c63b5bfc762d6b1741b550021b347432e8
refs/heads/master
2020-04-21T06:08:04.412207
2009-09-21T15:18:27
2009-09-21T15:18:27
39,947,400
0
0
null
null
null
null
UTF-8
C++
false
false
1,552
h
#pragma once namespace my_render { MY_INTERFACE VertexBuffer { virtual ~VertexBuffer() {} virtual bool appendTexCoord1D_Array( const float * texCoords_1floatsForEach, size_t usageIndex ) PURE; virtual bool appendTexCoord2D_Array( const float * texCoords_2floatsForEach, size_t usageIndex ) PURE; virtual bool appendTexCoord3D_Array( const float * texCoords_3floatsForEach, size_t usageIndex ) PURE; virtual bool appendTexCoord4D_Array( const float * texCoords_4floatsForEach, size_t usageIndex ) PURE; virtual bool appendNormal_Array( const float * normals_3floatsForEach, size_t usageIndex ) PURE; virtual bool appendBinormal_Array( const float * binormal_3floatsForEach, size_t usageIndex ) PURE; virtual bool appendTangent_Array( const float * tangent_3floatsForEach, size_t usageIndex ) PURE; virtual bool appendUV_Array( const float * ut_2floatsForEach, size_t usageIndex ) PURE; virtual bool appendColor_Array( const NxU32 * color_3UnsignedIntForEach, size_t usageIndex ) PURE; virtual size_t getNumberOfVertex() PURE; MY_INTERFACE DrawPrimitive { virtual ~DrawPrimitive() {} virtual void POINTLIST() PURE; virtual void LINELIST() PURE; virtual void LINESTRIP() PURE; virtual void TRIANGLELIST() PURE; virtual void TRIANGLESTRIP() PURE; virtual void TRIANGLEFAN() PURE; }; virtual DrawPrimitive * drawPrimitive() PURE; virtual DrawPrimitive * drawPrimitive_positionOnly() PURE; }; }
[ "wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635" ]
[ [ [ 1, 37 ] ] ]
7f58bd1f86fe5e02833fb89b0c2e68d0c883c637
9773c3304eecc308671bcfa16b5390c81ef3b23a
/MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/MediaPlayerDlg.cpp
a78ece98cee5fb9da7a9c372753582aac18433c4
[]
no_license
15831944/AiPI-1
2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4
9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8
refs/heads/master
2021-12-02T20:34:03.136125
2011-10-27T00:07:54
2011-10-27T00:07:54
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
43,914
cpp
// MediaPlayerDlg.cpp : implementation file // #include "stdafx.h" #include <atlbase.h> #include "AIPI.h" #include "MediaPlayerDlg.h" #include "mp_playvideo.h" #include "mediatypes.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNAMIC(CMediaPlayerDlg, COXSizeDialogBar) ///////////////////////////////////////////////////////////////////////////// // CMediaPlayerDlg dialog CMediaPlayerDlg::CMediaPlayerDlg(CWnd* pParent /*=NULL*/) :COXSizeDialogBar(SZBARF_STDMOUSECLICKS|SZBARF_ALLOW_MDI_FLOAT|SZBARF_SOLIDGRIPPER) { //{{AFX_DATA_INIT(CMediaPlayerDlg) //}}AFX_DATA_INIT } void CMediaPlayerDlg::DoDataExchange(CDataExchange* pDX) { COXSizeDialogBar::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMediaPlayerDlg) DDX_Control(pDX, IDC_MP_SLIDER_VOLUME, m_MPVolumeSlider); DDX_Control(pDX, IDC_MP_SLIDER, m_MPSeekbar); DDX_Control(pDX, IDC_MP_EDIT_MEDIADIR, m_MPEditMediaDir); DDX_Control(pDX, IDC_MP_MOVIE_SCREEN, m_MPScreen); DDX_Control(pDX, IDC_MP_CHECK_FULLSCREEN, m_MPCheckFullScreen); DDX_Control(pDX, IDC_MP_CHECK_MUTE, m_MPCheckMute); DDX_Control(pDX, IDC_MP_BUTTON_BROWSE, m_MPButtonBrowse); DDX_Control(pDX, IDC_MP_BUTTON_STOP, m_MPButtonStop); DDX_Control(pDX, IDC_MP_BUTTON_PLAY, m_MPButtonPlay); DDX_Control(pDX, IDC_MP_BUTTON_PAUSE, m_MPButtonPause); DDX_Control(pDX, IDC_MP_CHECK_LOOP, m_MPCheckLoop); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMediaPlayerDlg, COXSizeDialogBar) //{{AFX_MSG_MAP(CMediaPlayerDlg) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_CLOSE() ON_BN_CLICKED(IDC_MP_BUTTON_PAUSE, OnPause) ON_BN_CLICKED(IDC_MP_BUTTON_PLAY, OnPlay) ON_BN_CLICKED(IDC_MP_BUTTON_STOP, OnStop) ON_BN_CLICKED(IDC_MP_BUTTON_BROWSE, OnButtonSetMediadir) ON_BN_CLICKED(IDC_MP_CHECK_MUTE, OnCheckMute) ON_BN_CLICKED(IDC_MP_CHECK_LOOP, OnCheckLoop) ON_WM_TIMER() ON_WM_DESTROY() ON_WM_ERASEBKGND() ON_BN_CLICKED(IDC_MP_CHECK_FULLSCREEN, OnCheckFullScreen) ON_BN_CLICKED(IDC_MP_MOVIE_SCREEN, OnMovieScreen) //ON_WM_CONTEXTMENU() //}}AFX_MSG_MAP ON_NOTIFY_EX(TTN_NEEDTEXT,0,DlgToolTips) // my tool tips handler END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMediaPlayerDlg message handlers void CMediaPlayerDlg::OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler) { COXSizeDialogBar::OnUpdateCmdUI(pTarget,FALSE); } ///////////////////////////////////////////////////////////////////////////// // CMediaPlayerDlg message handlers // 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 CMediaPlayerDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CenterVideo(); COXSizeDialogBar::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMediaPlayerDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } ///////////////////////////////////////////////////////////////////////////// // CMediaPlayerDlg DirectShow code and message handlers BOOL CMediaPlayerDlg::InitLayoutManager() { BOOL retval = TRUE; if(!m_LayoutManager.IsAttached()) { m_LayoutManager.Attach(this); m_LayoutManager.SetMinMax(IDC_MP_MOVIE_SCREEN, CSize(150,60), CSize(0,0)); //Constrain browse button m_LayoutManager.SetConstraint(IDC_MP_BUTTON_BROWSE, OX_LMS_BOTTOM, OX_LMT_SAME, -1); m_LayoutManager.SetConstraint(IDC_MP_BUTTON_BROWSE, OX_LMS_LEFT, OX_LMT_SAME, 1); //Constrain check full screen m_LayoutManager.SetConstraint(IDC_MP_CHECK_FULLSCREEN, OX_LMS_BOTTOM, OX_LMT_SAME, -1); m_LayoutManager.SetConstraint(IDC_MP_CHECK_FULLSCREEN, OX_LMS_RIGHT, OX_LMT_SAME, 1); //Constrain edit media dir m_LayoutManager.SetConstraint(IDC_MP_EDIT_MEDIADIR, OX_LMS_BOTTOM, OX_LMT_SAME, -1); m_LayoutManager.SetConstraint(IDC_MP_EDIT_MEDIADIR, OX_LMS_RIGHT, OX_LMT_OPPOSITE, -2, IDC_MP_CHECK_FULLSCREEN); m_LayoutManager.SetConstraint(IDC_MP_EDIT_MEDIADIR, OX_LMS_LEFT, OX_LMT_OPPOSITE, 1, IDC_MP_BUTTON_BROWSE); //Constrain button play m_LayoutManager.SetConstraint(IDC_MP_BUTTON_PLAY, OX_LMS_BOTTOM, OX_LMT_OPPOSITE, -2, IDC_MP_EDIT_MEDIADIR); m_LayoutManager.SetConstraint(IDC_MP_BUTTON_PLAY, OX_LMS_LEFT, OX_LMT_SAME, 1); m_LayoutManager.SetConstraint(IDC_MP_BUTTON_PLAY, OX_LMS_RIGHT, OX_LMT_POSITION, 22); //Constrain button stop m_LayoutManager.SetConstraint(IDC_MP_BUTTON_STOP, OX_LMS_BOTTOM, OX_LMT_OPPOSITE, -2, IDC_MP_EDIT_MEDIADIR); m_LayoutManager.SetConstraint(IDC_MP_BUTTON_STOP, OX_LMS_LEFT, OX_LMT_OPPOSITE, 1, IDC_MP_BUTTON_PLAY); m_LayoutManager.SetConstraint(IDC_MP_BUTTON_STOP, OX_LMS_RIGHT, OX_LMT_POSITION, 44); //Constrain button pause m_LayoutManager.SetConstraint(IDC_MP_BUTTON_PAUSE, OX_LMS_BOTTOM, OX_LMT_OPPOSITE, -2, IDC_MP_EDIT_MEDIADIR); m_LayoutManager.SetConstraint(IDC_MP_BUTTON_PAUSE, OX_LMS_LEFT, OX_LMT_OPPOSITE, 1, IDC_MP_BUTTON_STOP); m_LayoutManager.SetConstraint(IDC_MP_BUTTON_PAUSE, OX_LMS_RIGHT, OX_LMT_POSITION, 66); //Constrain static volume m_LayoutManager.SetConstraint(IDC_MP_STATIC_VOLUME, OX_LMS_BOTTOM, OX_LMT_OPPOSITE, -5, IDC_MP_EDIT_MEDIADIR); m_LayoutManager.SetConstraint(IDC_MP_STATIC_VOLUME, OX_LMS_RIGHT, OX_LMT_OPPOSITE, -5, IDC_MP_SLIDER_VOLUME); //Constrain slider volume m_LayoutManager.SetConstraint(IDC_MP_SLIDER_VOLUME, OX_LMS_BOTTOM, OX_LMT_OPPOSITE, -1, IDC_MP_EDIT_MEDIADIR); m_LayoutManager.SetConstraint(IDC_MP_SLIDER_VOLUME, OX_LMS_RIGHT, OX_LMT_SAME, -5); //Constrain check repeat m_LayoutManager.SetConstraint(IDC_MP_CHECK_LOOP, OX_LMS_BOTTOM, OX_LMT_OPPOSITE, -1, IDC_MP_SLIDER_VOLUME); m_LayoutManager.SetConstraint(IDC_MP_CHECK_LOOP, OX_LMS_RIGHT, OX_LMT_SAME, -5); //Constrain check mute m_LayoutManager.SetConstraint(IDC_MP_CHECK_MUTE, OX_LMS_BOTTOM, OX_LMT_OPPOSITE, -1, IDC_MP_SLIDER_VOLUME); m_LayoutManager.SetConstraint(IDC_MP_CHECK_MUTE, OX_LMS_RIGHT, OX_LMT_OPPOSITE, -10, IDC_MP_CHECK_LOOP); // Constrain the slider bar m_LayoutManager.SetConstraint(IDC_MP_SLIDER, OX_LMS_BOTTOM, OX_LMT_OPPOSITE, -2, IDC_MP_CHECK_LOOP); m_LayoutManager.SetConstraint(IDC_MP_SLIDER, OX_LMS_LEFT, OX_LMT_SAME, 0); m_LayoutManager.SetConstraint(IDC_MP_SLIDER, OX_LMS_RIGHT, OX_LMT_SAME, 0); // Constrain the movie screen m_LayoutManager.SetConstraint(IDC_MP_MOVIE_SCREEN, OX_LMS_TOP, OX_LMT_SAME, 0); m_LayoutManager.SetConstraint(IDC_MP_MOVIE_SCREEN, OX_LMS_BOTTOM, OX_LMT_OPPOSITE, 0, IDC_MP_SLIDER); m_LayoutManager.SetConstraint(IDC_MP_MOVIE_SCREEN, OX_LMS_LEFT, OX_LMT_SAME, 0); m_LayoutManager.SetConstraint(IDC_MP_MOVIE_SCREEN, OX_LMS_RIGHT, OX_LMT_SAME, 0); } return retval; } BOOL CMediaPlayerDlg::OnInitDialog() { COXSizeDialogBar::OnInitDialog(); /* LANGID dwLanguageID = GetSystemLanguagePrimaryID(); switch( dwLanguageID) { case LANG_SPANISH: CWnd::SetWindowText(_T("MediaPlayer")); GetDlgItem(IDC_MP_CHECK_LOOP)->SetWindowText(_T("Repetir")); GetDlgItem(IDC_MP_CHECK_MUTE)->SetWindowText(_T("Silencio")); GetDlgItem(IDC_MP_CHECK_FULLSCREEN)->SetWindowText(_T("Pantalla completa")); break; default: CWnd::SetWindowText(_T("MediaPlayer")); GetDlgItem(IDC_MP_CHECK_LOOP)->SetWindowText(_T("Repeat")); GetDlgItem(IDC_MP_CHECK_MUTE)->SetWindowText(_T("Mute")); GetDlgItem(IDC_MP_CHECK_FULLSCREEN)->SetWindowText(_T("Full screen")); break; } //Resize Controls AddSzControl(IDC_MP_STATIC_VOLUME, mdRelative, mdRepos); AddSzControl(IDC_MP_SLIDER, mdResize, mdRepos); AddSzControl(IDC_MP_SLIDER_VOLUME, mdRelative, mdRepos); AddSzControl(IDC_MP_MOVIE_SCREEN, mdResize, mdResize); AddSzControl(IDC_MP_BUTTON_PLAY, mdRelative, mdRepos); AddSzControl(IDC_MP_BUTTON_STOP, mdRelative, mdRepos); AddSzControl(IDC_MP_BUTTON_PAUSE, mdRelative, mdRepos); AddSzControl(IDC_MP_CHECK_LOOP, mdRepos, mdRepos); AddSzControl(IDC_MP_CHECK_MUTE, mdRepos, mdRepos); AddSzControl(IDC_MP_CHECK_FULLSCREEN, mdRepos, mdRepos); AddSzControl(IDC_MP_EDIT_MEDIADIR, mdResize, mdRepos); //Add icons hPlay= LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_MEDIAPLAYER_PLAY)); hPause= LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_MEDIAPLAYER_PAUSE)); hStop= LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_MEDIAPLAYER_STOP)); m_MPButtonPlay.SetIcon(hPlay); m_MPButtonPause.SetIcon(hPause); m_MPButtonStop.SetIcon(hStop); */ if(!InitLayoutManager()) { MessageBox(_T("Failed to init layout manager!")); } UpdateData(FALSE); //////////////////////////////////////////////////////////////////////// // // DirectShow-specific initialization code // Initialize COM CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); // Initialize DirectShow and query for needed interfaces HRESULT hr = InitDirectShow(); if(FAILED(hr)) { MPRetailOutput(TEXT("Failed to initialize DirectShow! hr=0x%x\r\n"), hr); return FALSE; } // IMPORTANT // Since we're embedding video in a child window of a dialog, // we must set the WS_CLIPCHILDREN style to prevent the bounding // rectangle from drawing over our video frames. // // Neglecting to set this style can lead to situations when the video // is erased and replaced with black (or the default color of the // bounding rectangle). m_MPScreen.ModifyStyle(0, WS_CLIPCHILDREN); // Initialize seeking trackbar range m_MPSeekbar.SetRange(0, 100, TRUE); m_MPSeekbar.SetTicFreq(5); //Current Volume g_lCurrentVolume_MP = MP_VOLUME_FULL; //Current Window size g_bFullScreen_MP = FALSE; //Set the Slider m_MPVolumeSlider.SetRange(0, MP_MINIMUM_VOLUME, TRUE); //SetMediadir(); EnableToolTips(); return TRUE; // return TRUE unless you set the focus to a control } LONG CMediaPlayerDlg::GetDXMediaPath(TCHAR *szPath, DWORD dwPathSize) { HKEY hKey=0; DWORD dwType=0, dwValueSize=dwPathSize; // Open the appropriate registry key LONG lResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\DirectX SDK"), 0, KEY_READ, &hKey ); if( ERROR_SUCCESS != lResult ) return -1; // Start with DirectX9 SDK lResult = RegQueryValueEx( hKey, _T("DX9SDK Samples Path"), NULL, &dwType, (BYTE*)szPath, &dwValueSize ); if( ERROR_SUCCESS != lResult ) { // Next try DirectX 8.1 SDK lResult = RegQueryValueEx( hKey, _T("DX81SDK Samples Path"), NULL, &dwType, (BYTE*)szPath, &dwValueSize ); if( ERROR_SUCCESS != lResult ) { // Finally, try DirectX 8.0 SDK lResult = RegQueryValueEx( hKey, _T("DX8SDK Samples Path"), NULL, &dwType, (BYTE*)szPath, &dwValueSize ); if( ERROR_SUCCESS != lResult ) { RegCloseKey( hKey ); return -1; } } } RegCloseKey( hKey ); // Now that we have the location of the installed SDK samples path, // append the name of the folder where media files are stored. // Make sure that the szPath string has enough space to hold the // full SDK samples path plus the "\Media\" string. if ((_tcslen(szPath) + MP_STR_MEDIA_FOLDER_SIZE) < dwPathSize ) { _tcscat( szPath, MP_STR_MEDIA_FOLDER ); return 0; } else return -1; } void CMediaPlayerDlg::OnClose() { // Release DirectShow interfaces MPStopMedia(); FreeDirectShow(); g_bFullScreen_MP = FALSE; // Release COM CoUninitialize(); COXSizeDialogBar::OnClose(); } void CMediaPlayerDlg::OnDestroy() { FreeDirectShow(); COXSizeDialogBar::OnDestroy(); } void CMediaPlayerDlg::OnButtonSetMediadir() { CFileDialog dlgFile(TRUE); CString title; CString strFilter, strDefault, strFilename; VERIFY(title.LoadString(AFX_IDS_OPENFILE)); // Initialize the file extensions and descriptions strFilter += "Media Files (*.avi, *.mpg, *.wav, *.mid, *.mpeg)\0"; strFilter += (TCHAR)'\0'; strFilter += _T("*.avi;*.mpg;*.wav;*.mid;*.mpeg\0"); strFilter += (TCHAR)'\0'; dlgFile.m_ofn.nMaxCustFilter++; CString allFilter; VERIFY(allFilter.LoadString(AFX_IDS_ALLFILTER)); // Append the "*.*" all files filter strFilter += allFilter; strFilter += (TCHAR)'\0'; // next string strFilter += _T("*.*\0"); strFilter += (TCHAR)'\0\0'; // last string dlgFile.m_ofn.nMaxCustFilter++; dlgFile.m_ofn.lpstrFilter = strFilter; dlgFile.m_ofn.lpstrTitle = title; dlgFile.m_ofn.lpstrFile = strFilename.GetBuffer(_MAX_PATH); // Display the file open dialog INT_PTR nResult = dlgFile.DoModal(); // If a file was selected, update the main dialog if (nResult == IDOK) { m_MPEditMediaDir.SetWindowText(strFilename); // Render this file and show the first video frame, if present OnSelectFile(); } strFilename.ReleaseBuffer(); m_MPCheckFullScreen.EnableWindow(true); // Don't bother with full-screen for audio-only files if ((g_bAudioOnly_MP) || (!pVW_MP)) { m_MPCheckFullScreen.EnableWindow(false); return; } } void CMediaPlayerDlg::OnSelectFile() { HRESULT hr; TCHAR szFilename[MAX_PATH]; // Read file name from Edit control m_MPEditMediaDir.GetWindowText(szFilename, MAX_PATH); // Remember current play state to restart playback int nCurrentState = g_psCurrent_MP; // First release any existing interfaces ResetDirectShow(); // Load the selected media file hr = PrepareMedia(szFilename); if (FAILED(hr)) { // Error - disable play button and give feedback switch(languagePrimaryID) { case LANG_SPANISH: MessageBox(TEXT("¡Fallo en interpretación de fichero!")); break; default: MessageBox(TEXT("File failed to render!")); break; } m_MPButtonPlay.EnableWindow(FALSE); FreeDirectShow(); MessageBeep(0); return; } else { m_MPButtonPlay.EnableWindow(TRUE); } // Set up the seeking trackbar and read capabilities ConfigureSeekbar(); // Read the current volume slider setting so that the current // global volume will be preserved m_MPVolumeSlider.EnableWindow(TRUE); HandleVolumeSlider(0); // If the user has asked to mute audio then we // need to mute this new clip before continuing. if (g_bGlobalMute_MP) MPMuteAudio(); // If we were running when the user changed selection, // start running the newly selected clip if (nCurrentState == State_Running) { OnPlay(); } else { // Cue the first video frame OnStop(); } } BOOL CMediaPlayerDlg::IsWindowsMediaFile(LPTSTR lpszFile) { TCHAR szFilename[MAX_PATH]; // Copy the file name to a local string and convert to lowercase _tcsncpy(szFilename, lpszFile, NUMELMS(szFilename)); szFilename[MAX_PATH-1] = 0; _tcslwr(szFilename); if (_tcsstr(szFilename, TEXT(".asf")) || _tcsstr(szFilename, TEXT(".wma")) || _tcsstr(szFilename, TEXT(".wmv"))) return TRUE; else return FALSE; } HRESULT CMediaPlayerDlg::PrepareMedia(LPTSTR lpszMovie) { USES_CONVERSION; HRESULT hr = S_OK; // Is this a Windows Media file (ASF, WMA, WMV)? If so, use the new // ASF Reader filter, which is faster and much better at seeking than // the default ASF Reader filter used by default with RenderFile. if (IsWindowsMediaFile(lpszMovie)) { hr = RenderWMFile(T2W(lpszMovie)); if (FAILED(hr)) { MPRetailOutput(TEXT("*** Failed(%08lx) to Render WM File(%s)!\r\n"), hr, lpszMovie); return hr; } } else { // Allow DirectShow to create the FilterGraph for this media file hr = pGB_MP->RenderFile(T2W(lpszMovie), NULL); if (FAILED(hr)) { MPRetailOutput(TEXT("*** Failed(%08lx) in RenderFile(%s)!\r\n"), hr, lpszMovie); return hr; } } // Set the message drain of the video window to point to our main // application window. If this is an audio-only or MIDI file, // then put_MessageDrain will fail. hr = pVW_MP->put_MessageDrain((OAHWND) m_hWnd); if (FAILED(hr)) { g_bAudioOnly_MP = TRUE; } // Have the graph signal event via window callbacks hr = pME_MP->SetNotifyWindow((OAHWND)m_hWnd, WM_GRAPHNOTIFY, 0); // Configure the video window if (!g_bAudioOnly_MP) { // We'll manually set the video to be visible hr = pVW_MP->put_Visible(OAFALSE); hr = pVW_MP->put_WindowStyle(WS_CHILD); hr = pVW_MP->put_Owner((OAHWND) m_MPScreen.GetSafeHwnd()); // Place video window within the bounding rectangle CenterVideo(); // Make the video window visible within the screen window. // If this is an audio-only file, then there won't be a video interface. hr = pVW_MP->put_Visible(OATRUE); hr = pVW_MP->SetWindowForeground(-1); } return hr; } HRESULT CMediaPlayerDlg::RenderWMFile(LPCWSTR wFile) { HRESULT hr=S_OK; IFileSourceFilter *pFS=NULL; IBaseFilter *pReader=NULL; // Load the improved ASF reader filter by CLSID hr = CreateFilter(CLSID_WMAsfReader, &pReader); if(FAILED(hr)) { MPRetailOutput(TEXT("Failed to create WMAsfWriter filter! hr=0x%x\n"), hr); return hr; } // Add the ASF reader filter to the graph. For ASF/WMV/WMA content, // this filter is NOT the default and must be added explicitly. hr = pGB_MP->AddFilter(pReader, L"ASF Reader"); if(FAILED(hr)) { MPRetailOutput(TEXT("Failed to add ASF reader filter to graph! hr=0x%x\n"), hr); pReader->Release(); return hr; } // // Windows Media 9 Series (code named 'Corona') no longer requires // a stub library. If using WMF9, we don't need to provide a CKeyProvider // implementation, and we don't need to link with the WMStub.lib library. // #ifndef TARGET_WMF9 // Create the key provider that will be used to unlock the WM SDK JIF(AddKeyProvider(pGB_MP)); #endif // Set its source filename JIF(pReader->QueryInterface(IID_IFileSourceFilter, (void **) &pFS)); JIF(pFS->Load(wFile, NULL)); pFS->Release(); CLEANUP: // If there was a rendering error, make sure that the reader is released // // Otherwise, wince the graph is built and the filters are added to // the graph, the WM ASF reader interface can be released. SAFE_RELEASE(pReader); return hr; } HRESULT CMediaPlayerDlg::CreateFilter(REFCLSID clsid, IBaseFilter **ppFilter) { HRESULT hr; hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void **) ppFilter); if(FAILED(hr)) { MPRetailOutput(TEXT("CreateFilter: Failed to create filter! hr=0x%x\n"), hr); *ppFilter = NULL; return hr; } return S_OK; } // Windows Media 9 Series (code named 'Corona') no longer requires // a stub library. If using WMF9, we don't need to provide a CKeyProvider // implementation, and we don't need to link with the WMStub.lib library. // #ifndef TARGET_WMF9 HRESULT CMediaPlayerDlg::AddKeyProvider(IGraphBuilder *pGraph) { HRESULT hr; // Instantiate the key provider class, and AddRef it // so that COM doesn't try to free our static object. prov.AddRef(); // Don't let COM try to free our static object. // Give the graph an IObjectWithSite pointer to us for callbacks & QueryService. IObjectWithSite* pObjectWithSite = NULL; hr = pGraph->QueryInterface(IID_IObjectWithSite, (void**)&pObjectWithSite); if (SUCCEEDED(hr)) { // Use the IObjectWithSite pointer to specify our key provider object. // The filter graph manager will use this pointer to call // QueryService to do the unlocking. // If the unlocking succeeds, then we can build our graph. hr = pObjectWithSite->SetSite((IUnknown *) (IServiceProvider *) &prov); pObjectWithSite->Release(); } return hr; } #endif void CMediaPlayerDlg::OnPause() { if (g_psCurrent_MP == State_Paused) { MPRunMedia(); StartSeekTimer(); } else { StopSeekTimer(); MPPauseMedia(); } } void CMediaPlayerDlg::OnPlay() { MPRunMedia(); StartSeekTimer(); } void CMediaPlayerDlg::OnStop() { HRESULT hr; if (!pMC_MP || !pMS_MP) return; // Stop playback immediately with IMediaControl::Stop(). StopSeekTimer(); MPStopMedia(); // Wait for the stop to propagate to all filters OAFilterState fs; hr = pMC_MP->GetState(500, &fs); if (FAILED(hr)) { MPRetailOutput(TEXT("Failed to read graph state! hr=0x%x\r\n"), hr); } // Reset to beginning of media clip LONGLONG pos=0; hr = pMS_MP->SetPositions(&pos, AM_SEEKING_AbsolutePositioning , NULL, AM_SEEKING_NoPositioning); if (FAILED(hr)) { MPRetailOutput(TEXT("Failed to seek to beginning of media! hr=0x%x\r\n"), hr); } // Display the first frame of the media clip, if it contains video. // StopWhenReady() pauses all filters internally (which allows the video // renderer to queue and display the first video frame), after which // it sets the filters to the stopped state. This enables easy preview // of the video's poster frame. hr = pMC_MP->StopWhenReady(); if (FAILED(hr)) { MPRetailOutput(TEXT("Failed in StopWhenReady! hr=0x%x\r\n"), hr); } // Reset slider bar and position label back to zero ReadMediaPosition(); } HRESULT CMediaPlayerDlg::InitDirectShow(void) { HRESULT hr = S_OK; g_bAudioOnly_MP = FALSE; // Zero interfaces (sanity check) pVW_MP = NULL; pBV_MP = NULL; JIF(CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC, IID_IGraphBuilder, (void **)&pGB_MP)); JIF(pGB_MP->QueryInterface(IID_IMediaControl, (void **)&pMC_MP)); JIF(pGB_MP->QueryInterface(IID_IMediaSeeking, (void **)&pMS_MP)); JIF(pGB_MP->QueryInterface(IID_IBasicVideo, (void **)&pBV_MP)); JIF(pGB_MP->QueryInterface(IID_IVideoWindow, (void **)&pVW_MP)); JIF(pGB_MP->QueryInterface(IID_IMediaEventEx, (void **)&pME_MP)); JIF(pGB_MP->QueryInterface(IID_IBasicAudio, (void **)&pBA_MP)); return S_OK; CLEANUP: FreeDirectShow(); return(hr); } HRESULT CMediaPlayerDlg::FreeDirectShow(void) { HRESULT hr=S_OK; StopSeekTimer(); MPStopMedia(); // Remember the current volume slider position so that the // same volume level can be applied to the next clip HandleVolumeSlider(0); // Disable event callbacks if (pME_MP) hr = pME_MP->SetNotifyWindow((OAHWND)NULL, 0, 0); // Hide video window and remove owner. This is not necessary here, // since we are about to destroy the filter graph, but it is included // for demonstration purposes. Remember to hide the video window and // clear its owner when destroying a window that plays video. if(pVW_MP) { hr = pVW_MP->put_Visible(OAFALSE); hr = pVW_MP->put_Owner(NULL); } SAFE_RELEASE(pMC_MP); SAFE_RELEASE(pMS_MP); SAFE_RELEASE(pVW_MP); SAFE_RELEASE(pBV_MP); SAFE_RELEASE(pME_MP); SAFE_RELEASE(pGB_MP); SAFE_RELEASE(pBA_MP); return hr; } void CMediaPlayerDlg::ResetDirectShow(void) { // Destroy the current filter graph its filters. FreeDirectShow(); // Reinitialize graph builder and query for interfaces InitDirectShow(); } void CMediaPlayerDlg::CenterVideo(void) { LONG width, height; HRESULT hr; if ((g_bAudioOnly_MP) || (!pVW_MP)) return; // Read coordinates of video container window RECT rc; m_MPScreen.GetClientRect(&rc); width = rc.right - rc.left; height = rc.bottom - rc.top; // Ignore the video's original size and stretch to fit bounding rectangle hr = pVW_MP->SetWindowPosition(rc.left, rc.top, width, height); if (FAILED(hr)) { MPRetailOutput(TEXT("Failed to set window position! hr=0x%x\r\n"), hr); return; } } LRESULT CMediaPlayerDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { // Field notifications from the DirectShow filter graph manager // and those posted by the application switch (message) { case WM_GRAPHNOTIFY: HandleGraphEvent(); break; case WM_HSCROLL: HandleTrackbar(LOWORD(wParam)); break; case WM_VSCROLL: HandleVolumeSlider(LOWORD(wParam)); break; case WM_PLAYFILE: PlaySelectedFile(); break; case WM_KEYDOWN: switch(LOWORD(wParam)) { case 'P': OnPlay(); break; case 'S': OnStop(); break; case 'U': OnPause(); break; case 'L': OnCheckLoop(); break; case 'M': OnCheckMute(); break; case VK_ESCAPE: if (g_bFullScreen_MP) OnCheckFullScreen(); else OnClose(); break; } break; case WM_CLOSE: FreeDirectShow(); break; } // Pass along this message to the video window, which exists as a child // of the m_MPScreen window. This method should be used by windows that // make a renderer window a child window. It forwards significant messages // to the child window that the child window would not otherwise receive. if (pVW_MP) { pVW_MP->NotifyOwnerMessage((LONG_PTR) m_hWnd, message, wParam, lParam); } return COXSizeDialogBar::WindowProc(message, wParam, lParam); } HRESULT CMediaPlayerDlg::HandleGraphEvent(void) { LONG evCode, evParam1, evParam2; HRESULT hr=S_OK; // Since we may have a scenario where we're shutting down the application, // but events are still being generated, make sure that the event // interface is still valid before using it. It's possible that // the interface could be freed during shutdown but later referenced in // this callback before the app completely exits. if (!pME_MP) return S_OK; while(SUCCEEDED(pME_MP->GetEvent(&evCode, (LONG_PTR *) &evParam1, (LONG_PTR *) &evParam2, 0))) { // Spin through the events if(EC_COMPLETE == evCode) { // If looping, reset to beginning and continue playing if (g_bLooping_MP) { LONGLONG pos=0; // Reset to first frame of movie hr = pMS_MP->SetPositions(&pos, AM_SEEKING_AbsolutePositioning , NULL, AM_SEEKING_NoPositioning); if (FAILED(hr)) { // Some custom filters (like the Windows CE MIDI filter) // may not implement seeking interfaces (IMediaSeeking) // to allow seeking to the start. In that case, just stop // and restart for the same effect. This should not be // necessary in most cases. MPStopMedia(); MPRunMedia(); } } else { // Stop playback and display first frame of movie OnStop(); } } // Free memory associated with this event hr = pME_MP->FreeEventParams(evCode, evParam1, evParam2); } return hr; } void CMediaPlayerDlg::OnCheckMute() { // Remember global mute status for next file. When you destroy a // filtergraph, you lose all of its audio settings. Therefore, when // we create the next graph, we will mute the audio before running // the graph if this global variable is set. g_bGlobalMute_MP ^= 1; if (g_bGlobalMute_MP) { MPMuteAudio(); m_MPVolumeSlider.EnableWindow(FALSE); } else { MPResumeAudio(); if (pBA_MP) m_MPVolumeSlider.EnableWindow(TRUE); } } void CMediaPlayerDlg::OnCheckLoop() { g_bLooping_MP ^= 1; } void CMediaPlayerDlg::SetMediaDir(CString strFileName) { //CString strFilename; //strFilename = TEXT("F:\\VIDEOS\\IzabellaScorupco\\Exorcist__the_Beginning_Izabella_Scorupco.avi"); //strFilename = TEXT("E:\\Mis documentos\\Mis imágenes\\Batman_Dead_End.mov"); m_MPEditMediaDir.SetWindowText(strFileName); // Render this file and show the first video frame, if present OnSelectFile(); strFileName.ReleaseBuffer(); } void CMediaPlayerDlg::PlaySelectedFile() { OnPlay(); } // The GraphBuilder interface provides a FindFilterByName() method, // which provides similar functionality to the method below. // This local method is provided for educational purposes. // IBaseFilter *CMediaPlayerDlg::FindFilterFromName(LPTSTR szNameToFind) { USES_CONVERSION; HRESULT hr; IEnumFilters *pEnum = NULL; IBaseFilter *pFilter = NULL; ULONG cFetched; BOOL bFound = FALSE; // Get filter enumerator hr = pGB_MP->EnumFilters(&pEnum); if (FAILED(hr)) return NULL; // Enumerate all filters in the graph while((pEnum->Next(1, &pFilter, &cFetched) == S_OK) && (!bFound)) { FILTER_INFO FilterInfo; TCHAR szName[256]; hr = pFilter->QueryFilterInfo(&FilterInfo); if (FAILED(hr)) { pFilter->Release(); pEnum->Release(); return NULL; } // Compare this filter's name with the one we want lstrcpy(szName, W2T(FilterInfo.achName)); if (! lstrcmp(szName, szNameToFind)) { bFound = TRUE; } FilterInfo.pGraph->Release(); // If we found the right filter, don't release its interface. // The caller will use it and release it later. if (!bFound) pFilter->Release(); else break; } pEnum->Release(); return (bFound ? pFilter : NULL); } BOOL CMediaPlayerDlg::SupportsPropertyPage(IBaseFilter *pFilter) { HRESULT hr; ISpecifyPropertyPages *pSpecify; // Discover if this filter contains a property page hr = pFilter->QueryInterface(IID_ISpecifyPropertyPages, (void **)&pSpecify); if (SUCCEEDED(hr)) { pSpecify->Release(); return TRUE; } else return FALSE; } // // Some hardware decoders and video renderers support stepping media // frame by frame with the IVideoFrameStep interface. See the interface // documentation for more details on frame stepping. // BOOL CMediaPlayerDlg::CanStep(void) { HRESULT hr; IVideoFrameStep* pFS; hr = pGB_MP->QueryInterface(__uuidof(IVideoFrameStep), (PVOID *)&pFS); if (FAILED(hr)) return FALSE; // Check if this decoder can step hr = pFS->CanStep(0L, NULL); pFS->Release(); if (hr == S_OK) return TRUE; else return FALSE; } void CMediaPlayerDlg::ConfigureSeekbar() { // Disable seekbar for new file and reset tracker/position label m_MPSeekbar.SetPos(0); g_rtTotalTime=0; // If we can't read the file's duration, disable the seek bar if (pMS_MP && SUCCEEDED(pMS_MP->GetDuration(&g_rtTotalTime))) m_MPSeekbar.EnableWindow(TRUE); else m_MPSeekbar.EnableWindow(FALSE); } void CMediaPlayerDlg::StartSeekTimer() { // Cancel any pending timer event StopSeekTimer(); // Create a new timer g_wTimerID = SetTimer(MP_TIMERID, MP_TICKLEN, NULL); } void CMediaPlayerDlg::StopSeekTimer() { // Cancel the timer if(g_wTimerID) { KillTimer(g_wTimerID); g_wTimerID = 0; } } void CMediaPlayerDlg::OnTimer(UINT nIDEvent) { ReadMediaPosition(); COXSizeDialogBar::OnTimer(nIDEvent); } void CMediaPlayerDlg::ReadMediaPosition() { HRESULT hr; REFERENCE_TIME rtNow; if (!pMS_MP) return; // Read the current stream position hr = pMS_MP->GetCurrentPosition(&rtNow); if (FAILED(hr)) return; // Convert position into a percentage value and update slider position if (g_rtTotalTime != 0) { long lTick = (long)((rtNow * 100) / g_rtTotalTime); m_MPSeekbar.SetPos(lTick); } else m_MPSeekbar.SetPos(0); } void CMediaPlayerDlg::HandleVolumeSlider(WPARAM wReq) { HRESULT hr=S_OK; long lVolume; // Disregard ENDSCROLL messages, which are redundant if ((!pBA_MP) || (wReq == SB_ENDSCROLL)) return; // Since the IBasicAudio interface adjusts volume on a logarithmic // scale from -10000 to 0, volumes below -4000 sound like silence. // Therefore, the slider covers a smaller range. int nPosition = m_MPVolumeSlider.GetPos(); // Since slider goes from MINIMUM_VOLUME to 0, use the negative value lVolume = -1 * nPosition; // Save current volume to global variable for use with Mute/Resume audio g_lCurrentVolume_MP = lVolume; // Set new volume hr = pBA_MP->put_Volume(lVolume); } void CMediaPlayerDlg::HandleVolumeUp(WPARAM wReq) { HRESULT hr=S_OK; long lVolume; // Disregard ENDSCROLL messages, which are redundant if ((!pBA_MP) || (wReq == SB_ENDSCROLL)) return; // Since the IBasicAudio interface adjusts volume on a logarithmic // scale from -10000 to 0, volumes below -4000 sound like silence. // Therefore, the slider covers a smaller range. int nPosition = m_MPVolumeSlider.GetPos(); // Since slider goes from MINIMUM_VOLUME to 0, use the negative value lVolume = -1 * nPosition++; m_MPVolumeSlider.SetPos( nPosition); // Save current volume to global variable for use with Mute/Resume audio g_lCurrentVolume_MP = lVolume; // Set new volume hr = pBA_MP->put_Volume(lVolume); } void CMediaPlayerDlg::HandleVolumeDown(WPARAM wReq) { HRESULT hr=S_OK; long lVolume; // Disregard ENDSCROLL messages, which are redundant if ((!pBA_MP) || (wReq == SB_ENDSCROLL)) return; // Since the IBasicAudio interface adjusts volume on a logarithmic // scale from -10000 to 0, volumes below -4000 sound like silence. // Therefore, the slider covers a smaller range. int nPosition = m_MPVolumeSlider.GetPos(); // Since slider goes from MINIMUM_VOLUME to 0, use the negative value lVolume = -1 * nPosition; // Save current volume to global variable for use with Mute/Resume audio g_lCurrentVolume_MP = lVolume; // Set new volume hr = pBA_MP->put_Volume(lVolume); } void CMediaPlayerDlg::HandleTrackbar(WPARAM wReq) { HRESULT hr; static OAFilterState state; static BOOL bStartOfScroll = TRUE; if ((!pMS_MP) || (!pMC_MP)) return; // If the file is not seekable, the trackbar is disabled. DWORD dwPosition = m_MPSeekbar.GetPos(); // Pause when the scroll action begins. if (bStartOfScroll) { hr = pMC_MP->GetState(10, &state); bStartOfScroll = FALSE; hr = pMC_MP->Pause(); } // Update the position continuously. REFERENCE_TIME rtNew = (g_rtTotalTime * dwPosition) / 100; hr = pMS_MP->SetPositions(&rtNew, AM_SEEKING_AbsolutePositioning, NULL, AM_SEEKING_NoPositioning); // Restore the state at the end. if (wReq == TB_ENDTRACK) { if (state == State_Stopped) hr = pMC_MP->Stop(); else if (state == State_Running) hr = pMC_MP->Run(); bStartOfScroll = TRUE; } } void CMediaPlayerDlg::OnSizedOrDocked(int cx, int cy, BOOL bFloating, int flags) { UNREFERENCED_PARAMETER(bFloating); UNREFERENCED_PARAMETER(flags); UNREFERENCED_PARAMETER(cx); UNREFERENCED_PARAMETER(cy); m_LayoutManager.RedrawLayout(); } BOOL CMediaPlayerDlg::OnEraseBkgnd(CDC *pDC) { // Intercept background erasing for the movie window, since the // video renderer will keep the screen painted. Without this code, // your video window might get painted over with gray (the default // background brush) when it is obscured by another window and redrawn. CRect rc; // Get the bounding rectangle for the movie screen m_MPScreen.GetWindowRect(&rc); ScreenToClient(&rc); // Exclude the clipping region occupied by our movie screen pDC->ExcludeClipRect(&rc); // Erase the remainder of the dialog as usual return COXSizeDialogBar::OnEraseBkgnd(pDC); } void CMediaPlayerDlg::OnCheckFullScreen() { MPToggleFullScreen(); m_MPCheckFullScreen.SetCheck(0); } void CMediaPlayerDlg::OnMovieScreen() { OnCheckFullScreen(); } BOOL CMediaPlayerDlg::DlgToolTips(UINT id, NMHDR * pNMHDR, LRESULT * pResult ) { LANGID dwLanguageID = GetSystemLanguagePrimaryID(); TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *)pNMHDR; UINT nID = pTTT->uFlags; if(pTTT->uFlags & TTF_IDISHWND) { nID= ::GetDlgCtrlID((HWND)nID); if(!nID) { HWND hWndPlay = m_MPButtonPlay.GetSafeHwnd(); HWND hWndStop = m_MPButtonStop.GetSafeHwnd(); HWND hWndPause = m_MPButtonPause.GetSafeHwnd(); HWND hWndMute = m_MPCheckMute.GetSafeHwnd(); HWND hWndLoop = m_MPCheckLoop.GetSafeHwnd(); HWND hWndFullScreen = m_MPCheckFullScreen.GetSafeHwnd(); HWND hWndVolume = m_MPVolumeSlider.GetSafeHwnd(); HWND hWndSeekBar = m_MPSeekbar.GetSafeHwnd(); //Show tooltip Play if((HWND)(pNMHDR->idFrom) == hWndPlay) { switch(dwLanguageID) { case LANG_SPANISH: pTTT->lpszText = _T("Reproducir [R]"); break; default : pTTT->lpszText = _T("Play [P]"); break; } return TRUE; } //Show tooltip Stop if((HWND)(pNMHDR->idFrom) == hWndStop) { switch(dwLanguageID) { case LANG_SPANISH: pTTT->lpszText = _T("Detener [D]"); break; default : pTTT->lpszText = _T("Stop [S]"); break; } return TRUE; } //Show tooltip Pause if((HWND)(pNMHDR->idFrom) == hWndPause) { switch(dwLanguageID) { case LANG_SPANISH: pTTT->lpszText = _T("Pausar [P]"); break; default : pTTT->lpszText = _T("Pause [U]"); break; } return TRUE; } //Show tooltip Mute if((HWND)(pNMHDR->idFrom) == hWndMute) { switch(dwLanguageID) { case LANG_SPANISH: pTTT->lpszText = _T("Silencio [S]"); break; default : pTTT->lpszText = _T("Mute [M]"); break; } return TRUE; } //Show tooltip Loop if((HWND)(pNMHDR->idFrom) == hWndLoop) { switch(dwLanguageID) { case LANG_SPANISH: pTTT->lpszText = _T("Repetir [I]"); break; default : pTTT->lpszText = _T("Loop [L]"); break; } return TRUE; } //Show tooltip FullScreen if((HWND)(pNMHDR->idFrom) == hWndFullScreen) { switch(dwLanguageID) { case LANG_SPANISH: pTTT->lpszText = _T("Pantalla completa [C] Abandonar [Alt+Esc]"); break; default : pTTT->lpszText = _T("FullScreen [F] Quit [Alt+Esc]"); break; } return TRUE; } //Show tooltip Volume if((HWND)(pNMHDR->idFrom) == hWndVolume) { switch(dwLanguageID) { case LANG_SPANISH: pTTT->lpszText = _T("Volumen"); break; default : pTTT->lpszText = _T("Volume"); break; } return TRUE; } //Show tooltip Seekbar if((HWND)(pNMHDR->idFrom) == hWndSeekBar) { switch(dwLanguageID) { case LANG_SPANISH: pTTT->lpszText = _T("Buscar"); break; default : pTTT->lpszText = _T("Find"); break; } return TRUE; } } } return FALSE; } static CString GetShort(UINT id) { CString str; str.LoadString(id); int nIndex = str.ReverseFind(_T('\n')); if(nIndex!=-1) { str=str.Mid(nIndex+1); } return str; } /* void CMediaPlayerDlg::OnContextMenu(CWnd* pWnd, CPoint point) { UNREFERENCED_PARAMETER(pWnd); if(point.x==-1 && point.y==-1) { CRect rect; GetWindowRect(rect); point = rect.TopLeft()+CPoint(10,10); } SetFocus(); CNewMenu menu; menu.CreatePopupMenu(); menu.InsertMenu(0, MF_BYPOSITION ,ID_CTRL_MEDIAPLAYER_PLAY , GetShort(ID_CTRL_MEDIAPLAYER_PLAY)); menu.InsertMenu(1, MF_BYPOSITION , ID_CTRL_MEDIAPLAYER_STOP, GetShort(ID_CTRL_MEDIAPLAYER_STOP)); menu.InsertMenu(2, MF_BYPOSITION , ID_CTRL_MEDIAPLAYER_PAUSE, GetShort(ID_CTRL_MEDIAPLAYER_PAUSE)); menu.InsertMenu(3, MF_BYPOSITION|MF_SEPARATOR); menu.InsertMenu(4, MF_BYPOSITION ,ID_CTRL_MEDIAPLAYER_MUTE , GetShort(ID_CTRL_MEDIAPLAYER_MUTE)); menu.InsertMenu(5, MF_BYPOSITION ,ID_CTRL_MEDIAPLAYER_LOOP , GetShort(ID_CTRL_MEDIAPLAYER_LOOP)); menu.InsertMenu(6, MF_BYPOSITION ,ID_CTRL_MEDIAPLAYER_FULLSCREEN , GetShort(ID_CTRL_MEDIAPLAYER_FULLSCREEN)); menu.SetMenuTitle(_T("MediaPlayer"),MFT_GRADIENT|MFT_SIDE_TITLE); menu.LoadToolBar(IDR_MEDIAPLAYERDLG); menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, point.x, point.y, AfxGetMainWnd()); } */
[ [ [ 1, 1583 ] ] ]
9bc7e5a12644b204fa7d12a3020cebfc2c388c45
6581dacb25182f7f5d7afb39975dc622914defc7
/VCCapture/CatchScreen.h
e8b321913b58668305e41c44361a4400733a8550
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,409
h
// CatchScreen.h : main header file for the CATCHSCREEN application // #if !defined(AFX_CATCHSCREEN_H__54FC5DBC_639B_4E2B_A70B_249707411760__INCLUDED_) #define AFX_CATCHSCREEN_H__54FC5DBC_639B_4E2B_A70B_249707411760__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CCatchScreenApp: // See CatchScreen.cpp for the implementation of this class // class CCatchScreenApp : public CWinApp { public: CCatchScreenApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCatchScreenApp) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CCatchScreenApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CATCHSCREEN_H__54FC5DBC_639B_4E2B_A70B_249707411760__INCLUDED_)
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 50 ] ] ]
d5c0e43fdb46d4427368e38712949dcdb2ee494d
f2cbdee1dfdcad7b77c597e1af5f40ad83bad4aa
/MyC++/fstream/test.cpp
5b41a33e9891af46f2c668602899ad0974244be0
[]
no_license
jdouglas71/Examples
d03d9effc414965991ca5b46fbcf808a9dd6fe6d
b7829b131581ea3a62cebb2ae35571ec8263fd61
refs/heads/master
2021-01-18T14:23:56.900005
2011-04-07T19:34:04
2011-04-07T19:34:04
1,578,581
1
1
null
null
null
null
UTF-8
C++
false
false
282
cpp
/** * FStream Example * */ #include <iostream.h> #include <fstream.h> int main(int argc, char* argv[]) { ofstream ofile( "jasond.tmp", ios::app ); ofile << "Jason is really the coolest guy on the planet" << endl; ofile.flush(); ofile.close(); return 0; }
[ [ [ 1, 18 ] ] ]
9cd2a3295ec0c47cfe562ebe9126ecdf8e345b61
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/mangalore/physics/capsuleshape.cc
c8c9e73e43b7e56906c368744bcbf8737dfe117b
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
2,759
cc
//------------------------------------------------------------------------------ // physics/capsuleshape.cc // (C) 2005 RadonLabs GmbH //------------------------------------------------------------------------------ #include "physics/capsuleshape.h" #include "gfx2/ngfxserver2.h" namespace Physics { ImplementRtti(Physics::CapsuleShape, Physics::Shape); ImplementFactory(Physics::CapsuleShape); //------------------------------------------------------------------------------ /** */ CapsuleShape::CapsuleShape() : Shape(Capsule), radius(1.0f), length(1.0f) { // empty } //------------------------------------------------------------------------------ /** */ CapsuleShape::~CapsuleShape() { // empty } //------------------------------------------------------------------------------ /** Create a capsule object, add it to ODE's collide space, and initialize the mass member. */ bool CapsuleShape::Attach(dSpaceID spaceId) { if (Shape::Attach(spaceId)) { dGeomID capsule = dCreateCapsule(0, this->radius, this->length); this->AttachGeom(capsule, spaceId); dMassSetCapsule(&(this->odeMass), Physics::MaterialTable::GetDensity(this->materialType), 3, this->radius, this->length); this->TransformMass(); return true; } return false; } //------------------------------------------------------------------------------ /** Render a debug visualization of the capsule shape. */ void CapsuleShape::RenderDebug(const matrix44& parentTransform) { if (this->IsAttached()) { nGfxServer2* gfxServer = nGfxServer2::Instance(); vector3 capScale(this->radius, this->radius, this->radius); vector4 color = this->GetDebugVisualizationColor(); matrix44 cap0Transform; cap0Transform.scale(capScale); cap0Transform.translate(vector3(0.0f, 0.0f, this->length * 0.5f)); cap0Transform *= this->GetTransform(); cap0Transform *= parentTransform; gfxServer->DrawShape(nGfxServer2::Sphere, cap0Transform, color); matrix44 cap1Transform; cap1Transform.scale(capScale); cap1Transform.translate(vector3(0.0f, 0.0f, -this->length * 0.5f)); cap1Transform *= this->GetTransform(); cap1Transform *= parentTransform; gfxServer->DrawShape(nGfxServer2::Sphere, cap1Transform, color); matrix44 cylTransform; cylTransform.scale(vector3(this->radius, this->radius, this->length)); cylTransform *= this->GetTransform(); cylTransform *= parentTransform; gfxServer->DrawShape(nGfxServer2::Cylinder, cylTransform, color); } } } // namespace Physics
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 86 ] ] ]
56c7cc27ddc9e1ff955970572f756fbb10c1cfff
4031d76cff71165452918d1f42e920a50f255904
/src/third_party/maart/utility/fastmap.h
b883fa8d2b2666fec0e8f8c688239a31d44da538
[]
no_license
temporaer/seralign
c9ad6e66f941b71b55924f1436f447e443082a8d
fddea59c5d9ac3449a41184ddb2d20de8c71ec38
refs/heads/master
2016-08-04T07:42:00.631008
2009-02-04T17:26:27
2009-02-04T17:26:27
77,186
2
0
null
null
null
null
MacCentralEurope
C++
false
false
13,313
h
/** * @file fastmap.h * * Implements the FastMap data dimension reduction algorithm. * * Copyright 2003-2006 Steven Blackburn, http://www.beeka.org * * This file is part of the Music and Audio Retreival Tools (MaART). * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef maart_fastmap_h #define maart_fastmap_h #include <exception> #include <cassert> #include <vector> #include "utility/distance.h" #include <boost/foreach.hpp> namespace utility { /** * The class which implements the FastMap algorithm. * * @param T The object type. For example, vector<float>, if each object is a * feature vector of floating-point numbers. * * Example: * fastmap< vector<float> > fm; * * @note The FastMap algorithm is published in a paper by Christos Faloutsos * and King-Ip (David) Lin. "FastMap: A Fast Algorithm for Indexing, * Data-Mining and Visualization of Traditional and Multimedia Datasets", * SIGMOD Record (ACM Special Interest Group on Management of Data), * 24, 2, issn:0163-5808, pp. 163--174, June, 1995. */ template <class T> class fastmap { public: typedef T object_t; typedef std::vector<float> mapped_obj_t; typedef std::vector<mapped_obj_t> mapped_objs_t; typedef std::vector< object_t > objects_t; // Define what a collection of objects is made of typedef float scoreT; // The result of a distance comparison typedef void (*progress_fn_t)(size_t total, size_t current); typedef std::vector< std::pair<unsigned int, unsigned int> > pivot_array_t; private: abstract_distance_functor<T, scoreT> const * distance_fn; progress_fn_t progress_fn; // Stores the ids of the pivot objects - one pair per recursive call [2 x k pivot array PA[]] pivot_array_t pivot_array; // whether pivot_array should be overwritten bool mPivotLocked; // At the end of the algorithm, the i-th row is the image of the i-th object [N x k array X[]] mapped_objs_t X; protected: const float fm_dist(const objects_t &objects, unsigned int a, unsigned int b, unsigned int p); void choose_distant_objects(const objects_t &objects, unsigned int *a, unsigned int *b, unsigned int p); void do_map(unsigned int k, const objects_t &objects, unsigned int column = 0); inline void resetPivots(){mPivotLocked = false;} public: fastmap() : distance_fn(NULL), progress_fn(NULL), mPivotLocked(false) { }; void set_distance_function(abstract_distance_functor<T, scoreT> const * fn) { distance_fn = fn; }; const progress_fn_t set_progress_function(progress_fn_t fn) { progress_fn_t old = progress_fn; progress_fn = fn; return old; }; void make_map(unsigned int k, const objects_t &objects); bool save_pivot_ids(const std::string &filename); bool load_pivot_ids(const std::string &filename); const std::vector<float> map_object(const object_t &object); double evaluate_stress(const objects_t &objects, unsigned int k); const mapped_objs_t &get_map() const { return X; }; }; /** * Returns the disimilarity between the two objects, including the projection (p) */ template <class T> const float fastmap<T>::fm_dist(const objects_t &objects, unsigned int a, unsigned int b, unsigned int p) { if (p == 0) return (*distance_fn)(objects[a], objects[b]); else { // p must be > 0, so xa and xb must be in the p-1 column const float d=fm_dist(objects, a, b, p-1); const float xa=X[a][p-1]; const float xb=X[b][p-1]; return sqrt( (d*d) - ((xa-xb)*(xa-xb)) ); } } /** * Choose distant objects. * 1) Choose arbitrarily an object, and let it be the second pivot object Ob * 2) let Oa = (the object that is farthest apart from Ob) (according to the distance function dist ()) * 3) let Ob = (the object that is farthest apart from 0a) * 4) report the objects 0a and ob as the desired pair of objects. * * @todo Add a exit the iterations if the solution doesn't change */ template <class T> void fastmap<T>::choose_distant_objects(const objects_t &objects, unsigned int *a, unsigned int *b, unsigned int p) { #if DEBUG_LEVEL > 0 DEBUG_STREAM << "Choosing distant objects for projection " << p << std::endl; #endif /** The number of iterations to find the most distant objects */ const unsigned int num_iterations = 5; // // Choose arbitrarily an object, and let it be the second pivot object Ob // *b = 0; // Start with the first object, to avoid randomness, apart from anything else float last_distance = 0.0; // A note of the distance this iteration has to beat for (unsigned int iteration = 0; iteration < num_iterations; iteration++) { // // let Oa = (the object that is farthest apart from Ob) (according to the distance function dist()) // *a = *b; float max_distance = 0.0; for (unsigned int n=0; n<objects.size(); n++) { const float distance = fm_dist(objects, *b, n, p); if (distance > max_distance) { *a = n; max_distance = distance; } } // // let Ob = (the object that is farthest apart from 0a) // *b = *a; max_distance = 0.0; for (unsigned int n=0; n<objects.size(); n++) { const float distance = fm_dist(objects, *a, n, p); if (distance > max_distance) { *b = n; max_distance = distance; } } // // Ensure each iteration is increasing the distance, stop if it isn't. // If this happens, it is probably due to the same two objects being // selected each time round the loop. // if (max_distance > last_distance) last_distance = max_distance; else { #if DEBUG_LEVEL > 0 DEBUG_STREAM << "Stopping distance object search after iteration " << iteration << std::endl; #endif break; } } } /** * FastMap. Initialise the map for k and then call do_map(). * * @param k The desired number of resulting dimensions. * @param objects The array of objects. */ template <class T> void fastmap<T>::make_map(unsigned int k, const objects_t &objects) { assert(distance_fn != NULL); #if DEBUG_LEVEL > 0 DEBUG_STREAM << "Initialisting the output map (X) for " << objects.size() << " rows" << std::endl; #endif // Initialise the array of mapped features X.resize(objects.size()); for (unsigned int n=0; n<objects.size(); n++) X[n].resize(k); if(!mPivotLocked){ pivot_array.clear(); pivot_array.reserve(k); } do_map(k, objects); #if DEBUG_LEVEL > 0 DEBUG_STREAM << "Pivot objects indexes:" << std::endl; for (unsigned int n=0; n < pivot_array.size(); n++) DEBUG_STREAM << " " << n << " : " << pivot_array[n].first << " --- " << pivot_array[n].second << std::endl; #endif } /** * FastMap recursive function. This function is called by fastmap::make_map. * * @param k The desired number of resulting dimensions. * * @param objects The array of objects. * * @param column Indicates the column of the X[] array currently being updated */ template <class T> void fastmap<T>::do_map(unsigned int k, const objects_t &objects, unsigned int column) { #if DEBUG_LEVEL > 0 DEBUG_STREAM << "fastmap: k = " << k << ", column = " << column << std::endl; #endif // 1) Check for the end of the recursion. (Could probably use k to imply column) if (k == 0) return; // 2) Choose pivot objects unsigned int a, b; if(mPivotLocked){ a = pivot_array[column].first; b = pivot_array[column].second; }else{ choose_distant_objects(objects, &a, &b, column); // 3) Record the ids of the pivot objects pivot_array.push_back(std::pair<unsigned int, unsigned int>(a, b)); } #if DEBUG_LEVEL > 1 DEBUG_STREAM << "Pivot objects choosen: a = " << a << ", b = " << b << std::endl; DEBUG_STREAM << "Distance = " << fm_dist(objects, a, b, column) << std::endl; #endif // 4) if ( fm_dist(objects, a, b, column) == 0.0) { // set X[ i, col#] =0 for every i and return // since all inter-object distances are 0 for (unsigned int i=0; i<objects.size(); i++) for (unsigned int n=0; n<k; n++) X[i][column+n] = 0.0; #if DEBUG_LEVEL > 0 DEBUG_STREAM << "No further collapsing possible" << std::endl; #endif return; } // Project objects on line (Oa, Ob) const float dab = fm_dist(objects, a, b, column); for (unsigned int i=0; i<objects.size(); i++) { const float dai = fm_dist(objects, a, i, column); const float dbi = fm_dist(objects, b, i, column); X[i][column] = ((dai*dai) + (dab*dab) - (dbi*dbi)) / (dab * 2.0); } // 6) Consider the projections of the objects on a hyper-plane // perpendicular to the line (Oa, Ob); the distance function Dí() // between two projections is given by Eq. 4 do_map(k-1, objects, column+1); // lock pivots when finished if(column==0) mPivotLocked = true; } /** * Saves the pivot object ids */ template <class T> bool fastmap<T>::save_pivot_ids(const std::string &filename) { std::ofstream output(filename.c_str()); if (!output) return false; for (pivot_array_t::const_iterator p=pivot_array.begin(); p!=pivot_array.end(); p++) output << p->first << ' ' << p->second << std::endl; return true; } /** * Load the pivot object ids */ template <class T> bool fastmap<T>::load_pivot_ids(const std::string &filename) { std::ifstream input(filename.c_str()); if (!input) return false; pivot_array.clear(); unsigned int a, b; do { input >> a >> b; if (input) pivot_array.push_back(std::pair<unsigned int, unsigned int>(a, b)); } while (input); return true; } /** * Calculates the stress introduced by the mapping for a value of k. * The 'stress' function gives the relative error that the distances in k-d space * suffer from, on average. * * \verbatim * [ sum_for_each_pair [ (new_distance - old_distance)^2 ] ] * stress = sqrt[ ----------------------------------------------------- ] * [ sum_for_each_pair [ (old_distance)^2 ] ] * \endverbatim * * The new_distance is the Eucildean distance between the FastMapped 'images'. * The old_distance is the one given by the distance function. * * @param objects The collection of vectors to compare with. This *must* be * the same as the set used to fastmap, as each is compared * with the mapping that is (currently) held internally. * * @param k The number of dimensions of the mapped images to consider in the * stress calculations. * * @todo Could be clever about symetric distances and halve the calculations needed. */ template <class T> double fastmap<T>::evaluate_stress(const objects_t &objects, unsigned int k) { #if DEBUG_LEVEL > 0 DEBUG_STREAM << "Calculating stress, which takes " << objects.size() * objects.size() << " comparisons" << std::endl; #endif assert(k <= X[0].size()); double over = 0.0; double under = 0.0; for (unsigned int i=0; i<objects.size(); i++) for (unsigned int j=0; j<objects.size(); j++) { // Calculate the euclidean distance between the two images to this point float diff = 0.0; for (unsigned int n=0; n < k; n++) diff += (X[i][n] - X[j][n]) * (X[i][n] - X[j][n]); const double d1 = (diff == 0.0) ? 0.0 : sqrt(diff); const double d2 = (*distance_fn)(objects[i], objects[j]); over += (d1-d2) * (d1-d2); under += d1*d1; } #if DEBUG_LEVEL > 1 DEBUG_STREAM << "Calculating stress: over = " << over << ", under = " << under << std::endl; #endif return sqrt(over/under); } /** * Map an object into k dimensions using the pivot objects from the current map */ template <class T> const std::vector<float> fastmap<T>::map_object(const object_t &object) { std::vector<float> mapped; throw std::runtime_error("not implemented"); return mapped; } }; // End of the utility namespace #endif
[ [ [ 1, 426 ] ] ]
01738cabc41481b573950b1e2a39bf5c6388ab35
2f77d5232a073a28266f5a5aa614160acba05ce6
/01.DevelopLibrary/04.SmsCode/InfoCenterOfSmartPhone/UiEditControl.cpp
db3d9d892c885abc9c7ff4764e1e510564f254bf
[]
no_license
radtek/mobilelzz
87f2d0b53f7fd414e62c8b2d960e87ae359c81b4
402276f7c225dd0b0fae825013b29d0244114e7d
refs/heads/master
2020-12-24T21:21:30.860184
2011-03-26T02:19:47
2011-03-26T02:19:47
58,142,323
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
6,411
cpp
#include"stdafx.h" #include"UiEditControl.h" #include"ContactorsWnd.h" #include "RecieversStringParser.h" UiEditControl::UiEditControl() { } UiEditControl::~UiEditControl() { //if(NULL != m_pclContactorsWnd ) //{ // delete m_pclContactorsWnd ; // m_pclContactorsWnd = NULL; //} } //void UiEditControl::OnFocused (UiWin *pWinPrev) //{ // //} // //zds 2010/03/21 19:39 //int UiEditControl::OnLButtonUp123 ( UINT fwKeys, int xPos, int yPos ) //{ //RECT EditRc = GetClientRect(); //if( (yPos <= EditRc.bottom && yPos >= EditRc.top) &&( xPos <= EditRc.right && xPos >=EditRc.left) ) //{ // int i = MZ_ANIMTYPE_SCROLL_BOTTOM_TO_TOP_2; // m_lFlag = 1; // // if(NULL != m_pclContactorsWnd ) // { // delete m_pclContactorsWnd ; // m_pclContactorsWnd = NULL; // } // m_pclContactorsWnd = new CContactorsWnd; // m_pclContactorsWnd->SetParent(this); // RECT rcWork = MzGetWorkArea(); // m_pclContactorsWnd->Create(rcWork.left,rcWork.top,RECT_WIDTH(rcWork),RECT_HEIGHT(rcWork), 0, 0, 0, 0); // m_pclContactorsWnd->Show(); // g_bContactShow = TRUE; //} // return 0; //} //zds 2010/03/21 19:39 int UiEditControl::OnLButtonUp ( UINT fwKeys, int xPos, int yPos ) { //if ( 0 == g_clBackupSipID.Data1 ){ // SipGetCurrentIM(&g_clBackupSipID); //} //BOOL b = SipSetCurrentIM(&g_clMeizuSipID); //if(!b) //{ // //SipSetCurrentIM(&g_clBackupSipID); //} MzOpenSip(IM_SIP_MODE_DIGIT, 0); //SetSipMode(IM_SIP_MODE_DIGIT,0); long lRowCount = GetRowCount(); UpdateFontColor(RGB(0,0,0),0,0,lRowCount,0); int r = UiEdit::OnLButtonUp(fwKeys, xPos, yPos); long lCurRow = Invalid_4Byte; long lCurCol = Invalid_4Byte; GetCaretPos((size_t*)&lCurRow, (size_t*)&lCurCol); if ( (Invalid_4Byte!=lCurRow)&&(Invalid_4Byte!=lCurCol) ){ long lPos = Invalid_4Byte; ConvertRowCol2LinePos(lCurRow, lCurCol, lPos); CRecieversStringParser clParser; CMzString& clText = GetText(); long lWSize = 0; wchar_t* pwcsTextBuf = clParser.GetWStringBuf(lWSize); F_wcscpyn(pwcsTextBuf, clText.C_Str(), lWSize); long lBeginPos = Invalid_4Byte; long lEndPos = Invalid_4Byte; clParser.GetContactorRangeByPos(lPos, lBeginPos, lEndPos); BOOL b = clParser.IsContactor(lBeginPos, lEndPos); if ( !b ){ lBeginPos = Invalid_4Byte; lEndPos = Invalid_4Byte; } if( (lBeginPos!=Invalid_4Byte)&&(lEndPos!=Invalid_4Byte)&&(lPos!=lBeginPos) ){ long lRowBegin = 0; long lRowEnd = 0; long lColBegin = 0; long lColEnd = 0; ConvertLinePos2RowCol(lBeginPos, lRowBegin, lColBegin); ConvertLinePos2RowCol(lEndPos, lRowEnd, lColEnd); UpdateFontColor(RGB(167,137,63), lRowBegin, lColBegin, lRowEnd, lColEnd); SetCaretPos(lRowEnd, (lColEnd+1)); Invalidate(); Update(); } } return r; } void UiEditControl::UpdateData( long lFlag ) { CRecieversStringParser clParser; CMzString& clText = GetText(); long lWSize = 0; wchar_t* pwcsTextBuf = clParser.GetWStringBuf(lWSize); F_wcscpyn(pwcsTextBuf, clText.C_Str(), lWSize); clParser.UpdateStringByContactors(); SetText(clParser.GetWStringBuf(lWSize)); Invalidate(); Update(); } //void UiEditControl::UpdateTextByRecievers(BOOL bIsAddChar, long lWillPos) //{ // long lReciversCount = g_ReciversList.GetItemCount(); // wchar_t wcsReciversName[512] = L""; // //wcscat(wcsReciversName, L"ÊÕ¼þÈË:" ); // for(int i = 0; i < lReciversCount; i++) // { // wcscat(wcsReciversName, g_ReciversList.GetItem(i)->StringTitle ); // if ( bIsAddChar ){ // if ( lWillPos == (g_ReciversList.GetItem(i)->lEndPos+1) ){ // wcscat(wcsReciversName, L";" ); // } // } // } // // SetText(wcsReciversName); // Invalidate(); // Update(); //} //void UiEditControl::OnClick( size_t nIndex ) //{ // UiSingleLineEdit::OnClick(nIndex); // long lCursorPos = GetCursePos(); // int b =0; // return; //} //int UiEditControl::OnChar( TCHAR chCharCode, LPARAM lKeyData ) //{ // CMzString& wcsControlText = GetText(); // int b =0; // return 0; //} int UiEditControl::OnKeyDown(int nVirtKey, DWORD lKeyData) { int r = UiEdit::OnKeyDown(nVirtKey, lKeyData); long lCurRow = Invalid_4Byte; long lCurCol = Invalid_4Byte; long lPos = Invalid_4Byte; GetCaretPos((size_t*)&lCurRow, (size_t*)&lCurCol); if ( (Invalid_4Byte!=lCurRow)&&(Invalid_4Byte!=lCurCol) ){ ConvertRowCol2LinePos(lCurRow, lCurCol, lPos); } CRecieversStringParser clParser; CMzString& clText = GetText(); long lWSize = 0; wchar_t* pwcsTextBuf = clParser.GetWStringBuf(lWSize); F_wcscpyn(pwcsTextBuf, clText.C_Str(), lWSize); long lWillPos = 0; if ( (8 == nVirtKey) && ( lKeyData == 0 )){//delete button down lWillPos = clParser.DeleteContentByPos(lPos); ConvertLinePos2RowCol(lWillPos, lCurRow, lCurCol); }else if ( ((48 <= nVirtKey)&&(57>=nVirtKey)) || ( 3 == nVirtKey )){//numbers button down clParser.AddSeparator(lPos); }else{ //cancel input } SetText(clParser.GetWStringBuf(lWSize)); SetCaretPos(lCurRow, lCurCol); Invalidate(); Update(); return r; } void UiEditControl::ConvertLinePos2RowCol(long lLinePos, long& lRow, long& lCol) { long lRowCount = GetRowCount(); long lTotalCharCount = 0; for ( int i = 0; i < lRowCount; i++ ) { if ( (i+1) <= (lRowCount-1) ){ long lCurRowCharCount = GetCharCount(i,0,(i+1),0); long lTemp = lTotalCharCount+lCurRowCharCount; if ( lLinePos < (lTemp) ){ lRow = i; lCol = lLinePos-lTotalCharCount; break; } lTotalCharCount=lTemp; } else{ lRow = i; lCol = lLinePos-lTotalCharCount; break; } } } void UiEditControl::ConvertRowCol2LinePos(long lRow, long lCol, long& lLinePos) { lLinePos = GetCharCount(0,0,lRow,lCol); } void UiEditControl::UpdateRecievers() { CRecieversStringParser clParser; CMzString& clText = GetText(); long lWSize = 0; wchar_t* pwcsTextBuf = clParser.GetWStringBuf(lWSize); F_wcscpyn(pwcsTextBuf, clText.C_Str(), lWSize); clParser.UpdateRecievers(); } void UiEditControl::UpdateContactors() { CRecieversStringParser clParser; CMzString& clText = GetText(); long lWSize = 0; wchar_t* pwcsTextBuf = clParser.GetWStringBuf(lWSize); F_wcscpyn(pwcsTextBuf, clText.C_Str(), lWSize); clParser.UpdateContactors(); }
[ "lidan8908589@8983de3c-2b35-11df-be6c-f52728ce0ce6", "[email protected]" ]
[ [ [ 1, 18 ], [ 20, 24 ], [ 27, 59 ], [ 61, 92 ], [ 94, 107 ], [ 109, 110 ], [ 112, 122 ], [ 125, 242 ] ], [ [ 19, 19 ], [ 25, 26 ], [ 60, 60 ], [ 93, 93 ], [ 108, 108 ], [ 111, 111 ], [ 123, 124 ] ] ]
9743889ca4f592ee2edc4db209397bbb3237e93e
f8b364974573f652d7916c3a830e1d8773751277
/emulator/allegrex/disassembler/MTIC.h
ee7ad699b4906a7469c86e8fd55ff0632a0f82cf
[]
no_license
lemmore22/pspe4all
7a234aece25340c99f49eac280780e08e4f8ef49
77ad0acf0fcb7eda137fdfcb1e93a36428badfd0
refs/heads/master
2021-01-10T08:39:45.222505
2009-08-02T11:58:07
2009-08-02T11:58:07
55,047,469
0
0
null
null
null
null
UTF-8
C++
false
false
309
h
/* MTIC */ void AllegrexInstructionTemplate< 0x70000026, 0xfc1fffff >::disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment) { using namespace Allegrex; ::strcpy(opcode_name, "mtic"); ::sprintf(operands, "%s", gpr_name[rt(opcode)]); ::strcpy(comment, ""); }
[ [ [ 1, 9 ] ] ]
69360cac8295b3e5f41618bce4a2f968bdc8eb90
d752d83f8bd72d9b280a8c70e28e56e502ef096f
/FugueDLL/Marshalling/Libraries.h
ca0be78969c0246e7c3525da709538fdbcd9471a
[]
no_license
apoch/epoch-language.old
f87b4512ec6bb5591bc1610e21210e0ed6a82104
b09701714d556442202fccb92405e6886064f4af
refs/heads/master
2021-01-10T20:17:56.774468
2010-03-07T09:19:02
2010-03-07T09:19:02
34,307,116
0
0
null
null
null
null
UTF-8
C++
false
false
414
h
// // The Epoch Language Project // FUGUE Virtual Machine // // Routines for binding to external libraries // #pragma once // Forward declarations namespace VM { class Program; } namespace Marshalling { void BindToLibrary(const std::wstring& filename, VM::Program& program); void BindToLanguageExtension(const std::wstring& filename, VM::Program& program, bool registereverything); }
[ "[email protected]", "don.apoch@localhost" ]
[ [ [ 1, 19 ], [ 21, 22 ] ], [ [ 20, 20 ] ] ]
08da8b72318dec03a7bfa012f1c4b6786986b480
fad6f9883d4ad2686c196dc532a9ecb9199500ee
/NXP-LPC/CommTest/CommTest/PacketDetailDlg.h
e45c4958e1dec0c60f27c8df091b3bf7c407ff2a
[]
no_license
aquarius20th/nxp-lpc
fe83d6a140d361a1737d950ff728c6ea9a16a1dd
4abfb804daf0ac9c59bd90d879256e7a3c1b2f30
refs/heads/master
2021-01-10T13:54:40.237682
2009-12-22T14:54:59
2009-12-22T14:54:59
48,420,260
0
0
null
null
null
null
GB18030
C++
false
false
708
h
#pragma once // CPacketDetailDlg 对话框 class CPacket; class CPacketDetailDlg : public CBCGPDialog { DECLARE_DYNAMIC(CPacketDetailDlg) public: CPacketDetailDlg(CPacket *pPacket,CWnd* pParent = NULL); // 标准构造函数 virtual ~CPacketDetailDlg(); CPacket *m_pPacket; private: CBCGPGridCtrl m_wndGridTree; CImageList m_Images; void UpdateTree( ); CBCGPGridRow* CreateNewRow (); // 对话框数据 enum { IDD = IDD_DLG_PACKET_DETAIL }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: virtual BOOL OnInitDialog(); afx_msg void OnSize(UINT nType, int cx, int cy); UINT m_nId; };
[ "lijin.unix@13de9a6c-71d3-11de-b374-81e7cb8b6ca2" ]
[ [ [ 1, 34 ] ] ]
2f6b63bb0020dd76eecebfd281b4600cf7457acc
335783c9e5837a1b626073d1288b492f9f6b057f
/source/fbxcmd/daolib/Model/MAO/MAOCommon.h
b4a8af42779ead0b043d1b7ae270b56c2b3f6a23
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
code-google-com/fbx4eclipse
110766ee9760029d5017536847e9f3dc09e6ebd2
cc494db4261d7d636f8c4d0313db3953b781e295
refs/heads/master
2016-09-08T01:55:57.195874
2009-12-03T20:35:48
2009-12-03T20:35:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
389
h
/********************************************************************** *< FILE: MATCommon.h DESCRIPTION: MAT File Format HISTORY: *> Copyright (c) 2009, All Rights Reserved. **********************************************************************/ #pragma once #include "DataHeader.h" #include "DAOFormat.h" #include "text.h" namespace DAO { namespace MAT { } }
[ "tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 22 ] ] ]
368c0cf39dcded20269ae814255429e76c3fa36d
5851a831bcc95145bf501b40e90e224d08fa4ac9
/src/db-engine/database.cpp
2dc53ec8e5f0177581c2ff607f2b69abe6065dd1
[]
no_license
jemyzhang/Cashup
a80091921a2e74f24db045dd731f7bf43c09011a
f4e768a7454bfa437ad9842172de817fa8da71e2
refs/heads/master
2021-01-13T01:35:51.871352
2010-03-06T14:26:55
2010-03-06T14:26:55
null
0
0
null
null
null
null
GB18030
C++
false
false
48,386
cpp
#include <MzCommon.h> using namespace MzCommon; #include "database.h" #include "..\res\resource.h" #ifdef _DEBUG #define DEFAULT_DB L"Program Files\\M8Cash\\cash.db" #pragma comment(lib,"MzCommond.lib") #else #define DEFAULT_DB L"\\Disk\\Programs\\M8Cash\\cash.db" #pragma comment(lib,"MzCommon.lib") #endif //老版本定义 #define OLD_TABLE_ACCOUNT L"ACCOUNTS_v1" #define OLD_TABEL_CATEGORY L"CATEGORIES_v1" #define V1_TABLE_TRANSACTION L"RECORDS_v1" #define V2_TABLE_TRANSACTION L"RECORDS_v2" //新版本定义 #define TABLE_ACCOUNT L"ACCOUNTS_v1" #define TABLE_CATEGORY L"CATEGORIES_v1" #define TABLE_TRANSACTION V2_TABLE_TRANSACTION #define TABLE_PERSON L"PERSONS_v1" #ifdef _DEBUG #define db_out(s) printf("%s:%d: %s\n",__FUNCTION__, __LINE__, s) #else #define db_out(s) #endif #define TRY try #define CATCH catch extern HINSTANCE LangresHandle; clsCASHDB::clsCASHDB() { wchar_t currpath[MAX_PATH]; bool ret = true; if(File::GetCurrentPath(currpath)){ wsprintf(db_path,L"%s\\cash.db",currpath); }else{ wsprintf(db_path,DEFAULT_DB); } connect(); //构造时立即打开 } clsCASHDB::~clsCASHDB() { disconnect(); clean(); } //打开数据库 bool clsCASHDB::connect(){ bool bRet = true; TRY{ bool bfileNotExists = false; if(!File::FileExists(db_path)){ bfileNotExists = true; } sqlconn.open(db_path); sqlconn.createPinyinSearchEngine(); //文件新建时创建默认表 if(bfileNotExists) createDefaultDatabase(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //关闭数据库 bool clsCASHDB::disconnect(){ bool bRet = true; TRY{ sqlconn.close(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //测试密码 bool clsCASHDB::checkpwd(wchar_t* pwd,int len){ bool bRet = false; if(pwd && len != 0){ decrypt(pwd,len); } TRY{ bRet = sqlconn.executeint(L"select count(*) from sqlite_master;") > 0; }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } if(!bRet){ //如果解密失败,则需要断开数据库后再连接 disconnect(); connect(); } return bRet; } //解密数据库 bool clsCASHDB::decrypt(wchar_t* pwd, int len){ char* temp = new char[len*2+1]; int bytecnt = 0; wchar_t *p = pwd; char* b_pwd = temp; for(int i = 0; i < len; i++){ wchar_t w = *p++; if(w&0xff){ *b_pwd++ = w&0xff; bytecnt++; } if((w>>8)&0xff){ *b_pwd++ = (w>>8)&0xff; bytecnt++; } } *b_pwd = '\0'; bool bRet = true; TRY{ sqlconn.decypt(temp,bytecnt); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } delete temp; return bRet; } //加密数据库 bool clsCASHDB::encrypt(wchar_t* pwd, int len){ char* temp = new char[len*2+1]; int bytecnt = 0; wchar_t *p = pwd; char* b_pwd = temp; for(int i = 0; i < len; i++){ wchar_t w = *p++; if(w&0xff){ *b_pwd++ = w&0xff; bytecnt++; } if((w>>8)&0xff){ *b_pwd++ = (w>>8)&0xff; bytecnt++; } } *b_pwd = '\0'; bool bRet = true; TRY{ sqlconn.encypt(temp,bytecnt); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } delete temp; return bRet; } //清除分类列表和帐号列表 void clsCASHDB::clean(){ cleanAccountList(); cleanCategoryList(); } //载入帐号和分类 bool clsCASHDB::load(){ if(!loadAccounts() || !loadCategories()){ return false; } return true; } //恢复数据库 void clsCASHDB::recover(){ createDefaultDatabase(); restoreDefaultCategory(); } /****************************************************** /* 具体操作过程 *******************************************************/ void clsCASHDB::createDefaultDatabase() { createDefaultAccounts(); createDefaultCategories(); createDefaultPersons(); createDefaultTransaction(); } /////////////////////////账户相关///////////////////////////// //创建:默认账户 bool clsCASHDB::createDefaultAccounts(){ bool bRet = true; TRY{ //create table sqlite3_command cmd(sqlconn, L"create table if not exist '" TABLE_ACCOUNT L"' (ID numeric primary key,NAME text NOT NULL,INITIALVALUE integer,NOTE text,ISFIX integer);" ); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } if(!bRet) return bRet; //创建table失败 CONST_CASH_ACCOUNT_t default_accounts[] = { {0, IDS_STR_CASH, 0, IDS_STR_CASH, 1}, {1, IDS_STR_CREDIT, 0, IDS_STR_CREDIT, 1}, {2, IDS_STR_SAVING, 0, IDS_STR_SAVING, 1}, }; int aSets = sizeof (default_accounts) / sizeof (CONST_CASH_ACCOUNT_t); TRY{ sqlite3_command cmd(sqlconn, L"insert into '" TABLE_ACCOUNT L"' (ID,NAME,INITIALVALUE,NOTE,ISFIX) " L"values(?,?,?,?,?);" ); for(int i = 0; i < aSets; i++){ cmd.bind(1,static_cast<int>(default_accounts[i].id)); cmd.bind(2, LOADSTRING(default_accounts[i].nameID).C_Str(), LOADSTRING(default_accounts[i].nameID).Length()*2); cmd.bind(3,default_accounts[i].initval); cmd.bind(4, LOADSTRING(default_accounts[i].noteID).C_Str(), LOADSTRING(default_accounts[i].noteID).Length()*2); cmd.bind(5,static_cast<int>(default_accounts[i].isfix)); cmd.executenonquery(); } }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //新增:账户 bool clsCASHDB::appendAccount(CASH_ACCOUNT_ptr acc) { bool bRet = true; TRY{ sqlite3_command cmd(this->sqlconn, L"insert into '" TABLE_ACCOUNT L"' (ID,NAME,INITIALVALUE,NOTE,ISFIX)" L" values(?,?,?,?,?);"); cmd.bind(1,static_cast<int>(acc->id)); cmd.bind(2,acc->name, lstrlen(acc->name)*2); cmd.bind(3,static_cast<int>(acc->initval)); cmd.bind(4,acc->note,lstrlen(acc->note)*2); cmd.bind(5,static_cast<int>(acc->isfix)); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } //数据库写入成功后,同时增加到帐号列表,减少数据库读操作 if(bRet){ CASH_ACCOUNT_ptr newAcc = new CASH_ACCOUNT_t; newAcc->id = acc->id; C::newstrcpy(&newAcc->name,acc->name); C::newstrcpy(&newAcc->note,acc->note); newAcc->initval = acc->initval; newAcc->isfix = acc->isfix; list_account.push_back(newAcc); } return bRet; } //删除:账户:对应ID int clsCASHDB::deleteAccountById(int id){ const CASH_ACCOUNT_ptr beremoved = accountById(id); if(beremoved == NULL) return -3; //无此账户 //检查是否正在被使用 bool bUsed = true; TRY{ sqlite3_command cmd(sqlconn, L"select count(*) from '" TABLE_TRANSACTION L"' where ACCOUNTID=? or TOACCOUNTID=?"); cmd.bind(1,id); cmd.bind(2,id); if(cmd.executeint() == 0){ bUsed = false; } }CATCH(exception &ex){ db_out(ex.what()); } if(bUsed) return -1; //正在被使用,无法删除 //从账户列表中删除账户 list_account.remove(beremoved); delete beremoved; //从数据库中删除分类 TRY{ sqlite3_command cmd(sqlconn, L"delete from '" TABLE_ACCOUNT L"' where ID=?"); cmd.bind(1,id); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); } return 0; } //更新账户 bool clsCASHDB::updateAccount(CASH_ACCOUNT_ptr a){ if(a == NULL) return false; bool bRet = true; TRY{ sqlite3_command cmd(sqlconn, L"update '" TABLE_ACCOUNT L"' set NAME=?, NOTE=?, INITIALVALUE=? where ID=?"); cmd.bind(1,a->name,lstrlen(a->name)*2); cmd.bind(2,a->note,lstrlen(a->note)*2); cmd.bind(3,a->initval); cmd.bind(4,static_cast<int>(a->id)); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } if(bRet){ updateAccountList(a->id, a); } return bRet; } //更新账户列表 bool clsCASHDB::updateAccountList(int id,CASH_ACCOUNT_ptr t) { list<CASH_ACCOUNT_ptr>::iterator i = list_account.begin(); CASH_ACCOUNT_ptr a; for (; i != list_account.end(); i++){ a = *i; if(a->id == id){ if(a == t) return true; a->initval = t->initval; a->isfix = t->isfix; C::newstrcpy(&a->name,t->name); C::newstrcpy(&a->note,t->note); return true; } } return false; } //载入:账户 bool clsCASHDB::loadAccounts() { //载入前清除垃圾,防止重复载入 cleanAccountList(); bool bRet = true; TRY{ sqlite3_command cmd(this->sqlconn, L"select * from '" TABLE_ACCOUNT L"';"); sqlite3_reader reader = cmd.executereader(); while(reader.read()){ CASH_ACCOUNT_ptr accs = new CASH_ACCOUNT_t; accs->id = reader.getint(0); C::newstrcpy(&accs->name,reader.getstring16(1).c_str()); accs->initval = reader.getint(2); C::newstrcpy(&accs->note,reader.getstring16(3).c_str()); accs->isfix = reader.getint(4); list_account.push_back(accs); } }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //清除:帐号列表 void clsCASHDB::cleanAccountList(){ if(list_account.size()){ list<CASH_ACCOUNT_ptr>::iterator c = list_account.begin(); for(;c != list_account.end(); c++){ delete *c; } list_account.clear(); } } //根据id获得帐号 CASH_ACCOUNT_ptr clsCASHDB::accountById(int id) { list<CASH_ACCOUNT_ptr>::iterator i = list_account.begin(); CASH_ACCOUNT_ptr a; for (; i != list_account.end(); i++){ a = *i; if(a->id == id){ return a; } } return NULL; } //根据ID获取账户名称 wchar_t* clsCASHDB::getAccountNameById(int id) { CASH_ACCOUNT_ptr paccount = accountById(id); return (paccount == NULL ? NULL : paccount->name); } //清除搜索结果:账户 void clsCASHDB::clearAccountSearchResults(){ if(!list_search_account.empty()){ list<CASH_ACCOUNT_ptr>::iterator i = list_search_account.begin(); for(;i != list_search_account.end();i++){ delete *i; } list_search_account.clear(); } } //搜索:账户 bool clsCASHDB::searchAccounts(sqlite3_command& cmd){ //do some clear work clearAccountSearchResults(); bool bRet = true; TRY{ sqlite3_reader reader = cmd.executereader(); while(reader.read()){ CASH_ACCOUNT_ptr r = new CASH_ACCOUNT_t; r->id = reader.getint(0); C::newstrcpy(&r->name,reader.getstring16(1).c_str()); r->initval = reader.getint(2); C::newstrcpy(&r->note,reader.getstring16(3).c_str()); r->isfix = reader.getint(4); list_search_account.push_back(r); } }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } if(list_search_account.empty()) bRet = false; return bRet; } //检查是否重复账户:按照name判断 int clsCASHDB::checkDupAccount(CASH_ACCOUNT_ptr pa, bool *bconflict){ if(pa == NULL || pa->name == NULL) return -1; int retid = -1; bool bconf = false; TRY{ sqlite3_command cmd(sqlconn, L"select * from '" TABLE_ACCOUNT L"' where NAME=? COLLATE NOCASE;"); cmd.bind(1,pa->name,lstrlen(pa->name)*2); if(!searchAccounts(cmd)){ CASH_ACCOUNT_ptr r = list_search_account.front(); retid = r->id; //返回存在的记录id号 if(r->initval != pa->initval || r->isfix != pa->isfix || lstrcmp(r->note,pa->note) != 0){ //有冲突 bconf = true; } if(bconflict){ *bconflict = bconf; } } }CATCH(exception &ex){ db_out(ex.what()); } return retid; } //获取账户数量 int clsCASHDB::getAccountSize(){ int retval = 0; TRY{ sqlite3_command cmd(sqlconn, L"select count(ID) from '" TABLE_ACCOUNT L"';"); retval = cmd.executeint(); }CATCH(exception &ex){ db_out(ex.what()); } return retval; } //获取账户ID最大值 int clsCASHDB::getMaxAccountID(){ int retval = 0; TRY{ sqlite3_command cmd(sqlconn, L"select max(ID) from '" TABLE_ACCOUNT L"';"); retval = cmd.executeint(); }CATCH(exception &ex){ db_out(ex.what()); } return retval; } //////////////////分类相关/////////////////////////// //创建:默认分类 bool clsCASHDB::createDefaultCategories(){ bool bRet = true; TRY{ //create table sqlite3_command cmd(sqlconn, L"create table if not exist '" TABLE_CATEGORY L"' (ID numeric primary key,NAME text NOT NULL,TYPE integer NOT NULL,PARENTID numeric NOT NULL,LEVEL integer);" ); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } if(!bRet) return bRet; //创建table失败 CONST_CASH_CATEGORY_t default_categories[] = { {0, IDS_STR_EXPENSE, CT_OUTGOING, -1, 0}, {1, IDS_STR_INCOME, CT_INCOME, -1, 0}, {2, IDS_STR_TRANSFER, CT_TRANSFER, -1, 2}, //设置为无子目录 }; int aSets = sizeof (default_categories) / sizeof (CONST_CASH_CATEGORY_t); TRY{ sqlite3_command cmd(sqlconn, L"insert into '" TABLE_CATEGORY L"' (ID,NAME,TYPE,PARENTID,LEVEL) " L"values(?,?,?,?,?);" ); for(int i = 0; i < aSets; i++){ cmd.bind(1,static_cast<int>(default_categories[i].id)); cmd.bind(2, LOADSTRING(default_categories[i].nameID).C_Str(), LOADSTRING(default_categories[i].nameID).Length()*2); cmd.bind(3,static_cast<int>(default_categories[i].type)); cmd.bind(4,static_cast<int>(default_categories[i].parentid)); cmd.bind(5,static_cast<int>(default_categories[i].level)); cmd.executenonquery(); } }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //恢复:默认分类 bool clsCASHDB::restoreDefaultCategory() { CONST_CASH_CATEGORY_t default_categories[] = { {0, IDS_STR_EXPENSE, CT_OUTGOING, -1, 0}, {1, IDS_STR_INCOME, CT_INCOME, -1, 0}, {2, IDS_STR_TRANSFER, CT_TRANSFER, -1, 2}, //设置为无子目录 }; bool bRet = true; TRY{ sqlite3_command cmd(sqlconn, L"update '" TABLE_CATEGORY L"' set NAME=? where LEVEL=? and TYPE=? and PARENTID=-1;" ); for(int i = 0; i < sizeof(default_categories)/sizeof(CONST_CASH_CATEGORY_t); i++){ cmd.bind(1,LOADSTRING(default_categories[i].nameID).C_Str(), LOADSTRING(default_categories[i].nameID).Length()*2); cmd.bind(2,static_cast<int>(default_categories[i].level)); cmd.bind(3,static_cast<int>(default_categories[i].type)); cmd.executenonquery(); } }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //新增:分类 bool clsCASHDB::appendCategory(CASH_CATEGORY_ptr cat) { bool bRet = true; TRY{ sqlite3_command cmd(this->sqlconn, L"insert into '" TABLE_CATEGORY L"' (ID,NAME,TYPE,PARENTID,LEVEL)" L" values(?,?,?,?,?);"); cmd.bind(1,static_cast<int>(cat->id)); cmd.bind(2,cat->name, lstrlen(cat->name)*2); cmd.bind(3,static_cast<int>(cat->type)); cmd.bind(4,static_cast<int>(cat->parentid)); cmd.bind(5,static_cast<int>(cat->level)); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } //数据库写入成功后,同时增加到分类列表,减少数据库读操作 if(bRet){ CASH_CATEGORY_ptr newCat = new CASH_CATEGORY_t; newCat->id = cat->id; newCat->level = cat->level; C::newstrcpy(&newCat->name,cat->name); newCat->parentid = cat->parentid; newCat->type = cat->type; list_category.push_back(newCat); } return bRet; } //删除:对应ID:分类 int clsCASHDB::deleteCategoryById(int id){ CASH_CATEGORY_ptr beremoved = categoryById(id); if(beremoved == NULL) return -3; //无此分类 if(beremoved->level == 0) return -2; //根分类,不能删除 if(beremoved->level < 2){ //检查是否有子类 list<CASH_CATEGORY_ptr>::iterator i = list_category.begin(); for (; i!=list_category.end(); i++){ CASH_CATEGORY_ptr chk = *i; if(chk->parentid == id){ return -1; //有子类,无法删除 } } } //检查是否正在被使用 bool bUsed = true; TRY{ sqlite3_command cmd(sqlconn, L"select count(*) from '" TABLE_TRANSACTION L"' where CATEGORYID=?"); cmd.bind(1,id); if(cmd.executeint() == 0){ bUsed = false; } }CATCH(exception &ex){ db_out(ex.what()); } if(bUsed) return -1; //正在被使用,无法删除 //从分类列表中删除分类 list_category.remove(beremoved); delete beremoved; //从数据库中删除分类 TRY{ sqlite3_command cmd(sqlconn, L"delete from '" TABLE_CATEGORY L"' where ID=?"); cmd.bind(1,id); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); } return 0; } //更新:分类列表 bool clsCASHDB::updateCategoryList(int id,CASH_CATEGORY_ptr t) { list<CASH_CATEGORY_ptr>::iterator i = list_category.begin(); CASH_CATEGORY_ptr a; for (; i != list_category.end(); i++){ a = *i; if(a->id == id){ if(a == t) return true; a->level = t->level; a->parentid = t->parentid; a->type = t->type; C::newstrcpy(&a->name,t->name); return true; } } return false; } //更新:分类 bool clsCASHDB::updateCategory(CASH_CATEGORY_ptr a){ if(a == NULL) return false; bool bRet = true; TRY{ sqlite3_command cmd(sqlconn, L"update '" TABLE_CATEGORY L"' set NAME=?,LEVEL=?,PARENTID=?,TYPE=? where ID=?"); cmd.bind(1,a->name,lstrlen(a->name)*2); cmd.bind(2,static_cast<int>(a->level)); cmd.bind(3,static_cast<int>(a->parentid)); cmd.bind(4,static_cast<int>(a->type)); cmd.bind(5,static_cast<int>(a->id)); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } if(bRet){ updateCategoryList(a->id, a); } return bRet; } //载入:分类 bool clsCASHDB::loadCategories() { //载入前清除垃圾,防止重复载入 cleanCategoryList(); bool bRet = true; TRY{ sqlite3_command cmd(this->sqlconn, L"select * from '" TABLE_CATEGORY L"' order by NAME collate pinyin;"); sqlite3_reader reader = cmd.executereader(); while(reader.read()){ CASH_CATEGORY_ptr c = new CASH_CATEGORY_t; c->id = reader.getint(0); C::newstrcpy(&c->name,reader.getstring16(1).c_str()); c->type = static_cast<CASH_TRANSACT_TYPE_t>(reader.getint(2)); c->parentid = reader.getint(3); c->level = reader.getint(4); list_category.push_back(c); } }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //清除:分类列表 void clsCASHDB::cleanCategoryList(){ if(list_category.size()){ list<CASH_CATEGORY_ptr>::iterator t = list_category.begin(); for(;t != list_category.end(); t++){ delete *t; } list_category.clear(); } } //根据ID获得分类 CASH_CATEGORY_ptr clsCASHDB::categoryById(int id) { list<CASH_CATEGORY_ptr>::iterator i = list_category.begin(); CASH_CATEGORY_ptr a; for (; i != list_category.end(); i++){ a = *i; if(a->id == id){ return a; } } return NULL; } //根据ID获取分类名称 wchar_t* clsCASHDB::getCategoryNameById(int id) { CASH_CATEGORY_ptr pcategory = categoryById(id); return (pcategory == NULL ? NULL : pcategory->name); } //根据ID获取分类全名(包括父类) //TODO: 返回值必须在使用完毕后销毁 wchar_t* clsCASHDB::getCategoryFullNameById(int id) { wchar_t* fullname; wchar_t* nodename[3]; //child max depth = 3 int depth = 0; int szfullname = 0; int nodeidx = id; CASH_CATEGORY_ptr c; do { c = categoryById(nodeidx); if(c != NULL){ nodename[depth++] = c->name; nodeidx = c->parentid; szfullname += lstrlen(c->name); }else{ nodeidx = -1; //当不能找到对应category时结束 } } while (nodeidx != -1); //分配字符串空间 fullname = new wchar_t[szfullname + 1]; for (int i = depth-1; i >= 0; i--) { lstrcat(fullname, nodename[i]); if (i != 0) { lstrcat(fullname, L" - "); } } return fullname; } //清除搜索结果:分类 void clsCASHDB::clearCategorySearchResults(){ if(!list_search_category.empty()){ list<CASH_CATEGORY_ptr>::iterator i = list_search_category.begin(); for(;i != list_search_category.end();i++){ delete *i; } list_search_category.clear(); } } //搜索:分类 bool clsCASHDB::searchCategories(sqlite3_command& cmd){ bool rc = true; //do some clear work clearCategorySearchResults(); bool bRet = true; TRY{ sqlite3_reader reader = cmd.executereader(); while(reader.read()){ CASH_CATEGORY_ptr r = new CASH_CATEGORY_t; r->id = reader.getint(0); C::newstrcpy(&r->name,reader.getstring16(1).c_str()); r->type = static_cast<CASH_TRANSACT_TYPE_t>(reader.getint(2)); r->parentid = reader.getint(3); r->level = reader.getint(4); list_search_category.push_back(r); } }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } if(list_search_category.empty()) bRet = false; return bRet; } //检查是否为子分类 bool clsCASHDB::isChildCategory(int childId, int parentId){ CASH_CATEGORY_ptr child = categoryById(childId); CASH_CATEGORY_ptr parent = categoryById(parentId); if(child->level <= parent->level || child->parentid == -1) return false; if(child->level == 2 && parent->level == 0){ CASH_CATEGORY_ptr parent1 = categoryById(child->parentid); if(parent1->parentid == parent->id){ return true; }else{ return false; } } if(child->parentid == parent->id){ return true; } return false; } //检查是否重复分类:按照name判断 int clsCASHDB::checkDupCategory(CASH_CATEGORY_ptr pc, bool *bconflict){ if(pc == NULL || pc->name == NULL) return -1; int retid = -1; TRY{ sqlite3_command cmd(sqlconn, L"select count(*),ID,TYPE from '" TABLE_CATEGORY L"' where NAME=? and LEVEL=? and PARENTID=?;"); cmd.bind(1,pc->name,lstrlen(pc->name)*2); cmd.bind(2,static_cast<int>(pc->level)); cmd.bind(3,static_cast<int>(pc->parentid)); sqlite3_reader reader = cmd.executereader(); if(reader.getint(0) != 0){ retid = reader.getint(1); if(reader.getint(2) != pc->type){ if(bconflict) *bconflict = true; } } }CATCH(exception &ex){ db_out(ex.what()); } return retid; } //获取分类:根据级别 bool clsCASHDB::getCategoryByLevel(int level){ bool bRet = true; TRY{ sqlite3_command cmd(sqlconn, L"select * from '" TABLE_CATEGORY L"' where LEVEL=? order by NAME collate pinyin;"); bRet = searchCategories(cmd); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //获取分类数量 int clsCASHDB::getCategorySize(){ int retval = 0; TRY{ sqlite3_command cmd(sqlconn, L"select count(ID) from '" TABLE_CATEGORY L"';"); retval = cmd.executeint(); }CATCH(exception &ex){ db_out(ex.what()); } return retval; } //获取分类ID最大值 int clsCASHDB::getMaxCategoryID(){ int retval = 0; TRY{ sqlite3_command cmd(sqlconn, L"select max(ID) from '" TABLE_CATEGORY L"';"); retval = cmd.executeint(); }CATCH(exception &ex){ db_out(ex.what()); } return retval; } /////////交易相关 //创建:默认交易明细 bool clsCASHDB::createDefaultTransaction(){ bool bRet = true; TRY{ //create table sqlite3_command cmd(sqlconn, L"create table if not exist '" TABLE_TRANSACTION L"' (TRANSACTID numeric primary key,DATE text not null,AMOUNT integer not null,NOTE text," L" ACCOUNTID numeric not null,CATGORYID numeric not null,TOACCOUNTID numeric,ISTRANSFER integer not null," L" PERSON_ID numeric not null default 0);" ); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //新增:交易明细 bool clsCASHDB::appendTransaction(CASH_TRANSACT_ptr r) { bool bRet = true; TRY{ //获取最大的交易ID r->transid = getMaxTransactionID() + 1; sqlite3_command cmd(this->sqlconn, L"insert into '" TABLE_TRANSACTION L"' (TRANSACTID,DATE,AMOUNT,NOTE,ACCOUNTID,CATGORYID,TOACCOUNTID,ISTRANSFER,PERSON_ID)" L" values(?,?,?,?,?,?,?,?,?);"); cmd.bind(1,static_cast<int>(r->transid)); cmd.bind(2,r->date, lstrlen(r->date)*2); cmd.bind(3,static_cast<int>(r->amount)); cmd.bind(4,r->note,lstrlen(r->note)*2); cmd.bind(5,static_cast<int>(r->accountid)); cmd.bind(6,static_cast<int>(r->categoryid)); cmd.bind(7,static_cast<int>(r->toaccountid)); cmd.bind(8,static_cast<int>(r->isTransfer)); cmd.bind(9,static_cast<int>(r->personid)); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //载入:交易明细 bool clsCASHDB::loadTransactions() { bool bRet = true; TRY{ sqlite3_command cmd(this->sqlconn, L"select * from '" TABLE_TRANSACTION L"';"); bRet = searchTransactions(cmd); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //根据ID获得交易明细 bool clsCASHDB::recordById(int id,CASH_TRANSACT_ptr pr) { bool bRet = true; if(pr == NULL) return false; //指针错误 TRY{ sqlite3_command cmd(this->sqlconn, L"select * from '" TABLE_TRANSACTION L"' where TRANSACTID=?;"); cmd.bind(1,id); sqlite3_reader reader = cmd.executereader(); while(reader.read()){ pr->transid = reader.getint(0); C::newstrcpy(&pr->date,reader.getstring16(1).c_str()); pr->amount = reader.getint(2); C::newstrcpy(&pr->note,reader.getstring16(3).c_str()); pr->accountid = reader.getint(4); pr->categoryid = reader.getint(5); pr->toaccountid = reader.getint(6); pr->isTransfer = reader.getint(7); pr->personid = reader.getint(8); } }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //删除:对应ID:交易明细 bool clsCASHDB::deleteTransactionById(int id){ bool bRet = true; //从数据库中删除分类 TRY{ sqlite3_command cmd(sqlconn, L"delete from '" TABLE_TRANSACTION L"' where TRANSACTID=?"); cmd.bind(1,id); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //更新:交易明细 bool clsCASHDB::updateTransaction(CASH_TRANSACT_ptr a){ if(a == NULL) return false; bool bRet = true; TRY{ sqlite3_command cmd(sqlconn, L"update '" TABLE_CATEGORY L"' set NOTE=?,DATE=?,AMOUNT=?,ACCOUNTID=?," L"CATGORYID=?,TOACCOUNTID=?,ISTRANSFER=?,PERSON_ID=? " L"where TRANSACTID=?"); cmd.bind(1,a->note,lstrlen(a->note)*2); cmd.bind(2,a->date,lstrlen(a->date)*2); cmd.bind(3,a->amount); cmd.bind(4,static_cast<int>(a->accountid)); cmd.bind(5,static_cast<int>(a->categoryid)); cmd.bind(6,static_cast<int>(a->toaccountid)); cmd.bind(7,static_cast<int>(a->isTransfer)); cmd.bind(8,static_cast<int>(a->personid)); cmd.bind(9,static_cast<int>(a->transid)); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //清除搜索结果:交易明细 void clsCASHDB::clearTransactionSearchResults(){ if(!list_search_record.empty()){ list<CASH_TRANSACT_ptr>::iterator i = list_search_record.begin(); for(;i != list_search_record.end();i++){ delete *i; } list_search_record.clear(); } } //搜索:交易明细 bool clsCASHDB::searchTransactions(sqlite3_command& cmd){ bool bRet = true; //do some clear work clearTransactionSearchResults(); TRY{ sqlite3_reader reader = cmd.executereader(); while(reader.read()){ CASH_TRANSACT_ptr r = new CASH_TRANSACT_t; r->transid = reader.getint(0); C::newstrcpy(&r->date,reader.getstring16(1).c_str()); r->amount = reader.getint(2); C::newstrcpy(&r->note,reader.getstring16(3).c_str()); r->accountid = reader.getint(4); r->categoryid = reader.getint(5); r->toaccountid = reader.getint(6); r->isTransfer = reader.getint(7); r->personid = reader.getint(8); list_search_record.push_back(r); } }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } if(list_search_record.empty()) bRet = false; return bRet; } //获取明细数量 int clsCASHDB::getTransactionSize(){ int retval = 0; TRY{ sqlite3_command cmd(sqlconn, L"select count(TRANSACTID) from '" TABLE_TRANSACTION L"';"); retval = cmd.executeint(); }CATCH(exception &ex){ db_out(ex.what()); } return retval; } //获取明细ID最大值 int clsCASHDB::getMaxTransactionID(){ int retval = 0; TRY{ sqlite3_command cmd(sqlconn, L"select max(TRANSACTID) from '" TABLE_TRANSACTION L"';"); retval = cmd.executeint(); }CATCH(exception &ex){ db_out(ex.what()); } return retval; } //获取明细最小日期 uRecordDate_t clsCASHDB::getMinTransactionDate(){ uRecordDate_t retval; retval.Value = 0; TRY{ sqlite3_command cmd(sqlconn, L"select min(DATE) from '" TABLE_TRANSACTION L"';"); const wchar_t *date = cmd.executestring16().c_str(); if(date != 0){ DWORD y,m,d; swscanf(date,L"%04d-%02d-%02d",&y,&m,&d); retval.Date.Year = y; retval.Date.Month = m; retval.Date.Day = d; } }CATCH(exception &ex){ db_out(ex.what()); } return retval; } //获取明细最大日期 uRecordDate_t clsCASHDB::getMaxTransactionDate(){ uRecordDate_t retval; retval.Value = 0; TRY{ sqlite3_command cmd(sqlconn, L"select max(DATE) from '" TABLE_TRANSACTION L"';"); const wchar_t *date = cmd.executestring16().c_str(); if(date != 0){ DWORD y,m,d; swscanf(date,L"%04d-%02d-%02d",&y,&m,&d); retval.Date.Year = y; retval.Date.Month = m; retval.Date.Day = d; } }CATCH(exception &ex){ db_out(ex.what()); } return retval; } void clsCASHDB::AccountInOutById(int &in, int &out, int id,RECORDATE_ptr date, RECORDATE_ptr datend){ in = AccountInById(id,date,datend); out = AccountOutById(id,date,datend); return; } int clsCASHDB::AccountInById(int id,RECORDATE_ptr date, RECORDATE_ptr datend){ RECORDATE_t d1,d2; int amount = 0; formatDate(date,datend,d1,d2); TRY{ wchar_t date1[32]; wchar_t date2[32]; wsprintf(date1,L"%04d-%02d-%02d 00:00:00",d1.Year,d1.Month,d1.Day); wsprintf(date2,L"%04d-%02d-%02d 23:59:59",d2.Year,d2.Month,d2.Day); if(id == -1){ sqlite3_command cmd(sqlconn, L"select sum(amount) from '" TABLE_TRANSACTION L"' where categoryid in (select id from '" TABLE_CATEGORY L"' where type=0 and DATE between ? and ?;"); cmd.bind(1,date1,lstrlen(date1)*2); //date 1 cmd.bind(2,date2,lstrlen(date2)*2); //date 2 amount = cmd.executeint(); }else{ sqlite3_command cmd(sqlconn, L"select sum(amount) from '" TABLE_TRANSACTION L"' where ((accountid=? and categoryid in (select id from '" TABLE_CATEGORY L"' where type=0)) or (toaccountid=? and categoryid in (select id from '" TABLE_CATEGORY L"' where type=2))) and DATE between ? and ?;"); cmd.bind(1,id); //accountid cmd.bind(2,id); //toaccountid cmd.bind(3,date1,lstrlen(date1)*2); //date 1 cmd.bind(4,date2,lstrlen(date2)*2); //date 2 amount = cmd.executeint(); } }CATCH(exception &ex){ db_out(ex.what()); } return amount; } int clsCASHDB::AccountOutById(int id,RECORDATE_ptr date, RECORDATE_ptr datend){ RECORDATE_t d1,d2; int amount = 0; formatDate(date,datend,d1,d2); TRY{ wchar_t date1[32]; wchar_t date2[32]; wsprintf(date1,L"%04d-%02d-%02d 00:00:00",d1.Year,d1.Month,d1.Day); wsprintf(date2,L"%04d-%02d-%02d 23:59:59",d2.Year,d2.Month,d2.Day); if(id == -1){ sqlite3_command cmd(sqlconn, L"select sum(amount) from '" TABLE_TRANSACTION L"' where categoryid in (select id from '" TABLE_CATEGORY L"' where type=1 and DATE between ? and ?;"); cmd.bind(1,date1,lstrlen(date1)*2); //date 1 cmd.bind(2,date2,lstrlen(date2)*2); //date 2 amount = cmd.executeint(); }else{ sqlite3_command cmd(sqlconn, L"select sum(amount) from '" TABLE_TRANSACTION L"' where accountid=? and categoryid in (select id from '" TABLE_CATEGORY L"' where type!=0) and DATE between ? and ?;"); cmd.bind(1,id); //accountid cmd.bind(3,date1,lstrlen(date1)*2); //date 1 cmd.bind(4,date2,lstrlen(date2)*2); //date 2 amount = cmd.executeint(); } }CATCH(exception &ex){ db_out(ex.what()); } return amount; } int clsCASHDB::AccountBalanceById(int id,RECORDATE_ptr date, bool binit, RECORDATE_ptr datend){ int in = 0; int out = 0; CASH_ACCOUNT_ptr a = accountById(id); int balance = binit ? a->initval : 0; AccountInOutById(in,out,id,date,datend); return (balance + in - out); } void clsCASHDB::formatDate(RECORDATE_ptr date, RECORDATE_ptr datend, RECORDATE_t &d1, RECORDATE_t &d2){ if(date){ d1.Year = date->Year > 0 ? date->Year : 0; d1.Month = date->Month > 0 ? date->Month : 0; d1.Day = date->Day > 0 ? date->Day : 0; }else{ d1.Year = 0; d1.Month = 0; d1.Day = 0; } if(datend){ d2.Year = datend->Year > 0 ? datend->Year : 0xfff; d2.Month = datend->Month > 0 ? datend->Month : 12; d2.Day = datend->Day > 0 ? datend->Day : 31; }else{ d2.Year = 0xfff; d2.Month = 12; d2.Day = 31; } } bool clsCASHDB::getTransactionsByDate(RECORDATE_ptr date, RECORDATE_ptr datend){ RECORDATE_t d1, d2; formatDate(date,datend,d1,d2); bool bRet = false; TRY{ wchar_t date1[32]; wchar_t date2[32]; wsprintf(date1,L"%04d-%02d-%02d 00:00:00",d1.Year,d1.Month,d1.Day); wsprintf(date2,L"%04d-%02d-%02d 23:59:59",d2.Year,d2.Month,d2.Day); sqlite3_command cmd(sqlconn, L"select * from '" TABLE_TRANSACTION L"' where DATE between ? and ? order by DATE desc;"); cmd.bind(1,date1,lstrlen(date1)*2); //date 1 cmd.bind(2,date2,lstrlen(date2)*2); //date 2 bRet = searchTransactions(cmd); }CATCH(exception &ex){ db_out(ex.what()); } return bRet; } bool clsCASHDB::getTransactionsByDate_v2( RECORDATE_ptr date, RECORDATE_ptr datend, UINT orderby){ RECORDATE_t d1, d2; formatDate(date,datend,d1,d2); wchar_t *sql = new wchar_t[256]; wsprintf(sql, L"select * from '" TABLE_TRANSACTION, L"' where DATE between ? and ? order by "); switch(orderby){ case 1: wcscat(sql,L"ACCOUNTID,DATE DESC;"); break; case 2: wcscat(sql,L"CATGORYID,DATE DESC;"); break; case 0: default: wcscat(sql,L"DATE DESC;"); break; } bool bRet = false; TRY{ wchar_t date1[32]; wchar_t date2[32]; wsprintf(date1,L"%04d-%02d-%02d 00:00:00",d1.Year,d1.Month,d1.Day); wsprintf(date2,L"%04d-%02d-%02d 23:59:59",d2.Year,d2.Month,d2.Day); sqlite3_command cmd(sqlconn,sql); cmd.bind(1,date1,lstrlen(date1)*2); //date 1 cmd.bind(2,date2,lstrlen(date2)*2); //date 2 bRet = searchTransactions(cmd); }CATCH(exception &ex){ db_out(ex.what()); } delete sql; return bRet; } bool clsCASHDB::getTransactionsByCategory(int id, RECORDATE_ptr date, RECORDATE_ptr datend){ RECORDATE_t d1, d2; formatDate(date,datend,d1,d2); bool bRet = false; TRY{ wchar_t date1[32]; wchar_t date2[32]; wsprintf(date1,L"%04d-%02d-%02d 00:00:00",d1.Year,d1.Month,d1.Day); wsprintf(date2,L"%04d-%02d-%02d 23:59:59",d2.Year,d2.Month,d2.Day); sqlite3_command cmd(sqlconn, L"select * from '" TABLE_TRANSACTION L"' where CATGORYID=? and DATE between ? and ? order by DATE desc;"); cmd.bind(1,id); cmd.bind(2,date1,lstrlen(date1)*2); //date 1 cmd.bind(3,date2,lstrlen(date2)*2); //date 2 bRet = searchTransactions(cmd); }CATCH(exception &ex){ db_out(ex.what()); } return bRet; } bool clsCASHDB::getTransactionsByAccount(int id, RECORDATE_ptr date, RECORDATE_ptr datend){ RECORDATE_t d1, d2; formatDate(date,datend,d1,d2); bool bRet = false; TRY{ wchar_t date1[32]; wchar_t date2[32]; wsprintf(date1,L"%04d-%02d-%02d 00:00:00",d1.Year,d1.Month,d1.Day); wsprintf(date2,L"%04d-%02d-%02d 23:59:59",d2.Year,d2.Month,d2.Day); sqlite3_command cmd(sqlconn, L"select * from '" TABLE_TRANSACTION L"' where ACCOUNTID=? and DATE between ? and ? order by DATE desc;"); cmd.bind(1,id); cmd.bind(2,date1,lstrlen(date1)*2); //date 1 cmd.bind(3,date2,lstrlen(date2)*2); //date 2 bRet = searchTransactions(cmd); }CATCH(exception &ex){ db_out(ex.what()); } return bRet; } bool clsCASHDB::getTransactionsByToAccount(int id, RECORDATE_ptr date, RECORDATE_ptr datend){ RECORDATE_t d1, d2; formatDate(date,datend,d1,d2); bool bRet = false; TRY{ wchar_t date1[32]; wchar_t date2[32]; wsprintf(date1,L"%04d-%02d-%02d 00:00:00",d1.Year,d1.Month,d1.Day); wsprintf(date2,L"%04d-%02d-%02d 23:59:59",d2.Year,d2.Month,d2.Day); sqlite3_command cmd(sqlconn, L"select * from '" TABLE_TRANSACTION L"' where TOACCOUNTID=? and DATE between ? and ? order by DATE desc;"); cmd.bind(1,id); cmd.bind(2,date1,lstrlen(date1)*2); //date 1 cmd.bind(3,date2,lstrlen(date2)*2); //date 2 bRet = searchTransactions(cmd); }CATCH(exception &ex){ db_out(ex.what()); } return bRet; } //检查是否是重复记录:按照date, amount, account id, category id判断 int clsCASHDB::checkDupTransaction(CASH_TRANSACT_ptr pr){ if(pr == NULL || pr->date == NULL) return -1; int retid = -1; //返回存在的记录ID TRY{ sqlite3_command cmd(sqlconn, L"select count(*),TRANSACTID from '" TABLE_TRANSACTION L"' where DATE like ? and AMOUNT=? " L"and CATEGORYID=? and ACCOUNTID=? and TOACCOUNTID=? " L"and ISTRANSFER=?;"); wchar_t sqldate[24]; wcscpy(sqldate,pr->date); sqldate[10] = '%'; sqldate[11] = '\0'; cmd.bind(1,sqldate,lstrlen(sqldate)*2); cmd.bind(2,pr->amount); cmd.bind(3,static_cast<int>(pr->categoryid)); cmd.bind(4,static_cast<int>(pr->accountid)); cmd.bind(5,static_cast<int>(pr->toaccountid)); cmd.bind(6,static_cast<int>(pr->isTransfer)); sqlite3_reader reader = cmd.executereader(); if(reader.getint(0) > 0){ retid = reader.getint(1); } }CATCH(exception &ex){ db_out(ex.what()); } return retid; } //////////////////////人员相关//////////////////// //创建:默认人员 bool clsCASHDB::createDefaultPersons(){ bool bRet = true; TRY{ //create table sqlite3_command cmd(sqlconn, L"create table if not exist '" TABLE_PERSON L"' (ID integer primary key not null, NAME text not null, TYPE numeric not null);" ); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } if(!bRet) return bRet; //创建table失败 TRY{ sqlite3_command cmd(sqlconn, L"insert into '" TABLE_PERSON L"' (ID,NAME,TYPE) " L"values(?,?,?);" ); cmd.bind(1,0); cmd.bind(2, LOADSTRING(IDS_STR_PERSON_DEFAULT).C_Str(), LOADSTRING(IDS_STR_PERSON_DEFAULT).Length()*2); cmd.bind(3,static_cast<int>(PRSN_FAMILY)); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //新增:人员 bool clsCASHDB::appendPerson(CASH_PERSON_ptr p){ if(p == NULL || p->name == NULL) return false; bool bRet = true; TRY{ p->id = getMaxPersonID() + 1; //check if is being used sqlite3_command cmd(sqlconn, L"insert into '" TABLE_TRANSACTION L"' (ID, NAME, TYPE) values(?,?,?);"); cmd.bind(1,static_cast<int>(p->id)); cmd.bind(2,p->name,lstrlen(p->name)*2); cmd.bind(3,static_cast<int>(p->type)); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //删除:人员:根据ID bool clsCASHDB::deletePersonById(int id){ bool bRet = true; TRY{ //检查是否正在被使用 sqlite3_command cmd(sqlconn, L"select count(*) from '" TABLE_TRANSACTION L"' where PERSON_ID=?;"); cmd.bind(1,id); if(cmd.executeint() > 0){ bRet = false; } }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } if(!bRet) return bRet; TRY{ //从数据库中删除 sqlite3_command cmd(sqlconn, L"delete from '" TABLE_PERSON L"' where ID=?;"); cmd.bind(1,id); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //更新:人员 bool clsCASHDB::updatePerson(CASH_PERSON_ptr p){ if(p == NULL || p->name == NULL) return false; bool bRet = true; TRY{ //check if is being used sqlite3_command cmd(sqlconn, L"update '" TABLE_TRANSACTION L"' set NAME=?, TYPE=?, ID=?;"); cmd.bind(1,p->name,lstrlen(p->name)*2); cmd.bind(2,static_cast<int>(p->type)); cmd.bind(3,static_cast<int>(p->id)); cmd.executenonquery(); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //获取:人员:根据ID CASH_PERSON_ptr clsCASHDB::personById(int id){ CASH_PERSON_ptr pPerson = NULL; TRY{ sqlite3_command cmd(sqlconn, L"select * from '" TABLE_PERSON L"' where ID=?"); cmd.bind(1,id); if(!searchPerson(cmd)){ pPerson = list_search_person.front(); } }CATCH(exception ex){ db_out(ex.what()); } return pPerson; } //获取:人员名称:根据ID wchar_t* clsCASHDB::getPersonNameById(int id){ CASH_PERSON_ptr p = personById(id); if(p){ return p->name; } return NULL; } //获取:人员:最大编号 int clsCASHDB::getMaxPersonID(){ int nRet = 0; TRY{ sqlite3_command cmd(sqlconn, L"select max(id) from '" TABLE_PERSON L"';"); nRet = cmd.executeint(); }CATCH(exception &ex){ db_out(ex.what()); } return nRet; } //人员类型列表名称ID const int PersonTypeStrID[] = { IDS_STR_PERSON_FAMILY, IDS_STR_PERSON_CONTACT, IDS_STR_PERSON_INSTITUTION }; //获取:人员类型:名称 int clsCASHDB::getPersonTypeNameStrID(CASH_PERSON_TYPE_t tid){ int tsize = sizeof(PersonTypeStrID)/sizeof(PersonTypeStrID[0]); if(tid >= tsize) tid = PRSN_FAMILY; return PersonTypeStrID[tid]; } //获取:人员:类型名称列表 const int* clsCASHDB::getPersonTypeNameStrSet(int *nsize){ if(nsize) *nsize = sizeof(PersonTypeStrID)/sizeof(PersonTypeStrID[0]); return PersonTypeStrID; } //获取:人员列表:根据类型 bool clsCASHDB::getPersonByType(CASH_PERSON_TYPE_t t){ bool bRet = false; TRY{ if( t == PRSN_ALL ){ sqlite3_command cmd(sqlconn, L"select * from '" TABLE_PERSON L"' order by type"); bRet = searchPerson(cmd); }else{ sqlite3_command cmd(sqlconn, L"select * from '" TABLE_PERSON L"' where TYPE=?"); cmd.bind(1,static_cast<int>(t)); bRet = searchPerson(cmd); } }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //清除:人员:搜索结果列表 void clsCASHDB::clearPersonSearchResults(){ if(!list_search_person.empty()){ list<CASH_PERSON_ptr>::iterator i = list_search_person.begin(); for(;i != list_search_person.end();i++){ delete *i; } list_search_person.clear(); } } //搜索:人员 bool clsCASHDB::searchPerson(sqlite3_command& cmd){ int resCount = 0; //do some clear work clearPersonSearchResults(); bool bRet = true; TRY{ sqlite3_reader reader = cmd.executereader(); while(reader.read()){ CASH_PERSON_ptr r = new CASH_PERSON_t; r->id = reader.getint(0); C::newstrcpy(&r->name,reader.getstring16(1).c_str()); r->type = static_cast<CASH_PERSON_TYPE_t>(reader.getint(2)); list_search_person.push_back(r); } //当无记录时 if(list_search_person.empty()) bRet = false; }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } //检查:人员名称:是否已存在 //如果存在则返回ID int clsCASHDB::checkDupPerson(CASH_PERSON_ptr pP){ if(pP == NULL || pP->name == NULL) return -1; int nRet = -1; TRY{ sqlite3_command cmd(sqlconn, L"select count(*),ID from '" TABLE_PERSON L"' where NAME=? collate nocase;"); cmd.bind(1,pP->name); sqlite3_reader reader = cmd.executereader(); while(reader.read()){ if(reader.getint(0)){ nRet = reader.getint(1); } } }CATCH(exception &ex){ db_out(ex.what()); nRet = -1; } return nRet; } #if 0 ////数据库更新 bool clsCASHDB::checkDatabaseVersion_v1(){ bool rc = false; wsprintf(sqlcmdw,L"select count(*) from sqlite_master where name=\"%s\"",V1_TABLE_TRANSACTION); if (sqlite3_prepare16(db, sqlcmdw, -1, &pStmt, &pzTail) == SQLITE_OK) { while (sqlite3_step(pStmt) == SQLITE_ROW) { int count = sqlite3_column_int(pStmt, 0); if(count == 1){ rc = true; } } }else{ rc = false; } sqlite3_finalize(pStmt); return rc; } void clsCASHDB::updateDatabaseVersion_v1(){ beginTrans(); wsprintf(sqlcmdw,L"ALTER TABLE %s RENAME TO %s",V1_TABLE_TRANSACTION,V2_TABLE_TRANSACTION); int rc = sqlite3_prepare16(db,sqlcmdw,-1,&pStmt,&pzTail); if(rc == SQLITE_OK){ rc = sqlite3_step(pStmt); }else{ return; } sqlite3_finalize(pStmt); commitTrans(); if(loadTransactions()){ list<CASH_TRANSACT_ptr>::iterator i = list_search_record.begin(); beginTrans(); for(; i != list_search_record.end(); i++){ CASH_TRANSACT_ptr r = *i; wchar_t newdate[32]; wsprintf(newdate,L"%0s 00:00:00",r->date); C::newstrcpy(&r->date,newdate); //更新日期格式 wsprintf(sqlcmdw,L"UPDATE %s SET DATE=\"%s\" WHERE TRANSACTID=%d",TABLE_TRANSACTION,r->date,r->transid); rc = sqlite3_prepare16(db,sqlcmdw,-1,&pStmt,&pzTail); if(rc == SQLITE_OK){ rc = sqlite3_step(pStmt); } sqlite3_finalize(pStmt); } commitTrans(); //清理工作 clean(); } } bool clsCASHDB::TableExists(wchar_t* tablename){ bool nRet = false; wsprintf(sqlcmdw,L"select count(*) from sqlite_master where type='table' and name = '%s'",tablename); if (sqlite3_prepare16(db,sqlcmdw,-1,&pStmt,&pzTail) == SQLITE_OK) { if(sqlite3_step(pStmt) == SQLITE_ROW){ nRet = (sqlite3_column_int(pStmt, 0) != 0); } } sqlite3_finalize(pStmt); return nRet; } bool clsCASHDB::addFieldPerson(){ //检查是否存在PERSON_ID字段 bool bfield = false; int rc = 0; wsprintf(sqlcmdw,L"select PERSON_ID from %s",TABLE_TRANSACTION); if (sqlite3_prepare16(db, sqlcmdw, -1, &pStmt, &pzTail) == SQLITE_OK) { rc = sqlite3_step(pStmt); if(rc == SQLITE_ROW || rc == SQLITE_DONE) { bfield = true; } } sqlite3_finalize(pStmt); //字段不存在,增加字段 bool retval = false; if(!bfield){ wsprintf(sqlcmdw, L"ALTER TABLE '%s' ADD COLUMN PERSON_ID NUMERIC NOT NULL DEFAULT 0", TABLE_TRANSACTION); if (sqlite3_prepare16(db, sqlcmdw, -1, &pStmt, &pzTail) == SQLITE_OK) { if(sqlite3_step(pStmt) == SQLITE_DONE) { retval = true; } } sqlite3_finalize(pStmt); } return retval; } #endif /////////////数据库操作 bool clsCASHDB::beginTrans(){ bool bRet = true; TRY{ sqlconn.executenonquery(L"begin;"); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } bool clsCASHDB::commitTrans(){ bool bRet = true; TRY{ sqlconn.executenonquery(L"commit;"); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; } bool clsCASHDB::reorgDatebase(){ bool bRet = true; TRY{ sqlconn.executenonquery(L"VACUUM"); }CATCH(exception &ex){ db_out(ex.what()); bRet = false; } return bRet; }
[ "jemyzhang@e7c2eee8-530d-454e-acc3-bb8019a9d48c" ]
[ [ [ 1, 1968 ] ] ]
8875694e9fd29d69ffdea114f94a14b16afbb307
3e3d5fa109cdd653d43867b46307683514d916a0
/src/feature/HfccExtractor.cpp
f708be8c6c4ddb61d1d0d353bff9dd9fa7dc9651
[]
no_license
badog1011/aquila
b8a767ea07829934bbbb2b2a4e501e473cfae301
887a63ddb032cfc7f71cce72a439b5b5dd2fe65c
refs/heads/master
2016-08-12T00:32:19.598867
2010-03-25T11:28:56
2010-03-25T11:28:56
50,173,002
0
0
null
null
null
null
UTF-8
C++
false
false
3,000
cpp
/** * @file HfccExtractor.cpp * * HFCC feature extraction - implementation. * * @author Zbigniew Siciarz * @date 2007-2010 * @version 2.5.1 * @since 2.5.1 */ #include "HfccExtractor.h" #include "../MelFiltersBank.h" namespace Aquila { MelFiltersBank* HfccExtractor::hfccFilters = 0; /** * Sets frame length and number of parameters per frame. * * @param frameLength frame length in milliseconds * @param paramsPerFrame number of params per frame */ HfccExtractor::HfccExtractor(unsigned int frameLength, unsigned int paramsPerFrame): MfccExtractor(frameLength, paramsPerFrame) { type = "HFCC"; } /** * Deletes the extractor object. */ HfccExtractor::~HfccExtractor() { } /** * Calculates HFCC features for each frame. * * @param wav recording object * @param options transform options */ void HfccExtractor::process(WaveFile* wav, const TransformOptions& options) { wavFilename = wav->getFilename(); unsigned int framesCount = wav->getFramesCount(); featureArray.resize(framesCount); if (m_indicator) m_indicator->start(0, framesCount-1); unsigned int N = wav->getSamplesPerFrameZP(); updateFilters(wav->getSampleFrequency(), N); spectrumType frameSpectrum(N); std::vector<double> filtersOutput(MELFILTERS); std::vector<double> frameHfcc(m_paramsPerFrame); Transform transform(options); // for each frame: FFT -> Mel filtration -> DCT for (unsigned int i = 0; i < framesCount; ++i) { transform.fft(wav->frames[i], frameSpectrum); hfccFilters->applyAll(frameSpectrum, N, filtersOutput); transform.dct(filtersOutput, frameHfcc); featureArray[i] = frameHfcc; if (m_indicator) m_indicator->progress(i); } if (m_indicator) m_indicator->stop(); } /** * Updates the filter bank. * * (Re)creates new filter bank when sample frequency or spectrum size * changed. If requested, enables only some filters. * * @param frequency sample frequency * @param N spectrum size */ void HfccExtractor::updateFilters(unsigned int frequency, unsigned int N) { if (!hfccFilters) { hfccFilters = new MelFiltersBank(frequency, N, true); } else { if (hfccFilters->getSampleFrequency() != frequency || hfccFilters->getSpectrumLength() != N) { delete hfccFilters; hfccFilters = new MelFiltersBank(frequency, N, true); } } if (enabledFilters) hfccFilters->setEnabledFilters(enabledFilters); } }
[ "antyqjon@e3e259e2-fbb7-11de-bceb-371847987001" ]
[ [ [ 1, 109 ] ] ]
4486221a64c2dd57e2f9a76a0a540d3e37fba81d
291355fd4592e4060bca01383e2c3a2eff55bd58
/src/stringlist.h
03e2b59c552e171e2c54bc1c509e6fb74a5d2de8
[]
no_license
rrader/cprompt
6d7c9aac25d134971bbf99d4e84848252a626bf3
dfb7d55111b6e8d3c3a0a0a1c703c04a58d5e808
refs/heads/master
2020-05-16T22:06:16.127336
2010-01-23T21:33:04
2010-01-23T21:33:04
1,659,726
1
1
null
null
null
null
UTF-8
C++
false
false
1,306
h
#ifndef STRINGLIST_H_INCLUDED #define STRINGLIST_H_INCLUDED #include "lists.h" #include "string.h" namespace ag { class stringlist : public ag::list<char*> { public: stringlist():list<char*>() {}; stringlist(char*ar[],int count) { for(int i=0;i<count;i++) addstr(ar[i]); }; void addstr(char* s) { char* c=new char[strlen(s)+1]; strcpy(c,s); c[strlen(s)]=0; add_tail(c); }; member findstr(char* s) { member p=head; while (p!=NULL) { if (strcmp(p->data,s)==0) return p; p=p->next; } return NULL; }; char* makestrfromelements() { int iSz=0; for(member sm=head;sm!=NULL;sm=sm->next) iSz+=strlen(sm->data); char* s=new char[iSz+1]; int iSz2=0; for(member sm=head;sm!=NULL;sm=sm->next) { for(int i=0;i<strlen(sm->data);i++) s[i+iSz2]=sm->data[i]; iSz2+=strlen(sm->data); } s[iSz]=0; return s; }; private: }; } #endif // STRINGLIST_H_INCLUDED
[ [ [ 1, 60 ] ] ]
729b0d7c1b7a4d8b420d9ef029367d87fad59c3a
8270eedb9660f6257229db97f767b91d7054b568
/usaco_oct09/sinavcan/milkweed.cpp
5b92304579e9ca2d17b2a1327af553fe490ba683
[]
no_license
kuzux/olimpcan
979201e982e15741248b5d0574a7f4ffdb14c7f2
947cb5f5dab6c78cbee2d6fa12b081817b684d37
refs/heads/master
2016-09-05T13:19:25.681613
2009-12-19T12:51:10
2009-12-19T12:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,627
cpp
/* PROG: milkweed LANG: C++ ID: kuzux921 */ #include<fstream> #define GRASS '.' #define ROCK '*' #define WEED 'W' using namespace std; char field[100][100]; char next[100][100]; int W, H, ngrass; void control(int i, int j){ if(i&&field[i-1][j]==WEED){ next[i][j] = WEED; ngrass--; } else if(j&&field[i][j-1]==WEED){ next[i][j] = WEED; ngrass--; } else if(i&&j&&field[i-1][j-1]==WEED){ next[i][j] = WEED; ngrass--; } else if(i!=H-1&&field[i+1][j]==WEED){ next[i][j] = WEED; ngrass--; } else if(j!=W-1&&field[i][j+1]==WEED){ next[i][j] = WEED; ngrass--; } else if(i!=H-1&&j!=W-1&&field[i+1][j+1]==WEED){ next[i][j] = WEED; ngrass--; } else if(i&&j!=W-1&&field[i-1][j+1]==WEED){ next[i][j] = WEED; ngrass--; } else if(j&&i!=H-1&&field[i+1][j-1]==WEED){ next[i][j] = WEED; ngrass--; } } void nextweek(){ for(int i=0;i<H;i++) for(int j=0;j<W;j++) field[i][j] = next[i][j]; } int main(){ ifstream in("milkweed.in"); ofstream out("milkweed.out"); int sx, sy; in >> W >> H >> sx >> sy; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ in >> next[i][j]; if(next[i][j]==GRASS) ngrass++; } } ngrass--; next[H-sy][sx-1]=WEED; int week; nextweek(); for(week=0;;week++){ if(ngrass==0) break; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(field[i][j]!=GRASS) continue; control(i,j); } } nextweek(); } out << week << endl; return 0; }
[ [ [ 1, 91 ] ] ]
1311e53a28288a87aad60f2b7e8d5d778394c78d
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Interface/WndChangeName.cpp
54cf9807ddcf5fd9fd4b87ee092f481b734f8553
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UHC
C++
false
false
5,358
cpp
#include "stdafx.h" #include "resData.h" #include "WndChangeName.h" #include "dpclient.h" #include "definetext.h" extern CDPClient g_DPlay; /* WndId : APP_CHANGENAME CtrlId : WIDC_STATIC1 CtrlId : WIDC_OK CtrlId : WIDC_CANCEL CtrlId : WIDC_EDIT_CHANGENAME */ CWndChangeName::CWndChangeName() { } CWndChangeName::~CWndChangeName() { } void CWndChangeName::OnDraw( C2DRender* p2DRender ) { #ifdef __S_SERVER_UNIFY if( g_WndMng.m_bAllAction == FALSE ) { CRect rectRoot = m_pWndRoot->GetLayoutRect(); CRect rectWindow = GetWindowRect(); CPoint point( rectRoot.right - rectWindow.Width(), 110 ); Move( point ); MoveParentCenter(); } #endif // __S_SERVER_UNIFY } void CWndChangeName::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); m_dwData = 0; CRect rectRoot = m_pWndRoot->GetLayoutRect(); CRect rectWindow = GetWindowRect(); CPoint point( rectRoot.right - rectWindow.Width(), 110 ); Move( point ); MoveParentCenter(); } BOOL CWndChangeName::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_CHANGENAME, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndChangeName::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndChangeName::OnSize( UINT nType, int cx, int cy ) { CWndNeuz::OnSize( nType, cx, cy ); } void CWndChangeName::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndChangeName::OnLButtonDown( UINT nFlags, CPoint point ) { } void CWndChangeName::SetData( WORD wId, WORD wReset ) { m_dwData = MAKELONG( wId, wReset ); } extern DWORD IsValidPlayerName( CString& strName ); BOOL CWndChangeName::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if( nID == WIDC_OK ) { CWndEdit* pEdit = (CWndEdit*)GetDlgItem( WIDC_EDIT_CHANGENAME ); CString string = pEdit->GetString(); DWORD dwError = ::IsValidPlayerName( string ); if( dwError > 0 ) { g_WndMng.OpenMessageBox( prj.GetText(dwError) ); pEdit->SetFocus(); return TRUE; } if( prj.IsInvalidName( string ) #ifdef __RULE_0615 || prj.IsAllowedLetter( string ) == FALSE #endif // __RULE_0615 ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0020) ) ); return TRUE; } g_DPlay.SendQuerySetPlayerName( m_dwData, (LPSTR)(LPCSTR)string ); Destroy(); } else if( nID == WIDC_CANCEL || nID == WTBID_CLOSE ) { #ifdef __S_SERVER_UNIFY if( g_WndMng.m_bAllAction == FALSE ) return TRUE; #endif // __S_SERVER_UNIFY Destroy(); } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } #ifdef __PET_1024 CWndChangePetName::CWndChangePetName() { m_dwId = 0; } CWndChangePetName::~CWndChangePetName() { } void CWndChangePetName::OnDraw( C2DRender* p2DRender ) { #ifdef __S_SERVER_UNIFY if( g_WndMng.m_bAllAction == FALSE ) { CRect rectRoot = m_pWndRoot->GetLayoutRect(); CRect rectWindow = GetWindowRect(); CPoint point( rectRoot.right - rectWindow.Width(), 110 ); Move( point ); MoveParentCenter(); } #endif // __S_SERVER_UNIFY } void CWndChangePetName::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); m_dwData = 0; CRect rectRoot = m_pWndRoot->GetLayoutRect(); CRect rectWindow = GetWindowRect(); CPoint point( rectRoot.right - rectWindow.Width(), 110 ); Move( point ); MoveParentCenter(); } BOOL CWndChangePetName::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_CHANGENAME, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndChangePetName::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndChangePetName::OnSize( UINT nType, int cx, int cy ) { CWndNeuz::OnSize( nType, cx, cy ); } void CWndChangePetName::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndChangePetName::OnLButtonDown( UINT nFlags, CPoint point ) { } void CWndChangePetName::SetData( WORD wId, WORD wReset ) { m_dwData = MAKELONG( wId, wReset ); } //extern DWORD IsValidPlayerName( CString& strName ); BOOL CWndChangePetName::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { if( nID == WIDC_OK ) { CWndEdit* pEdit = (CWndEdit*)GetDlgItem( WIDC_EDIT_CHANGENAME ); CString string = pEdit->GetString(); DWORD dwError = ::IsValidPlayerName( string ); if( dwError > 0 ) { g_WndMng.OpenMessageBox( prj.GetText(dwError) ); pEdit->SetFocus(); return TRUE; } if( prj.IsInvalidName( string ) #ifdef __RULE_0615 || prj.IsAllowedLetter( string ) == FALSE #endif // __RULE_0615 ) { g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0020) ) ); return TRUE; } // 펫 이름을 바꾸도록 요청하는 함수를 호출한다 g_DPlay.SendDoUseItemInput(m_dwId, (LPSTR)(LPCSTR)string); Destroy(); } else if( nID == WIDC_CANCEL || nID == WTBID_CLOSE ) { #ifdef __S_SERVER_UNIFY if( g_WndMng.m_bAllAction == FALSE ) return TRUE; #endif // __S_SERVER_UNIFY Destroy(); } return CWndNeuz::OnChildNotify( message, nID, pLResult ); } #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 235 ] ] ]
6f96eec35844f3f7da8148a043f74571f9a00a54
80959be98b57106e6bd41c33c5bfb7dd5e9c88cd
/SkyBox.cpp
4cbade43d66223afb8bc16b41d9909633ef6f64e
[]
no_license
dalorin/FPSDemo
e9ab067cfad73d404cc0ea01190212d5192405b0
cf29b61a9654652a3f8d60d742072e1a8eaa3ca7
refs/heads/master
2020-07-26T17:42:10.801273
2010-12-27T00:16:55
2010-12-27T00:16:55
1,199,462
1
0
null
null
null
null
UTF-8
C++
false
false
3,803
cpp
#include "SkyBox.h" #include "Utils.h" #include <vector> #include "Shader.h" #include "GameEngine.h" SkyBox::SkyBox(GameEngine *engine, const char* north, const char* south, const char* east, const char* west, const char* up, const char* down) : Object(engine) { // Load skybox textures m_textures = new GLuint[5]; glGenTextures(5, m_textures); Utils::loadTexture(north, m_textures[0]); Utils::loadTexture(south, m_textures[1]); Utils::loadTexture(east, m_textures[2]); Utils::loadTexture(west, m_textures[3]); Utils::loadTexture(up, m_textures[4]); GLfloat length, neg_length; length = 1.0f; neg_length = -length; // Construct skybox GLfloat vertices[] = { //North length, length, neg_length, neg_length, length, neg_length, neg_length, neg_length, neg_length, length, neg_length, neg_length, //South neg_length, length, length, length, length, length, length, neg_length, length, neg_length, neg_length, length, //East length, length, length, length, length, neg_length, length, neg_length, neg_length, length, neg_length, length, //West neg_length, length, neg_length, neg_length, length, length, neg_length, neg_length, length, neg_length, neg_length, neg_length, //Up neg_length, length, neg_length, length, length, neg_length, length, length, length, neg_length, length, length, }; glGenBuffers(1, &m_vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); glBufferData(GL_ARRAY_BUFFER, 60 * sizeof(GLfloat), vertices, GL_STATIC_DRAW); std::vector<GLshort> texCoords; for (int i = 0; i < 5; i++) { texCoords.push_back(1); texCoords.push_back(1); texCoords.push_back(0); texCoords.push_back(1); texCoords.push_back(0); texCoords.push_back(0); texCoords.push_back(1); texCoords.push_back(0); } glGenBuffers(1, &m_texCoordBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_texCoordBuffer); glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(GLshort), &texCoords[0], GL_STATIC_DRAW); //Set material properties. m_materialProps.setProperty(MaterialProps::AMBIENT, 1.0f, 1.0f, 1.0f, 1.0f); m_materialProps.setProperty(MaterialProps::DIFFUSE, 0.0f, 0.0f, 0.0f, 1.0f); m_materialProps.setProperty(MaterialProps::SPECULAR, 0.0f, 0.0f, 0.0f, 1.0f); m_materialProps.setProperty(MaterialProps::EMISSIVE, 0.0f, 0.0f, 0.0f, 1.0f); m_materialProps.setShininess(0.0f); } void SkyBox::onPrepare(GLfloat dt) { } void SkyBox::onRender() { glPushMatrix(); GLfloat modelviewMatrix[16]; glGetFloatv(GL_MODELVIEW_MATRIX, modelviewMatrix); // Remove translation from modelview matrix. for (int i = 12; i <= 14; i++) modelviewMatrix[i] = 0.0f; glLoadMatrixf(modelviewMatrix); glScalef(500.0f, 500.0f, 500.0f); glTranslatef(0.0f, 0.2f, 0.0f); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, m_texCoordBuffer); glVertexAttribPointer(2, 2, GL_SHORT, GL_FALSE, 0, BUFFER_OFFSET(0)); glEnableVertexAttribArray(2); ShaderProgram *program = m_engine->m_skyboxProgram; program->bind(); program->sendMatrices(); program->sendUniform("texture0", 0); program->sendMaterialProps(m_materialProps); for (int i = 0; i < 5; i++) { glBindTexture(GL_TEXTURE_2D, m_textures[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glDrawArrays(GL_QUADS, (i) * 4, 4); } glDisableVertexAttribArray(2); glDisableVertexAttribArray(0); glPopMatrix(); } SkyBox::~SkyBox(void) { }
[ [ [ 1, 136 ] ] ]
971111cfad8ffe0c902c3c2f785ee3f38b028eab
b8ac0bb1d1731d074b7a3cbebccc283529b750d4
/Code/controllers/OdometryCalibration/robotapi/DifferentialWheelsWOdometry.h
612da3bbdebc347fb168b22b4eea4f512c611fac
[]
no_license
dh-04/tpf-robotica
5efbac38d59fda0271ac4639ea7b3b4129c28d82
10a7f4113d5a38dc0568996edebba91f672786e9
refs/heads/master
2022-12-10T18:19:22.428435
2010-11-05T02:42:29
2010-11-05T02:42:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,103
h
#ifndef robotapi_DifferentialWheelsWOdometry_h #define robotapi_DifferentialWheelsWOdometry_h #include <robotapi/IDifferentialWheels.h> #include <utils/MyPoint.h> #include <utils/MyAngle.h> #include <WorldInfo.h> namespace robotapi { class DifferentialWheelsWOdometry : public robotapi::IDifferentialWheels { public: DifferentialWheelsWOdometry(WorldInfo * wi); // class destructor virtual ~DifferentialWheelsWOdometry(){}; virtual double getLeftEncoder(); virtual double getRightEncoder(); void computeOdometry(); double getOrientation(); utils::MyPoint * getPosition(); private: void computePosition(double ldist, double rdist); double distanceBetweenWheels; double leftWheelRadius; double rightWheelRadius; double encoderResolution; double lastLeftEncoder; double lastRightEncoder; robotapi::IDifferentialWheels * wheels; utils::MyPoint * lastPosition; utils::MyAngle * lastAngle; }; } /* End of namespace robotapi */ #endif // robotapi_DifferentialWheelsWOdometry_h
[ "guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a" ]
[ [ [ 1, 43 ] ] ]
936cf1cfe75b774a5be732b64c0acdbb8dd04350
58ef4939342d5253f6fcb372c56513055d589eb8
/DesktopHotKey/Client/inc/DesktopHotKeyAppView.h
92dce1b1ec4e9e33a225ae4d9fce5fc3126540fd
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
UTF-8
C++
false
false
1,205
h
/* ============================================================================ Name : DesktopHotKeyAppView.h Author : zengcity Copyright : Your copyright notice Description : Declares view class for application. ============================================================================ */ #ifndef __DESKTOPHOTKEYAPPVIEW_h__ #define __DESKTOPHOTKEYAPPVIEW_h__ // INCLUDES #include <e32std.h> #include <e32base.h> #include <aknview.h> #include <avkon.hrh> #include <f32file.h> #include "DesktopHotKeyAppContainer.h" // CLASS DECLARATION class CDesktopHotKeyAppView : public CAknView { public: // Constructors and destructor ~CDesktopHotKeyAppView(); static CDesktopHotKeyAppView* NewL(); static CDesktopHotKeyAppView* NewLC(); public: TUid Id() const; void HandleCommandL(TInt aCommand); void HandleStatusPaneSizeChange(); private: CDesktopHotKeyAppView(); void ConstructL(); protected: void DoActivateL(const TVwsViewId& aPrevViewId, TUid aCustomMessageId, const TDesC8& aCustomMessage); void DoDeactivate(); private: CDesktopHotKeyAppContainer * iContainer; }; #endif // __DESKTOPHOTKEYAPPVIEW_h__ // End of File
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 50 ] ] ]
7d21c95974e09bbb9771f962d15444244cc086f2
6581dacb25182f7f5d7afb39975dc622914defc7
/WinsockLab/SO_RCVTIMEO/SO_RCVTIMEOsrc.cpp
d793acabca490743f06889a8a1649fd832432f37
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,078
cpp
// Description: // This is a trivial sample that sets the receive timeout // option and then attempts to receive a datagram which will // fail with a timeout message. // // No command line arguments // // Link to ws2_32.lib #include <windows.h> #include <winsock.h> #include <stdio.h> // Function: main // Description: // Load Winsock, create a UDP socket, set the timeout value, // and then call recvfrom() will will fail with a timeout since // no data is being sent. int main(int argc, char **argv) { WSADATA wsd; SOCKADDR_IN from; SOCKET s; int ret, iVal=0, fromsz; unsigned int sz = sizeof(iVal); char rcvbuf[1024]; // Load Winsock if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { printf("WSAStartup() failed with error code %d\n", WSAGetLastError()); return -1; } else printf("WSAStartup() should be OK!\n"); // Create a datagram socket s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (s == INVALID_SOCKET) { printf("socket() failed with error code %d\n", WSAGetLastError()); return -1; } else printf("socket() is OK!\n"); // Set the timeout value iVal = 1000; ret = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *)&iVal, sz); if (ret == SOCKET_ERROR) { printf("setsockopt() failed with error code %d\n", WSAGetLastError()); return -1; } else printf("setsockopt() is OK!\n"); printf("Timeout was set...\n"); // Retrieve the value just to be sure printf("Do a verification...\n"); ret = getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *)&iVal, &sz); if (ret == SOCKET_ERROR) { printf("getsockopt() failed with error code %d\n", WSAGetLastError()); return -1; } else printf("getsockopt() is fine!\n"); printf("Timeout value == %d\n", iVal); // To test the receive function we need to bind first from.sin_family = AF_INET; from.sin_addr.s_addr = htonl(INADDR_ANY); from.sin_port = htons(5150); ret = bind(s, (SOCKADDR *)&from, sizeof(from)); if (ret == SOCKET_ERROR) { printf("bind() failed: %d\n", WSAGetLastError()); return -1; } // Call receive which will fail with WSAETIMEDOUT fromsz = sizeof(from); ret = recvfrom(s, rcvbuf, 1024, 0, (SOCKADDR *)&from, &fromsz); if (ret == SOCKET_ERROR) { if (WSAGetLastError() == WSAETIMEDOUT) printf("recvfrom() failed with error code 10060 (WSAETIMEDOUT)\n"); else printf("recvfrom() failed with error code %d\n", WSAGetLastError()); } else printf("recvfrom() looks fine!\n"); if(closesocket(s) == 0) printf("closesocket() should be fine!\n"); else printf("closesocket() failed with error code %d\n", WSAGetLastError()); if(WSACleanup() == 0) printf("WSACleanup() is OK!\n"); else printf("WSACleanup() failed with error code %d\n", WSAGetLastError()); return 0; }
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 107 ] ] ]
dfcfb3bc150fbefbb4bceeb0f57d2c707e548d18
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/SRC/Protos/arp.cc
ac52e897031613478200d65ae8da09631f7df644
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
UTF-8
C++
false
false
17,548
cc
// GENERAL PUBLIC LICENSE AGREEMENT // // PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM // // BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF // THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO // NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER. // // This Program is licensed, not sold to you by GEORGIA TECH RESEARCH // CORPORATION ("GTRC"), owner of all code and accompanying documentation // (hereinafter "Program"), for use only under the terms of this License, // and GTRC reserves any rights not expressly granted to you. // // 1. This License allows you to: // // (a) make copies and distribute copies of the Program's source code // provide that any such copy clearly displays any and all appropriate // copyright notices and disclaimer of warranty as set forth in Article 5 // and 6 of this License. All notices that refer to this License and to // the absence of any warranty must be kept intact at all times. A copy // of this License must accompany any and all copies of the Program // distributed to third parties. // // A fee may be charged to cover the cost associated with the physical // act of transferring a copy to a third party. At no time shall the // program be sold for commercial gain either alone or incorporated with // other program(s) without entering into a separate agreement with GTRC. // // // (b) modify the original copy or copies of the Program or any portion // thereof ("Modification(s)"). Modifications may be copied and // distributed under the terms and conditions as set forth above, // provided the following conditions are met: // // i) any and all modified files must be affixed with prominent // notices that you have changed the files and the date that the changes // occurred. // // ii) any work that you distribute, publish, or make available, that // in whole or in part contains portions of the Program or derivative // work thereof, must be licensed at no charge to all third parties under // the terms of this License. // // iii) if the modified program normally reads commands interactively // when run, you must cause it, when started running for such interactive // use in the most ordinary way, to display and/or print an announcement // with all appropriate copyright notices and disclaimer of warranty as // set forth in Article 5 and 6 of this License to be clearly displayed. // In addition, you must provide reasonable access to this License to the // user. // // Any portion of a Modification that can be reasonably considered // independent of the Program and separate work in and of itself is not // subject to the terms and conditions set forth in this License as long // as it is not distributed with the Program or any portion thereof. // // // 2. This License further allows you to copy and distribute the Program // or a work based on it, as set forth in Article 1 Section b in // object code or executable form under the terms of Article 1 above // provided that you also either: // // i) accompany it with complete corresponding machine-readable source // code, which must be distributed under the terms of Article 1, on a // medium customarily used for software interchange; or, // // ii) accompany it with a written offer, valid for no less than three // (3) years from the time of distribution, to give any third party, for // no consideration greater than the cost of physical transfer, a // complete machine-readable copy of the corresponding source code, to be // distributed under the terms of Article 1 on a medium customarily used // for software interchange; or, // // // 3. Export Law Assurance. // // You agree that the Software will not be shipped, transferred or // exported, directly into any country prohibited by the United States // Export Administration Act and the regulations thereunder nor will be // used for any purpose prohibited by the Act. // // 4. Termination. // // If at anytime you are unable to comply with any portion of this // License you must immediately cease use of the Program and all // distribution activities involving the Program or any portion thereof. // // // 5. Disclaimer of Warranties and Limitation on Liability. // // YOU ACCEPT THE PROGRAM ON AN "AS IS" BASIS. GTRC MAKES NO WARRANTY // THAT ALL ERRORS CAN BE OR HAVE BEEN ELIMINATED FROM PROGRAM. GTRC // SHALL NOT BE RESPONSIBLE FOR LOSSES OF ANY KIND RESULTING FROM THE USE // OF PROGRAM AND ITS ACCOMPANYING DOCUMENT(S), AND CAN IN NO WAY PROVIDE // COMPENSATION FOR ANY LOSSES SUSTAINED, INCLUDING BUT NOT LIMITED TO // ANY OBLIGATION, LIABILITY, RIGHT, CLAIM OR REMEDY FOR TORT, OR FOR ANY // ACTUAL OR ALLEGED INFRINGEMENT OF PATENTS, COPYRIGHTS, TRADE SECRETS, // OR SIMILAR RIGHTS OF THIRD PARTIES, NOR ANY BUSINESS EXPENSE, MACHINE // DOWNTIME OR DAMAGES CAUSED TO YOU BY ANY DEFICIENCY, DEFECT OR ERROR // IN PROGRAM OR MALFUNCTION THEREOF, NOR ANY INCIDENTAL OR CONSEQUENTIAL // DAMAGES, HOWEVER CAUSED. GTRC DISCLAIMS ALL WARRANTIES, BOTH EXPRESS // AND IMPLIED RESPECTING THE USE AND OPERATION OF PROGRAM AND ITS // ACCOMPANYING DOCUMENTATION, INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR PARTICULAR PURPOSE AND ANY IMPLIED // WARRANTY ARISING FROM COURSE OF PERFORMANCE, COURSE OF DEALING OR // USAGE OF TRADE. GTRC MAKES NO WARRANTY THAT PROGRAM IS ADEQUATELY OR // COMPLETELY DESCRIBED IN, OR BEHAVES IN ACCORDANCE WITH ANY // ACCOMPANYING DOCUMENTATION. THE USER OF PROGRAM IS EXPECTED TO MAKE // THE FINAL EVALUATION OF PROGRAM'S USEFULNESS IN USER'S OWN // ENVIRONMENT. // // GTRC represents that, to the best of its knowledge, the software // furnished hereunder does not infringe any copyright or patent. // // GTRC shall have no obligation for support or maintenance of Program. // // 6. Copyright Notice. // // THE SOFTWARE AND ACCOMPANYING DOCUMENTATION ARE COPYRIGHTED WITH ALL // RIGHTS RESERVED BY GTRC. UNDER UNITED STATES COPYRIGHT LAWS, THE // SOFTWARE AND ITS ACCOMPANYING DOCUMENTATION MAY NOT BE COPIED EXCEPT // AS GRANTED HEREIN. // // You acknowledge that GTRC is the sole owner of Program, including all // copyrights subsisting therein. Any and all copies or partial copies // of Program made by you shall bear the copyright notice set forth below // and affixed to the original version or such other notice as GTRC shall // designate. Such notice shall also be affixed to all improvements or // enhancements of Program made by you or portions thereof in such a // manner and location as to give reasonable notice of GTRC's copyright // as set forth in Article 1. // // Said copyright notice shall read as follows: // // Copyright 2004 // Dr. George F. Riley // Georgia Tech Research Corporation // Atlanta, Georgia 30332-0415 // All Rights Reserved // // $Id: arp.cc,v 1.10 2006/01/20 17:37:47 riley Exp $ // Georgia Tech Network Simulator - Address Resolution Protocol Class // Mohamed Abd Elhafez. Georgia Tech, Spring 2004 // Implements the Address Resolution Protocol, Layer 3 #include <iostream> #ifdef HAVE_QT #include <qnamespace.h> #endif #include "debug.h" #include "arp.h" #include "l2proto802.3.h" #include "node.h" #include "droppdu.h" #include "hex.h" #include "interface.h" #include "simulator.h" using namespace std; ARPHeader::ARPHeader() : hwmacaddrtype(1), protoaddrtype(0x800), hwmacaddrsize(6), protoaddrsize(4), op(0), srcmacaddr(MACAddr::NONE), srcipaddr(), dstmacaddr(MACAddr::NONE), dstipaddr() { } ARPHeader::ARPHeader(const ARPHeader& r) : hwmacaddrtype(r.hwmacaddrtype), protoaddrtype(r.protoaddrtype), hwmacaddrsize(r.hwmacaddrsize), protoaddrsize(r.protoaddrsize), op(r.op), srcmacaddr(r.srcmacaddr), srcipaddr(r.srcipaddr), dstmacaddr(r.dstmacaddr), dstipaddr(r.dstipaddr) { } ARPHeader::~ARPHeader() { } Size_t ARPHeader::Size() const { Count_t sz = 28; return sz; } // Serialization Size_t ARPHeader::SSize() { return sizeof(hwmacaddrtype) + // type sizeof(protoaddrtype) + sizeof(hwmacaddrsize) + sizeof(protoaddrsize) + sizeof(op) + sizeof(srcmacaddr) + sizeof(srcipaddr) + sizeof(dstmacaddr) + sizeof(dstipaddr); } char* ARPHeader::Serialize(char* b, Size_t& sz) { IPAddr_t src = srcipaddr; IPAddr_t dst = dstipaddr; b = SerializeToBuffer(b, sz, hwmacaddrtype); b = SerializeToBuffer(b, sz, protoaddrtype); b = SerializeToBuffer(b, sz, hwmacaddrsize); b = SerializeToBuffer(b, sz, protoaddrsize); b = SerializeToBuffer(b, sz, op); b = SerializeToBuffer(b, sz, srcmacaddr); b = SerializeToBuffer(b, sz, src); b = SerializeToBuffer(b, sz, dstmacaddr); b = SerializeToBuffer(b, sz, dst); return b; } char* ARPHeader::Construct(char* b , Size_t& sz) { IPAddr_t src ; IPAddr_t dst; b = ConstructFromBuffer(b, sz, hwmacaddrtype); b = ConstructFromBuffer(b, sz, protoaddrtype); b = ConstructFromBuffer(b, sz, hwmacaddrsize); b = ConstructFromBuffer(b, sz, protoaddrsize); b = ConstructFromBuffer(b, sz, op); b = ConstructFromBuffer(b, sz, srcmacaddr); b = ConstructFromBuffer(b, sz, src); b = ConstructFromBuffer(b, sz, dstmacaddr); b = ConstructFromBuffer(b, sz, dst); srcipaddr = IPAddr(src); dstipaddr = IPAddr(dst); return b; } void ARPHeader::Trace(Tfstream& tos, Bitmap_t b, Packet* p, const char* s) { tos << " "; if (s) tos << s; tos << "L3-ARP"; if (Detail(ARP::HWMACADDRTYPE, b)) tos << " " << hwmacaddrtype; if (Detail(ARP::PROTOADDRTYPE, b)) tos << " " << protoaddrtype; if (Detail(ARP::HWMACADDRSIZE, b)) tos << " " << hwmacaddrsize; if (Detail(ARP::PROTOADDRSIZE, b)) tos << " " << protoaddrsize; if (Detail(ARP::OP, b)) { if(op == ARP::REQUEST) tos << " REQ" ; else if(op == ARP::REPLY) tos << " RPL"; } if (Detail(ARP::SRCIPADDR, b)) tos << " " << srcipaddr; if (Detail(ARP::DSTIPADDR, b)) tos << " " << dstipaddr; if (Detail(ARP::SRCMACADDR, b)) tos << " " << srcmacaddr; if (Detail(ARP::DSTMACADDR, b)) tos << " " << dstmacaddr; if (Detail(ARP::UID, b)) { // Get uid from packet if (p) tos << " " << p->uid; else tos << " " << 0; } } // IP Protocol Class Methods ARP::ARP(Node* n) { rxtimeout = DEFAULT_RX_TIMEOUT; // Insert this protocol object in the local protocol graph for this node // if the node exists. If it doesn't exist, it will be added when // the node pointer is associted with the interface. if (n) n->InsertProto(3, Proto(), this); // Set default tracing options DetailOff(HWMACADDRTYPE); DetailOff(PROTOADDRTYPE); DetailOff(HWMACADDRSIZE); DetailOff(PROTOADDRSIZE); } void ARP::ARPRequest(Interface* i, Packet* p, int type) { IPV4Header* iphdr = (IPV4Header*)p->PeekPDU(); DEBUG(0, (cout << "Sending arp req for IP " << IPAddr::ToDotted(iphdr->dst) << endl)); // check the arp cache for the destination IP ARPCache_t::iterator j = arpcache.find(iphdr->dst); if (j != arpcache.end()) // found then just send the packet { DEBUG(0, (cout << "Entry " << IPAddr::ToDotted((*j).first) << " expires at " <<(*j).second.lifetime << endl)); if((*j).second.lifetime > Simulator::Now() ) // not Expired { DEBUG(0, (cout << "Entry found mac is ")); if ((*j).second.state == ARPEntry::RESOLVED) // We already know the MAC address { // cout << (*j).second.mac << " forwarding pkt to iface" << endl; // Send the packet to the destination mac i->Send(p, (*j).second.mac, type); } else if ((*j).second.state == ARPEntry::PENDING) // We havent resolved the IP address yet { DEBUG(0, (cout << "Unresolved yet queuing packet" << endl)); // Queue the packet for later (*j).second.pQueue.push(PacketPair_t( p, type)); } return; } // else // entry is expired // { // cout << "Entry " << IPAddr::ToDotted((*j).first) << " Is expired" << endl; // // send the packet to the old address // //i->Send(p, (*j).second.mac, type); // } } DEBUG(0,(cout << "Entry not found or expired, creating new" << endl)); // ARP entry doesnt exist or has expired // create cache entry ARPEntry e = ARPEntry(ARPEntry::PENDING, MACAddr::NONE, Simulator::Now() + timeout, 1); e.pQueue.push(PacketPair_t(p, type)); // Queue the packet for later arpcache[iphdr->dst] = e; // store the new entry // prepare arp request packet Packet* pkt; #ifdef HAVE_QT pkt = new ColoredPacket(Qt::green); // green packets #else pkt = new Packet(); #endif ARPHeader* arphdr = new ARPHeader(); arphdr->op = ARP::REQUEST; arphdr->dstmacaddr = MACAddr::NONE; // The mac address is gonna be filled in the reply arphdr->dstipaddr = iphdr->dst; arphdr->srcmacaddr = i->GetMACAddr(); arphdr->srcipaddr = i->GetIPAddr(); pkt->PushPDU(arphdr); // Add to trace file if (Trace::Enabled()) i->GetNode()->TracePDU(this, arphdr, pkt, "-"); // schedule retransmition Scheduler::Schedule(new ARPEvent(ARPEvent::RETRANSMIT, pkt->Copy(), iphdr->dst, i), rxtimeout, this); // give packet to iface to send it // ARP request packets are broadcast i->Send(pkt, MACAddr::Broadcast(), ARP_PROTOCOL); } void ARP::DataIndication(Interface* i,Packet* p) { ARPHeader* hdr = (ARPHeader*)p->PopPDU(); DEBUG(0,(cout << "Got ARP Packet " << p->uid << " For IP " << IPAddr::ToDotted(hdr->dstipaddr) << " my IP is " << i->GetIPAddr() << endl)); // Add to trace file if (Trace::Enabled()) i->GetNode()->TracePDU(this, hdr, p, "+"); // is this ARP packet for my IP Address ? if(hdr->dstipaddr == i->GetIPAddr()) { ARPCache_t::iterator j = arpcache.find(hdr->srcipaddr); // Do we already have the source entry in our cache ? if (j != arpcache.end()) // found { //cout << "Entry found updating it " << endl; // Uodating the ARP entry (*j).second.lifetime = Simulator::Now() + timeout; (*j).second.mac = hdr->srcmacaddr; // Updating the mac address in case the IP Addresses are not static if((*j).second.state == ARPEntry::PENDING) { (*j).second.state = ARPEntry::RESOLVED; // Now that we have resolved the MAC address we send all queued packets while ( !(*j).second.pQueue.empty() ) // send the queued pkts { PacketPair_t pp = (*j).second.pQueue.front(); i->Send(pp.first, hdr->srcmacaddr, pp.second); (*j).second.pQueue.pop(); // Remove from the queue } } (*j).second.retries = 0; } else { // create cache entry ARPEntry e = ARPEntry(ARPEntry::RESOLVED, hdr->srcmacaddr, Simulator::Now() + timeout, 0); arpcache[hdr->srcipaddr] = e; } if(hdr->op == ARP::REQUEST) { // prepare arp reply packet Packet* pkt; #ifdef HAVE_QT pkt = new ColoredPacket(Qt::blue); // blue packets #else pkt = new Packet(); #endif ARPHeader* arphdr = new ARPHeader(); arphdr->op = ARP::REPLY; arphdr->dstmacaddr = hdr->srcmacaddr; arphdr->dstipaddr = hdr->srcipaddr; arphdr->srcmacaddr = i->GetMACAddr(); arphdr->srcipaddr = i->GetIPAddr(); pkt->PushPDU(arphdr); // Add to trace file if (Trace::Enabled()) i->GetNode()->TracePDU(this, arphdr, pkt, "+"); // give packet to iface to send it // ARP reply packets are unicast i->Send(pkt, arphdr->dstmacaddr, ARP_PROTOCOL); } } else { // just drop the packet as it is not addressed to this host DEBUG(0,(cout << "dropping packet " << p->uid << endl)); DropPDU d("L3-NA", p); // NA= Not Addressed i->GetNode()->TracePDU(nil, &d); Stats::pktsDropped++; delete p; } } void ARP::Handle(Event* e, Time_t t) { ARPEvent* ae = (ARPEvent*)e; ARPCache_t::iterator j; switch(ae->event) { case ARPEvent::RETRANSMIT : j = arpcache.find(ae->dst); if (j != arpcache.end()) // found { if((*j).second.state == ARPEntry::PENDING) { if( ((*j).second.retries++ > MAX_RETRIES) || ((*j).second.lifetime < Simulator::Now()) ) { while ( !(*j).second.pQueue.empty() ) // delete the queued pkts { PacketPair_t pp = (*j).second.pQueue.front(); DropPDU d("L3-NE", pp.first); // NE = Not Exist (cant find mac address for that IP) ae->iface->GetNode()->TracePDU(nil, &d); DEBUG(0,(cout << "Packet Dropped " << endl)); Stats::pktsDropped++; delete pp.first; (*j).second.pQueue.pop(); } // delete entry arpcache.erase(j); } else { //cout << "Resending the arp request packet " << ae->p->uid << " at time " << t << endl; // Send the arp request one more time Scheduler::Schedule( new ARPEvent(ARPEvent::RETRANSMIT, ae->p->Copy(), ae->dst, ae->iface), rxtimeout, this); ae->iface->Send(ae->p, MACAddr::Broadcast(), ARP_PROTOCOL); } } } break; default: break; } delete ae; }
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 505 ] ] ]
76a32d0f6b6cbb83bbb9e32e31c6da01a06da770
85d9531c984cd9ffc0c9fe8058eb1210855a2d01
/QxOrm/include/QxTraits/is_std_set.h
892f36ba07463a6eb24b25d3b0d0e0d2a5f602a9
[]
no_license
padenot/PlanningMaker
ac6ece1f60345f857eaee359a11ee6230bf62226
d8aaca0d8cdfb97266091a3ac78f104f8d13374b
refs/heads/master
2020-06-04T12:23:15.762584
2011-02-23T21:36:57
2011-02-23T21:36:57
1,125,341
0
1
null
null
null
null
UTF-8
C++
false
false
1,867
h
/**************************************************************************** ** ** http://www.qxorm.com/ ** http://sourceforge.net/projects/qxorm/ ** Original file by Lionel Marty ** ** This file is part of the QxOrm library ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any ** damages arising from the use of this software. ** ** GNU Lesser General Public License Usage ** This file must be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file 'license.lgpl.txt' included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact : ** [email protected] ** ****************************************************************************/ #ifndef _QX_IS_STD_SET_H_ #define _QX_IS_STD_SET_H_ #ifdef _MSC_VER #pragma once #endif #include <set> #include <boost/mpl/if.hpp> #include <boost/mpl/logical.hpp> namespace qx { namespace trait { template <typename T> class is_std_set { private: template <typename V> static char isContainer(const std::set<V> &); static int isContainer(...); static T t; public: enum { value = (sizeof(qx::trait::is_std_set<T>::isContainer(t)) == sizeof(char)) }; typedef typename boost::mpl::if_c<qx::trait::is_std_set<T>::value, boost::mpl::true_, boost::mpl::false_>::type type; }; } // namespace trait } // namespace qx #endif // _QX_IS_STD_SET_H_
[ [ [ 1, 64 ] ] ]
fd4d1e7a7622943191d10a85930c9b956cb67063
c3ae23286c2e8268355241f8f06cd1309922a8d6
/rateracerlib/mathlib/Matrix3.cpp
7fdffc56208b026601ac141290be28f94e53d59e
[]
no_license
BackupTheBerlios/rateracer-svn
2f43f020ecdd8a3528880d474bec1c0464879597
838ad3f326962028ce8d493d2c06f6af6ea4664c
refs/heads/master
2020-06-04T03:31:51.633612
2005-05-30T06:38:01
2005-05-30T06:38:01
40,800,078
0
0
null
null
null
null
UTF-8
C++
false
false
6,755
cpp
#include "Matrix3.h" #include "Vec3.h" // // private function: RCD // - dot product of row i of matrix A and row j of matrix B // MATH_INLINE float RCD(const Matrix3& A, const Matrix3& B, int i, int j) { return A[i][0] * B[0][j] + A[i][1] * B[1][j] + A[i][2] * B[2][j]; } // // private function: MINOR // - MINOR of M[r][c]; r in {0,1,2}-{r0,r1}; c in {0,1,2}-{c0,c1} // MATH_INLINE float MINOR(const Matrix3& M, int r0, int r1, int c0, int c1) { return M[r0][c0] * M[r1][c1] - M[r1][c0] * M[r0][c1]; } // // OPERATORS // Matrix3& Matrix3::operator +=(const Matrix3& M) { m_[0][0] += M[0][0]; m_[0][1] += M[0][1]; m_[0][2] += M[0][2]; m_[1][0] += M[1][0]; m_[1][1] += M[1][1]; m_[1][2] += M[1][2]; m_[2][0] += M[2][0]; m_[2][1] += M[2][1]; m_[2][2] += M[2][2]; return *this; } Matrix3& Matrix3::operator -=(const Matrix3& M) { m_[0][0] -= M[0][0]; m_[0][1] -= M[0][1]; m_[0][2] -= M[0][2]; m_[1][0] -= M[1][0]; m_[1][1] -= M[1][1]; m_[1][2] -= M[1][2]; m_[2][0] -= M[2][0]; m_[2][1] -= M[2][1]; m_[2][2] -= M[2][2]; return *this; } Matrix3& Matrix3::operator *=(const Matrix3& M) { assign(RCD(*this, M, 0, 0), RCD(*this, M, 1, 0), RCD(*this, M, 2, 0), RCD(*this, M, 0, 1), RCD(*this, M, 1, 1), RCD(*this, M, 2, 1), RCD(*this, M, 0, 2), RCD(*this, M, 1, 2), RCD(*this, M, 2, 2)); return *this; } Matrix3& Matrix3::operator *=(float d) { m_[0][0] *= d; m_[0][1] *= d; m_[0][2] *= d; m_[1][0] *= d; m_[1][1] *= d; m_[1][2] *= d; m_[2][0] *= d; m_[2][1] *= d; m_[2][2] *= d; return *this; } Matrix3& Matrix3::operator /=(float d) { float di = 1 / d; m_[0][0] *= di; m_[0][1] *= di; m_[0][2] *= di; m_[1][0] *= di; m_[1][1] *= di; m_[1][2] *= di; m_[2][0] *= di; m_[2][1] *= di; m_[2][2] *= di; return *this; } Matrix3 Matrix3::operator +(const Matrix3& M) const { return Matrix3(m_[0][0] + M[0][0], m_[1][0] + M[1][0], m_[2][0] + M[2][0], m_[0][1] + M[0][1], m_[1][1] + M[1][1], m_[2][1] + M[2][1], m_[0][2] + M[0][2], m_[1][2] + M[1][2], m_[2][2] + M[2][2]); } Matrix3 Matrix3::operator -(const Matrix3& M) const { return Matrix3(m_[0][0] - M[0][0], m_[1][0] - M[1][0], m_[2][0] - M[2][0], m_[0][1] - M[0][1], m_[1][1] - M[1][1], m_[2][1] - M[2][1], m_[0][2] - M[0][2], m_[1][2] - M[1][2], m_[2][2] - M[2][2]); } Matrix3 Matrix3::operator -() const { return Matrix3(-m_[0][0], -m_[1][0], -m_[2][0], -m_[0][1], -m_[1][1], -m_[2][1], -m_[0][2], -m_[1][2], -m_[2][2]); } Matrix3 Matrix3::operator *(const Matrix3& M) const { return Matrix3(RCD(*this, M, 0, 0), RCD(*this, M, 1, 0), RCD(*this, M, 2, 0), RCD(*this, M, 0, 1), RCD(*this, M, 1, 1), RCD(*this, M, 2, 1), RCD(*this, M, 0, 2), RCD(*this, M, 1, 2), RCD(*this, M, 2, 2)); } Matrix3 Matrix3::operator *(float d) const { return Matrix3(m_[0][0] * d, m_[1][0] * d, m_[2][0] * d, m_[0][1] * d, m_[1][1] * d, m_[2][1] * d, m_[0][2] * d, m_[1][2] * d, m_[2][2] * d); } Matrix3 Matrix3::operator /(float d) const { assert(!isZero(d)); float di = 1 / d; return Matrix3(m_[0][0] * di, m_[1][0] * di, m_[2][0] * di, m_[0][1] * di, m_[1][1] * di, m_[2][1] * di, m_[0][2] * di, m_[1][2] * di, m_[2][2] * di); } Matrix3 operator *(float d, const Matrix3& M) { return Matrix3(M[0][0] * d, M[1][0] * d, M[2][0] * d, M[0][1] * d, M[1][1] * d, M[2][1] * d, M[0][2] * d, M[1][2] * d, M[2][2] * d); } bool Matrix3::operator ==(const Matrix3& M) const { return(fuzzyEQ(m_[0][0], M[0][0]) && fuzzyEQ(m_[0][1], M[0][1]) && fuzzyEQ(m_[0][2], M[0][2]) && fuzzyEQ(m_[1][0], M[1][0]) && fuzzyEQ(m_[1][1], M[1][1]) && fuzzyEQ(m_[1][2], M[1][2]) && fuzzyEQ(m_[2][0], M[2][0]) && fuzzyEQ(m_[2][1], M[2][1]) && fuzzyEQ(m_[2][2], M[2][2])); } bool Matrix3::operator !=(const Matrix3& M) const { return (!(*this == M)); } Vec3 Matrix3::operator *(const Vec3& v) const { return Vec3(m_[0][0] * v[0] + m_[0][1] * v[1] + m_[0][2] * v[2], m_[1][0] * v[0] + m_[1][1] * v[1] + m_[1][2] * v[2], m_[2][0] * v[0] + m_[2][1] * v[1] + m_[2][2] * v[2]); } Vec3 operator *(const Vec3& v, const Matrix3& M) { return Vec3(v[0] * M[0][0] + v[1] * M[1][0] + v[2] * M[2][0], v[0] * M[0][1] + v[1] * M[1][1] + v[2] * M[2][1], v[0] * M[0][2] * v[1] * M[1][2] + v[2] * M[2][2]); } // // OPERATIONS // Matrix3 Matrix3::transpose() const { return Matrix3(m_[0][0], m_[0][1], m_[0][2], m_[1][0], m_[1][1], m_[1][2], m_[2][0], m_[2][1], m_[2][2]); } Matrix3 Matrix3::inverse() const { assert(!isSingular()); return adjoint() / determinant(); } Matrix3 Matrix3::adjoint() const { return Matrix3( MINOR(*this, 1, 2, 1, 2), -MINOR(*this, 1, 2, 0, 2), MINOR(*this, 1, 2, 0, 1), -MINOR(*this, 0, 2, 1, 2), MINOR(*this, 0, 2, 0, 2), -MINOR(*this, 0, 2, 0, 1), MINOR(*this, 0, 1, 1, 2), -MINOR(*this, 0, 1, 0, 2), MINOR(*this, 0, 1, 0, 1) ); } float Matrix3::determinant() const { return m_[0][0] * MINOR(*this, 1, 2, 1, 2) - m_[0][1] * MINOR(*this, 1, 2, 0, 2) + m_[0][2] * MINOR(*this, 1, 2, 0, 1); } bool Matrix3::isSingular() const { return isZero(determinant()); } // TRANSFORMATION MATRICES Matrix3 Matrix3::identity() { return Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1); } Matrix3 Matrix3::rotate(float angle) { float sine = sinf(deg2rad(angle)); float cosine = cosf(deg2rad(angle)); return Matrix3(cosine, -sine, 0, sine, cosine, 0, 0, 0, 1); } Matrix3 Matrix3::scale(float sx, float sy) { return Matrix3(sx, 0, 0, 0, sy, 0, 0, 0, 1); } Matrix3 Matrix3::scaleUniform(float s) { return Matrix3(s, 0, 0, 0, s, 0, 0, 0, 1); } Matrix3 Matrix3::translate(float x, float y) { return Matrix3(1, 0, x, 0, 1, y, 0, 0, 1); } void Matrix3::print( char *str ) { if( str ) { printf("%s\n", str ); } printf( "%.2f %.2f %.2f\n" "%.2f %.2f %.2f\n" "%.2f %.2f %.2f\n" "%.2f %.2f %.2f\n", m_[0][0], m_[1][0], m_[2][0], m_[0][1], m_[1][1], m_[2][1], m_[0][2], m_[1][2], m_[2][2] ); }
[ "gweronimo@afd64b18-8dda-0310-837d-b02fe5df315d" ]
[ [ [ 1, 251 ] ] ]
23d7edb2ac84246268210c125406af6ae59961c4
c9812a465dfc049458d64d2715c1875f77c7d6a2
/unitTest/main.cpp
182f045d01aa418108e255c282afb938387efc28
[]
no_license
Tharantyr/akira
cfe9a016f0e0e310305aa7787453625b4f2c2d6a
fd89b304e385c66d66482babbe9651f5c45443b5
refs/heads/master
2021-01-10T15:16:10.603208
2008-07-09T17:23:02
2008-07-09T17:23:02
54,077,785
0
0
null
null
null
null
UTF-8
C++
false
false
435
cpp
// unitTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "vector.h" #include <boost/test/unit_test.hpp> using namespace boost::unit_test; extern void Vector3TestCases(void); test_suite* init_unit_test_suite(int, char* []) { test_suite* suite = BOOST_TEST_SUITE("Akira Math Library Test Suite"); suite->add(BOOST_TEST_CASE(&Vector3TestCases)); return suite; }
[ "khchung00@602a7b48-f520-0410-8bd5-356264b4cf1a" ]
[ [ [ 1, 20 ] ] ]
afcb8500a45a6080ba7a09c099e14ff5b501f11b
4118f852c5a0a9ac6860de430a26612643eccade
/src/debugLogs.cpp
13603565e25f4fb05e39df8c86c85cb56ece6458
[]
no_license
Domesday/BeebEm-AIV
0df6bbea1d0870ffd22a53bb0213992f2d2240a8
24397e4b504822d492ea3731c2ff17858e041968
refs/heads/master
2016-09-06T12:08:59.586263
2011-09-09T21:24:45
2011-09-09T21:24:45
2,354,864
0
0
null
null
null
null
UTF-8
C++
false
false
1,594
cpp
/**************************************************************** BeebEm - BBC Micro and Master 128 Emulator Copyright (C) 1994 David Alan Gilbert Copyright (C) 1997 Mike Wyatt Copyright (C) 2001 Richard Gellman This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ****************************************************************/ /*************** * debugLogs.cpp : Introduced by D.M.Sergeant (17/10/2002) * Implements simple functions to open and close the log files ***************/ #include <stdio.h> int logInstr = 0; int dms_win_flag = 0; void openLog(FILE * &logf, char log_fn[]) { if (logf != NULL) return; else logf = fopen(log_fn, "wb"); if (logf == NULL) printf("Could not open Log file \"%s\"\n", log_fn); else { fprintf(logf, "Log File Opened\n"); fflush(logf); } } void closeLog(FILE * &logf) { if (logf != NULL) fclose(logf); }
[ [ [ 1, 52 ] ] ]
8152b9b9c4144b705db75a3ac4961e7d201411ad
b414a8f5b425617f897b5d97bbede96507e17d96
/agdevku_qt_version/agdevku_GUI/heap/HeapFile.h
105c852e70e071f1cb899e14c6977cee09d509cb
[]
no_license
agenthunt/agdevku
e7ce02e6f936a6980839fc538f158160c2060d05
c6f6c8e9fbbb71f2b0288b8ab3ebd001aac6d5d7
refs/heads/master
2016-08-02T23:22:21.985871
2010-01-24T01:00:36
2010-01-24T01:00:36
32,114,047
0
0
null
null
null
null
UTF-8
C++
false
false
1,225
h
/* * HeapFile.h * * Created on: Oct 2, 2009 * Author: shailesh */ #ifndef HEAPFILE_H_ #define HEAPFILE_H_ #include "../global/GlobalStructures.h" #include "DirectoryHeaderPage.h" class TableScan; /** * All tables are stored in Heapfiles. Heap file is a logical file and * physically it is just a bunch of pages . We follow the directory chain * model. */ class HeapFile { public: HeapFile(const char *fileName); HeapFile(int dirHeaderPageNumber); virtual ~HeapFile(); //void createFile(const char *fileName);//does not make sense to have //this method, constructor suffices the purpose void deleteFile(); STATUS_CODE insertRecord(char *record,unsigned recordLen,RIDStruct& rid); void deleteRecord(const RIDStruct& rid); STATUS_CODE updateRecord(const RIDStruct rid,char*& record,unsigned& recordLen); void getRecord(const RIDStruct& rid,char*& record,unsigned& recordLen); int getNextRecordNumber();//used in generating table IDs for sysTable.... int getNumOfRecords(); int getDirectoryHeaderPageNumber(); private: DirectoryHeaderPage *dirHeaderPage_; friend class TableScan; void initHeapFile(int dirHeaderPageNumber); }; #endif /* HEAPFILE_H_ */
[ "[email protected]@1dbec2b6-b029-11de-8bdf-3374eb5c7316" ]
[ [ [ 1, 42 ] ] ]
5f99c5ad4c118dfa91cd26ab1080dae445f055b5
b08e948c33317a0a67487e497a9afbaf17b0fc4c
/Landscape/Landscape.h
e95e9cc1fad547f2244100a0a59272ecb08bff47
[]
no_license
15831944/bastionlandscape
e1acc932f6b5a452a3bd94471748b0436a96de5d
c8008384cf4e790400f9979b5818a5a3806bd1af
refs/heads/master
2023-03-16T03:28:55.813938
2010-05-21T15:00:07
2010-05-21T15:00:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,310
h
#ifndef __LANDSCAPE_H__ #define __LANDSCAPE_H__ #include "../Core/Core.h" #include "../Core/Octree.h" #include "../Display/Display.h" #include "../Display/Surface.h" #include "../Landscape/LandscapeTypes.h" namespace ElixirEngine { //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- #define LANDSCAPE_USE_HIGHEST_LOD_ONLY 1 #define LANDSCAPE_USE_MORPHING 0 //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- enum ELandscapeVertexFormat { ELandscapeVertexFormat_UNKNOWN, ELandscapeVertexFormat_DEFAULT, ELandscapeVertexFormat_LIQUID, }; struct LandscapeVertexDefault { #if LANDSCAPE_USE_MORPHING static VertexElement s_VertexElement[7]; #else // LANDSCAPE_USE_MORPHING static VertexElement s_VertexElement[6]; #endif // LANDSCAPE_USE_MORPHING LandscapeVertexDefaultRef operator = (LandscapeVertexIndependentRef _rVertexIndependent); Vector3 m_f3Position; #if LANDSCAPE_USE_MORPHING Vector3 m_f3Position2; #endif // LANDSCAPE_USE_MORPHING Vector3 m_f3Normal; Vector4 m_f4Color; Vector2 m_f2UV; Vector3 m_f3UV2; // slope, height, water level }; struct LandscapeVertexLiquid { static VertexElement s_VertexElement[6]; LandscapeVertexLiquidRef operator = (LandscapeVertexIndependentRef _rVertexIndependent); Vector3 m_f3Position; Vector3 m_f3Normal; Vector3 m_f3BiNormal; Vector3 m_f3Tangent; Vector2 m_f2UV; }; struct LandscapeVertexIndependent { struct LODVertexLink { UInt m_uLOD; UInt m_uIndex; }; typedef vector<LODVertexLink> LODVertexLinkVec; void AddLink(const UInt& _uLOD, const UInt& _uIndex); LODVertexLinkVec m_vLinks; Vector3 m_f3Position; #if LANDSCAPE_USE_MORPHING Vector3 m_f3Position2; #endif // LANDSCAPE_USE_MORPHING Vector3 m_f3Normal; Vector2 m_f2UV; float m_fNormalizedSlope; float m_fNormalizedHeight; UInt m_uWaterLevel; }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class Landscape : public DisplayObject { public: struct OpenInfo { string m_strName; OctreePtr m_pOctree; UInt m_uQuadSize; UInt m_uGridSize; ELandscapeVertexFormat m_eFormat; string m_strHeightmap; string m_strLayersConfig; float m_fPixelErrorMax; float m_fFloorScale; float m_fHeightScale; Key m_uRenderStageKey; }; struct LODInfo { UInt m_uStartIndex; UInt m_uStripSize; UInt m_uGridSize; UInt m_uQuadSize; UInt m_uGeometricError; UInt m_uVertexPerRowCount; UInt m_uRowCount; UInt m_uVertexCount; UInt m_uNumVertices; UInt m_uIncrement; Key m_uVertexBuffer; VoidPtr m_pVertexes; LandscapeVertexIndependentPtr m_pVertexesIndependent; }; typedef LODInfo* LODInfoPtr; typedef LODInfo& LODInfoRef; struct GlobalInfo { GlobalInfo(); void Reset(); bool Create(const OpenInfo& _rOpenInfo); void Release(); string m_strName; LODInfoPtr m_pLODs; OctreePtr m_pOctree; Key m_uRenderStageKey; UInt m_uQuadSize; UInt m_uGridSize; UInt m_uChunkCount; UInt m_uVertexCount; UInt m_uVertexPerRowCount; UInt m_uRowCount; UInt m_uStripSize; UInt m_uLODCount; UInt m_uTotalLODStripSize; float m_fPixelErrorMax; float m_fFloorScale; float m_fHeightScale; float m_fMinHeight; float m_fMaxHeight; ELandscapeVertexFormat m_eFormat; }; public: Landscape(DisplayRef _rDisplay); virtual ~Landscape(); static ELandscapeVertexFormat StringToVertexFormat(const string& _strFormat); virtual bool Create(const boost::any& _rConfig); virtual void Update(); virtual void Release(); virtual void SetWorldMatrix(MatrixRef _rWorld); virtual void SetMaterial(DisplayMaterialPtr _pMaterial); virtual void SetRenderStage(const Key& _uRenderPass); virtual void Render(); bool Open(const OpenInfo& _rOpenInfo); void Close(); const GlobalInfo& GetGlobalInfo() const; void GetVertexPosition(LODInfoRef _rLODInfo, const UInt& _uIndexBufferIndex, const UInt& _uVertexStartIndex, Vector3& _rPosition); bool SetIndices(); bool UseLODVertexBuffer(const UInt& _uLOD); void UseLayering(); const UIntPtr GetIndices() const; void UpdateObjectLocation(DisplayObjectPtr _pObject); bool GetWaterIndex(const Vector3& _f3Pos, UIntRef _uLevel); protected: bool CreateVertexBufferIndependent(); void ComputeVertexIndependentMorphs(LODInfoRef _rLODInfo); void ComputeVertexIndependentNormals(LODInfoRef _rLODInfo); bool CreateVertexBufferDefault(); bool CreateVertexBufferLiquid(); bool CreateIndexBuffer(); bool CreateChunks(); bool LoadHeightmap(const string& _strFileName); void InterpolatePixelA8R8G8B8(const DisplaySurface::UVInfo& _rUVInfo, ByteRef _uRed, ByteRef _uGreen, ByteRef _uBlue, ByteRef _uAlpha); protected: GlobalInfo m_oGlobalInfo; LandscapeChunkPtrVec m_vGrid; LandscapeChunkPtrVec m_vRenderList; KeyVec m_vVertexBuffers; VoidPtrVec m_vVertexes; LandscapeVertexIndependentPtrVec m_vVertexesIndependent; Key m_uCurrentVertexBuffer; Key m_uIndexBuffer; UIntPtr m_pIndexes; LandscapeLayeringPtr m_pLayering; DisplayPtr m_pDisplay; Key m_uRenderStageKey; private: }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class LandscapeChunk : public DisplayObject, public OctreeObject { public: enum ESubChild { ESubChild_NORTHWEST, ESubChild_NORTHEAST, ESubChild_SOUTHWEST, ESubChild_SOUTHEAST, ESubChild_COUNT // last enum member }; struct CreateInfo { UInt m_uX; UInt m_uZ; }; public: LandscapeChunk(LandscapeRef _rLandscape, OctreeRef _rOctree, const UInt& _uLOD); virtual ~LandscapeChunk(); virtual bool Create(const boost::any& _rConfig); virtual void Update(); virtual void Release(); virtual void SetWorldMatrix(MatrixRef _rWorld); virtual void SetMaterial(DisplayMaterialPtr _pMaterial); virtual void SetRenderStage(const Key& _uRenderPass); virtual void RenderBegin(); virtual void Render(); virtual bool RayIntersect(const Vector3& _f3RayBegin, const Vector3& _f3RayEnd, Vector3& _f3Intersect); void Traverse(LandscapeChunkPtrVecRef _rRenderList, const Vector3& _rCamPos, const float& _fPixelSize); UInt GetLODID() const; void UpdateObjectLocation(DisplayObjectPtr _pObject); bool GetWaterIndex(const Vector3& _f3Pos, UIntRef _uLevel); protected: bool CreateBoundingMesh(); protected: static Key s_uMorphFactorKey; LandscapeRef m_rLandscape; UInt m_uStartVertexIndex; UInt m_uLOD; LandscapeChunkPtr m_pParent; LandscapeChunkPtr m_pChildren[ESubChild_COUNT]; Vector3 m_f3AABB[2]; // 0 = (left, bottom, near), 1 = (right, top, far) Vector3 m_f3Center; Vector3 m_f3Extends; Landscape::LODInfoPtr m_pLODInfo; DisplayPtr m_pDisplay; float m_fMorphFactor; UInt m_uIndexX; UInt m_uIndexZ; private: }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class LandscapeLayering : public CoreObject { public: struct CreateInfo { string m_strPath; }; typedef CreateInfo* CreateInfoPtr; typedef CreateInfo& CreateInfoRef; struct Layer { bool Evaluate(const float& _fSlope, const float& _fHeight); UInt m_uAtlasIndex; float m_fMinHeight; float m_fMaxHeight; float m_fMinSlope; float m_fMaxSlope; }; typedef Layer* LayerPtr; typedef Layer& LayerRef; typedef vector<Layer> LayerVec; public: LandscapeLayering(LandscapeLayerManagerRef _rLandscapeLayerManager); virtual ~LandscapeLayering(); virtual bool Create(const boost::any& _rConfig); virtual void Update(); virtual void Release(); DisplayTexturePtr GetAtlas(); DisplayTexturePtr GetSlopeAndHeightLUT(); DisplayTexturePtr GetNoise(); Vector4& GetShaderInfo(); protected: bool CreateFromLuaConfig(CreateInfoRef _rInfo); bool CreateAtlas(LuaObjectRef _rLuaObject); bool CreateSlopeAndHeightLUT(LuaObjectRef _rLuaObject); bool CreateNoise(LuaObjectRef _rLuaObject); protected: LayerVec m_vLayers; LandscapeLayerManagerRef m_rLandscapeLayerManager; DisplayTexturePtr m_pAtlas; DisplayTexturePtr m_pSlopeAndHeightLUT; DisplayTexturePtr m_pNoise; Vector4 m_oShaderInfo; string m_strAtlasName; string m_strSAHLUTName; string m_strNoiseName; private: }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class LandscapeLayerManager : public CoreObject { public: LandscapeLayerManager(DisplayRef _rDisplay); virtual ~LandscapeLayerManager(); static void SetInstance(LandscapeLayerManagerPtr _pInstance); static LandscapeLayerManagerPtr GetInstance(); virtual bool Create(const boost::any& _rConfig); virtual void Update(); virtual void Release(); void SetCurrentLayering(LandscapeLayeringPtr _pLayering); LandscapeLayeringPtr Get(const string& _strFileName); void UnloadAll(); DisplayRef GetDisplay(); protected: LandscapeLayeringPtr Load(const string& _strFileName); protected: static LandscapeLayerManagerPtr s_pInstance; LandscapeLayeringPtrMap m_mConfigs; DisplayRef m_rDisplay; LandscapeLayeringPtr m_pCurrentLayering; Key m_uAtlasDiffuseKey; Key m_uAtlasLUTKey; Key m_uNoiseKey; Key m_uAtlasDiffuseInfoKey; private: }; } #endif // __LANDSCAPE_H__
[ "voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329" ]
[ [ [ 1, 378 ] ] ]
42ae92d3bf202bedc340e77662bba33f63c88627
1da68729e9666aaa3d2e9129614a5c44bc9fcf2a
/templates.h
3163a25e04108df2d0377ba8d7d3ede9860b6979
[ "MIT" ]
permissive
kragen/libutp
4723286e9b733a7d476c3fe90d083d7bba29ceff
205ba228299ffccec6dfb25e18f0036094a4bb5b
refs/heads/master
2021-01-18T17:40:28.900372
2010-05-28T06:12:49
2010-05-28T06:12:49
698,991
0
1
null
null
null
null
UTF-8
C++
false
false
4,195
h
#ifndef __TEMPLATES_H__ #define __TEMPLATES_H__ #include "utypes.h" #include <assert.h> #if defined(POSIX) /* Allow over-writing FORCEINLINE from makefile because gcc 3.4.4 for buffalo doesn't seem to support __attribute__((always_inline)) in -O0 build (strangely, it works in -Os build) */ #ifndef FORCEINLINE // The always_inline attribute asks gcc to inline the function even if no optimization is being requested. // This macro should be used exclusive-or with the inline directive (use one or the other but not both) // since Microsoft uses __forceinline to also mean inline, // and this code is following a Microsoft compatibility model. // Just setting the attribute without also specifying the inline directive apparently won't inline the function, // as evidenced by multiply-defined symbols found at link time. #define FORCEINLINE inline __attribute__((always_inline)) #endif #endif // Utility templates #undef min #undef max template <typename T> static inline T min(T a, T b) { if (a < b) return a; return b; } template <typename T> static inline T max(T a, T b) { if (a > b) return a; return b; } template <typename T> static inline T min(T a, T b, T c) { return min(min(a,b),c); } template <typename T> static inline T max(T a, T b, T c) { return max(max(a,b),c); } template <typename T> static inline T clamp(T v, T mi, T ma) { if (v > ma) v = ma; if (v < mi) v = mi; return v; } #pragma pack(push,1) namespace aux { FORCEINLINE uint16 host_to_network(uint16 i) { return htons(i); } FORCEINLINE uint32 host_to_network(uint32 i) { return htonl(i); } FORCEINLINE int32 host_to_network(int32 i) { return htonl(i); } FORCEINLINE uint16 network_to_host(uint16 i) { return ntohs(i); } FORCEINLINE uint32 network_to_host(uint32 i) { return ntohl(i); } FORCEINLINE int32 network_to_host(int32 i) { return ntohl(i); } } template <class T> struct big_endian { T operator=(T i) { m_integer = aux::host_to_network(i); return i; } operator T() const { return aux::network_to_host(m_integer); } private: T m_integer; }; typedef big_endian<int32> int32_big; typedef big_endian<uint32> uint32_big; typedef big_endian<uint16> uint16_big; #pragma pack(pop) template<typename T> static inline void zeromem(T *a, size_t count = 1) { memset(a, 0, count * sizeof(T)); } // WARNING: The template parameter MUST be a POD type! template <typename T, size_t minsize = 16> class Array { protected: T *mem; size_t alloc,count; public: Array(size_t init) { Init(init); } Array() { Init(); } ~Array() { Free(); } void inline Init() { mem = NULL; alloc = count = 0; } void inline Init(size_t init) { Init(); if (init) Resize(init); } size_t inline GetCount() const { return count; } size_t inline GetAlloc() const { return alloc; } void inline SetCount(int c) { count = c; } inline T& operator[](size_t offset) { assert(offset ==0 || offset<alloc); return mem[offset]; } inline const T& operator[](size_t offset) const { assert(offset ==0 || offset<alloc); return mem[offset]; } void inline Resize(size_t a) { if (a == 0) { free(mem); Init(); } else { mem = (T*)realloc(mem, (alloc=a) * sizeof(T)); } } void Grow() { Resize(::max<size_t>(minsize, alloc * 2)); } inline size_t Append(const T &t) { if (count >= alloc) Grow(); size_t r=count++; mem[r] = t; return r; } T inline &Append() { if (count >= alloc) Grow(); return mem[count++]; } void inline Compact() { Resize(count); } void inline Free() { free(mem); Init(); } void inline Clear() { count = 0; } bool inline MoveUpLast(size_t index) { assert(index < count); size_t c = --count; if (index != c) { mem[index] = mem[c]; return true; } return false; } bool inline MoveUpLastExist(const T &v) { return MoveUpLast(LookupElementExist(v)); } size_t inline LookupElement(const T &v) const { for(size_t i = 0; i != count; i++) if (mem[i] == v) return i; return (size_t) -1; } bool inline HasElement(const T &v) const { return LookupElement(v) != -1; } }; #endif //__TEMPLATES_H__
[ [ [ 1, 146 ] ] ]
da1aba8c274aa7a886e1bdcdb37c46fa35944584
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/Key.h
4cdfecdb265b8e2a424904f2657ae862ba04a8fa
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
2,633
h
#pragma once #ifndef __HALAK_KEYS_H__ #define __HALAK_KEYS_H__ # include <Halak/FWD.h> namespace Halak { struct Key { HKThisIsStaticStruct(Key); enum Code { None = 0x00, Enter = 0x0D, Escape = 0x1B, Left = 0x25, Up = 0x26, Right = 0x27, Down = 0x28, D0 = '0', D1 = '1', D2 = '2', D3 = '3', D4 = '4', D5 = '5', D6 = '6', D7 = '7', D8 = '8', D9 = '9', A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4A, K = 0x4B, L = 0x4C, M = 0x4D, N = 0x4E, O = 0x4F, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5A, F1 = 0x70, F2 = 0x71, F3 = 0x72, F4 = 0x73, F5 = 0x74, F6 = 0x75, F7 = 0x76, F8 = 0x77, F9 = 0x78, F10 = 0x79, F11 = 0x7A, F12 = 0x7B, MouseLeftButton = 0x01, MouseRightButton = 0x02, MouseMiddleButton = 0x04, /* GamePadA = 0xF0, GamePadB = 0xF1, GamePadX = 0xF2, GamePadY = 0xF3, GamePadUp = 0xF4, GamePadDown = 0xF5, GamePadLeft = 0xF6, GamePadRight = 0xF7, GamePadStart = 0xF8, GamePadBack = 0xF9, GamePadSelect = 0xFA, GamePadLeftThumb = 0xFB, GamePadRightThumb = 0xFC, GamePadLeftShoulder = 0xFD, GamePadRightShoulder = 0xFE, */ }; static const int Count = 256; static const Code Codes[Count]; }; } #endif
[ [ [ 1, 98 ] ] ]
c1f1b589a3d4f7a43e6f3daefd186c32a5d068cb
2b4926fd49a0fcebbed2b39b589202fc686836a5
/app/willard/phase2.cc
c296f463272c379e9aab5b6c6444a597a3a34bd3
[ "BSD-2-Clause" ]
permissive
prop-cc/prop-cc
c88eef95490b2fad048d0df617333ab94fdd497f
3569940fc0d039d10b9d6389e8e7a5aa6daae3a2
refs/heads/master
2020-12-25T05:27:49.470629
2011-09-14T21:20:19
2011-09-14T21:20:19
2,223,487
1
0
null
null
null
null
UTF-8
C++
false
false
21,950
cc
/////////////////////////////////////////////////////////////////////////////// // This file is generated automatically using Prop (version 2.4.1). // The original source file is "..\..\..\app\willard\phase2.pcc". /////////////////////////////////////////////////////////////////////////////// #define PROP_REWRITING_USED #define PROP_STRCMP_USED #define PROP_QUARK_USED #define PROP_TUPLE2_USED #include <propdefs.h> #line 1 "../../../app/willard/phase2.pcc" #include <AD/pretty/postream.h> #include "phase2.h" #include "list.h" /////////////////////////////////////////////////////////////////////////////// // // Constructor and destructor for phase2 // /////////////////////////////////////////////////////////////////////////////// Phase2::Phase2() {} Phase2::~Phase2() {} /////////////////////////////////////////////////////////////////////////////// // // Method to invoke phase2 // /////////////////////////////////////////////////////////////////////////////// Exp Phase2::phase2(Exp e) { message("Quantifier elimination phase", e); (*this)(e); return collect_subqueries(e); } /////////////////////////////////////////////////////////////////////////////// // // Transformation to eliminate existential quantifiers // by transforming them into count queries. // /////////////////////////////////////////////////////////////////////////////// #line 30 "../../../app/willard/phase2.pcc" #line 109 "../../../app/willard/phase2.pcc" /////////////////////////////////////////////////////////////////////////////// // // This macro can be redefined by the user for debugging // /////////////////////////////////////////////////////////////////////////////// #ifndef DEBUG_Phase2 #define DEBUG_Phase2(repl,redex,file,line,rule) repl #else static const char * Phase2_file_name = "..\..\..\app\willard\phase2.pcc"; #endif static const TreeTables::Offset Phase2_accept_base [ 73 ] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 3, 5, 6, 6, 6, 7, 8, 8, 9, 10, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 15, 16, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 21, 23, 25, 26, 26, 26, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 48 }; static const TreeTables::ShortRule Phase2_accept_vector [ 50 ] = { -1, 0, -1, 18, -1, 13, -1, 17, -1, 18, -1, 18, -1, 16, -1, 14, -1, 11, -1, 18, -1, 12, -1, 7, -1, 10, -1, 9, -1, 6, -1, 5, -1, 4, -1, 3, -1, 2, -1, 1, -1, 15, -1, 8, -1, 7, 8, -1, 8, -1 }; static const TreeTables::ShortState Phase2_theta_1[1][2] = { { 0, 18 } }; static const TreeTables::ShortState Phase2_theta_2[11][17] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 24, 0, 0, 44, 0, 58, 62, 63, 64, 65, 66, 67, 68, 0, 0, 0 }, { 0, 0, 40, 40, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 40, 40, 40 }, { 0, 0, 39, 39, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 39, 39, 39 }, { 0, 0, 38, 38, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 38, 38, 38 }, { 0, 0, 37, 37, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 37, 37, 37 }, { 0, 0, 36, 36, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 36, 36, 36 }, { 0, 0, 35, 35, 0, 35, 0, 0, 0, 0, 0, 0, 0, 0, 35, 35, 35 }, { 0, 0, 34, 43, 0, 57, 0, 0, 0, 0, 0, 0, 0, 0, 70, 71, 72 }, { 0, 0, 33, 33, 0, 56, 0, 0, 0, 0, 0, 0, 0, 0, 33, 56, 33 }, { 0, 23, 0, 0, 23, 0, 23, 23, 23, 23, 23, 23, 23, 23, 0, 0, 0 } }; static const TreeTables::ShortState Phase2_theta_4[2] = { 0, 22 }; static const TreeTables::ShortState Phase2_theta_9[5][2] = { { 15, 20 }, { 27, 28 }, { 29, 30 }, { 54, 55 }, { 54, 55 } }; static const TreeTables::ShortState Phase2_theta_10[2][2][9] = { { { 16, 16, 21, 41, 41, 42, 42, 69, 69 }, { 16, 16, 21, 41, 41, 42, 42, 69, 69 } }, { { 16, 16, 21, 41, 41, 42, 42, 69, 69 }, { 16, 25, 21, 41, 41, 42, 42, 69, 69 } } }; static const TreeTables::ShortState Phase2_theta_13[11][4] = { { 0, 19, 26, 59 }, { 0, 19, 31, 61 }, { 0, 32, 26, 59 }, { 0, 46, 45, 60 }, { 0, 47, 26, 59 }, { 0, 48, 26, 59 }, { 0, 49, 26, 59 }, { 0, 50, 26, 59 }, { 0, 51, 26, 59 }, { 0, 52, 26, 59 }, { 0, 53, 26, 59 } }; static const TreeTables::ShortState Phase2_check [ 174 ] = { 0, 2, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 11, 0, 5, 12, 4, 11, 0, 10, 10, 0, 0, 4, 11, 11, 11, 11, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 11, 11, 13, 0, 0, 4, 4, 4, 0, 14, 0, 0, 14, 0, 0, 13, 0, 14, 10, 0, 0, 14, 0, 14, 14, 14, 14, 0, 0, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 0, 0, 0, 15, 15, 0, 0, 0, 0, 0, 16, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 0, 14, 16, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 0, 16, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 0, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; TreeTables::ShortState Phase2_next [ 174 ] = { 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 2, 0, 0, 2, 1, 1, 1, 1, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 1, 1, 0, 0, 14, 15, 16, 0, 1, 0, 0, 2, 0, 0, 1, 0, 2, 4, 0, 0, 2, 0, 3, 4, 5, 6, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 1, 7, 8, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 4, 2, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 0, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 4, 4, 4, 0, 3, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; inline void Phase2::labeler(char const * redex,int& s__,int) { { if (_less_string(redex,">=")) { if (_less_string(redex,"=")) { if (_equal_string(redex,"/=")) {s__ = 5;} else if (_equal_string(redex,"<")) {s__ = 8;} else if (_equal_string(redex,"<=")) {s__ = 9;} else {s__ = 0;} } else { if (_equal_string(redex,"=")) {s__ = 4;} else if (_equal_string(redex,">")) {s__ = 6;} else {s__ = 0;} } } else { if (_less_string(redex,"not")) { if (_equal_string(redex,">=")) {s__ = 7;} else if (_equal_string(redex,"and")) {s__ = 10;} else if (_equal_string(redex,"nonempty")) {s__ = 12;} else {s__ = 0;} } else { if (_equal_string(redex,"not")) {s__ = 3;} else if (_equal_string(redex,"or")) {s__ = 11;} else {s__ = 0;} } } } } inline void Phase2::labeler(Quark redex,int& s__,int) { { s__ = 0; } } void Phase2::labeler (Exp & redex, int& s__, int r__) { replacement__: int cached__; if (r__ && boxed(redex) && (cached__ = redex->get_rewrite_state()) != BURS::undefined_state) { s__ = cached__; return; } switch(redex->tag__) { case a_Exp::tag_OP: { int s0__; int s1__; labeler(_OP(redex)->_1, s0__, r__); labeler(_OP(redex)->_2, s1__, r__); s__ = Phase2_theta_2[Phase2_check[0 + s0__] == 3 ? Phase2_next[0 + s0__] : 0][Phase2_check[0 + s1__] == 4 ? Phase2_next[0 + s1__] : 0]; } break; case a_Exp::tag_APP: { int s0__; int s1__; labeler(_APP(redex)->_1, s0__, r__); labeler(_APP(redex)->_2, s1__, r__); s__ = 0;} break; case a_Exp::tag_LIT: { int s0__; labeler(_LIT(redex)->LIT, s0__, r__); s__ = Phase2_theta_4[Phase2_check[0 + s0__] == 5 ? Phase2_next[0 + s0__] : 0]; } break; case a_Exp::tag_ID: { int s0__; labeler(_ID(redex)->ID, s0__, r__); s__ = 13;} break; case a_Exp::tag_TUPLE: { int s0__; labeler(_TUPLE(redex)->TUPLE, s0__, r__); s__ = 0;} break; case a_Exp::tag_FORALL: { int s0__; int s1__; int s2__; labeler(_FORALL(redex)->_1, s0__, r__); labeler(_FORALL(redex)->_2, s1__, r__); labeler(_FORALL(redex)->_3, s2__, r__); s__ = 0;} break; case a_Exp::tag_EXISTS: { int s0__; int s1__; int s2__; labeler(_EXISTS(redex)->_1, s0__, r__); labeler(_EXISTS(redex)->_2, s1__, r__); labeler(_EXISTS(redex)->_3, s2__, r__); s__ = 14;} break; case a_Exp::tag_GUARD: { int s0__; int s1__; labeler(_GUARD(redex)->_1, s0__, r__); labeler(_GUARD(redex)->_2, s1__, r__); s__ = Phase2_theta_9[Phase2_check[0 + s0__] == 10 ? Phase2_next[0 + s0__] : 0][Phase2_check[0 + s1__] == 11 ? Phase2_next[0 + s1__] : 0]; } break; case a_Exp::tag_GENERATOR: { int s0__; int s1__; int s2__; labeler(_GENERATOR(redex)->_1, s0__, r__); labeler(_GENERATOR(redex)->_2, s1__, r__); labeler(_GENERATOR(redex)->_3, s2__, r__); s__ = Phase2_theta_10[Phase2_check[0 + s0__] == 12 ? Phase2_next[0 + s0__] : 0][Phase2_check[37 + s1__] == 13 ? Phase2_next[37 + s1__] : 0][Phase2_check[50 + s2__] == 14 ? Phase2_next[50 + s2__] : 0]; } break; default: { int s0__; int s1__; int s2__; labeler(_LET(redex)->_1, s0__, r__); labeler(_LET(redex)->_2, s1__, r__); labeler(_LET(redex)->_3, s2__, r__); s__ = 0;} break; } const TreeTables::ShortRule * o__ = Phase2_accept_vector + Phase2_accept_base[s__]; accept__: switch (*o__) { case 18: { #line 102 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(GUARD(And(_GUARD(redex)->_1,_GUARD(_GUARD(redex)->_2)->_1),_GUARD(_GUARD(redex)->_2)->_2),redex,Phase2_file_name,102,"GUARD (p1, GUARD (p2, E)): ..."); r__ = 1; goto replacement__; } #line 107 "../../../app/willard/phase2.pcc" } break; case 17: if ((_GENERATOR(redex)->_1->_1 == _ID(_GENERATOR(redex)->_3)->ID)) { #line 101 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(_GENERATOR(redex)->_2->_1,redex,Phase2_file_name,101,"GENERATOR (#[x], #[A], ID y) | (redex!GENERATOR.1!#[...].1 == redex!GENERATOR.3!ID): ..."); r__ = 1; goto replacement__; } #line 102 "../../../app/willard/phase2.pcc" } else { ++o__; goto accept__; } break; case 16: if ((_BOOL(_LIT(_GUARD(_GENERATOR(redex)->_3)->_1)->LIT)->BOOL == true)) { #line 100 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(GENERATOR(_GENERATOR(redex)->_1,_GENERATOR(redex)->_2,_GUARD(_GENERATOR(redex)->_3)->_2),redex,Phase2_file_name,100,"GENERATOR (x, A, GUARD (LIT BOOL _, E)) | (redex!GENERATOR.3!GUARD.1!LIT!BOOL == true): ..."); r__ = 1; goto replacement__; } #line 101 "../../../app/willard/phase2.pcc" } else { ++o__; goto accept__; } break; case 15: { #line 98 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(GUARD(_OP(_GUARD(_GENERATOR(redex)->_3)->_1)->_2->_1,GENERATOR(_GENERATOR(redex)->_1,_GENERATOR(redex)->_2,GUARD(_OP(_GUARD(_GENERATOR(redex)->_3)->_1)->_2->_2->_1,_GUARD(_GENERATOR(redex)->_3)->_2))),redex,Phase2_file_name,98,"GENERATOR (x, A, GUARD (OP (\"and\", #[p1 as OP (\"nonempty\", #[C]), p2]), E)): ..."); r__ = 1; goto replacement__; } #line 100 "../../../app/willard/phase2.pcc" } break; case 14: { #line 96 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(GUARD(_GUARD(_GENERATOR(redex)->_3)->_1,GENERATOR(_GENERATOR(redex)->_1,_GENERATOR(redex)->_2,_GUARD(_GENERATOR(redex)->_3)->_2)),redex,Phase2_file_name,96,"GENERATOR (x, A, GUARD (p as OP (\"nonempty\", #[C]), E)): ..."); r__ = 1; goto replacement__; } #line 98 "../../../app/willard/phase2.pcc" } break; case 13: { #line 95 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(GENERATOR(append(_GENERATOR(redex)->_1,_GENERATOR(_GENERATOR(redex)->_3)->_1),append(_GENERATOR(redex)->_2,_GENERATOR(_GENERATOR(redex)->_3)->_2),_GENERATOR(_GENERATOR(redex)->_3)->_3),redex,Phase2_file_name,95,"GENERATOR (x, A, GENERATOR (y, B, C)): ..."); r__ = 1; goto replacement__; } #line 96 "../../../app/willard/phase2.pcc" } break; case 12: { #line 93 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Or(_OP(_OP(redex)->_2->_1)->_2->_1,Or(_OP(_OP(redex)->_2->_1)->_2->_2->_1,_OP(redex)->_2->_2->_1)),redex,Phase2_file_name,93,"OP (\"or\", #[OP (\"or\", #[a, b]), c]): ..."); r__ = 1; goto replacement__; } #line 95 "../../../app/willard/phase2.pcc" } break; case 11: { #line 92 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(_OP(_OP(redex)->_2->_1)->_2->_1,redex,Phase2_file_name,92,"OP (\"not\", #[OP (\"not\", #[a])]): ..."); r__ = 1; goto replacement__; } #line 93 "../../../app/willard/phase2.pcc" } break; case 10: { #line 91 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(And(Not(_OP(_OP(redex)->_2->_1)->_2->_1),Not(_OP(_OP(redex)->_2->_1)->_2->_2->_1)),redex,Phase2_file_name,91,"OP (\"not\", #[OP (\"or\", #[a, b])]): ..."); r__ = 1; goto replacement__; } #line 92 "../../../app/willard/phase2.pcc" } break; case 9: { #line 90 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Or(Not(_OP(_OP(redex)->_2->_1)->_2->_1),Not(_OP(_OP(redex)->_2->_1)->_2->_2->_1)),redex,Phase2_file_name,90,"OP (\"not\", #[OP (\"and\", #[a, b])]): ..."); r__ = 1; goto replacement__; } #line 91 "../../../app/willard/phase2.pcc" } break; case 8: { #line 89 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Or(And(_OP(redex)->_2->_1,_OP(_OP(redex)->_2->_2->_1)->_2->_1),And(_OP(redex)->_2->_1,_OP(_OP(redex)->_2->_2->_1)->_2->_2->_1)),redex,Phase2_file_name,89,"OP (\"and\", #[a, OP (\"or\", #[b, c])]): ..."); r__ = 1; goto replacement__; } #line 90 "../../../app/willard/phase2.pcc" } break; case 7: { #line 88 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Or(And(_OP(_OP(redex)->_2->_1)->_2->_1,_OP(redex)->_2->_2->_1),And(_OP(_OP(redex)->_2->_1)->_2->_2->_1,_OP(redex)->_2->_2->_1)),redex,Phase2_file_name,88,"OP (\"and\", #[OP (\"or\", #[a, b]), c]): ..."); r__ = 1; goto replacement__; } #line 89 "../../../app/willard/phase2.pcc" } break; case 6: { #line 83 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Gt(_OP(_OP(redex)->_2->_1)->_2->_1,_OP(_OP(redex)->_2->_1)->_2->_2->_1),redex,Phase2_file_name,83,"OP (\"not\", #[OP (\"<=\", #[a, b])]): ..."); r__ = 1; goto replacement__; } #line 88 "../../../app/willard/phase2.pcc" } break; case 5: { #line 82 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Ge(_OP(_OP(redex)->_2->_1)->_2->_1,_OP(_OP(redex)->_2->_1)->_2->_2->_1),redex,Phase2_file_name,82,"OP (\"not\", #[OP (\"<\", #[a, b])]): ..."); r__ = 1; goto replacement__; } #line 83 "../../../app/willard/phase2.pcc" } break; case 4: { #line 81 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Lt(_OP(_OP(redex)->_2->_1)->_2->_1,_OP(_OP(redex)->_2->_1)->_2->_2->_1),redex,Phase2_file_name,81,"OP (\"not\", #[OP (\">=\", #[a, b])]): ..."); r__ = 1; goto replacement__; } #line 82 "../../../app/willard/phase2.pcc" } break; case 3: { #line 80 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Le(_OP(_OP(redex)->_2->_1)->_2->_1,_OP(_OP(redex)->_2->_1)->_2->_2->_1),redex,Phase2_file_name,80,"OP (\"not\", #[OP (\">\", #[a, b])]): ..."); r__ = 1; goto replacement__; } #line 81 "../../../app/willard/phase2.pcc" } break; case 2: { #line 79 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Eq(_OP(_OP(redex)->_2->_1)->_2->_1,_OP(_OP(redex)->_2->_1)->_2->_2->_1),redex,Phase2_file_name,79,"OP (\"not\", #[OP (\"/=\", #[a, b])]): ..."); r__ = 1; goto replacement__; } #line 80 "../../../app/willard/phase2.pcc" } break; case 1: { #line 78 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Ne(_OP(_OP(redex)->_2->_1)->_2->_1,_OP(_OP(redex)->_2->_1)->_2->_2->_1),redex,Phase2_file_name,78,"OP (\"not\", #[OP (\"=\", #[a, b])]): ..."); r__ = 1; goto replacement__; } #line 79 "../../../app/willard/phase2.pcc" } break; case 0: { #line 36 "../../../app/willard/phase2.pcc" IdSet S; free_vars(_EXISTS(redex)->_3,S); // Transform: exists x : A . p where x does not occur in p // into: #A > 0 and p if (! S.contains(_EXISTS(redex)->_1)) { #line 41 "../../../app/willard/phase2.pcc" #line 41 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(And(Nonempty(_EXISTS(redex)->_2),_EXISTS(redex)->_3),redex,Phase2_file_name,35,"EXISTS (x, A, p): ..."); r__ = 1; goto replacement__; } #line 41 "../../../app/willard/phase2.pcc" #line 41 "../../../app/willard/phase2.pcc" } // Transform: exists x : A . p(x) // into: #C > 0 // where C = { x : A | p(x) } if (S.size() == 1) { Id C = gensym("C"); Exp find_query = GENERATOR( #line 48 "../../../app/willard/phase2.pcc" #line 48 "../../../app/willard/phase2.pcc" list_1_(_EXISTS(redex)->_1) #line 48 "../../../app/willard/phase2.pcc" #line 48 "../../../app/willard/phase2.pcc" , #line 48 "../../../app/willard/phase2.pcc" #line 48 "../../../app/willard/phase2.pcc" list_1_(_EXISTS(redex)->_2) #line 48 "../../../app/willard/phase2.pcc" #line 48 "../../../app/willard/phase2.pcc" ,GUARD(_EXISTS(redex)->_3,ID(_EXISTS(redex)->_1))); add_subquery(C,find_query); #line 50 "../../../app/willard/phase2.pcc" #line 50 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Nonempty(ID(C)),redex,Phase2_file_name,35,"EXISTS (x, A, p): ..."); r__ = 1; goto replacement__; } #line 50 "../../../app/willard/phase2.pcc" #line 50 "../../../app/willard/phase2.pcc" } // Transform: exists x : A . p(x,y) // into: C(y) // where C = { [y, #{ [y,x] : x in A | p(x,y)}] : y in B } if (S.size() == 2) { Id C = gensym("C"); Id y = "???"; foreach(i,S) if (S.value(i) != _EXISTS(redex)->_1) y = S.value(i); Exp B = range_of(y); Exp count_query = GENERATOR( #line 62 "../../../app/willard/phase2.pcc" #line 62 "../../../app/willard/phase2.pcc" list_1_(y) #line 62 "../../../app/willard/phase2.pcc" #line 62 "../../../app/willard/phase2.pcc" , #line 62 "../../../app/willard/phase2.pcc" #line 62 "../../../app/willard/phase2.pcc" list_1_(B) #line 62 "../../../app/willard/phase2.pcc" #line 62 "../../../app/willard/phase2.pcc" , TUPLE( #line 63 "../../../app/willard/phase2.pcc" #line 63 "../../../app/willard/phase2.pcc" list_1_(ID(y),list_1_(Count(GENERATOR(list_1_(_EXISTS(redex)->_1),list_1_(_EXISTS(redex)->_2),GUARD(_EXISTS(redex)->_3,TUPLE(list_1_(ID(y),list_1_(ID(_EXISTS(redex)->_1))))))))) #line 66 "../../../app/willard/phase2.pcc" #line 66 "../../../app/willard/phase2.pcc" )); add_subquery(C,count_query); #line 68 "../../../app/willard/phase2.pcc" #line 68 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(Gt(APP(C,list_1_(ID(y))),Zero),redex,Phase2_file_name,35,"EXISTS (x, A, p): ..."); r__ = 1; goto replacement__; } #line 68 "../../../app/willard/phase2.pcc" #line 68 "../../../app/willard/phase2.pcc" } // Arity is not zero or one error("Cannot simplify quantifier",redex); #line 73 "../../../app/willard/phase2.pcc" } break; } if (boxed(redex)) { redex->set_rewrite_state(s__); } { switch (redex->tag__) { case a_Exp::tag_LET: { if ( #line 108 "../../../app/willard/phase2.pcc" has_subqueries() #line 108 "../../../app/willard/phase2.pcc" ) { #line 108 "../../../app/willard/phase2.pcc" { redex = DEBUG_Phase2(collect_subqueries(redex),redex,Phase2_file_name,108,"LET (x, A, B) | has_subqueries(): ..."); r__ = 1; goto replacement__; } #line 109 "../../../app/willard/phase2.pcc" } else { } } break; default: {} break; } } } void Phase2::labeler (Literal & redex, int& s__, int r__) { replacement__: switch(redex->tag__) { case a_Literal::tag_INT: { int s0__; s0__ = 0; // int s__ = 0;} break; case a_Literal::tag_STRING: { int s0__; labeler(_STRING(redex)->STRING, s0__, r__); s__ = 0;} break; default: { int s0__; s0__ = 0; // Bool s__ = 17;} break; } } void Phase2::labeler (a_List<Exp> * & redex, int& s__, int r__) { replacement__: if ((redex)) { int s0__; int s1__; labeler(redex->_1, s0__, r__); labeler(redex->_2, s1__, r__); s__ = Phase2_theta_13[Phase2_check[73 + s0__] == 15 ? Phase2_next[73 + s0__] : 0][Phase2_check[101 + s1__] == 16 ? Phase2_next[101 + s1__] : 0]; } else {s__ = 2; } } void Phase2::labeler (a_List<Id> * & redex, int& s__, int r__) { replacement__: if ((redex)) { int s0__; int s1__; labeler(redex->_1, s0__, r__); labeler(redex->_2, s1__, r__); s__ = Phase2_theta_1[0][Phase2_check[0 + s1__] == 2 ? Phase2_next[0 + s1__] : 0]; } else {s__ = 1; } } #line 109 "../../../app/willard/phase2.pcc" #line 109 "../../../app/willard/phase2.pcc" #line 110 "../../../app/willard/phase2.pcc" /* ------------------------------- Statistics ------------------------------- Merge matching rules = yes Number of DFA nodes merged = 10 Number of ifs generated = 14 Number of switches generated = 1 Number of labels = 0 Number of gotos = 0 Adaptive matching = disabled Fast string matching = disabled Inline downcasts = disabled -------------------------------------------------------------------------- */
[ [ [ 1, 562 ] ] ]
b0edeeb63191ab64367382fe082c8afe0295ca16
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/Shared/GlobalMgr.h
0730a3f3d79d77ce59fca83672b1a6307553e616
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
1,271
h
// ----------------------------------------------------------------------- // // // MODULE : GlobalMgr.h // // PURPOSE : Definition of global definitions // // CREATED : 7/07/99 // // (c) 1999-2000 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __GLOBAL_MGR_H__ #define __GLOBAL_MGR_H__ #include "SurfaceMgr.h" #include "MissionButeMgr.h" #include "SkillsButeMgr.h" #include "SoundMgr.h" #include "DebrisMgr.h" #include "SoundFilterMgr.h" #include "SoundButeMgr.h" #include "DamageTypes.h" class CFXButeMgr; class CGlobalMgr { protected : CGlobalMgr(); virtual ~CGlobalMgr(); virtual LTBOOL Init(); virtual void Term( ); CFXButeMgr* m_pFXButeMgr; // Same as g_pFXButeMgr CDebrisMgr m_DebrisMgr; // Same as g_pDebrisMgr CSoundFilterMgr m_SoundFilterMgr; // Same as g_pSoundFilterMgr CSurfaceMgr m_SurfaceMgr; // Same as g_pSurfaceMgr CSkillsButeMgr m_SkillsButeMgr; // Same as g_pSkillsButeMgr CSoundButeMgr m_SoundButeMgr; // Same as g_pSoundButeMgr CDTButeMgr m_DTButeMgr; virtual void ShutdownWithError(char* pMgrName, char* pButeFilePath) = 0; }; #endif // __GLOBAL_MGR_H__
[ [ [ 1, 52 ] ] ]
c3a24ccfffb68ed972e1d655f3c104ec807f62bf
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/CrashReporter/CrashReporter/CrashReporterDlg.cpp
d6792fe6cfc0ca73d95ebdd2c109e03641dd24af
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
GB18030
C++
false
false
9,522
cpp
// CrashReporterDlg.cpp : 实现文件 // #include "stdafx.h" #include "CrashReporter.h" #include "CrashReporterDlg.h" #include ".\crashreporterdlg.h" #include "HttpUploadFileProc.h" #include "WinMsg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialog { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 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() // CCrashReporterDlg 对话框 CCrashReporterDlg::CCrashReporterDlg(CWnd* pParent /*=NULL*/) : CDialog(CCrashReporterDlg::IDD, pParent) , m_bAutoRestart(FALSE) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); //m_hProcThread = INVALID_HANDLE_VALUE; m_pUploadProc = NULL; m_bTinyWndSize = TRUE; } void CCrashReporterDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_EDIT_EMAIL, m_editEmail); DDX_Control(pDX, IDC_STATIC_PROGRESS_STATUS, m_sttcProgrsStatus); DDX_Control(pDX, IDC_PROGRESS_SEND, m_progressSend); DDX_Control(pDX, ID_BNCANCEL, m_bnCancel); DDX_Control(pDX, IDOK, m_bnOk); DDX_Control(pDX, IDC_EDIT_DESC, m_editDesc); DDX_Control(pDX, IDC_STATIC_TINY_BOUNDARY, m_sttcTinyBoundary); DDX_Control(pDX, IDC_STATIC_LARGE_BOUNDARY, m_sttcLargeBoundary); DDX_Check(pDX, IDC_CHECK_AUTO_RESTART, m_bAutoRestart); } BEGIN_MESSAGE_MAP(CCrashReporterDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDOK, OnBnClickedOk) ON_MESSAGE(WM_UPLOAD_PROGRESS, OnUploadProgress) ON_BN_CLICKED(IDCANCEL, OnBnClickedCancel) ON_BN_CLICKED(ID_BNCANCEL, OnBnClickedBncancel) ON_EN_MAXTEXT(IDC_EDIT_DESC, OnEnMaxtextEditDesc) ON_EN_MAXTEXT(IDC_EDIT_EMAIL, OnEnMaxtextEditEmail) ON_WM_CLOSE() ON_BN_CLICKED(IDC_MORE_INFO, OnBnClickedMoreInfo) ON_WM_DESTROY() END_MESSAGE_MAP() void CCrashReporterDlg::SetProcStatus(int iStatus) { switch(iStatus) { case PS_NOT_SEND: m_sttcProgrsStatus.SetWindowText(_T("")); m_sttcProgrsStatus.ShowWindow(SW_HIDE); //m_progressSend.ShowWindow(SW_HIDE); m_progressSend.SetPos(0); m_bnOk.EnableWindow(TRUE); m_bnCancel.SetWindowText(_T("不发送")); break; case PS_SENDING: m_sttcProgrsStatus.ShowWindow(SW_SHOW); //m_progressSend.ShowWindow(SW_SHOW); m_bnOk.EnableWindow(FALSE); m_bnCancel.SetWindowText(_T("取消")); break; case PS_SUCCEEDED: m_sttcProgrsStatus.ShowWindow(SW_SHOW); //m_progressSend.ShowWindow(SW_SHOW); m_bnOk.EnableWindow(FALSE); m_bnCancel.SetWindowText(_T("关闭")); break; default: break; } m_iProcStatus = iStatus; } void CCrashReporterDlg::LimitPrompt(UINT uLimit) { CString str; str.Format(_T("最多只能输入%d个英文字符或%d个中文字符。"), uLimit, uLimit/2); ::AfxMessageBox(str); } void CCrashReporterDlg::ChangeWndSize(BOOL bTiny) { CRect rtBoundary; if (bTiny) m_sttcTinyBoundary.GetWindowRect(&rtBoundary); else m_sttcLargeBoundary.GetWindowRect(&rtBoundary); CRect rtWnd; GetWindowRect(&rtWnd); SetWindowPos(NULL, 0, 0, rtWnd.Width(), rtBoundary.top - rtWnd.top, SWP_NOZORDER | SWP_NOMOVE); // 如果是tiny模式,则禁示编辑框,以避免Tab键跳到这些框上。 m_editDesc.EnableWindow(!bTiny); m_editEmail.EnableWindow(!bTiny); } // CCrashReporterDlg 消息处理程序 BOOL CCrashReporterDlg::OnInitDialog() { CDialog::OnInitDialog(); // 将\“关于...\”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 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); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 m_bAutoRestart = TRUE; UpdateData(FALSE); ChangeWndSize(m_bTinyWndSize); m_editDesc.SetLimitText(MAX_DESC - 10); m_editEmail.SetLimitText(MAX_PATH - 10); SetProcStatus(PS_NOT_SEND); return TRUE; // 除非设置了控件的焦点,否则返回 TRUE } void CCrashReporterDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CCrashReporterDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作矩形中居中 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; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标显示。 HCURSOR CCrashReporterDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CCrashReporterDlg::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 //OnOK(); if (PS_NOT_SEND != GetProcStatus()) return; SetProcStatus(PS_SENDING); CString strEmail; m_editEmail.GetWindowText(strEmail); CString strDesc; m_editDesc.GetWindowText(strDesc); m_pUploadProc = (CHttpUploadFileProc*) ::AfxBeginThread(RUNTIME_CLASS(CHttpUploadFileProc), THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED); ZeroMemory(&m_pUploadProc->m_threadParam, sizeof(SHttpUploadFileThreadParam)); _tcsncpy(m_pUploadProc->m_threadParam.szFileName, m_strFileName, MAX_PATH - 1); m_pUploadProc->m_threadParam.szFileName[MAX_PATH - 1] = _T('\0'); m_pUploadProc->m_threadParam.hNotifyWnd = GetSafeHwnd(); m_pUploadProc->m_threadParam.uNotifyMsg = WM_UPLOAD_PROGRESS; _tcsncpy(m_pUploadProc->m_threadParam.szEmail, strEmail, MAX_PATH - 1); m_pUploadProc->m_threadParam.szEmail[MAX_PATH - 1] = _T('\0'); _tcsncpy(m_pUploadProc->m_threadParam.szDesc, strDesc, MAX_DESC - 1); m_pUploadProc->m_threadParam.szDesc[MAX_DESC - 1] = _T('\0'); m_pUploadProc->ResumeThread(); } LRESULT CCrashReporterDlg::OnUploadProgress(WPARAM wParam, LPARAM lParam) { if (PS_SENDING != GetProcStatus()) return 0; HRESULT hr = (HRESULT) wParam; if (SUCCEEDED(hr)) { if (P_HUF_PROGRESS == hr) { m_progressSend.SetPos((int) lParam); } else { m_sttcProgrsStatus.SetWindowText(CHttpUploadFileProc::Result2Str(hr)); } } if (S_HUF_FINISHED == hr) { SetProcStatus(PS_SUCCEEDED); //m_hProcThread = NULL; m_pUploadProc = NULL; ::AfxMessageBox(_T("已成功发送错误报告。感谢您的支持!")); OnCancel(); } if (FAILED(hr)) { //m_hProcThread = NULL; m_pUploadProc = NULL; SetProcStatus(PS_NOT_SEND); CString strErrorInfo; strErrorInfo = CHttpUploadFileProc::Result2Str(hr); m_sttcProgrsStatus.SetWindowText(strErrorInfo); ::AfxMessageBox(strErrorInfo); } return 0; } void CCrashReporterDlg::OnBnClickedCancel() { // TODO: 在此添加控件通知处理程序代码 //OnCancel(); } void CCrashReporterDlg::OnBnClickedBncancel() { // TODO: 在此添加控件通知处理程序代码 if (PS_SENDING == GetProcStatus()) { if (!::IsBadReadPtr(m_pUploadProc, sizeof(CHttpUploadFileProc))) m_pUploadProc->SuspendThread(); if (IDYES == ::AfxMessageBox(_T("取消发送?"), MB_YESNO)) { if (!::IsBadReadPtr(m_pUploadProc, sizeof(CHttpUploadFileProc))) { m_pUploadProc->Terminate(); } SetProcStatus(PS_NOT_SEND); } if (!::IsBadReadPtr(m_pUploadProc, sizeof(CHttpUploadFileProc))) m_pUploadProc->ResumeThread(); } else { OnCancel(); } } void CCrashReporterDlg::OnEnMaxtextEditDesc() { // TODO: 在此添加控件通知处理程序代码 LimitPrompt(MAX_DESC - 10); } void CCrashReporterDlg::OnEnMaxtextEditEmail() { // TODO: 在此添加控件通知处理程序代码 LimitPrompt(MAX_PATH - 10); } void CCrashReporterDlg::OnClose() { // TODO: 在此添加消息处理程序代码和/或调用默认值 OnBnClickedBncancel(); //CDialog::OnClose(); } void CCrashReporterDlg::OnBnClickedMoreInfo() { // TODO: 在此添加控件通知处理程序代码 m_bTinyWndSize = !m_bTinyWndSize; ChangeWndSize(m_bTinyWndSize); } void CCrashReporterDlg::OnDestroy() { CDialog::OnDestroy(); // TODO: 在此处添加消息处理程序代码 UpdateData(); }
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 382 ] ] ]
9c1421a48c79245c39bd511513a6030135532367
bf971db1963b088a40a39a9f72e2fc60544e711a
/zlist.h
d84ad0922e80ced0eb76ec040311df68a7cab6c6
[]
no_license
zebraxxl/sini
9b95ffbfd016c734af1482d49b3aab17adc751e4
3a679b6cf99f26e1c5f409787f502c07beee1313
refs/heads/master
2016-09-10T12:32:17.793675
2011-09-09T21:16:10
2011-09-09T21:16:10
32,348,590
0
0
null
null
null
null
UTF-8
C++
false
false
3,498
h
#ifndef __ZLIST_H__ #define __ZLIST_H__ #ifdef _MSC_VER # define DECL_FRIEND_CROSSCOMPILERVERSION(x) friend x #else # define DECL_FRIEND_CROSSCOMPILERVERSION(x) #endif template <class T> class CZList { private: typedef struct Node{ friend struct ListIteraror; DECL_FRIEND_CROSSCOMPILERVERSION(CZList); private: T val; Node *prev; Node *next; inline void DelThis() { if (next) next->DelThis(); delete this; } inline Node( const T &v, Node *p, Node *n ):val(v),prev(p),next(n){} }; Node *first; Node *last; unsigned int count; public: typedef struct ListIteraror { DECL_FRIEND_CROSSCOMPILERVERSION(CZList); private: Node *curr; inline ListIteraror( Node *c ):curr(c){} public: inline ListIteraror():curr(0){} inline ListIteraror &operator=(const ListIteraror &o) { curr = o.curr; return *this; } inline ListIteraror &operator++() { if (curr) curr = curr->next; return *this; } inline ListIteraror &operator++(int) { if (curr) curr = curr->next; return *this; } inline ListIteraror &operator--() { if ((curr)&&(curr->prev)) curr = curr->prev; return *this; } inline ListIteraror &operator--(int) { if ((curr)&&(curr->prev)) curr = curr->prev; return *this; } inline bool IsNULL()const { return (curr == 0); } inline bool operator==(const ListIteraror &o)const { return (curr == o.curr); } inline bool operator!=(const ListIteraror &o)const { return (curr != o.curr); } inline T &operator->() { return curr->val; } inline T &operator*() { return curr->val; } }; inline CZList():first(0),last(0),count(0){}; inline ~CZList(){Clear();} inline ListIteraror get_begin()const{return ListIteraror( first );} inline ListIteraror get_end()const{return ListIteraror( last );} inline unsigned int get_size()const{return count;} inline void AddToBegin( const T &val ) { Node *tmp = first; first = new Node( val, 0, first ); if (tmp) tmp->prev = first; else if (!last) last = first; count++; } inline void AddToEnd( const T &val ) { Node *tmp = last; last = new Node( val, last, 0 ); if (tmp) tmp->next = last; else if (!first) first = last; count++; } inline void AddAfter ( ListIteraror &i, const T &val ) { if (i.curr) { Node *tmp = i.curr->next; i.curr->next = new Node( val, i.curr, i.curr->next ); count++; if (tmp) tmp->prev = i.curr->next; else last = i.curr->next; } } inline void AddBefore( ListIteraror &i, const T &val ) { if (i.curr) { Node *tmp = i.curr->prev; i.curr->prev = new Node( val, i.curr->prev, i.curr ); count++; if (tmp) tmp->next = i.curr->prev; else first = i.curr->prev; } } inline void Delete( const ListIteraror &i ) { if (i.curr) { if (i.curr->next) i.curr->next->prev = i.curr->prev; else last = i.curr->prev; if (i.curr->prev) i.curr->prev->next = i.curr->next; else first = i.curr->next; count--; } } inline void Clear() { if (first) { Node *next; Node *curr = first; while (curr) { next = curr->next; delete curr; curr = next; } } first = 0; last = 0; count = 0; } }; #endif //__ZLIST_H__
[ "zebraxxl@38bddf81-f72c-4749-2c60-6f4cd93a2835" ]
[ [ [ 1, 201 ] ] ]
e3dd0a93aa577f3c697f69a4b7457b0cddbb8b0f
5bf43d726d0d7b5e2822108bf1690fc5b270a0a6
/Game.cpp
422b25f4d364f10b128c694d7d000ccd3bc64c18
[]
no_license
jjonir/sevendayroguelike
1149dc6d849535cd162fe02f7bfa10f53c5fddc0
45cef84b3488d49fadfb72695131f5a79d935e2e
refs/heads/master
2021-01-25T07:18:57.191405
2010-03-27T17:41:44
2010-03-27T17:41:44
38,375,977
0
0
null
null
null
null
UTF-8
C++
false
false
8,844
cpp
#include <stdlib.h> #include <curses.h> #include <string.h> #include "Agent.h" #include "Player.h" #include "Level.h" #include "Game.h" Game::Game() { init_game(); } Game::~Game() { delwin(message_win); delwin(level_win); delwin(stats_win); endwin(); } //Initialize curses, colors, windows, and the game objects. bool Game::init_game() { initscr(); start_color(); resize_term(35, 82); raw(); noecho(); keypad(stdscr, TRUE); curs_set(0); init_pair(0, COLOR_WHITE, COLOR_BLACK); init_pair(1, COLOR_RED, COLOR_BLACK); init_pair(2, COLOR_YELLOW, COLOR_BLACK); init_pair(3, COLOR_BLACK, COLOR_WHITE); init_pair(4, COLOR_MAGENTA, COLOR_BLACK); message_win = subwin(stdscr, 2, 80, 0, 1); wmove(message_win, 1, 0); message_line_1[0] = message_line_0[0] = '\0'; level_win = subwin(stdscr, 30, 80, 2, 1); stats_win = subwin(stdscr, 3, 80, 32, 1); inventory_win = newwin(0, 0, 0, 0); current_level = 0; floors[current_level] = new Level(level_win, this); num_levels = 1; player = new Player(floors[current_level], this); floors[current_level]->add_agent(player); deaders = (Agent_List *)malloc(sizeof(Agent_List)); //need to free this and children in destructor deaders->next = NULL; game_over = game_won = game_lost = false; return true; } void Game::show_title() { mvprintw(1, 30, "The Spy Who Rogued Me"); mvprintw(3, 30, "A Seven Day Roguelike"); mvprintw(5, 30, "by robalan and jjonir"); mvprintw(10, 37, "#######"); mvprintw(11, 37, "#.....#"); mvprintw(12, 37, "#..@..#"); mvprintw(13, 37, "#.....#"); mvprintw(14, 37, "#######"); getch(); clear(); char *text1 = "The year is 1952. The place, a tiny village in Northern Sibera.\n" "Buried nearby is a secret government installation containing weapons\n" "that could destroy the world as we know it. Only you have the daring,\n" "derring-do, and derringers to stop these dastardly deviants in their\n" "tracks. Your mission, should you choose to accept it, is to fight or\n" "sneak your way through the labyrinthine passages carved into the hills\n" "and find the central control room to thwart this plot once and for all.\n"; mvprintw(0, 0, "%s", text1); printw("%s", "\nPress a key to accept this mission.\n"); curs_set(2); getch(); clear(); echo(); mvprintw(1, 1, "Enter your name: "); name[0] = 'M'; name[1] = '\0'; scanw("%31s", name); noecho(); curs_set(0); clear(); mvprintw(0, 0, "Mission Briefing.\n%s:", name); char *text2 = " You will parachute directly into the installation. You will carry as little\n" "as possible to minimize the danger of detection. You will be equipped with\n" "a derringer, some ammunition, a pocketknife, and a your jumpsuit. We trust\n" "that you will be able to find any other tools you need in the base.\n"; mvprintw(2, 0, "%s", text2); getch(); clear(); } //The main game loop. void Game::play() { player->mutual_fov(); int input; do { floors[current_level]->monsters_mutual_fov(); wclear(level_win); floors[current_level]->print(); wrefresh(level_win); show_messages(); end_message_turn(); wclear(stats_win); mvwprintw(stats_win, 0, 0, "HP %2i/%2i Floor %i", player->get_hp(), player->get_max_hp(), current_level); if (floors[current_level]->contains_item(player->get_x_pos(), player->get_y_pos())) mvwprintw(stats_win, 0, 40, "There is a %s on the floor.", floors[current_level]->get_item(player->get_x_pos(), player->get_y_pos())->get_name()); mvwprintw(stats_win, 1, 0, "Equipment: Melee weapon: %-12s Suit: %s", player->get_inventory()->get_current_melee_weapon()->get_name(), player->get_inventory()->get_current_suit()->get_name()); mvwprintw(stats_win, 2, 0, " Ranged weapon: %-13s Hat: %s", player->get_inventory()->get_current_ranged_weapon()->get_name(), player->get_inventory()->get_current_hat()->get_name()); wrefresh(stats_win); refresh(); player_acted = false; input = player->take_turn(); if(!game_over && player_acted) floors[current_level]->monsters_take_turns(); } while(input != 'Q' && !game_over); if(game_lost) { show_messages(); while(getch() != 'Q'); } } void Game::end() { if(game_lost) { clear(); mvprintw(0, 0, "Mission Report.\n%s ", name); char *text1 = "was sent on a mission three days ago.\n" "We have not had word since then. "; printw("%s", text1); mvprintw(3, 0, "%s", name); printw(" is assumed deceased."); mvprintw(5, 1, "Press any key to file this report. "); curs_set(2); getch(); curs_set(0); mvprintw(6, 1, "Report filed."); getch(); } else if(game_won) { clear(); char *text1 = "After you descend the stairs, you find yourself in a control room.\n" "There seems to be nobody else here; All of the guards were on the\n" "upper floors of the installation. You find the controls to shut down\n" "the base entirely, conveniently placed where anyone who manages to\n" "infiltrate the lower floors can activate them. You swipe any papers\n" "that look like they would be useful for your organization. Now all\n" "that remains is to wipe their files.\n"; mvprintw(0, 0, "%s", text1); mvprintw(8, 1, "Press any key to delete the plans for the weapon system. "); curs_set(2); getch(); curs_set(0); mvprintw(9, 1, "The files have been removed.\n\n" "Now all that remains is to escape this installation and meet with\n" "your contact outside, then to get back home."); getch(); clear(); mvprintw(0, 0, "Congratulations, %s!\n\nYou have won the game!\n\n\n\n" "This game was made for the 2010 seven day roguelike competition.\n\n" "Programming and Design by robalan and jjonir.\n\n" "Input and output use the public domain curses library.\n\n" "Thank you for playing!", name); getch(); } else { //wtf } } //Go down a stair. Create a new level if there is none. //If this is the last level, win the game. bool Game::descend() { if (current_level < 15) { floors[current_level]->remove_agent(player); current_level++; if (current_level >= num_levels) { floors[current_level] = new Level(level_win, this); num_levels++; } player->set_location(floors[current_level]); return true; } else { win(); return false; } } //Go up a stair. bool Game::ascend() { if (current_level > 0) { floors[current_level]->remove_agent(player); current_level--; player->set_location(floors[current_level]); return true; } else { return false; } } void Game::player_act() { player_acted = true; } void Game::end_message_turn() { if(message_line_1[0]) { strcpy(message_line_0, message_line_1); message_line_1[0] = '\0'; } } void Game::win() { game_over = true; game_won = true; } void Game::lose() { game_over = true; game_lost = true; } Agent *Game::get_player() { return player; } void Game::add_dead_agent(Agent *agent) { Agent_List *l = (Agent_List *)malloc(sizeof(Agent_List)); l->agent = agent; l->next = deaders->next; deaders->next = l; } void Game::write_message(const char *msg) { unsigned int mx = getmaxx(message_win); if(strlen(msg) + strlen(message_line_1) >= mx) { strcpy(message_line_0, message_line_1); message_line_1[0] = '\0'; } strcat(message_line_1, msg); strcat(message_line_1, " "); show_messages(); } //messages shown in aimmode or lookmode, don't keep them around. void Game::write_temp_message(const char *msg) { wclear(message_win); wattron(message_win, COLOR_PAIR(2)); mvwprintw(message_win, 0, 0, "%s", message_line_0); wattroff(message_win, COLOR_PAIR(2)); mvwprintw(message_win, 1, 0, "%s", msg); wrefresh(message_win); } void Game::show_messages() { wclear(message_win); wattron(message_win, COLOR_PAIR(2)); mvwprintw(message_win, 0, 0, "%s", message_line_0); wattroff(message_win, COLOR_PAIR(2)); mvwprintw(message_win, 1, 0, "%s", message_line_1); wrefresh(message_win); }
[ "Jjonir@e8a8b742-2983-11df-8871-772815e25991", "robalan@e8a8b742-2983-11df-8871-772815e25991", "jjonir@e8a8b742-2983-11df-8871-772815e25991" ]
[ [ [ 1, 30 ], [ 33, 36 ], [ 38, 39 ], [ 41, 41 ], [ 46, 50 ], [ 54, 55 ], [ 100, 104 ], [ 106, 106 ], [ 108, 109 ], [ 112, 113 ], [ 119, 121 ], [ 123, 123 ], [ 178, 178 ], [ 180, 180 ], [ 184, 184 ], [ 187, 187 ], [ 198, 198 ], [ 201, 201 ], [ 209, 209 ], [ 231, 242 ], [ 245, 249 ], [ 269, 270 ] ], [ [ 31, 32 ], [ 40, 40 ], [ 42, 45 ], [ 107, 107 ], [ 114, 118 ], [ 179, 179 ], [ 182, 183 ], [ 185, 186 ], [ 188, 192 ], [ 194, 197 ], [ 199, 200 ], [ 202, 208 ] ], [ [ 37, 37 ], [ 51, 53 ], [ 56, 99 ], [ 105, 105 ], [ 110, 111 ], [ 122, 122 ], [ 124, 177 ], [ 181, 181 ], [ 193, 193 ], [ 210, 230 ], [ 243, 244 ], [ 250, 268 ] ] ]
bb5c0ea46f3d8a0a25eb9e1215228b531c180154
9f2d447c69e3e86ea8fd8f26842f8402ee456fb7
/shooting2011/shooting2011/client.h
3b4ae02ecb1107afac1be3222d6b65ca61ab638b
[]
no_license
nakao5924/projectShooting2011
f086e7efba757954e785179af76503a73e59d6aa
cad0949632cff782f37fe953c149f2b53abd706d
refs/heads/master
2021-01-01T18:41:44.855790
2011-11-07T11:33:44
2011-11-07T11:33:44
2,490,410
0
1
null
null
null
null
UTF-8
C++
false
false
462
h
#ifndef __CLIENT_H__ #define __CLIENT_H__ #include "connection.h" class ClientConnection : private NonCopyable{ private: int port_; IPDATA ip_; Connection server_; bool connected_; public: ClientConnection(int port, IPDATA ip); void assign(int port, IPDATA ip); bool connect(); int send(const string &message); int receive(string &ret); int send(vector<int> &message); int receive(vector<int> &ret); }; #endif // __CLIENT_H__
[ [ [ 1, 7 ], [ 12, 12 ], [ 20, 22 ] ], [ [ 8, 11 ], [ 13, 19 ] ] ]
3e6d694d8ce2b7e1eefca9714fb224a49bee968f
a1e5c0a674084927ef5b050ebe61a89cd0731bc6
/OpenGL_SceneGraph_Stussman/Code/Aufgabe4/include/factories/builder.h
01582fd4bf92349fab9e999fa9af8ccea3b37dfc
[]
no_license
danielkummer/scenegraph
55d516dc512e1b707b6d75ec2741f48809d8797f
6c67c41a38946ac413333a84c76340c91b87dc96
refs/heads/master
2016-09-01T17:36:02.995636
2008-06-05T09:45:24
2008-06-05T09:45:24
32,327,185
0
0
null
null
null
null
UTF-8
C++
false
false
4,027
h
#ifndef _BUILDER_H #define _BUILDER_H #include "main.h" #include "nodes/allnodes.h" #include "planetdefs.h" #include "actions/actionbase.h" //for the spaceship builder: #include "factories/actionfactory.h" //-------------------------------------------------------// class Builder{ public: // Builder(); Builder(GroupNode* aRootNode, ActionBase* aAction=NULL); ~Builder(); AbstractNode* getResult(); AbstractNode* getLast(); AbstractNode* getRoot(); // void setRootNode(GroupNode* aNode); void buildGroupNode(ActionBase* aAction=NULL); void buildTransformSeparator(ActionBase* aAction=NULL); void buildSphereNode(double aRadius, int aSlices = 16, int aStacks = 16, GLboolean aUseTexCoord=GL_FALSE, ActionBase* aAction=NULL); void buildLineNode(float aVert1X, float aVert1Y, float aVert1Z, float aVert2X, float aVert2Y, float aVert2Z, float aWidth=1.0, ActionBase* aAction=NULL); void buildTranslationNode(float aX, float aY, float aZ, ActionBase* aAction=NULL); void buildRotationNode(float aAngle, float aAxisX, float aAxisY, float aAxisZ, ActionBase* aAction=NULL); void buildScaleNode(float aScaleX=1.0f, float aScaleY=1.0f, float aScaleZ=1.0f, ActionBase* aAction=NULL); void buildUniformScaleNode(float aScaleX=1.0f, ActionBase* aAction=NULL); void buildRotorNode(float aAngleVel, float aAngle, float aAxisX, float aAxisY, float aAxisZ, ActionBase* aAction=NULL); void buildLightNode(GLenum aLightNr, ActionBase* aAction=NULL); void buildLightNode(GLenum aLightNr, float posX, float posY, float posZ, float posW, float ambA, float ambB, float ambC, float ambD, float diffA, float diffB, float diffC, float diffD, ActionBase* aAction = NULL); void buildMaterialNode(GLenum aFace, ActionBase* aAction=NULL); void buildMaterialNode(GLenum aFace, Material* aMaterial, ActionBase* aAction=NULL); void buildColorNode(float aRed, float aGreen, float aBlue, float aAlpha=1.0f, ActionBase* aAction=NULL); void buildTextureNode(GLint aTexID, GLenum aTarget=GL_TEXTURE_2D, ActionBase* aAction=NULL); void buildTextureNode(GLint aTexID, GLenum aTarget, GLenum aSFactor, GLenum aDFactor, ActionBase* aAction=NULL); void buildShadowNode(float* aLightPos, float* aNormal, float* aPointInPlane, float* aColor, ActionBase* aAction=NULL); void buildToggleNode(ActionBase* aAction=NULL); void buildTranslatorNode(float xpos,float ypos, float zpos, float xvel, float yvel, float zvel, ActionBase* aAction=NULL); void buildShootSpawn(GroupNode* aNode,ActionBase* aAction=NULL); void buildLaserSpawn(GroupNode* aNode,ActionBase* aAction=NULL); void buildDestructorNode(float time,ActionBase* aAction=NULL); void buildLineNode(float aVert1X, float aVert1Y, float aVert1Z, float aVert2X, float aVert2Y, float aVert2Z, float aWidth, float ,ActionBase* aAction=NULL); void buildPolygonObjectNode(char* objFileName, char* matFileName, ActionBase* aAction=NULL); void buildMoveNode(std::vector<ActionBase*> aActions = std::vector<ActionBase*>()); void buildCamNode(std::vector<ActionBase*> aActions); void buildCamFollowNode(AbstractNode* aGlueNode, ActionBase* aAction=NULL); void append(ActionBase* aAction, AbstractNode* aNode); private: GroupNode* mCurrent; AbstractNode* mLastAdded; }; //-------------------------------------------------------// /* class Director{ public: AbstractNode* createPlanet(PlanetDef* aPlanterDef, AbstractNode** aNodelist=NULL, unsigned aNodeCount=0); AbstractNode* createSun(); AbstractNode* createSolarSystem(); AbstractNode* createAxis(float aLength=1.0); AbstractNode* createSaturnRings(PlanetDef* aPlanetDef, char* aTextureName, float aInnerFactor=1.5f, float aOuterFactor=2.5f); private: Builder mBuilder; }; */ //-------------------------------------------------------// #endif
[ "dr0iddr0id@fe886383-234b-0410-a1ab-e127868e2f45", "daniel.kummer@fe886383-234b-0410-a1ab-e127868e2f45", "[email protected]@fe886383-234b-0410-a1ab-e127868e2f45" ]
[ [ [ 1, 8 ], [ 12, 40 ], [ 42, 48 ], [ 54, 54 ], [ 59, 84 ] ], [ [ 9, 11 ], [ 41, 41 ], [ 55, 56 ], [ 58, 58 ] ], [ [ 49, 53 ], [ 57, 57 ] ] ]
3c30dba64f387ee282899974987f32ba26d4f570
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/SimRobotCore/Controller/View.cpp
a205a11b1f45e309ef0c22a50808c9115640696c
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
843
cpp
/** * @file Controller/View.cpp * * Implementation of class View * * @author <A href="mailto:[email protected]">Tim Laue</A> */ #include "View.h" void View::addToLists(std::vector<SensorPort>& sensorPortList, std::vector<Actuatorport*>&, std::vector<Actuator*>&) { sensorPortList.push_back(SensorPort(fullName, 0, this)); } void View::addToDescriptions(std::vector<ObjectDescription>& objectDescriptionTree, int depth) { //Add Sensorport: ObjectDescription sensorportDesc; int p = name.find_last_of('.'); sensorportDesc.name = p == -1 ? name : name.substr(p + 1); sensorportDesc.fullName = fullName; sensorportDesc.depth = depth; sensorportDesc.type = OBJECT_TYPE_SENSORPORT; objectDescriptionTree.push_back(sensorportDesc); }
[ "alon@rogue.(none)" ]
[ [ [ 1, 30 ] ] ]
026c994f29a25362624dbf46a59ffd4b1bbd017a
d94c6cce730a771c18a6d84c7991464129ed3556
/safeFatPrinter/trunk/src/template_painter.h
106acac245bace31e45868018ac34599f35d8eac
[]
no_license
S1aNT/cupsfilter
09afbcedb4f011744e670fae74d71fce4cebdd25
26ecc1e76eefecde2b00173dff9f91ebd92fb349
refs/heads/master
2021-01-02T09:26:27.015991
2011-03-15T06:43:47
2011-03-15T06:43:47
32,496,994
0
0
null
null
null
null
UTF-8
C++
false
false
1,336
h
#ifndef TEMPLATE_PAINTER_H #define TEMPLATE_PAINTER_H #include <QObject> #include <QPainter> #include <QGraphicsScene> #include <QGraphicsRectItem> #include <QMap> #include <QMatrix> #include <QFile> #include <QDataStream> #define POINT_TO_CM(cm) ((cm)/28.3465058) #define POINT_TO_MM(mm) ((mm)/2.83465058) //////// 0.352777778 #define POINT_TO_DM(dm) ((dm)/283.465058) #define POINT_TO_INCH(inch) ((inch)/72.0) #define MM_TO_POINT(mm) ((mm)*2.83465058) #define CM_TO_POINT(cm) ((cm)*28.3465058) ///// 28.346456693 #define DM_TO_POINT(dm) ((dm)*283.465058) #define INCH_TO_POINT(inch) ((inch)*72.0) static const int ObjectName = 0; class template_painter : public QObject { Q_OBJECT public: template_painter(); QGraphicsScene * getScene(); public slots: //void draw_overPage(bool PageOrient,QString &psize,QString &stamp,QString &mb); void read4filedraw2scene(QString &file_name,int page); private: void setPaperSize(const QString &psize); QMap<QString, int> page_size; QMatrix matrix; QRect main_rect; int page_orientation; int page_height; int page_width; int margin_top,margin_bottom,margin_left,margin_right; bool page_orient; QGraphicsScene *scene; QPainter * paintBox; }; #endif // TEMPLATE_PAINTER_H
[ [ [ 1, 49 ] ] ]
82aa59be6fd9102b419bdcd8696e0e8e6747626b
c6f4fe2766815616b37beccf07db82c0da27e6c1
/ReactorCollisionResponse.cpp
0bd7b1399d678aeece63707baddfccd5f4a6e8e0
[]
no_license
fragoulis/gpm-sem1-spacegame
c600f300046c054f7ab3cbf7193ccaad1503ca09
85bdfb5b62e2964588f41d03a295b2431ff9689f
refs/heads/master
2023-06-09T03:43:53.175249
2007-12-13T03:03:30
2007-12-13T03:03:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
293
cpp
#include "ReactorCollisionResponse.h" #include "VitalsHealth.h" #include "Object.h" using tlib::Object; using tlib::OCVitalsHealth; void ReactorCollisionResponse::respond() { OCVitalsHealth *cVitals = (OCVitalsHealth*)getOwner()->getComponent("vitals"); cVitals->hit( 1 ); }
[ "john.fragkoulis@201bd241-053d-0410-948a-418211174e54" ]
[ [ [ 1, 11 ] ] ]
067ca123ca2cb19b44cc90988a8b3c9eaa459187
33cdd09e352529963fe8b28b04e0d2e33483777b
/trunk/ReportAsistent/APTransform.h
4933b4ec00778102de7e56ee537e2b4ea6980931
[]
no_license
BackupTheBerlios/reportasistent-svn
20e386c86b6990abafb679eeb9205f2aef1af1ac
209650c8cbb0c72a6e8489b0346327374356b57c
refs/heads/master
2020-06-04T16:28:21.972009
2010-05-18T12:06:48
2010-05-18T12:06:48
40,804,982
0
0
null
null
null
null
UTF-8
C++
false
false
4,424
h
// APTransform.h: interface for the CAPTransform class. // ////////////////////////////////////////////////////////////////////// /* This file is part of LM Report Asistent. Authors: Jan Dedek, Jan Kodym, Martin Chrz, Iva Bartunkova LM Report Asistent is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. LM Report Asistent 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 LM Report Asistent; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #if !defined(AFX_APTRANSFORM_H__3C627318_5510_492C_93AE_77F522093738__INCLUDED_) #define AFX_APTRANSFORM_H__3C627318_5510_492C_93AE_77F522093738__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //zrusi varovani o prilis dlouhem identifikatoru #pragma warning( disable : 4786 ) /** * class CFilterProcessor: This class serves as a callback interface for calling of filtering functions - e.g. ProcessSimpleFilter. * * @author */ class CFilterProcessor { public: //vrati TRUE pokud funkce uspela /** * ProcessFilteredOut: * * @param filtered_output_node * @param node_order * @param user1 * @param user2 * @return virtual BOOL */ virtual BOOL ProcessFilteredOut( MSXML2::IXMLDOMNodePtr filtered_output_node, //XML uzel ktery z plugin output prosel fitrem int node_order, //poradi filtered_output_node uzlu mezi temi ktere prosly LPARAM user1, //uzivatelsky parametr, ktery byl predan filtrovaci funkci LPARAM user2 //uzivatelsky parametr, ktery byl predan filtrovaci funkci ) = 0; }; /** * class CAElTransform: This class serves for generation of one active element to a MS Word document. * * @author */ class CAElTransform: public CFilterProcessor { private: MSXML2::IXMLDOMElementPtr & m_active_element; MSXML2::IXMLDOMDocumentPtr m_plug_out; void static ApplyFixedValueFilter(MSXML2::IXMLDOMElementPtr & filter_dom, LPCTSTR attr_name, BOOL num_compare, LPCTSTR fixed_value); void static ApplyTopNFilter(MSXML2::IXMLDOMElementPtr & filter_dom, LPCTSTR attr_name, BOOL numeric_sort, BOOL descending_sort, int top_n); void static ApplyTresholdFilter(MSXML2::IXMLDOMElementPtr & filter_dom, LPCTSTR attr_name, BOOL numeric_sort, BOOL descending_sort, LPCTSTR treshold); public: BOOL LoadFilterDOM(public_source_id_t sId, MSXML2::IXMLDOMElementPtr & filter_DOM); void TransformCmplexFilterToSimple(); void ApplyAllFilters(MSXML2::IXMLDOMElementPtr & filter_dom); void ApplyAllAttributeFilters(MSXML2::IXMLDOMElementPtr & filter_dom); void static ApplySingleAttributeFilter(MSXML2::IXMLDOMElementPtr & filter_dom, MSXML2::IXMLDOMElementPtr attribute_filter); protected: void FillElementAttributes(MSXML2::IXMLDOMNodePtr & output_node); virtual BOOL ProcessFilteredOut(MSXML2::IXMLDOMNodePtr filtered_output_node, int node_order, LPARAM user1, LPARAM user2); void ProcessSimpleFlter(MSXML2::IXMLDOMNodePtr & destination_parent); void ProcessAllTransformations(MSXML2::IXMLDOMNodePtr & target, MSXML2::IXMLDOMNodePtr & destination_parent); void ProcessSingleTransformation( MSXML2::IXMLDOMNodePtr & target, MSXML2::IXMLDOMNodePtr & destination_parent, MSXML2::IXMLDOMNodePtr & transformation_node); void static CAElTransform::SetTransformationOptions(MSXML2::IXMLDOMNodePtr & el_transformation, MSXML2::IXMLDOMNodePtr & values_node); public: BOOL ProcessSimpleFlter(CFilterProcessor & processor, LPARAM user1 = 0, LPARAM user2 = 0); BOOL FillElementAttributes(int index_of_filtered_out); MSXML2::IXMLDOMDocumentFragmentPtr DoAllTransnformations(); CAElTransform(MSXML2::IXMLDOMElementPtr & active_element); CAElTransform(MSXML2::IXMLDOMElementPtr & active_element, MSXML2::IXMLDOMNodePtr & plugin_output); ~CAElTransform(); }; #pragma warning( default : 4786 ) #endif // !defined(AFX_APTRANSFORM_H__3C627318_5510_492C_93AE_77F522093738__INCLUDED_)
[ "dedej1am@fded5620-0c03-0410-a24c-85322fa64ba0", "chrzm@fded5620-0c03-0410-a24c-85322fa64ba0", "ibart@fded5620-0c03-0410-a24c-85322fa64ba0" ]
[ [ [ 1, 3 ], [ 6, 6 ], [ 23, 27 ], [ 29, 33 ], [ 39, 42 ], [ 53, 61 ], [ 67, 115 ] ], [ [ 4, 5 ], [ 7, 22 ], [ 34, 34 ], [ 36, 38 ], [ 43, 52 ], [ 62, 62 ], [ 64, 66 ] ], [ [ 28, 28 ], [ 35, 35 ], [ 63, 63 ] ] ]
516c7154e5144eba7edc274b36fc98dc320112a0
af260b99d9f045ac4202745a3c7a65ac74a5e53c
/tags/engine/src/persistance/StrOutputStream.h
d4524b444c6d268f683acef9c5ee0f1f9658f3da
[]
no_license
BackupTheBerlios/snap-svn
560813feabcf5d01f25bc960d474f7e218373da0
a99b5c64384cc229e8628b22f3cf6a63a70ed46f
refs/heads/master
2021-01-22T09:43:37.862180
2008-02-17T15:50:06
2008-02-17T15:50:06
40,819,397
0
0
null
null
null
null
UTF-8
C++
false
false
2,773
h
#ifndef _SeedSearcher_Persistance_StrOutputStream_h #define _SeedSearcher_Persistance_StrOutputStream_h #include "OutputStream.h" #include <string> BEGIN_NAMESPACE (Persistance); template <class StringT> class TStrOutputStream : public OutputStream { public: TStrOutputStream (StringT& out) : _out (out) { } protected: virtual void nextBuffer() { Size bytes = bytesInBuffer (); if (bytes > 0) { _out.append (_buffer, bytes); } setupBuffer (reinterpret_cast<Ptr> (_buffer), sizeof (_buffer)); } virtual bool hasMoreBuffers() const { return true; } private: char _buffer [1024]; StringT& _out; }; typedef TStrOutputStream <std::string> StrOutputStream; class FixedBufferOutputStream : public OutputStream { public: FixedBufferOutputStream (char* inBuffer, int inCapacity) : _host (inBuffer), _hostCapacity (inCapacity), _size (0) { } ~FixedBufferOutputStream () { if (bytesInBuffer () > 0) flush (); } int bytesWritten () const { return _size; } class BufferOverrun: public BaseException {}; virtual void nextBuffer () { bufferPos += bytesInBuffer (); doFlush (); if (bufStart == 0 && bufEnd == 0) throwx (BufferOverrun ()); } virtual void flush (){ bufferPos += bytesInBuffer (); doFlush (); if (bufStart == 0 && bufEnd == 0) throwx (BufferOverrun ()); } virtual bool hasMoreBuffers() const { return _size < _hostCapacity; } int getSize () const { return _size; } protected: char* _host; int _hostCapacity; int _size; void doFlush () { _size += bytesInBuffer (); if (_hostCapacity < _size) setupBuffer (Ptr (NULL), Size (0)); else setupBuffer (Ptr (_host + _size), _hostCapacity - _size); } }; END_NAMESPACE (Persistance); #endif // // File : $RCSfile: $ // $Workfile: StrOutputStream.h $ // Version : $Revision: 7 $ // $Author: Aviad $ // $Date: 16/12/04 6:07 $ // Description : // The Persistence library contains both high & low level IO classes // and is high-performance, highly reusable framework // // Author: // Aviad Rozenhek (mailto:[email protected]) 2003-2004 // // written for the SeedSearcher program. // for details see www.huji.ac.il/~hoan // and also http://www.cs.huji.ac.il/~nirf/Abstracts/BGF1.html // // this file and as well as its library are released for academic research // only. the LESSER GENERAL PUBLIC LICENSE (LPGL) license // as well as any other restrictions as posed by the computational biology lab // and the library authors appliy. //
[ "aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478" ]
[ [ [ 1, 111 ] ] ]
00a4dd6988c88925368616a5d82bd09a693331fb
12203ea9fe0801d613bbb2159d4f69cab3c84816
/Export/cpp/windows/obj/src/nme/display/StageQuality.cpp
6eb5b06eed683a0fd36633737f2583cea8588726
[]
no_license
alecmce/haxe_game_of_life
91b5557132043c6e9526254d17fdd9bcea9c5086
35ceb1565e06d12c89481451a7bedbbce20fa871
refs/heads/master
2016-09-16T00:47:24.032302
2011-10-10T12:38:14
2011-10-10T12:38:14
2,547,793
0
0
null
null
null
null
UTF-8
C++
false
false
2,532
cpp
#include <hxcpp.h> #ifndef INCLUDED_nme_display_StageQuality #include <nme/display/StageQuality.h> #endif namespace nme{ namespace display{ ::nme::display::StageQuality StageQuality_obj::BEST; ::nme::display::StageQuality StageQuality_obj::HIGH; ::nme::display::StageQuality StageQuality_obj::LOW; ::nme::display::StageQuality StageQuality_obj::MEDIUM; HX_DEFINE_CREATE_ENUM(StageQuality_obj) int StageQuality_obj::__FindIndex(::String inName) { if (inName==HX_CSTRING("BEST")) return 3; if (inName==HX_CSTRING("HIGH")) return 2; if (inName==HX_CSTRING("LOW")) return 0; if (inName==HX_CSTRING("MEDIUM")) return 1; return super::__FindIndex(inName); } int StageQuality_obj::__FindArgCount(::String inName) { if (inName==HX_CSTRING("BEST")) return 0; if (inName==HX_CSTRING("HIGH")) return 0; if (inName==HX_CSTRING("LOW")) return 0; if (inName==HX_CSTRING("MEDIUM")) return 0; return super::__FindArgCount(inName); } Dynamic StageQuality_obj::__Field(const ::String &inName) { if (inName==HX_CSTRING("BEST")) return BEST; if (inName==HX_CSTRING("HIGH")) return HIGH; if (inName==HX_CSTRING("LOW")) return LOW; if (inName==HX_CSTRING("MEDIUM")) return MEDIUM; return super::__Field(inName); } static ::String sStaticFields[] = { HX_CSTRING("LOW"), HX_CSTRING("MEDIUM"), HX_CSTRING("HIGH"), HX_CSTRING("BEST"), ::String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(StageQuality_obj::BEST,"BEST"); HX_MARK_MEMBER_NAME(StageQuality_obj::HIGH,"HIGH"); HX_MARK_MEMBER_NAME(StageQuality_obj::LOW,"LOW"); HX_MARK_MEMBER_NAME(StageQuality_obj::MEDIUM,"MEDIUM"); }; static ::String sMemberFields[] = { ::String(null()) }; Class StageQuality_obj::__mClass; Dynamic __Create_StageQuality_obj() { return new StageQuality_obj; } void StageQuality_obj::__register() { Static(__mClass) = hx::RegisterClass(HX_CSTRING("nme.display.StageQuality"), hx::TCanCast< StageQuality_obj >,sStaticFields,sMemberFields, &__Create_StageQuality_obj, &__Create, &super::__SGetClass(), &CreateStageQuality_obj, sMarkStatics); } void StageQuality_obj::__boot() { Static(BEST) = hx::CreateEnum< StageQuality_obj >(HX_CSTRING("BEST"),3); Static(HIGH) = hx::CreateEnum< StageQuality_obj >(HX_CSTRING("HIGH"),2); Static(LOW) = hx::CreateEnum< StageQuality_obj >(HX_CSTRING("LOW"),0); Static(MEDIUM) = hx::CreateEnum< StageQuality_obj >(HX_CSTRING("MEDIUM"),1); } } // end namespace nme } // end namespace display
[ [ [ 1, 83 ] ] ]
756cbdbe584d53d0b36e9116f277e18c144051d7
f9774f8f3c727a0e03c170089096d0118198145e
/传奇mod/mirserver/LoginGate/ThreadFuncForComm.cpp
e6d196468ffa62f629fed81fc4e558265b5719e9
[]
no_license
sdfwds4/fjljfatchina
62a3bcf8085f41d632fdf83ab1fc485abd98c445
0503d4aa1907cb9cf47d5d0b5c606df07217c8f6
refs/heads/master
2021-01-10T04:10:34.432964
2010-03-07T09:43:28
2010-03-07T09:43:28
48,106,882
1
1
null
null
null
null
UTF-8
C++
false
false
1,134
cpp
#include "stdafx.h" #define PACKET_KEEPALIVE "%--$" extern HWND g_hToolBar; extern HWND g_hStatusBar; extern SOCKET g_csock; extern SOCKADDR_IN g_caddr; void SendExToServer(char *pszPacket); BOOL jRegGetKey(LPCTSTR pSubKeyName, LPCTSTR pValueName, LPBYTE pValue); VOID WINAPI OnTimerProc(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) { switch (idEvent) { case _ID_TIMER_KEEPALIVE: { if (g_csock != INVALID_SOCKET) { SendExToServer(PACKET_KEEPALIVE); SendMessage(g_hStatusBar, SB_SETTEXT, MAKEWORD(2, 0), (LPARAM)_TEXT("Check Activity")); } break; } case _ID_TIMER_CONNECTSERVER: { if (g_csock == INVALID_SOCKET) { DWORD dwIP = 0; int nPort = 0; InsertLogMsg(IDS_APPLY_RECONNECT); jRegGetKey(_LOGINGATE_SERVER_REGISTRY, _TEXT("RemoteIP"), (LPBYTE)&dwIP); if (!jRegGetKey(_LOGINGATE_SERVER_REGISTRY, _TEXT("RemotePort"), (LPBYTE)&nPort)) nPort = 5000; ConnectToServer(g_csock, &g_caddr, _IDM_CLIENTSOCK_MSG, NULL, dwIP, nPort, FD_CONNECT|FD_READ|FD_CLOSE); } break; } } }
[ "fjljfat@4a88d1ba-22b1-11df-8001-4f4b503b426e" ]
[ [ [ 1, 49 ] ] ]
efab6d78bbea56728d60a7c43325099201bfed84
b1093f654e78210a00e6ca561c1a8f8f108f543e
/include/Kernel.h
8a11857791fbc2122108ef9781393942143de81d
[]
no_license
childhood/libAiml
bc82b7cd8859aa6fe0a7a3c42ffe4591438ae329
7954dc347463bcb4ab0070af87b9cbd421b08acc
refs/heads/master
2021-01-18T10:07:02.407246
2010-09-20T04:40:34
2010-09-20T04:40:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,100
h
/** * Kernel - Brains of the operation * * @author Jonathan Roewen */ #ifndef KERNEL_H #define KERNEL_H #include <string> #include <stdlib.h> using namespace std; #include "Element.h" #include "PredicateEngine.h" class Match; class Responder; class Nodemaster; class StringTokenizer; class Kernel { public: Kernel(); ~Kernel(); static string bootstrap(); static bool load(const string &file); static void load10(const string &file, PElement &root); static void loadSubstitutions(); static Nodemaster * add(const string &context, const string &pattern, const string &that, const string &topic); static Match *match(const string &context, const string &input, const string &that, const string &topic); static Match *match(Nodemaster *node, Nodemaster *parent, int state, const string &input, const string &star, const string &path); static string process(Match *m, PElement e, Responder *, const string &id); static string respond(const string &input, const string &id, const string &prefix = ""); static string respond(const string &input, const string &id, bool srai, const string &prefix = ""); static string respond(const string &input, const string &id, Responder *, bool srai = false, const string &prefix = ""); static string respond(const string &input, const string &id, int depth, bool srai, const string &prefix = ""); static string respond(const string &input, const string &id, Responder *, int depth, bool srai, const string &prefix = ""); static void convertTempAiml(); static PredicateEngine *predicates; static bool trace; static int maxRecursiveDepth; static string botName; static string connectPattern; static string noMatchPattern; static string loopPattern; private: static void addStar(Match *, const string &, int); static void addPath(Match *, const string &, int); static bool lookup(const string &, const string &); static void loadTemporaryData(); static Nodemaster *root; static const int CONTEXT, INPUT, THAT, TOPIC; static const string constants; }; #endif
[ [ [ 1, 62 ] ] ]
c531ee9b568f98b14e374e916f1ca98ac1efb9a2
bb948fa4eb86d36ddddc4fb78807c6f7620e578d
/standalone/pynary/test/test_dll.cpp
3f9501a9abe672734fb8eff5d7edd9e15e80afee
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
trietptm/openrce-snippets
82d5a57f73be3ee114673c5bbcc012d9189908e5
c1d85a4e6979a09d2c9126e3026039300c368e6c
refs/heads/master
2020-05-27T17:34:14.217997
2009-02-03T09:09:20
2009-02-03T09:09:20
36,658,405
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #include <stdio.h> #include <tchar.h> #include "Math.h" extern "C" int MyFunction(int arg) { printf("%d",doSomething(arg)); return 0; }
[ "c1de0x@4f06ebed-573f-0410-ba13-9bbf17867248" ]
[ [ [ 1, 15 ] ] ]
8859c27983f619aeec9e2221a1c1bc329c402afb
6ee200c9dba87a5d622c2bd525b50680e92b8dab
/Autumn/Game/Viewer/Viewer.h
92bff318b79bbc986902d7ab82ae9992a83ea273
[]
no_license
Ishoa/bizon
4dbcbbe94d1b380f213115251e1caac5e3139f4d
d7820563ab6831d19e973a9ded259d9649e20e27
refs/heads/master
2016-09-05T11:44:00.831438
2010-03-10T23:14:22
2010-03-10T23:14:22
32,632,823
0
0
null
null
null
null
UTF-8
C++
false
false
653
h
#ifndef _VIEWER_ #define _VIEWER_ #ifndef _ENGINE_DX_ #include "Engine/Engine/EngineDx.h" #endif class Node; class PLYObject; class Terrain; class Sky; class Viewer : public Engine { protected: Node * m_pRoot; PLYObject * m_pTeapot; Terrain * m_pTerrain; Sky * m_pSky; public: Viewer(); virtual ~Viewer(); virtual HRESULT Create(HWND _hWnd, HINSTANCE _hInstance, unsigned int _uWidth, unsigned int _uHeight, bool _bFullscreen = false); virtual HRESULT Destroy(); virtual void Update(); virtual void Render(); virtual HRESULT Resize(unsigned int _uWidth, unsigned int _uHeight); }; #endif // _VIEWER_
[ "edouard.roge@ab19582e-f48f-11de-8f43-4547254af6c6" ]
[ [ [ 1, 33 ] ] ]
6ed168eea6509a36518cbe770c8acc148d773846
d01196cdfc4451c4e1c88343bdb1eb4db9c5ac18
/source/client/global/dll_int.cpp
657a2783a5dc15afa277456a03e07a1366602d45
[]
no_license
ferhan66h/Xash3D_ancient
7491cd4ff1c7d0b48300029db24d7e08ba96e88a
075e0a6dae12a0952065eb9b2954be4a8827c72f
refs/heads/master
2021-12-10T07:55:29.592432
2010-05-09T00:00:00
2016-07-30T17:37:36
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
12,657
cpp
//======================================================================= // Copyright XashXT Group 2008 © // dll_int.cpp - dll entry points //======================================================================= #include "extdll.h" #include "utils.h" #include "ref_params.h" #include "studio_ref.h" #include "hud.h" #include "aurora.h" #include "r_particle.h" #include "r_tempents.h" #include "r_beams.h" #include "ev_hldm.h" #include "pm_shared.h" #include "r_weather.h" cl_enginefuncs_t g_engfuncs; cl_globalvars_t *gpGlobals; movevars_t *gpMovevars = NULL; ref_params_t *gpViewParams = NULL; CHud gHUD; // main DLL entry point BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved ) { return TRUE; } static HUD_FUNCTIONS gFunctionTable = { sizeof( HUD_FUNCTIONS ), HUD_VidInit, HUD_Init, HUD_Redraw, HUD_UpdateEntityVars, HUD_UpdateOnRemove, HUD_Reset, HUD_StartFrame, HUD_Frame, HUD_Shutdown, HUD_RenderCallback, HUD_CreateEntities, HUD_AddVisibleEntity, HUD_StudioEvent, HUD_StudioFxTransform, V_CalcRefdef, PM_Move, // pfnPM_Move PM_Init, // pfnPM_Init PM_FindTextureType, // pfnPM_FindTextureType HUD_CmdStart, HUD_CmdEnd, IN_CreateMove, IN_MouseEvent, IN_KeyEvent, VGui_ConsolePrint, }; //======================================================================= // GetApi //======================================================================= int CreateAPI( HUD_FUNCTIONS *pFunctionTable, cl_enginefuncs_t* pEngfuncsFromEngine, cl_globalvars_t *pGlobals ) { if( !pFunctionTable || !pEngfuncsFromEngine ) { return FALSE; } // copy HUD_FUNCTIONS table to engine, copy engfuncs table from engine memcpy( pFunctionTable, &gFunctionTable, sizeof( HUD_FUNCTIONS )); memcpy( &g_engfuncs, pEngfuncsFromEngine, sizeof( cl_enginefuncs_t )); gpGlobals = pGlobals; gpViewParams = gpGlobals->pViewParms; gpMovevars = gpViewParams->movevars; return TRUE; } int HUD_VidInit( void ) { if ( g_pParticleSystems ) g_pParticleSystems->ClearSystems(); if ( g_pViewRenderBeams ) g_pViewRenderBeams->ClearBeams(); if ( g_pParticles ) g_pParticles->Clear(); if ( g_pTempEnts ) g_pTempEnts->Clear(); ResetRain (); gHUD.VidInit(); return 1; } void HUD_ShutdownEffects( void ) { if ( g_pParticleSystems ) { // init partsystem delete g_pParticleSystems; g_pParticleSystems = NULL; } if ( g_pViewRenderBeams ) { // init render beams delete g_pViewRenderBeams; g_pViewRenderBeams = NULL; } if ( g_pParticles ) { // init particles delete g_pParticles; g_pParticles = NULL; } if ( g_pTempEnts ) { // init client tempents delete g_pTempEnts; g_pTempEnts = NULL; } } void HUD_Init( void ) { g_engfuncs.pfnAddCommand ("noclip", NULL, "enable or disable no clipping mode" ); g_engfuncs.pfnAddCommand ("notarget", NULL, "notarget mode (monsters do not see you)" ); g_engfuncs.pfnAddCommand ("fullupdate", NULL, "re-init HUD on start demo recording" ); g_engfuncs.pfnAddCommand ("give", NULL, "give specified item or weapon" ); g_engfuncs.pfnAddCommand ("drop", NULL, "drop current/specified item or weapon" ); g_engfuncs.pfnAddCommand ("intermission", NULL, "go to intermission" ); g_engfuncs.pfnAddCommand ("spectate", NULL, "enable spectator mode" ); g_engfuncs.pfnAddCommand ("gametitle", NULL, "show game logo" ); g_engfuncs.pfnAddCommand ("god", NULL, "classic cheat" ); g_engfuncs.pfnAddCommand ("fov", NULL, "set client field of view" ); g_engfuncs.pfnAddCommand ("fly", NULL, "fly mode (flight)" ); HUD_ShutdownEffects (); g_pParticleSystems = new ParticleSystemManager(); g_pViewRenderBeams = new CViewRenderBeams(); g_pParticles = new CParticleSystem(); g_pTempEnts = new CTempEnts(); InitRain(); // init weather system gHUD.Init(); IN_Init (); // link all events EV_HookEvents (); } int HUD_Redraw( float flTime, int state ) { switch( state ) { case CL_LOADING: DrawProgressBar(); break; case CL_ACTIVE: gHUD.Redraw( flTime ); break; case CL_PAUSED: gHUD.Redraw( flTime ); DrawPause(); break; case CL_CHANGELEVEL: DrawImageBar( 100, "m_loading" ); break; } return 1; } void HUD_UpdateEntityVars( edict_t *ent, const entity_state_t *state, const entity_state_t *prev ) { float m_fLerp; if( state->ed_type == ED_CLIENT && state->ed_flags & ESF_NO_PREDICTION ) m_fLerp = 1.0f; else m_fLerp = GetLerpFrac(); if( state->flags & FL_PROJECTILE && state->ed_flags & ( ESF_NO_PREDICTION|ESF_NODELTA )) { // cut rocket trail, dont pass it from teleport // FIXME: don't work g_pViewRenderBeams->KillDeadBeams( ent ); } // copy state to progs ent->v.modelindex = state->modelindex; ent->v.weaponmodel = state->weaponmodel; ent->v.sequence = state->sequence; ent->v.gaitsequence = state->gaitsequence; ent->v.body = state->body; ent->v.skin = state->skin; ent->v.effects = state->effects; ent->v.velocity = state->velocity; ent->v.basevelocity = state->basevelocity; ent->v.oldorigin = ent->v.origin; // previous origin holds ent->v.mins = state->mins; ent->v.maxs = state->maxs; ent->v.framerate = state->framerate; ent->v.colormap = state->colormap; ent->v.rendermode = state->rendermode; ent->v.renderfx = state->renderfx; ent->v.fov = state->fov; ent->v.scale = state->scale; ent->v.weapons = state->weapons; ent->v.gravity = state->gravity; ent->v.health = state->health; ent->v.solid = state->solid; ent->v.movetype = state->movetype; ent->v.flags = state->flags; ent->v.ideal_pitch = state->idealpitch; ent->v.animtime = state->animtime; ent->v.ltime = state->localtime; if( state->groundent != -1 ) ent->v.groundentity = GetEntityByIndex( state->groundent ); else ent->v.groundentity = NULL; if( state->aiment != -1 ) ent->v.aiment = GetEntityByIndex( state->aiment ); else ent->v.aiment = NULL; switch( ent->v.movetype ) { case MOVETYPE_NONE: case MOVETYPE_STEP: // monster's steps will be interpolated on render-side ent->v.origin = state->origin; ent->v.angles = state->angles; ent->v.oldorigin = prev->origin; // used for lerp 'monster view' ent->v.oldangles = prev->angles; // used for lerp 'monster view' break; default: ent->v.angles = LerpAngle( prev->angles, state->angles, m_fLerp ); ent->v.origin = LerpPoint( prev->origin, state->origin, m_fLerp ); ent->v.basevelocity = LerpPoint( prev->basevelocity, state->basevelocity, m_fLerp ); break; } // interpolate scale, renderamount etc ent->v.scale = LerpPoint( prev->scale, state->scale, m_fLerp ); ent->v.rendercolor = LerpPoint( prev->rendercolor, state->rendercolor, m_fLerp ); ent->v.renderamt = LerpPoint( prev->renderamt, state->renderamt, m_fLerp ); if( ent->v.animtime ) { // use normal studio lerping ent->v.frame = state->frame; } else { // round sprite and brushmodel frames ent->v.frame = Q_rint( state->frame ); } switch( state->ed_type ) { case ED_CLIENT: ent->v.punchangle = LerpAngle( prev->punch_angles, state->punch_angles, m_fLerp ); ent->v.viewangles = LerpAngle( prev->viewangles, state->viewangles, m_fLerp ); ent->v.view_ofs = LerpPoint( prev->viewoffset, state->viewoffset, m_fLerp ); if( prev->fov != 90.0f && state->fov == 90.0f ) ent->v.fov = state->fov; // fov is reset, so don't lerping else ent->v.fov = LerpPoint( prev->fov, state->fov, m_fLerp ); ent->v.maxspeed = state->maxspeed; ent->v.iStepLeft = state->iStepLeft; ent->v.flFallVelocity = state->flFallVelocity; if( ent == GetLocalPlayer()) { edict_t *viewent = GetViewModel(); // if viewmodel has changed update sequence here if( viewent->v.modelindex != state->viewmodel ) { // ALERT( at_console, "Viewmodel changed\n" ); SendWeaponAnim( viewent->v.sequence, viewent->v.body, viewent->v.framerate ); } // setup player viewmodel (only for local player!) viewent->v.modelindex = state->viewmodel; gHUD.m_flFOV = ent->v.fov; // keep client fov an actual } break; case ED_PORTAL: case ED_MOVER: case ED_BSPBRUSH: ent->v.movedir = BitsToDir( state->body ); ent->v.oldorigin = state->oldorigin; break; case ED_SKYPORTAL: { skyportal_t *sky = &gpViewParams->skyportal; // setup sky portal sky->vieworg = ent->v.origin; sky->viewanglesOffset.x = sky->viewanglesOffset.z = 0.0f; sky->viewanglesOffset.y = gHUD.m_flTime * ent->v.angles[1]; sky->scale = (ent->v.scale ? 1.0f / ent->v.scale : 0.0f ); // critical stuff sky->fov = ent->v.fov; } break; case ED_BEAM: ent->v.oldorigin = state->oldorigin; // beam endpoint ent->v.frags = state->gaitsequence; if( state->owner != -1 ) ent->v.owner = GetEntityByIndex( state->owner ); else ent->v.owner = NULL; // add server beam now g_pViewRenderBeams->AddServerBeam( ent ); break; default: ent->v.movedir = Vector( 0, 0, 0 ); break; } int i; // copy blendings for( i = 0; i < MAXSTUDIOBLENDS; i++ ) ent->v.blending[i] = state->blending[i]; // copy controllers for( i = 0; i < MAXSTUDIOCONTROLLERS; i++ ) ent->v.controller[i] = state->controller[i]; // g-cont. moved here because we may needs apply null scale to skyportal if( ent->v.scale == 0.0f && ent->v.skin >= 0 ) ent->v.scale = 1.0f; ent->v.pContainingEntity = ent; } int HUD_AddVisibleEntity( edict_t *pEnt, int ed_type ) { float oldScale, oldRenderAmt; float shellScale = 1.0f; int result; if ( pEnt->v.renderfx == kRenderFxGlowShell ) { oldRenderAmt = pEnt->v.renderamt; oldScale = pEnt->v.scale; pEnt->v.renderamt = 255; // clear amount } result = CL_AddEntity( pEnt, ed_type, -1 ); if ( pEnt->v.renderfx == kRenderFxGlowShell ) { shellScale = (oldRenderAmt * 0.0015f); // shellOffset pEnt->v.scale = oldScale + shellScale; // sets new scale pEnt->v.renderamt = 128; // render glowshell result |= CL_AddEntity( pEnt, ed_type, g_pTempEnts->hSprGlowShell ); // restore parms pEnt->v.scale = oldScale; pEnt->v.renderamt = oldRenderAmt; } if ( pEnt->v.effects & EF_BRIGHTFIELD ) { g_engfuncs.pEfxAPI->R_EntityParticles( pEnt ); } // add in muzzleflash effect if ( pEnt->v.effects & EF_MUZZLEFLASH ) { if( ed_type == ED_VIEWMODEL ) pEnt->v.effects &= ~EF_MUZZLEFLASH; g_pTempEnts->WeaponFlash( pEnt, 1 ); } // add light effect if ( pEnt->v.effects & EF_LIGHT ) { g_pTempEnts->AllocDLight( pEnt->v.origin, 100, 100, 100, 200, 0.001f, 0 ); g_pTempEnts->RocketFlare( pEnt->v.origin ); } // add dimlight if ( pEnt->v.effects & EF_DIMLIGHT ) { if ( ed_type == ED_CLIENT ) { EV_UpadteFlashlight( pEnt ); } else { g_pTempEnts->AllocDLight( pEnt->v.origin, RANDOM_LONG( 200, 230 ), 0.001f, 0 ); } } if ( pEnt->v.effects & EF_BRIGHTLIGHT ) { Vector pos( pEnt->v.origin.x, pEnt->v.origin.y, pEnt->v.origin.z + 16 ); g_pTempEnts->AllocDLight( pos, RANDOM_LONG( 400, 430 ), 0.001f, 0 ); } return result; } void HUD_CreateEntities( void ) { EV_UpdateBeams (); // egon use this EV_UpdateLaserSpot (); // predictable laserspot // add in any game specific objects here g_pViewRenderBeams->UpdateTempEntBeams( ); g_pTempEnts->Update(); } void HUD_UpdateOnRemove( edict_t *pEdict ) { // move TE_BEAMTRAIL, kill other beams g_pViewRenderBeams->KillDeadBeams( pEdict ); } void HUD_Reset( void ) { HUD_VidInit (); } void HUD_StartFrame( void ) { // clear list of server beams after each frame g_pViewRenderBeams->ClearServerBeams( ); } void HUD_Frame( double time ) { // place to call vgui_frame // VGUI not implemented, wait for version 0.75 gHUD.m_Sound.Update(); } void HUD_Shutdown( void ) { gHUD.m_Sound.Close(); HUD_ShutdownEffects (); IN_Shutdown (); // perform shutdown operations g_engfuncs.pfnDelCommand ("noclip" ); g_engfuncs.pfnDelCommand ("notarget" ); g_engfuncs.pfnDelCommand ("fullupdate" ); g_engfuncs.pfnDelCommand ("give" ); g_engfuncs.pfnDelCommand ("drop" ); g_engfuncs.pfnDelCommand ("intermission" ); g_engfuncs.pfnDelCommand ("spectate" ); g_engfuncs.pfnDelCommand ("gametitle" ); g_engfuncs.pfnDelCommand ("god" ); g_engfuncs.pfnDelCommand ("fov" ); g_engfuncs.pfnDelCommand ("fly" ); }
[ [ [ 1, 475 ] ] ]
7b9f3d707c65a69d4629fc76155979ecfc8cd240
d8ee6216089aa884589ca9175d3bc191dcc1ea12
/PostEffectProgram/Src/GraphicEntity.cpp
1666a38d05e8a0d56df29f130bb0bc86e60ba55c
[]
no_license
OtterOrder/posteffectprogram
a15035eb96a107ec220f834baeb4c4db2573fd56
ff713b71ba72984e74fc62e9a1f7b1fb8fb43198
refs/heads/master
2016-09-05T09:06:20.138050
2009-06-30T07:21:43
2009-06-30T07:21:43
32,115,407
0
0
null
null
null
null
UTF-8
C++
false
false
2,585
cpp
#include "GraphicEntity.h" #include "Camera.h" #include "GBufferRenderer.h" //------------------------------------------------------------------------------------------------------------------------------ GraphicEntity::GraphicEntity(void) { m_pMesh = NULL; m_pMaterial = NULL; MatrixIdentity(&m_WorldMatrix); } //------------------------------------------------------------------------------------------------------------------------------ GraphicEntity::~GraphicEntity(void) { Release (); } //------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------ void GraphicEntity::Release () { SAFE_DELETE(m_pMesh); SAFE_DELETE(m_pMaterial); } //------------------------------------------------------------------------------------------------------------------------------ HRESULT GraphicEntity::Initialize(cStr _meshFileName, cStr _vertexShaderFileName, cStr _vertexEntryPoint, cStr _pixelShaderFileName, cStr _pixelEntryPoint) { SAFE_NEW(m_pMesh, Mesh); if ( FAILED(m_pMesh->LoadFromXFile(_meshFileName)) ) { SAFE_DELETE(m_pMesh); return E_FAIL; } SAFE_NEW(m_pMaterial, Material); m_pMaterial->SetShader(_vertexShaderFileName, _vertexEntryPoint, _pixelShaderFileName, _pixelEntryPoint); return S_OK; } //------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------ void GraphicEntity::Draw () { if (!m_pMesh) return; if (m_pMaterial) { m_pMaterial->Apply(); } getDevice->SetVertexDeclaration(m_pMesh->m_pVD); getDevice->SetStreamSource(0, m_pMesh->m_pVB, 0, m_pMesh->m_VertexSize); getDevice->SetIndices(m_pMesh->m_pIB); getDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, m_pMesh->m_NbVertices, 0, m_pMesh->m_NbFaces); } //------------------------------------------------------------------------------------------------------------------------------ void GraphicEntity::DrawWithoutMaterial () { getDevice->SetVertexDeclaration(m_pMesh->m_pVD); getDevice->SetStreamSource(0, m_pMesh->m_pVB, 0, m_pMesh->m_VertexSize); getDevice->SetIndices(m_pMesh->m_pIB); getDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, m_pMesh->m_NbVertices, 0, m_pMesh->m_NbFaces); }
[ "alban.chagnoleau@7ea0d518-2368-11de-96a1-5542d1fc8aa6", "germain.mazac@7ea0d518-2368-11de-96a1-5542d1fc8aa6" ]
[ [ [ 1, 3 ], [ 5, 29 ], [ 31, 33 ], [ 35, 40 ], [ 42, 47 ], [ 49, 54 ], [ 56, 57 ], [ 59, 59 ], [ 62, 62 ], [ 64, 66 ], [ 68, 68 ], [ 70, 70 ], [ 73, 73 ], [ 75, 75 ] ], [ [ 4, 4 ], [ 30, 30 ], [ 34, 34 ], [ 41, 41 ], [ 48, 48 ], [ 55, 55 ], [ 58, 58 ], [ 60, 61 ], [ 63, 63 ], [ 67, 67 ], [ 69, 69 ], [ 71, 72 ], [ 74, 74 ] ] ]
6fbfd29e32dc2329ce13a2b3d12f5c0da2486b85
e8f3f51e5f96432fdad1f1335155de5d45738e39
/AdvComboBoxDemo.h
2b9c956ffec09b0a231001be909e5209706b448a
[]
no_license
zephyrer/advcombobox
d7d40b642e4b7cb503c2b76d7435dff553768424
92abf3482c825df80a6b17b0db5eb1062e9f1228
refs/heads/master
2020-05-24T15:34:59.617035
2010-09-29T19:55:47
2010-09-29T19:55:47
40,066,912
0
0
null
null
null
null
UTF-8
C++
false
false
2,898
h
///////////////////////////////////////////////////////////////////////////// // AdvComboBoxDemo.h : main header file for the ADVCOMBOBOXDEMO application // // Copyright (c) 2010 Mathias Tunared // // 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. // // This file is provided "as is" with no expressed or implied warranty. // The author accepts no liability for any damage/loss of business that // this product may cause. // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_ADVCOMBOBOXDEMO_H__D3488651_1658_4B01_957A_7C90F656E8DA__INCLUDED_) #define AFX_ADVCOMBOBOXDEMO_H__D3488651_1658_4B01_957A_7C90F656E8DA__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CAdvComboBoxDemoApp: // See AdvComboBoxDemo.cpp for the implementation of this class // class CAdvComboBoxDemoApp : public CWinApp { public: CAdvComboBoxDemoApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAdvComboBoxDemoApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CAdvComboBoxDemoApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ADVCOMBOBOXDEMO_H__D3488651_1658_4B01_957A_7C90F656E8DA__INCLUDED_)
[ [ [ 1, 75 ] ] ]
06f743000a30af8fc7d14dd234226c81fed90140
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Core/Source/RemoteEvents.cpp
63a08020306b3e0722d662f5b18a970008684de7
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
1,621
cpp
#include "corepch.h" #include "RemoteEvents.h" KMAP<KSTR, const EventTemplate*> g_kEventMap; ////////////////////////////////////////////////////////////////////////// EventTemplate ev_lvl_init ("ev_lvl_init"); EventTemplate ev_lvl_update ("ev_lvl_update"); EventTemplate ev_lvl_timer ("ev_lvl_timer"); EventTemplate ev_lvl_destroy ("ev_lvl_destroy"); ////////////////////////////////////////////////////////////////////////// EventTemplate ev_post_spawn ("ev_post_spawn"); EventTemplate ev_post_attack ("ev_post_attack"); EventTemplate ev_post_damage ("ev_post_damage"); EventTemplate ev_post_picked ("ev_post_picked"); EventTemplate ev_post_pick_terrain ("ev_post_pick_terrain"); EventTemplate ev_post_touchdown ("ev_post_touchdown"); EventTemplate ev_post_throw_item ("ev_post_throw_item"); EventTemplate ev_post_reborn ("ev_post_reborn"); EventTemplate ev_post_killed ("ev_post_killed"); EventTemplate ev_post_destroy ("ev_post_destroy"); ////////////////////////////////////////////////////////////////////////// EventTemplate ev_sync_translate ("ev_sync_translate"); EventTemplate ev_sync_gametime ("ev_sync_gametime"); ////////////////////////////////////////////////////////////////////////// EventTemplate ev_do_spawn ("ev_do_spawn"); EventTemplate ev_on_timer ("ev_on_timer"); EventTemplate ev_do_quit ("ev_do_quit"); EventTemplate ev_sync_gameresult ("ev_sync_gameresult"); EventTemplate ev_restore_hp ("ev_restore_hp"); EventTemplate ev_learn_skill ("ev_learn_skill"); EventTemplate ev_do_teleport ("ev_do_teleport");
[ "[email protected]", "apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f" ]
[ [ [ 1, 16 ], [ 18, 27 ], [ 32, 32 ], [ 34, 36 ] ], [ [ 17, 17 ], [ 28, 31 ], [ 33, 33 ] ] ]
db23a2aec90a9a3bc4be68a8ae9ba2d27c16ca99
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/mangalore/msg/updatetransform.cc
fb9b43d18fe72c21362ec6e6324e54cd906cc421
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
439
cc
//------------------------------------------------------------------------------ // msg/updatetransform.cc // (C) 2006 Radon Labs GmbH //------------------------------------------------------------------------------ #include "msg/updatetransform.h" namespace Message { ImplementRtti(Message::UpdateTransform, Message::Msg); ImplementFactory(Message::UpdateTransform); ImplementMsgId(UpdateTransform); } // namespace Message
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 12 ] ] ]
058af90d99402bd6cf631c7e4f8b81142cf79af8
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/multiplayer/ricochet/cl_dll/hl/hl_baseentity.cpp
9ca1e69e2416abae71b9b957b93463a5d124cc5f
[]
no_license
joropito/amxxgroup
637ee71e250ffd6a7e628f77893caef4c4b1af0a
f948042ee63ebac6ad0332f8a77393322157fa8f
refs/heads/master
2021-01-10T09:21:31.449489
2010-04-11T21:34:27
2010-04-11T21:34:27
47,087,485
1
0
null
null
null
null
UTF-8
C++
false
false
14,529
cpp
/*** * * Copyright (c) 1999, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ /* ========================== This file contains "stubs" of class member implementations so that we can predict certain weapons client side. From time to time you might find that you need to implement part of the these functions. If so, cut it from here, paste it in hl_weapons.cpp or somewhere else and add in the functionality you need. ========================== */ #include "extdll.h" #include "util.h" #include "cbase.h" #include "player.h" #include "weapons.h" #include "nodes.h" // Globals used by game logic const Vector g_vecZero = Vector( 0, 0, 0 ); int gmsgWeapPickup = 0; enginefuncs_t g_engfuncs; globalvars_t *gpGlobals; ItemInfo CBasePlayerItem::ItemInfoArray[MAX_WEAPONS]; void EMIT_SOUND_DYN(edict_t *entity, int channel, const char *sample, float volume, float attenuation, int flags, int pitch) { } // CBaseEntity Stubs int CBaseEntity :: TakeHealth( float flHealth, int bitsDamageType ) { return 1; } int CBaseEntity :: TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ) { return 1; } CBaseEntity *CBaseEntity::GetNextTarget( void ) { return NULL; } int CBaseEntity::Save( CSave &save ) { return 1; } int CBaseEntity::Restore( CRestore &restore ) { return 1; } void CBaseEntity::SetObjectCollisionBox( void ) { } int CBaseEntity :: Intersects( CBaseEntity *pOther ) { return 0; } void CBaseEntity :: MakeDormant( void ) { } int CBaseEntity :: IsDormant( void ) { return 0; } BOOL CBaseEntity :: IsInWorld( void ) { return TRUE; } int CBaseEntity::ShouldToggle( USE_TYPE useType, BOOL currentState ) { return 0; } int CBaseEntity :: DamageDecal( int bitsDamageType ) { return -1; } CBaseEntity * CBaseEntity::Create( char *szName, const Vector &vecOrigin, const Vector &vecAngles, edict_t *pentOwner ) { return NULL; } void CBaseEntity::SUB_Remove( void ) { } // CBaseDelay Stubs void CBaseDelay :: KeyValue( struct KeyValueData_s * ) { } int CBaseDelay::Restore( class CRestore & ) { return 1; } int CBaseDelay::Save( class CSave & ) { return 1; } // CBaseAnimating Stubs int CBaseAnimating::Restore( class CRestore & ) { return 1; } int CBaseAnimating::Save( class CSave & ) { return 1; } // DEBUG Stubs edict_t *DBG_EntOfVars( const entvars_t *pev ) { return NULL; } void DBG_AssertFunction(BOOL fExpr, const char* szExpr, const char* szFile, int szLine, const char* szMessage) { } // UTIL_* Stubs void UTIL_PrecacheOther( const char *szClassname ) { } void UTIL_BloodDrips( const Vector &origin, const Vector &direction, int color, int amount ) { } void UTIL_DecalTrace( TraceResult *pTrace, int decalNumber ) { } void UTIL_GunshotDecalTrace( TraceResult *pTrace, int decalNumber ) { } BOOL UTIL_IsValidEntity( edict_t *pent ) { return TRUE; } void UTIL_SetOrigin( entvars_t *, const Vector &org ) { } BOOL UTIL_GetNextBestWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pCurrentWeapon ) { return TRUE; } void UTIL_LogPrintf(char *,...) { } void UTIL_ClientPrintAll( int,char const *,char const *,char const *,char const *,char const *) { } void ClientPrint( entvars_t *client, int msg_dest, const char *msg_name, const char *param1, const char *param2, const char *param3, const char *param4 ) { } // CBaseToggle Stubs int CBaseToggle::Restore( class CRestore & ) { return 1; } int CBaseToggle::Save( class CSave & ) { return 1; } void CBaseToggle :: KeyValue( struct KeyValueData_s * ) { } // CGrenade Stubs void CGrenade::BounceSound( void ) { } void CGrenade::Explode( Vector, Vector ) { } void CGrenade::Explode( TraceResult *, int ) { } void CGrenade::Killed( entvars_t *, int ) { } void CGrenade::Spawn( void ) { } CBaseEntity* CBaseMonster :: CheckTraceHullAttack( float flDist, int iDamage, int iDmgType ) { return NULL; } void CBaseMonster :: Look ( int iDistance ) { } float CBaseAnimating :: StudioFrameAdvance ( float flInterval ) { return 0.0; } int CBaseMonster::IRelationship ( CBaseEntity *pTarget ) { return 0; } CBaseEntity *CBaseMonster :: BestVisibleEnemy ( void ) { return NULL; } BOOL CBaseMonster :: FInViewCone ( CBaseEntity *pEntity ) { return FALSE; } BOOL CBaseMonster :: FInViewCone ( Vector *pOrigin ) { return FALSE; } BOOL CBaseEntity :: FVisible ( CBaseEntity *pEntity ) { return FALSE; } BOOL CBaseEntity :: FVisible ( const Vector &vecOrigin ) { return FALSE; } void CBaseMonster :: MakeIdealYaw( Vector vecTarget ) { } float CBaseMonster::ChangeYaw ( int yawSpeed ) { return 0; } int CBaseAnimating :: LookupActivity ( int activity ) { return 0; } int CBaseAnimating :: LookupActivityHeaviest ( int activity ) { return 0; } BOOL CBaseAnimating :: GetSequenceFlags( ) { return FALSE; } void CBaseAnimating :: DispatchAnimEvents ( float flInterval ) { } float CBaseAnimating :: SetBoneController ( int iController, float flValue ) { return 0.0; } void CBaseAnimating :: InitBoneControllers ( void ) { } float CBaseAnimating :: SetBlending ( int iBlender, float flValue ) { return 0; } void CBaseAnimating :: GetBonePosition ( int iBone, Vector &origin, Vector &angles ) { } void CBaseAnimating :: GetAttachment ( int iAttachment, Vector &origin, Vector &angles ) { } int CBaseAnimating :: FindTransition( int iEndingSequence, int iGoalSequence, int *piDir ) { return -1; } void CBaseAnimating :: GetAutomovement( Vector &origin, Vector &angles, float flInterval ) { } void CBaseAnimating :: SetBodygroup( int iGroup, int iValue ) { } int CBaseAnimating :: GetBodygroup( int iGroup ) { return 0; } void CBaseEntity::TraceAttack(entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType) { } void CBaseEntity::FireBullets(ULONG cShots, Vector vecSrc, Vector vecDirShooting, Vector vecSpread, float flDistance, int iBulletType, int iTracerFreq, int iDamage, entvars_t *pevAttacker ) { } void CBaseEntity :: TraceBleed( float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType ) { } void CBaseMonster :: MakeDamageBloodDecal ( int cCount, float flNoise, TraceResult *ptr, const Vector &vecDir ) { } void CBaseMonster::ReportAIState( void ) { } void CBaseMonster :: KeyValue( KeyValueData *pkvd ) { } BOOL CBaseMonster :: FCheckAITrigger ( void ) { return FALSE; } void CBaseMonster::CorpseFallThink( void ) { } void CBaseMonster :: MonsterInitDead( void ) { } void CBaseMonster :: TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType) { } BOOL CBaseMonster :: ShouldFadeOnDeath( void ) { return FALSE; } void CBaseMonster :: RadiusDamage(entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int iClassIgnore, int bitsDamageType ) { } void CBaseMonster :: RadiusDamage( Vector vecSrc, entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int iClassIgnore, int bitsDamageType ) { } void CBaseMonster::FadeMonster( void ) { } void CBaseMonster :: GibMonster( void ) { } BOOL CBaseMonster :: HasHumanGibs( void ) { return FALSE; } BOOL CBaseMonster :: HasAlienGibs( void ) { return FALSE; } Activity CBaseMonster :: GetDeathActivity ( void ) { return (Activity)0; } void CBaseMonster::BecomeDead( void ) {} void CBaseMonster :: Killed( entvars_t *pevAttacker, int iGib ) {} int CBaseMonster :: TakeHealth (float flHealth, int bitsDamageType) { return 0; } int CBaseMonster :: TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType ) { return 0; } int TrainSpeed(int iSpeed, int iMax) { return 0; } void CBasePlayer :: DeathSound( void ) { } int CBasePlayer :: TakeHealth( float flHealth, int bitsDamageType ) { return 0; } void CBasePlayer :: TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType) { } int CBasePlayer :: TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType ) { return 0; } void CBasePlayer::RemoveAllItems( BOOL removeSuit ) { } void CBasePlayer::WaterMove() { } BOOL CBasePlayer::IsOnLadder( void ) { return FALSE; } void CBasePlayer::PlayerDeathThink(void) { } void CBasePlayer::StartDeathCam( void ) { } void CBasePlayer::StartObserver( Vector vecPosition, Vector vecViewAngle ) { } void CBasePlayer::PlayerUse ( void ) { } void CBasePlayer::Jump() { } void CBasePlayer::Duck( ) { } int CBasePlayer::Classify ( void ) { return 0; } void CBasePlayer :: PlayStepSound(int step, float fvol) { } void CBasePlayer :: UpdateStepSound( void ) { } void CBasePlayer::PreThink(void) { } void CBasePlayer::CheckTimeBasedDamage() { } void CBasePlayer :: UpdateGeigerCounter( void ) { } void CBasePlayer::CheckSuitUpdate() { } void CBasePlayer::SetSuitUpdate(char *name, int fgroup, int iNoRepeatTime) { } void CBasePlayer :: UpdatePlayerSound ( void ) { } void CBasePlayer :: Precache( void ) { } int CBasePlayer::Save( CSave &save ) { return 0; } void CBasePlayer::RenewItems(void) { } int CBasePlayer::Restore( CRestore &restore ) { return 0; } void CBasePlayer::SelectNextItem( int iItem ) { } BOOL CBasePlayer::HasWeapons( void ) { return FALSE; } void CBasePlayer::SelectPrevItem( int iItem ) { } CBaseEntity *FindEntityForward( CBaseEntity *pMe ) { return NULL; } BOOL CBasePlayer :: FlashlightIsOn( void ) { return FALSE; } void CBasePlayer :: FlashlightTurnOn( void ) { } void CBasePlayer :: FlashlightTurnOff( void ) { } void CBasePlayer :: ForceClientDllUpdate( void ) { } void CBasePlayer::ImpulseCommands( ) { } void CBasePlayer::CheatImpulseCommands( int iImpulse ) { } int CBasePlayer::AddPlayerItem( CBasePlayerItem *pItem ) { return FALSE; } int CBasePlayer::RemovePlayerItem( CBasePlayerItem *pItem ) { return FALSE; } void CBasePlayer::ItemPreFrame() { } void CBasePlayer::ItemPostFrame() { } int CBasePlayer::AmmoInventory( int iAmmoIndex ) { return -1; } int CBasePlayer::GetAmmoIndex(const char *psz) { return -1; } void CBasePlayer::SendAmmoUpdate(void) { } void CBasePlayer :: UpdateClientData( void ) { } BOOL CBasePlayer :: FBecomeProne ( void ) { return TRUE; } void CBasePlayer :: BarnacleVictimBitten ( entvars_t *pevBarnacle ) { } void CBasePlayer :: BarnacleVictimReleased ( void ) { } int CBasePlayer :: Illumination( void ) { return 0; } void CBasePlayer :: EnableControl(BOOL fControl) { } Vector CBasePlayer :: GetAutoaimVector( float flDelta ) { return g_vecZero; } Vector CBasePlayer :: AutoaimDeflection( Vector &vecSrc, float flDist, float flDelta ) { return g_vecZero; } void CBasePlayer :: ResetAutoaim( ) { } void CBasePlayer :: SetCustomDecalFrames( int nFrames ) { } int CBasePlayer :: GetCustomDecalFrames( void ) { return -1; } void CBasePlayer::DropPlayerItem ( char *pszItemName ) { } BOOL CBasePlayer::HasPlayerItem( CBasePlayerItem *pCheckItem ) { return FALSE; } BOOL CBasePlayer :: SwitchWeapon( CBasePlayerItem *pWeapon ) { return FALSE; } Vector CBasePlayer :: GetGunPosition( void ) { return g_vecZero; } const char *CBasePlayer::TeamID( void ) { return ""; } int CBasePlayer :: GiveAmmo( int iCount, char *szName, int iMax ) { return 0; } void CBasePlayer::AddPoints( int score, BOOL bAllowNegativeScore ) { } void CBasePlayer::AddPointsToTeam( int score, BOOL bAllowNegativeScore ) { } void CBasePlayer::RemoveAllPowerups( void ) {} bool CBasePlayer::HasPowerup(int) { return 0; } void ClearMultiDamage(void) { } void ApplyMultiDamage(entvars_t *pevInflictor, entvars_t *pevAttacker ) { } void AddMultiDamage( entvars_t *pevInflictor, CBaseEntity *pEntity, float flDamage, int bitsDamageType) { } void SpawnBlood(Vector vecSpot, int bloodColor, float flDamage) { } int DamageDecal( CBaseEntity *pEntity, int bitsDamageType ) { return 0; } void DecalGunshot( TraceResult *pTrace, int iBulletType ) { } void EjectBrass ( const Vector &vecOrigin, const Vector &vecVelocity, float rotation, int model, int soundtype ) { } void AddAmmoNameToAmmoRegistry( const char *szAmmoname ) { } int CBasePlayerItem::Restore( class CRestore & ) { return 1; } int CBasePlayerItem::Save( class CSave & ) { return 1; } int CBasePlayerWeapon::Restore( class CRestore & ) { return 1; } int CBasePlayerWeapon::Save( class CSave & ) { return 1; } void CBasePlayerItem :: SetObjectCollisionBox( void ) { } void CBasePlayerItem :: FallInit( void ) { } void CBasePlayerItem::FallThink ( void ) { } void CBasePlayerItem::Materialize( void ) { } void CBasePlayerItem::AttemptToMaterialize( void ) { } void CBasePlayerItem :: CheckRespawn ( void ) { } CBaseEntity* CBasePlayerItem::Respawn( void ) { return NULL; } void CBasePlayerItem::DefaultTouch( CBaseEntity *pOther ) { } void CBasePlayerItem::DestroyItem( void ) { } int CBasePlayerItem::AddToPlayer( CBasePlayer *pPlayer ) { return TRUE; } void CBasePlayerItem::Drop( void ) { } void CBasePlayerItem::Kill( void ) { } void CBasePlayerItem::Holster( int skiplocal ) { } void CBasePlayerItem::AttachToPlayer ( CBasePlayer *pPlayer ) { } int CBasePlayerWeapon::AddDuplicate( CBasePlayerItem *pOriginal ) { return 0; } int CBasePlayerWeapon::AddToPlayer( CBasePlayer *pPlayer ) { return FALSE; } int CBasePlayerWeapon::UpdateClientData( CBasePlayer *pPlayer ) { return 0; } BOOL CBasePlayerWeapon :: AddPrimaryAmmo( int iCount, char *szName, int iMaxClip, int iMaxCarry ) { return TRUE; } BOOL CBasePlayerWeapon :: AddSecondaryAmmo( int iCount, char *szName, int iMax ) { return TRUE; } BOOL CBasePlayerWeapon :: IsUseable( void ) { return TRUE; } int CBasePlayerWeapon::PrimaryAmmoIndex( void ) { return -1; } int CBasePlayerWeapon::SecondaryAmmoIndex( void ) { return -1; } void CBasePlayerAmmo::Spawn( void ) { } CBaseEntity* CBasePlayerAmmo::Respawn( void ) { return this; } void CBasePlayerAmmo::Materialize( void ) { } void CBasePlayerAmmo :: DefaultTouch( CBaseEntity *pOther ) { } int CBasePlayerWeapon::ExtractAmmo( CBasePlayerWeapon *pWeapon ) { return 0; } int CBasePlayerWeapon::ExtractClipAmmo( CBasePlayerWeapon *pWeapon ) { return 0; } void CBasePlayerWeapon::RetireWeapon( void ) { }
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 248 ] ] ]
4afc6dfa5b0998686511891a8b1efc0f48455ec8
2821bd16a5e375893ee2733b9d6a5565edc46685
/IEView.cpp
67e064c4e1b1a7911ba542b61764233a1d9bda70
[]
no_license
zephyrer/activelog
24eab2107dd11f3c1ecb7b8e78e87fb0a6dcb3b2
febf3a1080959c28215d84f0c2f92aff032f4240
refs/heads/master
2021-01-13T02:27:24.587560
2009-07-20T02:47:48
2009-07-20T02:47:48
40,067,861
0
0
null
null
null
null
UTF-8
C++
false
false
12,079
cpp
/******************************************************************* ActiveLog is a utility developed by VATech Systems Copyright (C) 2006 - 2009 VATech Systems. 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/>. You can contact VATech Systems at email address [email protected]. ***********************************************************************/ #include "stdafx.h" #include "VAALOG.h" #include "ALDoc.h" #include "IEView.h" #include "LeftView.h" #include "cxmldoc.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CIEView IMPLEMENT_DYNCREATE(CIEView, CHtmlView) BEGIN_MESSAGE_MAP(CIEView, CHtmlView) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, &CHtmlView::OnFilePrint) ON_COMMAND(ID_EDIT_FIND, &CIEView::OnEditFind) END_MESSAGE_MAP() static const GUID CGID_IWebBrowser = { 0xED016940L, 0xBD5B, 0x11cf, { 0xBA, 0x4E, 0x00, 0xC0, 0x4F, 0xD7, 0x08, 0x16 } }; //DEFINE_GUID(CGID_IWebBrowser,0xED016940L, // 0xBD5B,0x11cf,0xBA, 0x4E,0x00, // 0xC0,0x4F,0xD7,0x08,0x16); // CIEView construction/destruction CIEView::CIEView():m_pXmlDoc(NULL) { // TODO: add construction code here m_pListView = NULL; CxmlDoc* pXmlDoc = NULL; CxmlDoc::Create(&pXmlDoc); m_pXmlDoc = pXmlDoc; } CIEView::~CIEView() { if(m_pXmlDoc) { m_pXmlDoc->Close(); m_pXmlDoc = NULL; } } BOOL CIEView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CHtmlView::PreCreateWindow(cs); } void CIEView::OnInitialUpdate() { CHtmlView::OnInitialUpdate(); Navigate2(_T("about:blank"),NULL,NULL); } // CIEView printing // CIEView diagnostics #ifdef _DEBUG void CIEView::AssertValid() const { CHtmlView::AssertValid(); } void CIEView::Dump(CDumpContext& dc) const { CHtmlView::Dump(dc); } CALDoc* CIEView::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CALDoc))); return (CALDoc*)m_pDocument; } #endif //_DEBUG // CIEView message handlers void CIEView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { if(pSender) { if(pSender->IsKindOf( RUNTIME_CLASS( CLeftView ))) { CALDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if(!pDoc->m_listItems.IsEmpty()) { // TODO Async open if (GetBusy()) // See if it's busy with something else Stop(); // .. and make sure it's not // get item index DWORD nIndex = (DWORD) lHint; POSITION pos = pDoc->m_listItems.FindIndex(nIndex); PITEMDATA pData = NULL; if( pos != NULL){ pData = pDoc->m_listItems.GetAt(pos); } ShowItem(pData); } } } } bool CIEView::SaveFile(CString strFileName, CString strData) { // ADD UNICODE BYTES CFile myFile; CFileException fileException; if ( !myFile.Open( strFileName, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite , &fileException ) ) { TRACE( "Can't open file %s, error = %u\n", strFileName, fileException.m_cause ); // if(fileException.m_cause == CFileException::sharingViolation) // TCHAR szLastError[1024]; // sprintf_s(szLastError, "Can't open file %s, error = %u\n", pDoc->m_strTempFileName, fileException.m_cause); // OutputDebugString(szLastError ); return false; } else { #if defined UNICODE // if parser is not available // other than UTF-16 encoding will fail to show const WCHAR UNICODE_BOM = 0xFEFF; myFile.Write( &UNICODE_BOM, sizeof( UNICODE_BOM )); myFile.Write(strData, strData.GetLength() * sizeof(TCHAR)); myFile.Close(); #else myFile.Write(strData, strData.GetLength()); myFile.Close(); #endif } return true; } HRESULT CIEView::NavigateText(CString strText) { // The Document Object Model isn't fully initialized until // the browser has finished navigating to a first URL. A quick // and handy one is "about:blank" - this has to be done before // executing this method HRESULT hr = S_OK; TRACE("NavigateText before GetHtmlDocument \n"); // Get a pointer to our document // TODO - Check if this is safe to use // Get a pointer to the HTML Document Object Model's interface IDispatch * pDisp = GetHtmlDocument(); if (!pDisp) return E_FAIL; TRACE("NavigateText before QueryInterface IID_IHTMLDocument2\n"); IHTMLDocument2* document = NULL; if (SUCCEEDED(pDisp->QueryInterface( IID_IHTMLDocument2, (void**)&document ))) { //if (SUCCEEDED(document->open(CComBSTR("text/html"), // CComVariant(CComBSTR("_self")), // CComVariant(CComBSTR("")), // CComVariant((bool)1), // NULL))) // <- if used busy cursor will be shown // IHTMLDocument2::open Method // Empty URL and parameters opens the current document CComBSTR bstrURL; CComVariant varDummy; TRACE("document->opening...\n"); if (SUCCEEDED(hr = document->open(bstrURL, varDummy, varDummy, varDummy, NULL))) { TRACE("document->open succeeded\n"); // Following sample from IHTMLDocument2::write Method VARIANT *pVal; SAFEARRAY *sfArray; //BSTR bstr = SysAllocString(OLESTR("Written by IHTMLDocument2::write().")); // Creates a new one-dimensional array sfArray = SafeArrayCreateVector(VT_VARIANT, 0, 1); if (sfArray != NULL && document != NULL) { hr = SafeArrayAccessData(sfArray,(LPVOID*) & pVal); pVal->vt = VT_BSTR; pVal->bstrVal = strText.AllocSysString(); hr = SafeArrayUnaccessData(sfArray); hr = document->write(sfArray); // Overwrite HTML if(FAILED(hr)) dprintf( "document->open fail 0x%.8x\n", hr ); } //SysFreeString(bstr); if (sfArray != NULL) { SafeArrayDestroy(sfArray); } } else{ TRACE("document->open fail\n"); dprintf( "document->open fail 0x%.8x\n", hr ); } document->close(); // close, Update browser document->Release(); // Don't forget to release the reference } return hr; } HRESULT CIEView::NavigateText2(CString strText) { ENSURE(m_pBrowserApp != NULL); HRESULT hr = E_FAIL; CComPtr<IDispatch> spDispDocument; m_pBrowserApp->get_Document(&spDispDocument); CComQIPtr<IHTMLDocument2> spDoc = spDispDocument; if (spDoc != NULL) { // open doc and write LPDISPATCH lpdRet; if (SUCCEEDED(hr = spDoc->open(CComBSTR("text/html"), CComVariant(CComBSTR("_self")), CComVariant(CComBSTR("")), CComVariant((bool)1), &lpdRet))) { COleSafeArray vPostData; vPostData.CreateOneDim(VT_UI1, strText.GetLength() * sizeof(TCHAR), strText.GetBuffer()); hr = spDoc->write(COleVariant(vPostData).parray); // write contents to doc hr = spDoc->close(); // close } } return hr; } HRESULT CIEView::LoadContent(CString strText) { ENSURE(m_pBrowserApp != NULL); HRESULT hr = E_FAIL; CComPtr<IDispatch> spDispDocument; m_pBrowserApp->get_Document(&spDispDocument); CComQIPtr<IHTMLDocument2> spDoc = spDispDocument; if (spDoc != NULL) { CComQIPtr<IPersistStreamInit> spPSI = spDoc; if (spPSI) { ULONG ulWritten; LARGE_INTEGER li = {0, 0}; // // TODO - Check if additionally is required // to allocate memory for CreateStreamOnHGlobal // CComPtr<IStream> spStream; CHECKHR(CreateStreamOnHGlobal(NULL, TRUE, &spStream)); // // TODO - Check if verification for ulWritten is required // CHECKHR(spStream->Write(strText.GetBuffer(), strText.GetLength() * sizeof(TCHAR), &ulWritten)); // Reset the stream back to the beginning CHECKHR(spStream->Seek(li, STREAM_SEEK_SET, NULL)); CHECKHR(spPSI->Load(spStream)); } } CleanUp: return hr; } void CIEView::OnEditFind() { //1 : FIND, 2: VIEWSOURCE, 3 : OPTIONS DWORD nCmdID = 1; // Same as CHtmlView::OnFilePrint if (m_pBrowserApp != NULL) { CComPtr<IDispatch> spDisp; m_pBrowserApp->get_Document(&spDisp); if (spDisp != NULL) { // the control will handle all printing UI CComQIPtr<IOleCommandTarget> spTarget = spDisp; if (spTarget != NULL) spTarget->Exec(&CGID_IWebBrowser, nCmdID, 0, NULL, NULL); } } } /* HRESULT CIEView::NavigateText(CString strText) { // Get a pointer to the HTML Document Object Model's interface IDispatch * pDisp = GetHtmlDocument(); if (!pDisp) return E_FAIL; IHTMLDocument2* document; if (SUCCEEDED(pDisp->QueryInterface( IID_IHTMLDocument2, (void**)&document ))) { // Empty URL and parameters opens the current document CComBSTR bstrURL; CComVariant varDummy; document->open(bstrURL, varDummy, varDummy, varDummy, NULL); // Create a safearray to store the HTML text SAFEARRAY *pSA; SAFEARRAYBOUND saBound = {1, 0}; pSA = SafeArrayCreate(VT_VARIANT, 1, &saBound); if (pSA != NULL ) { // Copy the HTML into the one and only element VARIANT *pVar; CComBSTR bstrHTML = strText; // Load the text varDummy = bstrHTML; // .. into a variant ( reuse old one ) SafeArrayAccessData(pSA, (void**)&pVar); // Access safearray data pVar[0] = varDummy; // Set the text data SafeArrayUnaccessData(pSA); // Release access // Write the HTML as the document's new text document->write(pSA); // Overwrite HTML } document->close(); // Update browser SafeArrayDestroy(pSA); // Finished with the safearray pDoc->Release(); // Don't forget to release the reference } return S_OK; } */ int CIEView::ShowItem(PITEMDATA pData) { if(pData) { CALDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if ( m_pXmlDoc ) { if(m_pXmlDoc->LoadXML(pData->sData)) { if(!m_pXmlDoc->SaveXML(pDoc->m_strTempFileName)) { // possible sharingViolation error pDoc->GetNewTempFileName(); m_pXmlDoc->SaveXML(pDoc->m_strTempFileName); } Navigate2(pDoc->m_strTempFileName, navNoHistory, // Do not add the resource or file to the history list. // The new page replaces the current page in the list. NULL); } else { //NavigateText(pData->sData); LoadContent(pData->sData); } } else { if( !SaveFile(pDoc->m_strTempFileName, pData->sData) ) { // possible sharingViolation error pDoc->GetNewTempFileName(); if( !SaveFile(pDoc->m_strTempFileName, pData->sData) ) return -1; // OutputDebugString("New temporary file\n"); } Navigate2(pDoc->m_strTempFileName, navNoHistory, // Do not add the resource or file to the history list. // The new page replaces the current page in the list. NULL); } } else { // This call is required too much time for execution //Navigate2(_T("about:blank"), // navNoHistory, // Do not add the resource or file to the history list. // // The new page replaces the current page in the list. // NULL); //NavigateText(_T("")); LoadContent(_T("")); } return 0; }
[ "vatechsystems@85faade2-74d6-11de-ba67-499d525147dd" ]
[ [ [ 1, 443 ] ] ]
dc0a644d207c25161fe157321d5726b2716b29d7
021e8c48a44a56571c07dd9830d8bf86d68507cb
/build/vtk/vtkExtractSelectedSlices.h
6b9e770089b0092ebd25e04c6019156940652324
[ "BSD-3-Clause" ]
permissive
Electrofire/QdevelopVset
c67ae1b30b0115d5c2045e3ca82199394081b733
f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5
refs/heads/master
2021-01-18T10:44:01.451029
2011-05-01T23:52:15
2011-05-01T23:52:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,637
h
/*========================================================================= Program: Visualization Toolkit Module: vtkExtractSelectedSlices.h ------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. ------------------------------------------------------------------------- Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef __vtkExtractSelectedSlices_h #define __vtkExtractSelectedSlices_h #include <vtkArrayDataAlgorithm.h> // .NAME vtkExtractSelectedSlices - Extract selected slices from a vtkArray // // Inputs: // Input port 0: (required) A vtkSparseArray<double> of any dimension. // Input port 1: (required) A vtkSelection containing indices. // // Outputs: // Output port 0: A vtkSparseArray<double> containing only the selected slices. // // Note that the indices in the input selection must be less-than the maximum // extent of the input array along the slice dimension. // // .SECTION Caveats // Only works with vtkSparseArray<double>, this needs to be generalized. // // .SECTION Thanks // Developed by Timothy M. Shead ([email protected]) at Sandia National Laboratories. class VTK_TEXT_ANALYSIS_EXPORT vtkExtractSelectedSlices : public vtkArrayDataAlgorithm { public: static vtkExtractSelectedSlices* New(); vtkTypeMacro(vtkExtractSelectedSlices, vtkArrayDataAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Controls the dimension along which slices will be extracted. Default: 0 vtkGetMacro(SliceDimension, int); vtkSetMacro(SliceDimension, int); //BTX protected: vtkExtractSelectedSlices(); ~vtkExtractSelectedSlices(); int FillInputPortInformation(int, vtkInformation*); int RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector*); private: vtkExtractSelectedSlices(const vtkExtractSelectedSlices&); // Not implemented void operator=(const vtkExtractSelectedSlices&); // Not implemented int SliceDimension; //ETX }; #endif
[ "ganondorf@ganondorf-VirtualBox.(none)" ]
[ [ [ 1, 79 ] ] ]
eb6b6b198409592ea1070fa43a8d4a26b43633d8
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/GameSDK/GameUILib/Include/XUI_IME.h
55e4509d8d7897e15df529296e3c6670691e88a4
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
GB18030
C++
false
false
4,158
h
#pragma once #ifndef _XUI_IME_H #define _XUI_IME_H #include <Windows.h> #include <ObjBase.h> #include <Dimm.h> #include "XUI_Header.h" #define MAX_CANDLIST 10 #define MAX_COMPSTRING_SIZE 256 #define GETLANG() LOWORD(XUI_IME::m_hklCurrent) #define GETPRIMLANG() ((WORD)PRIMARYLANGID(GETLANG())) #define GETSUBLANG() SUBLANGID(GETLANG()) #define LANG_CHS MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED) #define LANG_CHT MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL) #define IMEUI_STATE_OFF 0 #define IMEUI_STATE_ON 1 #define IMEUI_STATE_ENGLISH 2 #define INDICATOR_NON_IME 0 #define INDICATOR_CHS 1 #define INDICATOR_CHT 2 #define INDICATOR_KOREAN 3 #define INDICATOR_JAPANESE 4 #define INDICATOR_ENGLISH 5 namespace XGC { namespace ui { class XUI_IME { public: XUI_IME(void); ~XUI_IME(void); static bool Initialize(); static void RenderImeWindow(); static void CheckInputLocale(); static void OnInputLangChange(); static void CheckToggleState(); static void ResetCompositionString(); static HINSTANCE m_hDllImm32; // IMM32 DLL handle static HINSTANCE m_hDllIme; // IME DLL handle static HINSTANCE m_hDllVer; // Version DLL handle static HIMC m_hImcDef; // Default input context static HKL m_hklCurrent; // Current keyboard layout of the process static iRect m_rcWindow; struct CCandList { CCandList(); std::list< std::wstring > l; std::string strBuffer; _int32 nCaretPos; _int32 nFirstSelected; // First character position of the selected string in HoriCand _int32 nHoriSelectedLen; // Length of the selected string in HoriCand _uint32 dwCount; // Number of valid entries in the candidate list _uint32 dwSelection; // Currently selected candidate entry relative to page top _uint32 dwPageSize; _int32 nReadingError; // Index of the error character bool bShowWindow; // Whether the candidate list window is visible iRect rcCandidate; // Candidate rectangle computed and filled each time before rendered }; static CCandList m_CandList; // 输入法绘制结构。 static wchar_t m_CompString[MAX_COMPSTRING_SIZE]; static wchar_t m_CompStringAttr[MAX_COMPSTRING_SIZE]; static INPUTCONTEXT* (WINAPI * _ImmLockIMC)( HIMC ); static BOOL (WINAPI * _ImmUnlockIMC)( HIMC ); static LPVOID (WINAPI * _ImmLockIMCC)( HIMCC ); static BOOL (WINAPI * _ImmUnlockIMCC)( HIMCC ); static BOOL (WINAPI * _ImmDisableTextFrameService)( DWORD ); static LONG (WINAPI * _ImmGetCompositionStringW)( HIMC, DWORD, LPVOID, DWORD ); static DWORD (WINAPI * _ImmGetCandidateListW)( HIMC, DWORD, LPCANDIDATELIST, DWORD ); static HIMC (WINAPI * _ImmGetContext)( HWND ); static BOOL (WINAPI * _ImmReleaseContext)( HWND, HIMC ); static HIMC (WINAPI * _ImmAssociateContext)( HWND, HIMC ); static BOOL (WINAPI * _ImmGetOpenStatus)( HIMC ); static BOOL (WINAPI * _ImmSetOpenStatus)( HIMC, BOOL ); static BOOL (WINAPI * _ImmGetConversionStatus)( HIMC, LPDWORD, LPDWORD ); static HWND (WINAPI * _ImmGetDefaultIMEWnd)( HWND ); static UINT (WINAPI * _ImmGetDescriptionW)( HKL, LPWSTR, UINT ); static UINT (WINAPI * _ImmGetIMEFileNameA)( HKL, LPSTR, UINT ); static UINT (WINAPI * _ImmGetVirtualKey)( HWND ); static BOOL (WINAPI * _ImmNotifyIME)( HIMC, DWORD, DWORD, DWORD ); static BOOL (WINAPI * _ImmSetConversionStatus)( HIMC, DWORD, DWORD ); static BOOL (WINAPI * _ImmSimulateHotKey)( HWND, DWORD ); static BOOL (WINAPI * _ImmIsIME)( HKL ); // Function pointers: Traditional Chinese IME static UINT (WINAPI * _GetReadingString)( HIMC, UINT, LPWSTR, PINT, BOOL*, PUINT ); static BOOL (WINAPI * _ShowReadingWindow)( HIMC, BOOL ); // Function pointers: Verion library imports static BOOL (APIENTRY * _VerQueryValueA)( const LPVOID, LPSTR, LPVOID *, PUINT ); static BOOL (APIENTRY * _GetFileVersionInfoA)( LPSTR, DWORD, DWORD, LPVOID ); static DWORD (APIENTRY * _GetFileVersionInfoSizeA)( LPSTR, LPDWORD ); }; } }; #endif
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 109 ] ] ]
c19eadfafc16408841d14ee0e7f858db8dc5e104
bda7b365b5952dc48827a8e8d33d11abd458c5eb
/InGameDownloadManager.h
e082a41f2dbed4faa5175bc4c62ae6d5c7b9f810
[]
no_license
MrColdbird/gameservice
3bc4dc3906d16713050612c1890aa8820d90272e
009d28334bdd8f808914086e8367b1eb9497c56a
refs/heads/master
2021-01-25T09:59:24.143855
2011-01-31T07:12:24
2011-01-31T07:12:24
35,889,912
3
3
null
null
null
null
UTF-8
C++
false
false
5,594
h
// ====================================================================================== // File : InGameDownloadManager.h // Author : Li Chen // Last Change : 01/07/2011 | 14:36:49 PM | Friday,January // Description : // ====================================================================================== #ifndef GAMESERVICE_INGAMEDOWNLOAD_MANAGER_H #define GAMESERVICE_INGAMEDOWNLOAD_MANAGER_H #include <map> namespace GameService { //-------------------------------------------------------------------------------------- // Name: DownloadManager // Desc: Initiates Content Downloads with the user, tracks download status //-------------------------------------------------------------------------------------- class DownloadRequest; class DownloadManager { public: DownloadManager(); ~DownloadManager(); //-------------------------------------------------------------------------------------- // Name: RequestDownload // Desc: Creates a DownloadRequest object to store OfferIDs to be downloaded. // Caller will add OfferIDs to the DownloadRequest object using // DownloadRequest::AddOffer //-------------------------------------------------------------------------------------- DownloadRequest* RequestDownload( GS_DWORD nOffers ); //-------------------------------------------------------------------------------------- // Name: DownloadItems // Desc: Displays the Marketplace blade to the user to allow purchasing/downloading // the list of OfferIDs that were added to the DownloadRequest //-------------------------------------------------------------------------------------- GS_VOID DownloadItems( DownloadRequest *pRequest ); //-------------------------------------------------------------------------------------- // Name: Update // Desc: Check to see if the Marketplace blade is still showing // Refresh the status of all the pending downloads that are being tracked //-------------------------------------------------------------------------------------- GS_VOID Update(); typedef std::map< ULONGLONG, GS_DWORD > PendingDownloadMap; // Enable iterating over the collection of pending downloads GS_DWORD Count() { return m_mPendingDownloads.size(); } PendingDownloadMap::iterator begin() { return m_mPendingDownloads.begin(); } PendingDownloadMap::iterator end() { return m_mPendingDownloads.end(); } private: //-------------------------------------------------------------------------------------- // Track Pending Downloads //-------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------- // Name: AddPendingDownload // Desc: Add another OfferID to the list of pending downloads without duplication //-------------------------------------------------------------------------------------- GS_VOID AddPendingDownload( ULONGLONG qwOfferID ); //-------------------------------------------------------------------------------------- // Name: RefreshPendingDownloads // Desc: Get the latest status for each OfferID in the collection //-------------------------------------------------------------------------------------- GS_VOID RefreshPendingDownloads(); public: //-------------------------------------------------------------------------------------- // Name: RemoveExpiredDownloads // Desc: Clean out all the downloads that have completed or errored out //-------------------------------------------------------------------------------------- GS_VOID RemoveExpiredDownloads(); PendingDownloadMap m_mPendingDownloads; private: // Requesting Offer Downloads DownloadRequest *m_pCurrentRequest; HRESULT m_hrOverlappedResult; XOVERLAPPED m_Overlapped; }; //-------------------------------------------------------------------------------------- // Name: DownloadRequest // Desc: Auxilliary class to encapsulate a list of OfferIDs for content to be downloaded // DownloadRequests are created and managed by the DownloadManager //-------------------------------------------------------------------------------------- class DownloadRequest { public: DownloadRequest( GS_DWORD nSize ); ~DownloadRequest(); //-------------------------------------------------------------------------------------- // Name: AddOffer // Desc: Adds an OfferID to the array of OfferIDs //-------------------------------------------------------------------------------------- GS_BOOL AddOffer( ULONGLONG qwOfferIDtoAdd ); private: GS_DWORD m_dwOfferIDs; // Number of OfferIDs in the request GS_DWORD m_dwSize; // Max number of OfferIDs that will fit in the request ULONGLONG *m_pOfferIDs; // Storage for the OfferIDs public: GS_DWORD GetOfferIDCount() const { return m_dwOfferIDs; } const ULONGLONG* GetOfferIDs() const { return m_pOfferIDs; } ULONGLONG GetOfferID( GS_DWORD dwIndex ) const { assert( dwIndex < m_dwOfferIDs ); return m_pOfferIDs[dwIndex]; } private: // don't want to copy these DownloadRequest( const DownloadRequest &) {} DownloadRequest &operator=( const DownloadRequest &) { return *this; } }; } // namespace #endif // GAMESERVICE_INGAMEDOWNLOAD_MANAGER_H
[ "leavesmaple@383b229b-c81f-2bc2-fa3f-61d2d0c0fe69" ]
[ [ [ 1, 133 ] ] ]
8bb81641c595a83e694b1879d970e128b3516cd6
55196303f36aa20da255031a8f115b6af83e7d11
/private/external/gameswf/base/png_helper.h
7e18d1eebcce55d58393afb2bc5b2ea74d0dd4f5
[]
no_license
Heartbroken/bikini
3f5447647d39587ffe15a7ae5badab3300d2a2ff
fe74f51a3a5d281c671d303632ff38be84d23dd7
refs/heads/master
2021-01-10T19:48:40.851837
2010-05-25T19:58:52
2010-05-25T19:58:52
37,190,932
0
0
null
null
null
null
UTF-8
C++
false
false
784
h
// png_helper.h -- Thatcher Ulrich <[email protected]> 2004 // This source code has been donated to the Public Domain. Do // whatever you want with it. // Wrapper for png file operations. The actual work is done by the // libpng lib. #ifndef PNG_HELPER_H #define PNG_HELPER_H #include "base/tu_config.h" #include <stdio.h> namespace png_helper { void write_grayscale(FILE* out, uint8* data, int width, int height); // Data should be in [RGBA...] byte order. width and height // in pixels (not bytes). void write_rgba(FILE* out, uint8* data, int width, int height); // TODO: add more helpers as needed... } #endif // PNG_HELPER_H // Local Variables: // mode: C++ // c-basic-offset: 8 // tab-width: 8 // indent-tabs-mode: t // End:
[ "viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587" ]
[ [ [ 1, 36 ] ] ]
9506bb864d4457eeecbffe8c20d08c8b195c0ad5
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleMaths/TShapeBox.h
cdde172e36fb7465396a29513d6023db1078060a
[]
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
3,541
h
/*------------------------------------------------------ kind of TShape -------------------------------------------------------*/ #pragma once #include "TBox.h" #include "TShape.h" class TLMaths::TShapeBox : public TLMaths::TShape { public: TShapeBox() {} TShapeBox(const TLMaths::TBox& Box) : m_Shape ( Box ) {} static TRef GetShapeType_Static() { return TLMaths_ShapeRef(TBox); } virtual TRef GetShapeType() const { return TLMaths_ShapeRef(TBox); } virtual Bool IsValid() const { return m_Shape.IsValid(); } virtual void SetInvalid() { return m_Shape.SetInvalid(); } virtual float3 GetCenter() const { return m_Shape.GetCenter(); } virtual void Transform(const TLMaths::TTransform& Transform) { m_Shape.Transform( Transform ); } virtual TPtr<TShape> Transform(const TLMaths::TTransform& Transform,TPtr<TShape>& pOldShape,Bool KeepShape=FALSE) const; virtual void Untransform(const TLMaths::TTransform& Transform) { m_Shape.Untransform( Transform ); } virtual TPtr<TShape> Untransform(const TLMaths::TTransform& Transform,TPtr<TShape>& pOldShape,Bool KeepShape=FALSE) const; virtual Bool HasIntersection(TShapeSphere& OtherShape); virtual Bool HasIntersection(TShapeBox& OtherShape); virtual Bool HasIntersection(TShapeBox2D& OtherShape); const TLMaths::TBox& GetBox() const { return m_Shape; } void SetBox(const TLMaths::TBox& Box) { m_Shape = Box; } protected: virtual Bool ImportData(TBinaryTree& Data); virtual Bool ExportData(TBinaryTree& Data) const; public: TLMaths::TBox m_Shape; }; class TLMaths::TShapeBox2D : public TLMaths::TShape { public: TShapeBox2D() {} TShapeBox2D(const TLMaths::TBox2D& Box) : m_Shape ( Box ) {} static TRef GetShapeType_Static() { return TLMaths_ShapeRef(TBox2D); } virtual TRef GetShapeType() const { return TLMaths_ShapeRef(TBox2D); } virtual Bool IsValid() const { return m_Shape.IsValid(); } virtual void SetInvalid() { return m_Shape.SetInvalid(); } virtual float3 GetCenter() const { return m_Shape.GetCenter(); } virtual float3 GetRandomPosition() const; // return a random position inside the shape virtual void Transform(const TLMaths::TTransform& Transform) { m_Shape.Transform( Transform ); } virtual TPtr<TShape> Transform(const TLMaths::TTransform& Transform,TPtr<TShape>& pOldShape,Bool KeepShape=FALSE) const; virtual void Untransform(const TLMaths::TTransform& Transform) { m_Shape.Untransform( Transform ); } virtual TPtr<TShape> Untransform(const TLMaths::TTransform& Transform,TPtr<TShape>& pOldShape,Bool KeepShape=FALSE) const; virtual Bool HasIntersection(TShapeSphere& OtherShape); virtual Bool HasIntersection(TShapeSphere2D& OtherShape); virtual Bool HasIntersection(TShapeBox& OtherShape); virtual Bool HasIntersection(TShapeBox2D& OtherShape); virtual Bool HasIntersection(TShapeCapsule2D& OtherShape); virtual Bool HasIntersection(TLMaths::TLine& Line) const { return m_Shape.GetIntersection( Line ); } const TLMaths::TBox2D& GetBox() const { return m_Shape; } void SetBox(const TLMaths::TBox2D& Box) { m_Shape = Box; } protected: virtual Bool ImportData(TBinaryTree& Data); virtual Bool ExportData(TBinaryTree& Data) const; public: TLMaths::TBox2D m_Shape; };
[ [ [ 1, 83 ] ] ]
90358db6626a7f6da83c18695aacbc649c942bfa
9773c3304eecc308671bcfa16b5390c81ef3b23a
/MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/ChartCtrl/ChartAxisLabel.cpp
0c339f32e9663c4b18990f7b89cf8b1869ff18d0
[]
no_license
15831944/AiPI-1
2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4
9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8
refs/heads/master
2021-12-02T20:34:03.136125
2011-10-27T00:07:54
2011-10-27T00:07:54
null
0
0
null
null
null
null
IBM852
C++
false
false
3,361
cpp
/* * * ChartAxisLabel.cpp * * Written by CÚdric Moonen ([email protected]) * * * * This code may be used for any non-commercial and commercial purposes in a compiled form. * The code may be redistributed as long as it remains unmodified and providing that the * author name and this disclaimer remain intact. The sources can be modified WITH the author * consent only. * * This code is provided without any garanties. I cannot be held responsible for the damage or * the loss of time it causes. Use it at your own risks * * An e-mail to notify me that you are using this code is appreciated also. * * */ #include "stdafx.h" #include "ChartAxisLabel.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CChartAxisLabel::CChartAxisLabel(CChartCtrl* pParent, bool bHorizontal):CChartObject(pParent) { m_bIsHorizontal = bHorizontal; m_iFontSize = 100; m_strFontName = _T("Microsoft Sans Serif"); m_strLabelText = _T(""); } CChartAxisLabel::~CChartAxisLabel() { } CSize CChartAxisLabel::GetSize(CDC *pDC) const { CSize LabelSize; LabelSize.cx = 0; LabelSize.cy = 0; if (!m_bIsVisible) return LabelSize; if (!pDC->GetSafeHdc()) return LabelSize; if (m_strLabelText == _T("")) return LabelSize; COLORREF OldColor = pDC->SetTextColor(m_ObjectColor); CFont NewFont; CFont* pOldFont; NewFont.CreatePointFont(m_iFontSize, (LPCTSTR)m_strFontName.c_str(),pDC); pOldFont = pDC->SelectObject(&NewFont); LabelSize = pDC->GetTextExtent(m_strLabelText.c_str()); LabelSize.cx += 4; LabelSize.cy += 4; if (!m_bIsHorizontal) { int Width = LabelSize.cy; int Height = LabelSize.cx; LabelSize.cx = Width; LabelSize.cy = Height; } pDC->SelectObject(pOldFont); DeleteObject(NewFont); pDC->SetTextColor(OldColor); return LabelSize; } void CChartAxisLabel::Draw(CDC *pDC) { if (!m_bIsVisible) return; if (!pDC->GetSafeHdc()) return; if (m_strLabelText == _T("")) return; CFont NewFont; NewFont.CreatePointFont(m_iFontSize, (LPCTSTR)m_strFontName.c_str(),pDC); CFont* pOldFont; if (!m_bIsHorizontal) { LOGFONT LogFont; NewFont.GetLogFont(&LogFont); LogFont.lfOrientation = 900; LogFont.lfEscapement = 900; CFont VertFont; VertFont.CreateFontIndirect(&LogFont); pOldFont = pDC->SelectObject(&VertFont); pDC->ExtTextOut(m_ObjectRect.left + 2,m_ObjectRect.top, ETO_CLIPPED,NULL,m_strLabelText.c_str(),NULL); pDC->SelectObject(pOldFont); DeleteObject(VertFont); DeleteObject(NewFont); } else { pOldFont = pDC->SelectObject(&NewFont); pDC->ExtTextOut(m_ObjectRect.left,m_ObjectRect.top + 2, ETO_CLIPPED,NULL,m_strLabelText.c_str(),NULL); pDC->SelectObject(pOldFont); DeleteObject(NewFont); } } void CChartAxisLabel::SetPosition(int LeftBorder, int TopBorder, CDC *pDC) { CSize NewSize = GetSize(pDC); CRect NewRect; NewRect.top = TopBorder; NewRect.bottom = TopBorder + NewSize.cy; NewRect.left = LeftBorder; NewRect.right = LeftBorder + NewSize.cx; CChartObject::SetRect(NewRect); }
[ [ [ 1, 138 ] ] ]
7aa9e091e91c962c048bfec59e0db0bb4142aa51
fb71c08b1c1e7ea4d7abc82e65b36272069993e1
/src/CTimer.hpp
49095363153249f7e0a2667f83f2d328007e61b8
[]
no_license
cezarygerard/fpteacher
1bb4ea61bc86cbadcf47a810c8bb441f598d278a
7bdfcf7c047caa9382e22a9d26a2d381ce2d9166
refs/heads/master
2021-01-23T03:47:54.994165
2010-03-25T01:12:04
2010-03-25T01:12:04
39,897,391
0
0
null
null
null
null
UTF-8
C++
false
false
3,009
hpp
/**\file * @author Czarek Zawadka * @date 2009.12.12 * @version 0.6 * @class CTimer CTimer.hpp * @brief klasa CTimer pozwala klasom implementujacym interfejs CTimerObserver na dostep do timera z SDL'a. CTimer to singleton * * * Korzystanie z CTimer polega na wywolaniu klasy addObserver i cieszeniu sie z dokladnego odmierzania czasu, * gdy juz sie nacieszymy mozna wywolac removeObserver. * * * Dzialanie klasy CTimer polega na obudowaniu SDL'a. Wykorzystywana jest metoda SDL_AddTimer(Uint32 interval, SDL_NewTimerCallback callback, void* param), * ktora zalatwia wszystko. Parametry tej funkcji to: interval - odmierzany czas, callback - funkcja ktora ma * zostac wywolana po odliczeniu do konca, param - argument z ktorym ma byc wywolana funkcja callback. * W CTimer zostala zdefiniowana funkcja timerCallback, ktora jest uzywana jako callback. Parametremi sa: interval(wymagane przez SDL) * oraz wskaznik na * zainteresowanego CTimerObserver'a. * * * @todo wzbogacenie klasy o mozliwosc pauzowania timera * @todo dodac inicjalizacje SLD_Timera gdy to jeszcze nie nastapilo */ #ifndef CTIMER_H #define CTIMER_H #include <map> // naglowki SDL #include "SDL.h" #include "CSingleton.hpp" #include "CTimerObserver.hpp" using namespace std; class CTimerObserver; class CTimer : public CSingleton<CTimer> { friend class CSingleton<CTimer>; public: ///rejestrowanie obserwatora. Poczatek odmierzania czasu jest natychmiasowy ///@param o - obserwator ktory bedzie powiadamiany ///@param interval - odmierzany czas ///@return SDL_TimerID - id kotre przypisano SDL_TimerID addObserver(CTimerObserver& o, int interval); ///usuwanie obserwatora void removeObserver(const CTimerObserver& o); //void start(const CTimerObserver& o); //void stop(const CTimerObserver& o); ///pozwala uzyskac aktualny czas(liczony od uruchomienia SDL), lub czas jaki minal od refTime ///@param refTime - czas od ktorego ma byc liczony aktualny czas int getTime(int refTime = 0); ///Klasa opakowujaca SDL_Delay, sterowanie wraca do miejsca wywolania o delayTime milisekundach ///@param delayTime w milisekundach, powinna byc wielokrotnosc 40ms void delay(int delayTime); private: ///wskaznik na ta metode jest argumentem funkcji SDL_AddTimer(), tutaj realizowane jest ///powiadamianie obserwatorow ///@param interval - odmierzany czas ///@param param - wskaznik na obserwatora dla ktorego odmierzany jest czas static Uint32 timerCallback(Uint32 interval, void* param); ///Konstruktor domyslny CTimer(); ///Destruktor ~CTimer(); ///klucz do mapy observers_, dodanie obserwatora inkrementuje id_ o jeden dla kolejnych obserwatorow static int id_; ///struktura opakowujaca CTimerObserver. Zawiera SDL_TimerID struct TimerParam { SDL_TimerID timreId_; CTimerObserver * observer_; }; ///kontener przechowujacy obserwatorow map<int, TimerParam> observers_; }; #endif //~~CTimer.hpp
[ "czarek.zawadka@8e29c490-c8d6-11de-b6dc-25c59a28ecba", "fester3000@8e29c490-c8d6-11de-b6dc-25c59a28ecba", "r.malinowski88@8e29c490-c8d6-11de-b6dc-25c59a28ecba" ]
[ [ [ 1, 3 ], [ 7, 8 ], [ 11, 12 ], [ 18, 27 ], [ 32, 33 ], [ 35, 40 ], [ 42, 45 ], [ 48, 55 ], [ 58, 60 ], [ 62, 64 ], [ 67, 86 ], [ 88, 92 ] ], [ [ 4, 4 ], [ 6, 6 ], [ 9, 10 ], [ 13, 17 ], [ 28, 31 ], [ 34, 34 ], [ 41, 41 ], [ 56, 57 ], [ 65, 66 ], [ 87, 87 ], [ 93, 93 ] ], [ [ 5, 5 ], [ 46, 47 ], [ 61, 61 ] ] ]
f76c5a099ade4f05960d601153e8cc4d69aaf7e1
7c51155f60ff037d1b8d6eea1797c7d17e1d95c2
/linux-interpreter-end2/interpreter-test.cpp
1362a119eca6e80789011f883a74c69bd8607f01
[]
no_license
BackupTheBerlios/ejvm
7258cd180256970d57399d0c153d00257dbb127c
626602de9ed55a825efeefd70970c36bcef0588d
refs/heads/master
2020-06-11T19:47:07.882834
2006-07-10T16:39:59
2006-07-10T16:39:59
39,960,044
0
0
null
null
null
null
UTF-8
C++
false
false
552
cpp
#include"ejvm.h" #include"ExecutionEng.h" #include"ByteCode.h" void test( void){ e_byte_t byte_code[]={e_VALUE_OF_iconst_0 , e_VALUE_OF_istore_1 , e_VALUE_OF_iconst_0 , e_VALUE_OF_istore_2 , e_VALUE_OF_iload_1 , e_VALUE_OF_iconst_1 , e_VALUE_OF_iadd , e_VALUE_OF_istore_2 , e_VALUE_OF_return }; ByteCode* method = new ByteCode(); method->nameIndex=0; method->length=0; method->maxStack=6; method->maxLocals=6; method->codeLength=6; method->code=byte_code; method->exceptionTable=NULL; ExecutionEng::e_exexute(NULL,method); }
[ "eslam" ]
[ [ [ 1, 19 ] ] ]
b13ba21462e6c65972a4bab9a77a2bbd8e17347b
36fea6c98ecabcd5e932f2b7854b3282cdb571ee
/release/moc_qtpropertybrowserutils_p.cpp
7dbb8f11765c842d8977107b0df1a82cae294b07
[]
no_license
doomfrawen/visualcommand
976adaae69303d8b4ffc228106a1db9504e4a4e4
f7bc1d590444ff6811f84232f5c6480449228e19
refs/heads/master
2016-09-06T17:40:57.775379
2009-07-28T22:48:23
2009-07-28T22:48:23
32,345,504
0
0
null
null
null
null
UTF-8
C++
false
false
4,500
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'qtpropertybrowserutils_p.h' ** ** Created: Mon Jun 22 19:12:00 2009 ** by: The Qt Meta Object Compiler version 61 (Qt 4.5.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../src/qtpropertybrowserutils_p.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'qtpropertybrowserutils_p.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 61 #error "This file was generated using the moc from 4.5.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_QtBoolEdit[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 1, 12, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors // signals: signature, parameters, type, tag, flags 12, 11, 11, 11, 0x05, 0 // eod }; static const char qt_meta_stringdata_QtBoolEdit[] = { "QtBoolEdit\0\0toggled(bool)\0" }; const QMetaObject QtBoolEdit::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_QtBoolEdit, qt_meta_data_QtBoolEdit, 0 } }; const QMetaObject *QtBoolEdit::metaObject() const { return &staticMetaObject; } void *QtBoolEdit::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_QtBoolEdit)) return static_cast<void*>(const_cast< QtBoolEdit*>(this)); return QWidget::qt_metacast(_clname); } int QtBoolEdit::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: toggled((*reinterpret_cast< bool(*)>(_a[1]))); break; default: ; } _id -= 1; } return _id; } // SIGNAL 0 void QtBoolEdit::toggled(bool _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } static const uint qt_meta_data_QtKeySequenceEdit[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 3, 12, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors // signals: signature, parameters, type, tag, flags 28, 19, 18, 18, 0x05, // slots: signature, parameters, type, tag, flags 61, 19, 18, 18, 0x0a, 90, 18, 18, 18, 0x08, 0 // eod }; static const char qt_meta_stringdata_QtKeySequenceEdit[] = { "QtKeySequenceEdit\0\0sequence\0" "keySequenceChanged(QKeySequence)\0" "setKeySequence(QKeySequence)\0" "slotClearShortcut()\0" }; const QMetaObject QtKeySequenceEdit::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_QtKeySequenceEdit, qt_meta_data_QtKeySequenceEdit, 0 } }; const QMetaObject *QtKeySequenceEdit::metaObject() const { return &staticMetaObject; } void *QtKeySequenceEdit::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_QtKeySequenceEdit)) return static_cast<void*>(const_cast< QtKeySequenceEdit*>(this)); return QWidget::qt_metacast(_clname); } int QtKeySequenceEdit::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: keySequenceChanged((*reinterpret_cast< const QKeySequence(*)>(_a[1]))); break; case 1: setKeySequence((*reinterpret_cast< const QKeySequence(*)>(_a[1]))); break; case 2: slotClearShortcut(); break; default: ; } _id -= 3; } return _id; } // SIGNAL 0 void QtKeySequenceEdit::keySequenceChanged(const QKeySequence & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } QT_END_MOC_NAMESPACE
[ "flouger@13a168e0-7ae3-11de-a146-1f7e517e55b8" ]
[ [ [ 1, 149 ] ] ]
a2baf07626d7c73aeedbe11b026478537c5fdecc
073dfce42b384c9438734daa8ee2b575ff100cc9
/RCF/src/RCF/RcfBoostThreads/boost_1_33_1/libs/thread/src/mutex.inl
78a69fac5486ab051fde3d499ded84d57a486535
[]
no_license
r0ssar00/iTunesSpeechBridge
a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf
71a27a52e66f90ade339b2b8a7572b53577e2aaf
refs/heads/master
2020-12-24T17:45:17.838301
2009-08-24T22:04:48
2009-08-24T22:04:48
285,393
1
0
null
null
null
null
UTF-8
C++
false
false
3,721
inl
// dummy // Copyright (C) 2001-2003 // William E. Kempf // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. William E. Kempf makes no representations // about the suitability of this software for any purpose. // It is provided "as is" without express or implied warranty. namespace { #if defined(BOOST_HAS_WINTHREADS) //:PREVENT THIS FROM BEING DUPLICATED typedef BOOL (WINAPI* TryEnterCriticalSection_type)(LPCRITICAL_SECTION lpCriticalSection); TryEnterCriticalSection_type g_TryEnterCriticalSection = 0; boost::once_flag once_init_TryEnterCriticalSection = BOOST_ONCE_INIT; void init_TryEnterCriticalSection() { //TryEnterCriticalSection is only available on WinNT 4.0 or later; //it is not available on Win9x. OSVERSIONINFO version_info = {sizeof(OSVERSIONINFO)}; ::GetVersionEx(&version_info); if (version_info.dwPlatformId == VER_PLATFORM_WIN32_NT && version_info.dwMajorVersion >= 4) { if (HMODULE kernel_module = GetModuleHandle(TEXT("KERNEL32.DLL"))) g_TryEnterCriticalSection = reinterpret_cast<TryEnterCriticalSection_type>(GetProcAddress(kernel_module, "TryEnterCriticalSection")); } } inline bool has_TryEnterCriticalSection() { boost::call_once(init_TryEnterCriticalSection, once_init_TryEnterCriticalSection); return g_TryEnterCriticalSection != 0; } inline HANDLE mutex_cast(void* p) { return reinterpret_cast<HANDLE>(p); } inline LPCRITICAL_SECTION critical_section_cast(void* p) { return reinterpret_cast<LPCRITICAL_SECTION>(p); } inline void* new_critical_section() { try { LPCRITICAL_SECTION critical_section = new ::CRITICAL_SECTION; if (critical_section == 0) throw boost::thread_resource_error(); InitializeCriticalSection(critical_section); return critical_section; } catch(...) { throw boost::thread_resource_error(); } } inline void* new_mutex(const char* name) { #if defined(BOOST_NO_ANSI_APIS) USES_CONVERSION; HANDLE mutex = CreateMutexW(0, 0, A2CW(name)); #else HANDLE mutex = CreateMutexA(0, 0, name); #endif if (mutex == 0 || mutex == INVALID_HANDLE_VALUE) //:xxx (check for both values?) throw boost::thread_resource_error(); return reinterpret_cast<void*>(mutex); } inline void delete_critical_section(void* mutex) { DeleteCriticalSection(critical_section_cast(mutex)); delete critical_section_cast(mutex); } inline void delete_mutex(void* mutex) { int res = 0; res = CloseHandle(mutex_cast(mutex)); assert(res); } inline void wait_critical_section_infinite(void* mutex) { EnterCriticalSection(critical_section_cast(mutex)); //:xxx Can throw an exception under low memory conditions } inline bool wait_critical_section_try(void* mutex) { BOOL res = g_TryEnterCriticalSection(critical_section_cast(mutex)); return res != 0; } inline int wait_mutex(void* mutex, int time) { unsigned int res = 0; res = WaitForSingleObject(mutex_cast(mutex), time); //:xxx assert(res != WAIT_FAILED && res != WAIT_ABANDONED); return res; } inline void release_critical_section(void* mutex) { LeaveCriticalSection(critical_section_cast(mutex)); } inline void release_mutex(void* mutex) { BOOL res = FALSE; res = ReleaseMutex(mutex_cast(mutex)); assert(res); } #endif }
[ [ [ 1, 127 ] ] ]
9f33c205cbdcaeceb25a64f6246ae540d5cb8df8
58ef4939342d5253f6fcb372c56513055d589eb8
/LemonMicro/inc/LemonMicroAppUi.h
e4d48d7cf583bfc4955944c10bddc02ed5bd10cd
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
UTF-8
C++
false
false
1,938
h
/* ============================================================================ Name : LemonMicroAppUi.h Author : Copyright : Your copyright notice Description : Declares UI class for application. ============================================================================ */ #ifndef __LEMONMICROAPPUI_h__ #define __LEMONMICROAPPUI_h__ // INCLUDES #include <aknappui.h> // FORWARD DECLARATIONS class CLemonMicroAppView; class CFileRecordAdapter; class CStreamRecordAdapter; // CLASS DECLARATION /** * CLemonMicroAppUi application UI class. * Interacts with the user through the UI and request message processing * from the handler class */ class CLemonMicroAppUi : public CAknAppUi { public: // Constructors and destructor /** * ConstructL. * 2nd phase constructor. */ void ConstructL(); /** * CLemonMicroAppUi. * C++ default constructor. This needs to be public due to * the way the framework constructs the AppUi */ CLemonMicroAppUi(); /** * ~CLemonMicroAppUi. * Virtual Destructor. */ virtual ~CLemonMicroAppUi(); private: // Functions from base classes /** * From CEikAppUi, HandleCommandL. * Takes care of command handling. * @param aCommand Command to be handled. */ void HandleCommandL(TInt aCommand); /** * HandleStatusPaneSizeChange. * Called by the framework when the application status pane * size is changed. */ void HandleStatusPaneSizeChange(); /** * From CCoeAppUi, HelpContextL. * Provides help context for the application. * size is changed. */ CArrayFix<TCoeHelpContext>* HelpContextL() const; private: // Data /** * The application view * Owned by CLemonMicroAppUi */ CLemonMicroAppView* iAppView; CFileRecordAdapter* iFileRecorder; CStreamRecordAdapter* iStreamRecorder; }; #endif // __LEMONMICROAPPUI_h__ // End of File
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 88 ] ] ]
90134954518545588c752e8ae8207bd84eb875d2
7b6292601467a32ab84e3f2c35801226dedb1490
/Timer/AboutDlg.h
7fc1d89706cd4d50c31ffda2f933a2642cd7b858
[]
no_license
mareqq/mareq-timer
b4bc9134573fec6d554b7da51dc5d9350cc73581
180a60d7e1d8190f80b05177a0270cc0309e7822
refs/heads/master
2021-01-21T07:39:46.790716
2008-09-02T13:56:09
2008-09-02T13:56:09
32,898,637
0
0
null
null
null
null
UTF-8
C++
false
false
544
h
#pragma once #include "resource.h" #include "afxwin.h" #include "staticlink.h" class CAboutDlg : public CDialog { DECLARE_DYNAMIC(CAboutDlg) public: CAboutDlg(CWnd* pParent = NULL); virtual ~CAboutDlg(); enum { IDD = IDD_ABOUT }; protected: virtual void DoDataExchange(CDataExchange* pDX); virtual BOOL OnInitDialog(); DECLARE_MESSAGE_MAP() protected: CStatic m_TitleCtrl; CStaticLink m_GooglecodeLink; CStaticLink m_LinkMareqCom; CStaticLink m_MareqSk; CFont m_TitleFont; };
[ "mareqq@62a7fa73-be4e-0410-9e8d-e136552d7b79" ]
[ [ [ 1, 30 ] ] ]
1f6e2a15858b32d0c39b04614e159640328b8817
bd48897ed08ecfea35d8e00312dd4f9d239e95c4
/contest/template.cpp
b8dd9bd1050052af0ec25e92155a4b09cb25bf0c
[]
no_license
blmarket/lib4bpp
ab83dbb95cc06e7b55ea2ca70012e341be580af1
2c676543de086458b93b1320b7b2ad7f556a24f7
refs/heads/master
2021-01-22T01:28:03.718350
2010-11-30T06:45:42
2010-11-30T06:45:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
830
cpp
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <cmath> #include <sstream> #include <queue> #include <set> #include <map> #include <vector> #include <complex> #define mp make_pair #define pb push_back #define sqr(x) ((x)*(x)) #define foreach(it,c) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it) using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<string> VS; typedef pair<int,int> PII; typedef long long LL; typedef complex<double> Point; template<typename T> inline int size(const T &a) { return a.size(); } template<typename T> inline bool operator<(const int &a,const vector<T> &b) { return a<b.size(); } bool process(void) { return true; } int main(void) { while(process()); return 0; }
[ "blmarket@dbb752b6-32d3-11de-9d05-31133e6853b1" ]
[ [ [ 1, 40 ] ] ]
4dc144e900289d635d4ead0d11fb843b1e346a6b
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nscene/src/nscene/nskinanimator_main.cc
e4576997a940a6740044fe1e6adecfa7faf9c599
[]
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,456
cc
#include "precompiled/pchnscene.h" //------------------------------------------------------------------------------ // nskinanimator_main.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "nscene/nskinanimator.h" #include "nscene/nskinshapenode.h" #include "anim2/nanimation.h" #include "anim2/nanimationserver.h" #include "anim2/nanimstatearray.h" #include "character/ncharacter2.h" #include "nscene/ncscene.h" #include "entity/nentity.h" #include "variable/nvariableserver.h" nNebulaScriptClass(nSkinAnimator, "nanimator"); //------------------------------------------------------------------------------ /** */ nSkinAnimator::nSkinAnimator() : characterVarIndex(0), animStateVarHandle(nVariable::InvalidHandle), animEnabled(true) { this->skinShapeNodeClass = kernelServer->FindClass("nskinshapenode"); this->shadowSkinShapeNodeClass = kernelServer->FindClass("nshadowskinshapenode"); n_assert(this->skinShapeNodeClass); n_assert(this->shadowSkinShapeNodeClass); this->animRestartVarHandle = nVariableServer::Instance()->GetVariableHandleByName("chnRestartAnim"); } //------------------------------------------------------------------------------ /** */ nSkinAnimator::~nSkinAnimator() { // empty } //------------------------------------------------------------------------------ /** Unload the animation resource file. */ void nSkinAnimator::UnloadAnim() { if (this->refAnim.isvalid()) { this->refAnim->Release(); this->refAnim.invalidate(); } } //------------------------------------------------------------------------------ /** Load the animation resource file. */ bool nSkinAnimator::LoadAnim() { if ((!this->refAnim.isvalid()) && (!this->animName.IsEmpty())) { const char* fileName = this->animName.Get(); nAnimation* anim = nAnimationServer::Instance()->NewMemoryAnimation(fileName); n_assert(anim); if (!anim->IsValid()) { anim->SetFilename(fileName); if (!anim->Load()) { n_printf("nSkinAnimator: Error loading anim file '%s'\n", fileName); anim->Release(); return false; } } this->refAnim = anim; //this->character.SetAnimation(anim); //<MA> int stateIndex; for (stateIndex = 0; stateIndex < this->GetNumStates(); stateIndex++) { nAnimState& animState = this->animStateArray.GetStateAt(stateIndex); if (!animState.IsAnimValid()) { animState.SetAnim(anim); } } //</MA> this->character.SetAnimStateArray(&this->animStateArray); } return true; } //------------------------------------------------------------------------------ /** Load the resources needed by this object. */ bool nSkinAnimator::LoadResources() { if (nSceneNode::LoadResources()) { this->LoadAnim(); return true; } return false; } //------------------------------------------------------------------------------ /** Unload the resources. */ void nSkinAnimator::UnloadResources() { nSceneNode::UnloadResources(); this->UnloadAnim(); } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::EntityCreated(nEntityObject* entityObject) { nAnimator::EntityCreated(entityObject); // see if resources need to be reloaded if (!this->AreResourcesValid()) { this->LoadResources(); } nCharacter2* curCharacter = n_new(nCharacter2(this->character)); n_assert(curCharacter); // put frame persistent data in render context nRenderContext& renderContext = entityObject->GetComponent(nComponentType<ncScene>())->RenderContext(); nVariable::Handle charHandle = nVariableServer::Instance()->GetVariableHandleByName("charPointer"); this->characterVarIndex = renderContext->AddLocalVar(nVariable(charHandle, curCharacter)); } //------------------------------------------------------------------------------ /** - 15-Jan-04 floh AreResourcesValid()/LoadResource() moved to scene server */ void nSkinAnimator::Animate(nSceneNode* sceneNode, nEntityObject* entityObject) { n_assert(sceneNode); n_assert(entityObject); n_assert(nVariable::InvalidHandle != this->channelVarHandle); ncScene* renderContext = entityObject->GetComponentSafe(nComponentType<ncScene>()); const nVariable& charVar = renderContext.GetLocalVar(this->characterVarIndex); nCharacter2* curCharacter = (nCharacter2*) charVar.GetObj(); n_assert(curCharacter); // update the animation enabled flag //curCharacter->SetAnimEnabled(this->animEnabled); // check if I am already uptodate for this frame uint curFrameId = renderContext->GetFrameId(); if (curCharacter->GetLastEvaluationFrameId() != curFrameId) { curCharacter->SetLastEvaluationFrameId(curFrameId); // get the sample time from the render context nVariable* var = renderContext.GetVariable(this->channelVarHandle); if (var == 0) { n_error("nSkinAnimator::Animate: TimeChannel Variable '%s' not found in the RenderContext!\n", nVariableServer::Instance()->GetVariableName(this->channelVarHandle)); } float curTime = var->GetFloat(); // get the time offset from the render context var = renderContext->GetVariable(this->channelOffsetVarHandle); float curOffset = 0 != var ? var->GetFloat() : 0.0f; // get the current anim state from the anim state channel // (assume 0 as default state index) var = renderContext.GetVariable(this->animStateVarHandle); int animState = 0; if (var) { animState = var->GetInt(); } int restartAnim = 0; var = renderContext->GetVariable(this->animRestartVarHandle); if (var) { restartAnim = var->GetInt(); } if ((animState != curCharacter->GetActiveState()) || (0 != restartAnim)) { // activate new state if (curCharacter->IsValidStateIndex(animState)) { curCharacter->SetActiveState(animState, curTime, curOffset); } else { n_printf("Warning: Invalid state index %d. State switch ignored. \n", animState); } } // evaluate the current state of the character skeleton curCharacter->EvaluateSkeleton(curTime, &renderContext); } // update the source node with the new char skeleton state if (sceneNode->IsA(this->skinShapeNodeClass)) { nSkinShapeNode* skinShapeNode = (nSkinShapeNode*) sceneNode; skinShapeNode->SetCharSkeleton(&curCharacter->GetSkeleton()); } else if (sceneNode->IsA(this->shadowSkinShapeNodeClass)) { nShadowSkinShapeNode* shadowSkinShapeNode = (nShadowSkinShapeNode*) sceneNode; shadowSkinShapeNode->SetCharSkeleton(&curCharacter->GetSkeleton()); } else { n_error("nSkinAnimator::Animate(): invalid scene node class\n"); } } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::EntityDestroyed(nEntityObject* entityObject) { nRenderContext& renderContext = entityObject->GetComponent(nComponentType<ncScene>())->RenderContext(); nVariable var; var = renderContext.GetLocalVar(this->characterVarIndex); nCharacter2* curCharacter = (nCharacter2*) var.GetObj(); n_assert(curCharacter); curCharacter->Release(); } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::BeginJoints(int numJoints) { this->character.GetSkeleton().Clear(); this->character.GetSkeleton().BeginJoints(numJoints); } //------------------------------------------------------------------------------ /** Add a joint to the joint skeleton. */ void nSkinAnimator::SetJoint(int jointIndex, int parentJointIndex, const vector3& poseTranslate, const quaternion& poseRotate, const vector3& poseScale) { this->character.GetSkeleton().SetJoint(jointIndex, parentJointIndex, poseTranslate, poseRotate, poseScale); } //------------------------------------------------------------------------------ /** Finish adding joints to the joint skeleton. */ void nSkinAnimator::EndJoints() { this->character.GetSkeleton().EndJoints(); } //------------------------------------------------------------------------------ /** Get number of joints in joint skeleton. */ int nSkinAnimator::GetNumJoints() { return this->character.GetSkeleton().GetNumJoints(); } //------------------------------------------------------------------------------ /** Get joint attributes. */ void nSkinAnimator::GetJoint(int index, int& parentJointIndex, vector3& poseTranslate, quaternion& poseRotate, vector3& poseScale) { nCharJoint& joint = this->character.GetSkeleton().GetJointAt(index); parentJointIndex = joint.GetParentJointIndex(); poseTranslate = joint.GetPoseTranslate(); poseRotate = joint.GetPoseRotate(); poseScale = joint.GetPoseScale(); } //------------------------------------------------------------------------------ /** Set name of anim resource file. */ void nSkinAnimator::SetAnim(const char* name) { n_assert(name); this->UnloadAnim(); this->animName = name; } //------------------------------------------------------------------------------ /** Get name of anim resource file. */ const char* nSkinAnimator::GetAnim() const { return this->animName.IsEmpty() ? 0 : this->animName.Get(); } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::SetStateChannel(const char* name) { this->animStateVarHandle = nVariableServer::Instance()->GetVariableHandleByName(name); } //------------------------------------------------------------------------------ /** Returns the name of the animation variable which drives this animation. This variable exists within the variable server located at @c /sys/servers/variable. */ const char* nSkinAnimator::GetStateChannel() { if (nVariable::InvalidHandle == this->animStateVarHandle) { return 0; } else { return nVariableServer::Instance()->GetVariableName(this->animStateVarHandle); } } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::BeginStates(int num) { this->animStateArray.Begin(num); } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::SetState(int stateIndex, int animGroupIndex, float fadeInTime) { nAnimState newState; newState.SetAnimGroupIndex(animGroupIndex); newState.SetFadeInTime(fadeInTime); this->animStateArray.SetState(stateIndex, newState); } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::SetStateName(int stateIndex, const nString& name) { this->animStateArray.GetStateAt(stateIndex).SetName(name); } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::EndStates() { this->animStateArray.End(); } //------------------------------------------------------------------------------ /** */ int nSkinAnimator::GetNumStates() const { return this->animStateArray.GetNumStates(); } //------------------------------------------------------------------------------ /** */ const nAnimState& nSkinAnimator::GetStateAt(int stateIndex) { return this->animStateArray.GetStateAt(stateIndex); } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::BeginClips(int stateIndex, int numClips) { this->animStateArray.GetStateAt(stateIndex).BeginClips(numClips); } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::SetClip(int stateIndex, int clipIndex, const char* weightChannelName) { // number of anim curves in a clip is identical to number of (joints * 3) // (one curve for translation, rotation and scale) int numCurves = this->GetNumJoints() * 3; n_assert(numCurves > 0); // the first anim curve index of this clip is at (numCurves * clipIndex) int firstCurve = numCurves * clipIndex; // get the variable handle for the weightChannel nVariable::Handle varHandle = nVariableServer::Instance()->GetVariableHandleByName(weightChannelName); n_assert(nVariable::InvalidHandle != varHandle); nAnimClip newClip(firstCurve, numCurves, varHandle); this->animStateArray.GetStateAt(stateIndex).SetClip(clipIndex, newClip); } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::EndClips(int stateIndex) { this->animStateArray.GetStateAt(stateIndex).EndClips(); } //------------------------------------------------------------------------------ /** */ int nSkinAnimator::GetNumClips(int stateIndex) const { return this->animStateArray.GetStateAt(stateIndex).GetNumClips(); } //------------------------------------------------------------------------------ /** */ void nSkinAnimator::GetClipAt(int stateIndex, int clipIndex, const char*& weightChannelName) { nVariable::Handle varHandle = this->animStateArray.GetStateAt(stateIndex).GetClipAt(clipIndex).GetWeightChannelHandle(); weightChannelName = nVariableServer::Instance()->GetVariableName(varHandle); } //------------------------------------------------------------------------------ /** Begin adding animation event tracks to a clip. */ void nSkinAnimator::BeginAnimEventTracks(int stateIndex, int clipIndex, int numTracks) { this->animStateArray.GetStateAt(stateIndex).GetClipAt(clipIndex).SetNumAnimEventTracks(numTracks); } //------------------------------------------------------------------------------ /** Begin adding events to an animation event track. */ void nSkinAnimator::BeginAnimEventTrack(int stateIndex, int clipIndex, int trackIndex, const nString& name, int numEvents) { nAnimEventTrack& t = this->animStateArray.GetStateAt(stateIndex).GetClipAt(clipIndex).GetAnimEventTrackAt(trackIndex); t.SetName(name); t.SetNumEvents(numEvents); } //------------------------------------------------------------------------------ /** Set an animation event in a track */ void nSkinAnimator::SetAnimEvent(int stateIndex, int clipIndex, int trackIndex, int eventIndex, float time, const vector3& translate, const quaternion& rotate, const vector3& scale) { nAnimEventTrack& t = this->animStateArray.GetStateAt(stateIndex).GetClipAt(clipIndex).GetAnimEventTrackAt(trackIndex); nAnimEvent e; e.SetTime(time); e.SetTranslation(translate); e.SetQuaternion(rotate); e.SetScale(scale); t.SetEvent(eventIndex, e); } //------------------------------------------------------------------------------ /** End adding animation events. */ void nSkinAnimator::EndAnimEventTrack(int /*stateIndex*/, int /*clipIndex*/, int /*trackIndex*/) { // empty } //------------------------------------------------------------------------------ /** End adding animation event tracks. */ void nSkinAnimator::EndAnimEventTracks(int /*stateIndex*/, int /*clipIndex*/) { // empty } //------------------------------------------------------------------------------ /** Get the index of the nCharacter2 pointer used when accessing the render context in Animate() @return the requested index into the render context */ int nSkinAnimator::GetCharacterVarIndex() { return this->characterVarIndex; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 531 ] ] ]
a3b5b7a610e1c7526a9bafd43229594af4828876
b83c990328347a0a2130716fd99788c49c29621e
/include/boost/archive/polymorphic_iarchive.hpp
4b126ea22824f3672b4142157019eab20e548386
[]
no_license
SpliFF/mingwlibs
c6249fbb13abd74ee9c16e0a049c88b27bd357cf
12d1369c9c1c2cc342f66c51d045b95c811ff90c
refs/heads/master
2021-01-18T03:51:51.198506
2010-06-13T15:13:20
2010-06-13T15:13:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,489
hpp
#ifndef BOOST_ARCHIVE_POLYMORPHIC_IARCHIVE_HPP #define BOOST_ARCHIVE_POLYMORPHIC_IARCHIVE_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // polymorphic_iarchive.hpp // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // 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) // See http://www.boost.org for updates, documentation, and revision history. #include <cstddef> // std::size_t #include <climits> // ULONG_MAX #include <boost/config.hpp> #if defined(BOOST_NO_STDC_NAMESPACE) namespace std{ using ::size_t; } // namespace std #endif #include <string> #include <boost/cstdint.hpp> #include <boost/serialization/pfto.hpp> #include <boost/archive/detail/iserializer.hpp> #include <boost/archive/detail/interface_iarchive.hpp> #include <boost/serialization/nvp.hpp> #include <boost/archive/detail/register_archive.hpp> #include <boost/archive/detail/decl.hpp> #include <boost/archive/detail/abi_prefix.hpp> // must be the last header // determine if its necessary to handle (u)int64_t specifically // i.e. that its not a synonym for (unsigned) long // if there is no 64 bit int or if its the same as a long // we shouldn't define separate functions for int64 data types. #if defined(BOOST_NO_INT64_T) #define BOOST_NO_INTRINSIC_INT64_T #else #if defined(ULLONG_MAX) #if(ULONG_MAX == 18446744073709551615ul) // 2**64 - 1 #define BOOST_NO_INTRINSIC_INT64_T #endif #elif defined(ULONG_MAX) #if(ULONG_MAX != 0xffffffff && ULONG_MAX == 18446744073709551615ul) // 2**64 - 1 #define BOOST_NO_INTRINSIC_INT64_T #endif #else #define BOOST_NO_INTRINSIC_INT64_T #endif #endif namespace boost { template<class T> class shared_ptr; namespace serialization { class extended_type_info; } // namespace serialization namespace archive { namespace detail { class BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_iarchive; class BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_iarchive; } class polymorphic_iarchive; class polymorphic_iarchive_impl : public detail::interface_iarchive<polymorphic_iarchive> { #ifdef BOOST_NO_MEMBER_TEMPLATE_FRIENDS public: #else friend class detail::interface_iarchive<polymorphic_iarchive>; friend class load_access; #endif // primitive types the only ones permitted by polymorphic archives virtual void load(bool & t) = 0; virtual void load(char & t) = 0; virtual void load(signed char & t) = 0; virtual void load(unsigned char & t) = 0; #ifndef BOOST_NO_CWCHAR #ifndef BOOST_NO_INTRINSIC_WCHAR_T virtual void load(wchar_t & t) = 0; #endif #endif virtual void load(short & t) = 0; virtual void load(unsigned short & t) = 0; virtual void load(int & t) = 0; virtual void load(unsigned int & t) = 0; virtual void load(long & t) = 0; virtual void load(unsigned long & t) = 0; #if !defined(BOOST_NO_INTRINSIC_INT64_T) virtual void load(boost::int64_t & t) = 0; virtual void load(boost::uint64_t & t) = 0; #endif virtual void load(float & t) = 0; virtual void load(double & t) = 0; // string types are treated as primitives virtual void load(std::string & t) = 0; #ifndef BOOST_NO_STD_WSTRING virtual void load(std::wstring & t) = 0; #endif // used for xml and other tagged formats virtual void load_start(const char * name) = 0; virtual void load_end(const char * name) = 0; virtual void register_basic_serializer(const detail::basic_iserializer & bis) = 0; // msvc and borland won't automatically pass these to the base class so // make it explicit here template<class T> void load_override(T & t, BOOST_PFTO int) { archive::load(* this->This(), t); } // special treatment for name-value pairs. template<class T> void load_override( #ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING const #endif boost::serialization::nvp<T> & t, int ){ load_start(t.name()); archive::load(* this->This(), t.value()); load_end(t.name()); } protected: virtual ~polymorphic_iarchive_impl(){}; public: // utility function implemented by all legal archives virtual void set_library_version(unsigned int archive_library_version) = 0; virtual unsigned int get_library_version() const = 0; virtual unsigned int get_flags() const = 0; virtual void delete_created_pointers() = 0; virtual void reset_object_address( const void * new_address, const void * old_address ) = 0; virtual void load_binary(void * t, std::size_t size) = 0; // these are used by the serialization library implementation. virtual void load_object( void *t, const detail::basic_iserializer & bis ) = 0; virtual const detail::basic_pointer_iserializer * load_pointer( void * & t, const detail::basic_pointer_iserializer * bpis_ptr, const detail::basic_pointer_iserializer * (*finder)( const boost::serialization::extended_type_info & type ) ) = 0; }; } // namespace archive } // namespace boost // note special treatment of shared_ptr. This type needs a special // structure associated with every archive. We created a "mix-in" // class to provide this functionality. Since shared_ptr holds a // special esteem in the boost library - we included it here by default. #include <boost/archive/shared_ptr_helper.hpp> namespace boost { namespace archive { class polymorphic_iarchive : public polymorphic_iarchive_impl, public detail::shared_ptr_helper { public: virtual ~polymorphic_iarchive(){}; }; } // namespace archive } // namespace boost // required by export BOOST_SERIALIZATION_REGISTER_ARCHIVE(boost::archive::polymorphic_iarchive) #include <boost/archive/detail/abi_suffix.hpp> // pops abi_suffix.hpp pragmas #endif // BOOST_ARCHIVE_POLYMORPHIC_IARCHIVE_HPP
[ [ [ 1, 197 ] ] ]
21e214866ef09278527bfb625eed00b01f36d5c4
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/program_options/src/positional_options.cpp
63ae1b256315e3e47c7a21b9036710e856d4a3b1
[]
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,341
cpp
// Copyright Vladimir Prus 2004. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #define BOOST_PROGRAM_OPTIONS_SOURCE #include <boost/program_options/config.hpp> #include <boost/program_options/positional_options.hpp> #include <boost/limits.hpp> #include <cassert> namespace boost { namespace program_options { positional_options_description::positional_options_description() {} void positional_options_description::add(const char* name, int max_count) { assert(max_count != -1 || m_trailing.empty()); if (max_count == -1) m_trailing = name; else { m_names.resize(m_names.size() + max_count, name); } } unsigned positional_options_description::max_total_count() const { return m_trailing.empty() ? m_names.size() : std::numeric_limits<unsigned>::max(); } const std::string& positional_options_description::name_for_position(unsigned position) const { assert(position < max_total_count()); if (position < m_names.size()) return m_names[position]; else return m_trailing; } }}
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 53 ] ] ]
f97662bd0bb2742085e24aed966168b1aaa8cef5
faacd0003e0c749daea18398b064e16363ea8340
/3rdparty/phonon/frontendinterface_p.h
8081cc34b274dd20ef36ae34ab825f300fb41528
[]
no_license
yjfcool/lyxcar
355f7a4df7e4f19fea733d2cd4fee968ffdf65af
750be6c984de694d7c60b5a515c4eb02c3e8c723
refs/heads/master
2016-09-10T10:18:56.638922
2009-09-29T06:03:19
2009-09-29T06:03:19
42,575,701
0
0
null
null
null
null
UTF-8
C++
false
false
2,384
h
/* This file is part of the KDE project Copyright (C) 2007 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Trolltech ASA (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PHONON_FRONTENDINTERFACEPRIVATE_H #define PHONON_FRONTENDINTERFACEPRIVATE_H #include "addoninterface.h" #include "mediaobject_p.h" #include "phononnamespace_p.h" #include <QtCore/QPointer> QT_BEGIN_NAMESPACE #ifndef QT_NO_PHONON_MEDIACONTROLLER namespace Phonon { class FrontendInterfacePrivate { public: FrontendInterfacePrivate(MediaObject *mp) : media(mp) { Q_ASSERT(media); MediaObjectPrivate *d = media->k_func(); d->interfaceList << this; } virtual ~FrontendInterfacePrivate() { if (media) { MediaObjectPrivate *d = media->k_func(); d->interfaceList << this; } } virtual void backendObjectChanged(QObject *iface) = 0; void _backendObjectChanged() { pDebug() << Q_FUNC_INFO; QObject *x = media->k_ptr->backendObject(); if (x) { backendObjectChanged(x); } } AddonInterface *iface() { return qobject_cast<AddonInterface *>(media->k_ptr->backendObject()); } QPointer<MediaObject> media; }; } // namespace Phonon #endif //QT_NO_PHONON_MEDIACONTROLLER QT_END_NAMESPACE #endif // PHONON_FRONTENDINTERFACEPRIVATE_H
[ "futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9" ]
[ [ [ 1, 68 ] ] ]
3890fd92c692db462704efcef3dd2175dd629ff0
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Modules/TestShell/TestShell.cpp
516cdef61b31e218833cc143fd82417689b134bd
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
53,860
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* This module is intended for various experiments. * NOT FOR USE IN A PRODUCTION TARGET !!! */ #include "arch.h" #include "MsgBufferEnums.h" #include "Module.h" #include "Serial.h" #include "CtrlHub.h" #include "ParameterEnums.h" #include "Parameter.h" #include "NavPacket.h" #include "GuiProt/ServerEnums.h" #include "NavServerComEnums.h" #include "ErrorModule.h" #include "MapEnums.h" #include "NavServerComEnums.h" #include "NavServerCom.h" #include "Destinations.h" #include "isabTime.h" #include "Quality.h" #include "PositionState.h" #include "NavTask.h" #include "TestShell.h" #include "Buffer.h" #include "nav2util.h" /* #include "RouteInfo.h" */ /* #include "../NavTask/Route.h" */ #include "../NavTask/Point.h" #include "Nav2Error.h" #include "GuiProt/SearchArea.h" #include "GuiProt/SearchRegion.h" #include "GuiProt/SearchItem.h" #include "GuiProt/AdditionalInfo.h" #include "GuiProt/FullSearchItem.h" #include "GuiProt/GuiProtMess.h" #include "GuiProt/MapClasses.h" #include <functional> #include <algorithm> #include "GetIMEI.h" // #define USE_UICTRL //#ifdef USE_UICTRL //# include "../UiCtrl/ThinClient/include/NavCtrlGuiProt.h" //# include "../UiCtrl/ThinClient/include/StringObject.h" //# include "../UiCtrl/ThinClient/include/DataBuffer.h" //#endif #ifdef __SYMBIAN32__ # include <ctype.h> #endif #include "LogMacros.h" #include <assert.h> #define TOLAT 97223144 #define TOLON 23016896 using namespace std; namespace isab { ///Special subclass of buffer that doesn't zero terminate strings ///written with nprintf. class OutputBuffer : public Buffer { public: OutputBuffer(int len) : Buffer(len) {} OutputBuffer() : Buffer() {} int nprintf(size_t size, const char* format, ...); }; inline int OutputBuffer::nprintf(size_t size, const char* format, ...) { va_list args; va_start(args, format); int ret = Buffer::vnprintf(size, format, args); va_end(args); m_validBytes -= 1; m_writePos -= 1; return ret; } TestShell::TestShell(SerialProviderPublic *p, Nav2Error::Nav2ErrorTable * errorTable, bool regressionTest) : Module("TestShell"), m_serialProvider(p), /* m_route(m_log), */ m_syncrequestID(0), m_regressionTest(regressionTest), m_shortRouteOutput(0), m_errorTable(errorTable) { SerialConsumerPublic *consumer; DBG("TestShell::TestShell\n"); p->setOwnerModule(this); consumer = new SerialConsumerPublic(m_queue); p->connect(consumer); newLowerModule(p); m_parameterProvider = new ParameterProviderPublic(this); m_nscProvider = new NavServerComProviderPublic(this); m_dstProvider = new DestinationsProviderPublic(this); m_navTaskProvider = new NavTaskProviderPublic(this); m_mapnum = 0; } void TestShell::decodedConnectionNotify(enum ConnectionNotify state, enum ConnectionNotifyReason /*reason*/, uint32 /*src*/) { switch(state){ case CONNECTED: DBG("Connected"); m_serialProvider-> sendData(7, reinterpret_cast<const uint8*>("READY.\n")); break; case CONNECTING: case DISCONNECTING: case CLEAR: case WAITING_FOR_USER: break; } } void TestShell::decodedSolicitedError( const ErrorObj& err, uint32 src, uint32 dst ) { OutputBuffer error(128); if(m_regressionTest){ error.nprintf(128, "dst: %0#10x received from src: %0#10x:\n", dst, src); error.nprintf(256, "SolicitedError: %s\n", m_errorTable->getErrorString( err.getErr() ) ); error.nprintf(32, "<end of reply>\n"); } else { error.nprintf(512, "dst: %0#10x received from src: %0#10x: " "SolicitedError: %s\n", dst, src, m_errorTable->getErrorString( err.getErr() ) ); } outputToTcp(error); } void TestShell::decodedUnsolicitedError( const ErrorObj& err, uint32 src ) { OutputBuffer error(128); if(m_regressionTest){ error.nprintf(128, "Received from \n"); error.nprintf(128, "src: %0#10x:\n", src); error.nprintf(128, "UnsolicitedError %0#x: %s\n", err.getErr(), m_errorTable->getErrorString( err.getErr() ) ); error.nprintf(200, "<end of reply>\n"); } else { error.nprintf(256, "Recieved from src: %0#10x: " "UnsolicitedError %0#x: %s\n", src, err.getErr(), m_errorTable->getErrorString( err.getErr() ) ); } outputToTcp(error); } void TestShell::decodedStartupComplete() { Module::decodedStartupComplete(); m_rawRootPublic->manageMulticast(JOIN, Module::NSCProgressMessages); m_rawRootPublic->manageMulticast(JOIN, Module::NavTaskMessages); m_rawRootPublic->manageMulticast(JOIN, Module::ErrorMessages); m_rawRootPublic->manageMulticast(JOIN, Module::LatestNews); m_rawRootPublic->manageMulticast(JOIN, ParameterProviderPublic::paramIdToMulticastGroup(ParameterEnums::NT_UserTrafficUpdatePeriod)); } void TestShell::treeIsShutdown() { delete m_parameterProvider; m_parameterProvider = NULL; delete m_nscProvider; m_nscProvider = NULL; delete m_dstProvider; m_dstProvider = NULL; delete m_navTaskProvider; m_navTaskProvider = NULL; Module::treeIsShutdown(); } CtrlHubPublic * TestShell::rootPublic() { // // FIXME - use dynamic_cast here? Check null result then. // // FIXME - inline this! // return dynamic_cast<SerialConsumerPublic *>m_rawRootPublic; // This is actually safe since the connect message is only sent // by a directly attached public class to the module. Since we // created the public interface (of type SerialProviderPublic) // we know that that is the class that created the connect message. // SerialProviderPublic in turn only accepts a // SerialConsumerPublic as parameter. return reinterpret_cast<CtrlHubPublic *>(m_rawRootPublic); } MsgBuffer * TestShell::dispatch(MsgBuffer *buf) { //DBG("TestShell::dispatch : %i\n", buf->getMsgType()); buf = m_serialConsumerDecoder.dispatch(buf, this); if (buf) buf = m_ctrlHubAttachedDecoder.dispatch(buf, this); if (buf) buf = m_parameterConsumerDecoder.dispatch(buf, this); if (buf) buf = m_nscDecoder.dispatch(buf, this); if (buf) buf = m_serialProviderDecoder.dispatch(buf, this); if (buf) buf = m_dstDecoder.dispatch(buf, this); if (buf) buf = m_navTaskDecoder.dispatch(buf, this); if (buf) buf = m_errorDecoder.dispatch(buf, this); if (buf) buf=Module::dispatch(buf); return buf; } CtrlHubAttachedPublic * TestShell::newPublicCtrlHub() { DBG("newPublicCtrlHub()\n"); return new CtrlHubAttachedPublic(m_queue); } #ifndef M_PI #define M_PI 3.14159265358979323846 #endif static const double degreeFactor = 11930464.7111; static const double radianFactor = degreeFactor * 180 / M_PI; static const double invRadianFactor = 1.0 / radianFactor; int32 mc2Lat2Nav2(int32 mc2Lat) { return int32(mc2Lat * invRadianFactor * 100000000); } int32 mc2Lon2Nav2(int32 mc2Lon) { return int32(mc2Lon * invRadianFactor * 100000000); } void TestShell::decodedReceiveData(int length, const uint8 *inData, uint32 /*src*/) { while (length) { --length; int letter = *inData++; switch (toupper(letter)) { case 'A': DBG("Got A"); { int32 data[] = {1000, 1001, 1002, 1003, 1004}; m_parameterProvider->setParam(ParameterEnums::TS_Param1, data, 5); } break; case 'B': DBG("Got B"); { m_parameterProvider->getParam(ParameterEnums::TS_Param1); m_parameterProvider->getParam(ParameterEnums::TS_Param2); m_parameterProvider->getParam(ParameterEnums::TS_Param3); m_parameterProvider->getParam(ParameterEnums::TS_Param4); } break; case 'C': DBG("Got C"); { float data[] = {5.31F, 6.1F, 2.41F, 83.3F}; m_parameterProvider->setParam(ParameterEnums::TS_Param2, data, 4); } break; case 'D': DBG("Got D"); { DBG("Will join 0x%08x", ParameterProviderPublic::paramIdToMulticastGroup(ParameterEnums::TS_Param2)); // FIXME - create a paramToMulticastGroup. m_rawRootPublic->manageMulticast(Module::JOIN, ParameterProviderPublic::paramIdToMulticastGroup(ParameterEnums::TS_Param2)); } break; case 'E': DBG("Got E -- set string "); { const char *data[] = { "Adam", "Bertil", "Caesar" }; m_parameterProvider->setParam(ParameterEnums::TS_Param3, data, 3); } break; case 'F': DBG("Got F -- displaying favorites"); m_dstProvider->getFavorites(); break; #ifdef USE_UICTRL case 'G': { DBG("Got G"); // Where am I packet. // // Serial protocol: // // uint16 id = 0xaa; // something easy to spot. // Packet* data = new Packet(WHERE_AM_I, id); // // Gui protocol: //int32 length = 6; //uint8 version = 0; // Must be 0 for the test UiCtrl // to recognize this message as // a Gui message. //uint16 packetType = (0xA0 | 0x04); // where am i. //Buffer* data = new Buffer(length); //data->writeNext8bit( version ); //data->writeNext8bit( (length >> 16) & 0xff); //data->writeNext8bit( (length >> 8) & 0xff); //data->writeNext8bit( (length) & 0xff); //data->writeNext16bit( packetType ); //StringObject city("Lund"); //StringObject street("Trolle"); wchar_t* city = new wchar_t[1024]; wcscpy(city, L"Lund"); wchar_t* street = new wchar_t[1024]; wcscpy(street, L"Trolle"); uint32 countryCode = 1; // Sweden. int32 citySelection = -1; // Do not use selection. SearchRequestMessage message( countryCode, city, citySelection, street); DataBuffer buf(1024); message.serialize(&buf); Buffer* data = new Buffer(buf.getCurrentOffset()); data->writeNextByteArray(buf.getBufferAddress(), buf.getCurrentOffset()); //byte formatType = 0; // only type //byte packetType = 0x25; // where am i //data->writeNext8bit(formatType); //data->writeNext8bit(packetType); //data->writeNext16bit(id); static_cast<SerialConsumerPublic*>(m_rawRootPublic)->receiveData(data); } break; #else case 'G': { DBG("Got G Vector map request."); const char *reqstr = reinterpret_cast<const char*>(inData); char *end = strchr(reqstr, '\n'); DBG("end: %#x", *end); inData += end - reqstr + 1; length -= end - reqstr + 1; DBG("assert(*(inData-1) == '\\n': %d", *(inData-1) == '\n'); assert(*(inData-1) == '\n'); *end = 0; DBG("vectorMapRequest"); m_nscProvider->vectorMapRequest(reqstr); break; } case 'J' : { DBG("Got J Multi Vector map request."); // J0,1000,TUD3GB-UU,T+D3GB-WU const char* reqstr = reinterpret_cast<const char*>(inData); char *end = strchr( reqstr, '\n' ); inData += end - reqstr + 1; length -= end - reqstr + 1; char* tmpPtr = NULL; uint32 startOffset = strtoul( reqstr, &tmpPtr, 0 ); reqstr = tmpPtr + 1; uint32 maxSize = strtoul( reqstr, &tmpPtr, 0 ); reqstr = tmpPtr + 1; char* data = const_cast<char*>( reqstr ); DBG("vectorMapRequest %"PRIu32" %"PRIu32, startOffset, maxSize); *end = '\0'; while ( reqstr < end ) { char* tEnd = strchr( reqstr, ',' ); if ( tEnd == NULL ) { DBG("vectorMapRequest End %s", reqstr ); reqstr = end; } else { *tEnd = '\0'; DBG("vectorMapRequest %s", reqstr ); reqstr = tEnd + 1; } } uint32 dataSize = end - data + 1; m_nscProvider->multiVectorMapRequest( startOffset, maxSize, reinterpret_cast<const uint8*>(data), dataSize ); } break; #endif case 'H': DBG("Got H -- Parameter Sync"); m_nscProvider->paramSync(); break; case 'I': { DBG("Got I -- Adding 5 random favs."); for(int i = 0; i < 5; ++i){ char name[128] = {0}; snprintf(name, sizeof(name), "Fav%d-%#x", i, rand()); Favorite fav(rand(), rand(), "Fav1", "","","",""); m_dstProvider->addFavorite(&fav); } } break; case 'K': m_nscProvider->verifyLicenseKey("0CBHSDFHDKDHASFLSDHF", "+46462882236", NULL, NULL, NULL, MAX_INT32); break; case 'L': { /* Dumpa loggar här! FIXME - XXX */ } break; #if defined(__SYMBIAN32__) && !defined(_WIN32) case 'M': { OutputBuffer out; char* tmp = GetIMEI(); out.nprintf(200, "Got IMEI result: \"%s\".", tmp ? tmp : "FAILED"); outputToTcp(out); } break; #endif case 'N': { const char* one = "calling *(uint8*)(NULL)=0; "; const char* two = "Prepare to exit!"; const char* three = "Did not exit"; DBG("Got N -- %s", one); DBG("Got N -- %s", two); OutputBuffer out; out.nprintf(200, "%s\n%s\n", one, two); outputToTcp(out); #if defined(__SYMBIAN32__) && defined(_MSC_VER) User::Leave(KErrNoMemory); #endif *(volatile uint8*)(NULL)=0; *(volatile uint8*)(NULL)=1; DBG("Got N -- %s", three); out.clear(); out.nprintf(200, three); outputToTcp(out); } break; case 'O': { DBG("Got O -- set traffic update period to 1 minute."); int32 data[] = {1}; m_parameterProvider->setParam(ParameterEnums::NT_UserTrafficUpdatePeriod, data, 1); m_parameterProvider->setParam(ParameterEnums::NT_ServerTrafficUpdatePeriod, data, 1); } break; case 'P': { DBG("Got P -- Pda search for 'Bangat'"); m_nscProvider->originalSearch("", "Bangat", 0, MAX_UINT32, 97225505, 23016529); } break; case 'Q': DBG("Got Q (Quit - start shutdown)"); { rootPublic()->startShutdownProcedure(); } break; case 'R': { DBG("Got R -- Route Request"); //barav. till bangatan uint32 lat1 = TOLAT; uint32 lon1 = TOLON; uint32 lat2 = 97244585; uint32 lon2 = 23022070; m_navTaskProvider->ntRouteToGps(lat1,lon1,lat2,lon2); break; } case 'U': { DBG("Got U -- German Route Request"); //tyska coords. uint32 lat1 = 91363287; uint32 lon1 = 23737542; uint32 lat2 = 91240692; uint32 lon2 = 23844572; uint8 heading = 180; m_nscProvider->routeToGps(lat1, lon1, heading, lat2, lon2); } break; case 'V': { const char* passwd = "STORKAFINGER"; DBG("Got W - set web password: %s", passwd); m_parameterProvider->setParam(ParameterEnums::UC_WebPasswd, &passwd, 1); } break; case '_': // input with parameters. { // search or route or whatever, with additional parameters. // assume all of the command and parameters are available.. --length; uint8 letter = toupper(*inData++); char* idCopy = new char[length+1];// allocates a little too much. char* idCopyStart = idCopy; strncpy(idCopy, reinterpret_cast<const char*>(inData), length); // may copy a little too much. idCopy[length] = '\0'; switch (letter) { case 'A': { DBG("Got A -- delete destination."); uint32 id = strtoul(idCopy, NULL, 0); m_dstProvider->removeFavorite(id); } break; case 'O': { char* server_ptui = strsep(&idCopy, "_%\n"); int32 server = strtoul(server_ptui, NULL, 0); if(server != 0){ m_parameterProvider->setParam(ParameterEnums::NT_ServerTrafficUpdatePeriod, &server, 1); } int32 user = strtoul(idCopy, NULL, 0); if(user != 0){ m_parameterProvider->setParam(ParameterEnums::NT_UserTrafficUpdatePeriod, &user, 1); } DBG("Got O -- set user_ptui to %"PRId32 " and server_ptui to %"PRId32, user, server); } break; case 'Q': { // exit immediately exit(0); } break; case 'S': { char* areaQuery = strsep(&idCopy, "½%\n"); char* itemQuery = strsep(&idCopy, "½%\n"); char* areaQueryCopy = new char[strlen(areaQuery)+1]; char* itemQueryCopy = new char[strlen(itemQuery)+1]; strcpy(areaQueryCopy, areaQuery); strcpy(itemQueryCopy, itemQuery); // maybe copy first!? m_nscProvider->originalSearch(areaQueryCopy, itemQueryCopy, 0, MAX_UINT32, 97225505, 23016529); DBG("areaQueryCopy=%s, itemQueryCopy=%s", areaQueryCopy, itemQueryCopy); delete[] areaQueryCopy; delete[] itemQueryCopy; } break; case 'R': { int32 latOrig = atol(strsep(&idCopy, "½%\n")); int32 lonOrig = atol(strsep(&idCopy, "½%\n")); int32 latDest = atol(strsep(&idCopy, "½%\n")); int32 lonDest = atol(strsep(&idCopy, "½%\n")); m_shortRouteOutput = atol(strsep(&idCopy, "½%\n")); DBG("latOrig=%"PRIu32", lonOrig=%"PRIu32", " "latDest=%"PRIu32", lonDest=%"PRIu32, latOrig, lonOrig, latDest, lonDest); m_navTaskProvider->ntRouteToGps(latDest, lonDest, latOrig, lonOrig); } break; case 'M': { char* oLat = strsep(&idCopy, "½%\n"); const int32 latOrig = atol(oLat); char* oLon = strsep(&idCopy, "½%\n"); const int32 lonOrig = atol(oLon); const int32 latDest = atol(strsep(&idCopy, "½%\n")); const int32 lonDest = atol(strsep(&idCopy, "½%\n")); m_shortRouteOutput = atol(strsep(&idCopy, "½%\n")); DBG("oLat=%s, oLon=%s", oLat, oLon); DBG("latOrig=%"PRId32", lonOrig=%"PRId32", " "latDest=%"PRId32", lonDest=%"PRId32, latOrig, lonOrig, latDest, lonDest); DBG("latOrig=%"PRId32", lonOrig=%"PRId32", " "latDest=%"PRId32", lonDest=%"PRId32, mc2Lat2Nav2(latOrig), mc2Lon2Nav2(lonOrig), mc2Lat2Nav2(latDest), mc2Lon2Nav2(lonDest)); m_navTaskProvider->ntRouteToGps(mc2Lat2Nav2(latDest), mc2Lon2Nav2(lonDest), mc2Lat2Nav2(latOrig), mc2Lon2Nav2(lonOrig)); } break; case 'W': { uint32 lat = atol(strsep(&idCopy, "½\n")); uint32 lon = atol(strsep(&idCopy, "½\n")); DBG("lat=%"PRIu32", lon=%"PRIu32, lat, lon); m_nscProvider->whereAmI(lat, lon); } break; default: letter = ((letter & 0x7f) < ' ') ? '.' : letter; DBG("Unknown command %c", letter); }; // calc remaining length inData += idCopy - idCopyStart; delete[] idCopyStart; length = 0; // xxX; // length -= inData - inDataStart + 1; } break; case ' ': // Wait. // Don't do anything but reply. if(m_regressionTest){ OutputBuffer txt(100); txt.nprintf(200, "Space command, doing nothing.\n"); txt.nprintf(200, "<end of reply>\n"); outputToTcp(txt); } break; case 'S': { DBG("Got S -- originalSearch(, Lund, Traktor, ...)"); m_nscProvider->originalSearch("Lund", "Traktor", 0, MAX_UINT32, 97225505, 23016529); } break; case 'T': { DBG("Got T -- Sync destinations"); m_syncrequestID = m_dstProvider->syncFavorites(); } break; case 'W': { using namespace MapEnums; int32 lat = 97225505; int32 lon = 23016529; DBG("Got W - sending whereAmI(lat: %"PRId32", lon: %"PRId32")", lat, lon); m_nscProvider->whereAmI(lat, lon); m_nscProvider->whereAmI(); DBG("Requesting map."); int64 data; SET(data, lon, lat); PositionItem user(MapEnums::MapUserPositionItem, lat, lon); m_nscProvider->mapRequest(BoxBox(lat + 40000, lon - 40000, lat - 40000, lon + 40000), 200, 200, 150, 150, MapEnums::GIF, 1, &user); m_nscProvider->mapRequest(DiameterBox(lat, lon, 1200*2), 288, 190, 288, 190, MapEnums::GIF, 1, &user); m_nscProvider->mapRequest(DiameterBox(lat,lon, 5000), 458, 190, 458, 190, MapEnums::GIF, 0, NULL); m_nscProvider->mapRequest(DiameterBox(MAX_INT32, MAX_INT32, 2*3000), 200, 200, 150, 150, MapEnums::GIF, 1, &user); } break; case 'X': m_nscProvider->cancelRequest(); break; case 'Y': m_nscProvider->mapRequest(BoxBox(97225505, 23016529, 97211645, 23034280), 200, 200, 100, 100); break; case 'Z': { const char* server = "oss-nav.services.wayfinder.com:80"; const char* user[] = {"iola","passwd_not_used"}; const int32 strategy[3] = {0x03a, 60*1000, 20*1000}; int32 navigatorid = 0x0beef; DBG("Got Z -- setting NSC_serverHostName to %s",server); m_parameterProvider->setParam(ParameterEnums::NSC_ServerHostname, &server); m_parameterProvider->setParam(ParameterEnums::NSC_UserAndPasswd, user, 2); m_parameterProvider->setParam(ParameterEnums::NSC_NavigatorID, &navigatorid); m_parameterProvider->setParam(ParameterEnums::NSC_CachedConnectionStrategy, strategy, 3); break; } case '\n': case '\r': break; default: { char c = *(inData - 1); c = ((c & 0x7f) < ' ') ? '.' : c; DBG("Unknown command %c", c); } break; } } } void TestShell::decodedParamNoValue(uint32 paramId, uint32 src, uint32 dst) { DBG("decodedParamNoValue(0x%08"PRIx32", 0x%08"PRIx32", 0x%08"PRIx32")", paramId, src, dst); } void TestShell::decodedParamValue(uint32 paramId, const int32 * data, int32 numEntries, uint32 src, uint32 dst) { DBG("decodedParamValue(int32)(0x%08"PRIx32", (%"PRId32"), %"PRId32", " "0x%08"PRIx32", 0x%08"PRIx32")", paramId, *data, numEntries, src, dst); for (int i=0; i<numEntries; i++) { DBG(" %2i:(%"PRId32"):%#"PRIx32, i, data[i], uint32(data[i])); } } void TestShell::decodedParamValue(uint32 paramId, const float * data, int32 numEntries, uint32 src, uint32 dst) { DBG("decodedParamValue(float)(0x%08"PRIx32", (%f), %"PRId32", " "0x%08"PRIx32", 0x%08"PRIx32")", paramId, *data, numEntries, src, dst); int i; for (i=0; i<numEntries; i++) { DBG(" %2i:(%f)", i, data[i]); } } void TestShell::decodedParamValue(uint32 paramId, const char * const * data, int32 numEntries, uint32 src, uint32 dst) { DBG("decodedParamValue(string)(0x%08"PRIx32", (%s), %"PRId32", " "0x%08"PRIx32", 0x%08"PRIx32")", paramId, *data, numEntries, src, dst); int i; for (i=0; i<numEntries; i++) { DBG(" %2i:(%s)", i, data[i]); } } void TestShell::decodedParamValue(uint32 paramId, const uint8* /*data*/, int /*size*/, uint32 /*src*/, uint32 /*dst*/) { switch(paramId){ #ifdef __VC32__ case 0: // fall through. avoids compiler warning. #endif default: DBG("Received unknown %s parameter 0x%"PRIx32, "binary block", paramId); } } void TestShell::decodedWhereAmIReply(const char* country, const char* municipal, const char* city, const char* district, const char* streetname, int32 lat, int32 lon, uint32 src, uint32 dst) { INFO("Where Am I Reply -- results on tcp port"); OutputBuffer txt(100); txt.nprintf(200, "Where Am I Reply\n"); txt.nprintf(200, "country: %s\n",country); txt.nprintf(200, "municipal: %s\n", municipal); txt.nprintf(200, "city: %s\n", city); txt.nprintf(200, "district: %s\n", district); txt.nprintf(200, "streetname: %s\n", streetname); txt.nprintf(200, "lat: %u\n", lat); txt.nprintf(200, "lon: %u\n", lon); txt.nprintf(200, "src: %#x\n", src); txt.nprintf(200, "dst: %#x\n", dst); if(m_regressionTest){ txt.nprintf(200, "<end of reply>\n"); } outputToTcp(txt); } void TestShell::decodedSyncDestinationsReply(std::vector<Favorite*>& /*favs*/, std::vector<uint32>& /*removed*/, uint32 /*src*/, uint32 /*dst*/) { } void TestShell::decodedDestRequestOk( uint32 /*src*/, uint32 dst ) { if(dst == m_syncrequestID){ m_dstProvider->getFavorites(); m_syncrequestID = 0; } // Remove any outstanding requests here. } namespace { /// A functor that outputs a textual representation of SearchAreas. class OutputSearchArea{ Buffer& b; public: OutputSearchArea(Buffer& buf):b(buf){} typedef void result_type; typedef const SearchArea* argument_type; result_type operator()(argument_type arg) { b.nprintf(200, "SearchArea :: id %12s, name: %s\n", arg->getID(), arg->getName()); } }; /// A functor that outputs a textual represntation of a /// SearchRegion. The usage is a bit arcane. class OutputSearchRegion{ Buffer& b; const SearchItem& i; const char* prefix; public: OutputSearchRegion(Buffer& buf, const SearchItem& si, const char* p): b(buf), i(si), prefix(p) {} typedef void result_type; typedef unsigned argument_type; result_type operator()(argument_type arg) { const SearchRegion& r = *(i.getRegion(arg)); b.nprintf(256, "%sSearchRegion (%u) id: %s\n" "%s name: %s\n" "%s type: %#x\n", prefix, arg, r.getId(), prefix, r.getName(), prefix, (unsigned int)(r.getType())); } }; /// A functor that outputs a textual represntation of a /// AdditionalInfo. The usage is a bit arcane. class OutputAdditionalInfo{ Buffer& b; const FullSearchItem& i; const char* prefix; public: OutputAdditionalInfo(Buffer& buf, const FullSearchItem& si, const char* p) : b(buf),i(si), prefix(p){} typedef void result_type; typedef unsigned argument_type; result_type operator()(argument_type arg) { const AdditionalInfo& a = *(i.getInfo(arg)); b.nprintf(256, "%sAdditionalInfo (%u) key: %s\n" "%s value: %s\n" "%s type: %#x\n", prefix, arg, a.getKey(), prefix, a.getValue(), prefix, (unsigned int)(a.getType())); } }; ///Iterator that lets POD objects be used in algorithms /// probably not completely implemented. template<class T> class TypeIterator{ T q; public: TypeIterator(T w) : q(w) {} T operator*() { return q; }; TypeIterator<T> operator++() { TypeIterator<T> ret(q); ++q; return ret; } TypeIterator<T>& operator++(int a) { ++q; return *this;} bool operator!=(const TypeIterator<T>& ii){return q != ii.q;} bool operator==(const TypeIterator<T>& ii){return q == ii.q;} }; /// A functor that outputs FullSearchItems. class OutputFullSearchItem{ Buffer& b; public: OutputFullSearchItem(Buffer& buf):b(buf){} typedef void result_type; typedef const FullSearchItem* argument_type; result_type operator()(argument_type arg) { b.nprintf(256, "FullSearchItem::\n name: %s\n" " id: %s\n distance: %u\n type: %#x\n" " subtype: %#x\n", arg->getName(), arg->getID(), (unsigned int)(arg->getDistance()), arg->getType(), arg->getSubType()); std::for_each(TypeIterator<unsigned>(0), TypeIterator<unsigned>(arg->noRegions()), OutputSearchRegion(b,*arg," ")); b.nprintf(256, " lat: %i\n lon: %i\n alt: %i\n" " flags: %#x\n", (int)(arg->getLat()), (int)(arg->getLon()), (int)(arg->getAlt()), (unsigned int)(arg->getSearchModuleStatusFlags())); std::for_each(TypeIterator<unsigned>(0), TypeIterator<unsigned>(arg->noAdditionalInfo()), OutputAdditionalInfo(b, *arg, " ")); } }; class ExtractId : public unary_function<const FullSearchItem*, const char*> { public: result_type operator()(argument_type arg) { return arg->getID(); } }; } void TestShell::decodedSearchReply(unsigned nAreas, const SearchArea* const *sa, unsigned nItems, const FullSearchItem* const *fsi, uint16 /*begindex*/, uint16 /*total*/, uint32 /*src*/, uint32 /*dst*/) { typedef const SearchArea*const* iterator; OutputBuffer txt(512); for_each(sa, sa + nAreas, OutputSearchArea(txt)); for_each(fsi, fsi + nItems, OutputFullSearchItem(txt)); outputToTcp(txt); if(nAreas > 1){ MatchString<SearchArea> ms("Lund", &SearchArea::getName); iterator res = find_if(sa, sa + nAreas, ms); if(res != (sa + nAreas)){ m_nscProvider->refinedSearch("Bara", (*res)->getID(), 0, MAX_UINT32, 97225505, 23016529, 0); } } if(nItems > 0){ std::vector<const char*> id(nItems, NULL); std::transform(fsi, fsi + nItems, id.begin(), ExtractId()); std::transform(fsi, fsi + nItems, id.begin(), std::const_mem_fun_t<const char*, FullSearchItem>(&FullSearchItem::getID)); m_nscProvider->requestSearchInfo(nItems, &(id.front())); } } void TestShell::decodedSearchInfoReply(uint16 num, const char* const* id, const unsigned* index, unsigned numInfo, const AdditionalInfo*const* info, uint32 /*src*/, uint32 /*dst*/) { OutputBuffer txt(1024); for(int i = 0; i < num; ++i){ txt.nprintf(64,"%d: SearchItem id: %s\n", i, id[i]); int end = (i+1) < num ? index[i+1] : numInfo; for(int j = index[i]; j < end; ++j){ txt.nprintf(128, "%d: %d: AI key : '%s'\n%d: %d: AI value: '%s'\n" "%d: %d: AI type : %#x\n", i, j, info[j]->getKey(), i, j, info[j]->getValue(), i, j, info[j]->getType()); } } outputToTcp(txt); } void TestShell::decodedRouteReply(uint32 /*src*/, uint32 /*dst*/){} void TestShell::decodedNTRouteReply(int64 routeid,uint32 /*src*/, uint32 /*dst*/) { using namespace MapEnums; OutputBuffer txt(256); txt.nprintf(256,"Received route with id: %#010x%08x %X_%X\n", HIGH(routeid), LOW(routeid), HIGH(routeid), LOW(routeid)); outputToTcp(txt); char ROUTE[64] = {0}; sprintf(ROUTE, "%#010x%08x", HIGH(routeid), LOW(routeid)); // m_nscProvider->messageRequest(GuiProtEnums::non_HTML_email, // GuiProtEnums::RouteMessage, // "[email protected]", "[email protected]", // "-- \nOla", ROUTE); RouteItem routeItem(routeid); m_nscProvider->mapRequest(RouteBox(routeid), 300, 300, 200, 200, MapEnums::GIF, 1, &routeItem); m_nscProvider->mapRequest(RouteBox(routeid), 288, 190, 188, 190, MapEnums::GIF, 1, &routeItem); m_nscProvider->mapRequest(RouteBox(routeid), 458, 190, 458, 190, MapEnums::GIF, 1, &routeItem); m_nscProvider->mapRequest(RouteBox(routeid), 176, 144, 176, 144, MapEnums::GIF, 1, &routeItem); m_nscProvider->mapRequest(RouteBox(routeid), 176, 208, 176, 208, MapEnums::GIF, 1, &routeItem); } void TestShell::decodedBinaryDownload(const uint8* /*data*/, size_t /*length*/, uint32 src, uint32 dst) { INFO("Binary Download "); INFO("Src: 0x%"PRIx32, src); INFO("Dst: 0x%"PRIx32, dst); // INFODUMP("data: ", data, length); } void TestShell::decodedBinaryUploadReply(uint32 /*src*/, uint32 /*dst*/){} const char* comStatus(ComStatus status) { switch(status){ case invalid: return "invalid"; case connecting: return "connecting"; case connected: return "connected"; case sendingData: return "sendingData"; case downloadingData: return "downloadingData"; case done: return "done"; case disconnectionError: return "disconnectionError"; case unknownError: return "unknownError"; case connectionTimedOut: return "connectionTimedOut"; case numberOfStatuses: return "numberOfStatuses"; } return "???"; } void TestShell::decodedProgressMessage(ComStatus status, GuiProtEnums::ServerActionType type, uint32 done, uint32 of, uint32 /*dst*/, uint32 /*src*/) { //DBG("Received progressMessage"); int maxlen = strlen(" disconnectionError"); // spaces wanted and added by tomas for regressiontest. OutputBuffer output(70); output.nprintf(70, "%*s : %0#4x : %u/%u\n", maxlen, comStatus(status), type, done, of); outputToTcp(output); } void TestShell::outputToTcp(OutputBuffer& txt) { m_serialProvider->sendData(txt.getLength(), txt.accessRawData(0)); } void TestShell::decodedSendData(int length, const uint8 *data, uint32 src) { DBG("TestShell::decodedSendData(%i, %p)\n", length, data); // if(m_tcpThread){ // m_tcpThread->write(data, ssize_t(length)); // int bufferSize = 1024; // if (length > bufferSize){ // length = bufferSize; // } // OutputBuffer output(bufferSize); // output.writeNextByteArray(data, length); OutputBuffer output; output.nprintf(200,"decodedSendData(%d, %p, %#0x)\n", length, data, src); outputToTcp(output); // } else { // WARN("Cannot send data while disconnected!"); // } } SerialProviderPublic * TestShell::newPublicSerial() { DBG("newPublicSerial()\n"); SerialProviderPublic* spp = new SerialProviderPublic(m_queue); return spp; } void TestShell::decodedGetFavoritesReply(vector<GuiFavorite*>& guiFavorites, uint32 /*src*/, uint32 /*dst*/ ) { OutputBuffer txt(guiFavorites.size() * 60); std::vector<GuiFavorite*>::iterator q; for(q = guiFavorites.begin(); q != guiFavorites.end(); ++q){ GuiFavorite* gfav = *q; // Favorite* fav = gfav->getFavorite(); txt.nprintf(300,">>>>\nID: %0#10x\nName: %s\n", gfav->getID(), gfav->getName()); } outputToTcp(txt); m_dstProvider->getFavoritesAllData(); OutputBuffer txt2(100); txt2.nprintf(200, "<end of reply>\n"); outputToTcp(txt2); } void TestShell::decodedGetFavoritesAllDataReply(vector<Favorite*>& favorites, uint32 /*src*/, uint32 /*dst*/ ) { OutputBuffer txt(favorites.size() * 60); std::vector<Favorite*>::iterator q; for(q = favorites.begin(); q != favorites.end(); ++q){ Favorite* fav = *q; GuiFavorite* gfav = fav->getGuiFavorite(); txt.nprintf(300,">>>>\nID: %0#10x\nName: %s\nID: %0#10x\n" "lat: %d\nlon: %d\nname: %s\nshortname: %s\n" "description: %s\ncategory: %s\niconname: %s\n" "synced: %s\n", gfav->getID(), gfav->getName(), fav->getID(), fav->getLat(), fav->getLon(), fav->getName(), fav->getShortName(), fav->getDescription(), fav->getCategory(), fav->getMapIconName(), fav->isSynced() ? "yes": "no"); delete gfav; } outputToTcp(txt); } void TestShell::decodedGetFavoriteInfoReply( Favorite* /*favorite*/, uint32 /*src*/, uint32 /*dst*/ ) { } void TestShell::decodedFavoritesChanged( uint32 /*src*/, uint32 /*dst*/ ) { } void TestShell::Point__printAsString(Point& self, OutputBuffer &txt) { txt.nprintf(300, "<point>\n"); txt.nprintf(300, "isTrackPoint: %"PRIu8",\n", self.isTrackPoint()); txt.nprintf(300, "isWayPoint: %"PRIu8", \n", self.isWaypoint()); txt.nprintf(300, "action: %"PRIu16", \n", self.getWptAction()); txt.nprintf(300, "speedLimit: %"PRIu8", \n", self.getSpeedLimit()); txt.nprintf(300, "pointId: %"PRIu16", \n", self.getPointId()); txt.nprintf(300, "getX: %"PRIu16", \n", self.getX()); txt.nprintf(300, "getY: %"PRIu16", \n", self.getY()); txt.nprintf(300, "getScaleX: %f, \n", self.getScaleX()); txt.nprintf(300, "isMiniPoint: %"PRIu8", \n", self.isMiniPoint()); txt.nprintf(300, "isMicroPoint: %"PRIu8", \n", self.isMicroPoint()); //if (self.getMeters() != MAX_UINT16) { // txt.nprintf(300, // "meters: %"PRIu16", \n", // self.getMeters()); //} if (self.isWaypoint()) { txt.nprintf(300, "text: %s, \n", self.getText()); } txt.nprintf(300, "</point>\n"); } void TestShell::decodedInvalidateRoute(bool newRouteAvailable, int64 routeid, int32 tLat, int32 lLon, int32 bLat, int32 rLon, int32 oLat, int32 oLon, int32 dLat, int32 dLon, uint32 /*src*/) { OutputBuffer txt(512); if(newRouteAvailable){ txt.nprintf(500, "New Route: %#x%x\n" "Box: (%d,%d),(%d,%d)\n" "Origin: (%d,%d)\n" "Dest: (%d,%d)\n", HIGH(routeid), LOW(routeid), tLat, lLon, bLat, rLon, oLat, oLon, dLat, dLon); } else { txt.nprintf(500,"Route invalidated, no new route\n"); } outputToTcp(txt); } void TestShell::decodedMapReply(const BoxBox& bb, uint32 realWorldWidth, uint32 realWorldHeight, uint16 imageWidth, uint16 imageHeight, enum MapEnums::ImageFormat imageType, uint32 imageBufferSize, const uint8* imageBuffer, uint32 /*dst*/) { OutputBuffer txt(600); txt.nprintf(400, "[%d, %d] [%d, %d]\nimagetype: %d\n" "bufsize: %u\nbuf: %p\n", bb.getTopLat(), bb.getLeftLon(), bb.getBottomLat(), bb.getRightLon(), imageType, imageBufferSize, imageBuffer); outputToTcp(txt); #ifndef __SYMBIAN32__ // 0123456789 char filename[] = "mapimageXX.gif"; char datafile[] = "mapdataXX.txt"; datafile[7] = filename[8] = '0' + (m_mapnum / 10); datafile[8] = filename[9] = '0' + m_mapnum - ((m_mapnum / 10) * 10); m_mapnum = (m_mapnum + 1) % 100; FILE* file = fopen(filename, "wb"); if(file){ fwrite(imageBuffer, 1, imageBufferSize, file); fclose(file); } else { txt.clear(); txt.nprintf(100, "Failed to create file %s\n", filename); outputToTcp(txt); } if((file = fopen(datafile, "w"))){ fprintf(file, "TopLat: %d\nLeftLon: %d\nBottomLat: %d\nRightLon: %d\n" "RealWorldWidth: %u m\nRealWorldHeight %u m\n" "ImageWidth: %u pixels\nImagwHeight: %u pixels\n", bb.getTopLat(), bb.getLeftLon(), bb.getBottomLat(), bb.getRightLon(), realWorldWidth, realWorldHeight, imageWidth, imageHeight); fclose(file); } else { txt.clear(); txt.nprintf(100, "Failed to create file %s\n", filename); outputToTcp(txt); } #else realWorldWidth = realWorldWidth; // To remove warnings. realWorldHeight = realWorldHeight; realWorldWidth = imageWidth; realWorldHeight = imageHeight; #endif } void TestShell::decodedVectorMapReply(const char* request, uint32 size, const uint8* data, uint32 /*dst*/) { DBG("decodedVectorMapReply, request: '%s', size: %"PRIu32"(%#"PRIx32")", request, size, size); DBGDUMP("vectormapdata", data, size); const char* tag = "VMD"; OutputBuffer txt(size + strlen(tag) + strlen(request) + 15); txt.nprintf(64,"%s:%s:%d:",tag,request,size);; for(unsigned i = 0; i < size; ++i){ txt.nprintf(3,"%02x",data[i]); } txt.nprintf(2,"\n"); outputToTcp(txt); } void TestShell::decodedMulitVectorMapReply(uint32 size, const uint8* data, uint32 /*dst*/) { DBG("decodedMultiVectorMapReply, size: %"PRIu32"(%#"PRIX32")",size,size); const char* tag = "MVMD"; OutputBuffer txt(size + strlen(tag) + 15); txt.nprintf(64,"%s:%d:",tag,size);; for(unsigned i = 0; i < size; ++i){ txt.nprintf(3,"%02x",data[i]); } txt.nprintf(2,"\n"); outputToTcp(txt); } void TestShell::decodedForceFeedMuliVectorMapReply( uint32 size, const uint8* data, uint32 dst ) { DBG( "decodedForceFeedMultiVectorMapReply, size: %"PRIu32"(%#"PRIx32")", size, size ); decodedMulitVectorMapReply( size, data, dst ); } void TestShell::decodedLatestNews(uint32 checksum, const uint8* data, unsigned length, uint32 /*src*/, uint32 /*dst*/) { DBG("decodedLatestNews"); #ifdef __linux char filename[] = "latestnews.gif"; #endif OutputBuffer txt(600); txt.nprintf(400, "New LatestNews image.\n Checksum: %#x\n Size : " "%u bytes\n" #ifdef __linux " Image saved to %s\n" #endif "", checksum, data #ifdef __linux , filename #endif ); outputToTcp(txt); #ifdef __linux FILE* fd = fopen(filename, "wb"); if(fd){ fwrite(data, 1, length, fd); fclose(fd); } #else length = length; // To remove warnings. #endif } #define ISOK(boolean) (boolean?"Ok":"not Ok") void TestShell::decodedLicenseReply(bool keyok, bool phoneok, bool regionok, bool nameok, bool emailok, GuiProtEnums::WayfinderType type, uint32 /*src*/, uint32 /*dst*/) { DBG("decodedLicenseReply"); OutputBuffer txt(400); txt.nprintf(400, "LicenseReply:\n Key: %s\n Phone: %s\n Region: %s\n" " Name: %s\n Email: %s\n" " WayfinderType: %d\n", ISOK(keyok), ISOK(phoneok), ISOK(regionok), ISOK(nameok), ISOK(emailok), int(type)); outputToTcp(txt); } } /* namespace isab */
[ [ [ 1, 1359 ] ] ]
09b0ebbd4ce912d8a5e3c776f9138950d39b9ee8
800b5ac63b77e8db5ae4d5ad29bc3e1b2ba8ad44
/battletamagotchi/inc/base/CReferenceCounter.h
cef21a8c2cac39f49329a51abc665c4b563d1814
[]
no_license
Juanma-lach/battletamagotchi
acf248e89a081b1bdcfb215ff7a635e166a61dd2
b73c0013e243fdf5a4ff12faedcafabe57f5da6d
refs/heads/master
2021-01-10T15:54:05.781544
2008-11-09T04:00:10
2008-11-09T04:00:10
44,135,556
0
0
null
null
null
null
UTF-8
C++
false
false
338
h
#ifndef __CLASS_REFERENCE_COUNTER_H_ #define __CLASS_REFERENCE_COUNTER_H_ class CReferenceCounter { int counter; protected: CReferenceCounter(){this->counter = 1; } public: void grab(void){ this->counter++; } void drop(void){ if(--this->counter == 0) delete this; } }; #endif
[ "desadoc@f8173780-9f05-11dd-9dc9-65bc890fb60a" ]
[ [ [ 1, 24 ] ] ]
10e99eef8390fed2bd95dde39e1227152b39c4eb
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/TO2/TO2InterfaceMgr.cpp
ce9fc611bbb0c610a39857701c10daa365706820
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
5,099
cpp
// ----------------------------------------------------------------------- // // // MODULE : TO2InterfaceMgr.cpp // // PURPOSE : Manage all interface related functionality // // CREATED : 4/6/99 // // (c) 1999-2001 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "TO2InterfaceMgr.h" #include "GameClientShell.h" // ----------------------------------------------------------------------- // // // ROUTINE: CTO2InterfaceMgr::CTO2InterfaceMgr // // PURPOSE: Constructor // // ----------------------------------------------------------------------- // CTO2InterfaceMgr::CTO2InterfaceMgr() : CInterfaceMgr() { } // ----------------------------------------------------------------------- // // // ROUTINE: CTO2InterfaceMgr::~CTO2InterfaceMgr // // PURPOSE: Destructor // // ----------------------------------------------------------------------- // CTO2InterfaceMgr::~CTO2InterfaceMgr() { } // ----------------------------------------------------------------------- // // // ROUTINE: CTO2InterfaceMgr::OnExitWorld() // // PURPOSE: Handle exiting a world // // ----------------------------------------------------------------------- // void CTO2InterfaceMgr::OnExitWorld() { g_pMissionText->Clear(); g_pChatInput->OnExitWorld(); g_pSubtitles->Clear(); // Now handle the base class CInterfaceMgr::OnExitWorld(); } // ----------------------------------------------------------------------- // // // ROUTINE: CTO2InterfaceMgr::OnCommandOn() // // PURPOSE: Handle command on // // ----------------------------------------------------------------------- // LTBOOL CTO2InterfaceMgr::OnCommandOn(int command) { if (g_pChatInput->IsVisible()) return LTTRUE; // Take appropriate action if (g_pRadio->IsVisible()) { if (command >= COMMAND_ID_CHOOSE_1 && command <= COMMAND_ID_CHOOSE_6 ) { uint8 nChoice = command - COMMAND_ID_CHOOSE_1; g_pRadio->Choose(nChoice); return LTTRUE; } else if (command >= COMMAND_ID_NEXT_WEAPON_1 && command <= COMMAND_ID_NEXT_WEAPON_6 ) { return LTTRUE; } } switch (command) { case COMMAND_ID_MESSAGE : case COMMAND_ID_TEAM_MESSAGE : { if (!IsTeamGameType() && (command == COMMAND_ID_TEAM_MESSAGE)) break; if (m_eGameState == GS_PLAYING && !g_pPlayerMgr->IsSpectatorMode() && !FadingScreen()) { if (m_AmmoChooser.IsOpen()) { m_AmmoChooser.Close(); } if (m_WeaponChooser.IsOpen()) { m_WeaponChooser.Close(); } g_pChatInput->Show(true, (command == COMMAND_ID_TEAM_MESSAGE) ); g_pScores->Show(false); } return LTTRUE; } break; case COMMAND_ID_RADIO : { if (m_eGameState == GS_PLAYING && (g_pGameClientShell->GetGameType() == eGameTypeCooperative || IsTeamGameType() ) ) { // [KLS 9/9/02] Made toggle and added sounds... g_pRadio->Show(!g_pRadio->IsVisible()); if (g_pRadio->IsVisible()) { g_pClientSoundMgr->PlayInterfaceSound("Interface\\Snd\\RadioOn.wav"); } else { g_pClientSoundMgr->PlayInterfaceSound("Interface\\Snd\\RadioOff.wav"); } } return LTTRUE; } break; case COMMAND_ID_COMPASS : { if (m_eGameState == GS_PLAYING && !g_pPlayerMgr->IsSpectatorMode()) { g_pCompass->Toggle(); if (g_pCompass->GetDraw()) { g_pClientSoundMgr->PlayInterfaceSound("Interface\\Snd\\CompassOn.wav"); } else { g_pClientSoundMgr->PlayInterfaceSound("Interface\\Snd\\CompassOff.wav"); } if( g_pGameClientShell->ShouldUseRadar() ) { g_pRadar->Toggle(); CUserProfile *pProfile = g_pProfileMgr->GetCurrentProfile(); if( IsMultiplayerGame() ) { if (g_pGameClientShell->GetGameType() != eGameTypeDeathmatch) { pProfile->m_bMPRadar = g_pRadar->GetDraw( ); } } else { pProfile->m_bSPRadar = g_pRadar->GetDraw( ); } pProfile->Save(); } } return LTTRUE; } break; default : { return CInterfaceMgr::OnCommandOn(command); } break; } return LTFALSE; } // ----------------------------------------------------------------------- // // // ROUTINE: CInterfaceMgr::OnKeyDown() // // PURPOSE: Handle OnKeyDown messages // // ----------------------------------------------------------------------- // LTBOOL CTO2InterfaceMgr::OnKeyDown(int key, int rep) { //handle stuff before default handling if (g_pRadio->IsVisible() && m_eGameState == GS_PLAYING && key == VK_ESCAPE) { g_pRadio->Show(false); g_pClientSoundMgr->PlayInterfaceSound("Interface\\Snd\\RadioOff.wav"); return LTTRUE; } //default handling if (CInterfaceMgr::OnKeyDown(key, rep)) return LTTRUE; //handle stuff after default handling // (nothing needed here yet) return LTFALSE; }
[ [ [ 1, 216 ] ] ]
056bbff7e08d7614843916d8da869ba7fbde6d69
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/XYLib/3D_DATA.H
70d43fb689d1c5f71772629ec27c65d372d3e38f
[]
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,523
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== // SysCAD Copyright Kenwalt (Pty) Ltd 1992,1994 #ifndef __3D_DATA_H #define __3D_DATA_H #ifndef __TRINET_H #include "trinet.h" #endif #ifdef __3D_DATA_CPP #define DllImportExport DllExport #elif !defined(XYLIB) #define DllImportExport DllImport #else #define DllImportExport #endif //============================================================================ DEFINE_TAGOBJ(C3DDataOnly); class DllImportExport C3DDataOnly : public C3DModel { DEFINE_SPARES(C3DDataOnly); public: flag AllContours; TriNet YTrinet; flag bDoYReFit; CCriticalSection m_TheLock; C3DDataOnly(pTagObjClass pClass_, pchar pTag, pTaggedObject pAttach, TagObjAttachment eAttach); virtual ~C3DDataOnly(); virtual void CopyModel(pC3DDataOnly pMd); virtual void Clear(); virtual void BuildDataDefn(DataDefnBlk & DDB); virtual double Zxy(double Xi, double Yi); virtual double Yxz(double Xi, double Zi); virtual flag ReFit(); virtual void Build(); virtual void Load(FxdEdtInfo &EI, Strng & Str); virtual long Parse(FxdEdtInfo &EI, Strng & Str); virtual long ButtonPushed(FxdEdtInfo &EI, Strng & Str); }; // =========================================================================== #undef DllImportExport #endif
[ [ [ 1, 52 ] ] ]
5537605e6f318095a0d305431236a8a772b12ceb
dde32744a06bb6697823975956a757bd6c666e87
/bwapi/SCProjects/BTHAIModule/Source/AgentManager.cpp
e60daf6b6a56f0c0385ff04960e8ea1e21d79f24
[]
no_license
zarac/tgspu-bthai
30070aa8f72585354ab9724298b17eb6df4810af
1c7e06ca02e8b606e7164e74d010df66162c532f
refs/heads/master
2021-01-10T21:29:19.519754
2011-11-16T16:21:51
2011-11-16T16:21:51
2,533,389
0
0
null
null
null
null
UTF-8
C++
false
false
7,381
cpp
#include "AgentManager.h" #include "AgentFactory.h" #include "CoverMap.h" #include "Commander.h" bool AgentManager::instanceFlag = false; AgentManager* AgentManager::instance = NULL; AgentManager::AgentManager() { } AgentManager::~AgentManager() { instanceFlag = false; for (int i = 0; i < (int)agents.size(); i++) { delete agents.at(i); } delete instance; } AgentManager* AgentManager::getInstance() { if (!instanceFlag) { instance = new AgentManager(); instanceFlag = true; } return instance; } BaseAgent* AgentManager::at(int i) { BaseAgent* agent = agents.at(i); agent->LockAgent(); return agent; } vector<BaseAgent*> AgentManager::getAgents() { return agents; } void AgentManager::release(BaseAgent* agent) { if(agent == NULL) return; agent->UnLockAgent(); } int AgentManager::size() { return agents.size(); } BaseAgent* AgentManager::getAgent(int unitID) { BaseAgent* agent = NULL; for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->getUnitID() == unitID) { agent = agents.at(i); break; } } return agent; } BaseAgent* AgentManager::getAgent(UnitType type) { for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->isOfType(type) && agents.at(i)->isAlive()) { return agents.at(i); } } return NULL; } BaseAgent* AgentManager::getCombatAgent(UnitType type) { for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->isOfType(type) && agents.at(i)->isAlive() && (agents.at(i)->isAttacking() || agents.at(i)->isDefending())) { return agents.at(i); } } return NULL; } BaseAgent* AgentManager::getClosestBase(TilePosition pos) { return getClosestAgent(pos, Broodwar->self()->getRace().getCenter()); } BaseAgent* AgentManager::getClosestAgent(TilePosition pos, UnitType type) { BaseAgent* agent = NULL; double bestDist = -1; for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->isOfType(type) && agents.at(i)->isAlive()) { double dist = agents.at(i)->getUnit()->getDistance(Position(pos)); if (bestDist < 0 || dist < bestDist) { bestDist = dist; agent = agents.at(i); } } } return agent; } void AgentManager::addAgent(Unit* unit) { bool found = false; for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->matches(unit)) { found = true; break; } } if (!found) { BaseAgent* newAgent = AgentFactory::getInstance()->createAgent(unit); agents.push_back(newAgent); if (newAgent->isBuilding()) { CoverMap::getInstance()->addConstructedBuilding(unit); } if (newAgent->isUnit()) { Commander::getInstance()->unitCreated(newAgent); } } } void AgentManager::addMorphAgent(Unit *unit) { // Remove old agent. for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->matches(unit)) { removeAgent(unit); } } // Create new... yeah! BaseAgent* newAgent = AgentFactory::getInstance()->createAgent(unit); agents.push_back(newAgent); if (newAgent->isBuilding()) { CoverMap::getInstance()->addConstructedBuilding(unit); } if (newAgent->isUnit()) { Commander::getInstance()->unitCreated(newAgent); } } void AgentManager::removeAgent(Unit* unit) { for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->matches(unit)) { if (agents.at(i)->isBuilding()) { CoverMap::getInstance()->buildingDestroyed(unit); } agents.at(i)->destroyed(); Commander::getInstance()->unitDestroyed(agents.at(i)); return; } } } void AgentManager::cleanup() { //Step 1. Check if any agent is under attack. If so, dont cleanup since //it might cause a Nullpointer. for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->isUnderAttack()) { return; } } //Step 2. Do the cleanup. int cnt = 0; int oldSize = (int)agents.size(); for (int i = 0; i < (int)agents.size(); i++) { if (!agents.at(i)->isAlive()) { agents.at(i)->LockAgent(); delete agents.at(i); agents.erase(agents.begin() + i); cnt++; i--; } } int newSize = (int)agents.size(); if (cnt > 0) { Broodwar->printf("[AgentManager] removed %d inactive agents %d->%d", cnt, oldSize, newSize); } } void AgentManager::computeActions() { for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->isAlive()) { agents.at(i)->computeActions(); } } } int AgentManager::getNoWorkers() { int wCnt = 0; for (int i = 0; i < (int)agents.size(); i++) { BaseAgent* agent = agents.at(i); if (agent != NULL && agent->isWorker() && agent->isAlive()) { wCnt++; } } return wCnt; } BaseAgent* AgentManager::getWorkerAt(int i) { int nWorkerPos = 0; for (int i = 0; i < (int)agents.size(); i++) { BaseAgent* agent = agents.at(i); if (agent != NULL && agent->isAlive() && agent->isWorker()) { if(nWorkerPos == i) { agent->LockAgent(); return agent; } nWorkerPos++; } } return NULL; } BaseAgent* AgentManager::getFreeWorker() { for (int i = 0; i < (int)agents.size(); i++) { BaseAgent* agent = agents.at(i); if (agent != NULL && agent->isAlive() && agent->isWorker()) { if (agent->getUnit()->isIdle() || (agent->getUnit()->isGatheringMinerals() && !agent->getUnit()->isCarryingMinerals())) { agent->LockAgent(); return agent; } } } return NULL; } BaseAgent* AgentManager::findClosestFreeWorker(TilePosition pos) { BaseAgent* bestAgent = NULL; double bestDist = -1; for (int i = 0; i < (int)getNoWorkers(); i++) { BaseAgent* agent = getWorkerAt(i); if (agent != NULL && agent->isFreeWorker()) { double cDist = agent->getUnit()->getDistance(Position(pos)); if (bestDist < 0 || cDist < bestDist) { bestDist = cDist; bestAgent = agent; } } release(agent); } return bestAgent; } bool AgentManager::isAnyAgentRepairingThisAgent(BaseAgent* repairedAgent) { for (int i = 0; i < (int)agents.size(); i++) { BaseAgent* agent = agents.at(i); if (agent->isAlive() && agent->isWorker()) { Unit* unit = agent->getUnit(); if (unit->isRepairing() || unit->isConstructing()) { if (unit->getTarget() != NULL && unit->getTarget()->getID() == repairedAgent->getUnitID()) { //Already have an assigned builder return true; } } } } return false; } int AgentManager::countNoUnits(UnitType type) { int cnt = 0; for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->isAlive()) { if (agents.at(i)->isOfType(type)) { cnt++; } } } return cnt; } int AgentManager::countNoBases() { int cnt = 0; for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->isAlive()) { if (agents.at(i)->getUnit()->getType().isResourceDepot()) { cnt++; } } } return cnt; } int AgentManager::countNoAttackingUnits() { int cnt = 0; for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->isAlive()) { if (agents.at(i)->isAttacking()) { cnt++; } } } return cnt; } int AgentManager::countNoDefendingUnits() { int cnt = 0; for (int i = 0; i < (int)agents.size(); i++) { if (agents.at(i)->isAlive()) { if (agents.at(i)->isDefending()) { cnt++; } } } return cnt; }
[ "rymdpung@.(none)", "[email protected]" ]
[ [ [ 1, 125 ], [ 148, 323 ] ], [ [ 126, 147 ] ] ]
9706886b697e88cf74c132048106ccb4b3625b2e
f6c641b102ebbffb48e93dd554a0b7eb7e639be7
/Source/Base/Base Graphics Library/Texture2D.hpp
09f68d817460c16d0700d1d228b7fb7823dd212d
[]
no_license
ZAsprose/rtrt-on-gpu
e3ca4921a3429cbc72e0cee8afd946200b83573d
4949e373c273f963467658ca25d39244da7fb4e6
refs/heads/master
2021-01-10T14:42:45.293509
2010-08-25T18:37:19
2010-08-25T18:37:19
53,016,647
0
0
null
null
null
null
UTF-8
C++
false
false
3,292
hpp
/* ----------------------------------------------------------------------------- | B A S E G R A P H I C S L I B R A R Y | ----------------------------------------------------------------------------- Copyright (c) 2009 - 2010 Denis Bogolepov ( denisbogol @ gmail.com ) This library 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 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _TEXTURE_2D_ #define _TEXTURE_2D_ #include "WrapMode.hpp" #include "FilterMode.hpp" #include "TextureData2D.hpp" namespace graphics { class Texture2D { public: /************************************************************************/ /* PUBLIC FIELDS */ /************************************************************************/ WrapMode WrapMode; FilterMode FilterMode; //------------------------------------------------------------------------ TextureData2D * Data; /************************************************************************/ /* CONSTRUCTOR AND DESTRUCTOR */ /************************************************************************/ Texture2D ( GLenum unit = 0, TextureData2D * data = NULL, GLenum target = GL_TEXTURE_RECTANGLE_ARB ); ~Texture2D ( void ); /************************************************************************/ /* PUBLIC METHODS */ /************************************************************************/ void Setup ( void ); void Update ( void ); //------------------------------------------------------------------------ void Bind ( void ); void Unbind ( void ); //------------------------------------------------------------------------ GLenum Unit ( void ) const; GLenum Target ( void ) const; GLuint Handle ( void ) const; private: /************************************************************************/ /* PRIVATE FIELDS */ /************************************************************************/ GLenum fUnit; GLenum fTarget; GLuint fHandle; }; } #endif
[ [ [ 1, 94 ] ] ]
1010dcfa74fb4ba95819b6a44d8fa76909f5ff6b
3d7fc34309dae695a17e693741a07cbf7ee26d6a
/aluminizer/FPGA_page.cpp
58317a09ab52e120ec2258422bec68f72a27879a
[ "LicenseRef-scancode-public-domain" ]
permissive
nist-ionstorage/ionizer
f42706207c4fb962061796dbbc1afbff19026e09
70b52abfdee19e3fb7acdf6b4709deea29d25b15
refs/heads/master
2021-01-16T21:45:36.502297
2010-05-14T01:05:09
2010-05-14T01:05:09
20,006,050
5
0
null
null
null
null
UTF-8
C++
false
false
1,939
cpp
#ifdef PRECOMPILED_HEADER #include "common.h" #endif #include "FPGA_connection.h" #include "FPGA_TCP.h" #include "FPGA_page.h" #include "ExperimentPage.h" #include "AluminizerApp.h" std::string getTcpStatusText(unsigned s) { switch (s) { case QAbstractSocket::UnconnectedState: return "Unconnected"; case QAbstractSocket::HostLookupState: return "HostLookup"; case QAbstractSocket::ConnectingState: return "Connecting"; case QAbstractSocket::ConnectedState: return "Connected"; case QAbstractSocket::BoundState: return "Bound"; case QAbstractSocket::ClosingState: return "Closing"; case QAbstractSocket::ListeningState: return "Listening"; } return ""; } FPGA_page::FPGA_page(const std::string& sPageName, ExperimentsSheet* pSheet, unsigned page_id) : FPGA_GUI(sPageName, pSheet, page_id), server("Server", &m_TxtParams, "", &m_vParameters, RP_FLAG_READ_ONLY), port("Port", &m_TxtParams, "0", &m_vParameters, RP_FLAG_READ_ONLY), status_text("Status", &m_TxtParams, "Disconnected", &m_vParameters, RP_FLAG_READ_ONLY), Latency("Latency [ms]", &m_TxtParams, "0", &m_vParameters, RP_FLAG_READ_ONLY) { SafeRecalculateParameters(); } FPGA_page::~FPGA_page() { } bool FPGA_page::RecalculateParameters() { bool bChanged = false; bChanged |= server.SetValue(theApp->fpga->server_name); bChanged |= port.SetValue(theApp->fpga->port); bChanged |= status_text.SetValue(getTcpStatusText(theApp->fpga->fpga_tcp->socket_state())); return bChanged; } void FPGA_page::AddAvailableActions(std::vector<std::string>* p) { FPGA_GUI::AddAvailableActions(p); p->push_back("TEST LATENCY"); } void FPGA_page::on_action(const std::string& s) { if (s == "TEST LATENCY") { Latency.SetValue(theApp->fpga->measure_latency() * 1000); Latency.PostUpdateGUI(); return; } FPGA_GUI::on_action(s); }
[ "trosen@814e38a0-0077-4020-8740-4f49b76d3b44" ]
[ [ [ 1, 68 ] ] ]
c98cafdde634d63b82509991f5ad02133c10b99a
9e590d76ad900ef940486ccda8633bd79c6acd4e
/ki2key/core/Core.hpp
5808b0472460484ca3c230a4b2e1ea940b51ade4
[ "BSD-2-Clause" ]
permissive
szk/Ki2Key
f66ec830e61d14ddf3c42ac469cd88da2dcf9e03
9498f32df419f94acbbecdffefbef25dc083eecf
refs/heads/master
2020-05-16T23:11:19.061205
2011-12-07T15:45:21
2011-12-07T15:45:21
1,168,628
0
0
null
null
null
null
UTF-8
C++
false
false
2,948
hpp
/* * Copyright (c) 2011, Tatsuhiko Suzuki * 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. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef CORE_HPP__ #define CORE_HPP__ #include "Common.hpp" #include "view/View.hpp" #include "MsgSender.hpp" #include "Setting.hpp" #include "sensor/Sensor.hpp" #include "mode/IRHandMode.hpp" #include "mode/IRTileMode.hpp" class Core { public: Core(void); virtual ~Core(void); const bool init(View* view_, Setting* setting_, MsgSender* sender_); const Int32 tick_with_wait(void); const Int32 finish(void); const bool activate_sensor(const bool on_); // on setting const Str add_action(void); const bool edit_action(const Str& gesture_, const ActionItem itm_, const Str& content_, const uInt32 opt_value_ = 0); const size_t get_action_size(void) const; const Action& get_action(const size_t idx_) const; const Action& get_action(const Str& gesture_) const; const bool remove_action(const Str& gesture_); void clear_cmd(void); Str pop_cmd(void); const bool is_cmd_empty(void); #ifdef DUMMY_DEVICE void set_device(const DevCmd cmd_) { sensor.set_device(cmd_); } #endif private: Sensor sensor; View* view; MsgSender* sender; Setting* setting; ActMap acts; Action act_invalid; UsrList users; std::stack<Str> cmd_stack; Str empty_str; }; #endif
[ [ [ 1, 83 ] ] ]