blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
8f8c09d69907c3c6e6ee795deb168d2af4c7e6e8
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak.Toolkit/ChangePropertyCommand.h
252daf0326c975adf90fc1d8efcbce14449a9ceb
[]
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
1,287
h
#pragma once #ifndef __HALAK_TOOLKIT_CHANGEPROPERTYCOMMAND_H__ #define __HALAK_TOOLKIT_CHANGEPROPERTYCOMMAND_H__ # include <Halak.Toolkit/FWD.h> # include <Halak.Toolkit/AnyPtr.h> # include <Halak/RestorableCommand.h> # include <Halak/Any.h> namespace Halak { namespace Toolkit { class ChangePropertyCommand : public RestorableCommand { public: ChangePropertyCommand(const AnyPtr& target, const PropertyInfo* propertyInfo, const Any& value); virtual ~ChangePropertyCommand(); virtual void Execute(); virtual void Undo(); const AnyPtr& GetTargetPointee() const; const PropertyInfo* GetPropertyInfo() const; const Any& GetOldValue() const; const Any& GetNewValue() const; private: AnyPtr target; const PropertyInfo* propertyInfo; Any newValue; Any oldValue; private: friend void __Startup__(); static void __Startup__(); }; } } #endif
[ [ [ 1, 41 ] ] ]
35f922018df75a27540b050fa3b633f31b08f792
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/compatanalysercmd/headeranalyser/src/CommandFile.cpp
5be79af75bca2ee7c7dd54fb0d5b02a5c38da086
[]
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
5,144
cpp
/* * Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include "CmdGlobals.h" #ifdef __WIN__ #pragma warning(disable:4786) #endif #include <iostream> #include <fstream> #include <vector> #include "CommandFile.h" #include "HAException.h" #include "Utils.h" using namespace std; // ---------------------------------------------------------------------------- // CommandFile::CommandFile // File name is gien as parameter // // ---------------------------------------------------------------------------- // CommandFile::CommandFile(string aFilename) : iCmdBufLen(0), iCmdBuf(NULL) { iFilename = aFilename; } // ---------------------------------------------------------------------------- // CommandFile::CommandFile // ---------------------------------------------------------------------------- // CommandFile::~CommandFile() { if (iCmdBuf != NULL) { for (unsigned int i = 0; i < iCmdBufLen; i++) { delete [] iCmdBuf[i]; } delete [] iCmdBuf; iCmdBuf = NULL; } } // ---------------------------------------------------------------------------- // CommandFile::getCommandBuffer // ---------------------------------------------------------------------------- // char** CommandFile::getCommandBuffer() { readCommandFile(iFilename); return iCmdBuf; } // ---------------------------------------------------------------------------- // CommandFile::commandBufferLength // // ---------------------------------------------------------------------------- // size_t CommandFile::commandBufferLength() { return iCmdBufLen; } // ---------------------------------------------------------------------------- // CommandFile::readCommandFile // Reads parameters from the command file. // ---------------------------------------------------------------------------- // void CommandFile::readCommandFile(string filename) { #if ( defined(_DEBUG) || defined(DEBUG) ) && !defined(NO_DBG) cout << "Reading command file\n"; #endif ifstream input(filename.c_str(), ios::in); if (!input.is_open()) { throw HAException("Cannot open command file"); } char c; string str; unsigned long linecount = 1; bool careForSpace = true; bool strSpace = false; bool whitespace = true; vector<string> parmlist; parmlist.push_back("padding"); while (input.get(c)) { if (c == ' ' && careForSpace == true) { if (whitespace == false) { parmlist.push_back(str); } str = ""; whitespace = false; careForSpace = false; }else if (c == ' ' && strSpace == false) { }else if (c == '\\' || c == '/') { str += DIR_SEPARATOR; }else if (c == '"') { if (strSpace == false) { careForSpace = false; strSpace = true; } else { careForSpace = true; strSpace = false; } whitespace = false; }else if (c != '\n') { if (careForSpace == false && strSpace == false) { careForSpace = true; } str += c; whitespace = false; } else { if (strSpace == true) { string line; ltoa(linecount, line, 10); throw HAException("Syntax error: New line has come before ending quotation mark(\"). Line: " + line); } if (str.length() != 0) { parmlist.push_back(str); } linecount++; str = ""; whitespace = true; } } if (str.length() != 0) { parmlist.push_back(str); } // Store parameter information size_t elementcount = parmlist.size(); iCmdBufLen = elementcount; if (iCmdBuf) { delete iCmdBuf; iCmdBuf = NULL; } iCmdBuf = new char*[elementcount]; // Copy the parameter list from vector to char** // (in order to be compatible with CommandLine::parse()) for (unsigned int i = 0; i < parmlist.size(); i++) { size_t charcount = parmlist.at(i).length(); iCmdBuf[i] = new char[charcount+1]; const char* cbuf = parmlist.at(i).c_str(); unsigned int j = 0; for(j = 0; j < charcount; j++) { iCmdBuf[i][j] = cbuf[j]; } iCmdBuf[i][j] = '\0'; } }
[ "none@none" ]
[ [ [ 1, 193 ] ] ]
9e4c85bae05efb546624b814f16db1b54bd8a851
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/WireKeys/WireKeys.cpp
e89a2a094a794821eab6b34a2e51ff500d89ad82
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
WINDOWS-1251
C++
false
false
21,319
cpp
// #include <crtdbg.h> #include "stdafx.h" #include "_common.h" #include "_externs.h" #include "DLG_Chooser.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #pragma comment(exestr,"Copyright ©2002-2007 WiredPlane.com. All rights reserved. Build time:"__TIMESTAMP__) const char* szBuildDate=__TIMESTAMP__; CSettings objSettings; AppMainDlg* pMainDialogWindow=NULL; extern int iGlobalState; extern CCriticalSection pCahLock; // ///////////////////////////////////////////////////////////////////////////// // AppMainApp BEGIN_MESSAGE_MAP(AppMainApp, CWinApp) //{{AFX_MSG_MAP(AppMainApp) //}}AFX_MSG_MAP ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() int GetWinAmpPlStatus(HWND hWin=0); void FillSplashParams(const char* szTitle, CSplashParams& par); void ShowWinampTitle(BOOL bOnlyOSD) {_XLOG_ static HWND hwndWinamp=NULL; if(hwndWinamp==NULL || !IsWindow(hwndWinamp)){_XLOG_ hwndWinamp=::FindWindow("Winamp v1.x",NULL); } if(hwndWinamp==NULL){_XLOG_ return; } char szNewTitle[256]=""; ::GetWindowText(hwndWinamp,szNewTitle,sizeof(szNewTitle)); if(strlen(szNewTitle)==0){_XLOG_ return; } CString sTitle=szNewTitle; // Дальше... ReparseWinampTitle(sTitle,hwndWinamp,!bOnlyOSD); if(objSettings.lShowWTitInTooltip && !bOnlyOSD){_XLOG_ ShowBaloon(sTitle,objSettings.lStripAllWinampTitle?"":CString("WinAmp: ")+_l("Song"),objSettings.lWinampOSDTime*1000); }else{_XLOG_ CSplashParams* par=new CSplashParams; FillSplashParams(_l("WinAmp controls"),*par); if(objSettings.lStripAllWinampTitle){_XLOG_ par->szText=sTitle; }else{_XLOG_ par->szText=Format("%s: %s",_l("Song"),sTitle); } FORK(ShowWTitleSplash,par); } } CNewVersionChecker& GetVersionChecker(); DWORD WINAPI CheckNewVersionInThread(LPVOID p) {_XLOG_ //Sleep(1000*60*120);// Через 2 часа работы проверяем GetVersionChecker().SetTraits(); StartCheckNewVersion(objSettings.lDaysBetweenChecks); return 0; } //---------------------------- extern DWORD dwClipAttachTime; BOOL bOnScreenSaverDone=FALSE; DWORD PriorityClasses[]= {NORMAL_PRIORITY_CLASS, HIGH_PRIORITY_CLASS, REALTIME_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, IDLE_PRIORITY_CLASS}; DWORD PriorityClassesNT[]= {ABOVE_NORMAL_PRIORITY_CLASS, HIGH_PRIORITY_CLASS, REALTIME_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, IDLE_PRIORITY_CLASS}; #define TIMER_SETTIMER_TICK 60*30*1000 #define TIMER_BOOST_TICK 3000 #define TIMER_CPUUSAGE_TICK 1000 #define TIMER_WAMPT_TICK 5000 #define TIMER_WINAMP_FAST 900 #define TIMER_LANGINDIC 500 void OnAfterScreensaver(BOOL); BOOL OnBeforeScreensaver(BOOL); DWORD WINAPI GlobalOnTimer(LPVOID pValue) {_XLOG_ TRACETHREAD; DWORD dwLastActivePPR=0; DWORD dwLastActivePID=0; DWORD dwSleepTime=TIMER_SETTIMER_TICK; HWND hLastActiveApp=NULL; // Ставим случ. дату чтобы в первый раз сработала проверка COleDateTime dtLast=COleDateTime(1900,01,01,00,00,00); int dtLastDay=-1; BOOL bNTFeatures=IsRealNT(); DWORD dwStartTickCount=GetTickCount(); while(pMainDialogWindow){_XLOG_ if(pMainDialogWindow->iRunStatus==-2){_XLOG_ return 0; } if(pMainDialogWindow->iRunStatus!=1){_XLOG_ Sleep(500); continue; } static long lScrSaveInit=0; if(lScrSaveInit==0){_XLOG_ ::SetThreadPriority(::GetCurrentThread(),THREAD_PRIORITY_LOWEST); lScrSaveInit=1; if(objSettings.lSetRandomScreensaver){_XLOG_ wk.InitScreenSaverPaths(); } objSettings.sJpgEditorDef=GetExtensionAssociatedAction("jpg",""); if(objSettings.sJpgEditorDef==""){_XLOG_ objSettings.sJpgEditorDef=GetExtensionAssociatedAction("bmp",""); } // Переаттач спая буфера if(dwClipAttachTime && GetTickCount()-dwClipAttachTime>5*60000){ pMainDialogWindow->OnReattachClips(); } //борьба с видеорежимами CVideoModes::GetAvailableVideoModes(objSettings.videoModes); {// Сокращенный список разрешений CVideoMode mdTmp; objSettings.videoModesShort.RemoveAll(); if(objSettings.lStartupDesktop==0){_XLOG_ CVideoModes::GetCurrentVideoMode(objSettings.lResolutions[0]); } for(int i=objSettings.videoModes.GetSize()-1;i>=0;i--){_XLOG_ if(objSettings.lUseAllVModes){_XLOG_ objSettings.videoModes[i].dwAdditionalData=i; objSettings.videoModesShort.Add(objSettings.videoModes[i]); }else{_XLOG_ CVideoMode& mdCur=objSettings.videoModes[i]; if(mdTmp.m_dwWidth!=mdCur.m_dwWidth || mdTmp.m_dwHeight!=mdCur.m_dwHeight){_XLOG_ mdTmp.m_dwWidth=mdCur.m_dwWidth; mdTmp.m_dwHeight=mdCur.m_dwHeight; mdCur.dwAdditionalData=i; objSettings.videoModesShort.Add(mdCur); } } } // Сортируем videoModesShort чтобы с более высокой частотой шли первыми for(int iSort1=0;iSort1<objSettings.videoModesShort.GetSize()-1;iSort1++){_XLOG_ for(int iSort2=iSort1+1;iSort2<objSettings.videoModesShort.GetSize()-1;iSort2++){_XLOG_ if(objSettings.videoModesShort[iSort1].m_dwHeight==objSettings.videoModesShort[iSort2].m_dwHeight && objSettings.videoModesShort[iSort1].m_dwWidth==objSettings.videoModesShort[iSort2].m_dwWidth){_XLOG_ if(objSettings.videoModesShort[iSort1].m_dwFrequency*1000+objSettings.videoModesShort[iSort1].m_dwBitsPerPixel>objSettings.videoModesShort[iSort2].m_dwFrequency*1000+objSettings.videoModesShort[iSort2].m_dwBitsPerPixel){_XLOG_ CVideoMode mT=objSettings.videoModesShort[iSort1]; objSettings.videoModesShort[iSort1]=objSettings.videoModesShort[iSort2]; objSettings.videoModesShort[iSort2]=mT; } } } } } ::SetThreadPriority(::GetCurrentThread(),THREAD_PRIORITY_NORMAL); } //////////////////////////////////////////////// // Проверяем dwSleepTime=TIMER_SETTIMER_TICK; DWORD dwCurTick=GetTickCount(); //////////////////////////////////////////////// // Обновление загрузки проца if(objSettings.lShowCPUInTrayIcon>0){_XLOG_ static DWORD dwPrevTime=0; // Так как сюда можем и чаще попадать... if(long(dwCurTick-dwPrevTime)>=1000*objSettings.lShowCPUInTraySecs){_XLOG_ dwPrevTime=dwCurTick; pMainDialogWindow->SetWindowIcon(); if(objSettings.lShowCPUInTraySecs==0){_XLOG_ objSettings.lShowCPUInTraySecs=5; } } dwSleepTime=1000*objSettings.lShowCPUInTraySecs; } if(objSettings.lShowDateInTrayIcon==3 && pMainDialogWindow){_XLOG_ if(dwSleepTime>TIMER_LANGINDIC){_XLOG_ dwSleepTime=TIMER_LANGINDIC; } pMainDialogWindow->PostMessage(LANG_CHANGE,99,99); } if(objSettings.lSetRandomScreensaver){_XLOG_ if(dwSleepTime>TIMER_WAMPT_TICK){_XLOG_ dwSleepTime=TIMER_WAMPT_TICK; } if(isScreenSaverActive() && objSettings.lIsScreensaverRandomized==0){_XLOG_ RandomizeScreensaver(); }else{_XLOG_ objSettings.lIsScreensaverRandomized=0; } } if(objSettings.lStopWinAmpOnLock || objSettings.sAppToRWS!="" || objSettings.lSetRandomScreensaver){_XLOG_ if(dwSleepTime>TIMER_WAMPT_TICK){_XLOG_ dwSleepTime=TIMER_WAMPT_TICK; } if((isScreenSaverActive() || isWindowStationLocked()) && !bOnScreenSaverDone){_XLOG_ OnBeforeScreensaver(TRUE); } } if(objSettings.lLogCPUHungers){ static DWORD dwLast=GetTickCount(); if(GetTickCount()-dwLast>10000){ __FLOWLOG; CCSLock lpc(&pCahLock,1); dwLast=GetTickCount(); int d=int(GetCPUTimesPercents()); if(d>80){ __FLOWLOG; // Кто жрет наши ресурсы??? CString s; s+="\n============ "; s+=DateFormat(COleDateTime::GetCurrentTime(),FALSE)+" "+TimeFormat(COleDateTime::GetCurrentTime(),TRUE,FALSE); s+="============\n"; EnumProcesses(1); long iInd=-1; LONGLONG lMax=-1; for(int i=0; i<GetProccessCash().GetSize();i++){_XLOG_ if(GetProccessCash()[i].sProcExePath!="" && GetProccessCash()[i].sProcName!="Idle" && GetProccessCash()[i].lProcent>0){_XLOG_ s+=Format("%s, CPU=%02f Kernel=%02f User=%02f\n",GetProccessCash()[i].sProcExePath, double(GetProccessCash()[i].lProcent)/100000.0f,double(GetProccessCash()[i].KernelTime)/100000.0f,double(GetProccessCash()[i].UserTime)/100000.0f); } } AppendFile(objSettings.sLogCPUHungers,s); } } } // Сброс клавиатурного буфера // Раз в 2 секунды {_XLOG_ static DWORD dwPrevTime=0; if(long(dwCurTick-dwPrevTime)>=1000*2){_XLOG_ dwPrevTime=dwCurTick; // Восстановление после скринсейвера if(bOnScreenSaverDone){_XLOG_ if(dwSleepTime>TIMER_WAMPT_TICK){_XLOG_ dwSleepTime=TIMER_WAMPT_TICK; } if(!isScreenSaverActive() && !isWindowStationLocked()){_XLOG_ OnAfterScreensaver(TRUE); } } if(!isWin98()){_XLOG_ BOOL bNeedDrop=0; static CString sLastDesk="???"; HDESK desktop = OpenInputDesktop(0,FALSE,DESKTOP_READOBJECTS); if(desktop){_XLOG_ char szData[256]=""; DWORD dwLen=0; GetUserObjectInformation(desktop, UOI_NAME, szData, sizeof(szData), &dwLen); CString sDesk=szData; CloseDesktop(desktop); if(sLastDesk!=sDesk){_XLOG_ TRACE2("New desktop!! %s->%s\n",sLastDesk,sDesk); sLastDesk=sDesk; bNeedDrop=1; } }else if(sLastDesk!=""){_XLOG_ TRACE1("New desktop!! %s->''\n",sLastDesk); sLastDesk=""; bNeedDrop=1; } if(bNeedDrop){_XLOG_ WKIHOTKEYS_ResetKB(); } } } } //////////////////////////////////////////////// // Смена заголовка винампа if(pMainDialogWindow && objSettings.lCatchWinampTitle){_XLOG_ static HWND hwndWinamp=NULL; if(hwndWinamp==NULL || !IsWindow(hwndWinamp)){_XLOG_ hwndWinamp=::FindWindow("Winamp v1.x",NULL); } if(hwndWinamp){_XLOG_ static CString sPrevTitle="_WINAMP отдыхает_"; if(dwSleepTime>TIMER_WAMPT_TICK){_XLOG_ dwSleepTime=TIMER_WAMPT_TICK; } CString sNewTitle; char szNewTitle[256]=""; ::GetWindowText(hwndWinamp,szNewTitle,sizeof(szNewTitle)); sNewTitle=szNewTitle; if(GetWinAmpPlStatus()==0){_XLOG_ // Если заголовок скроллится - отсекаем это! if(sPrevTitle.Find(sNewTitle.Left(20))==-1){_XLOG_ ShowWinampTitle(FALSE); }else{_XLOG_ dwSleepTime=TIMER_WINAMP_FAST; } } sPrevTitle=sNewTitle; } } //////////////////////////////////////////////// // Наступление нового дня? COleDateTime dt=COleDateTime::GetCurrentTime(); if(dtLastDay==-1 || ((dt.GetHour()>11) && (dt.GetDay()!=dtLast.GetDay() || dt.GetMonth()!=dtLast.GetMonth() || dt.GetYear()!=dtLast.GetYear()))){_XLOG_ if(objSettings.iLikStatus!=2){_XLOG_ UpdateTrialityStatus(objSettings.sLikUser,objSettings.sLikKey); } if(objSettings.lCheckForUpdate){_XLOG_ CheckNewVersionInThread(0); } dtLast=dt; if(dtLastDay==-1){_XLOG_ dtLastDay=dt.GetDay(); } // Обновляем иконку, anyway if(pMainDialogWindow){_XLOG_ pMainDialogWindow->PostMessage(UPDATE_ICON,0,0); } } if(dt.GetDay()!=dtLastDay){_XLOG_ if(objSettings.lShowDateInTrayIcon>0){_XLOG_ pMainDialogWindow->PostMessage(UPDATE_ICON,0,0); } dtLastDay=dt.GetDay(); } CheckAndDisablePayFeaturesIfNeeded(); //////////////////////////////////////////////// // Ждем до следующей проверки WaitForSingleObject(objSettings.hTimerEvent,dwSleepTime); }; if(dwLastActivePID!=0){_XLOG_ HANDLE hLastActiveProc=::OpenProcess(PROCESS_SET_INFORMATION,FALSE,dwLastActivePID); if (!( (hLastActiveProc) == NULL || (hLastActiveProc) == INVALID_HANDLE_VALUE )){_XLOG_ SetPriorityClass(hLastActiveProc,dwLastActivePPR); CloseHandle(hLastActiveProc); } } iGlobalState=4; return 0; } ///////////////////////////////////////////////////////////////////////////// // AppMainApp construction AppMainApp::AppMainApp() {_XLOG_ } int AddBitmapToIList(CImageList& list, UINT bmpID) {_XLOG_ #ifdef GDI_NOICONS return 0; #endif CBitmap* bmp=new CBitmap; bmp->LoadBitmap(bmpID); int iRes=list.Add(bmp, RGB(255, 255, 255)); delete bmp; return iRes; } ///////////////////////////////////////////////////////////////////////////// // The one and only AppMainApp object AppMainApp theApp; ///////////////////////////////////////////////////////////////////////////// // AppMainApp initialization CRect AppMainApp::rDesktopRECT; CRect AppMainApp::rFakedRect; CWnd* AppMainApp::m_pFakeWnd=NULL; UINT AppMainApp::iWM_THIS=GetProgramWMMessage(); UINT AppMainApp::iWM_WIRENOTE=GetProgramWMMessage(PARENT_PROG); UINT AppMainApp::iWM_EXTERN=RegisterWindowMessage("WK_EXTERN_STUFF"); BOOL AppMainApp::InitInstance() {_XLOG_ CDebugWPHelper::isDebug()=0; if(CLogFlow::isEnabled()){ GlobalAddAtom("WPLABSDEBUG-WK"); CDebugWPHelper::isDebug()=1; } CString sExe; GetCommandLineParameter("execute",sExe,0); if(sExe!=""){_XLOG_ ExecuteMacroByString(sExe); return FALSE; } GetCommandLineParameter("add",sExe,0); if(sExe!=""){_XLOG_ ExecuteMacroByString(CString(ADD_MACRO_PREF)+sExe); return FALSE; } pMainDialogWindow=NULL; CString sWait; GetCommandLineParameter("wait",sWait); DWORD dwStartWait=GetTickCount(); if(sWait=="yes"){_XLOG_ while(CheckProgrammRunState(NULL, UNIQUE_TO_TRUSTEE, false) && GetTickCount()-dwStartWait<180000){_XLOG_ Sleep(1000); } } // Проверяем спайрежим CString sMode; GetCommandLineParameter("spymode",sMode); if(sMode.GetLength()){ spyMode()=1; if(IsThisProgrammAlreadyRunning()){ return FALSE; } } if(!spyMode() && isFileExist(GetAppFolder()+SPY_MODE_APP)){ underSpyMode()=1; ::ShellExecute(NULL,"",GetAppFolder()+SPY_MODE_APP,"-spymode=yes",GetAppFolder(),SW_HIDE); } if(!spyMode() && !underSpyMode()){ if(IsThisProgrammAlreadyRunning()){ DWORD dwTarget=BSM_APPLICATIONS; BroadcastSystemMessage(BSF_FORCEIFHUNG | BSF_IGNORECURRENTTASK | BSF_POSTMESSAGE, &dwTarget, iWM_THIS, WPARAM(99), LPARAM(99)); return FALSE; } } CString sNoPlugin; GetCommandLineParameter("plugins",sNoPlugin); if(sNoPlugin!=""){_XLOG_ if(sNoPlugin.CompareNoCase("no")==0 || sNoPlugin.CompareNoCase("false")==0 || sNoPlugin.CompareNoCase("0")==0){_XLOG_ objSettings.lDoNotLoadMacros=1; } } objSettings.hActiveApplicationAtStart=GetForegroundWindow(); AfxEnableControlContainer(); //AfxInitRichEdit(); #if WINVER<=0x0050 #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif #endif OleInitialize(NULL); // objSettings.sLikUser=""; objSettings.sLikKey=""; WKIHOTKEYS_CheckForExternalDLL()=TRUE; HANDLE hLicenseFile=::CreateFile(GetUserFolder()+LICENSE_KEY_FILE, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); if (!hLicenseFile || hLicenseFile==INVALID_HANDLE_VALUE){_XLOG_ // Из локального каталога! hLicenseFile=::CreateFile(CString(GetApplicationDir())+LICENSE_KEY_FILE, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); } if (hLicenseFile && hLicenseFile!=INVALID_HANDLE_VALUE){_XLOG_ DWORD dwRead=0; char szKey[2048]=""; objSettings.sLikKey=""; ::ReadFile(hLicenseFile, szKey, sizeof(szKey), &dwRead, NULL); objSettings.sLikUser=CDataXMLSaver::GetInstringPart("user:[","]",szKey); objSettings.sLikKey=CDataXMLSaver::GetInstringPart("key:[","]",szKey); ::CloseHandle(hLicenseFile); } dwTID=::GetCurrentThreadId(); UpdateTrialityStatus(objSettings.sLikUser,objSettings.sLikKey); if(objSettings.iLikStatus<0){_XLOG_ #ifdef _DEBUG AfxMessageBox(Format("Anti hack! %s",GetCOMError(GetLastError()))); #endif CSettings* objAntiDebug=0; objAntiDebug->ApplySettings(); return FALSE; } // Основные иконки theApp.MainImageList.Create(16, 16, ILC_COLOR16 | ILC_MASK, 0, 2); AddBitmapToIList(theApp.MainImageList,IDB_IMAGELIST); // Иконки из ImageList-а for(int i=0;i<theApp.MainImageList.GetImageCount();i++){_XLOG_ HICON hIcon=theApp.MainImageList.ExtractIcon(i); _bmp().AddBmp(_IL(i),hIcon); ClearIcon(hIcon); } CString sConfFile=getFileFullName(CString(PROGNAME)+".conf"); CString sIniFileInfo; ReadFile(CString(GetApplicationDir())+"install.ini",sIniFileInfo); if(sIniFileInfo!=""){_XLOG_ sIniFileInfo+="\r\n"; } if(sIniFileInfo.Find("UserData")==-1 || sIniFileInfo.Find("ConfigFile")==-1){_XLOG_ sIniFileInfo+="ConfigFile="; sIniFileInfo+=sConfFile; sIniFileInfo+="\r\n"; sIniFileInfo+="UserData="; sIniFileInfo+=GetPathPart(sConfFile,1,1,0,0); sIniFileInfo+="\r\n"; SaveFile(CString(GetApplicationDir())+"install.ini",sIniFileInfo); } if(!isFileExist(sConfFile)){// если первый запуск - выбор языка objSettings.bStartWithOptions=TRUE; #ifdef _DEBUG int iLang=0; #else int iLang=(GetUserDefaultLangID()==0x0419?1:0); #endif CStringArray aLangBufferNames; int iLangsCount=wk.GetBuffersLang(aLangBufferNames,iLang); // Нет главной программы. спрашиваем стартовый язык пользователя!!! if(iLangsCount>1){_XLOG_ CDLG_Chooser dlgChooser(CString(PROGNAME" - ")+_l("Select language"),_l("Choose your language"),&aLangBufferNames, GetUserDefaultLangID()==0x0419?1:0, IDR_MAINICO,NULL); iLang=dlgChooser.DoModal(); } if(iLang>=0){_XLOG_ GetApplicationLang()=iLang; } } CString sConsoleMode; GetCommandLineParameter("console",sConsoleMode); if(sConsoleMode=="help"){_XLOG_ ShowHelp("Overview"); return 0; } ::GetWindowRect(GetDesktopWindow(),&rDesktopRECT); // Пытаемся к пустому окну захимичится rFakedRect.SetRect(-10,0,0,0); LPCTSTR szClass = AfxRegisterWndClass(NULL); WNDCLASS pClassInfo; memset(&pClassInfo,0,sizeof(pClassInfo)); if(GetClassInfo(AfxGetApp()->m_hInstance,szClass,&pClassInfo)){_XLOG_ pClassInfo.lpszClassName="WK_MAIN"; if(RegisterClass(&pClassInfo)!=0){_XLOG_ szClass=pClassInfo.lpszClassName; }; } m_pFakeWnd = new CWnd; m_pFakeWnd->CreateEx(0, szClass, "WK_ROOT", 0, rFakedRect, NULL, 0); m_pFakeWnd->ShowWindow(SW_HIDE); m_pFakeWnd->EnableWindow(FALSE); // Грузим настройки-обязательно после создания окна, на окно вешаются провертя objSettings.Load(); // ********** CI18N::GetTranslationIFace()=CUITranslationImpl::getInstance(); AppRunStateFile(NULL, 0, NULL); InstallDefaultMacros(); if(objSettings.bStartWithOptions){_XLOG_ if(IsStartupWithWindows()==FALSE){_XLOG_ StartupApplicationWithWindows(TRUE); } } // Создаем pMainDialogWindow = new AppMainDlg(); if(!pMainDialogWindow){_XLOG_ AfxMessageBox(Format("Failed to create main window! %s",GetCOMError(GetLastError()))); return FALSE; } theApp.m_pMainWnd=pMainDialogWindow;// Сначала задаем главное окно, потом создаем его pMainDialogWindow->Create(AppMainDlg::IDD,m_pFakeWnd); {// Запускаем поток, следящий за всем DWORD dwTimerTrackerId=0; HANDLE TimerTracker=::CreateThread(NULL, 0, GlobalOnTimer, NULL, 0, &dwTimerTrackerId); CloseHandle(TimerTracker); } if(objSettings.bStartWithOptions){_XLOG_ pMainDialogWindow->PostMessage(WM_COMMAND,ID_SYSTRAY_ABOUT,0); objSettings.bApplicationFirstRun=TRUE; } objSettings.bStartWithOptions=FALSE; // Все! return TRUE; } int AppMainApp::ExitInstance() {_XLOG_ AppRunStateFile(NULL, -1, NULL); if(m_pFakeWnd){_XLOG_ m_pFakeWnd->DestroyWindow(); delete m_pFakeWnd; } //Тут на выходе зависает... //Возможно слишком поздно. не будем деинициализировать //OleUninitialize(); return CWinApp::ExitInstance(); } LRESULT AppMainApp::ProcessWndProcException(CException* e, const MSG* pMsg) {_XLOG_ return CWinApp::ProcessWndProcException(e, pMsg); } BOOL AppMainApp::PreTranslateMessage(MSG* pMsg) {_XLOG_ return CWinApp::PreTranslateMessage(pMsg); } CWnd* AfxWPGetMainWnd() {_XLOG_ return pMainDialogWindow; } BOOL& spyMode() { static BOOL b=0; return b; } BOOL& underSpyMode() { static BOOL b=0; return b; } #ifndef NOSTUB_VC6 #define COMPILE_MULTIMON_STUBS #include <multimon.h> #endif #pragma message("Long perspective - минимизировать вызовы EscapeStringUTF8, EscapeString, DeEntitize") #pragma message("Long perspective - макросы в проигрывателе записывать для WireKeys. без плагина")
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 603 ] ] ]
7634fac8ee122d08767e23e15193e8f4baf3d6af
920f766fe36acd51410160bb0332c83ed38da4c7
/phase2/misc.cpp
27bfd4db5712420bf380745f1fdc0380777d9761
[]
no_license
shaikuf/hagiga-basnooker
4b302f9c969e119204291655bedb419b89f2cd31
7eb329bcf000ee8b29f22410a9b3a14ab8963abd
refs/heads/master
2016-09-06T00:58:14.129776
2010-06-07T14:12:38
2010-06-07T14:12:38
41,489,609
0
0
null
null
null
null
UTF-8
C++
false
false
5,326
cpp
#include <cv.h> #include <highgui.h> #include "misc.h" #include <iostream> #include <vector> using namespace std; CvSeq *tableBorders() { static bool once = true; static CvMemStorage *mem; static CvSeq* borders; if(once) { // read from file only once mem = cvCreateMemStorage(); char filename[100]; _snprintf_s(filename, 100, "edges-%d.xml", 0); borders = (CvSeq*)cvLoad(filename, mem); once = false; } // and return it always return borders; } void drawBorders(IplImage *dst, int width) { CvSeq *borders = tableBorders(); for(int i = 0; i < borders->total; i++) { CvPoint p1 = *(CvPoint*)cvGetSeqElem(borders, i); CvPoint p2 = *(CvPoint*)cvGetSeqElem(borders, (i+1)%borders->total); cvLine(dst, p1, p2, cvScalar(0, 255, 0), width); } } void printBorderAngles() { CvSeq *borders = tableBorders(); // print the angles of the borders CvPoint p0 = *(CvPoint*)cvGetSeqElem(borders, 0); // top-left CvPoint p1 = *(CvPoint*)cvGetSeqElem(borders, 1); // top-right CvPoint p2 = *(CvPoint*)cvGetSeqElem(borders, 2); // bottom-right CvPoint p3 = *(CvPoint*)cvGetSeqElem(borders, 3); // bottom-left // angle of the bottom against the horizon double theta = atan2((double)p2.y-p3.y, p2.x-p3.x); // angle of the top against the horizon double theta_tag = atan2((double)p1.y-p0.y, (double)p1.x-p0.x); // angle of the left side against the horizon double betta = atan2((double)p0.y-p3.y, p0.x-p3.x); // angle of the right side against the horizon double betta_tag = atan2((double)p1.y-p2.y, p1.x-p2.x); cout<<"bottom="<<theta*180/PI<<"\n"<<"top="<<theta_tag*180/PI<<"\n" <<"left="<<betta*180/PI<<"\n"<<"right="<<betta_tag*180/PI<<endl; } IplImage *createBlankCopy(IplImage *src, int channels, int depth) { if(depth == -1) depth = src->depth; if(channels == -1) channels = src->nChannels; return cvCreateImage(cvGetSize(src), depth, channels); } vector<CvPoint2D32f> filterPointsOnTable(const vector<CvPoint2D32f> &centers, double max_dist) { CvSeq *borders = tableBorders(); vector<CvPoint2D32f> res_points; vector<CvPoint2D32f>::const_iterator i; for(i=centers.begin(); i != centers.end(); i++) { if(cvPointPolygonTest(borders, *i, 1) >= -1*max_dist) res_points.push_back(*i); } return res_points; } bool isPointOnTable(CvPoint2D32f p, double max_dist) { CvSeq *borders = tableBorders(); return (cvPointPolygonTest(borders, p, 1) >= -1*max_dist); } bool isPointOnTable(CvPoint p, double max_dist) { return isPointOnTable(cvPoint2D32f(p.x, p.y), max_dist); } void markCross(IplImage *img, CvPoint center, CvScalar color) { // print an overlay image of the found circle IplImage *overlay_drawing = createBlankCopy(img, 1); cvSet(overlay_drawing, cvScalar(0)); // draw the cross on the overlay int line_len = 5; cvLine(overlay_drawing, cvPoint(cvRound(center.x)-line_len, cvRound(center.y)), cvPoint(cvRound(center.x)+line_len, cvRound(center.y)), cvScalar(0xff), 1); cvLine(overlay_drawing, cvPoint(cvRound(center.x), cvRound(center.y)-line_len), cvPoint(cvRound(center.x), cvRound(center.y)+line_len), cvScalar(0xff), 1); // draw the overlay on the image cvSet(img, color, overlay_drawing); cvReleaseImage(&overlay_drawing); } void paintHolesBlack(IplImage *img) { static CvPoint p[6]; static int radii[6]; static bool once = true; if(once) { CvMat* holes = (CvMat*)cvLoad("Hole.xml"); for(int i=0; i<6; i++){ p[i].x = CV_MAT_ELEM(*holes,int,i,0); p[i].y = CV_MAT_ELEM(*holes,int,i,1); radii[i] = CV_MAT_ELEM(*holes,int,i,2); } once = false; } for(int i=0; i<6; i++) cvCircle(img, p[i], radii[i], cvScalar(0), -1); } CvRect tableBordersBoundingRect(int offset) { CvSeq *borders = tableBorders(); // actually we return a rect with BOUNDING_RECT_OFFSET more on each side CvRect bound = cvBoundingRect(borders); return cvRect(bound.x-offset/2, bound.y-offset/2, bound.width+offset, bound.height+offset); } bool isMoving(IplImage *img) { // always keep a gray copy of the last frame static IplImage *last_frame = 0; if(last_frame == 0) { // if it's the first time, allocate it and return last_frame = createBlankCopy(img, 1); cvCvtColor(img, last_frame, CV_BGR2GRAY); return false; } // create a difference image of the gray images IplImage *img_gray = createBlankCopy(last_frame); IplImage *diff = createBlankCopy(last_frame); cvCvtColor(img, img_gray, CV_BGR2GRAY); cvAbsDiff(img_gray, last_frame, diff); // threshold it cvThreshold(diff, diff, 20, 255, CV_THRESH_BINARY); if(IS_MOVING_DEBUG) { cvNamedWindow("Diff"); cvShowImage("Diff", diff); } // update the last_frame cvCopy(img_gray, last_frame); // see if we have movement on any pixel double max; cvMinMaxLoc(diff, 0, &max, 0, 0); cvReleaseImage(&img_gray); cvReleaseImage(&diff); return (max > 0); } double dist(CvPoint p1, CvPoint p2) { return pow((double)((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y)), (double)0.5); } double dist(CvPoint2D32f p1, CvPoint2D32f p2) { return pow((double)((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y)), (double)0.5); }
[ "c1ph3r.il@9f8e2b2e-e8c3-11de-b92f-5d3588262692" ]
[ [ [ 1, 190 ] ] ]
eb15829eca349a051917f34dc1b111008a6a2d20
e626f4235084b56fcc1d619b9fffc5216f5eec0c
/metaparser2/ComMetaParserService20/NodeValue.cpp
f773cd5de7cb7312037f5b85225dde5f05808ae8
[]
no_license
Programming-Systems-Lab/archived-metaparser2
b6721d6a040eac85f38600f43cb83136fe936f2c
aa8401f295f601833f17f6b2dd098fef211ee49b
refs/heads/master
2020-07-09T05:15:55.067233
2002-05-13T22:43:16
2002-05-13T22:43:16
67,139,974
0
0
null
null
null
null
UTF-8
C++
false
false
3,450
cpp
#include "StdAfx.h" #include "NodeValue.h" #include "Util.h" #include <boost/regex.hpp> void IntValue::SetValue(_bstr_t v) { m_Value = ::atoi((char *) v); } void IntValue::Print() { wprintf(L"%d\n", m_Value); } void RealValue::SetValue(_bstr_t v) { m_Value = ::atof((char *) v); } void RealValue::Print() { wprintf(L"%lf\n", m_Value); } void BoolValue::SetValue(_bstr_t v) { if(IsEquals(v, "true")) { m_Value = true; } else { m_Value = false; } } void BoolValue::Print() { if(m_Value == true) { wprintf(L"true\n"); } else { wprintf(L"false\n"); } } void StrValue::SetValue(_bstr_t v) { m_Value = v; } void StrValue::Print() { wprintf(L"%s\n", (wchar_t *) m_Value); } bool StrValue::Match(NodeValue *arg) { if(arg->m_Type == n_STR) { boost::regex expression((char*) ((StrValue *) arg)->m_Value); if(boost::regex_match((char*) m_Value, expression)) { return true; } } return false; } NodeValue* GetNodeValue(IXMLDOMNodePtr pNode) { NodeValue *pVal; IXMLDOMNamedNodeMapPtr pAttributes; IXMLDOMNodePtr pAttrNode; _bstr_t n, v; pVal = NULL; pAttributes = pNode->attributes; n = "type"; pAttrNode = pAttributes->getNamedItem(n); if(pAttrNode != NULL) { v = (_bstr_t) pAttrNode->GetnodeValue(); if(IsEquals(v, "int")) { pVal = new IntValue(); } else if(IsEquals(v, "real")) { pVal = new RealValue(); } else if(IsEquals(v, "bool")) { pVal = new BoolValue(); } else if(IsEquals(v, "string")) { pVal = new StrValue(); } } n = "value"; pAttrNode = pAttributes->getNamedItem(n); if(pAttrNode != NULL && pVal != NULL) { v = (_bstr_t) pAttrNode->GetnodeValue(); pVal->SetValue(v); } n = "path"; pAttrNode = pAttributes->getNamedItem(n); if(pAttrNode != NULL && pVal != NULL) { v = (_bstr_t) pAttrNode->GetnodeValue(); pVal->m_Path = v; } n = "namespace"; pAttrNode = pAttributes->getNamedItem(n); if(pAttrNode != NULL) { v = (_bstr_t) pAttrNode->GetnodeValue(); if(pVal == NULL) { pVal = new IntValue(); } pVal->m_Namespace = v; } n = "name"; pAttrNode = pAttributes->getNamedItem(n); if(pAttrNode != NULL) { v = (_bstr_t) pAttrNode->GetnodeValue(); if(pVal == NULL) { pVal = new IntValue(); } pVal->m_Name = v; } return pVal; } NodeValue* CopyNodeValue(NodeValue *pVal) { NodeValue *pRetVal; pRetVal = 0; if(pVal->m_Type == n_INT) { pRetVal = new IntValue(); } if(pVal->m_Type == n_REAL) { pRetVal = new RealValue(); } if(pVal->m_Type == n_BOOL) { pRetVal = new BoolValue(); } if(pVal->m_Type == n_STR) { pRetVal = new StrValue(); } if(pRetVal == 0) { return NULL; } pRetVal->m_Name = pVal->m_Name; pRetVal->m_Namespace = pVal->m_Namespace; pRetVal->m_Path = pVal->m_Path; pRetVal->m_Type = pVal->m_Type; if(pRetVal->m_Type == n_INT) { ((IntValue *) pRetVal)->m_Value = ((IntValue *) pVal)->m_Value; } if(pRetVal->m_Type == n_REAL) { ((RealValue *) pRetVal)->m_Value = ((RealValue *) pVal)->m_Value; } if(pRetVal->m_Type == n_BOOL) { ((BoolValue *) pRetVal)->m_Value = ((BoolValue *) pVal)->m_Value; } if(pRetVal->m_Type == n_STR) { ((StrValue *) pRetVal)->m_Value = ((StrValue *) pVal)->m_Value; } return pRetVal; }
[ "sw375" ]
[ [ [ 1, 211 ] ] ]
cb56e2bc7f127f2adf92982abdfb5335bc8f0c56
e98d99816ad42028e5988ade802ffdf9846da166
/Mediotic/mediElasticAttractorForceManipulator.h
3c30f010dfef8ffd02017d7e6fd784e22417860c
[]
no_license
OpenEngineDK/extensions-MediPhysics
5e9b3a0d178db8e9a42ce7724ee35fdfee70ec64
94fdd25f90608ad3db6b3c6a30db1c1e4c490987
refs/heads/master
2016-09-14T04:26:29.607457
2008-10-14T12:14:53
2008-10-14T12:14:53
58,073,189
0
0
null
null
null
null
UTF-8
C++
false
false
4,705
h
#pragma once #include "mediManipulator.h" #include "MathMisc.h" #include "mediParticle.h" #include "mediBody.h" class mediElasticAttractorForceManipulator : public mediManipulator { float forceweight; class Neighbourhood; vector<Neighbourhood> neighbours; // particle i has neighbourhood i. class Triple { mediParticle* particles[3]; float weights[4]; //(alphai, alphaj, alphak, beta) void calculateWeights(Vector3 coord) { float abcArea = (cross((particles[0]->getPos()-particles[1]->getPos()),(particles[2]->getPos()-particles[1]->getPos()))).length(); weights[0] = cross(particles[1]->getPos()-coord,particles[2]->getPos()-coord).length() / abcArea; weights[1] = cross(particles[0]->getPos()-coord,particles[2]->getPos()-coord).length() / abcArea; weights[2] = cross(particles[0]->getPos()-coord,particles[1]->getPos()-coord).length() / abcArea; } public: Triple() { weights[0]=0;weights[1]=0;weights[2]=0;weights[3]=0; } Triple(mediParticle *p1, mediParticle *p2, mediParticle *p3, mediParticle *reference) { particles[0]=p1; particles[1]=p2; particles[2]=p3; Vector3 coord = projectPointOntoPlane(particles[0]->getPos(),particles[1]->getPos(),particles[2]->getPos(),reference->getPos()); weights[3] = (coord-reference->getPos()).length(); // now length must have correct sign (not just positive) Vector3 vectorToReference = coord-reference->getPos(); Vector3 normal = cross(particles[1]->getPos()-particles[0]->getPos(), particles[2]->getPos()-particles[0]->getPos()); vectorToReference.makeUnitVector(); normal.makeUnitVector(); if (dot(vectorToReference,normal)>0) weights[3]=-weights[3]; calculateWeights(coord); /*if (isValid() && (getPoint()-reference->getPos()).length()>0.000001 ) { std::cout << coord << std::endl; std:: cout << (particles[0]->getPos()*weights[0]+particles[1]->getPos()*weights[1]+particles[2]->getPos()*weights[2]) << std::endl; std::cout << (getPoint()-reference->getPos()) << std::endl; }*/ } Vector3 getPoint() { Vector3 Qt = (particles[0]->getPos()*weights[0]+particles[1]->getPos()*weights[1]+particles[2]->getPos()*weights[2]); Vector3 normal = cross(particles[1]->getPos()-particles[0]->getPos(), particles[2]->getPos()-particles[0]->getPos()); normal.makeUnitVector(); return Qt+weights[3]*normal; } bool isValid() { return (weights[0]+weights[1]+weights[2])<=1 && (weights[0]+weights[1]+weights[2])>0.9; } }; class Neighbourhood { private: vector<Triple> triples; mediParticle* particle; public: Neighbourhood(vector<mediParticle>& all_particles, mediParticle* current_particle, float threshold) { particle = current_particle; vector<mediParticle *> close_particles; //cout<< "sovs1" <<endl; for(unsigned int i = 0; i<all_particles.size(); i++) if (&all_particles[i] != current_particle && (all_particles[i].getPos()-current_particle->getPos()).length()<threshold ) { close_particles.push_back(&all_particles[i]); } //cout<< "sovs2" <<endl; //clean out in particles XXXX hack //if(false) /* while (all_particles.size()>4) { int index = rand()%all_particles.size(); all_particles.erase(all_particles.begin()+index); }*/ //cout<< "sovs3" <<endl; int stop = close_particles.size(); // if (stop>10) stop = 10; // if (all_particles.size()>2) // for(int i=0; i<stop; i++) // for(int j=i+1; j<stop; j++) // for(int k=j+1; k<stop; k++) stop = 10000; int counter = 0; while(triples.size()<50 && counter<stop) { int ii = rand()%close_particles.size(); int ji = rand()%close_particles.size(); int ki = rand()%close_particles.size(); Triple triple = Triple(close_particles[ii], close_particles[ji], close_particles[ki], current_particle); if (triple.isValid()) { triples.push_back(triple); //cout << triples.size(); } counter++; } //cout<< "sovs4" <<endl; } void apply(float forceweight) { Vector3 p; for(unsigned int i=0; i < triples.size(); i++) { p = p + triples[i].getPoint(); } p = p/triples.size(); particle->addForce((p-particle->getPos())*forceweight); } bool isEmpty() { return triples.size()==0; } long getNoTriples() { return triples.size(); } }; public: mediElasticAttractorForceManipulator(mediBody *body, float forceweight, float threshold); ~mediElasticAttractorForceManipulator(void); void apply(); };
[ [ [ 1, 172 ] ] ]
78a85bf13bdd6a2645c47b94c0137da0eb46cfb2
5e61787e7adba6ed1c2b5e40d38098ebdf9bdee8
/sans/models/c_models/lamellarPS.cpp
6587a59409d8287fbcb4be4b1e06b014729bc8a2
[]
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
3,219
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 */ /** * Scattering model classes * The classes use the IGOR library found in * sansmodels/src/libigor * * TODO: refactor so that we pull in the old sansmodels.c_extensions * TODO: add 2D function */ #include <math.h> #include "models.hh" #include "parameters.hh" #include <stdio.h> using namespace std; extern "C" { #include "libCylinder.h" #include "lamellarPS.h" } LamellarPSModel :: LamellarPSModel() { scale = Parameter(1.0); spacing = Parameter(400.0, true); spacing.set_min(0.0); delta = Parameter(30.0); delta.set_min(0.0); sld_bi = Parameter(6.3e-6); sld_sol = Parameter(1.0e-6); n_plates = Parameter(20.0); caille = Parameter(0.1); background = Parameter(0.0); } /** * Function to evaluate 1D scattering function * The NIST IGOR library is used for the actual calculation. * @param q: q-value * @return: function value */ double LamellarPSModel :: operator()(double q) { double dp[8]; // Fill parameter array for IGOR library // Add the background after averaging dp[0] = scale(); dp[1] = spacing(); dp[2] = delta(); dp[3] = sld_bi(); dp[4] = sld_sol(); dp[5] = n_plates(); dp[6] = caille(); dp[7] = 0.0; // Get the dispersion points for spacing and delta (thickness) vector<WeightPoint> weights_spacing; spacing.get_weights(weights_spacing); vector<WeightPoint> weights_delta; delta.get_weights(weights_delta); // Perform the computation, with all weight points double sum = 0.0; double norm = 0.0; // Loop over short_edgeA weight points for(int i=0; i< (int)weights_spacing.size(); i++) { dp[1] = weights_spacing[i].value; for(int j=0; j< (int)weights_spacing.size(); j++) { dp[2] = weights_delta[i].value; sum += weights_spacing[i].weight * weights_delta[j].weight * LamellarPS_kernel(dp, q); norm += weights_spacing[i].weight * weights_delta[j].weight; } } return sum/norm + background(); } /** * Function to evaluate 2D scattering function * @param q_x: value of Q along x * @param q_y: value of Q along y * @return: function value */ double LamellarPSModel :: operator()(double qx, double qy) { double q = sqrt(qx*qx + qy*qy); return (*this).operator()(q); } /** * Function to evaluate 2D scattering function * @param pars: parameters of the cylinder * @param q: q-value * @param phi: angle phi * @return: function value */ double LamellarPSModel :: evaluate_rphi(double q, double phi) { return (*this).operator()(q); } /** * Function to calculate effective radius * @return: effective radius value */ double LamellarPSModel :: calculate_ER() { //NOT implemented yet!!! }
[ [ [ 1, 36 ], [ 40, 40 ], [ 43, 55 ], [ 57, 62 ], [ 69, 69 ], [ 76, 78 ], [ 80, 80 ], [ 89, 98 ], [ 101, 110 ], [ 112, 112 ] ], [ [ 37, 39 ], [ 41, 42 ], [ 56, 56 ], [ 63, 68 ], [ 70, 75 ], [ 79, 79 ], [ 81, 88 ], [ 99, 100 ], [ 111, 111 ], [ 113, 120 ] ] ]
d4b9ba4afa929c77c320bc9082b2dcb5c434ce9d
29c5bc6757634a26ac5103f87ed068292e418d74
/src/tlclasses/CSkillProperty.h
c3ccf1a5fa37acb3cc13d75b005d6015c863e041
[]
no_license
drivehappy/tlapi
d10bb75f47773e381e3ba59206ff50889de7e66a
56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9
refs/heads/master
2021-03-19T07:10:57.343889
2011-04-18T22:58:29
2011-04-18T22:58:29
32,191,364
5
0
null
null
null
null
UTF-8
C++
false
false
1,533
h
#pragma once #include "_CList.h" #include "CRunicCore.h" #include "CSkillEvent.h" namespace TLAPI { struct CResourceManager; struct CSkillProperty; struct CSkill; struct CDataGroup; #pragma pack(1) struct CSkillProperty : CRunicCore { float unk0[5]; CResourceManager *pCResourceManager; CSkillProperty *pCSkillProperty; CSkill *pCSkill; u32 unk1[2]; CDataGroup *pCDataGroup; u32 unk2; CList<CList<CSkillEvent*>*> listOfListOfSkillEvents; u32 unk3[2]; float unk4[18]; wstring skillIconName; wstring skillIconInactive; wstring skillName; wstring skillName2; float unk5[8]; wstring unkName; wstring skillDescription; void dumpSkillProperty() { logColor(B_GREEN, L" skillName: %s", skillName.c_str()); logColor(B_GREEN, L" skillName2: %s", skillName2.c_str()); logColor(B_GREEN, L" listOfListOfSkillEvents size: %i", listOfListOfSkillEvents.size); /* for (u32 i = 0; i < listOfListOfSkillEvents.size; i++) { logColor(B_RED, L" listOfListOfSkillEvents[%i] size: %i", i, listOfListOfSkillEvents[i]->size); for (u32 j = 0; j < listOfListOfSkillEvents[i]->size; j++) { logColor(B_RED, L" listOfListOfSkillEvents[%i][%i] SkillEvent Dump", i, j); listOfListOfSkillEvents[i]->operator [](j)->dumpSkillEvent(); } } */ } }; #pragma pack() };
[ "drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522" ]
[ [ [ 1, 70 ] ] ]
3df12e9f786b5b4654d1a067bf1015c5c615006d
a6364718e205f8a83f180f5f06703e8964d6eafe
/foo_lyricsgrabber2/foo_lyricsgrabber2/py_provider.cpp
d89a02c21480d4cf615c624d9043fc33f25460aa
[ "MIT" ]
permissive
LWain83/lyricsgrabber2
b40f56303b7de120a8f12292e194faac661a79e3
b71765433d6ac0c1d1b85b6b1d82de705c6d5718
refs/heads/master
2016-08-12T18:53:51.990628
2010-08-28T07:13:29
2010-08-28T07:13:29
52,316,826
0
0
null
null
null
null
UTF-8
C++
false
false
2,343
cpp
#include "stdafx.h" #include "ui_conf.h" #include "py_provider.h" static grabber::provider_factory<py_provider> g_provider; GUID py_provider::get_provider_guid() { // {6323D7E6-328D-4168-A325-CE78C0120BDE} static const GUID guid = { 0x6323d7e6, 0x328d, 0x4168, { 0xa3, 0x25, 0xce, 0x78, 0xc0, 0x12, 0xb, 0xde } }; return guid; } bool py_provider::get_provider_description(pfc::string_base & p_out) { p_out = "Add support for user-defined provider in python scripting language\n\n\n\n"; p_out += "Copyright (c) 2001-2008 Python Software Foundation.\nAll Rights Reserved.\n\n"; p_out += "Copyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n\n"; p_out += "Copyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\n"; p_out += "Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved\n\n"; return true; } bool py_provider::get_provider_url(pfc::string_base & p_out) { p_out = "http://code.google.com/p/lyricsgrabber2/"; return true; } unsigned py_provider::get_menu_item_count() { return m_site.get_script_count(); } void py_provider::get_menu_item_name(unsigned p_index, pfc::string_base & p_out) { p_out = m_site.get_script_name(p_index); } pfc::string_list_impl * py_provider::lookup(unsigned p_index, metadb_handle_list_cref p_meta, threaded_process_status & p_status, abort_callback & p_abort) { TRACK_CALL_TEXT("py_provider::lookup"); pfc::string_list_impl * data = new pfc::string_list_impl; bool status; status = m_site.invoke(p_index, p_meta, p_status, p_abort, *data); if (status == false) { delete data; data = NULL; } return data; } bool py_provider::show_config_popup(HWND wnd_parent) { if (!m_conf_dlg || !m_conf_dlg->IsWindow()) { m_conf_dlg = new CConfDlg(m_site); m_conf_dlg->Create(wnd_parent); } m_conf_dlg->ShowWindow(SW_SHOW); return true; } void py_provider::set_config(stream_reader * p_reader, t_size p_size, abort_callback & p_abort) { m_site.get_config().read_from_stream(p_reader, p_size, p_abort); // HACK: For services is not prepared on DLL loading m_site.init(); } void py_provider::get_config(stream_writer * p_writer, abort_callback & p_abort) { m_site.get_config().write_to_stream(p_writer, p_abort); }
[ "qudeid@d0561270-fede-e5e2-f771-9cccb1c17e5b" ]
[ [ [ 1, 82 ] ] ]
4a92e998e97570554b524319d9487398a5b8e36d
cb87858032792e50607a06dceb10196d6a5de2fa
/FileGDB_DotNet/RowNet.cpp
b3708713871df8c3e51bee72419e22de21b98817
[]
no_license
nakijun/filegdb-dotnet-wrapper
16722077839b77b4940106dc5ac293325776c792
92f156a57527d802a6ace734f842528b359b11b4
refs/heads/master
2021-01-10T06:56:04.987321
2011-06-07T13:54:45
2011-06-07T13:54:45
51,569,516
0
0
null
null
null
null
UTF-8
C++
false
false
10,810
cpp
/** * Code by Sasa Ivetic (Map It Out Inc.) 2011 */ #include "stdafx.h" #include "RowNet.h" #include "PointShapeBufferNet.h" #include "MultiPointShapeBufferNet.h" #include "MultiPartShapeBufferNet.h" #include "MultiPatchShapeBufferNet.h" #include "FGDBException.h" namespace FileGDB_DotNet { bool RowNet::IsNull(String^ field) { std::wstring wField; MarshalString(field, wField); bool val; fgdbError hr; if ((hr = this->fgdbApiRow->IsNull(wField, val)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } return val; } void RowNet::SetNull(String^ field) { std::wstring wField; MarshalString(field, wField); fgdbError hr; if ((hr = this->fgdbApiRow->SetNull(wField)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } long RowNet::GetOID() { int32 val; fgdbError hr; if ((hr = this->fgdbApiRow->GetOID(val)) != S_OK) { throw gcnew FGDBException("Error getting OID. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } return val; } System::Guid^ RowNet::GetGlobalID() { FileGDBAPI::Guid val; fgdbError hr; if ((hr = this->fgdbApiRow->GetGlobalID(val)) != S_OK) { throw gcnew Exception("Error getting Global ID. Error code: " + hr + " (0x" + hr.ToString("X8") + ")"); } return MarshalGuid(val); } ShapeBufferNet^ RowNet::GetGeometry() { FileGDBAPI::ShapeBuffer* sb = new FileGDBAPI::ShapeBuffer; fgdbError hr; if ((hr = this->fgdbApiRow->GetGeometry(*sb)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } FileGDBAPI::ShapeType shapeType; sb->GetShapeType(shapeType); ShapeBufferNet^ outsb; // Create the appropriate class based on the shape type switch (shapeType) { case FileGDBAPI::shapeGeneralPoint: case FileGDBAPI::shapePoint: case FileGDBAPI::shapePointM: case FileGDBAPI::shapePointZ: case FileGDBAPI::shapePointZM: outsb = gcnew PointShapeBufferNet(); break; case FileGDBAPI::shapeGeneralMultipoint: case FileGDBAPI::shapeMultipoint: case FileGDBAPI::shapeMultipointM: case FileGDBAPI::shapeMultipointZ: case FileGDBAPI::shapeMultipointZM: outsb = gcnew MultiPointShapeBufferNet(); break; case FileGDBAPI::shapeGeneralPolyline: case FileGDBAPI::shapePolyline: case FileGDBAPI::shapePolylineM: case FileGDBAPI::shapePolylineZ: case FileGDBAPI::shapePolylineZM: case FileGDBAPI::shapeGeneralPolygon: case FileGDBAPI::shapePolygon: case FileGDBAPI::shapePolygonM: case FileGDBAPI::shapePolygonZ: case FileGDBAPI::shapePolygonZM: outsb = gcnew MultiPartShapeBufferNet(); break; case FileGDBAPI::shapeMultiPatch: case FileGDBAPI::shapeMultiPatchM: case FileGDBAPI::shapeGeneralMultiPatch: outsb = gcnew MultiPatchShapeBufferNet(); break; default: outsb = gcnew ShapeBufferNet(); break; }; // Delete the internal buffer pointer and assign it to the one created earlier delete outsb->fgdbApiShapeBuffer; outsb->fgdbApiShapeBuffer = sb; return outsb; } void RowNet::SetGeometry(ShapeBufferNet^ val) { fgdbError hr; if ((hr = this->fgdbApiRow->SetGeometry(*val->fgdbApiShapeBuffer)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } short RowNet::GetShort(String^ field) { std::wstring wField; MarshalString(field, wField); short val; fgdbError hr; if ((hr = this->fgdbApiRow->GetShort(wField, val)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } return val; } void RowNet::SetShort(String^ field, short val) { std::wstring wField; MarshalString(field, wField); fgdbError hr; if ((hr = this->fgdbApiRow->SetShort(wField, val)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } int32 RowNet::GetInteger(String^ field) { std::wstring wField; MarshalString(field, wField); int32 val; fgdbError hr; if ((hr = this->fgdbApiRow->GetInteger(wField, val)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } return val; } void RowNet::SetInteger(String^ field, int32 val) { std::wstring wField; MarshalString(field, wField); fgdbError hr; if ((hr = this->fgdbApiRow->SetInteger(wField, val)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } float RowNet::GetFloat(String^ field) { std::wstring wField; MarshalString(field, wField); float val; fgdbError hr; if ((hr = this->fgdbApiRow->GetFloat(wField, val)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } return val; } void RowNet::SetFloat(String^ field, float val) { std::wstring wField; MarshalString(field, wField); fgdbError hr; if ((hr = this->fgdbApiRow->SetFloat(wField, val)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } double RowNet::GetDouble(String^ field) { std::wstring wField; MarshalString(field, wField); double val; fgdbError hr; if ((hr = this->fgdbApiRow->GetDouble(wField, val)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } return val; } void RowNet::SetDouble(String^ field, double val) { std::wstring wField; MarshalString(field, wField); fgdbError hr; if ((hr = this->fgdbApiRow->SetDouble(wField, val)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } System::DateTime^ RowNet::GetDate(String^ field) { std::wstring wField; MarshalString(field, wField); struct tm val; fgdbError hr; if ((hr = this->fgdbApiRow->GetDate(wField, val)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } return MarshalDateTime(val); } void RowNet::SetDate(String^ field, System::DateTime val) { std::wstring wField; MarshalString(field, wField); struct tm dtval = MarshalDateTime(val); fgdbError hr; if ((hr = this->fgdbApiRow->SetDate(wField, dtval)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } String^ RowNet::GetString(String^ field) { std::wstring wField; MarshalString(field, wField); std::wstring val; fgdbError hr; if ((hr = this->fgdbApiRow->GetString(wField, val)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } String^ retval = gcnew String(val.c_str()); return retval; } void RowNet::SetString(String^ field, String^ val) { std::wstring wField, wVal; MarshalString(field, wField); MarshalString(val, wVal); fgdbError hr; if ((hr = this->fgdbApiRow->SetString(wField, wVal)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } Guid^ RowNet::GetGUID(String^ field) { std::wstring wField; MarshalString(field, wField); FileGDBAPI::Guid val; fgdbError hr; if ((hr = this->fgdbApiRow->GetGUID(wField, val)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } return MarshalGuid(val); } void RowNet::SetGUID(String^ field, Guid val) { std::wstring wField; MarshalString(field, wField); FileGDBAPI::Guid guidval = MarshalGuid(val); fgdbError hr; if ((hr = this->fgdbApiRow->SetGUID(wField, guidval)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } String^ RowNet::GetXML(String^ field) { std::wstring wField; MarshalString(field, wField); std::string val; fgdbError hr; if ((hr = this->fgdbApiRow->GetXML(wField, val)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } String^ retval = gcnew String(val.c_str()); return retval; } void RowNet::SetXML(String^ field, String^ val) { std::wstring wField; std::string sVal; MarshalString(field, wField); MarshalString(val, sVal); fgdbError hr; if ((hr = this->fgdbApiRow->SetXML(wField, sVal)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } RasterNet^ RowNet::GetRaster(String^ field) { std::wstring wField; MarshalString(field, wField); RasterNet^ outraster = gcnew RasterNet(); fgdbError hr; if ((hr = this->fgdbApiRow->GetRaster(wField, *outraster->fgdbApiRaster)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } return outraster; } void RowNet::SetRaster(String^ field, RasterNet^ val) { std::wstring wField; MarshalString(field, wField); fgdbError hr; if ((hr = this->fgdbApiRow->SetRaster(wField, *val->fgdbApiRaster)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } ByteArrayNet^ RowNet::GetBinary(String^ field) { std::wstring wField; MarshalString(field, wField); ByteArrayNet^ outba = gcnew ByteArrayNet(); fgdbError hr; if ((hr = this->fgdbApiRow->GetBinary(wField, *outba->fgdbApiByteArray)) != S_OK) { throw gcnew FGDBException("Error getting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } return outba; } void RowNet::SetBinary(String^ field, ByteArrayNet^ val) { std::wstring wField; MarshalString(field, wField); fgdbError hr; if ((hr = this->fgdbApiRow->SetBinary(wField, *val->fgdbApiByteArray)) != S_OK) { throw gcnew FGDBException("Error setting value. Error code: " + hr + " (0x" + hr.ToString("X8") + ")", hr); } } }
[ "sivetic@595f332e-62bf-ab4c-4ca1-b707e713c6df" ]
[ [ [ 1, 385 ] ] ]
e00b2c4eecb916ffc9ba0a4548b4a43970bcf4e2
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/dom/impl/DOMCharacterDataImpl.cpp
cd28cd48b9688d9610e8786b253b926065efd1b0
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
8,792
cpp
/* * Copyright 2001-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOMCharacterDataImpl.cpp 176280 2005-01-07 15:32:34Z amassari $ */ #include "DOMCharacterDataImpl.hpp" #include <xercesc/dom/DOMException.hpp> #include <xercesc/dom/DOMNode.hpp> #include "DOMRangeImpl.hpp" #include "DOMDocumentImpl.hpp" #include "DOMCasts.hpp" #include "DOMStringPool.hpp" #include <xercesc/util/XMLUniDefs.hpp> XERCES_CPP_NAMESPACE_BEGIN DOMCharacterDataImpl::DOMCharacterDataImpl(DOMDocument *doc, const XMLCh *dat) : fDataBuf(0) , fDoc(0) { fDoc = (DOMDocumentImpl*)doc; fDataBuf = fDoc->popBuffer(); if (!fDataBuf) fDataBuf = new (fDoc) DOMBuffer(fDoc, dat); else fDataBuf->set(dat); } DOMCharacterDataImpl::DOMCharacterDataImpl(const DOMCharacterDataImpl &other) : fDataBuf(0) , fDoc(0) { fDoc = (DOMDocumentImpl*)other.fDoc; fDataBuf = fDoc->popBuffer(); if (!fDataBuf) fDataBuf = new (fDoc) DOMBuffer(fDoc, other.fDataBuf->getRawBuffer()); else fDataBuf->set(other.fDataBuf->getRawBuffer()); } DOMCharacterDataImpl::~DOMCharacterDataImpl() { } const XMLCh * DOMCharacterDataImpl::getNodeValue() const { return fDataBuf->getRawBuffer(); } void DOMCharacterDataImpl::setNodeValue(const DOMNode *node, const XMLCh *value) { if (castToNodeImpl(node)->isReadOnly()) throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR, 0, GetDOMCharacterDataImplMemoryManager); fDataBuf->set(value); if (node->getOwnerDocument() != 0) { Ranges* ranges = ((DOMDocumentImpl *)node->getOwnerDocument())->getRanges(); if (ranges != 0) { XMLSize_t sz = ranges->size(); if (sz != 0) { for (XMLSize_t i =0; i<sz; i++) { ranges->elementAt(i)->receiveReplacedText((DOMNode*)node); } } } } } void DOMCharacterDataImpl::appendData(const DOMNode *node, const XMLCh *dat) { if(castToNodeImpl(node)->isReadOnly()) throw DOMException( DOMException::NO_MODIFICATION_ALLOWED_ERR, 0, GetDOMCharacterDataImplMemoryManager); fDataBuf->append(dat); } void DOMCharacterDataImpl::deleteData(const DOMNode *node, XMLSize_t offset, XMLSize_t count) { if (castToNodeImpl(node)->isReadOnly()) throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR, 0, GetDOMCharacterDataImplMemoryManager); // Note: the C++ XMLCh * operation throws the correct DOMExceptions // when parameter values are bad. // XMLSize_t len = this->fDataBuf->getLen(); if (offset > len) throw DOMException(DOMException::INDEX_SIZE_ERR, 0, GetDOMCharacterDataImplMemoryManager); // Cap the value of delLength to avoid trouble with overflows // in the following length computations. if (count > len) count = len; // If the length of data to be deleted would extend off the end // of the string, cut it back to stop at the end of string. if (offset + count >= len) count = len - offset; XMLSize_t newLen = len - count; XMLCh* newString; XMLCh temp[4000]; if (newLen >= 3999) newString = (XMLCh*) XMLPlatformUtils::fgMemoryManager->allocate ( (newLen+1) * sizeof(XMLCh) );//new XMLCh[newLen+1]; else newString = temp; XMLString::copyNString(newString, fDataBuf->getRawBuffer(), offset); XMLString::copyString(newString+offset, fDataBuf->getRawBuffer()+offset+count); fDataBuf->set(newString); if (newLen >= 3999) XMLPlatformUtils::fgMemoryManager->deallocate(newString);//delete[] newString; // We don't delete the old string (doesn't work), or alter // the old string (may be shared) // It just hangs around, possibly orphaned. if (node->getOwnerDocument() != 0) { Ranges* ranges = ((DOMDocumentImpl *)node->getOwnerDocument())->getRanges(); if (ranges != 0) { XMLSize_t sz = ranges->size(); if (sz != 0) { for (XMLSize_t i =0; i<sz; i++) { ranges->elementAt(i)->updateRangeForDeletedText( (DOMNode*)node, offset, count); } } } } } const XMLCh *DOMCharacterDataImpl::getData() const { return fDataBuf->getRawBuffer(); } // // getCharDataLength - return the length of the character data string. // XMLSize_t DOMCharacterDataImpl::getLength() const { return fDataBuf->getLen(); } void DOMCharacterDataImpl::insertData(const DOMNode *node, XMLSize_t offset, const XMLCh *dat) { if (castToNodeImpl(node)->isReadOnly()) throw DOMException( DOMException::NO_MODIFICATION_ALLOWED_ERR, 0, GetDOMCharacterDataImplMemoryManager); // Note: the C++ XMLCh * operation throws the correct DOMExceptions // when parameter values are bad. // XMLSize_t len = fDataBuf->getLen(); if (offset > len) throw DOMException(DOMException::INDEX_SIZE_ERR, 0, GetDOMCharacterDataImplMemoryManager); XMLSize_t datLen = XMLString::stringLen(dat); XMLSize_t newLen = len + datLen; XMLCh* newString; XMLCh temp[4000]; if (newLen >= 3999) newString = (XMLCh*) XMLPlatformUtils::fgMemoryManager->allocate ( (newLen + 1) * sizeof(XMLCh) );//new XMLCh[newLen+1]; else newString = temp; XMLString::copyNString(newString, fDataBuf->getRawBuffer(), offset); XMLString::copyNString(newString+offset, dat, datLen); XMLString::copyString(newString+offset+datLen, fDataBuf->getRawBuffer()+offset); fDataBuf->set(newString); if (newLen >= 3999) XMLPlatformUtils::fgMemoryManager->deallocate(newString);//delete[] newString; if (node->getOwnerDocument() != 0) { Ranges* ranges = ((DOMDocumentImpl *)node->getOwnerDocument())->getRanges(); if (ranges != 0) { XMLSize_t sz = ranges->size(); if (sz != 0) { for (XMLSize_t i =0; i<sz; i++) { ranges->elementAt(i)->updateRangeForInsertedText( (DOMNode*)node, offset, datLen); } } } } } void DOMCharacterDataImpl::replaceData(const DOMNode *node, XMLSize_t offset, XMLSize_t count, const XMLCh *dat) { if (castToNodeImpl(node)->isReadOnly()) throw DOMException( DOMException::NO_MODIFICATION_ALLOWED_ERR, 0, GetDOMCharacterDataImplMemoryManager); deleteData(node, offset, count); insertData(node, offset, dat); } void DOMCharacterDataImpl::setData(const DOMNode *node, const XMLCh *arg) { setNodeValue(node, arg); } const XMLCh * DOMCharacterDataImpl::substringData(const DOMNode *node, XMLSize_t offset, XMLSize_t count) const { // Note: the C++ XMLCh * operation throws the correct DOMExceptions // when parameter values are bad. // XMLSize_t len = fDataBuf->getLen(); if (offset > len) throw DOMException(DOMException::INDEX_SIZE_ERR, 0, GetDOMCharacterDataImplMemoryManager); XMLCh* newString; XMLCh temp[4000]; if (len >= 3999) newString = (XMLCh*) ((DOMDocumentImpl *)node->getOwnerDocument())->getMemoryManager()->allocate ( (len + 1) * sizeof(XMLCh) );//new XMLCh[len+1]; else newString = temp; XMLString::copyNString(newString, fDataBuf->getRawBuffer()+offset, count); newString[count] = chNull; const XMLCh* retString = ((DOMDocumentImpl *)node->getOwnerDocument())->getPooledString(newString); if (len >= 3999) ((DOMDocumentImpl *)node->getOwnerDocument())->getMemoryManager()->deallocate(newString);//delete[] newString; return retString; } void DOMCharacterDataImpl::releaseBuffer() { fDoc->releaseBuffer(fDataBuf); } XERCES_CPP_NAMESPACE_END
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 300 ] ] ]
a91b2d3376a20fd27c47b6f21a353db09d512b45
f13f46fbe8535a7573d0f399449c230a35cd2014
/JelloMan/ContentManager.h
f62987abb4690a1d6a210746389bc80b62a5ab99
[]
no_license
fangsunjian/jello-man
354f1c86edc2af55045d8d2bcb58d9cf9b26c68a
148170a4834a77a9e1549ad3bb746cb03470df8f
refs/heads/master
2020-12-24T16:42:11.511756
2011-06-14T10:16:51
2011-06-14T10:16:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,383
h
#pragma once #include "d3dUtil.h" #include "EffectLoader.h" #include "TextureLoader.h" #include "ModelLoader.h" #include "vertex.h" #include "ImageLoader.h" #include "TextFormatLoader.h" #include "SplineLoader.h" #include "TerrainLoader.h" class TextureLoader; class EffectLoader; #define Content ContentManager::GetSingleton() enum DefaultTextureType { DefaultTextureType_White, DefaultTextureType_Black, DefaultTextureType_Gray, DefaultTextureType_Normal }; class ContentManager { public: virtual ~ContentManager(); void Init(ID3D10Device* pDXDevice); template <typename T> T* LoadEffect(const tstring& assetName) { return m_pEffectLoader->Load<T>(m_pDevice, assetName); } Texture2D* LoadTexture2D(const tstring& assetName, bool cpuReadAccess = false); Texture2D* LoadTexture2D(DefaultTextureType type); Model<VertexPosNormTanTex>* LoadModel(const tstring& assetName); Model<VertexPos>* LoadSpline(const tstring& assetName); Model<VertexPosNormTanTex>* LoadTerrain(const tstring& assetName); SoftbodyMesh* LoadSoftbodyMesh(const tstring& assetName); //* Loads image from a file location. * Image* LoadImage(const tstring& fileNameRef, int newWidth = 0, int newHeight = 0); //* Loads new text format. * TextFormat* LoadTextFormat(const tstring& fontName, float size, bool bold = false, bool italic = false); ID3D10Device* GetDxDevice() const { return m_pDevice; } static ContentManager* GetSingleton(); private: ContentManager(); // initialize wic imaging factory void CreateWICFactory(); //------------------------------------------------- // Datamembers //------------------------------------------------- ID3D10Device* m_pDevice; IWICImagingFactory* m_pWICFactory; ImageLoader* m_pImageLoader; TextFormatLoader* m_pTextFormatLoader; TextureLoader* m_pTextureLoader; EffectLoader* m_pEffectLoader; ModelLoader* m_pModelLoader; TerrainLoader* m_pTerrainLoader; SplineLoader* m_pSplineLoader; static ContentManager* m_pSingleton; // ------------------------- // Disabling default copy constructor and default // assignment operator. // ------------------------- ContentManager(const ContentManager& yRef); ContentManager& operator=(const ContentManager& yRef); };
[ "bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6", "[email protected]" ]
[ [ [ 1, 6 ], [ 10, 29 ], [ 31, 39 ], [ 43, 44 ], [ 46, 47 ], [ 52, 54 ], [ 56, 56 ], [ 63, 66 ], [ 71, 75 ], [ 77, 88 ] ], [ [ 7, 9 ], [ 30, 30 ], [ 40, 42 ], [ 45, 45 ], [ 48, 51 ], [ 55, 55 ], [ 57, 62 ], [ 67, 70 ], [ 76, 76 ] ] ]
ff6ba799f6c43996c26e4e2165f1d428d759637c
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/angle_forward.hpp
2b38609022d550ff8cb7221884ea1d7839f97c54
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
14,520
hpp
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // #ifndef AOSLCPP_AOSL__ANGLE_FORWARD_HPP #define AOSLCPP_AOSL__ANGLE_FORWARD_HPP // Begin prologue. // // // End prologue. #include <xsd/cxx/version.hxx> #if (XSD_INT_VERSION != 3030000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> #include <xsd/cxx/xml/dom/serialization-header.hxx> #include <xsd/cxx/tree/serialization.hxx> #include <xsd/cxx/tree/serialization/byte.hxx> #include <xsd/cxx/tree/serialization/unsigned-byte.hxx> #include <xsd/cxx/tree/serialization/short.hxx> #include <xsd/cxx/tree/serialization/unsigned-short.hxx> #include <xsd/cxx/tree/serialization/int.hxx> #include <xsd/cxx/tree/serialization/unsigned-int.hxx> #include <xsd/cxx/tree/serialization/long.hxx> #include <xsd/cxx/tree/serialization/unsigned-long.hxx> #include <xsd/cxx/tree/serialization/boolean.hxx> #include <xsd/cxx/tree/serialization/float.hxx> #include <xsd/cxx/tree/serialization/double.hxx> #include <xsd/cxx/tree/serialization/decimal.hxx> #include <xsd/cxx/tree/std-ostream-operators.hxx> /** * @brief C++ namespace for the %http://www.w3.org/2001/XMLSchema * schema namespace. */ namespace xml_schema { // anyType and anySimpleType. // /** * @brief C++ type corresponding to the anyType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::type Type; /** * @brief C++ type corresponding to the anySimpleType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::simple_type< Type > SimpleType; /** * @brief Alias for the anyType type. */ typedef ::xsd::cxx::tree::type Container; // 8-bit // /** * @brief C++ type corresponding to the byte XML Schema * built-in type. */ typedef signed char Byte; /** * @brief C++ type corresponding to the unsignedByte XML Schema * built-in type. */ typedef unsigned char UnsignedByte; // 16-bit // /** * @brief C++ type corresponding to the short XML Schema * built-in type. */ typedef short Short; /** * @brief C++ type corresponding to the unsignedShort XML Schema * built-in type. */ typedef unsigned short UnsignedShort; // 32-bit // /** * @brief C++ type corresponding to the int XML Schema * built-in type. */ typedef int Int; /** * @brief C++ type corresponding to the unsignedInt XML Schema * built-in type. */ typedef unsigned int UnsignedInt; // 64-bit // /** * @brief C++ type corresponding to the long XML Schema * built-in type. */ typedef long long Long; /** * @brief C++ type corresponding to the unsignedLong XML Schema * built-in type. */ typedef unsigned long long UnsignedLong; // Supposed to be arbitrary-length integral types. // /** * @brief C++ type corresponding to the integer XML Schema * built-in type. */ typedef long long Integer; /** * @brief C++ type corresponding to the nonPositiveInteger XML Schema * built-in type. */ typedef long long NonPositiveInteger; /** * @brief C++ type corresponding to the nonNegativeInteger XML Schema * built-in type. */ typedef unsigned long long NonNegativeInteger; /** * @brief C++ type corresponding to the positiveInteger XML Schema * built-in type. */ typedef unsigned long long PositiveInteger; /** * @brief C++ type corresponding to the negativeInteger XML Schema * built-in type. */ typedef long long NegativeInteger; // Boolean. // /** * @brief C++ type corresponding to the boolean XML Schema * built-in type. */ typedef bool Boolean; // Floating-point types. // /** * @brief C++ type corresponding to the float XML Schema * built-in type. */ typedef float Float; /** * @brief C++ type corresponding to the double XML Schema * built-in type. */ typedef double Double; /** * @brief C++ type corresponding to the decimal XML Schema * built-in type. */ typedef double Decimal; // String types. // /** * @brief C++ type corresponding to the string XML Schema * built-in type. */ typedef ::xsd::cxx::tree::string< char, SimpleType > String; /** * @brief C++ type corresponding to the normalizedString XML Schema * built-in type. */ typedef ::xsd::cxx::tree::normalized_string< char, String > NormalizedString; /** * @brief C++ type corresponding to the token XML Schema * built-in type. */ typedef ::xsd::cxx::tree::token< char, NormalizedString > Token; /** * @brief C++ type corresponding to the Name XML Schema * built-in type. */ typedef ::xsd::cxx::tree::name< char, Token > Name; /** * @brief C++ type corresponding to the NMTOKEN XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtoken< char, Token > Nmtoken; /** * @brief C++ type corresponding to the NMTOKENS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtokens< char, SimpleType, Nmtoken > Nmtokens; /** * @brief C++ type corresponding to the NCName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::ncname< char, Name > Ncname; /** * @brief C++ type corresponding to the language XML Schema * built-in type. */ typedef ::xsd::cxx::tree::language< char, Token > Language; // ID/IDREF. // /** * @brief C++ type corresponding to the ID XML Schema * built-in type. */ typedef ::xsd::cxx::tree::id< char, Ncname > Id; /** * @brief C++ type corresponding to the IDREF XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idref< char, Ncname, Type > Idref; /** * @brief C++ type corresponding to the IDREFS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idrefs< char, SimpleType, Idref > Idrefs; // URI. // /** * @brief C++ type corresponding to the anyURI XML Schema * built-in type. */ typedef ::xsd::cxx::tree::uri< char, SimpleType > Uri; // Qualified name. // /** * @brief C++ type corresponding to the QName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::qname< char, SimpleType, Uri, Ncname > Qname; // Binary. // /** * @brief Binary buffer type. */ typedef ::xsd::cxx::tree::buffer< char > Buffer; /** * @brief C++ type corresponding to the base64Binary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::base64_binary< char, SimpleType > Base64Binary; /** * @brief C++ type corresponding to the hexBinary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::hex_binary< char, SimpleType > HexBinary; // Date/time. // /** * @brief Time zone type. */ typedef ::xsd::cxx::tree::time_zone TimeZone; /** * @brief C++ type corresponding to the date XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date< char, SimpleType > Date; /** * @brief C++ type corresponding to the dateTime XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date_time< char, SimpleType > DateTime; /** * @brief C++ type corresponding to the duration XML Schema * built-in type. */ typedef ::xsd::cxx::tree::duration< char, SimpleType > Duration; /** * @brief C++ type corresponding to the gDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gday< char, SimpleType > Gday; /** * @brief C++ type corresponding to the gMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth< char, SimpleType > Gmonth; /** * @brief C++ type corresponding to the gMonthDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth_day< char, SimpleType > GmonthDay; /** * @brief C++ type corresponding to the gYear XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear< char, SimpleType > Gyear; /** * @brief C++ type corresponding to the gYearMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear_month< char, SimpleType > GyearMonth; /** * @brief C++ type corresponding to the time XML Schema * built-in type. */ typedef ::xsd::cxx::tree::time< char, SimpleType > Time; // Entity. // /** * @brief C++ type corresponding to the ENTITY XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entity< char, Ncname > Entity; /** * @brief C++ type corresponding to the ENTITIES XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entities< char, SimpleType, Entity > Entities; // Namespace information and list stream. Used in // serialization functions. // /** * @brief Namespace serialization information. */ typedef ::xsd::cxx::xml::dom::namespace_info< char > NamespaceInfo; /** * @brief Namespace serialization information map. */ typedef ::xsd::cxx::xml::dom::namespace_infomap< char > NamespaceInfomap; /** * @brief List serialization stream. */ typedef ::xsd::cxx::tree::list_stream< char > ListStream; /** * @brief Serialization wrapper for the %double type. */ typedef ::xsd::cxx::tree::as_double< Double > AsDouble; /** * @brief Serialization wrapper for the %decimal type. */ typedef ::xsd::cxx::tree::as_decimal< Decimal > AsDecimal; /** * @brief Simple type facet. */ typedef ::xsd::cxx::tree::facet Facet; // Flags and properties. // /** * @brief Parsing and serialization flags. */ typedef ::xsd::cxx::tree::flags Flags; /** * @brief Parsing properties. */ typedef ::xsd::cxx::tree::properties< char > Properties; // Parsing/serialization diagnostics. // /** * @brief Error severity. */ typedef ::xsd::cxx::tree::severity Severity; /** * @brief Error condition. */ typedef ::xsd::cxx::tree::error< char > Error; /** * @brief List of %error conditions. */ typedef ::xsd::cxx::tree::diagnostics< char > Diagnostics; // Exceptions. // /** * @brief Root of the C++/Tree %exception hierarchy. */ typedef ::xsd::cxx::tree::exception< char > Exception; /** * @brief Exception indicating that the size argument exceeds * the capacity argument. */ typedef ::xsd::cxx::tree::bounds< char > Bounds; /** * @brief Exception indicating that a duplicate ID value * was encountered in the object model. */ typedef ::xsd::cxx::tree::duplicate_id< char > DuplicateId; /** * @brief Exception indicating a parsing failure. */ typedef ::xsd::cxx::tree::parsing< char > Parsing; /** * @brief Exception indicating that an expected element * was not encountered. */ typedef ::xsd::cxx::tree::expected_element< char > ExpectedElement; /** * @brief Exception indicating that an unexpected element * was encountered. */ typedef ::xsd::cxx::tree::unexpected_element< char > UnexpectedElement; /** * @brief Exception indicating that an expected attribute * was not encountered. */ typedef ::xsd::cxx::tree::expected_attribute< char > ExpectedAttribute; /** * @brief Exception indicating that an unexpected enumerator * was encountered. */ typedef ::xsd::cxx::tree::unexpected_enumerator< char > UnexpectedEnumerator; /** * @brief Exception indicating that the text content was * expected for an element. */ typedef ::xsd::cxx::tree::expected_text_content< char > ExpectedTextContent; /** * @brief Exception indicating that a prefix-namespace * mapping was not provided. */ typedef ::xsd::cxx::tree::no_prefix_mapping< char > NoPrefixMapping; /** * @brief Exception indicating that the type information * is not available for a type. */ typedef ::xsd::cxx::tree::no_type_info< char > NoTypeInfo; /** * @brief Exception indicating that the types are not * related by inheritance. */ typedef ::xsd::cxx::tree::not_derived< char > NotDerived; /** * @brief Exception indicating a serialization failure. */ typedef ::xsd::cxx::tree::serialization< char > Serialization; /** * @brief Error handler callback interface. */ typedef ::xsd::cxx::xml::error_handler< char > ErrorHandler; /** * @brief DOM interaction. */ namespace dom { /** * @brief Automatic pointer for DOMDocument. */ using ::xsd::cxx::xml::dom::auto_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA /** * @brief DOM user data key for back pointers to tree nodes. */ const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } // Forward declarations. // namespace aosl { class Angle; } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__ANGLE_FORWARD_HPP
[ "klaim@localhost" ]
[ [ [ 1, 608 ] ] ]
133ac00e287b9666015ed40c33ab9e788a692750
dc4f8d571e2ed32f9489bafb00b420ca278121c6
/mojo_engine/tRect.h
b05a8c3eac118d65e795faf1a15066f3dd121dc8
[]
no_license
mwiemarc/mojoware
a65eaa4ec5f6130425d2a1e489e8bda4f6f88ec0
168a2d3a9f87e6c585bde4a69b97db53f72deb7f
refs/heads/master
2021-01-11T20:11:30.945122
2010-01-25T00:27:47
2010-01-25T00:27:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,565
h
/******************************************************************************************************** /* /* tRect.h / mojo_engine /* /* This template creates classes that represent rectangles. Typedefs are defined for a rectangle /* of integers, a rectangle of floats, and a rectangle of doubles. /* /* There are a bunch of templated non-member functions following the class definition. /* /* Copyright 2009 Robert Sacks /* /* This file is part of Mojo. You may redistribute and/or modify Mojo under the terms of the GNU /* General Public License, version 3, as published by the Free Software Foundation. You should have /* received a copy of the license with mojo. If you did not, go to http://www.gnu.org. /* /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR /* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND /* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR /* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL /* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, /* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER /* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT /* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* /********************************************************************************************************/ #pragma once #include <windows.h> #include "tPt.h" namespace mojo { //======================================================================================================= // CLASS RECT //======================================================================================================= template<class C> class tRect { public: tRect () : x(0), y(0), dx(0), dy(0) {} tRect ( tRect<C> & rh ); tRect ( C x, C y, C dx, C dy ); tRect ( tPt<C> &Pos, tPt<C> &Dim ); template<class C> friend tRect<C> & combine ( tRect<C> * combo, tRect<C> * r1, tRect<C> * r2 ); tPt<C> pos (); tPt<C> dim (); ~tRect () {;}; tRect<C> & operator= ( const tRect<C> & rh ); bool operator== (const tRect<C> & rh ); tRect<C> & operator/= ( C rh ); C x; // x position C y; // y position C dx; // width C dy; // height }; //======================================================================================================= // TYPEDEFS //======================================================================================================= typedef tRect<int> cRectI; typedef tRect<double> cRectD; typedef tRect<float> cRectF; //======================================================================================================= // CODE //======================================================================================================= //------------------------------------------------------------------------------------------------------- // OPERATOR /= //------------------------------------------------------------------------------------------------------- template<class C> tRect<C>& tRect<C>::operator/= ( C rh ) { x /= rh; y /= rh; dx /= rh; dy /= rh; return *this; } //------------------------------------------------------------------------------------------------------- // IS POINT IN RECT // b = big, s = small; the small one is moved so none of it is outside b // if small is too big to fit, its top-left is inside and bottom-right is outside //------------------------------------------------------------------------------------------------------- template<class C> void move_rect_inside_rect ( tRect<C> * b, tRect<C> * s ) { tPt<C> ul ( s->x, s->y ); tPt<C> lr ( s->x + s->dx, s->y + s->dy ); if ( ! is_point_in_rect ( b, & lr ) ) { if ( b->x + b->dx < lr.x ) // to far right s->x = b->x + b->dx - s->dx; if ( b->y + b->dy < lr.y ) // too far down s->y = b->y + b->dy - s->dy; } if ( ! is_point_in_rect ( b, & ul ) ) { if ( ul.x < b->x ) // too far left s->x = b->x; if ( ul.y < b->y ) // too far up s->y = b->y; } } //------------------------------------------------------------------------------------------------------- // IS POINT IN RECT //------------------------------------------------------------------------------------------------------- template<class C> bool is_point_in_rect ( tRect<C> * r, tPt<C> * p ) { if ( r->x <= p->x && r->y <= p->y && p->x < r->x + r->dx && p->y < r->y + r->dy ) return true; else return false; } //------------------------------------------------------------------------------------------------------- // COMBINE aka UNION //------------------------------------------------------------------------------------------------------- template<class C> tRect<C>& combine ( tRect<C> * com, tRect<C> * r1, tRect<C> * r2 ) { com->x = r1->x < r2->x ? r1->x : r2->x; com->y = r1->y < r2->y ? r1->y : r2->y; C x1abs = r1->x + r1->dx; C x2abs = r2->x + r2->dx; if ( x1abs < x2abs ) com->dx = x2abs - com->x; else com->dx = x1abs - com->x; C y1abs = r1->y + r1->dy; C y2abs = r2->y + r2->dy; if ( y1abs < y2abs ) com->dy = y2abs - com->y; else com->dy = y1abs - com->y; return *com; } //------------------------------------------------------------------------------------------------------- // POS //------------------------------------------------------------------------------------------------------- template<class C> mojo::tPt<C> tRect<C>::pos() { mojo::tPt<C> ret ( x,y); return ret; } //------------------------------------------------------------------------------------------------------- // DIM //------------------------------------------------------------------------------------------------------- template<class C> tPt<C> tRect<C>::dim() { tPt<C> ret ( dx, dy); return ret; } // ------------------------------------------------------------ // OPERATOR == // ------------------------------------------------------------ template<class C> bool tRect<C>::operator== ( const tRect<C> & rh ) { if ( x == rh.x && y == rh.y && dx == rh.dx && dy == rh.dy ) return true; else return false; } //------------------------------------------------------------------------------------------------------- // CONSTRUCTORS //------------------------------------------------------------------------------------------------------- template<class C> tRect<C>::tRect ( tRect<C> & rh ) { x = rh.x; y = rh.y; dx = rh.dx; dy = rh.dy; } template<class C> tRect<C>::tRect ( C rh_x, C rh_y, C rh_dx, C rh_dy ) { x = rh_x; y = rh_y; dx = rh_dx; dy = rh_dy; } template<class C> tRect<C>::tRect ( tPt<C> & Pos, tPt<C> & Dim ) { x = Pos.x; y = Pos.y; dx = Dim.x; dy = Dim.y; } //------------------------------------------------------------------------------------------------------- // OPERATOR= //------------------------------------------------------------------------------------------------------- template<class C> tRect<C> & tRect<C>::operator= ( const tRect<C> & rh ) { x = rh.x; y = rh.y; dx = rh.dx; dy = rh.dy; return *this; } } // namespace
[ [ [ 1, 241 ] ] ]
82979eb6bf2954ca2a953820688819fea7876726
2982a765bb21c5396587c86ecef8ca5eb100811f
/util/wm5/LibMathematics/Base/Wm5BitHacks.h
3ebf1592fcfd3eb8ef23665e518b30d207c14375
[]
no_license
evanw/cs224final
1a68c6be4cf66a82c991c145bcf140d96af847aa
af2af32732535f2f58bf49ecb4615c80f141ea5b
refs/heads/master
2023-05-30T19:48:26.968407
2011-05-10T16:21:37
2011-05-10T16:21:37
1,653,696
27
9
null
null
null
null
UTF-8
C++
false
false
1,028
h
// Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.1 (2010/10/01) // Bit hacks are available at // http://graphics.stanford.edu/~seander/bithacks.html #ifndef WM5BITHACKS_H #define WM5BITHACKS_H #include "Wm5MathematicsLIB.h" namespace Wm5 { WM5_MATHEMATICS_ITEM bool IsPowerOfTwo (unsigned int value); WM5_MATHEMATICS_ITEM bool IsPowerOfTwo (int value); WM5_MATHEMATICS_ITEM unsigned int Log2OfPowerOfTwo (unsigned int powerOfTwo); WM5_MATHEMATICS_ITEM int Log2OfPowerOfTwo (int powerOfTwo); // Fast conversion from a IEEE 32-bit floating point number F in [0,1] to a // a 32-bit integer I in [0,2^P-1]. The input 'value' is F, the input // 'power' is P, and the return value of the function is I. inline int ScaledFloatToInt (float value, int power); #include "Wm5BitHacks.inl" } #endif
[ [ [ 1, 35 ] ] ]
d5399895a729fa1309684f0b5b9a71cfeb950722
51e1cf5dc3b99e8eecffcf5790ada07b2f03f39c
/SMC/src/enemy.cpp
f91c460552dad478ff6a3a99df4df692b0ee2668
[]
no_license
jdek/jim-pspware
c3e043b59a69cf5c28daf62dc9d8dca5daf87589
fd779e1148caac2da4c590844db7235357b47f7e
refs/heads/master
2021-05-31T06:45:03.953631
2007-06-25T22:45:26
2007-06-25T22:45:26
56,973,047
2
1
null
null
null
null
UTF-8
C++
false
false
1,369
cpp
/*************************************************************************** enemy.cpp - base class for all enemies ------------------- copyright : (C) 2003-2004 by Artur Hallmann (C) 2003-2005 by FluXy ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "include/globals.h" /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ cEnemy :: cEnemy( double x, double y ) : cObjectSprite( x, y ) { array = ARRAY_ENEMY; type = TYPE_ENEMY; state = FALL; dead = 0; counter = 0; walk_count = 0; } cEnemy :: ~cEnemy( void ) { } void cEnemy :: DieStep( void ) { // virtual function }
[ "rinco@ff2c0c17-07fa-0310-a4bd-d48831021cb5" ]
[ [ [ 1, 41 ] ] ]
39d1aa41b945da35ef881faa227235dac60bc48b
27651c3f5f829bff0720d7f835cfaadf366ee8fa
/QBluetooth/ServiceAdvertiser/QBtServiceAdvertiser_symbian.h
9a459feb5ffb19c6ddb453d192ccfbc907e00d72
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
cpscotti/Push-Snowboarding
8883907e7ee2ddb9a013faf97f2d9673b9d0fad5
cc3cc940292d6d728865fe38018d34b596943153
refs/heads/master
2021-05-27T16:35:49.846278
2011-07-08T10:25:17
2011-07-08T10:25:17
1,395,155
1
1
null
null
null
null
UTF-8
C++
false
false
3,287
h
/* * QBtServiceAdvertiser_symbian.h * * * Author: Ftylitakis Nikolaos * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef QBTSERVICEADVERTISER_SYMBIAN_H_ #define QBTSERVICEADVERTISER_SYMBIAN_H_ // INCLUDES #include <e32base.h> #include <coecntrl.h> #include <es_sock.h> #include <btdevice.h> #include <bt_sock.h> #include <btsdp.h> #include <btmanclient.h> #include <QBtTypes.h> #include <QBtServiceAdvertiser.h> class QBtServiceAdvertiserPrivate : public CBase { public: /*! * NewL(QBtServiceAdvertiser* publicClass) * * Create new QBtServiceAdvertiserPrivate object * return a pointer to the created instance of QBtServiceAdvertiserPrivate */ static QBtServiceAdvertiserPrivate* NewL(QBtServiceAdvertiser* publicClass); /*! * NewLC(QBtServiceAdvertiser* publicClass) * */ static QBtServiceAdvertiserPrivate* NewLC(QBtServiceAdvertiser* publicClass); /*! * ~CDeviceDiscoverer() * * Destroy the object and release all memory objects */ ~QBtServiceAdvertiserPrivate(); /*! * StartAdvertiser(const QBtService& service) * * Starts the service advertiser. * * param service the service class that contains all the necessery * information for transmitting the service */ void StartAdvertiser(const QBtService& service); /*! * StopAdvertiser() * * Stops the service advertiser. our entry from service * discovery database will be removed. */ void StopAdvertiser(); /*! * UpdateAvailability() * * Updates the availability of advertised service. the service * record in service discovery database will be updated accordingly. * * param aAvailable true if the service should be set as available, * false if unavailable. */ void UpdateAvailability(TBool aAvailable); private: /*! * QBtServiceAdvertiserPrivate(QBtServiceAdvertiser* publicClass) * * Perform the first phase of two phase construction */ QBtServiceAdvertiserPrivate(QBtServiceAdvertiser* publicClass); /*! * ConstructL() * */ void ConstructL(); private: // service discovery protocol session RSdp iSdp; // service discovery database (sdp) RSdpDatabase iSdpDB; // service record TSdpServRecordHandle iRecord; // service record state TInt iRecordState; // local service to advertise QBtService* localService; //pointer to parent object (from constructor). Not owned by this class QBtServiceAdvertiser *p_ptr; }; #endif /* QBTSERVICEADVERTISER_SYMBIAN_H_ */
[ "cpscotti@c819a03f-852d-4de4-a68c-c3ac47756727" ]
[ [ [ 1, 122 ] ] ]
c82ba0f927cb2f5258be35afe778794bec2e6164
335783c9e5837a1b626073d1288b492f9f6b057f
/source/fbxcmd/daolib/Model/MAT/MATFile.cpp
712f2858382245828ef2767e6ec3f7c09b9427b7
[ "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
11,543
cpp
/********************************************************************** *< FILE: MATFile.h DESCRIPTION: MAT File Format HISTORY: *> Copyright (c) 2009, All Rights Reserved. **********************************************************************/ #include <stdafx.h> #include <windows.h> #include <sys/stat.h> #include <sys/types.h> #include <stdexcept> #include <stdio.h> #include <stdarg.h> #include <tchar.h> #include <typeinfo.h> #include "expat.h" #include "MATFile.h" #include "cxmlparser.h" #include "DataHeader.h" #include "daolog.h" using namespace std; using namespace boost; using namespace DAO; using namespace DAO::MAT; class MATParser { Context context; Material *p; public: void set_Object(Material*pObject){ this->p = pObject; } void StartElementHandler(XML_Parser parser, const XML_Char *name, const XML_Char **atts); void EndElementHandler(XML_Parser parser, const XML_Char *name); }; ////////////////////////////////////////////////////////////////////////// class MATFile::Impl { public: MaterialPtr root; }; DAO::MAT::MATFile::MATFile() { } DAO::MAT::MATFile::~MATFile() { } void DAO::MAT::MATFile::open( const _tstring& filename ) { CXmlParser<MATParser> modelParser; modelParser.set_Object( this->pimpl->root.ToPointer() ); modelParser.Reset(); modelParser.ParseFile(filename.c_str()); } void DAO::MAT::MATFile::open( IDAOStream& stream ) { CXmlParser<MATParser> modelParser; modelParser.set_Object( this->pimpl->root.ToPointer() ); XML_Status status = XML_STATUS_ERROR; char buf[0x1000]; status = XML_STATUS_OK; for( size_t nRead = stream.Read(buf, 1, sizeof(buf)) ; nRead != 0 && status == XML_STATUS_OK ; nRead = stream.Read(buf, 1, sizeof(buf)) ) { int isFinal = (nRead != sizeof(buf)); status = modelParser.ParseString(buf, nRead, isFinal); } } void DAO::MAT::MATFile::save( const _tstring& filename ) { } void DAO::MAT::MATFile::save( IDAOStream& stream ) { } void DAO::MAT::MATFile::dump() { } void DAO::MAT::MATFile::dump( const _tstring& filename ) { } DAO::MAT::MaterialRef DAO::MAT::MATFile::get_Object() { return MaterialRef(this->pimpl->root); } DAO::MAT::MaterialRef DAO::MAT::MATFile::get_Object() const { return MaterialRef(this->pimpl->root); } ////////////////////////////////////////////////////////////////////////// static bool ParseParameterSet( const XML_Char * name, const XML_Char ** atts, ParameterSet &set ) { if ( 0 == _tcscmp( name, _T("Parameter") ) ) { const XML_Char *type = XML_LookupTextAttribute("Type", atts); const XML_Char *name = XML_LookupTextAttribute("Name", atts); int size = XML_LookupIntAttribute("Size", atts, 0); if (type == NULL || name == NULL) return false; stringstream sval(XML_LookupStringAttribute("Default", atts)); if ( 0 == _tcscmp( type, _T("Float") ) ) { float value; sval >> value; set[name] = value; } else if ( 0 == _tcscmp( type, _T("Vector2f") ) ) { Vector2f value; sval >> value.x >> value.y ; set[name] = value; } else if ( 0 == _tcscmp( type, _T("Vector3f") ) ) { Vector4f value; sval >> value.x >> value.y >> value.z; set[name] = value; } else if ( 0 == _tcscmp( type, _T("Vector4f") ) ) { Vector4f value; sval >> value.x >> value.y >> value.z >> value.w; set[name] = value; } else if ( 0 == _tcscmp( type, _T("Matrix4x4f") ) ) { Matrix44 m; sval >> m[0][0] >> m[0][1] >> m[0][2] >> m[0][3] >> m[1][0] >> m[1][1] >> m[1][2] >> m[1][3] >> m[2][0] >> m[2][1] >> m[2][2] >> m[2][3] >> m[3][0] >> m[3][1] >> m[3][2] >> m[3][3] ; set[name] = m; } else if ( 0 == _tcscmp( type, _T("Vector4fArray") ) ) { set[name] = Vector4fArray(); Vector4fArray &m = any_cast<Vector4fArray &>(set[name]); m.resize(size); for (int i=0; i<size; ++i) { Vector4f& value = m[i]; sval >> value.x >> value.y >> value.y >> value.w; } } else if ( 0 == _tcscmp( type, _T("Texture") ) ) { set[name] = Texture(); Texture &m = any_cast<Texture&>(set[name]); m.Name = XML_LookupStringAttribute("Name", atts); m.SamplerName = XML_LookupStringAttribute("SamplerName", atts); m.Default = XML_LookupStringAttribute("Default", atts); } else { DAOLog::Debug("Unknown parameter specified: '%s'", type); } return true; } return false; } struct PassContext : ParserContext<Pass> { typedef ParserContext<Pass> base; PassContext( Pass* val ) : base(val) {} PassContext( Pass& val ) : base(val) {} bool StartElementHandler(Context& context, const XML_Char *name, const XML_Char **atts) { Pass& val = this->ref(); if ( _tcscmp(name, TEXT("Pass")) == 0 ) { val.Name = XML_LookupStringAttribute("Name", atts); val.VertexShader = XML_LookupStringAttribute("VertexShader", atts); val.PixelShader = XML_LookupStringAttribute("PixelShader", atts); val.State = XML_LookupStringAttribute("State", atts); return true; } else if ( 0 == _tcscmp( name, _T("ParameterSetRef") ) ) { val.RefName = XML_LookupStringAttribute("Ref", atts); } else if ( 0 == _tcscmp( name, _T("InternalParameter") ) ) { return true; } else { Pass& val = this->ref(); if ( ParseParameterSet(name, atts, val.Parameters) ) return true; } return false; } }; struct TechniqueContext : ParserContext<Technique> { typedef ParserContext<Technique> base; TechniqueContext( Technique* val ) : base(val) {} TechniqueContext( Technique& val ) : base(val) {} bool StartElementHandler(Context& context, const XML_Char *name, const XML_Char **atts) { Technique& val = this->ref(); if ( 0 == _tcscmp( name, _T("Technique") ) ) { val.Name = XML_LookupStringAttribute("Name", atts); return true; } else if ( 0 == _tcscmp( name, _T("Pass") ) ) { context.contexts.push_front( new PassContext(val.Pass) ); } else if ( 0 == _tcscmp( name, _T("LogicTest") ) ) { context.contexts.push_front( new PassContext(val.Pass) ); } return false; } }; struct LogicContext : ParserContext<Logic> { typedef ParserContext<Logic> base; LogicContext( Logic* val ) : base(val) {} LogicContext( Logic& val ) : base(val) {} bool StartElementHandler(Context& context, const XML_Char *name, const XML_Char **atts) { Logic& val = this->ref(); if ( 0 == _tcscmp( name, _T("Logic") ) ) { val.Note = XML_LookupStringAttribute("Note", atts); return true; } else if ( 0 == _tcscmp( name, _T("Technique") ) ) { context.contexts.push_front( new TechniqueContext(val.Technique) ); } return false; } }; struct LogicRootContext : ParserContext<LogicRoot> { typedef ParserContext<LogicRoot> base; LogicRootContext( LogicRoot* val ) : base(val) {} LogicRootContext( LogicRoot& val ) : base(val) {} bool StartElementHandler(Context& context, const XML_Char *name, const XML_Char **atts) { LogicRoot& val = this->ref(); if ( 0 == _tcscmp( name, _T("Logic") ) ) { if (val.Note.empty()) { val.Note = XML_LookupStringAttribute("Note", atts); return true; } else { LogicList::iterator pr = val.Logic.insert(val.Logic.end(), Logic() ); if (pr != val.Logic.end()) { context.contexts.push_front( new LogicContext(*pr) ); } return false; } } return false; } }; struct SemanticContext : ParserContext<Semantic> { typedef ParserContext<Semantic> base; SemanticContext( Semantic* val ) : base(val) {} SemanticContext( Semantic& val ) : base(val) {} bool StartElementHandler(Context& context, const XML_Char *name, const XML_Char **atts) { Semantic& val = this->ref(); if ( 0 == _tcscmp( name, _T("Semantic") ) ) { val.Name = XML_LookupStringAttribute("Name", atts); val.RenderClass = XML_LookupStringAttribute("RenderClass", atts); return true; } else if ( 0 == _tcscmp( name, _T("Logic") ) ) { context.contexts.push_front( new LogicRootContext(val.Logic) ); return false; } return false; } }; struct ParameterSetContext : ParserContext<ParameterSet> { typedef ParserContext<ParameterSet> base; ParameterSetContext( ParameterSet* val ) : base(val) {} ParameterSetContext( ParameterSet& val ) : base(val) {} bool StartElementHandler(Context& context, const XML_Char *name, const XML_Char **atts) { ParameterSet& set = this->ref(); if ( 0 == _tcscmp( name, _T("ParameterSet") ) ) { return true; }else if ( 0 == _tcscmp( name, _T("InternalParameter") ) ) { return true; } else { if ( ParseParameterSet(name, atts, set) ) return true; } return false; } }; ////////////////////////////////////////////////////////////////////////// struct MaterialContext : ParserContext<Material> { typedef ParserContext<Material> base; MaterialContext( Material* val ) : base(val) {} MaterialContext( Material& val ) : base(val) {} bool StartElementHandler(Context& context, const XML_Char *name, const XML_Char **atts) { Material& val = this->ref(); if ( _tcscmp(name, TEXT("Material")) == 0 ) { val.Name = XML_LookupStringAttribute("Name", atts); return true; } else if ( _tcscmp(name, TEXT("ParameterSet")) == 0 ) { ParameterSets& list = val.ParameterSets; _tstring id = XML_LookupStringAttribute("Name", atts); std::pair<ParameterSets::iterator, bool> pr = list.insert( ParameterSets::value_type(id, ParameterSet()) ); if (pr.second) { ParameterSet& val = (*pr.first).second; context.contexts.push_front( new ParameterSetContext( val ) ); } } else if ( _tcscmp(name, TEXT("Semantic")) == 0 ) { SemanticMap& list = val.Semantics; _tstring id = XML_LookupStringAttribute("Name", atts); std::pair<SemanticMap::iterator, bool> pr = list.insert( SemanticMap::value_type(id, Semantic()) ); if (pr.second) { Semantic& val = (*pr.first).second; context.contexts.push_front( new SemanticContext( val ) ); } } return false; } }; ////////////////////////////////////////////////////////////////////////// void MATParser::StartElementHandler( XML_Parser parser, const XML_Char *name, const XML_Char **atts ) { context.parser = parser; size_t len = context.contexts.size(); if ( _tcscmp(name, TEXT("Material")) == 0 ) { if (p) { context.contexts.push_front( new MaterialContext(p) ); } } bool handled = false; if (!context.contexts.empty()) { handled = context.contexts.front()->StartElementHandler(context, name, atts); if (!handled && (len == context.contexts.size())) handled = true; // element handler was not added } if (!handled) { for (ContextList::iterator itr = context.contexts.begin() ; itr != context.contexts.end() ; ++itr ) { if ( IParserContext* localcontext = (*itr) ) { if ( localcontext->StartElementHandler(context, name, atts) ) { handled = true; break; } } } } if (len == context.contexts.size()) { // Add empty handler context.contexts.push_front( new ParserContext<void*>(NULL) ); } } void MATParser::EndElementHandler( XML_Parser parser, const XML_Char *name ) { if (!context.contexts.empty()) { if ( IParserContext* localcontext = context.contexts.front() ) { localcontext->EndElementHandler(context, name); context.contexts.pop_front(); delete localcontext; } } }
[ "tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 416 ] ] ]
c4c2df3b451be622889a9b1b74b8c6a3d96b7748
b0252ba622183d115d160eb28953189930ebf9c0
/Source/CGamePlayState.h
566df494af3be7924a135b941c5f7718b8226862
[]
no_license
slewicki/khanquest
6c0ced33bffd3c9ee8a60c1ef936139a594fe2fc
f2d68072a1d207f683c099372454add951da903a
refs/heads/master
2020-04-06T03:40:18.180208
2008-08-28T03:43:26
2008-08-28T03:43:26
34,305,386
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,367
h
////////////////////////////////////////////////////////// // File: "CGamePlayState.h" // // Author: Sean Hamstra (SH) // // Purpose: To contain functionality of the gameplay state ////////////////////////////////////////////////////////// #pragma once #include <windows.h> #include "IGameState.h" #include "CUnit.h" #include "CSGD_TextureManager.h" #include "CSGD_WaveManager.h" #include "CSGD_DirectInput.h" #include "CSGD_Direct3D.h" #include "CBitmapFont.h" #include "CTileEngine.h" #include "CEventSystem.h" #include "CCamera.h" #include "ObjectManager.h" #include "CParticleEngine.h" class CHUDState; class CGame; class CGamePlayState : public IGameState { private: // Wrappers CSGD_Direct3D* m_pD3D; CSGD_WaveManager* m_pWM; CSGD_TextureManager* m_pTM; CSGD_DirectInput* m_pDI; CEventSystem* m_pES; CGame* m_pCG; CCamera* m_pCamera; ObjectManager* m_pOM; CParticleEngine* m_pPE; int m_nTestEmitter; int m_nSkyCloudID; int m_nSkyCloudID2; bool m_bIsPaused; bool m_bButtonDown; CHUDState* m_pHUD; POINT m_ptBoxLocation; POINT m_ptCurrentLocation; RECT m_rSelectionBox; //Engines CTileEngine* Map; //CTile* Tile; // TEMP BUTTONS FOR DEMO - SHOW WORLD MAP AFTER WIN OR LOSS // REMOVE AFTER DEMO RECT m_rVictoryButton; //------------------------------------------------------ int m_nScrollButtonID; int m_nButtonID; int m_nHUD_ID; CBitmapFont m_cFont; int m_nLucidiaWhiteID; int m_nTerrorLevel; int m_nSelectionID; float m_fJoyTimer; POINT m_ptMousePos; bool m_bTutorial; RECT m_rTutorial; // Create a vector of list of selected units (CUnit*) and make an accessor // for the HUD to use. The HUD should disply up to 8 units, the max that can be selected. //////////////////////////////////////////// // Function: "CGamePlayState(Constructor)" // Last Modified: July 18, 2008 // Purpose: Proper singleton //////////////////////////////////////////// CGamePlayState(void); CGamePlayState(const CGamePlayState&); CGamePlayState& operator=(const CGamePlayState&); //////////////////////////////////////////// // Function: "~CGamePlayState(Destructor)" // Last Modified: July 18, 2008 // Purpose: Proper singleton //////////////////////////////////////////// ~CGamePlayState(void); ////////////////////////////////////////////// // Function: "GetSelectionRect" // Last Modified: August 05, 2008 // Purpose: Create a Selection box for Multiple Unit selection. ////////////////////////////////////////////// RECT GetSelectionRect(); public: ////////////////////////////////////////////////////// // Function: “GetInstance” // Last Modified: July 18, 2008 // Purpose: To return an instance of the class ////////////////////////////////////////////////////// static CGamePlayState* GetInstance(void) { static CGamePlayState instance; return &instance; } ////////////////////////////////////////////////////// // Function: “Enter” // Last Modified: July 23, 2008 // Purpose: To load up all required information ////////////////////////////////////////////////////// void Enter(void); ////////////////////////////////////////////////////// // Function: “Exit” // Last Modified: July 23, 2008 // Purpose: To unload any needed information ////////////////////////////////////////////////////// void Exit(void); ////////////////////////////////////////////////////// // Function: “Input” // Last Modified: July 23, 2008 // Purpose: To get input from the user to interact // with the state ////////////////////////////////////////////////////// bool Input(float fElapsedTime); ////////////////////////////////////////////////////// // Function: “Update” // Last Modified: July 23, 2008 // Purpose: To update our information after input ////////////////////////////////////////////////////// void Update(float fElapsedTime); ////////////////////////////////////////////////////// // Function: “Render” // Last Modified: July 23, 2008 // Purpose: To render our information to the screen ////////////////////////////////////////////////////// void Render(float fElapsedTime); /////////////////////////////////////////// // Function: Accessors // Last Modified: July 23, 2008 // Purpose : Returns the specified type. /////////////////////////////////////////// int GetTerrorLevel() { return m_nTerrorLevel; } int GetSelectionID() { return m_nSelectionID; } /////////////////////////////////////////// // Function: Modifiers // Last Modified: July 23, 2008 // Purpose : Modifies the specified type. /////////////////////////////////////////// void SetTerrorLevel(int nTerrorLevel) { m_nTerrorLevel = nTerrorLevel; } void SetPaused(bool bPaused) { m_bIsPaused = bPaused; } ////////////////////////////////////////////////////// // Function: “IntToString” // Last Modified: July 23, 2008 // Purpose: Helper function, turn int to string ////////////////////////////////////////////////////// string IntToString(int nNum); };
[ "[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec", "[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec", "[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec", "[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec" ]
[ [ [ 1, 15 ], [ 17, 17 ], [ 19, 20 ], [ 23, 29 ], [ 31, 36 ], [ 43, 43 ], [ 46, 46 ], [ 54, 57 ], [ 59, 59 ], [ 61, 62 ], [ 64, 64 ], [ 69, 86 ], [ 94, 146 ], [ 148, 154 ], [ 158, 165 ] ], [ [ 16, 16 ], [ 30, 30 ], [ 44, 45 ], [ 47, 49 ], [ 58, 58 ], [ 60, 60 ], [ 63, 63 ], [ 65, 68 ], [ 87, 93 ], [ 147, 147 ], [ 155, 156 ] ], [ [ 18, 18 ], [ 50, 50 ], [ 53, 53 ] ], [ [ 21, 22 ], [ 37, 42 ], [ 51, 52 ], [ 157, 157 ] ] ]
1f36b455e0b8083e8a7b15fe26c08059becf2e11
a5301cc32d0a44e2a560436a92f2c3a71823f079
/Facial Recognition/HaarDetector.cpp
980ed1cff60960a06d06b18c67db298a723b1b58
[]
no_license
bblonski/head-gesture-rec
3577a26a600af4a9432b520509efe80b8b780c8e
7f44d72331966d8f717fa6faab57f4f065ea2bbb
refs/heads/master
2020-05-25T12:02:36.472112
2010-06-08T01:09:56
2010-06-08T01:09:56
32,485,651
0
1
null
null
null
null
UTF-8
C++
false
false
5,653
cpp
// $Id$ // Copyright (c) 2010 by Brian Blonski #include "HaarDetector.h" const char* const HaarDetector::HAAR_CLASSIFIER_WINDOW = "Haar Classifier"; const char* const HaarDetector::HAARCASCADE_DIR = "/data/"; const char* const HaarDetector::HAARCASCADE_EYE = "haarcascade_eye_tree_eyeglasses.xml"; const char* const HaarDetector::HAARCASCADE_PROFILE = "haarcascade_profileface.xml"; const char* const HaarDetector::HAARCASCADE_FRONTALFACE = "haarcascade_frontalface_default.xml"; HaarDetector::HaarDetector() { char cascadeName[FILENAME_MAX]; // Determine Haar cascade location _getcwd(cascadeName, sizeof(cascadeName)); strcat_s(cascadeName, HAARCASCADE_DIR); strcat_s(cascadeName, HAARCASCADE_FRONTALFACE); cascade = (CvHaarClassifierCascade*)cvLoad(cascadeName); // Determine Haar cascade location _getcwd(cascadeName, sizeof(cascadeName)); strcat_s(cascadeName, HAARCASCADE_DIR); strcat_s(cascadeName, HAARCASCADE_EYE); nestedCascade = (CvHaarClassifierCascade*)cvLoad(cascadeName); init(); } HaarDetector::HaarDetector(CvHaarClassifierCascade *pCascade, CvHaarClassifierCascade* pNestedCascade) : cascade(pCascade), nestedCascade(pNestedCascade) { init(); } HaarDetector::~HaarDetector(void) { #if SHOW_WINDOWS cvDestroyWindow(HAAR_CLASSIFIER_WINDOW); #endif cvReleaseHaarClassifierCascade(&cascade); } // Initializes class void HaarDetector::init() { #if SHOW_WINDOWS cvNamedWindow(HAAR_CLASSIFIER_WINDOW, CV_WINDOW_AUTOSIZE); #endif image = NULL; } // Detects the location of the face using a haar cascade classifier CvRect* HaarDetector::detect(const IplImage* frame) { CvRect* r = new CvRect(); if(!image) { image = cvCreateImage(cvGetSize(frame), 8, 1); image->origin = frame->origin; } cvCopyImage(frame, image); // Create a new frame based on the input frame IplImage* temp = cvCreateImage(cvGetSize(image), 8, 1); // Create two points to represent corners of the face bounding box CvPoint pt1, pt2; int i; storage = cvCreateMemStorage(0); // Clear the memory storage which was used before cvClearMemStorage(storage); // Check whether the cascade has loaded successfully. Else report and error and quit if(!cascade) { image = Utils::printMsg(image, "ERROR: Could not load classifier cascade\n", cvPoint(20, 200)); throw -1; } // Find whether the cascade is loaded, to find the faces. If yes, then: if(cascade) { // There can be more than one face in an image. So create a growable sequence of faces. // Detect the objects and store them in the sequence CvSeq* faces = cvHaarDetectObjects( image, // image to detect objects in cascade, // Haar classifier casacde in internal representation storage, // Memory storage to store the result 1.1, // The factor by which the search window is scaled between scans (1.1 = 10%) 2, // Minimum number of neighbor rectangles (-1) that make up an object CV_HAAR_DO_CANNY_PRUNING, // Mode of operation cvSize(80, 80)); // Minimum window size // Loop the number of faces found. //for(i = 0; i < (faces ? faces->total : 0); i++) // only loop on the first face for(i = 0; i < (faces && faces->total ? 1 : 0); i++) { // Create a new rectangle for drawing the face memcpy(r, (CvRect*)cvGetSeqElem(faces, i), sizeof(CvRect)); // Find the dimensions of the face,and scale it if necessary pt1.x = r->x + 10; pt2.x = (r->x+r->width - 20); pt1.y = r->y; pt2.y = (r->y+r->height); frame = Utils::printCoordinates(image, r->x + 0.5*r->width, r->y + 0.5*r->height, cvPoint(20,200)); // Draw the rectangle in the input image cvRectangle(image, pt1, pt2, CV_RGB(255, 0, 0), 3, 8, 0); } if(faces->total <= 0){ free(r); return NULL; } //if (faces->total > 0 && nestedCascade) //{ // CvMat small_img_roi; // CvPoint center; // CvScalar color = {{0, 255, 0}}; // int radius; // int j; // points.clear(); // cvGetSubRect(frame, &small_img_roi, *r); // CvSeq* nestedObjects = cvHaarDetectObjects(&small_img_roi, nestedCascade, storage, 2, 2, CV_HAAR_DO_CANNY_PRUNING); // for (j = 0; j < (nestedObjects ? nestedObjects->total : 0); j++) // { // CvRect *nr = (CvRect*)cvGetSeqElem(nestedObjects, j); // center.x = cvRound((r->x + nr->x + nr->width * 0.5)); // center.y = cvRound((r->y + nr->y + nr->height * 0.5)); // radius = cvRound((nr->width + nr->height) * 0.25); // cvCircle(image, center, radius, CV_RGB(0, 0, 255), 3, 8, 0); // points.push_back(center); // } //}else //{ // free(r); // r = NULL; //} } #if SHOW_WINDOWS cvShowImage(HAAR_CLASSIFIER_WINDOW, image); #endif // Release the temp image created. cvReleaseImage(&temp); cvReleaseMemStorage(&storage); return r; } // Returns an array of points for the locations of the subfeatures. vector<CvPoint> HaarDetector::getPoints() { return points; }
[ "Brian Blonski@localhost", "bblonski@localhost" ]
[ [ [ 1, 2 ], [ 4, 5 ], [ 11, 11 ], [ 13, 13 ], [ 26, 26 ], [ 31, 31 ], [ 33, 34 ], [ 36, 36 ], [ 41, 44 ], [ 46, 46 ], [ 51, 54 ], [ 56, 56 ], [ 64, 64 ], [ 66, 69 ], [ 71, 71 ], [ 73, 73 ], [ 76, 76 ], [ 79, 82 ], [ 84, 87 ], [ 96, 97 ], [ 101, 101 ], [ 104, 105 ], [ 108, 109 ], [ 111, 112 ], [ 114, 114 ], [ 143, 144 ], [ 148, 148 ], [ 152, 155 ], [ 157, 157 ], [ 159, 160 ] ], [ [ 3, 3 ], [ 6, 10 ], [ 12, 12 ], [ 14, 25 ], [ 27, 30 ], [ 32, 32 ], [ 35, 35 ], [ 37, 40 ], [ 45, 45 ], [ 47, 50 ], [ 55, 55 ], [ 57, 63 ], [ 65, 65 ], [ 70, 70 ], [ 72, 72 ], [ 74, 75 ], [ 77, 78 ], [ 83, 83 ], [ 88, 95 ], [ 98, 100 ], [ 102, 103 ], [ 106, 107 ], [ 110, 110 ], [ 113, 113 ], [ 115, 142 ], [ 145, 147 ], [ 149, 151 ], [ 156, 156 ], [ 158, 158 ] ] ]
46e1cac176c867997ae2df4ec7383fc07603579d
6a2e2931641de25b228d323c08ea4f52908c2fad
/sample/EmbeddingInWin32/view.h
c5f6ad9e8a5159e6de0bfc545d70da7135428cbe
[]
no_license
cnsuhao/chromium_base
875417cbbab6857af2349aa57a6037b7563b5fab
e252f10aa64f0a0ec942997f73dbf3bd685087cf
refs/heads/master
2021-04-06T17:04:41.317674
2011-12-26T15:06:47
2011-12-26T15:06:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
969
h
#pragma once #include "views/widget/widget.h" #include "views/widget/widget_delegate.h" class ExampleView : public views::WidgetDelegate { public: ExampleView(); virtual ~ExampleView() {}; // Creates all the examples and shows the window. void Init(gfx::NativeWindow parent); void AttachToNativeWindow( gfx::NativeWindow parent, views::Widget* widget ); private: // views::WidgetDelegate implementation: virtual bool CanResize() const OVERRIDE; virtual bool CanMaximize() const OVERRIDE; virtual std::wstring GetWindowTitle() const OVERRIDE; virtual views::View* GetContentsView() OVERRIDE; virtual void WindowClosing() OVERRIDE; virtual views::Widget* GetWidget() OVERRIDE; virtual const views::Widget* GetWidget() const OVERRIDE; virtual views::NonClientFrameView* CreateNonClientFrameView() OVERRIDE; views::View* contents_; DISALLOW_COPY_AND_ASSIGN(ExampleView); };
[ [ [ 1, 29 ] ] ]
db83f72ce36d0a89d297bc0ae6908421af8df30c
c7120eeec717341240624c7b8a731553494ef439
/src/cplusplus/freezone-samp/src/core/samp/samp_hook_events_addresses.cpp
f35b9f8eaa58ce02f40ea98d028c2398de2900f1
[]
no_license
neverm1ndo/gta-paradise-sa
d564c1ed661090336621af1dfd04879a9c7db62d
730a89eaa6e8e4afc3395744227527748048c46d
refs/heads/master
2020-04-27T22:00:22.221323
2010-09-04T19:02:28
2010-09-04T19:02:28
174,719,907
1
0
null
2019-03-09T16:44:43
2019-03-09T16:44:43
null
WINDOWS-1251
C++
false
false
26,913
cpp
#include "config.hpp" #include "samp_hook_events_addresses.hpp" namespace samp { address_t samp_on_bad_rcon_external = 0; address_t samp_on_bad_rcon_local = 0; address_t samp_on_player_rename = 0; address_t samp_on_player_chat = 0; address_t samp_on_recvfrom = 0; address_t samp_on_sendto = 0; address_t samp_is_bad_nick = 0; samp_hooks_t init() { samp_hooks_t rezult; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* { samp_hook_t hook(0x00476D90, "Windows 0.2.2 United"); hook.E8.push_back(replace_pair_t(0x0048235B, &samp_on_bad_rcon_external)); hook.E8.push_back(replace_pair_t(0x0047A98D, &samp_on_bad_rcon_local)); hook.FF15.push_back(replace_pair_t(0x0045E154, &samp_on_recvfrom)); hook.FF15.push_back(replace_pair_t(0x0047450A, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x00481C3E, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x00481D0F, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x00481EFA, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x00482182, &samp_on_sendto)); rezult.insert(std::make_pair("07fd932f7dd11c9b4f0e85e445c9b41f4614e37b", hook)); } { samp_hook_t hook(0x0046A590, "Windows 0.2X"); hook.E8.push_back(replace_pair_t(0x00475E31, &samp_on_bad_rcon_external)); hook.E8.push_back(replace_pair_t(0x0046E1EF, &samp_on_bad_rcon_local)); hook.FF15.push_back(replace_pair_t(0x00451744, &samp_on_recvfrom)); hook.FF15.push_back(replace_pair_t(0x00467BFA, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x004756FE, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x004757BF, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x004759AA, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x00475C32, &samp_on_sendto)); rezult.insert(std::make_pair("2b15c53b93a379629a59a96339baffcf9ebf3bcf", hook)); } { samp_hook_t hook(0x00477A30, "Windows 0.3a"); hook.E8.push_back(replace_pair_t(0x0047EB05, &samp_on_bad_rcon_external)); hook.E8.push_back(replace_pair_t(0x0047B51C, &samp_on_bad_rcon_local)); hook.E8.push_back(replace_pair_t(0x004676A9, &samp_on_player_rename)); hook.E8.push_back(replace_pair_t(0x0047C48C, &samp_on_player_chat)); hook.FF15.push_back(replace_pair_t(0x0045D8F2, &samp_on_recvfrom)); hook.FF15.push_back(replace_pair_t(0x004764BA, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x0047E3EE, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x0047E4AF, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x0047E68F, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x0047E914, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x004675A9, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x0047BE6B, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x0047C1FD, &samp_is_bad_nick)); rezult.insert(std::make_pair("e00401cc4d357c4017f178c588dcdc80230705f2", hook)); } */ { samp_hook_t hook(0x00478910, "Windows 0.3a R7"); hook.E8.push_back(replace_pair_t(0x0047FBA5, &samp_on_bad_rcon_external)); // "BAD RCON ATTEMPT BY: %s" hook.E8.push_back(replace_pair_t(0x0047C5BE, &samp_on_bad_rcon_local)); // "RCON (In-Game): Player #%d (%s) <%s> failed login." hook.E8.push_back(replace_pair_t(0x0047D54C, &samp_on_player_chat)); // "[chat] [%s]: %s" hook.E8.push_back(replace_pair_t(0x00467E49, &samp_on_player_rename)); // "[nick] %s nick changed to %s" hook.E8.push_back(replace_pair_t(0x00467D49, &samp_is_bad_nick)); // "SetPlayerName", см samp_on_player_rename, 6 блок с начала функции hook.E8.push_back(replace_pair_t(0x0047CF2B, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x0047D2BD, &samp_is_bad_nick)); hook.FF15.push_back(replace_pair_t(0x0045D322, &samp_on_recvfrom)); // recvfrom hook._8B1D.push_back(replace_pair_t(0x0045D190, &samp_on_sendto)); // __imp_sendto hook.FF15.push_back(replace_pair_t(0x0047739A, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x0047F48E, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x0047F54F, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x0047F72F, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x0047F9B4, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x00404E45, &samp_on_sendto)); // sendto rezult.insert(std::make_pair("dc384103bd9eb23080de94756cab993e63f3d8d9", hook)); // Нормальная версия самп сервера R7 rezult.insert(std::make_pair("7ad254501e77ea8c8358ed3fdb705895c05e7db9", hook)); // Версия самп сервера для Андреуса a1a R7 rezult.insert(std::make_pair("db16383f2327f935d40e85ee23dbbd2ab5a17a44", hook)); // Версия самп сервера для Гостауна g6a R7 rezult.insert(std::make_pair("68b181214e379b3e112f541131e44ef83c80c3d0", hook)); // Версия самп сервера для Юнайтеда u1a R7 } { samp_hook_t hook(0x00497140, "Windows 0.3b R2"); hook.E8.push_back(replace_pair_t(0x004A07A5, &samp_on_bad_rcon_external)); // sequence of bytes, "BAD RCON ATTEMPT BY: %s" hook.E8.push_back(replace_pair_t(0x0049AF4E, &samp_on_bad_rcon_local)); // sequence of bytes, "RCON (In-Game): Player #%d (%s) <%s> failed login." hook.E8.push_back(replace_pair_t(0x0049BB82, &samp_on_player_chat)); // sequence of bytes, "[chat] [%s]: %s" hook.E8.push_back(replace_pair_t(0x0048E919, &samp_on_player_rename)); // sequence of bytes, "[nick] %s nick changed to %s" hook.E8.push_back(replace_pair_t(0x0048E819, &samp_is_bad_nick)); // sequence of bytes, "SetPlayerName", 6 блок с начала функции, см samp_on_player_rename hook.E8.push_back(replace_pair_t(0x0049B8ED, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x0049F84A, &samp_is_bad_nick)); hook.FF15.push_back(replace_pair_t(0x00479F22, &samp_on_recvfrom)); // смотрим таблицу импорта, recvfrom из WSOCK32 hook._8B1D.push_back(replace_pair_t(0x00479D90, &samp_on_sendto)); // __imp_sendto hook.FF15.push_back(replace_pair_t(0x00495BCA, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x004A008E, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x004A014F, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x004A032F, &samp_on_sendto)); hook.FF15.push_back(replace_pair_t(0x004A05B4, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x00404E45, &samp_on_sendto)); // sendto rezult.insert(std::make_pair("da39a3ee5e6b4b0d3255bfef95601890afd80709", hook)); // Нормальная версия самп сервера } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* { samp_hook_t hook(0x8087B76, "Linux 0.2.2 United"); hook.E8.push_back(replace_pair_t(0x809E7E2, &samp_on_bad_rcon_external)); hook.E8.push_back(replace_pair_t(0x808DC0E, &samp_on_bad_rcon_local)); hook.E8.push_back(replace_pair_t(0x804D5C1, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x80E341A, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x804D57A, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8060CF4, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x809DE0D, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x809E0E5, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x809E2EA, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x809E562, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x809E923, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x80E35C2, &samp_on_sendto)); rezult.insert(std::make_pair("6bf4de0c60c944e11c26f61b670ee6d50f571370", hook)); } { samp_hook_t hook(0x807D760, "Linux 0.2X"); hook.E8.push_back(replace_pair_t(0x8091785, &samp_on_bad_rcon_external)); hook.E8.push_back(replace_pair_t(0x80827C8, &samp_on_bad_rcon_local)); hook.E8.push_back(replace_pair_t(0x804D381, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x80CD002, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x804CEFE, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x805CCEE, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8090F0A, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x80911FE, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8091412, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x80915EC, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8091762, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x80CD1B1, &samp_on_sendto)); rezult.insert(std::make_pair("57cf13f09f9f6d31465753346078322c3bd88450", hook)); } { samp_hook_t hook(0x8074F24, "Linux 0.3a R2"); hook.E8.push_back(replace_pair_t(0x8089060, &samp_on_bad_rcon_external)); hook.E8.push_back(replace_pair_t(0x8079C14, &samp_on_bad_rcon_local)); hook.E8.push_back(replace_pair_t(0x804DC60, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x80C1399, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x804DC02, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x805CD20, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8088865, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8088A80, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8088C33, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8088E3B, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x808919C, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x80C14FE, &samp_on_sendto)); rezult.insert(std::make_pair("8587d1fc896abf977f61f4dd158cc0ed0bd677f7", hook)); } { samp_hook_t hook(0x8074F24, "Linux 0.3a R3"); hook.E8.push_back(replace_pair_t(0x8089060, &samp_on_bad_rcon_external)); hook.E8.push_back(replace_pair_t(0x8079C14, &samp_on_bad_rcon_local)); hook.E8.push_back(replace_pair_t(0x80AFF48, &samp_on_player_rename)); hook.E8.push_back(replace_pair_t(0x804DC60, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x80C0B69, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x804DC02, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x805CD20, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8088865, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8088A80, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8088C33, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x8088E3B, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x808919C, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x80C0CCE, &samp_on_sendto)); rezult.insert(std::make_pair("bcc7a4cd8e29dc886875f00537a62b104113df0a", hook)); } { samp_hook_t hook(0x8074F58, "Linux 0.3a R4"); hook.E8.push_back(replace_pair_t(0x080891F8, &samp_on_bad_rcon_external)); hook.E8.push_back(replace_pair_t(0x08079C9A, &samp_on_bad_rcon_local)); hook.E8.push_back(replace_pair_t(0x0807BA0B, &samp_on_player_chat)); hook.E8.push_back(replace_pair_t(0x080B0108, &samp_on_player_rename)); hook.E8.push_back(replace_pair_t(0x0804DC74, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x080C0F69, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x0804DC16, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0805CD0C, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x080889FD, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x08088C18, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x08088DCB, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x08088FD3, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x08089334, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x080C10CE, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0807B04A, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x0807B6F5, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x080AFF97, &samp_is_bad_nick)); rezult.insert(std::make_pair("27f7cda5f4af9564af2369dc68aa9be370a2bbc7", hook)); // Нормальная версия самп сервера rezult.insert(std::make_pair("b1c4cd4ecb90985c4be97b94858aee574470800a", hook)); // Версия самп сервера для Гостауна g6a (версия = 59421) rezult.insert(std::make_pair("2b1be8b67303f74c3abeef41ec1638c6a1a624c3", hook)); // Версия самп сервера для Гостауна g6a R2 rezult.insert(std::make_pair("4b67f9acea723d11a596db08ec80519d33f66f76", hook)); // Версия самп сервера для Юнайтеда u1a R2 rezult.insert(std::make_pair("9511a53b037cff7a45607cee82bf0dbf1fa57639", hook)); // Версия самп сервера для Андреуса a1a R2 } { samp_hook_t hook(0x80763B0, "Linux 0.3a R5"); hook.E8.push_back(replace_pair_t(0x0808C99E, &samp_on_bad_rcon_external)); // "BAD RCON ATTEMPT BY: %s" hook.E8.push_back(replace_pair_t(0x0807B903, &samp_on_bad_rcon_local)); // "RCON (In-Game): Player #%d (%s) <%s> failed login." hook.E8.push_back(replace_pair_t(0x0807E0EE, &samp_on_player_chat)); // "[chat] [%s]: %s" hook.E8.push_back(replace_pair_t(0x080B4F8A, &samp_on_player_rename)); // "[nick] %s nick changed to %s" hook.E8.push_back(replace_pair_t(0x0804E07E, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x080C78D5, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x0804DBEE, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0805CC6E, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C12A, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C404, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C610, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C7F0, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C97E, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x080C7731, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0807DA5F, &samp_is_bad_nick)); // "SetPlayerName", см samp_on_player_rename, 6 блок с начала функции hook.E8.push_back(replace_pair_t(0x0807DED7, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x080B4E1D, &samp_is_bad_nick)); rezult.insert(std::make_pair("3cfdc3aa8dfc58085484641348b7df7f80fe28af", hook)); // Нормальная версия самп сервера rezult.insert(std::make_pair("ef4f27d90e2573ebbae7f2d22ac8fbb9cc396d2d", hook)); // Версия самп сервера для Андреуса a1a R4 rezult.insert(std::make_pair("97757dd3c0497cf28e6654f583876295c65012af", hook)); // Версия самп сервера для Гостауна g6a R4 rezult.insert(std::make_pair("beefe84853c509953106db12444fd094aa2283e8", hook)); // Версия самп сервера для Юнайтеда u1a R4 } { samp_hook_t hook(0x080763B0, "Linux 0.3a R6"); hook.E8.push_back(replace_pair_t(0x0808C78E, &samp_on_bad_rcon_external)); // "BAD RCON ATTEMPT BY: %s" hook.E8.push_back(replace_pair_t(0x0807B903, &samp_on_bad_rcon_local)); // "RCON (In-Game): Player #%d (%s) <%s> failed login." hook.E8.push_back(replace_pair_t(0x0807E0EE, &samp_on_player_chat)); // "[chat] [%s]: %s" hook.E8.push_back(replace_pair_t(0x080B4D7A, &samp_on_player_rename)); // "[nick] %s nick changed to %s" hook.E8.push_back(replace_pair_t(0x0804E07E, &samp_on_recvfrom)); // objdump -D samp03svr | grep 'recvfrom@plt', берем адреса из первого столбика hook.E8.push_back(replace_pair_t(0x080C7775, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x0804DBEE, &samp_on_sendto)); // objdump -D samp03svr | grep 'sendto@plt', берем адреса из первого столбика hook.E8.push_back(replace_pair_t(0x0805CC6E, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808BF1A, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C1F4, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C400, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C5E0, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C76E, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x080C75D1, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0807DA5F, &samp_is_bad_nick)); // "SetPlayerName", см samp_on_player_rename, 6 блок с начала функции hook.E8.push_back(replace_pair_t(0x0807DED7, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x080B4C0D, &samp_is_bad_nick)); rezult.insert(std::make_pair("4ed67e0d2699db78096f11e0e31427a3ae079ed1", hook)); // Нормальная версия самп сервера R5 rezult.insert(std::make_pair("099d9a5722001607d0a269a941846a8e60921223", hook)); // Версия самп сервера для Андреуса a1a R5 rezult.insert(std::make_pair("706fcb622e9bfe1a418b16558542e46dfa488b5a", hook)); // Версия самп сервера для Гостауна g6a R5 rezult.insert(std::make_pair("a627d0d7ce9a53a7af50d02f9f70368090f51578", hook)); // Версия самп сервера для Юнайтеда u1a R5 } */ { samp_hook_t hook(0x080763B0, "Linux 0.3a R7"); hook.E8.push_back(replace_pair_t(0x0808C79E, &samp_on_bad_rcon_external)); // "BAD RCON ATTEMPT BY: %s" hook.E8.push_back(replace_pair_t(0x0807B903, &samp_on_bad_rcon_local)); // "RCON (In-Game): Player #%d (%s) <%s> failed login." hook.E8.push_back(replace_pair_t(0x0807E0EE, &samp_on_player_chat)); // "[chat] [%s]: %s" hook.E8.push_back(replace_pair_t(0x080B4D8A, &samp_on_player_rename)); // "[nick] %s nick changed to %s" hook.E8.push_back(replace_pair_t(0x0807DA5F, &samp_is_bad_nick)); // "SetPlayerName", см samp_on_player_rename, 6 блок с начала функции hook.E8.push_back(replace_pair_t(0x0807DED7, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x080B4C1D, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x0804E07E, &samp_on_recvfrom)); // objdump -D samp03svr | grep 'recvfrom@plt', берем адреса из первого столбика hook.E8.push_back(replace_pair_t(0x080C7785, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x0804DBEE, &samp_on_sendto)); // objdump -D samp03svr | grep 'sendto@plt', берем адреса из первого столбика hook.E8.push_back(replace_pair_t(0x0805CC6E, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808BF2A, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C204, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C410, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C5F0, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0808C77E, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x080C75E1, &samp_on_sendto)); rezult.insert(std::make_pair("ef98b2427052df1ea654b8575a2a1cea042a318a", hook)); // Нормальная версия самп сервера R7 rezult.insert(std::make_pair("eaa290a39eecd37a99d189eaaaeb593dace2229b", hook)); // Версия самп сервера для Андреуса a1a R7 rezult.insert(std::make_pair("99212b20cc05f3cd558a2340aa3d55e97a60f7f9", hook)); // Версия самп сервера для Гостауна g6a R7 rezult.insert(std::make_pair("125c66bf2fdd3ff31fed302dcf74c186a83d913d", hook)); // Версия самп сервера для Юнайтеда u1a R7 } { samp_hook_t hook(0x08076B10, "Linux 0.3b R2"); hook.E8.push_back(replace_pair_t(0x0809FDCE, &samp_on_bad_rcon_external)); // "BAD RCON ATTEMPT BY: %s" hook.E8.push_back(replace_pair_t(0x0807C2E3, &samp_on_bad_rcon_local)); // "RCON (In-Game): Player #%d (%s) <%s> failed login." hook.E8.push_back(replace_pair_t(0x0807E731, &samp_on_player_chat)); // "[chat] [%s]: %s" hook.E8.push_back(replace_pair_t(0x080C842A, &samp_on_player_rename)); // "[nick] %s nick changed to %s" hook.E8.push_back(replace_pair_t(0x0807E507, &samp_is_bad_nick)); // "SetPlayerName", см samp_on_player_rename, 6 блок с начала функции hook.E8.push_back(replace_pair_t(0x080812DB, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x080C82BD, &samp_is_bad_nick)); hook.E8.push_back(replace_pair_t(0x0804E63E, &samp_on_recvfrom)); // objdump -D samp03svr | grep 'recvfrom@plt', берем адреса из первого столбика hook.E8.push_back(replace_pair_t(0x080DBAD5, &samp_on_recvfrom)); hook.E8.push_back(replace_pair_t(0x0804E1AE, &samp_on_sendto)); // objdump -D samp03svr | grep 'sendto@plt', берем адреса из первого столбика hook.E8.push_back(replace_pair_t(0x0805D2FE, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0809F55A, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0809F834, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0809FA40, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0809FC20, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x0809FDAE, &samp_on_sendto)); hook.E8.push_back(replace_pair_t(0x080DB931, &samp_on_sendto)); rezult.insert(std::make_pair("ddac809ea7faab82eb10358ee1600e8401dae067", hook)); // Нормальная версия самп сервера } return rezult; } samp_hooks_t samp_hooks = init(); } // namespace samp { /* Нахожение адресов под windows: Находим название методов: dumpbin /all c:\WINDOWS\system32\ws2_32.dll | find /i "sendto" dumpbin /all c:\WINDOWS\system32\ws2_32.dll | find /i "recvfrom" Ставим точку останова на {,,wsock32.dll}_sendto@24 {,,wsock32.dll}_recvfrom@24 {,,ws2_32.dll}_sendto@24 {,,ws2_32.dll}_recvfrom@24 Нахождение адресов по принтфам: ставим точку остонова на принтф, в watch пишем: *((char**)esp+0) - первый текстовой аргумент *((char**)esp+1) - второй текстовой аргумент *((char**)esp+2) или сместить +1 :) Получить дизасемблер: dumpbin /disasm C:\_dev\local_samp_server\samp-server.exe > C:\_dev\local_samp_server\samp-server.dumpbin objdump.exe -Dlx samp-server.exe > samp-server.objdump Линукс Получить дамп: objdump -D samp02Xsvr > samp02Xsvr.dmb Получить адреса: objdump -D samp02Xsvr | grep 'recvfrom@plt' objdump -D samp02Xsvr | grep 'sendto@plt' берем адреса из первого столбика samp_is_bad_nick находиться через строку в лог о смене ника через иду Отладка: gdb ./samp03svr b *0x8074F24 - точна останова на адрес (нужно на адрес принтфа) r - запустить прогу c - продолжить выполнение bt - показать стек q - выйди display *((char**)$sp + 1) - чтобы всегда выводил первый строковой аргумент print *((char**)$sp + 1) - печать первого строкового аргумента print *((char**)$sp + 2) - печать второго строкового аргумента (gdb) bt #0 0x08074f24 in putchar () #1 0x08089065 in putchar () берем вторую строчку и отнимаем 5: 0x08089065 - 5 = 0x08089065 для получения брейк поинта в игре нужно забить 2 c перед подключением */
[ "dimonml@19848965-7475-ded4-60a4-26152d85fbc5" ]
[ [ [ 1, 359 ] ] ]
a169316c7bca33d6beb07c112146ce8d5dbb60d1
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/MyGUIEngine/include/MyGUI_SharedLayerNode.h
55198288632e65d7f08880ff27e828db00b476ab
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
1,391
h
/*! @file @author Albert Semenov @date 05/2008 */ /* This file is part of MyGUI. MyGUI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MyGUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __MYGUI_SHARED_LAYER_NODE_H__ #define __MYGUI_SHARED_LAYER_NODE_H__ #include "MyGUI_Prerequest.h" #include "MyGUI_LayerNode.h" namespace MyGUI { class MYGUI_EXPORT SharedLayerNode : public LayerNode { MYGUI_RTTI_DERIVED( SharedLayerNode ) public: explicit SharedLayerNode(ILayer* _layer, ILayerNode* _parent = nullptr); virtual ~SharedLayerNode(); void addUsing() { mCountUsing++; } void removeUsing() { mCountUsing--; } size_t countUsing() const { return mCountUsing; } private: size_t mCountUsing; }; } // namespace MyGUI #endif // __MYGUI_SHARED_LAYER_NODE_H__
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 58 ] ] ]
e0f73e40d58a9683351dcb6ec382a740fff72e3c
87cfed8101402f0991cd2b2412a5f69da90a955e
/daq/daq/src/mwnidaq/niDIO.cpp
9bacd0bdd53a8a7458c2efd6394b2e75dec721d3
[]
no_license
dedan/clock_stimulus
d94a52c650e9ccd95dae4fef7c61bb13fdcbd027
890ec4f7a205c8f7088c1ebe0de55e035998df9d
refs/heads/master
2020-05-20T03:21:23.873840
2010-06-22T12:13:39
2010-06-22T12:13:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,541
cpp
// Copyright 1998-2003 The MathWorks, Inc. // $Revision: 1.3.4.5 $ $Date: 2003/10/15 18:32:53 $ // niDIO.cpp : Implementation of CMwnidaqApp and DLL registration. #include "stdafx.h" #include "mwnidaq.h" #include <nidaq.h> #include "niDIO.h" #include "niutil.h" #include <stdio.h> ///////////////////////////////////////////////////////////////////////////// // HRESULT CniDIO::Open(IDaqEngine *engine, int id,DevCaps* DeviceCaps) { // assign the engine access pointer CmwDevice::Open(engine); if (id<1) return E_INVALID_DEVICE_ID; DAQ_CHECK(CniDisp::Open(id,DeviceCaps)); DAQ_CHECK(Initialize()); //CComPtr<IProp> prop; //CComQIPtr<IPropContainer, &__uuidof(IPropContainer)> pCont; // common properties SetDaqHwInfo(); ATLTRACE("Dio Initialization complete\n"); return S_OK; } int CniDIO::Initialize() { if (!GetDevCaps()->HasDIO()) return E_DIO_UNSUPPORTED; return S_OK; } STDMETHODIMP CniDIO::ReadValues(LONG NumberOfPorts, LONG * PortList, ULONG * Data) { if (Data == NULL) return E_POINTER; for (int i=0;i<NumberOfPorts;i++) { short val; DAQ_CHECK(DIG_In_Port(_id,(short)PortList[i],&val)); Data[i]=val; } return S_OK; } STDMETHODIMP CniDIO::WriteValues(LONG NumberOfPorts, LONG * PortList, ULONG * Data, ULONG * Mask) { for (int i=0;i<NumberOfPorts;i++) { if (Mask[i]==0xff) { DAQ_CHECK(DIG_Out_Port(_id,(short)PortList[i],(short)Data[i])); } else { for (int j=0;j<8;j++) { if (Mask[i] & (1<<j)) { DAQ_CHECK(DIG_Out_Line(_id,(short)PortList[i],j,(short)(Data[i]>>j) & 1)); } } } } return S_OK; } STDMETHODIMP CniDIO::SetPortDirection(LONG Port, ULONG DirectionValues) { // this code as is will only work on e series boards if (DirectionValues==0) { DAQ_CHECK(DIG_Prt_Config(_id,(short)Port,0,0)); } else if (DirectionValues==0xff) { DAQ_CHECK(DIG_Prt_Config(_id,(short)Port,0,1)); } else { for (int i=0;i<8;i++) { DAQ_CHECK(DIG_Line_Config(_id,(short)Port,i,(short)(DirectionValues>>i) & 1)); } } return S_OK; } HRESULT CniDIO::SetDaqHwInfo() { //CComPtr<IProp> prop; // hwinfo property container // device name RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"devicename"), CComVariant(GetDevCaps()->deviceName))); // driver name RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"adaptorname"),CComVariant(L"nidaq"))); // device Id wchar_t idStr[8]; swprintf(idStr, L"%d", _id); RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"id"), CComVariant(idStr))); RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"totallines"),CComVariant(GetDevCaps()->nDIOLines)) ); if (GetDevCaps()->IsESeries() || GetDevCaps()->IsDSA() || GetDevCaps()->IsAODC()) { if ( GetDevCaps()->nDIOLines==8) { // directions 0:in 1:out 2:in/out RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"portdirections"),CComVariant(2L)) ); RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"portids"),CComVariant(0L)) ); // port line config 0:port 1: line RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"portlineconfig"),CComVariant(1L)) ); RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"portlinemasks"),CComVariant(255L)) ); } else { long portdir[]={2, 2, 2 ,2}; long ids[]={0, 2, 3, 4}; long linecfg[]={1, 0, 0, 0}; long linemasks[]={255, 255, 255, 255} ; CComVariant var; int size=max(GetDevCaps()->nDIOLines/8,sizeof(portdir)/sizeof(portdir[0])); // directions 0:in 1:out 2:in/out CreateSafeVector(portdir,size,&var); RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"portdirections"),var) ); CreateSafeVector(ids,size,&var); RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"portids"),var) ); // port line config 0:port 1: line CreateSafeVector(linecfg,size,&var); RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"portlineconfig"),var) ); CreateSafeVector(linemasks,size,&var); RETURN_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"portlinemasks"),var) ); } } else { CComVariant var; long ports=GetDevCaps()->nDIOLines/8; if (ports*8!=GetDevCaps()->nDIOLines) { ports++; _RPT0(_CRT_WARN,"Port has less then 8 lines\n"); } SAFEARRAY *ps = SafeArrayCreateVector(VT_I4, 0, ports ); if (ps==NULL) E_SAFEARRAY_ERR; // set the data type and values V_VT(&var)=VT_ARRAY | VT_I4; V_ARRAY(&var)=ps; TSafeArrayAccess <long> ar(&var); // used to access the array int i; if (GetDevCaps()->Is700()) { ar[0]=1; // Port 0 is output ar[1]=0; // Port 1 is input } else { // all ports are bydirectional for (i=0;i<ports;i++) ar[i]=2; } RETURN_HRESULT(_DaqHwInfo->put_MemberValue(L"portdirections",var) ); for (i=0;i<ports;i++) ar[i]=i; RETURN_HRESULT(_DaqHwInfo->put_MemberValue(L"portids",var) ); // port line config 0:port 1: line for (i=0;i<ports;i++) ar[i]=0; RETURN_HRESULT(_DaqHwInfo->put_MemberValue(L"portlineconfig",var) ); for (i=0;i<ports;i++) ar[i]=255; //does not work for <8 bit ports...? RETURN_HRESULT(_DaqHwInfo->put_MemberValue(L"portlinemasks",var) ); } RETURN_HRESULT(_DaqHwInfo->put_MemberValue(L"vendordriverdescription", CComVariant(L"National Instruments Data Acquisition Driver"))); char version[16]; GetDriverVersion(version); RETURN_HRESULT(_DaqHwInfo->put_MemberValue(L"vendordriverversion",CComVariant(version))); return S_OK; }
[ [ [ 1, 211 ] ] ]
4742ff2e628c6212c3d5a3e2874c5c6069e69c60
71d018f8dbcf49cfb07511de5d58d6ad7df816f7
/scistudio/trunk/impbitmap.cpp
1bb506c68f927f6c48dcbcaac66863923bddbe61
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
qq431169079/SciStudio
48225261386402530156fc2fc14ff0cad62174e8
a1fccbdcb423c045078b927e7c275b9d1bcae6b3
refs/heads/master
2020-05-29T13:01:50.800903
2010-09-14T07:10:07
2010-09-14T07:10:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,084
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #include <ClipBrd.hpp> #pragma hdrstop #include "picedit.h" #include "impbitmap.h" #include "gfxedits.h" #include "main.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TDlgImpBitmap *DlgImpBitmap; //--------------------------------------------------------------------------- __fastcall TDlgImpBitmap::TDlgImpBitmap(TComponent* Owner) : TForm(Owner) { wndPic=(TWndPicEdit*)Owner; Graphics::TBitmap *b = DrawBufferToBitmap(wndPic->pic->bitmaps[wndPic->activeScreen],sPIC_WIDTH,sPIC_HEIGHT,(wndPic->pic->palVGA)?&(wndPic->pic->palVGA->pal):&palEGA,FALSE,FALSE); pBmp = new Graphics::TBitmap; pBmp->Width = sPIC_WIDTH; pBmp->Height = sPIC_HEIGHT; pBmp->Canvas->Draw(0,0,b); delete b; dBmp = NULL; memset(bMask,0xFF,sizeof(bMask)); DRAGGING = FALSE; } //--------------------------------------------------------------------------- void __fastcall TDlgImpBitmap::SetBitmap() { if(!dBmp) return; pBmp->Canvas->Draw(rcBmp.left,rcBmp.top,dBmp); int x1,x2,y1,y2; x1 = rcBmp.left>0?rcBmp.left:0; y1 = rcBmp.top>0?rcBmp.top:0; x2 = (rcBmp.left+dBmp->Width); if(x2>=sPIC_WIDTH) x2 = sPIC_WIDTH-1; y2 = (rcBmp.top+dBmp->Height); if(y2>=sPIC_HEIGHT) y2 = sPIC_HEIGHT-1; for(int y = y1; y <= y2; y++) memset(bMask+(y*sPIC_WIDTH)+x1,0,x2-x1); FULL_DELETE(dBmp); Image1->Canvas->Draw(0,0,pBmp); } //--------------------------------------------------------------------------- void __fastcall TDlgImpBitmap::SetCoords() { if(!dBmp) return; rcBmp.right = rcBmp.left+dBmp->Width; rcBmp.bottom = rcBmp.top+dBmp->Height; Image1->Canvas->Draw(0,0,pBmp); Image1->Canvas->Draw(rcBmp.left,rcBmp.top,dBmp); } //--------------------------------------------------------------------------- void __fastcall TDlgImpBitmap::ToolButton2Click(TObject *Sender) { if(!BGOpenDialog->Execute()) return; SetBitmap(); dBmp = new Graphics::TBitmap; dBmp->LoadFromFile(BGOpenDialog->FileName); rcBmp.left = 0; rcBmp.top = 0; SetCoords(); } //--------------------------------------------------------------------------- #define SET_PANEL_TEXT(s) \ StatusBar->SimpleText = s //--------------------------------------------------------------------------- U32 GetColsUsed(U32 *bmpBuf, U32 bufSize, U32 *palBuf) { U32 i=0,j=0,cu=0,c; BOOL INC; for(i=0;i<bufSize;i++) { INC = TRUE; c=bmpBuf[i]; for(j=0;j<cu;j++) if(palBuf[j]==c) { INC = FALSE; break; } if(INC) { palBuf[cu] = c; cu++; if(cu>=256) break; } } return cu; } //--------------------------------------------------------------------------- #define GET_R(c) (c&0xFF) #define GET_G(c) ((c>>8) &0xFF) #define GET_B(c) ((c>>16)&0xFF) #define ABX(a) ((a<0)?-a:a) #define GET_DIFF(c1, c2)\ (ABX(GET_R(c1)-GET_R(c2))+ABX(GET_G(c1)-GET_G(c2))+ABX(GET_B(c1)-GET_B(c2))) #define GET_DIFFR(c1, c2)\ ABX(GET_R(c1)-GET_R(c2)) #define GET_DIFFG(c1, c2)\ ABX(GET_G(c1)-GET_G(c2)) #define GET_DIFFB(c1, c2)\ ABX(GET_B(c1)-GET_B(c2)) //--------------------------------------------------------------------------- U32 MatchCols(U32 *bmpBuf, U32 bufSize, U32 *palBuf, U8 diff, U32 maxCols) { U32 i=0,j=0,cu=0,c,g; BOOL INC; for(i=0;i<bufSize;i++) { INC = TRUE; c=bmpBuf[i]; for(j=0;j<cu;j++) { g = palBuf[j]; if(((GET_DIFFR(g,c)<=diff)&&(GET_DIFFG(g,c)<=diff)&&(GET_DIFFB(g,c)<=diff))) { bmpBuf[i] = palBuf[j]; INC = FALSE; break; } } if(INC) { palBuf[cu] = c; cu++; if(cu>=maxCols) ;// break; } } return cu; } //--------------------------------------------------------------------------- U8 PalEnt(U32 c, U32 *palBuf, U32 totalCols) { for(U32 j=0;j<totalCols;j++) if(palBuf[j]==c) return j; return 0; } //--------------------------------------------------------------------------- U8 *DecreaseBmpDepth(U32 *bmpBuf, U32 *palBuf, U32 bufSize, U32 maxCols) { U8 *outBuf = (U8*)ssAlloc(bufSize); U32 i=0,j=0,cu=0,c; BOOL INC; for(i=0;i<bufSize;i++) { INC = TRUE; c=bmpBuf[i]; for(j=0;j<cu;j++) if(palBuf[j]==c) { INC = FALSE; break; } if(INC) { palBuf[cu] = c; cu++; //if(cu==maxCols) // break; } outBuf[i] = j+64; } return outBuf; } //--------------------------------------------------------------------------- void __fastcall TDlgImpBitmap::Button1Click(TObject *Sender) { SetBitmap(); U8 *bmp8Buf; U32 *bmpBuf = (U32*)ssAlloc(sPIC_SIZE*sizeof(U32)); U32 *palBuf = (U32*)ssAlloc(sPIC_SIZE*sizeof(U32)); // erg..I know, lots of mem--max # of unique cols U32 j=0; SET_PANEL_TEXT("Creating bitmap buffer..."); TCanvas *cV=pBmp->Canvas; for(int y=0;y<sPIC_HEIGHT;y++) for(int x=0;x<sPIC_WIDTH;x++) bmpBuf[j++] = cV->Pixels[x][y]&0x00FFFFFF; U32 totalCols; maxCols = 191; j = 1; SET_PANEL_TEXT("Calculating colour depth..."); totalCols = GetColsUsed(bmpBuf,sPIC_SIZE,palBuf); if(totalCols>256) { ShowMessage("Col Depth++!"); return; } SET_PANEL_TEXT("Depth="+IntToStr(totalCols)+"..."); if(totalCols>maxCols) { SET_PANEL_TEXT("Building palette to chosen colour depth..."); do { totalCols = MatchCols(bmpBuf,sPIC_SIZE,palBuf,j,maxCols); j++; SET_PANEL_TEXT("Depth="+IntToStr(totalCols)+"..."); } while(totalCols>maxCols); SET_PANEL_TEXT("Depth conversion complete! Depth="+IntToStr(totalCols)); } SET_PANEL_TEXT("Converting 24 bit bitmap to 8 bit..."); //ssFree(palBuf); //palBuf = (U32*)ssAlloc(maxCols*sizeof(U32)); bmp8Buf = DecreaseBmpDepth(bmpBuf, palBuf, sPIC_SIZE, maxCols); ssFree(bmpBuf); Image1->Visible = FALSE; j=0; for(int y=0;y<sPIC_HEIGHT;y++) for(int x=0;x<sPIC_WIDTH;x++) Image1->Canvas->Pixels[x][y]=(TColor)palBuf[bmp8Buf[j++]]; Image1->Visible = TRUE; SET_PANEL_TEXT("Done!"); U8 *outBits = (U8*)ssAlloc(sPIC_SIZE); U16 size = EncodeSCI1Bits(bmp8Buf, outBits, sPIC_WIDTH, sPIC_HEIGHT, 0xFF, FALSE); wndPic->AddCode(0xFE); wndPic->AddCode(0x01); wndPic->AddCode(0); wndPic->AddCode(0); wndPic->AddCode(0); U8 *p = wndPic->pic->data+wndPic->pic->offset; wndPic->AddCode(0); wndPic->AddCode(0); wndPic->AddCode(sPIC_WIDTH&0xFF); wndPic->AddCode(sPIC_WIDTH>>8); wndPic->AddCode(sPIC_HEIGHT&0xFF); wndPic->AddCode(sPIC_HEIGHT>>8); wndPic->AddCode(0xFF); wndPic->AddCode(0); wndPic->AddCode(0); for(int i=0;i<size;i++) wndPic->AddCode(outBits[i]); size = wndPic->pic->data-p; p[0] = (size)&0xFF; p[1] = ((size)>>8)&0xFF; wndPic->AddCode(0xFE); wndPic->AddCode(0x02); for(int i=0;i<256;i++) wndPic->AddCode(i); wndPic->AddCode(0); wndPic->AddCode(0xFE); wndPic->AddCode(0); wndPic->AddCode(0xFF); for(int i=0;i<64;i++) { wndPic->AddCode(0); wndPic->AddCode(0); wndPic->AddCode(0); wndPic->AddCode(0); } for(int i=0;i<191;i++) { wndPic->AddCode(1); wndPic->AddCode(palBuf[i]&0xFF); wndPic->AddCode((palBuf[i]>>8)&0xFF); wndPic->AddCode((palBuf[i]>>16)&0xFF); } wndPic->AddCode(0); wndPic->AddCode(0); wndPic->AddCode(0); wndPic->AddCode(0); ssFree(bmp8Buf); ssFree(palBuf); ssFree(outBits); wndPic->UpdatePic(); Close(); } //--------------------------------------------------------------------------- void __fastcall TDlgImpBitmap::ToolButton5Click(TObject *Sender) { TClipboard *pCB = Clipboard(); if(pCB->HasFormat(CF_BITMAP)) { SetBitmap(); dBmp = new Graphics::TBitmap; dBmp->LoadFromClipboardFormat(CF_BITMAP, pCB->GetAsHandle(CF_BITMAP), 0); rcBmp.left = 0; rcBmp.top = 0; SetCoords(); } else { MessageBeep(0); ShowMessage("Clipboard does not contain a valid Bitmap!"); } } //--------------------------------------------------------------------------- void __fastcall TDlgImpBitmap::Image1MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { dnX = X; dnY = Y; if(Shift.Contains(ssLeft)) DRAGGING = (X>=rcBmp.left&&Y>=rcBmp.top&&X<=rcBmp.right&&Y<=rcBmp.bottom); } //--------------------------------------------------------------------------- void __fastcall TDlgImpBitmap::Image1MouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { mvX = X; mvY = Y; if(DRAGGING) { rcBmp.left -= (dnX-mvX); rcBmp.top -= (dnY-mvY); dnX = mvX; dnY = mvY; SetCoords(); } } //--------------------------------------------------------------------------- void __fastcall TDlgImpBitmap::Image1MouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { DRAGGING = FALSE; } //--------------------------------------------------------------------------- void __fastcall TDlgImpBitmap::StatusBarDrawPanel(TStatusBar *StatusBar, TStatusPanel *Panel, const TRect &Rect) { /* TCanvas *pCanvas = StatusBar->Canvas; pCanvas->Brush->Color = clRed; pCanvas->FillRect(Rect); pCanvas->Font->Color = clYellow; ImageList1->Draw(pCanvas,Rect.Left,Rect.Top, Panel->Index, true); pCanvas->TextOut(Rect.left + 30, Rect.top + 2, "Panel" + IntToStr(Panel->Index)); */} //---------------------------------------------------------------------------
[ "mageofmarr@d0e240c1-a1d3-4535-ae25-191325aad40e" ]
[ [ [ 1, 327 ] ] ]
a4477de75f9c747fbfaf15a486522c270d99dbd2
920f766fe36acd51410160bb0332c83ed38da4c7
/phase1/VideoCapture.h
7ef22de27008eba793cb269551a7d70aea36823b
[]
no_license
shaikuf/hagiga-basnooker
4b302f9c969e119204291655bedb419b89f2cd31
7eb329bcf000ee8b29f22410a9b3a14ab8963abd
refs/heads/master
2016-09-06T00:58:14.129776
2010-06-07T14:12:38
2010-06-07T14:12:38
41,489,609
0
0
null
null
null
null
UTF-8
C++
false
false
435
h
#ifndef _VIDEOCAPTURE_H #define _VIDEOCAPTURE_H #include <cxcore.h> #include <videoInput.h> using namespace std; class VideoCapture { videoInput _VI; int _device; int _height; int _width; public: VideoCapture(int index, int w, int h); void stop(); bool restart(); IplImage *CreateCaptureImage(); ~VideoCapture(); bool getFrame(IplImage *frame); bool waitFrame(IplImage *frame); }; #endif
[ "c1ph3r.il@9f8e2b2e-e8c3-11de-b92f-5d3588262692" ]
[ [ [ 1, 28 ] ] ]
28b9eca699f6f5de4728d58d05680aa4e3faeda8
bf4f0fc16bd1218720c3f25143e6e34d6aed1d4e
/KeyTree.cpp
3a795a7a2f824a6bd83efc5d8a52875048264603
[]
no_license
shergin/downright
4b0f161700673d7eb49459e4fde2b7d095eb91bb
6cc40cd35878e58f4ae8bae8d5e58256e6df4ce8
refs/heads/master
2020-07-03T13:34:20.697914
2009-09-29T19:15:07
2009-09-29T19:15:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
292
cpp
// KeyTree.cpp : implementation file // #include "stdafx.h" #include "Downright.h" #include "KeyTree.h" // CKeyTree IMPLEMENT_DYNAMIC(CKeyTree, CTreeCtrl) CKeyTree::CKeyTree() { } CKeyTree::~CKeyTree() { } BEGIN_MESSAGE_MAP(CKeyTree, CTreeCtrl) END_MESSAGE_MAP()
[ [ [ 1, 22 ] ] ]
dd1a90acbe16c89d376a4350785a819be01a4723
f90b1358325d5a4cfbc25fa6cccea56cbc40410c
/src/Combine/proteinIndirectComparison.cpp
aa5d7c4edb25684fee5a0e7a237cb75b046c247a
[]
no_license
ipodyaco/prorata
bd52105499c3fad25781d91952def89a9079b864
1f17015d304f204bd5f72b92d711a02490527fe6
refs/heads/master
2021-01-10T09:48:25.454887
2010-05-11T19:19:40
2010-05-11T19:19:40
48,766,766
0
0
null
null
null
null
UTF-8
C++
false
false
11,169
cpp
#include "proteinIndirectComparison.h" double ProteinIndirectComparison::dMaxCIwidth = 3; double ProteinIndirectComparison::dLnLikehoodCutOffset = 1.96; ProteinIndirectComparison::ProteinIndirectComparison() { bValidity = false; sLocus = ""; dLog2Ratio = 0; dLowerLimitCI = 0; dUpperLimitCI = 0; sName = ""; sNumerator = ""; sDenominator = ""; sDirectComparisonName0 = ""; sDirectComparisonName1 = ""; dMLEMinLog2Ratio = 0; dMLEMaxLog2Ratio = 0; dLog2RatioDiscretization = 0.1; } ProteinIndirectComparison::~ProteinIndirectComparison() { // destructor } bool ProteinIndirectComparison::testDirectComparison( ProteinDirectComparison directComparison0, ProteinDirectComparison directComparison1) { if( !calCombinationType( directComparison0.getNumerator(), directComparison0.getDenominator(), directComparison1.getNumerator(), directComparison1.getDenominator() ) ) { cout << "ERROR: cannot properly match the numerator and denominator of the two direct comparisons and the indirect comparison." << endl; return false; } if( directComparison0.getMLEMinLog2Ratio() != directComparison1.getMLEMinLog2Ratio() ) { cout << "ERROR: the two direct comparison must have the same minimum protein log2ratio." << endl; return false; } if( directComparison0.getMLEMaxLog2Ratio() != directComparison1.getMLEMaxLog2Ratio() ) { cout << "ERROR: the two direct comparison must have the same maximum protein log2ratio." << endl; return false; } if( directComparison0.getLog2RatioDiscretization() != directComparison1.getLog2RatioDiscretization() ) { cout << "ERROR: the two direct comparison must have the same protein Log2RatioDiscretization." << endl; return false; } return true; } bool ProteinIndirectComparison::runQuantification( string sInputLocus, ProteinDirectComparison directComparison0, ProteinDirectComparison directComparison1) { bValidity = false; dLog2Ratio = 0; dLowerLimitCI = 0; dUpperLimitCI = 0; if( !( directComparison0.isValid() && directComparison1.isValid() ) ) { // both direct comparisons for this locus have to be valid return true; } if( !calCombinationType( directComparison0.getNumerator(), directComparison0.getDenominator(), directComparison1.getNumerator(), directComparison1.getDenominator() ) ) { cout << "ERROR: cannot properly match the numerator and denominator of the two direct comparisons and the indirect comparison." << endl; return false; } vector<double> vdLog2RatioDC0; vector<double> vdLnLikelihoodDC0; vector<double> vdLog2RatioDC1; vector<double> vdLnLikelihoodDC1; if( !directComparison0.getProfileLikelihoodCurve(vdLog2RatioDC0, vdLnLikelihoodDC0) ) return false; if( !directComparison1.getProfileLikelihoodCurve(vdLog2RatioDC1, vdLnLikelihoodDC1) ) return false; if( vdLog2RatioDC0.size() != vdLog2RatioDC1.size() ) return false; int i; for( i = 0; i < vdLog2RatioDC0.size(); ++i ) { if( fabs(vdLog2RatioDC0[i] - vdLog2RatioDC1[i]) > 0.001 ) return false; } // combine every log2ratio from comparison 0 with every log2ratio from comparison 1 vector<double> vdLog2RatioAll; vector<double> vdLnLikelihoodAll; int j; for( i = 0; i < vdLog2RatioDC0.size(); ++i ) { for( j = 0; j < vdLog2RatioDC1.size(); ++j ) { vdLog2RatioAll.push_back( combineLog2Ratio(vdLog2RatioDC0[i], vdLog2RatioDC1[j]) ); vdLnLikelihoodAll.push_back( (vdLnLikelihoodDC0[i] + vdLnLikelihoodDC1[j]) ); } } // collapse the log2ratio into a non-redundant set of log2ratio double dCurrentLog2Ratio = 0; double dCurrentLnLikelihood = 0; double dOverMaxLog2Ratio = 10000000000.0; bool bFirstLog2Ratio = true; vdLog2Ratio.clear(); vdLnLikelihoodAll.clear(); dCurrentLog2Ratio = ( *(min_element( vdLog2RatioAll.begin(), vdLog2RatioAll.end() ) ) ); while( dCurrentLog2Ratio < dOverMaxLog2Ratio ) { bFirstLog2Ratio = true; dCurrentLnLikelihood = 0; // cout << "dCurrentLog2Ratio = " << dCurrentLog2Ratio << endl; for( i = 0; i < vdLog2RatioAll.size(); ++i ) { if( fabs(vdLog2RatioAll[i] - dCurrentLog2Ratio) < 0.00001 ) { // compute ln likelihood if(bFirstLog2Ratio) { dCurrentLnLikelihood = vdLnLikelihoodAll[i]; bFirstLog2Ratio = false; } else { // Wrong implementation: exp(vdLnLikelihoodAll[i]) can easily be out of range for double // dCurrentLnLikelihood = log( exp(dCurrentLnLikelihood) + exp(vdLnLikelihoodAll[i]) ); // if y > x, log(exp(x)+exp(y)) = y + log(exp(x-y)+1) if( dCurrentLnLikelihood > vdLnLikelihoodAll[i]) { dCurrentLnLikelihood = dCurrentLnLikelihood + log( 1 + exp(vdLnLikelihoodAll[i]-dCurrentLnLikelihood) ); } else { dCurrentLnLikelihood = vdLnLikelihoodAll[i] + log( 1 + exp(dCurrentLnLikelihood-vdLnLikelihoodAll[i]) ); } } vdLog2RatioAll[i] = dOverMaxLog2Ratio; //cout << "vdLog2RatioAll[i] = " << vdLog2RatioAll[i] << endl; } } vdLog2Ratio.push_back( dCurrentLog2Ratio ); vdLnLikelihood.push_back( dCurrentLnLikelihood ); dCurrentLog2Ratio = ( *(min_element( vdLog2RatioAll.begin(), vdLog2RatioAll.end() ) ) ); } //cout << "vdLog2Ratio.size() = " << vdLog2Ratio.size() << endl; //for( int x = 0; x < vdLog2Ratio.size(); ++x ) //{ // cout << "## " << vdLog2Ratio[x] << " === " << vdLnLikelihood[x] << endl; //} vdLog2RatioAll.clear(); vdLnLikelihoodAll.clear(); /* * calculate the maximum likelihood estimate and confidence interval from profile likelihood curve * this is copied from proteinDirectComparison.cpp * changed variable names: dMLEMinLog2Ratio dMLEMaxLog2Ratio dLog2RatioDiscretization */ dMLEMinLog2Ratio = ( *(min_element( vdLog2Ratio.begin(), vdLog2Ratio.end() ) ) ); dMLEMaxLog2Ratio = ( *(max_element( vdLog2Ratio.begin(), vdLog2Ratio.end() ) ) ); dLog2RatioDiscretization = directComparison0.getLog2RatioDiscretization(); double dMaxLnLikelihood = ( *(max_element( vdLnLikelihood.begin(), vdLnLikelihood.end() ) ) ); vector<double> vdSubRatioArray; // there could be multiple ratios that have maximum likelihood for( i = 0; i < vdLog2Ratio.size(); i++ ) { if ( vdLnLikelihood.at( i ) == dMaxLnLikelihood ) { vdSubRatioArray.push_back( vdLog2Ratio.at( i ) ); } } dLog2Ratio = vdSubRatioArray[0]; for ( i = 1; i < vdSubRatioArray.size(); i++ ) { if ( fabs( dLog2Ratio ) > fabs( vdSubRatioArray.at( i ) ) ) { dLog2Ratio = vdSubRatioArray.at( i ); } } double dLnLikelihoodCutoff = dMaxLnLikelihood - dLnLikehoodCutOffset; vdSubRatioArray.clear(); for( i = 0; i < vdLog2Ratio.size(); i++ ) { if ( vdLnLikelihood.at( i ) > dLnLikelihoodCutoff ) { vdSubRatioArray.push_back( vdLog2Ratio.at( i ) ); } } dLowerLimitCI = * min_element( vdSubRatioArray.begin(), vdSubRatioArray.end() ); dUpperLimitCI = * max_element( vdSubRatioArray.begin(), vdSubRatioArray.end() ); dLowerLimitCI = dLowerLimitCI - dLog2RatioDiscretization; dUpperLimitCI = dUpperLimitCI + dLog2RatioDiscretization; if( fabs( dLowerLimitCI ) < 0.000000001 ) dLowerLimitCI = 0; if( dLowerLimitCI < dMLEMinLog2Ratio ) dLowerLimitCI = dMLEMinLog2Ratio; if( fabs( dUpperLimitCI ) < 0.000000001 ) dUpperLimitCI = 0; if( dUpperLimitCI > dMLEMaxLog2Ratio ) dUpperLimitCI = dMLEMaxLog2Ratio; /* * Determine the validity of this protein according to the filterin criteria */ // CI width filtering double dWidthCI = dUpperLimitCI - dLowerLimitCI; if( dWidthCI < dMaxCIwidth ) bValidity = true; else bValidity = false; return true; } void ProteinIndirectComparison::eraseProfileLikelihoodCurve() { vdLog2Ratio.clear(); vdLnLikelihood.clear(); } void ProteinIndirectComparison::setName( string sNameConfig ) { sName = sNameConfig; } void ProteinIndirectComparison::setNumerator( string sNumeratorConfig ) { sNumerator = sNumeratorConfig; } void ProteinIndirectComparison::setDenominator( string sDenominatorConfig ) { sDenominator = sDenominatorConfig; } void ProteinIndirectComparison::setDirectComparisonName0( string sDirectComparisonName0Config) { sDirectComparisonName0 = sDirectComparisonName0Config; } void ProteinIndirectComparison::setDirectComparisonName1( string sDirectComparisonName1Config ) { sDirectComparisonName1 = sDirectComparisonName1Config; } string ProteinIndirectComparison::getName() { return sName; } string ProteinIndirectComparison::getNumerator() { return sNumerator; } string ProteinIndirectComparison::getDenominator() { return sDenominator; } string ProteinIndirectComparison::getDirectComparisonName0() { return sDirectComparisonName0; } string ProteinIndirectComparison::getDirectComparisonName1() { return sDirectComparisonName1; } void ProteinIndirectComparison::getEstimates(bool & bValidityRef, double & dLog2RatioRef, double & dLowerLimitCIRef, double & dUpperLimitCIRef ) { bValidityRef = bValidity; dLog2RatioRef = dLog2Ratio; dLowerLimitCIRef = dLowerLimitCI; dUpperLimitCIRef = dUpperLimitCI; } bool ProteinIndirectComparison::isValid() { return bValidity; } bool ProteinIndirectComparison::calCombinationType(string sDC0Numerator, string sDC0Denominator, string sDC1Numerator, string sDC1Denominator) { if( ( (sNumerator == sDC0Numerator) && (sDenominator == sDC1Numerator) && (sDC0Denominator == sDC1Denominator) ) || ( (sNumerator == sDC1Denominator) && (sDenominator == sDC0Denominator) && (sDC0Numerator == sDC1Numerator) ) ) { iCombinationType = 1; return true; } else if( ( (sNumerator == sDC0Denominator) && (sDenominator == sDC1Denominator) && (sDC0Numerator == sDC1Numerator) ) || ( (sNumerator == sDC1Numerator) && (sDenominator == sDC0Numerator) && (sDC0Denominator == sDC1Denominator) ) ) { iCombinationType = 2; return true; } else if( ( (sNumerator == sDC0Numerator) && (sDenominator == sDC1Denominator) && (sDC0Denominator == sDC1Numerator) ) || ( (sNumerator == sDC1Numerator) && (sDenominator == sDC0Denominator) && (sDC0Numerator == sDC1Denominator) ) ) { iCombinationType = 3; return true; } else if( ( (sNumerator == sDC0Denominator) && (sDenominator == sDC1Numerator) && (sDC0Numerator == sDC1Denominator) ) || ( (sNumerator == sDC1Denominator) && (sDenominator == sDC0Numerator) && (sDC0Denominator == sDC1Numerator) ) ) { iCombinationType = 4; return true; } else { iCombinationType = 0; return false; } } double ProteinIndirectComparison::combineLog2Ratio( double dLog2RatioDC0, double dLog2RatioDC1 ) { if( iCombinationType == 1 ) return (dLog2RatioDC0 - dLog2RatioDC1); else if( iCombinationType == 2 ) return (-(dLog2RatioDC0 - dLog2RatioDC1)); else if( iCombinationType == 3 ) return (dLog2RatioDC0 + dLog2RatioDC1); else if( iCombinationType == 4 ) return (-(dLog2RatioDC0 + dLog2RatioDC1)); else return 0; }
[ "chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a" ]
[ [ [ 1, 373 ] ] ]
fe6705c428d856b885bd26c6ab6d697077506729
3af6c2119743037b41eee8a46244ade56a2ac3e3
/Cpp/Box2D/Joints/Box2dMouseJointRef.cc
8faa39857f6be25e99911ecf5ce073cd43e0ac2f
[ "MIT" ]
permissive
TheProjecter/tgb-box2d-integration
16f848a8deb89d4ecbd4061712c385c19225b1b7
85cbc6e45f563dafc0b05e75a8f08338e1a5941a
refs/heads/master
2021-01-10T19:20:19.741374
2009-05-02T12:35:20
2009-05-02T12:35:20
42,947,643
0
0
null
null
null
null
UTF-8
C++
false
false
2,264
cc
//============================================================================= // Box2dMouseJointRef.cc //============================================================================= /* TGB-Box2D-Integration (http://code.google.com/p/tgb-box2d-integration/) Copyright (c) 2009 Michael Woerister Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "./Box2dMouseJointRef.h" #include "../Box2dUtil.h" IMPLEMENT_CONOBJECT(Box2dMouseJointRef); //=---------------------------------------------------------------------------- // Box2dMouseJointRef::setTarget() //=---------------------------------------------------------------------------- void Box2dMouseJointRef::setTarget( const b2Vec2 & target ) { AssertFatal( this->getJoint(), "Box2dMouseJointRef::setTarget() - No b2MouseJoint referenced." ); this->joint()->SetTarget( target ); } //=---------------------------------------------------------------------------- // Box2dMouseJointRef::setTarget() - ConsoleMethod //=---------------------------------------------------------------------------- ConsoleMethod( Box2dMouseJointRef, setTarget, void, 3, 3, "" ) { const b2Vec2 target = Box2dUtil::strTob2Vec2( argv[2] ); object->setTarget( target ); }
[ "michaelwoerister@f3bf45be-f2fd-11dd-89c5-9df526a60542" ]
[ [ [ 1, 51 ] ] ]
34b1ec28b0772a50a3a6c4117f71aa033e5e5ebf
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Common/Base/System/Stopwatch/hkStopwatch.inl
7e73cedd85870ec697560f9996fe71b10db714c8
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,965
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ HK_FORCE_INLINE void hkStopwatch::reset() { m_ticks_at_start = 0; m_ticks_total = 0; m_ticks_at_split = 0; m_split_total = 0; m_running_flag = 0; m_num_timings = 0; } HK_FORCE_INLINE hkStopwatch::hkStopwatch(const char* name) : m_name(name) { reset(); } HK_FORCE_INLINE void hkStopwatch::start() { HK_ASSERT(0x28f9f73c, ! m_running_flag); m_running_flag = true; m_ticks_at_start = getTickCounter(); m_ticks_at_split = m_ticks_at_start; } HK_FORCE_INLINE void hkStopwatch::stop() { HK_ASSERT(0x1d900cad, m_running_flag); m_running_flag = false; hkUint64 ticks_now = getTickCounter(); m_ticks_total += ticks_now - m_ticks_at_start; m_split_total += ticks_now - m_ticks_at_split; ++m_num_timings; } HK_FORCE_INLINE void hkStopwatch::resume() { m_running_flag = true; } HK_FORCE_INLINE hkBool hkStopwatch::isRunning() const { return m_running_flag; } HK_FORCE_INLINE const char* hkStopwatch::getName() const { return m_name; } HK_FORCE_INLINE int hkStopwatch::getNumTimings() const { return m_num_timings; } HK_FORCE_INLINE hkUint64 hkStopwatch::getSplitTicks() { hkUint64 t = m_split_total; if(m_running_flag) { hkUint64 now = getTickCounter(); t += now - m_ticks_at_split; m_ticks_at_split = now; } m_split_total = 0; return t; } HK_FORCE_INLINE hkReal hkStopwatch::getSplitSeconds() { return divide64(getSplitTicks(), getTicksPerSecond()); } HK_FORCE_INLINE hkUint64 hkStopwatch::getElapsedTicks() const { hkUint64 ticks = m_ticks_total; if( m_running_flag ) { ticks += getTickCounter() - m_ticks_at_start; } return ticks; } HK_FORCE_INLINE hkReal hkStopwatch::getElapsedSeconds() const { return divide64(getElapsedTicks(), getTicksPerSecond()); } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 112 ] ] ]
8329802a08a6feb08423f1ffb0b4e3fe88a05b4e
a48646eddd0eec81c4be179511493cbaf22965b9
/project/mysip/src/system/system_var.inc
7cebf7930b048e55cd3acad3172ea97a89c18e36
[]
no_license
lengue/tsip
0449f791a5cbe9e9fdaa1b4d7f1d1e28eff2f0ec
da8606bd7d865d4b4a389ec1594248a4044bc890
refs/heads/master
2021-01-10T08:40:32.925501
2010-06-05T12:44:10
2010-06-05T12:44:10
53,989,315
0
0
null
null
null
null
GB18030
C++
false
false
350
inc
/******************************************************************************* 功能 : 系统变量 创建人 : 唐春平 创建日期: 200.01.10 修改记录: *******************************************************************************/ extern SYS_MODULE_CB_S *g_pstMsgCB; extern SYS_MODULE_INFO_S g_astModuleCfg[SYS_MODULE_BUTT];
[ [ [ 1, 8 ] ] ]
b5dd1c582112e2a2ab95b1b03831f827a562e307
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/VolumeBrushFX.h
9c45d9f003134a1ee8c2a1b92042fe1c6845c1ed
[]
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,338
h
// ----------------------------------------------------------------------- // // // MODULE : VolumeBrushFX.h // // PURPOSE : VolumeBrush special fx class - Definition // // CREATED : 4/1/98 // // ----------------------------------------------------------------------- // #ifndef __VOLUME_BRUSH_FX_H__ #define __VOLUME_BRUSH_FX_H__ #include "SpecialFX.h" #include "ContainerCodes.h" #include "SurfaceDefs.h" struct VBCREATESTRUCT : public SFXCREATESTRUCT { VBCREATESTRUCT(); virtual void Read(ILTMessage_Read *pMsg); LTBOOL bFogEnable; LTFLOAT fFogFarZ; LTFLOAT fFogNearZ; LTVector vFogColor; LTVector vTintColor; LTVector vLightAdd; uint8 nSoundFilterId; LTBOOL bCanPlayMoveSnds; SurfaceType eSurfaceOverrideType; LTVector vCurrent; float fGravity; float fViscosity; float fFriction; PlayerPhysicsModel ePPhysicsModel; }; inline VBCREATESTRUCT::VBCREATESTRUCT() { bFogEnable = LTFALSE; fFogFarZ = 0.0f; fFogNearZ = 0.0f; nSoundFilterId = 0; bCanPlayMoveSnds = LTTRUE; eSurfaceOverrideType = ST_UNKNOWN; vFogColor.Init(); vTintColor.Init(); vLightAdd.Init(); vCurrent.Init(); fGravity = 0.0f; fViscosity = 0.0f; fFriction = 0.0f; ePPhysicsModel = PPM_NORMAL; } inline void VBCREATESTRUCT::Read(ILTMessage_Read *pMsg) { bFogEnable = pMsg->Readbool(); fFogFarZ = pMsg->Readfloat(); fFogNearZ = pMsg->Readfloat(); vFogColor = pMsg->ReadLTVector(); vTintColor = pMsg->ReadLTVector(); vLightAdd = pMsg->ReadLTVector(); nSoundFilterId = pMsg->Readuint8(); bCanPlayMoveSnds = pMsg->Readbool(); eSurfaceOverrideType = (SurfaceType)pMsg->Readuint8(); vCurrent = pMsg->ReadLTVector(); fGravity = pMsg->Readfloat(); fViscosity = pMsg->Readfloat(); fFriction = pMsg->Readfloat(); ePPhysicsModel = (PlayerPhysicsModel)pMsg->Readuint8(); } class CVolumeBrushFX : public CSpecialFX { public : CVolumeBrushFX() : CSpecialFX() { m_vFogColor.Init(); m_vTintColor.Init(255.0f, 255.0f, 255.0f); m_vLightAdd.Init(); m_bFogEnable = LTFALSE; m_fFogFarZ = 0.0f; m_fFogNearZ = 0.0f; m_nSoundFilterId = 0; m_bCanPlayMoveSnds = LTTRUE; m_eSurfaceOverrideType = ST_UNKNOWN; } virtual LTBOOL Update() { return !m_bWantRemove; } LTBOOL Init(SFXCREATESTRUCT* psfxCreateStruct) { if (!CSpecialFX::Init(psfxCreateStruct)) return LTFALSE; VBCREATESTRUCT* pVB = (VBCREATESTRUCT*)psfxCreateStruct; m_bFogEnable = pVB->bFogEnable; m_fFogFarZ = pVB->fFogFarZ; m_fFogNearZ = pVB->fFogNearZ; m_vFogColor = pVB->vFogColor; m_vTintColor = pVB->vTintColor; m_vLightAdd = pVB->vLightAdd; m_nSoundFilterId = pVB->nSoundFilterId; m_bCanPlayMoveSnds = pVB->bCanPlayMoveSnds; m_eSurfaceOverrideType = pVB->eSurfaceOverrideType; m_vCurrent = pVB->vCurrent; m_fGravity = pVB->fGravity; m_fViscosity = pVB->fViscosity; m_fFriction = pVB->fFriction; m_ePPhysicsModel = pVB->ePPhysicsModel; uint16 nCode; g_pLTClient->GetContainerCode(m_hServerObject, &nCode); m_eContainerCode = (ContainerCode)nCode; return LTTRUE; } LTBOOL CreateObject(ILTClient* pClientDE) { if (!CSpecialFX::CreateObject(pClientDE)) return LTFALSE; // Special case for liquid volume brushes, set the FLAG_RAYHIT // flag... if (m_hServerObject && IsLiquid(GetCode())) { g_pCommonLT->SetObjectFlags(m_hServerObject, OFT_Flags, FLAG_RAYHIT, FLAG_RAYHIT); } return LTTRUE; } LTBOOL IsFogEnable() const { return m_bFogEnable; } LTVector GetFogColor() const { return m_vFogColor; } LTFLOAT GetFogFarZ() const { return m_fFogFarZ; } LTFLOAT GetFogNearZ() const { return m_fFogNearZ; } LTVector GetTintColor() const { return m_vTintColor; } LTVector GetLightAdd() const { return m_vLightAdd; } uint8 GetSoundFilterId() const { return m_nSoundFilterId; } LTBOOL CanPlayMovementSounds() const { return m_bCanPlayMoveSnds; } SurfaceType GetSurfaceOverride() const { return m_eSurfaceOverrideType; } LTFLOAT GetGravity() const { return m_fGravity; } LTFLOAT GetFriction() const { return m_fFriction; } LTFLOAT GetViscosity() const { return m_fViscosity; } ContainerCode GetCode() const { return m_eContainerCode; } LTVector GetCurrent() const { return m_vCurrent; } PlayerPhysicsModel GetPhysicsModel() const { return m_ePPhysicsModel; } virtual uint32 GetSFXID() { return SFX_VOLUMEBRUSH_ID; } protected : LTBOOL m_bFogEnable; LTFLOAT m_fFogFarZ; LTFLOAT m_fFogNearZ; LTVector m_vFogColor; LTVector m_vTintColor; LTVector m_vLightAdd; uint8 m_nSoundFilterId; LTBOOL m_bCanPlayMoveSnds; SurfaceType m_eSurfaceOverrideType; LTVector m_vCurrent; float m_fGravity; float m_fViscosity; float m_fFriction; PlayerPhysicsModel m_ePPhysicsModel; ContainerCode m_eContainerCode; }; #endif // __VOLUME_BRUSH_FX_H__
[ [ [ 1, 184 ] ] ]
e36f29a79ce151ceba5c020f842af9bbd03cd9c3
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Application/SysCAD/ABOUTBOX.CPP
8ee163ff189747c256fcf91cc6d42fa3093a7ab2
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,690
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #define __ABOUTBOX_CPP #include "sc_defs.h" #include "resource.h" #include "aboutbox.h" #include "revhist.h" //#include <dos.h> //#include <direct.h> #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif //=========================================================================== BEGIN_MESSAGE_MAP(CAboutBox, CDialog) //{{AFX_MSG_MAP(CAboutBox) //}}AFX_MSG_MAP END_MESSAGE_MAP() //--------------------------------------------------------------------------- CAboutBox::CAboutBox(CWnd* pParent /*=NULL*/) : CDialog(CAboutBox::IDD, pParent) { //{{AFX_DATA_INIT(CAboutBox) //}}AFX_DATA_INIT } //--------------------------------------------------------------------------- void CAboutBox::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutBox) //}}AFX_DATA_MAP } //--------------------------------------------------------------------------- BOOL CAboutBox::OnInitDialog() { CDialog::OnInitDialog(); // initialize the big icon control //m_icon.SubclassDlgItem(IDC_BIGICON, this); //m_icon.SizeToContent(); // fill available memory /*CString str, strFmt; strFmt.LoadString(IDS_PHYSICAL_MEM); MEMORYSTATUS MemStat; MemStat.dwLength = sizeof(MEMORYSTATUS); GlobalMemoryStatus(&MemStat); wsprintf(str.GetBuffer(80), strFmt, MemStat.dwTotalPhys / 1024L); str.ReleaseBuffer(); SetDlgItemText(IDC_PHYSICAL_MEM, str); // fill disk free information struct _diskfree_t diskfree; if (_getdiskfree(_getdrive(), &diskfree) == 0) { strFmt.LoadString(IDS_DISK_SPACE); wsprintf(str.GetBuffer(80), strFmt, (DWORD)diskfree.avail_clusters * (DWORD)diskfree.sectors_per_cluster * (DWORD)diskfree.bytes_per_sector / (DWORD)1024L); str.ReleaseBuffer(); } else str.LoadString(IDS_DISK_SPACE_UNAVAIL); SetDlgItemText(IDC_DISK_SPACE, str);*/ // fill SysCAD version number etc Strng s; SetDlgItemText(IDC_SYSCAD_VERSION, FullVersion()); SetDlgItemText(IDC_ACOPYRIGHT, CopyrightNotice()); SetDlgItemText(IDC_ACOMPANY, FullCompany()); s.Set("Build date: %s", BuildDate()); SetDlgItemText(IDC_BUILDDATE, s()); s.Set("Distributed by %s", FullCompany2()); SetDlgItemText(IDC_ACOMPANY2, s()); /*if (strlen(SCD_PATCHNOTE)>0) { if (strlen(SCD_PATCHDATE)>0) s.Set("%s (%s)", SCD_PATCHNOTE, SCD_PATCHDATE); else s.Set("%s", SCD_PATCHNOTE); } else*/ s = "TODO"; SetDlgItemText(IDC_PATCH, s()); return TRUE; // return TRUE unless you set the focus to a control } //=========================================================================== /* #define CY_SHADOW 4 #define CX_SHADOW 4 BEGIN_MESSAGE_MAP(CBigIcon, CButton) //{{AFX_MSG_MAP(CBigIcon) ON_WM_DRAWITEM() ON_WM_ERASEBKGND() //}}AFX_MSG_MAP END_MESSAGE_MAP() //--------------------------------------------------------------------------- void CBigIcon::SizeToContent() { // get system icon size int cxIcon = ::GetSystemMetrics(SM_CXICON); int cyIcon = ::GetSystemMetrics(SM_CYICON); // a big icon should be twice the size of an icon + shadows SetWindowPos(NULL, 0, 0, cxIcon*2 + CX_SHADOW + 4, cyIcon*2 + CY_SHADOW + 4, SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOZORDER); } //--------------------------------------------------------------------------- void CBigIcon::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CDC* pDC = CDC::FromHandle(lpDrawItemStruct->hDC); ASSERT(pDC != NULL); CRect rect; GetClientRect(rect); int cxClient = rect.Width(); int cyClient = rect.Height(); // load icon //enter syscad icon here HICON hicon = ScdApp()->LoadIcon(IDR_MAINFRAME); if (hicon == NULL) return; // draw icon into off-screen bitmap int cxIcon = ::GetSystemMetrics(SM_CXICON); int cyIcon = ::GetSystemMetrics(SM_CYICON); CBitmap bitmap; if (!bitmap.CreateCompatibleBitmap(pDC, cxIcon, cyIcon)) return; CDC dcMem; if (!dcMem.CreateCompatibleDC(pDC)) return; CBitmap* pBitmapOld = dcMem.SelectObject(&bitmap); if (pBitmapOld == NULL) return; // blt the bits already on the window onto the off-screen bitmap dcMem.StretchBlt(0, 0, cxIcon, cyIcon, pDC, 2, 2, cxClient-CX_SHADOW-4, cyClient-CY_SHADOW-4, SRCCOPY); // draw the icon on the background dcMem.DrawIcon(0, 0, hicon); // draw border around icon CPen pen; pen.CreateStockObject(BLACK_PEN); CPen* pPenOld = pDC->SelectObject(&pen); pDC->Rectangle(0, 0, cxClient-CX_SHADOW, cyClient-CY_SHADOW); if (pPenOld) pDC->SelectObject(pPenOld); // draw shadows around icon CBrush br; br.CreateStockObject(DKGRAY_BRUSH); rect.SetRect(cxClient-CX_SHADOW, CY_SHADOW, cxClient, cyClient); pDC->FillRect(rect, &br); rect.SetRect(CX_SHADOW, cyClient-CY_SHADOW, cxClient, cyClient); pDC->FillRect(rect, &br); // draw the icon contents pDC->StretchBlt(2, 2, cxClient-CX_SHADOW-4, cyClient-CY_SHADOW-4, &dcMem, 0, 0, cxIcon, cyIcon, SRCCOPY); } //--------------------------------------------------------------------------- BOOL CBigIcon::OnEraseBkgnd(CDC*) { return TRUE; // we don't do any erasing... } */ //===========================================================================
[ [ [ 1, 88 ], [ 90, 95 ], [ 98, 193 ] ], [ [ 89, 89 ], [ 96, 97 ] ] ]
cea1e8d1d5c101aed856292ac22ec5b6748408b4
74d531abb9fda8dc621c5d8376eb10ec4ef19568
/src/renderer/renderer.h
a253b3effea3669d3e0c6d2b210ef91f64a777c4
[]
no_license
aljosaosep/xsoko
e207d6ec8de3196029e569e7765424a399a50f04
c52440ecee65dc2f3f38d996936e65b3ff3b8b5e
refs/heads/master
2021-01-10T14:27:04.644013
2009-09-02T20:39:53
2009-09-02T20:39:53
49,592,571
0
0
null
null
null
null
UTF-8
C++
false
false
3,742
h
/* * codename: xSoko * Copyright (C) Aljosa Osep, Jernej Skrabec, Jernej Halozan 2008 <[email protected], [email protected], [email protected]> * * xSoko project 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. * * xSoko project 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/>. */ /* * Codename: xSoko * File: renderer.h * * Summary: * Includes level renderer classes definition * * Author: Aljosa Osep 2007 * Changes: * Aljosa 2008 */ #ifndef __RENDERER_H #define __RENDERER_H #include <stdio.h> #include <string> #include "../CommonStructures.h" #include "../messages.h" using namespace PacGame::Structures; namespace PacGame { namespace RenderMaschine { // TODO: indent code properly /* #ifndef __VERTICES_DATA #define __VERTICES_DATA GLfloat box[] = { // FRONT -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, // BACK -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, // LEFT -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, // RIGHT 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, // TOP -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, // BOTTOM -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, }; GLfloat texCoords[] = { // FRONT 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // BACK 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // LEFT 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // RIGHT 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // TOP 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // BOTTOM 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; #endif*/ /********************************************************** * PRenderer * * Class for drawing stuff * -------------------------------------------------------- * Aljosa 2007-2008 * ********************************************************/ class PRenderer { private: // light properties float lightAmbient[4]; float lightDiffuse[4]; float lightPosition[4]; // GLfloat box[24][4]; // GLfloat texCoords[24][2]; // material properties // float matAmbient[4]; // float matDiffuse[4]; public: // constructor PRenderer(); // system functions bool init(); void deinit(); // getters float* getLightPosition(); // functions that are drawing stuff void drawBackground(); void drawSkyDome(); void drawCube(float x, float y, float size); void drawFloor(float x, float y, float size); }; } } #endif
[ "aljosa.osep@d77d96cf-bc4d-0410-95e8-7f58e8f99bdb", "jernej.halozan@d77d96cf-bc4d-0410-95e8-7f58e8f99bdb", "jernej.skrabec@d77d96cf-bc4d-0410-95e8-7f58e8f99bdb" ]
[ [ [ 1, 18 ], [ 20, 28 ], [ 44, 167 ] ], [ [ 19, 19 ], [ 29, 35 ], [ 38, 43 ], [ 168, 170 ] ], [ [ 36, 37 ] ] ]
1bc8d1945b523e2aa96f1fab3a28055cec47c240
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_graphics/image_formats/juce_JPEGLoader.cpp
446927a79fe7f9f1eec5ad6b49e660ee34c007f8
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
13,663
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #if JUCE_MSVC #pragma warning (push) #pragma warning (disable: 4365) #endif namespace jpeglibNamespace { #if JUCE_INCLUDE_JPEGLIB_CODE || ! defined (JUCE_INCLUDE_JPEGLIB_CODE) #if JUCE_MINGW typedef unsigned char boolean; #endif #define JPEG_INTERNALS #undef FAR #include "jpglib/jpeglib.h" #include "jpglib/jcapimin.c" #include "jpglib/jcapistd.c" #include "jpglib/jccoefct.c" #include "jpglib/jccolor.c" #undef FIX #include "jpglib/jcdctmgr.c" #undef CONST_BITS #include "jpglib/jchuff.c" #undef emit_byte #include "jpglib/jcinit.c" #include "jpglib/jcmainct.c" #include "jpglib/jcmarker.c" #include "jpglib/jcmaster.c" #include "jpglib/jcomapi.c" #include "jpglib/jcparam.c" #include "jpglib/jcphuff.c" #include "jpglib/jcprepct.c" #include "jpglib/jcsample.c" #include "jpglib/jctrans.c" #include "jpglib/jdapistd.c" #include "jpglib/jdapimin.c" #include "jpglib/jdatasrc.c" #include "jpglib/jdcoefct.c" #undef FIX #include "jpglib/jdcolor.c" #undef FIX #include "jpglib/jddctmgr.c" #undef CONST_BITS #undef ASSIGN_STATE #include "jpglib/jdhuff.c" #include "jpglib/jdinput.c" #include "jpglib/jdmainct.c" #include "jpglib/jdmarker.c" #include "jpglib/jdmaster.c" #undef FIX #include "jpglib/jdmerge.c" #undef ASSIGN_STATE #include "jpglib/jdphuff.c" #include "jpglib/jdpostct.c" #undef FIX #include "jpglib/jdsample.c" #include "jpglib/jdtrans.c" #include "jpglib/jfdctflt.c" #include "jpglib/jfdctint.c" #undef CONST_BITS #undef MULTIPLY #undef FIX_0_541196100 #include "jpglib/jfdctfst.c" #undef FIX_0_541196100 #include "jpglib/jidctflt.c" #undef CONST_BITS #undef FIX_1_847759065 #undef MULTIPLY #undef DEQUANTIZE #undef DESCALE #include "jpglib/jidctfst.c" #undef CONST_BITS #undef FIX_1_847759065 #undef MULTIPLY #undef DEQUANTIZE #include "jpglib/jidctint.c" #include "jpglib/jidctred.c" #include "jpglib/jmemmgr.c" #include "jpglib/jmemnobs.c" #include "jpglib/jquant1.c" #include "jpglib/jquant2.c" #include "jpglib/jutils.c" #include "jpglib/transupp.c" #else #define JPEG_INTERNALS #undef FAR #include <jpeglib.h> #endif } #undef max #undef min #if JUCE_MSVC #pragma warning (pop) #endif BEGIN_JUCE_NAMESPACE //============================================================================== namespace JPEGHelpers { using namespace jpeglibNamespace; #if ! JUCE_MSVC using jpeglibNamespace::boolean; #endif struct JPEGDecodingFailure {}; void fatalErrorHandler (j_common_ptr) { throw JPEGDecodingFailure(); } void silentErrorCallback1 (j_common_ptr) {} void silentErrorCallback2 (j_common_ptr, int) {} void silentErrorCallback3 (j_common_ptr, char*) {} void setupSilentErrorHandler (struct jpeg_error_mgr& err) { zerostruct (err); err.error_exit = fatalErrorHandler; err.emit_message = silentErrorCallback2; err.output_message = silentErrorCallback1; err.format_message = silentErrorCallback3; err.reset_error_mgr = silentErrorCallback1; } //============================================================================== void dummyCallback1 (j_decompress_ptr) {} void jpegSkip (j_decompress_ptr decompStruct, long num) { decompStruct->src->next_input_byte += num; num = jmin (num, (long) decompStruct->src->bytes_in_buffer); decompStruct->src->bytes_in_buffer -= num; } boolean jpegFill (j_decompress_ptr) { return 0; } //============================================================================== const int jpegBufferSize = 512; struct JuceJpegDest : public jpeg_destination_mgr { OutputStream* output; char* buffer; }; void jpegWriteInit (j_compress_ptr) {} void jpegWriteTerminate (j_compress_ptr cinfo) { JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest); const size_t numToWrite = jpegBufferSize - dest->free_in_buffer; dest->output->write (dest->buffer, (int) numToWrite); } boolean jpegWriteFlush (j_compress_ptr cinfo) { JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest); const int numToWrite = jpegBufferSize; dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer); dest->free_in_buffer = jpegBufferSize; return (boolean) dest->output->write (dest->buffer, numToWrite); } } //============================================================================== JPEGImageFormat::JPEGImageFormat() : quality (-1.0f) { } JPEGImageFormat::~JPEGImageFormat() {} void JPEGImageFormat::setQuality (const float newQuality) { quality = newQuality; } String JPEGImageFormat::getFormatName() { return "JPEG"; } bool JPEGImageFormat::canUnderstand (InputStream& in) { const int bytesNeeded = 10; uint8 header [bytesNeeded]; if (in.read (header, bytesNeeded) == bytesNeeded) { return header[0] == 0xff && header[1] == 0xd8 && header[2] == 0xff && (header[3] == 0xe0 || header[3] == 0xe1); } return false; } #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && JUCE_USE_COREIMAGE_LOADER Image juce_loadWithCoreImage (InputStream& input); #endif Image JPEGImageFormat::decodeImage (InputStream& in) { #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && JUCE_USE_COREIMAGE_LOADER return juce_loadWithCoreImage (in); #else using namespace jpeglibNamespace; using namespace JPEGHelpers; MemoryOutputStream mb; mb << in; Image image; if (mb.getDataSize() > 16) { struct jpeg_decompress_struct jpegDecompStruct; struct jpeg_error_mgr jerr; setupSilentErrorHandler (jerr); jpegDecompStruct.err = &jerr; jpeg_create_decompress (&jpegDecompStruct); jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small) ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr)); jpegDecompStruct.src->init_source = dummyCallback1; jpegDecompStruct.src->fill_input_buffer = jpegFill; jpegDecompStruct.src->skip_input_data = jpegSkip; jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart; jpegDecompStruct.src->term_source = dummyCallback1; jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData()); jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize(); try { jpeg_read_header (&jpegDecompStruct, TRUE); jpeg_calc_output_dimensions (&jpegDecompStruct); const int width = (int) jpegDecompStruct.output_width; const int height = (int) jpegDecompStruct.output_height; jpegDecompStruct.out_color_space = JCS_RGB; JSAMPARRAY buffer = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct, JPOOL_IMAGE, (JDIMENSION) width * 3, 1); if (jpeg_start_decompress (&jpegDecompStruct)) { image = Image (Image::RGB, width, height, false); image.getProperties()->set ("originalImageHadAlpha", false); const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect) const Image::BitmapData destData (image, Image::BitmapData::writeOnly); for (int y = 0; y < height; ++y) { jpeg_read_scanlines (&jpegDecompStruct, buffer, 1); const uint8* src = *buffer; uint8* dest = destData.getLinePointer (y); if (hasAlphaChan) { for (int i = width; --i >= 0;) { ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]); ((PixelARGB*) dest)->premultiply(); dest += destData.pixelStride; src += 3; } } else { for (int i = width; --i >= 0;) { ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]); dest += destData.pixelStride; src += 3; } } } jpeg_finish_decompress (&jpegDecompStruct); in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData()); } jpeg_destroy_decompress (&jpegDecompStruct); } catch (...) {} } return image; #endif } bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out) { using namespace jpeglibNamespace; using namespace JPEGHelpers; struct jpeg_compress_struct jpegCompStruct; jpeg_create_compress (&jpegCompStruct); struct jpeg_error_mgr jerr; setupSilentErrorHandler (jerr); jpegCompStruct.err = &jerr; JuceJpegDest dest; jpegCompStruct.dest = &dest; dest.output = &out; HeapBlock <char> tempBuffer (jpegBufferSize); dest.buffer = tempBuffer; dest.next_output_byte = (JOCTET*) dest.buffer; dest.free_in_buffer = jpegBufferSize; dest.init_destination = jpegWriteInit; dest.empty_output_buffer = jpegWriteFlush; dest.term_destination = jpegWriteTerminate; jpegCompStruct.image_width = (JDIMENSION) image.getWidth(); jpegCompStruct.image_height = (JDIMENSION) image.getHeight(); jpegCompStruct.input_components = 3; jpegCompStruct.in_color_space = JCS_RGB; jpegCompStruct.write_JFIF_header = 1; jpegCompStruct.X_density = 72; jpegCompStruct.Y_density = 72; jpeg_set_defaults (&jpegCompStruct); jpegCompStruct.dct_method = JDCT_FLOAT; jpegCompStruct.optimize_coding = 1; if (quality < 0.0f) quality = 0.85f; jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE); jpeg_start_compress (&jpegCompStruct, TRUE); const int strideBytes = (int) (jpegCompStruct.image_width * jpegCompStruct.input_components); JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct, JPOOL_IMAGE, (JDIMENSION) strideBytes, 1); const Image::BitmapData srcData (image, Image::BitmapData::readOnly); while (jpegCompStruct.next_scanline < jpegCompStruct.image_height) { uint8* dst = *buffer; if (srcData.pixelFormat == Image::RGB) { const uint8* src = srcData.getLinePointer ((int) jpegCompStruct.next_scanline); for (int i = srcData.width; --i >= 0;) { *dst++ = ((const PixelRGB*) src)->getRed(); *dst++ = ((const PixelRGB*) src)->getGreen(); *dst++ = ((const PixelRGB*) src)->getBlue(); src += srcData.pixelStride; } } else { for (int x = 0; x < srcData.width; ++x) { const Colour pixel (srcData.getPixelColour (x, (int) jpegCompStruct.next_scanline)); *dst++ = pixel.getRed(); *dst++ = pixel.getGreen(); *dst++ = pixel.getBlue(); } } jpeg_write_scanlines (&jpegCompStruct, buffer, 1); } jpeg_finish_compress (&jpegCompStruct); jpeg_destroy_compress (&jpegCompStruct); return true; } END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 426 ] ] ]
a87e6c346cd8001b0ed1bb5b5ec100dad515866b
288840a48549582b64d2eb312c2e348d588b278b
/src/dijkstra.cpp
54f0c513643cbf626d61870d74040a9ec8e6d4a0
[]
no_license
mikegogulski/Mephbot
590672d2cf859b2b125514d4f581b9543894ff46
efa1e17a447300b763111f0993a6bc91b6a7b0d4
refs/heads/master
2016-09-06T02:05:43.197714
2011-12-10T20:07:46
2011-12-10T20:07:46
1,107,469
9
5
null
null
null
null
UTF-8
C++
false
false
4,640
cpp
////////////////////////////////////////////////////////////////////////////// // // COPYRIGHT // // This program is Copyright (c) 2002 by Mike Gogulski <[email protected]> // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // // Syadasti's open-source human-readable software LICENSE // // This code is freely redistributable, provided that all credits and // copyright notices are preserved. // // You may use this code in your own software without restriction, provided // that your software is distributed with complete source code. // // You agree by making use of this code that whatever problems you experience // as a result are your fault, and yours alone. // ////////////////////////////////////////////////////////////////////////////// #define WIN32_LEAN_AND_MEAN #include "util.h" #include "logging.h" #include "dijkstra.h" class Vertex { public: int Adjacent[MAX]; // adjacent vertices int NumAdjacencies; // # of adjacent vertices double AdjacencyWeight[MAX]; // weights of adjacent vertices // these two will be undefined until dijkstra() is called int Previous; // previous hop on path from source double Cost; // Cost to here from source Vertex() { NumAdjacencies = 0; } void push(int neighbor, double Cost) { Adjacent[NumAdjacencies] = neighbor; AdjacencyWeight[NumAdjacencies] = Cost; NumAdjacencies++; } }; void dijkstra(Vertex *v, int size, int source) { double Cost[MAX]; int done[MAX]; int to_do = size; int i; for (i = 0; i < size; i++) { v[i].Cost = Cost[i] = INFINITY; v[i].Previous = -1; done[i] = 0; } Cost[source] = 0; while (to_do) { int iMin; for (i = 0; i < size; i++) { if (!done[i]) { iMin=i; break; } } for (i = iMin + 1; i < size; i++) if (!done[i] && Cost[i] < Cost[iMin]) { iMin = i; } done[iMin] = 1; to_do--; for (i = 0; i < v[iMin].NumAdjacencies; i++) if (Cost[iMin] + v[iMin].AdjacencyWeight[i] < Cost[v[iMin].Adjacent[i]]) { v[v[iMin].Adjacent[i]].Previous = iMin; v[v[iMin].Adjacent[i]].Cost = Cost[v[iMin].Adjacent[i]] = Cost[iMin] + v[iMin].AdjacencyWeight[i]; } } } myPOINT Points[MAX]; BYTE bPointsIndex = 2; // start at 2 to avoid PLAYER and STAIRS WORD StairsPath[MAX][2]; BYTE bStairsPathIndex = 0; int HopsToStairs = 0; VOID CreatePath(Vertex *v, int source, int dest) { if (source == dest) { StairsPath[bStairsPathIndex][0] = Points[dest].x; StairsPath[bStairsPathIndex][1] = Points[dest].y; bStairsPathIndex++; } else { if (v[dest].Previous != -1) { CreatePath(v, source, v[dest].Previous); StairsPath[bStairsPathIndex][0] = Points[dest].x; StairsPath[bStairsPathIndex][1] = Points[dest].y; bStairsPathIndex++; } else { dprintf(DEBUG_ALL, "ABORT: Unable to build path to stairs"); NumAborts++; Tick1 = 0; ChangeState(STATE_EXIT_GAME); ExitGame(); } } dprintf(DEBUG_DIJKSTRA, "bStairsPathIndex = %d", bStairsPathIndex); } VOID FindStairsPath(VOID) { Vertex v[MAX]; DWORD d; //Points[PLAYER].x = PLAYERX; //Points[PLAYER].y = PLAYERY; Points[PLAYER].x = WpDurance2X; Points[PLAYER].y = WpDurance2Y; Points[STAIRS].x = StairsX; Points[STAIRS].y = StairsY; // Create the graph dprintf(DEBUG_DIJKSTRA, "bPointsIndex = %d", bPointsIndex); for (int i = 0; i < bPointsIndex; i++) { for (int j = 0; j < bPointsIndex; j++) { if (i != j) { d = Dist2(Points[i].x, Points[i].y, Points[j].x, Points[j].y); //dprintf(DEBUG_DIJKSTRA, "d = %d", (int)sqrt((double)d)); if (d <= (DWORD)(2 * 60 * 60) /*&& (Points[i].x == Points[j].x || Points[i].y == Points[j].y)*/) { //dprintf(DEBUG_DIJKSTRA, "adding arc to %d (%.4X, %.4X) to Vertex %d (%.4X, %.4X)", j, Points[j].x, Points[j].y, i, Points[i].x, Points[i].y); v[i].push(j, sqrt((double)d)); } } } dprintf(DEBUG_DIJKSTRA, "Vertex %d at (%.4X, %.4X) has %d arcs", i, Points[i].x, Points[i].y, v[i].NumAdjacencies); } dprintf(DEBUG_DIJKSTRA, "Calling dijkstra()"); dijkstra(v, bPointsIndex, PLAYER); bStairsPathIndex = 0; dprintf(DEBUG_DIJKSTRA, "Calling CreatePath()"); CreatePath(v, PLAYER, STAIRS); HopsToStairs = bStairsPathIndex; dprintf(DEBUG_DIJKSTRA, "Player at (%.4X, %.4X)", PLAYERX, PLAYERY); for (int k = 0; k < bStairsPathIndex; k++) { dprintf(DEBUG_DIJKSTRA, "Hop %d: (%.4X, %.4X)", k, StairsPath[k][0], StairsPath[k][1]); } dprintf(DEBUG_DIJKSTRA, "Stairs at (%.4X, %.4X)", StairsX, StairsY); }
[ [ [ 1, 130 ] ] ]
e11343adc40d8ccfcf310e0f2ebe054ccb796753
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/SmartWires/SmallXmlRpcClientServer/DLG_ClientTest.h
8d0bde651da9d46c8ea2f1b3aa59ecb3176f1cf5
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
UTF-8
C++
false
false
1,729
h
#if !defined(AFX_DLG_CLIENTTEST_H__301E9B39_D301_4EEE_ABF6_96DD8CEC07C8__INCLUDED_) #define AFX_DLG_CLIENTTEST_H__301E9B39_D301_4EEE_ABF6_96DD8CEC07C8__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DLG_ClientTest.h : header file // ///////////////////////////////////////////////////////////////////////////// // DLG_ClientTest dialog #include "\PROJECTS_ROOT\Tools\SmartWndSizer\SmartWndSizer.h" class DLG_ClientTest : public CDialog { // Construction public: DWORD dwTimer; CSmartWndSizer Sizer; DLG_ClientTest(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(DLG_ClientTest) enum { IDD = IDD_TESTCLIENT }; CButton m_Stats; CString m_Address; CString m_Received; CString m_Sended; CString m_Method; CString m_Statistica; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(DLG_ClientTest) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(DLG_ClientTest) afx_msg void OnStart(); afx_msg void OnGetstatistic(); virtual BOOL OnInitDialog(); afx_msg void OnStartSync(); afx_msg void OnStartAsync(); afx_msg void OnUpdate(); afx_msg void OnDestroy(); afx_msg void OnTimer(UINT nIDEvent); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DLG_CLIENTTEST_H__301E9B39_D301_4EEE_ABF6_96DD8CEC07C8__INCLUDED_)
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 61 ] ] ]
ba0c974c8348cf3a6a88d78ac7010e46d8d36a5c
9176b0fd29516d34cfd0b143e1c5c0f9e665c0ed
/CS_153_Data_Structures/assignment9/exception.cpp
0e852efab3471c0a67140d4400574ed677c5d36e
[]
no_license
Mr-Anderson/james_mst_hw
70dbde80838e299f9fa9c5fcc16f4a41eec8263a
83db5f100c56e5bb72fe34d994c83a669218c962
refs/heads/master
2020-05-04T13:15:25.694979
2011-11-30T20:10:15
2011-11-30T20:10:15
2,639,602
2
0
null
null
null
null
UTF-8
C++
false
false
597
cpp
////////////////////////////////////////////////////////////////////// /// @file exception.cpp /// @author James Anderson Section A /// @brief Implementation file for exception class for assignment 9 ////////////////////////////////////////////////////////////////////// #include "exception.h" Exception::Exception (Error_Type _error_code, string _error_message) { m_error_code = _error_code; m_error_message = _error_message; } Error_Type Exception::error_code () { return m_error_code; } string Exception::error_message () { return m_error_message; }
[ [ [ 1, 22 ] ] ]
8da17615736fd59729102c3bb228a48e8363fbee
d7b345a8a6b0473c325fab661342de295c33b9c8
/beta/src/powerwindow/powerwindow.cpp
5a4f1331c8d204a48e2cfb527c3634a06d9fdd8c
[]
no_license
raould/Polaris-Open-Source
67ccd647bf40de51a3dae903ab70e8c271f3f448
10d0ca7e2db9e082e1d2ed2e43fa46875f1b07b2
refs/heads/master
2021-01-01T19:19:39.148016
2010-05-10T17:39:26
2010-05-10T17:39:26
631,953
3
2
null
null
null
null
UTF-8
C++
false
false
14,026
cpp
// Copyright 2010 Hewlett-Packard under the terms of the MIT X license // found at http://www.opensource.org/licenses/mit-license.html // powerwindow.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "powerwindow.h" #include "ActivePet.h" #include "ActiveWorld.h" #include "EventLoop.h" #include "FixAndClean.h" #include "../polaris/auto_privilege.h" #include "../polaris/Constants.h" #include "../polaris/Runnable.h" #include "../polaris/Logger.h" #include "../polaris/RegKey.h" #include <Wincrypt.h> #include <shellapi.h> #define MAX_LOADSTRING 100 const UINT TRAYICONID = 1; const UINT TRAYMSG = WM_APP; const UINT KILLPET = WM_APP + 1; class MainLoop; // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name NOTIFYICONDATA icon_data = {}; // The system tray icon info. Logger m_logger(L"WinMain"); // The logger for this module. bool m_waiting_to_die = false; // Are we waiting for the WM_QUIT message? MainLoop* m_main_loop = NULL; ActiveWorld* m_world = NULL; HANDLE* m_events = new HANDLE[0]; // The list of events to wait on. Runnable** m_event_handlers = new Runnable*[0]; // The list of corresponding event handlers. size_t m_event_count = 0; // The event list size. // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM); class MainLoop : public EventLoop { public: virtual void watch(HANDLE event, Runnable* handler) { assert(INVALID_HANDLE_VALUE != event); assert(NULL != handler); HANDLE* old_events = m_events; m_events = new HANDLE[m_event_count + 1]; memcpy(m_events, old_events, m_event_count * sizeof(HANDLE)); m_events[m_event_count] = event; delete[] old_events; Runnable** old_handlers = m_event_handlers; m_event_handlers = new Runnable*[m_event_count + 1]; memcpy(m_event_handlers, old_handlers, m_event_count * sizeof(Runnable*)); m_event_handlers[m_event_count] = handler; delete[] old_handlers; ++m_event_count; } virtual void ignore(HANDLE event, Runnable* handler) { size_t index = std::find(m_event_handlers, m_event_handlers + m_event_count, handler) - m_event_handlers; if (index != m_event_count) { HANDLE* old_events = m_events; m_events = new HANDLE[m_event_count - 1]; memcpy(m_events, old_events, index * sizeof(HANDLE)); memcpy(m_events + index, old_events + index + 1, (m_event_count - index - 1) * sizeof(HANDLE)); delete[] old_events; Runnable** old_handlers = m_event_handlers; m_event_handlers = new Runnable*[m_event_count - 1]; memcpy(m_event_handlers, old_handlers, index * sizeof(Runnable*)); memcpy(m_event_handlers + index, old_handlers + index + 1, (m_event_count - index - 1) * sizeof(Runnable*)); delete[] old_handlers; --m_event_count; } } }; class KillAndNotify : public ActiveAccount::Task { HANDLE m_notify; public: KillAndNotify(HANDLE notify) : m_notify(notify) {} virtual ~KillAndNotify() {} virtual void run(ActiveAccount& account) { account.kill(); SetEvent(m_notify); } }; int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_POWERWINDOW, szWindowClass, MAX_LOADSTRING); if (NULL != FindWindow(szWindowClass, NULL)) { return 0; } MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_POWERWINDOW); // Main message loop: MSG msg; while (true) { // Wait for the next event or message. DWORD result = ::MsgWaitForMultipleObjects(m_event_count, m_events, FALSE, INFINITE, QS_ALLINPUT); if (WAIT_OBJECT_0 + m_event_count == result) { while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (WM_QUIT == msg.message && m_waiting_to_die) { goto done; } if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } } else if (WAIT_OBJECT_0 <= result && WAIT_OBJECT_0 + m_event_count > result) { m_event_handlers[result - WAIT_OBJECT_0]->run(); // Ensure fairness by doing an explicit check on the remaining events. for (size_t i = result - WAIT_OBJECT_0 + 1; i < m_event_count; ++i) { if (WAIT_OBJECT_0 == ::WaitForSingleObject(m_events[i], 0)) { m_event_handlers[i]->run(); } } } else if (WAIT_FAILED == result) { // Should not happen. m_logger.log(L"MsgWaitForMultipleObjects()", GetLastError()); } else { // Should not happen. m_logger.log(L"MsgWaitForMultipleObjects() invalid return", result); } } done: // Kill all the running pets. m_logger.log(L"Killing all active pets..."); std::list<ActivePet*>& pets = m_world->list(); size_t pet_count = pets.size(); HANDLE* pet_done = new HANDLE[pet_count]; HANDLE* notify = pet_done; for (std::list<ActivePet*>::iterator i = pets.begin(); i != pets.end(); ++i) { *notify = CreateEvent(NULL, TRUE, FALSE, NULL); (*i)->send(new KillAndNotify(*notify)); ++notify; } WaitForMultipleObjects(pet_count, pet_done, TRUE, INFINITE); delete m_world; m_logger.log(L"Done."); return (int)msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // // COMMENTS: // // This function and its usage are only necessary if you want this code // to be compatible with Win32 systems prior to the 'RegisterClassEx' // function that was added to Windows 95. It is important to call this function // so that the application will get 'well formed' small icons associated // with it. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = (WNDPROC)WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_POWERWINDOW); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = (LPCTSTR)IDC_POWERWINDOW; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_POWERWINDOW); return RegisterClassEx(&wcex); } UINT_PTR CALLBACK CloseFileDialog(HWND hdlg, UINT uiMsg, WPARAM wParam, LPARAM lParam) { ::PostMessage(::GetParent(hdlg), WM_COMMAND, IDCANCEL, 0); return 0; } // // FUNCTION: InitInstance(HANDLE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } FixAndClean::fix(); m_main_loop = new MainLoop(); // Figure out the password for network authentication // If no authentication needed, a "" password is created // TODO: The main password setting mechanism has been moved to the activepet useServers run method, // so if the password is changed, the change is picked up when a pet is launched. Passing the // empty password through 500 method calls now makes little sense. Remove the passing of this stuff // through the stack. wchar_t password[1024] = {}; //RegKey polarisKey = RegKey::HKCU.open(Constants::registryBase()); //bool needsPassword = polarisKey.getValue(Constants::registryNeedsPassword()) == L"true"; //bool passwordStored = polarisKey.getValue(Constants::registryPasswordIsStored()) == L"true"; //if (needsPassword && !passwordStored) { // puts("Enter your password:\n"); // _getws(password); // for (int i = 0; i < 30; ++i) {printf("\n");} //} else if (needsPassword && passwordStored) { // FILE* passwordFile = _wfopen(Constants::passwordFilePath(Constants::polarisDataPath( // _wgetenv(L"USERPROFILE"))).c_str(), L"rb"); // DATA_BLOB clearPass; // DATA_BLOB cryptPass; // byte cryptBytes[1000]; // size_t bytesSize = fread(cryptBytes,1, 900, passwordFile); // cryptPass.pbData = cryptBytes; // cryptPass.cbData = bytesSize; // if (CryptUnprotectData(&cryptPass, NULL, NULL, NULL, NULL, // CRYPTPROTECT_UI_FORBIDDEN, &clearPass)) { // wcscpy(password, (wchar_t*) clearPass.pbData); // LocalFree(clearPass.pbData); // } else { // m_logger.log(L"cryptUnprotectData failed", GetLastError()); // } // //fgetws(password, sizeof(password) -1, passwordFile); // fclose(passwordFile); //} m_world = makeActiveWorld(m_main_loop, password); // Setup the systray icon. HICON tray_icon = (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDI_POWERWINDOW), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR); icon_data.cbSize = sizeof(NOTIFYICONDATA); icon_data.hWnd = hWnd; icon_data.uID = TRAYICONID; icon_data.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; icon_data.uCallbackMessage = TRAYMSG; icon_data.hIcon = tray_icon; lstrcpyn(icon_data.szTip, L"Polaris is active", sizeof icon_data.szTip / sizeof(wchar_t)); ::Shell_NotifyIcon(NIM_ADD, &icon_data); ::DestroyIcon(tray_icon); // Don't show the window. // ShowWindow(hWnd, nCmdShow); // UpdateWindow(hWnd); return TRUE; } void ShowSysTrayMenu(HWND hWnd) { POINT pt; GetCursorPos(&pt); HMENU hMenu = CreatePopupMenu(); if(hMenu) { AppendMenu(hMenu, MF_STRING, IDM_EXIT, _T("Exit")); HMENU hPets = CreatePopupMenu(); if (hPets) { std::list<ActivePet*>& pets = m_world->list(); if (pets.empty()) { AppendMenu(hPets, MF_GRAYED | MF_STRING, KILLPET, _T("No active pets")); } else { UINT index = 0; for (std::list<ActivePet*>::iterator i = pets.begin(); i != pets.end(); ++i) { std::wstring petname = (*i)->getName().c_str(); AppendMenu(hPets, MF_STRING, KILLPET + index, petname.c_str()); ++index; } } AppendMenu(hMenu, MF_POPUP, (UINT_PTR)hPets, _T("Kill")); } // note: must set window to the foreground or the // menu won't disappear when it should SetForegroundWindow(hWnd); TrackPopupMenu(hMenu, TPM_BOTTOMALIGN, pt.x, pt.y, 0, hWnd, NULL ); DestroyMenu(hPets); DestroyMenu(hMenu); } } // // FUNCTION: WndProc(HWND, unsigned, WORD, LONG) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case TRAYMSG: switch (lParam) { case WM_RBUTTONDOWN: case WM_CONTEXTMENU: ShowSysTrayMenu(hWnd); break; } break; case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: { std::list<ActivePet*>& pets = m_world->list(); if (wmId >= KILLPET && wmId < KILLPET + pets.size()) { std::list<ActivePet*>::iterator i = pets.begin(); for (int n = wmId; n != KILLPET; --n) { ++i; } (*i)->send(new ActiveAccount::Kill()); pets.erase(i); } else { return DefWindowProc(hWnd, message, wParam, lParam); } } } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // Add any drawing code here... EndPaint(hWnd, &ps); break; case WM_DESTROY: m_waiting_to_die = true; ::Shell_NotifyIcon(NIM_DELETE, &icon_data); PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE; }
[ [ [ 1, 426 ] ] ]
181a6703b6d9cee77f37e4189ad1e0fcd5b18a7d
0355816da4439e3022ff47421d542466ba8f6087
/lab2/src/cSphere.cpp
5a8a8a05009b0abfd3deef79fb47646526dc1978
[]
no_license
winkie/cg
59ca9b089866457752347d5000c3fa14dcb5604c
2b70e4f28e08f7639c046e5d1c44ab649a81b2f1
refs/heads/master
2016-08-03T16:36:29.548040
2011-04-15T11:03:17
2011-04-15T11:06:11
1,599,604
0
0
null
null
null
null
UTF-8
C++
false
false
24
cpp
#include "cSphere.h"
[ "winkie@desktop.(none)" ]
[ [ [ 1, 2 ] ] ]
ad2208dbd6b3fa5fdc95424361c1a93e01326a92
701f9ab221639b56c28417ee6f6ee984acb24142
/Src/Force Engine/Entity2D/Shape.h
35ce10bdaff6b73618cafc79309902a82a48129d
[]
no_license
nlelouche/desprog1
2397130e427b4ada83721ecbb1a131682bc73187
71c7839675698e74ca43dd26c4af752e309dccb6
refs/heads/master
2021-01-22T06:33:14.083467
2010-02-26T16:18:39
2010-02-26T16:18:39
32,653,851
0
0
null
null
null
null
UTF-8
C++
false
false
1,232
h
/**************************************************************************** Force Engine v0.5 Creado: 28/03/08 Clase: Shape.h Hecho by: German Battiston AKA Melkor ****************************************************************************/ //--------------------------------------------------------------------------- #ifndef SHAPE_H #define SHAPE_H //--------------------------------------------------------------------------- #include "../Defines/Defines.h" #include "../Graphics/Graphics.h" #include "../Entity2D/Entity2D.h" #include "../Graphics/GraphicsStructs.h" //--------------------------------------------------------------------------- class Graphics; //--------------------------------------------------------------------------- class FORCEENGINE_API Shape : public Entity2D { public: ~Shape(); virtual void Draw(Graphics & rkGraphics) const; virtual void onCollision(Entity2D* pkEntity) { /*****/ } int m_iCantVertices; ColorVertex * m_pkVertices; protected: Shape(); }; //--------------------------------------------------------------------------- #endif /*--- SHAPE_H ---*/ //---------------------------------------------------------------------------
[ "gersurfer@a82ef5f6-654a-0410-99b4-23d68ab79cb1" ]
[ [ [ 1, 44 ] ] ]
808c0d5311b2c6d290c3043c297d3d2c338b1e1a
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/archive/detail/oserializer.hpp
4a6662f4e45f5b311ba741180957d389a2fa886f
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
20,785
hpp
#ifndef BOOST_ARCHIVE_OSERIALIZER_HPP #define BOOST_ARCHIVE_OSERIALIZER_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #pragma inline_depth(511) #pragma inline_recursion(on) #endif #if defined(__MWERKS__) #pragma inline_depth(511) #endif /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // oserializer.hpp: interface for serialization system. // (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 <cassert> #include <boost/config.hpp> #include <boost/detail/workaround.hpp> #include <boost/throw_exception.hpp> #include <boost/smart_cast.hpp> #include <boost/static_assert.hpp> #include <boost/static_warning.hpp> #include <boost/type_traits/is_pointer.hpp> #include <boost/type_traits/is_fundamental.hpp> #include <boost/type_traits/is_enum.hpp> #include <boost/type_traits/is_volatile.hpp> #include <boost/type_traits/is_const.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/serialization/is_abstract.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/less.hpp> #include <boost/mpl/greater_equal.hpp> #include <boost/mpl/equal_to.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/list.hpp> #include <boost/mpl/empty.hpp> #include <boost/mpl/not.hpp> #ifndef BOOST_SERIALIZATION_DEFAULT_TYPE_INFO #include <boost/serialization/extended_type_info_typeid.hpp> #endif // the following is need only for dynamic cast of polymorphic pointers #include <boost/archive/detail/basic_oarchive.hpp> #include <boost/archive/detail/basic_oserializer.hpp> #include <boost/archive/detail/archive_pointer_oserializer.hpp> #include <boost/serialization/force_include.hpp> #include <boost/serialization/serialization.hpp> #include <boost/serialization/version.hpp> #include <boost/serialization/level.hpp> #include <boost/serialization/tracking.hpp> #include <boost/serialization/type_info_implementation.hpp> #include <boost/serialization/nvp.hpp> #include <boost/serialization/void_cast.hpp> #include <boost/archive/archive_exception.hpp> namespace boost { namespace serialization { class extended_type_info; } // namespace serialization namespace archive { // an accessor to permit friend access to archives. Needed because // some compilers don't handle friend templates completely class save_access { public: template<class Archive> static void end_preamble(Archive & ar){ ar.end_preamble(); } template<class Archive, class T> static void save_primitive(Archive & ar, const T & t){ ar.end_preamble(); ar.save(t); } }; namespace detail { template<class Archive, class T> class oserializer : public basic_oserializer { private: // private constructor to inhibit any existence other than the // static one explicit oserializer() : basic_oserializer( * boost::serialization::type_info_implementation<T>::type::get_instance() ) {} public: virtual BOOST_DLLEXPORT void save_object_data( basic_oarchive & ar, const void *x ) const BOOST_USED ; virtual bool class_info() const { return boost::serialization::implementation_level<T>::value >= boost::serialization::object_class_info; } virtual bool tracking(const unsigned int /* flags */) const { // if(0 != (flags & no_tracking)) // return false; return boost::serialization::tracking_level<T>::value == boost::serialization::track_always || boost::serialization::tracking_level<T>::value == boost::serialization::track_selectivly && serialized_as_pointer(); } virtual unsigned int version() const { return ::boost::serialization::version<T>::value; } virtual bool is_polymorphic() const { typedef BOOST_DEDUCED_TYPENAME boost::serialization::type_info_implementation< T >::type::is_polymorphic::type typex; return typex::value; } static oserializer & instantiate(){ static oserializer instance; return instance; } virtual ~oserializer(){} }; template<class Archive, class T> BOOST_DLLEXPORT void oserializer<Archive, T>::save_object_data( basic_oarchive & ar, const void *x ) const { // make sure call is routed through the highest interface that might // be specialized by the user. boost::serialization::serialize_adl( boost::smart_cast_reference<Archive &>(ar), * static_cast<T *>(const_cast<void *>(x)), version() ); } // instantiation of this template creates a static object. Note inversion of // normal argument order to workaround bizarre error in MSVC 6.0 which only // manifests iftself during compiler time. template<class T, class Archive> class pointer_oserializer : public archive_pointer_oserializer<Archive> { private: virtual const basic_oserializer & get_basic_serializer() const { return oserializer<Archive, T>::instantiate(); } virtual BOOST_DLLEXPORT void save_object_ptr( basic_oarchive & ar, const void * x ) const BOOST_USED ; #if defined(__GNUC__) || ( defined(BOOST_MSVC) && (_MSC_VER <= 1300) ) public: #endif // private constructor to inhibit any existence other than the // static one. Note GCC doesn't permit constructor to be private explicit BOOST_DLLEXPORT pointer_oserializer() BOOST_USED; static const pointer_oserializer instance; public: #if ! BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) // at least one compiler (CW) seems to require that serialize_adl // be explicitly instantiated. Still under investigation. void (* const m)(Archive &, T &, const unsigned); boost::serialization::extended_type_info * (* e)(); #endif static BOOST_DLLEXPORT const pointer_oserializer & instantiate() BOOST_USED; virtual ~pointer_oserializer(){} }; template<class T, class Archive> BOOST_DLLEXPORT const pointer_oserializer<T, Archive> & pointer_oserializer<T, Archive>::instantiate(){ return instance; } // note: instances of this template to be constructed before the main // is called in order for things to be initialized properly. For this // reason, hiding the instance in a static function as was done above // won't work here so we created a free instance here. template<class T, class Archive> const pointer_oserializer<T, Archive> pointer_oserializer<T, Archive>::instance; template<class T, class Archive> BOOST_DLLEXPORT void pointer_oserializer<T, Archive>::save_object_ptr( basic_oarchive & ar, const void * x ) const { assert(NULL != x); // make sure call is routed through the highest interface that might // be specialized by the user. T * t = static_cast<T *>(const_cast<void *>(x)); const unsigned int file_version = boost::serialization::version<T>::value; Archive & ar_impl = boost::smart_cast_reference<Archive &>(ar); boost::serialization::save_construct_data_adl<Archive, T>( ar_impl, t, file_version ); ar_impl << boost::serialization::make_nvp(NULL, * t); } template<class T, class Archive> #if ! BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) BOOST_DLLEXPORT pointer_oserializer<T, Archive>::pointer_oserializer() : archive_pointer_oserializer<Archive>( * boost::serialization::type_info_implementation<T>::type::get_instance() ), m(boost::serialization::serialize_adl<Archive, T>), e(boost::serialization::type_info_implementation<T>::type::get_instance) #else BOOST_DLLEXPORT pointer_oserializer<T, Archive>::pointer_oserializer() : archive_pointer_oserializer<Archive>( * boost::serialization::type_info_implementation<T>::type::get_instance() ) #endif { // make sure appropriate member function is instantiated oserializer<Archive, T> & bos = oserializer<Archive, T>::instantiate(); bos.set_bpos(this); } template<class Archive, class T> struct save_non_pointer_type { // note this bounces the call right back to the archive // with no runtime overhead struct save_primitive { static void invoke(Archive & ar, const T & t){ save_access::save_primitive(ar, t); } }; // same as above but passes through serialization struct save_only { static void invoke(Archive & ar, const T & t){ // make sure call is routed through the highest interface that might // be specialized by the user. boost::serialization::serialize_adl( ar, const_cast<T &>(t), ::boost::serialization::version<T>::value ); } }; // adds class information to the archive. This includes // serialization level and class version struct save_standard { static void invoke(Archive &ar, const T & t){ ar.save_object(& t, oserializer<Archive, T>::instantiate()); } }; // adds class information to the archive. This includes // serialization level and class version struct save_conditional { static void invoke(Archive &ar, const T &t){ //if(0 == (ar.get_flags() & no_tracking)) save_standard::invoke(ar, t); //else // save_only::invoke(ar, t); } }; typedef BOOST_DEDUCED_TYPENAME mpl::eval_if< // if its primitive mpl::equal_to< boost::serialization::implementation_level<T>, mpl::int_<boost::serialization::primitive_type> >, mpl::identity<save_primitive>, // else BOOST_DEDUCED_TYPENAME mpl::eval_if< // class info / version mpl::greater_equal< boost::serialization::implementation_level<T>, mpl::int_<boost::serialization::object_class_info> >, // do standard save mpl::identity<save_standard>, // else BOOST_DEDUCED_TYPENAME mpl::eval_if< // no tracking mpl::equal_to< boost::serialization::tracking_level<T>, mpl::int_<boost::serialization::track_never> >, // do a fast save mpl::identity<save_only>, // else // do a fast save only tracking is turned off mpl::identity<save_conditional> > > >::type typex; static void invoke(Archive & ar, const T & t){ // check that we're not trying to serialize something that // has been marked not to be serialized. If this your program // traps here, you've tried to serialize a class whose trait // has been marked "non-serializable". Either reset the trait // (see level.hpp) or change program not to serialize items of this class BOOST_STATIC_ASSERT(( mpl::greater_equal< boost::serialization::implementation_level<T>, mpl::int_<boost::serialization::primitive_type> >::value )); typex::invoke(ar, t); }; }; template<class Archive, class TPtr> struct save_pointer_type { template<class T> struct abstract { static const basic_pointer_oserializer * register_type(Archive & /* ar */){ // it has? to be polymorphic BOOST_STATIC_ASSERT( boost::serialization::type_info_implementation<T>::type::is_polymorphic::value ); return static_cast<const basic_pointer_oserializer *>(NULL); } }; template<class T> struct non_abstract { static const basic_pointer_oserializer * register_type(Archive & ar){ return ar.register_type(static_cast<T *>(NULL)); } }; template<class T> static const basic_pointer_oserializer * register_type(Archive &ar, T & /*t*/){ // there should never be any need to save an abstract polymorphic // class pointer. Inhibiting code generation for this // permits abstract base classes to be used - note: exception // virtual serialize functions used for plug-ins typedef BOOST_DEDUCED_TYPENAME mpl::eval_if< serialization::is_abstract<T>, mpl::identity<abstract<T> >, mpl::identity<non_abstract<T> > >::type typex; return typex::register_type(ar); } template<class T> struct non_polymorphic { static void save( Archive &ar, const T & t, const basic_pointer_oserializer * bpos_ptr ){ // save the requested pointer type ar.save_pointer(& t, bpos_ptr); } }; template<class T> struct polymorphic { static void save( Archive &ar, const T & t, const basic_pointer_oserializer * bpos_ptr ){ const boost::serialization::extended_type_info * this_type = boost::serialization::type_info_implementation<T>::type::get_instance(); // retrieve the true type of the object pointed to // if this assertion fails its an error in this library assert(NULL != this_type); const boost::serialization::extended_type_info * true_type = boost::serialization::type_info_implementation<T>::type::get_derived_extended_type_info(t); // note:if this exception is thrown, be sure that derived pointer // is either regsitered or exported. if(NULL == true_type){ boost::throw_exception( archive_exception(archive_exception::unregistered_class) ); } // if its not a pointer to a more derived type const void *vp = static_cast<const void *>(&t); if(*this_type == *true_type){ ar.save_pointer(vp, bpos_ptr); return; } // convert pointer to more derived type. if this is thrown // it means that the base/derived relationship hasn't be registered vp = serialization::void_downcast(*true_type, *this_type, &t); if(NULL == vp){ boost::throw_exception( archive_exception(archive_exception::unregistered_cast) ); } // sice true_type is valid, and this only gets made if the // pointer oserializer object has been created, this should never // fail bpos_ptr = archive_pointer_oserializer<Archive>::find(* true_type); assert(NULL != bpos_ptr); if(NULL == bpos_ptr) boost::throw_exception( archive_exception(archive_exception::unregistered_class) ); ar.save_pointer(vp, bpos_ptr); } }; template<class T> static void save( Archive & ar, const T &t, const basic_pointer_oserializer * bpos_ptr ){ typedef BOOST_DEDUCED_TYPENAME mpl::eval_if< BOOST_DEDUCED_TYPENAME boost::serialization:: type_info_implementation<T>::type::is_polymorphic, mpl::identity<polymorphic<T> >, mpl::identity<non_polymorphic<T> > >::type typey; typey::save(ar, const_cast<T &>(t), bpos_ptr); } template<class T> static void const_check(T & t){ BOOST_STATIC_ASSERT(! boost::is_const<T>::value); } static void invoke(Archive &ar, const TPtr t){ #ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION // if your program traps here, its because you tried to do // something like ar << t where t is a pointer to a const value // void f3(A const* a, text_oarchive& oa) // { // oa << a; // } // with a compiler which doesn't support remove_const // const_check(* t); #else // otherwise remove the const #endif const basic_pointer_oserializer * bpos_ptr = register_type(ar, * t); if(NULL == t){ basic_oarchive & boa = boost::smart_cast_reference<basic_oarchive &>(ar); boa.save_null_pointer(); save_access::end_preamble(ar); return; } save(ar, * t, bpos_ptr); }; }; template<class Archive, class T> struct save_enum_type { static void invoke(Archive &ar, const T &t){ // convert enum to integers on save const int i = static_cast<int>(t); ar << boost::serialization::make_nvp(NULL, i); } }; template<class Archive, class T> struct save_array_type { static void invoke(Archive &ar, const T &t){ save_access::end_preamble(ar); // consider alignment int count = sizeof(t) / ( static_cast<const char *>(static_cast<const void *>(&t[1])) - static_cast<const char *>(static_cast<const void *>(&t[0])) ); ar << BOOST_SERIALIZATION_NVP(count); int i; for(i = 0; i < count; ++i) ar << boost::serialization::make_nvp("item", t[i]); } }; // note bogus arguments to workaround msvc 6 silent runtime failure // declaration to satisfy gcc template<class Archive, class T> BOOST_DLLEXPORT const basic_pointer_oserializer & instantiate_pointer_oserializer( Archive * /* ar = NULL */, T * /* t = NULL */ ) BOOST_USED ; // definition template<class Archive, class T> BOOST_DLLEXPORT const basic_pointer_oserializer & instantiate_pointer_oserializer( Archive * /* ar = NULL */, T * /* t = NULL */ ){ // note: reversal of order of arguments to work around msvc 6.0 bug // that manifests itself while trying to link. return pointer_oserializer<T, Archive>::instantiate(); } } // detail template<class Archive, class T> inline void save(Archive & ar, const T &t){ typedef BOOST_DEDUCED_TYPENAME mpl::eval_if<is_pointer<T>, mpl::identity<detail::save_pointer_type<Archive, T> >, //else BOOST_DEDUCED_TYPENAME mpl::eval_if<is_enum<T>, mpl::identity<detail::save_enum_type<Archive, T> >, //else BOOST_DEDUCED_TYPENAME mpl::eval_if<is_array<T>, mpl::identity<detail::save_array_type<Archive, T> >, //else mpl::identity<detail::save_non_pointer_type<Archive, T> > > > >::type typex; typex::invoke(ar, t); } #ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING template<class T> struct check_tracking { typedef BOOST_DEDUCED_TYPENAME mpl::if_< // if its never tracked. BOOST_DEDUCED_TYPENAME mpl::equal_to< serialization::tracking_level<T>, mpl::int_<serialization::track_never> >, // it better not be a pointer mpl::not_<is_pointer<T> >, //else // otherwise if it might be tracked. So there shouldn't // be any problem making a const is_const<T> >::type typex; BOOST_STATIC_CONSTANT(bool, value = typex::value); }; template<class Archive, class T> inline void save(Archive & ar, T &t){ // if your program traps here, it indicates taht your doing one of the following: // a) serializing an object of a type marked "track_never" through a pointer. // b) saving an non-const object of a type not markd "track_never) // Either of these conditions may be an indicator of an error usage of the // serialization library and should be double checked. See documentation on // object tracking. BOOST_STATIC_ASSERT(check_tracking<T>::value); save(ar, const_cast<const T &>(t)); } #endif } // namespace archive } // namespace boost #endif // BOOST_ARCHIVE_OSERIALIZER_HPP
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 574 ] ] ]
9b684e873e8beef5dd24adfb4416fd188bc5a338
da49fe5fb9fc91dba1f0236411de3021e1e25348
/InfluenceMap.h
657aee12374bdc69712f1ca93264ea247e2c59df
[]
no_license
imbaczek/baczek-kpai
7f84d83ba395c2e5b5d85c10c14072049b4830ab
4291ec37f49fc8cb4a643133ed5f3024264e1e27
refs/heads/master
2020-03-28T19:13:42.841144
2009-10-29T21:39:02
2009-10-29T21:39:02
151,447
1
0
null
null
null
null
UTF-8
C++
false
false
1,835
h
#pragma once #include <map> #include <string> #include <vector> #include "float3.h" class BaczekKPAI; class InfluenceMap { protected: BaczekKPAI* ai; int lastMinimaFrame; //<? for caching purposes std::vector<int> minimaCachedValues; std::vector<float3> minimaCachedPositions; // partial updates size_t alliedProgress, enemyProgress; bool updateInProgress; bool enemiesDone; std::vector<int> friends, enemies; public: InfluenceMap(BaczekKPAI* ai, std::string); ~InfluenceMap(); static const int influence_size_divisor = 8; std::string configName; struct UnitData { std::string name; int max_value; int min_value; int radius; }; typedef std::map<std::string, UnitData> unit_value_map_t; unit_value_map_t unit_map; int mapw, maph; float scalex, scaley; typedef std::vector<std::vector<int> > map_t; map_t map; map_t workMap; /* reads a config file in a format like { "kernel": { "max": 5, "min": 0, "radius": 10 } } */ bool ReadJSONConfig(); static void WriteDefaultJSONConfig(std::string configName); int GetAtXY(int x, int y); void UpdateAll(const std::vector<int>& friends, const std::vector<int>& enemies); void Update(const std::vector<int>& friends, const std::vector<int>& enemies); void StartPartialUpdate(const std::vector<int>& friends, const std::vector<int>& enemies); void FinishPartialUpdate(); bool IsUpdateInProgress() { return updateInProgress; } bool UpdatePartial(bool allied, const std::vector<int>& uids); void UpdateSingleUnit(int uid, int sign, map_t& themap); void FindLocalMinima(float radius, std::vector<int>& values, std::vector<float3>& positions); void FindLocalMinNear(float3 point, float3& retpoint, int& retval); };
[ [ [ 1, 85 ] ] ]
13d83158b9422c1bf6845b4779388a722f0e37ff
5e6ff9e6e8427078135a7b4d3b194bcbf631e9cd
/EngineSource/dpslim/dpslim/stdafx.h
b9764e95d23e4201789e9ed543849ec49c8b19bb
[]
no_license
karakots/dpresurrection
1a6f3fca00edd24455f1c8ae50764142bb4106e7
46725077006571cec1511f31d314ccd7f5a5eeef
refs/heads/master
2016-09-05T09:26:26.091623
2010-02-01T11:24:41
2010-02-01T11:24:41
32,189,181
0
0
null
null
null
null
UTF-8
C++
false
false
548
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once //STL #include <vector> #include <map> #include <set> #include <string> #include <hash_map> //ATL #include <afxdb.h> //Standard Includes #include <stdlib.h> #include <fstream> #include <math.h> //MAIN DP INCLUDES #include "CMicroSegment.h" #include "MSDatabase.h" #include "microsegmentconst.h" using namespace std; using namespace stdext;
[ "Isaac.Noble@fd82578e-0ebe-11df-96d9-85c6b80b8d9c" ]
[ [ [ 1, 29 ] ] ]
4c0ad32571590b4377b7adaaf9f38fa4341ef2ea
14bc620a0365e83444dad45611381c7f6bcd052b
/ITUEngine/Abstractions/Time.hpp
01a64c6f8cad7b1b1d824e996edad130bc049252
[]
no_license
jumoel/itu-gameengine
a5750bfdf391ae64407217bfc1df8b2a3db551c7
062dd47bc1be0f39a0add8615e81361bcaa2bd4c
refs/heads/master
2020-05-03T20:39:31.307460
2011-12-19T10:54:10
2011-12-19T10:54:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
198
hpp
#ifndef ITUENGINE_TIME_H #define ITUENGINE_TIME_H #include <SDL.h> #include <stdint.h> class Time { public: static uint32_t GetCurrentMS() { return SDL_GetTicks(); } }; #endif
[ [ [ 1, 4 ], [ 6, 9 ], [ 11, 16 ] ], [ [ 5, 5 ], [ 10, 10 ] ] ]
39259228a129b25482cf9d533f9a580f2c0d1423
44630c205ee4e9044fcda5557b2d2243d26d6fa7
/as_sublight/source/avisynth.h
d587cb23f62a384cba564f993d7414999b6fde11
[]
no_license
pavelkryukov/avs-sublight
e0ca829b92531593b130bc852f288c8694a8bc5b
94a35a65493313ecbbd67b27da31c9f821e8e2fa
refs/heads/master
2020-05-17T05:51:03.542819
2011-11-26T15:13:11
2011-11-26T15:13:11
32,185,889
1
0
null
null
null
null
UTF-8
C++
false
false
27,809
h
// Avisynth v2.5. Copyright 2002 Ben Rudiak-Gould et al. // http://www.avisynth.org // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making a // combined work based on Avisynth. Thus, the terms and conditions of the GNU // General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate with // Avisynth solely through the interfaces defined in avisynth.h, regardless of the license // terms of these independent modules, and to copy and distribute the // resulting combined work under terms of your choice, provided that // every copy of the combined work is accompanied by a complete copy of // the source code of Avisynth (the version of Avisynth used to produce the // combined work), being distributed under the terms of the GNU General // Public License plus this exception. An independent module is a module // which is not derived from or based on Avisynth, such as 3rd-party filters, // import and export plugins, or graphical user interfaces. #ifndef __AVISYNTH_H__ #define __AVISYNTH_H__ enum { AVISYNTH_INTERFACE_VERSION = 3 }; /* Define all types necessary for interfacing with avisynth.dll Moved from internal.h */ // Win32 API macros, notably the types BYTE, DWORD, ULONG, etc. #include <windef.h> // COM interface macros #include <objbase.h> // Raster types used by VirtualDub & Avisynth #define in64 (__int64)(unsigned short) typedef unsigned long Pixel; // this will break on 64-bit machines! typedef unsigned long Pixel32; typedef unsigned char Pixel8; typedef long PixCoord; typedef long PixDim; typedef long PixOffset; /* Compiler-specific crap */ // Tell MSVC to stop precompiling here #ifdef _MSC_VER #pragma hdrstop #endif // Set up debugging macros for MS compilers; for others, step down to the // standard <assert.h> interface #ifdef _MSC_VER #include <crtdbg.h> #else #define _RPT0(a,b) ((void)0) #define _RPT1(a,b,c) ((void)0) #define _RPT2(a,b,c,d) ((void)0) #define _RPT3(a,b,c,d,e) ((void)0) #define _RPT4(a,b,c,d,e,f) ((void)0) #define _ASSERTE(x) assert(x) #include <assert.h> #endif // I had problems with Premiere wanting 1-byte alignment for its structures, // so I now set the Avisynth struct alignment explicitly here. #pragma pack(push,8) #define FRAME_ALIGN 16 // Default frame alignment is 16 bytes, to help P4, when using SSE2 // The VideoInfo struct holds global information about a clip (i.e. // information that does not depend on the frame number). The GetVideoInfo // method in IClip returns this struct. // Audio Sample information typedef float SFLOAT; enum { SAMPLE_INT8 = 1 << 0, SAMPLE_INT16 = 1 << 1, SAMPLE_INT24 = 1 << 2, // Int24 is a very stupid thing to code, but it's supported by some hardware. SAMPLE_INT32 = 1 << 3, SAMPLE_FLOAT = 1 << 4 }; enum { PLANAR_Y = 1 << 0, PLANAR_U = 1 << 1, PLANAR_V = 1 << 2, PLANAR_ALIGNED = 1 << 3, PLANAR_Y_ALIGNED = PLANAR_Y | PLANAR_ALIGNED, PLANAR_U_ALIGNED = PLANAR_U | PLANAR_ALIGNED, PLANAR_V_ALIGNED = PLANAR_V | PLANAR_ALIGNED, }; class AvisynthError /* exception */ { public: const char* const msg; AvisynthError(const char* _msg) : msg(_msg) { } }; struct VideoInfo { int width, height; // width=0 means no video unsigned fps_numerator, fps_denominator; int num_frames; // This is more extensible than previous versions. More properties can be added seeminglesly. // Colorspace properties. enum { CS_BGR = 1 << 28, CS_YUV = 1 << 29, CS_INTERLEAVED = 1 << 30, CS_PLANAR = 1 << 31 }; // Specific colorformats enum { CS_UNKNOWN = 0, CS_BGR24 = 1 << 0 | CS_BGR | CS_INTERLEAVED, CS_BGR32 = 1 << 1 | CS_BGR | CS_INTERLEAVED, CS_YUY2 = 1 << 2 | CS_YUV | CS_INTERLEAVED, CS_YV12 = 1 << 3 | CS_YUV | CS_PLANAR, // y-v-u, 4:2:0 planar CS_I420 = 1 << 4 | CS_YUV | CS_PLANAR, // y-u-v, 4:2:0 planar CS_IYUV = 1 << 4 | CS_YUV | CS_PLANAR, // same as above }; int pixel_type; // changed to int as of 2.5 int audio_samples_per_second; // 0 means no audio int sample_type; // as of 2.5 __int64 num_audio_samples; // changed as of 2.5 int nchannels; // as of 2.5 // Imagetype properties int image_type; enum { IT_BFF = 1 << 0, IT_TFF = 1 << 1, IT_FIELDBASED = 1 << 2 }; // useful functions of the above bool HasVideo() const { return (width != 0); } bool HasAudio() const { return (audio_samples_per_second != 0); } bool IsRGB() const { return !!(pixel_type & CS_BGR); } bool IsRGB24() const { return (pixel_type & CS_BGR24) == CS_BGR24; } // Clear out additional properties bool IsRGB32() const { return (pixel_type & CS_BGR32) == CS_BGR32 ; } bool IsYUV() const { return !!(pixel_type&CS_YUV ); } bool IsYUY2() const { return (pixel_type & CS_YUY2) == CS_YUY2; } bool IsYV12() const { return ((pixel_type & CS_YV12) == CS_YV12)||((pixel_type & CS_I420) == CS_I420); } bool IsColorSpace(int c_space) const { return ((pixel_type & c_space) == c_space); } bool Is(int property) const { return ((pixel_type & property)==property ); } bool IsPlanar() const { return !!(pixel_type & CS_PLANAR); } bool IsFieldBased() const { return !!(image_type & IT_FIELDBASED); } bool IsParityKnown() const { return ((image_type & IT_FIELDBASED)&&(image_type & (IT_BFF|IT_TFF))); } bool IsBFF() const { return !!(image_type & IT_BFF); } bool IsTFF() const { return !!(image_type & IT_TFF); } bool IsVPlaneFirst() const {return ((pixel_type & CS_YV12) == CS_YV12); } // Don't use this int BytesFromPixels(int pixels) const { return pixels * (BitsPerPixel()>>3); } // Will not work on planar images, but will return only luma planes int RowSize() const { return BytesFromPixels(width); } // Also only returns first plane on planar images int BMPSize() const { if (IsPlanar()) {int p = height * ((RowSize()+3) & ~3); p+=p>>1; return p; } return height * ((RowSize()+3) & ~3); } __int64 AudioSamplesFromFrames(__int64 frames) const { return (fps_numerator && HasVideo()) ? ((__int64)(frames) * audio_samples_per_second * fps_denominator / fps_numerator) : 0; } int FramesFromAudioSamples(__int64 samples) const { return (fps_denominator && HasAudio()) ? (int)((samples * (__int64)fps_numerator)/((__int64)fps_denominator * (__int64)audio_samples_per_second)) : 0; } __int64 AudioSamplesFromBytes(__int64 bytes) const { return HasAudio() ? bytes / BytesPerAudioSample() : 0; } __int64 BytesFromAudioSamples(__int64 samples) const { return samples * BytesPerAudioSample(); } int AudioChannels() const { return HasAudio() ? nchannels : 0; } int SampleType() const{ return sample_type;} bool IsSampleType(int testtype) const{ return !!(sample_type&testtype);} int SamplesPerSecond() const { return audio_samples_per_second; } int BytesPerAudioSample() const { return nchannels*BytesPerChannelSample();} void SetFieldBased(bool isfieldbased) { if (isfieldbased) image_type|=IT_FIELDBASED; else image_type&=~IT_FIELDBASED; } void Set(int property) { image_type|=property; } void Clear(int property) { image_type&=~property; } int BitsPerPixel() const { switch (pixel_type) { case CS_BGR24: return 24; case CS_BGR32: return 32; case CS_YUY2: return 16; case CS_YV12: case CS_I420: return 12; default: return 0; } } int BytesPerChannelSample() const { switch (sample_type) { case SAMPLE_INT8: return sizeof(signed char); case SAMPLE_INT16: return sizeof(signed short); case SAMPLE_INT24: return 3; case SAMPLE_INT32: return sizeof(signed int); case SAMPLE_FLOAT: return sizeof(SFLOAT); default: _ASSERTE("Sample type not recognized!"); return 0; } } // useful mutator void SetFPS(unsigned numerator, unsigned denominator) { if ((numerator == 0) || (denominator == 0)) { fps_numerator = 0; fps_denominator = 1; } else { unsigned x=numerator, y=denominator; while (y) { // find gcd unsigned t = x%y; x = y; y = t; } fps_numerator = numerator/x; fps_denominator = denominator/x; } } // Range protected multiply-divide of FPS void MulDivFPS(unsigned multiplier, unsigned divisor) { unsigned __int64 numerator = UInt32x32To64(fps_numerator, multiplier); unsigned __int64 denominator = UInt32x32To64(fps_denominator, divisor); unsigned __int64 x=numerator, y=denominator; while (y) { // find gcd unsigned __int64 t = x%y; x = y; y = t; } numerator /= x; // normalize denominator /= x; unsigned __int64 temp = numerator | denominator; // Just looking top bit unsigned u = 0; while (temp & 0xffffffff80000000) { // or perhaps > 16777216*2 temp = Int64ShrlMod32(temp, 1); u++; } if (u) { // Scale to fit const unsigned round = 1 << (u-1); SetFPS( (unsigned)Int64ShrlMod32(numerator + round, u), (unsigned)Int64ShrlMod32(denominator + round, u) ); } else { fps_numerator = (unsigned)numerator; fps_denominator = (unsigned)denominator; } } // Test for same colorspace bool IsSameColorspace(const VideoInfo& vi) const { if (vi.pixel_type == pixel_type) return TRUE; if (IsYV12() && vi.IsYV12()) return TRUE; return FALSE; } }; // VideoFrameBuffer holds information about a memory block which is used // for video data. For efficiency, instances of this class are not deleted // when the refcount reaches zero; instead they're stored in a linked list // to be reused. The instances are deleted when the corresponding AVS // file is closed. class VideoFrameBuffer { BYTE* const data; const int data_size; // sequence_number is incremented every time the buffer is changed, so // that stale views can tell they're no longer valid. long sequence_number; friend class VideoFrame; friend class Cache; friend class ScriptEnvironment; long refcount; public: VideoFrameBuffer(int size); VideoFrameBuffer(); ~VideoFrameBuffer(); const BYTE* GetReadPtr() const { return data; } BYTE* GetWritePtr() { ++sequence_number; return data; } int GetDataSize() { return data_size; } int GetSequenceNumber() { return sequence_number; } int GetRefcount() { return refcount; } }; class IClip; class PClip; class PVideoFrame; class IScriptEnvironment; class AVSValue; // VideoFrame holds a "window" into a VideoFrameBuffer. Operator new // is overloaded to recycle class instances. class VideoFrame { int refcount; VideoFrameBuffer* const vfb; const int offset, pitch, row_size, height, offsetU, offsetV, pitchUV; // U&V offsets are from top of picture. friend class PVideoFrame; void AddRef() { InterlockedIncrement((long *)&refcount); } void Release() { if (refcount==1) InterlockedDecrement(&vfb->refcount); InterlockedDecrement((long *)&refcount); } friend class ScriptEnvironment; friend class Cache; VideoFrame(VideoFrameBuffer* _vfb, int _offset, int _pitch, int _row_size, int _height); VideoFrame(VideoFrameBuffer* _vfb, int _offset, int _pitch, int _row_size, int _height, int _offsetU, int _offsetV, int _pitchUV); void* operator new(unsigned size); // TESTME: OFFSET U/V may be switched to what could be expected from AVI standard! public: int GetPitch() const { return pitch; } int GetPitch(int plane) const { switch (plane) {case PLANAR_U: case PLANAR_V: return pitchUV;} return pitch; } int GetRowSize() const { return row_size; } int GetRowSize(int plane) const { switch (plane) { case PLANAR_U: case PLANAR_V: if (pitchUV) return row_size>>1; else return 0; case PLANAR_U_ALIGNED: case PLANAR_V_ALIGNED: if (pitchUV) { int r = ((row_size+FRAME_ALIGN-1)&(~(FRAME_ALIGN-1)) )>>1; // Aligned rowsize if (r<=pitchUV) return r; return row_size>>1; } else return 0; case PLANAR_Y_ALIGNED: int r = (row_size+FRAME_ALIGN-1)&(~(FRAME_ALIGN-1)); // Aligned rowsize if (r<=pitch) return r; return row_size; } return row_size; } int GetHeight() const { return height; } int GetHeight(int plane) const { switch (plane) {case PLANAR_U: case PLANAR_V: if (pitchUV) return height>>1; return 0;} return height; } // generally you shouldn't use these three VideoFrameBuffer* GetFrameBuffer() const { return vfb; } int GetOffset() const { return offset; } int GetOffset(int plane) const { switch (plane) {case PLANAR_U: return offsetU;case PLANAR_V: return offsetV;default: return offset;}; } // in plugins use env->SubFrame() VideoFrame* Subframe(int rel_offset, int new_pitch, int new_row_size, int new_height) const; VideoFrame* Subframe(int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int pitchUV) const; const BYTE* GetReadPtr() const { return vfb->GetReadPtr() + offset; } const BYTE* GetReadPtr(int plane) const { return vfb->GetReadPtr() + GetOffset(plane); } bool IsWritable() const { return (refcount == 1 && vfb->refcount == 1); } BYTE* GetWritePtr() const { if (vfb->GetRefcount()>1) { _ASSERTE(FALSE); //throw AvisynthError("Internal Error - refcount was more than one!"); } return IsWritable() ? (vfb->GetWritePtr() + offset) : 0; } BYTE* GetWritePtr(int plane) const { if (plane==PLANAR_Y) { if (vfb->GetRefcount()>1) { _ASSERTE(FALSE); // throw AvisynthError("Internal Error - refcount was more than one!"); } return IsWritable() ? vfb->GetWritePtr() + GetOffset(plane) : 0; } return vfb->data + GetOffset(plane); } ~VideoFrame() { InterlockedDecrement(&vfb->refcount); } }; enum { CACHE_NOTHING=0, CACHE_RANGE=1, CACHE_ALL=2, CACHE_AUDIO=3, CACHE_AUDIO_NONE=4, CACHE_AUDIO_AUTO=5 }; // Base class for all filters. class IClip { friend class PClip; friend class AVSValue; int refcnt; void AddRef() { InterlockedIncrement((long *)&refcnt); } void Release() { InterlockedDecrement((long *)&refcnt); if (!refcnt) delete this; } public: IClip() : refcnt(0) {} virtual int __stdcall GetVersion() { return AVISYNTH_INTERFACE_VERSION; } virtual PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment* env) = 0; virtual bool __stdcall GetParity(int n) = 0; // return field parity if field_based, else parity of first field in frame virtual void __stdcall GetAudio(void* buf, __int64 start, __int64 count, IScriptEnvironment* env) = 0; // start and count are in samples virtual void __stdcall SetCacheHints(int cachehints,int frame_range) = 0 ; // We do not pass cache requests upwards, only to the next filter. virtual const VideoInfo& __stdcall GetVideoInfo() = 0; virtual __stdcall ~IClip() {} }; // smart pointer to IClip class PClip { IClip* p; IClip* GetPointerWithAddRef() const { if (p) p->AddRef(); return p; } friend class AVSValue; friend class VideoFrame; void Init(IClip* x) { if (x) x->AddRef(); p=x; } void Set(IClip* x) { if (x) x->AddRef(); if (p) p->Release(); p=x; } public: PClip() { p = 0; } PClip(const PClip& x) { Init(x.p); } PClip(IClip* x) { Init(x); } void operator=(IClip* x) { Set(x); } void operator=(const PClip& x) { Set(x.p); } IClip* operator->() const { return p; } // useful in conditional expressions operator void*() const { return p; } bool operator!() const { return !p; } ~PClip() { if (p) p->Release(); } }; // smart pointer to VideoFrame class PVideoFrame { VideoFrame* p; void Init(VideoFrame* x) { if (x) x->AddRef(); p=x; } void Set(VideoFrame* x) { if (x) x->AddRef(); if (p) p->Release(); p=x; } public: PVideoFrame() { p = 0; } PVideoFrame(const PVideoFrame& x) { Init(x.p); } PVideoFrame(VideoFrame* x) { Init(x); } void operator=(VideoFrame* x) { Set(x); } void operator=(const PVideoFrame& x) { Set(x.p); } VideoFrame* operator->() const { return p; } // for conditional expressions operator void*() const { return p; } bool operator!() const { return !p; } ~PVideoFrame() { if (p) p->Release();} }; class AVSValue { public: AVSValue() { type = 'v'; } AVSValue(IClip* c) { type = 'c'; clip = c; if (c) c->AddRef(); } AVSValue(const PClip& c) { type = 'c'; clip = c.GetPointerWithAddRef(); } AVSValue(bool b) { type = 'b'; boolean = b; } AVSValue(int i) { type = 'i'; integer = i; } // AVSValue(__int64 l) { type = 'l'; longlong = l; } AVSValue(float f) { type = 'f'; floating_pt = f; } AVSValue(double f) { type = 'f'; floating_pt = float(f); } AVSValue(const char* s) { type = 's'; string = s; } AVSValue(const AVSValue* a, int size) { type = 'a'; array = a; array_size = size; } AVSValue(const AVSValue& v) { Assign(&v, true); } ~AVSValue() { if (IsClip() && clip) clip->Release(); } AVSValue& operator=(const AVSValue& v) { Assign(&v, false); return *this; } // Note that we transparently allow 'int' to be treated as 'float'. // There are no int<->bool conversions, though. bool Defined() const { return type != 'v'; } bool IsClip() const { return type == 'c'; } bool IsBool() const { return type == 'b'; } bool IsInt() const { return type == 'i'; } // bool IsLong() const { return (type == 'l'|| type == 'i'); } bool IsFloat() const { return type == 'f' || type == 'i'; } bool IsString() const { return type == 's'; } bool IsArray() const { return type == 'a'; } PClip AsClip() const { _ASSERTE(IsClip()); return IsClip()?clip:0; } bool AsBool() const { _ASSERTE(IsBool()); return boolean; } int AsInt() const { _ASSERTE(IsInt()); return integer; } // int AsLong() const { _ASSERTE(IsLong()); return longlong; } const char* AsString() const { _ASSERTE(IsString()); return IsString()?string:0; } double AsFloat() const { _ASSERTE(IsFloat()); return IsInt()?integer:floating_pt; } bool AsBool(bool def) const { _ASSERTE(IsBool()||!Defined()); return IsBool() ? boolean : def; } int AsInt(int def) const { _ASSERTE(IsInt()||!Defined()); return IsInt() ? integer : def; } double AsFloat(double def) const { _ASSERTE(IsFloat()||!Defined()); return IsInt() ? integer : type=='f' ? floating_pt : def; } const char* AsString(const char* def) const { _ASSERTE(IsString()||!Defined()); return IsString() ? string : def; } int ArraySize() const { _ASSERTE(IsArray()); return IsArray()?array_size:1; } const AVSValue& operator[](int index) const { _ASSERTE(IsArray() && index>=0 && index<array_size); return (IsArray() && index>=0 && index<array_size) ? array[index] : *this; } private: short type; // 'a'rray, 'c'lip, 'b'ool, 'i'nt, 'f'loat, 's'tring, 'v'oid, or 'l'ong short array_size; union { IClip* clip; bool boolean; int integer; float floating_pt; const char* string; const AVSValue* array; // __int64 longlong; }; void Assign(const AVSValue* src, bool init) { if (src->IsClip() && src->clip) src->clip->AddRef(); if (!init && IsClip() && clip) clip->Release(); // make sure this copies the whole struct! ((__int32*)this)[0] = ((__int32*)src)[0]; ((__int32*)this)[1] = ((__int32*)src)[1]; } }; // instantiable null filter class GenericVideoFilter : public IClip { protected: PClip child; VideoInfo vi; public: GenericVideoFilter(PClip _child) : child(_child) { vi = child->GetVideoInfo(); } PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment* env) { return child->GetFrame(n, env); } void __stdcall GetAudio(void* buf, __int64 start, __int64 count, IScriptEnvironment* env) { child->GetAudio(buf, start, count, env); } const VideoInfo& __stdcall GetVideoInfo() { return vi; } bool __stdcall GetParity(int n) { return child->GetParity(n); } void __stdcall SetCacheHints(int cachehints,int frame_range) { } ; // We do not pass cache requests upwards, only to the next filter. virtual __stdcall ~GenericVideoFilter() {} }; /* Helper classes useful to plugin authors */ class AlignPlanar : public GenericVideoFilter { public: AlignPlanar(PClip _clip); static PClip Create(PClip clip); PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment* env); virtual __stdcall ~AlignPlanar() {} }; class FillBorder : public GenericVideoFilter { public: FillBorder(PClip _clip); static PClip Create(PClip clip); PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment* env); virtual __stdcall ~FillBorder() {} }; class ConvertAudio : public GenericVideoFilter /** * Helper class to convert audio to any format **/ { public: ConvertAudio(PClip _clip, int prefered_format); void __stdcall GetAudio(void* buf, __int64 start, __int64 count, IScriptEnvironment* env); void __stdcall SetCacheHints(int cachehints,int frame_range); // We do pass cache requests upwards, to the cache! static PClip Create(PClip clip, int sample_type, int prefered_type); static AVSValue __cdecl Create_float(AVSValue args, void*, IScriptEnvironment*); static AVSValue __cdecl Create_32bit(AVSValue args, void*, IScriptEnvironment*); static AVSValue __cdecl Create_24bit(AVSValue args, void*, IScriptEnvironment*); static AVSValue __cdecl Create_16bit(AVSValue args, void*, IScriptEnvironment*); static AVSValue __cdecl Create_8bit (AVSValue args, void*, IScriptEnvironment*); static AVSValue __cdecl Create_Any (AVSValue args, void*, IScriptEnvironment*); virtual _stdcall ~ConvertAudio(); private: void convertToFloat(char* inbuf, float* outbuf, char sample_type, int count); void convertToFloat_3DN(char* inbuf, float* outbuf, char sample_type, int count); void convertToFloat_SSE(char* inbuf, float* outbuf, char sample_type, int count); void convertToFloat_SSE2(char* inbuf, float* outbuf, char sample_type, int count); void convertFromFloat(float* inbuf, void* outbuf, char sample_type, int count); void convertFromFloat_3DN(float* inbuf, void* outbuf, char sample_type, int count); void convertFromFloat_SSE(float* inbuf, void* outbuf, char sample_type, int count); void convertFromFloat_SSE2(float* inbuf, void* outbuf, char sample_type, int count); __inline int Saturate_int8(float n); __inline short Saturate_int16(float n); __inline int Saturate_int24(float n); __inline int Saturate_int32(float n); char src_format; char dst_format; int src_bps; char *tempbuffer; SFLOAT *floatbuffer; int tempbuffer_size; }; // For GetCPUFlags. These are backwards-compatible with those in VirtualDub. enum { /* slowest CPU to support extension */ CPUF_FORCE = 0x01, // N/A CPUF_FPU = 0x02, // 386/486DX CPUF_MMX = 0x04, // P55C, K6, PII CPUF_INTEGER_SSE = 0x08, // PIII, Athlon CPUF_SSE = 0x10, // PIII, Athlon XP/MP CPUF_SSE2 = 0x20, // PIV, Hammer CPUF_3DNOW = 0x40, // K6-2 CPUF_3DNOW_EXT = 0x80, // Athlon CPUF_X86_64 = 0xA0, // Hammer (note: equiv. to 3DNow + SSE2, which // only Hammer will have anyway) CPUF_SSE3 = 0x100, // PIV+, Hammer }; #define MAX_INT 0x7fffffff #define MIN_INT -0x7fffffff // ::FIXME:: research why this is not 0x80000000 class IScriptEnvironment { public: virtual __stdcall ~IScriptEnvironment() {} virtual /*static*/ long __stdcall GetCPUFlags() = 0; virtual char* __stdcall SaveString(const char* s, int length = -1) = 0; virtual char* __stdcall Sprintf(const char* fmt, ...) = 0; // note: val is really a va_list; I hope everyone typedefs va_list to a pointer virtual char* __stdcall VSprintf(const char* fmt, void* val) = 0; __declspec(noreturn) virtual void __stdcall ThrowError(const char* fmt, ...) = 0; class NotFound /*exception*/ {}; // thrown by Invoke and GetVar typedef AVSValue (__cdecl *ApplyFunc)(AVSValue args, void* user_data, IScriptEnvironment* env); virtual void __stdcall AddFunction(const char* name, const char* params, ApplyFunc apply, void* user_data) = 0; virtual bool __stdcall FunctionExists(const char* name) = 0; virtual AVSValue __stdcall Invoke(const char* name, const AVSValue args, const char** arg_names=0) = 0; virtual AVSValue __stdcall GetVar(const char* name) = 0; virtual bool __stdcall SetVar(const char* name, const AVSValue& val) = 0; virtual bool __stdcall SetGlobalVar(const char* name, const AVSValue& val) = 0; virtual void __stdcall PushContext(int level=0) = 0; virtual void __stdcall PopContext() = 0; // align should be 4 or 8 virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi, int align=FRAME_ALIGN) = 0; virtual bool __stdcall MakeWritable(PVideoFrame* pvf) = 0; virtual /*static*/ void __stdcall BitBlt(BYTE* dstp, int dst_pitch, const BYTE* srcp, int src_pitch, int row_size, int height) = 0; typedef void (__cdecl *ShutdownFunc)(void* user_data, IScriptEnvironment* env); virtual void __stdcall AtExit(ShutdownFunc function, void* user_data) = 0; virtual void __stdcall CheckVersion(int version = AVISYNTH_INTERFACE_VERSION) = 0; virtual PVideoFrame __stdcall Subframe(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height) = 0; virtual int __stdcall SetMemoryMax(int mem) = 0; virtual int __stdcall SetWorkingDir(const char * newdir) = 0; virtual void* __stdcall ManageCache(int key, void* data) = 0; enum PlanarChromaAlignmentMode { PlanarChromaAlignmentOff, PlanarChromaAlignmentOn, PlanarChromaAlignmentTest }; virtual bool __stdcall PlanarChromaAlignment(PlanarChromaAlignmentMode key) = 0; virtual PVideoFrame __stdcall SubframePlanar(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV) = 0; }; // avisynth.dll exports this; it's a way to use it as a library, without // writing an AVS script or without going through AVIFile. IScriptEnvironment* __stdcall CreateScriptEnvironment(int version = AVISYNTH_INTERFACE_VERSION); #pragma pack(pop) #endif //__AVISYNTH_H__
[ [ [ 1, 781 ] ] ]
6a33e111f60c7a529ffef00021f7e6c960aa5e3d
960a896c95a759a41a957d0e7dbd809b5929c999
/Editor/headers.hpp
726e22ad33bb57bb66c64b07353573c513dd89ef
[]
no_license
WSPSNIPER/dangerwave
8cbd67a02eb45563414eaf9ecec779cc1a7f09d5
51af1171880104aa823f6ef8795a2f0b85b460d8
refs/heads/master
2016-08-12T09:50:00.996204
2010-08-24T22:55:52
2010-08-24T22:55:52
48,472,531
0
0
null
null
null
null
UTF-8
C++
false
false
207
hpp
#include<iostream> #include<fstream> #include<string> #include<cstdlib> #include<vector> #include<SFML/System.hpp> #include<SFML/Graphics.hpp> #include<SFML/Window.hpp> using namespace std;
[ "michaelbond2008@e78017d1-81bd-e181-eab4-ba4b7880cff6" ]
[ [ [ 1, 13 ] ] ]
53ad42de094b755bf5cc272da24ee3231a712558
a70580f8b567d0d21cbb3d863e3716961af53a65
/afd.h
bff5920a39c064bd2999286f0109a18b31071a54
[]
no_license
samuel-hcl/analisador-lexico-pascal
7db211ea33ebe2928899d630ec3ceb3fe895b29a
a661c0f337dff5ad6aca6b3593b584607a87ca3d
refs/heads/master
2020-08-06T17:02:14.025312
2010-04-30T02:35:54
2010-04-30T02:35:54
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,937
h
#include <iostream> #include <fstream> #include <string> #include <ctype.h> using namespace std; class AFD { public: AFD(); ofstream fout("output.txt"); private: FILE *sourcefile; //ponteiro do arquivo com o código fonte char filename[256]; //nome do arquivo bool abrearquivo(); //função que abre o arquivo e carrega o conteúdo para análise string sourcecode; //string onde é armazenado o código string buffertoken; //string onde é armazenado o token que está sendo analisado int si; //índice do caractere atual int codeline; //linha do código //Estados do autômato void EstadoInicial(char x); int Estado2(char x); int Estado3(char x); int Estado4(char x); int Estado5(char x); int Estado6(char x); int Estado7(char x); int Estado8(char x); int Estado9(char x); int Estado10(char x); int Estado11(char x); int Estado12(char x); int Estado13(char x); int Estado14(char x); int Estado15(char x); int Estado16(char x); int Estado17(char x); int Estado18(char x); int Estado19(char x); int Estado20(char x); int Estado21(char x); int Estado22(char x); int Estado23(char x); int Estado24(char x); bool Estado2loop(char x); bool PalavraReservada(); bool erroEstado3loop(char x); int erroEstado3(char x); void comentPAR(); void comentCHAVE(); //output void output(int code); };
[ "[email protected]@9dfcc0cf-42e3-9a8f-187f-b076de1ed97d" ]
[ [ [ 1, 60 ] ] ]
5671449f3819970f31ff0fcb692c5a4e41a4eabe
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/uploader/uploadergadgetwidget.cpp
f12b12a2240cd47a801f13c4d0ae7f6f73e149ee
[]
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,430
cpp
/** ****************************************************************************** * * @file uploadergadgetwidget.cpp * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup YModemUploader YModem Serial Uploader Plugin * @{ * @brief The YModem protocol serial uploader plugin *****************************************************************************/ /* * 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 "uploadergadgetwidget.h" UploaderGadgetWidget::UploaderGadgetWidget(QWidget *parent) : QWidget(parent) { setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); //main layout QVBoxLayout *layout = new QVBoxLayout; //choose file layout and widget QHBoxLayout *FileLayout = new QHBoxLayout; QWidget *FileWidget = new QWidget; FileWidget->setLayout(FileLayout); openFileNameLE=new QLineEdit(); QPushButton* loadfile = new QPushButton("Load File"); loadfile->setMaximumWidth(80); FileLayout->addWidget(openFileNameLE); FileLayout->addWidget(loadfile); //send file layout and widget QHBoxLayout *SendLayout = new QHBoxLayout; QWidget *SendWidget = new QWidget; SendWidget->setLayout(SendLayout); progressBar=new QProgressBar(); progressBar->setMaximum(100); QPushButton* sendBt = new QPushButton("Send"); sendBt->setMaximumWidth(80); SendLayout->addWidget(progressBar); SendLayout->addWidget(sendBt); //status layout and widget QHBoxLayout *StatusLayout = new QHBoxLayout; QWidget *StatusWidget = new QWidget; StatusWidget->setLayout(StatusLayout); status=new QLabel(); StatusLayout->addWidget(status); //add partial widgets to main widget layout->addWidget(FileWidget); layout->addWidget(SendWidget); layout->addWidget(StatusWidget); setLayout(layout); //connect signals to slots //fires when the user presses file button connect(loadfile, SIGNAL(clicked(bool)), this,SLOT(setOpenFileName())); //fires when the user presses send button connect(sendBt, SIGNAL(clicked(bool)), this,SLOT(send())); } //user pressed send, send file using a new thread with qymodem library void UploaderGadgetWidget::send() { Ymodem->SendFileT(openFileNameLE->text()); } //destructor !!?! do I need to delete something else? UploaderGadgetWidget::~UploaderGadgetWidget() { delete Port; delete Ymodem; } //from load configuration, creates a new qymodemsend class with the the port /** Cteates a new qymodemsend class. @param port The serial port to use. */ void UploaderGadgetWidget::setPort(QextSerialPort* port) { Port=port; Ymodem=new QymodemSend(*Port); //only now can we connect this signals //signals errors connect(Ymodem,SIGNAL(Error(QString,int)) ,this,SLOT(error(QString,int))); //signals new information connect(Ymodem,SIGNAL(Information(QString,int)), this,SLOT(info(QString,int))); //signals new percentage value connect(Ymodem,SIGNAL(Percent(int)), this,SLOT(updatePercSlot(int))); } /** Updates progress bar value. @param i New percentage value. */ void UploaderGadgetWidget::updatePercSlot(int i) { progressBar->setValue(i); } /** Opens an open file dialog. */ void UploaderGadgetWidget::setOpenFileName() { QFileDialog::Options options; QString selectedFilter; QString fileName = QFileDialog::getOpenFileName(this, tr("QFileDialog::getOpenFileName()"), openFileNameLE->text(), tr("All Files (*);;Text Files (*.bin)"), &selectedFilter, options); if (!fileName.isEmpty()) openFileNameLE->setText(fileName); } /** Shows a message box with an error string. @param errorString The error string to display. @param errorNumber Not used */ void UploaderGadgetWidget::error(QString errorString, int errorNumber) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Critical); msgBox.setText(errorString); msgBox.exec(); status->setText(errorString); } /** Shows a message box with an information string. @param infoString The information string to display. @param infoNumber Not used */ void UploaderGadgetWidget::info(QString infoString, int infoNumber) { status->setText(infoString); }
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 169 ] ] ]
348c8ad134209202ec4b9cfbbc2b15b38c40e806
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Interface/WndPvp.cpp
fdf664a720c4e1166db076c5611262a25fb0acdd
[]
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
9,065
cpp
#include "stdafx.h" #include "defineText.h" #include "AppDefine.h" #include "WndPvp.h" #include "WndManager.h" #include "DPClient.h" extern CDPClient g_DPlay; /**************************************************** WndId : APP_PVP - PVP CtrlId : WIDC_TABCTRL1 - ****************************************************/ CWndPvp::CWndPvp() { } CWndPvp::~CWndPvp() { } void CWndPvp::OnDraw( C2DRender* p2DRender ) { CRect rect = GetClientRect(); rect.bottom -= 30; // p2DRender->RenderFillRect( rect, 0xff00ffff ); int y = 0, nNext = 16; DWORD dwColor = D3DCOLOR_ARGB(255,0,0,0); // TCHAR szString[ 32 ]; // p2DRender->TextOut( 5, y, _T( "Name" ) ); y += nNext; //p2DRender->TextOut( 5, y, _T( "Style" ) ); y += nNext; // p2DRender->TextOut( 5, y, _T( "Job" ) ); y += nNext; //p2DRender->TextOut( 5, y, _T( "Guild" ) ); y += nNext; // p2DRender->TextOut( 5, y, _T( "Level" ) ); y += nNext; //p2DRender->TextOut( 5, y, _T( "Exp1." ) ); y += nNext; //p2DRender->TextOut( 5, y, _T( "Exp2." ) ); y += nNext; //p2DRender->TextOut( 5, y, _T( "Gold" ) ); y += nNext; char szBuff[32]; y = 15; strcpy( szBuff, g_pPlayer->GetFameName() ); if( IsEmpty(szBuff) ) { szBuff[0] = '-'; szBuff[1] = NULL; } p2DRender->TextOut( 90, y, szBuff, dwColor); y += nNext; #if __VER < 8 // __S8_PK strcpy( szBuff, g_pPlayer->GetSlaughterName() ); if( IsEmpty(szBuff) ) { szBuff[0] = '-'; szBuff[1] = NULL; } p2DRender->TextOut( 90, y, szBuff , dwColor ); y += nNext; #endif // __VER < 8 // __S8_PK // p2DRender->TextOut( 90, y, g_pPlayer->GetFameName() , dwColor); y += nNext; // p2DRender->TextOut( 90, y, g_pPlayer->GetSlaughterName() , dwColor ); y += nNext; y = 58; p2DRender->TextOut( 100, y, g_pPlayer->m_nFame , dwColor ); y += nNext; #if __VER < 8 // __S8_PK p2DRender->TextOut( 100, y, g_pPlayer->m_nSlaughter , dwColor ); y += nNext; p2DRender->TextOut( 100, y, g_pPlayer->m_nNumKill , dwColor ); y += nNext; #endif // __VER < 8 // __S8_PK } void CWndPvp::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); CRect rectRoot = m_pWndRoot->GetLayoutRect(); CPoint point( rectRoot.left, rectRoot.top + 96 + 16 ); Move( point ); } // 처음 이 함수를 부르면 윈도가 열린다. BOOL CWndPvp::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_PVP, 0, CPoint( 0, 0 ), pWndParent ); } BOOL CWndPvp::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndPvp::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndPvp::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndPvp::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndPvp::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { return CWndNeuz::OnChildNotify( message, nID, pLResult ); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////// // // PVP정보 // ///////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////// CWndPvpBase::CWndPvpBase() { m_bExpert = FALSE; m_pWndChangeJob = NULL; m_fWaitingConfirm = FALSE; m_nDisplay = 1; } CWndPvpBase::~CWndPvpBase() { SAFE_DELETE(m_pWndChangeJob); } void CWndPvpBase::OnDraw(C2DRender* p2DRender) { if( g_pPlayer->IsBaseJob() ) { if( g_pPlayer->GetLevel() >= MAX_JOB_LEVEL ) m_wndChangeJob.EnableWindow( TRUE ); else m_wndChangeJob.EnableWindow( FALSE ); } else if( g_pPlayer->IsExpert() ) { if( g_pPlayer->GetLevel() >= MAX_JOB_LEVEL + MAX_EXP_LEVEL ) m_wndChangeJob.EnableWindow( TRUE ); else m_wndChangeJob.EnableWindow( FALSE ); } CRect rect = GetClientRect(); rect.bottom -= 30; int y = 0, nNext = 15; DWORD dwColor = D3DCOLOR_ARGB(255,0,0,0); char szBuff[32]; y = 22; int gap1 = 0; int gap2 = 0; gap1 -= 10; gap2 -= 10; y = 15; strcpy( szBuff, g_pPlayer->GetFameName() ); if( IsEmpty(szBuff) ) { szBuff[0] = '-'; szBuff[1] = NULL; } p2DRender->TextOut( 100+gap1, y, szBuff , dwColor ); y += nNext; y = 33; p2DRender->TextOut( 100+gap2, y, g_pPlayer->m_nFame , dwColor ); y += nNext; #if __VER >= 8 // __S8_PK y += 20; p2DRender->TextOut( 100+gap2, y, g_pPlayer->GetPKValue() , dwColor ); y += nNext; y += 4; p2DRender->TextOut( 100+gap2, y, g_pPlayer->GetPKPropensity() , dwColor ); y += nNext; #else // __VER >= 8 // __S8_PK y += 4; p2DRender->TextOut( 100+gap2, y, g_pPlayer->m_nNumKill , dwColor ); y += nNext; y += 4; p2DRender->TextOut( 100+gap2, y, g_pPlayer->GetSlaughterName(), dwColor ); y += nNext; y += 4; p2DRender->TextOut( 100+gap2, y, g_pPlayer->m_nSlaughter , dwColor ); y += nNext; #endif // __VER >= 8 // __S8_PK y = 13; nNext = 19; dwColor = D3DCOLOR_ARGB(255, 0, 0, 180); #if __VER >= 8 // __S8_PK p2DRender->TextOut( 15, y, prj.GetText(TID_GAME_CHARACTTER_PVP1), dwColor ); y += nNext; p2DRender->TextOut( 15, y, prj.GetText(TID_GAME_CHARACTTER_PVP2), dwColor ); y += nNext; y += 20; p2DRender->TextOut( 15, y, prj.GetText(TID_GAME_CHARACTTER_PVP3), dwColor ); y += nNext; p2DRender->TextOut( 15, y, prj.GetText(TID_GAME_CHARACTTER_PVP4), dwColor ); y += nNext; #else // __VER >= 8 // __S8_PK p2DRender->TextOut( 7, y, prj.GetText(TID_GAME_CHARACTER_08), dwColor ); y += nNext; p2DRender->TextOut( 7, y, prj.GetText(TID_GAME_CHARACTER_09), dwColor ); y += nNext; p2DRender->TextOut( 7, y, prj.GetText(TID_GAME_CHARACTER_10), dwColor ); y += nNext; p2DRender->TextOut( 7, y, prj.GetText(TID_GAME_CHARACTER_11), dwColor ); y += nNext; p2DRender->TextOut( 7, y, prj.GetText(TID_GAME_CHARACTER_12), dwColor ); y += nNext; #endif // __VER >= 8 // __S8_PK } void CWndPvpBase::OnInitialUpdate() { CWndBase::OnInitialUpdate(); int y = 105; if( g_pPlayer->IsAuthHigher( AUTH_GAMEMASTER ) ) m_wndChangeJob.Create( ">", 0, CRect( 135, y, 135+40, y + 13 ), this, 10 ); #if __VER >= 9 // __CSC_VER9_2 SetTexture( m_pApp->m_pd3dDevice, MakePath( "Theme\\", ::GetLanguage(), _T( "WndPvP2.tga" ) ), TRUE ); #else //__CSC_VER9_2 SetTexture( m_pApp->m_pd3dDevice, MakePath( "Theme\\", ::GetLanguage(), _T( "wndPvP.tga" ) ), TRUE ); #endif //__CSC_VER9_2 FitTextureSize(); } BOOL CWndPvpBase::Initialize( CWndBase* pWndParent, DWORD dwWndId ) { CRect rectWindow = m_pWndRoot->GetWindowRect(); CRect rect( 240, 0, 240 + 330, 255 - 135 ); //SetTitle( GETTEXT( TID_APP_CHARACTER ) ); return CWndBase::Create(WBS_THICKFRAME|WBS_MOVE|WBS_SOUND|WBS_CAPTION|WBS_EXTENSION,rect,pWndParent,dwWndId); } BOOL CWndPvpBase::OnChildNotify(UINT message,UINT nID,LRESULT* pLResult) { if( message == WNM_CLICKED ) { switch( nID ) { case JOB_MERCENARY: case JOB_ACROBAT: case JOB_ASSIST: case JOB_MAGICIAN: case JOB_PUPPETEER: { if( nID != g_pPlayer->GetJob() ) { //"자신의 직업만 올릴수 있습니다" g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0037) ) ); } if( m_fWaitingConfirm == FALSE ) { g_DPlay.SendIncJobLevel( nID ); m_fWaitingConfirm = TRUE; } break; } case 10: // 전직 // 방랑자의 레벨이 15이상인것을 찾음 if( g_pPlayer->GetLevel() >= MAX_JOB_LEVEL ) { SAFE_DELETE(m_pWndChangeJob); m_pWndChangeJob = new CWndChangeJob( g_pPlayer->GetJob() ); m_pWndChangeJob->Initialize( this, 1106 ); } break; } } return CWndBase::OnChildNotify( message, nID, pLResult ); } BOOL CWndPvpBase::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndBase::OnCommand(nID,dwMessage,pWndBase); } void CWndPvpBase::OnSize(UINT nType, int cx, int cy) { int x = m_rectClient.Width() / 2; int y = m_rectClient.Height() - 30; CSize size = CSize( 70, 25); CRect rect1_1( x - ( size.cx / 2), y, ( x - ( size.cx / 2 ) ) + size.cx, y + size.cy ); CRect rect2_1( x - size.cx - 10, y, ( x - size.cx - 10 ) + size.cx, y + size.cy ); CRect rect2_2( x + 10 , y, ( x + 10 ) + size.cx, y + size.cy ); CRect rect3_1( x - ( size.cx / 2) - size.cx - 10, y, (x - ( size.cx / 2) - size.cx - 10) + size.cx, y + size.cy ); CRect rect3_2( x - ( size.cx / 2) , y, (x - ( size.cx / 2) ) + size.cx, y + size.cy ); CRect rect3_3( x + ( size.cx / 2) + 10 , y, (x + ( size.cx / 2) + 10 ) + size.cx, y + size.cy ); CWndBase::OnSize(nType,cx,cy); } void CWndPvpBase::OnLButtonUp(UINT nFlags, CPoint point) { } void CWndPvpBase::OnLButtonDown(UINT nFlags, CPoint point) { }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 273 ] ] ]
33aad8f5ac12fb237ae3461141ee19dafb3e74bf
105cc69f4207a288be06fd7af7633787c3f3efb5
/HovercraftUniverse/HovercraftUniverse/SpeedBoostPhantom.h
5b36b5ceb99e157ede2ed56e72325dcea11b60eb
[]
no_license
allenjacksonmaxplayio/uhasseltaacgua
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
ad54e9aa3ad841b8fc30682bd281c790a997478d
refs/heads/master
2020-12-24T21:21:28.075897
2010-06-09T18:05:23
2010-06-09T18:05:23
56,725,792
0
0
null
null
null
null
UTF-8
C++
false
false
778
h
#ifndef SpeedBoostPhantom_H #define SpeedBoostPhantom_H #include <Physics/Dynamics/Phantom/hkpSimpleShapePhantom.h> namespace HovUni { class SpeedBoost; /** * This is a boost phantom * When a player passes trough it should receive a boost or a slowdown. * @author Pieter-Jan Pintens */ class SpeedBoostPhantom : public hkpSimpleShapePhantom { private: SpeedBoost * mBoost; public: /** * Constructor * @param aabb, the bounding box * @param boost */ SpeedBoostPhantom(const hkpShape *shape, const hkTransform &transform, SpeedBoost * boost); ~SpeedBoostPhantom(void); virtual void addOverlappingCollidable( hkpCollidable* handle ); virtual void removeOverlappingCollidable( hkpCollidable* handle ); }; } #endif
[ "pintens.pieterjan@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c", "[email protected]" ]
[ [ [ 1, 7 ], [ 10, 25 ], [ 27, 39 ] ], [ [ 8, 9 ], [ 26, 26 ] ] ]
fa90fa32e0772277f29a02164544767bc59455ff
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
/GameServer/MapGroupKernel/Role.h
eaab4ffc2c6e7895bf403c45aae656904f34b216
[]
no_license
cronoszeu/revresyksgpr
78fa60d375718ef789042c452cca1c77c8fa098e
5a8f637e78f7d9e3e52acdd7abee63404de27e78
refs/heads/master
2020-04-16T17:33:10.793895
2010-06-16T12:52:45
2010-06-16T12:52:45
35,539,807
0
2
null
null
null
null
GB18030
C++
false
false
11,685
h
#pragma once #pragma warning(disable:4786) #include <list> #include <windows.h> #include "common.h" #include "define.h" #include "I_Role.h" #include "gameMap.h" class CRole : public IRole, public IMapThing { protected: CRole(); virtual ~CRole(); public: // get attrib virtual OBJID GetID () PURE_VIRTUAL_FUNCTION_0 virtual LPCTSTR GetName () PURE_VIRTUAL_FUNCTION_0 virtual DWORD GetLookFace () PURE_VIRTUAL_FUNCTION_0 virtual DWORD GetHair () PURE_VIRTUAL_FUNCTION_0 virtual char GetLength () PURE_VIRTUAL_FUNCTION_0 // 取得角色高矮 -- zlong 2004-02-03 virtual char GetFat () PURE_VIRTUAL_FUNCTION_0 // 取得角色胖瘦 -- zlong 2004-02-03 virtual int GetPosX () PURE_VIRTUAL_FUNCTION_0 virtual int GetPosY () PURE_VIRTUAL_FUNCTION_0 virtual int GetDir () PURE_VIRTUAL_FUNCTION_0 virtual uint64 GetEffect () PURE_VIRTUAL_FUNCTION_0 virtual int GetPose () PURE_VIRTUAL_FUNCTION_0 virtual DWORD GetLev () PURE_VIRTUAL_FUNCTION_0 virtual DWORD GetLife () { return 0; } virtual DWORD GetMaxLife () { return 0; } virtual DWORD GetMinAtk () { return 0; } virtual DWORD GetMaxAtk () { return 0; } virtual DWORD GetMgcMinAtk () { return 0; } virtual DWORD GetMgcMaxAtk () { return 0; } virtual DWORD GetAttack () { return 0; } virtual DWORD GetAtkHitRate () PURE_VIRTUAL_FUNCTION_0 virtual DWORD GetDef () { return 0; } virtual DWORD GetDefence () { return 0; } virtual DWORD GetDex () { return 0; } virtual DWORD GetDexterity () { return 0; } virtual DWORD GetDdg () { return 0; } virtual DWORD GetDodge () { return 0; } virtual DWORD GetMagicDef () { return 0; } virtual DWORD GetInterAtkRate () { return 0; } virtual DWORD GetIntervalAtkRate () { return 0; } virtual int GetHelmetTypeID () { return 0; } virtual int GetArmorTypeID () { return 0; } virtual int GetWeaponRTypeID () { return 0; } virtual int GetWeaponLTypeID () { return 0; } virtual int GetMountTypeID () { return 0; } virtual int GetMantleTypeID () { return 0; } // virtual DWORD GetMedalSelect () { return 0; } // virtual DWORD GetTitleSelect () { return 0; } virtual int GetDistance (int x, int y) { return __max(abs(GetPosX() - x), abs(GetPosY() - y)); } virtual int GetDistance (IMapThing* pTarget) { return __max(abs(GetPosX() - pTarget->GetPosX()), abs(GetPosY() - pTarget->GetPosY())); } virtual CGameMap* GetMap () { CHECKF(m_pMap); return m_pMap; } virtual DWORD GetSynID () { return ID_NONE; } virtual DWORD GetSynRank () { return RANK_NONE; } virtual DWORD GetSynRankShow () { return RANK_NONE; } virtual bool IsSimpleMagicAtk () { return 0; } virtual int GetSimpleMagicHitRate() { return 0; } virtual int GetTutorExp () { return 0; } virtual UCHAR GetTutorLevel () { return 0; } virtual UCHAR GetMercenaryRank () { return 0; } virtual DWORD GetMercenaryExp () { return 0; } virtual UCHAR GetNobilityRank () { return 0; } virtual DWORD GetExploit () { return 0; } public: // const virtual bool IsAlive () PURE_VIRTUAL_FUNCTION_0 virtual bool IsTalkEnable () { return false; } virtual bool IsGM () { return false; } virtual bool IsPM () { return false; } virtual bool IsMonster () { return false; } virtual bool IsDelThis () PURE_VIRTUAL_FUNCTION_0 virtual bool IsVirtuous () { return false; } virtual bool IsEvil () { return true; } virtual bool IsBowman () { return false; } virtual bool IsShieldEquip () { return false; } virtual bool IsWing () { return false; } virtual bool IsSendBlockInfo () { return false; } // return true: ppv返回对象指针 virtual bool QueryObj (OBJID idObjType, void** ppv) PURE_VIRTUAL_FUNCTION_0 virtual IMapThing* QueryMapThing () { return (IMapThing*)this; } virtual IRole* FindAroundRole (OBJID id) { return GetMap()->QueryRole(GetPosX(), GetPosY(), id); } virtual CUser* QueryOwnerUser () { return NULL; } public:// modify attrib ------------------------------ virtual void SetDir (int nDir) {} virtual void SetPose (int nPose) {} virtual void SetStatus (int nStatus, bool bSynchro=true) PURE_VIRTUAL_FUNCTION virtual void ClsStatus (int nStatus, bool bSynchro=true) PURE_VIRTUAL_FUNCTION virtual bool AddAttrib (int idxAttr, __int64 i64Data, int bSynchro) PURE_VIRTUAL_FUNCTION_0 virtual void ProcessOnMove (int nMoveMode) PURE_VIRTUAL_FUNCTION virtual void ProcessAfterMove () PURE_VIRTUAL_FUNCTION virtual void GetFootPrint (int& x, int& y) PURE_VIRTUAL_FUNCTION virtual bool SpendArrow () { return true; } virtual IStatus* QueryStatus(OBJID idType) { CHECKF(m_setStatus); return m_setStatus->GetObj(idType); } virtual IStatusSet* QueryStatusSet() { CHECKF(m_setStatus); return m_setStatus; } virtual void AwardBattleExp (int nExp, bool bGemEffect=true) {} virtual int AdjustHitRate (int nHitRate) { return nHitRate; } virtual int AdjustAttack (int nAtk) { return nAtk; } virtual int AdjustDefence (int nDef) { return nDef; } virtual int AdjustMagicAtk (int nAtk) { return nAtk; } virtual int AdjustMagicDef (int nDef) { return nDef; } virtual int AdjustBowDefence (int nDef) { return nDef; } virtual int AdjustWeaponDamage (int nDamage) { return nDamage; } virtual int AdjustMagicDamage (int nDamage) { return nDamage; } virtual void SetFightPause (int nInterval) {} virtual void SaveInfo () PURE_VIRTUAL_FUNCTION public: // system virtual void BroadcastRoomMsg(Msg* pMsg, bool bSendSelf = false); virtual void BroadcastRoomMsg(LPCTSTR szMsg, bool bSendSelf = false) PURE_VIRTUAL_FUNCTION virtual bool SendMsg(Msg* pMsg) { return true; } virtual bool SendSysMsg(const char* fmt, ...) { return true; } virtual void OnTimer(time_t tCurr) PURE_VIRTUAL_FUNCTION public: // map virtual bool MoveToward(int nDir, bool bSync = true); virtual void TransPos(int nPosX, int nPosY); virtual void JumpPos(int nPosX, int nPosY); virtual bool SyncTrackTo(int nPosX, int nPosY, int nDir, DWORD dwAction); virtual void ActiveTransPos(int nPosX, int nPosY); virtual bool SendSelfToBlock() PURE_VIRTUAL_FUNCTION_0 public: // fight ------------------------------ virtual void ClrAttackTarget () PURE_VIRTUAL_FUNCTION virtual bool SetAttackTarget(IRole* pTarget = NULL) PURE_VIRTUAL_FUNCTION_0 virtual bool AutoSkillAttack(IRole* pTarget) PURE_VIRTUAL_FUNCTION_0 virtual bool AdditionMagic(int nLifeLost, int nDamage) PURE_VIRTUAL_FUNCTION_0 virtual int Attack(IRole* pTarget) PURE_VIRTUAL_FUNCTION_0 virtual bool BeAttack(bool bMagic, IRole* pTarget, int nPower, bool bReflectEnable=true) PURE_VIRTUAL_FUNCTION_0 virtual bool MagicAttack(int nType, OBJID idTarget, int x, int y) PURE_VIRTUAL_FUNCTION_0 virtual void Kill(IRole* pTarget, DWORD dwDieWay) PURE_VIRTUAL_FUNCTION virtual void BeKill(IRole* pTarget = NULL) PURE_VIRTUAL_FUNCTION virtual bool IsAtkable(IRole* pTarget, bool bSendHint=false) PURE_VIRTUAL_FUNCTION_0 virtual bool IsBeAtkable() PURE_VIRTUAL_FUNCTION_0 virtual int GetAttackRange(int nTargetSizeAdd) PURE_VIRTUAL_FUNCTION_0 virtual int GetSizeAdd() PURE_VIRTUAL_FUNCTION_0 virtual int GetLuck() PURE_VIRTUAL_FUNCTION_0 virtual void SendDamageMsg(OBJID idTarget, int nDamage) PURE_VIRTUAL_FUNCTION virtual bool TransferShield(bool bMagic, IRole* pAtker, int nDamage) { return false; } public:// 为了修改魔法系统而增加的部分,等魔法系统修改完再做整理 -- zlong 2005-03-23 virtual void AwardSynWarScore(CNpc* pNpc, int nScore) {} virtual bool IsImmunity(IRole* pRole) { return false; } virtual DWORD GetProfession() { return 0; } virtual int GetGemExpEffect() { return 0; } virtual int GetGemMgcExpEffect() { return 0; } virtual bool SpendEquipItem(int nSubType, int nNum, bool bSynchro) { return false; } virtual int AdjustExp(IRole* pTarget, int nRawExp, bool bNewbieBonusMsg=false) { return nRawExp; } virtual bool DecEquipmentDurability(bool bBeAttack, bool bMagic, int bDurValue=1) { return false; } virtual void SendGemEffect() {} virtual bool IsEmbedGemType(int nGemType) { return false; } virtual DWORD GetMana() { return 0; } virtual DWORD GetMaxMana() { return 0; } virtual int GetEnergy() { return 0; } virtual bool CheckWeaponSubType(int nSubType, int nNum = 0) { return false; } virtual DWORD GetPotential() { return 0; } virtual CTransformation* QueryTransformation() { return NULL; } virtual bool IsArrowPass(int x, int y, int nAlt=ARROW_FLY_ALT) { return true; } virtual CTeam* GetTeam() { return NULL; } virtual CItem* GetEquipItemByPos(int nPosition) { return NULL; } virtual bool CheckCrime(IRole* pRole) { return false; } virtual void SetDelay(int nDelay) {} virtual CItem* GetWeaponR() { return NULL; } virtual CItem* GetWeaponL() { return NULL; } virtual bool DropItem(OBJID idItem, int x, int y) { return false; } virtual DWORD GetSoulSum() { return 0; } virtual bool Synchro() { return true; } virtual CItem* FindSpaceTransSpell() { return NULL; } virtual void AddEquipmentDurability(int nPosition, int nAddValue) {} virtual bool SynPosition(int nPosX, int nPosY, int nMaxDislocation = 8) { return true; } virtual bool Transform(DWORD dwType, int nKeepSecs, bool bSynchro = true) { return false; } virtual bool AddItem (CItem* pItem, bool bSynchro, bool bUpdate = true) { return false; } virtual bool IsInFan(POINT pos, POINT posSource, int nRange, int nWidth, POINT posCenter); virtual int AdjustData(int nData, int nAdjust, int nMaxData=0) { return CRole::AdjustDataEx(nData, nAdjust, nMaxData); } static int AdjustDataEx(int nData, int nAdjust, int nMaxData=0); virtual CMagic* QueryMagic() { return NULL; } protected: IStatusSet* m_setStatus; // uint64 m_i64Effect; PROCESS_ID m_idProcess; // CGameMap* m_pMap; int m_nPosX; int m_nPosY; int m_nDir; // 广播对象集 typedef std::list<OBJID> BROADCAST_SET; BROADCAST_SET m_setBCRole; BROADCAST_SET m_setBCMapItem; public: virtual bool UpdateBroadcastSet(bool bClearSet = false); virtual void ClrBroadcastSet(); public: virtual void AddToBCRoleSet (OBJID idRole, bool bSendMsg); virtual void RemoveFromBCRoleSet (OBJID idRole); virtual void AddToBCMapItemSet (OBJID idMapItem); virtual void RemoveFromBCMapItemSet (OBJID idMapItem); public: static bool AttachStatus(IRole* pRole, int nStatus, int nPower, int nSecs, int nTimes=0); // =0 : status once static bool DetachStatus(IRole* pRole, int nStatus); static void DetachWellStatus(IRole* pRole); static void DetachBadlyStatus(IRole* pRole); static void DetachAllStatus(IRole* pRole); static bool IsWellStatus(int nStatus); static bool IsBadlyStatus(int nStatus); };
[ "rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1" ]
[ [ [ 1, 252 ] ] ]
ee9b49cb3e620b2224679ae694e37ada6e974e14
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/srpc/test/DummyRpcClient.cpp
fac8161af06c97b0b27d3277a6e985527eb6c714
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
UTF-8
C++
false
false
1,197
cpp
#include "stdafx.h" #include "DummyRpcClient.h" IMPLEMENT_SRPC_EVENT_DISPATCHER(DummyRpcClient); DummyRpcClient::DummyRpcClient(srpc::RpcNetwork* rpcNetwork) : srpc::RpcReceiver(rpcNetwork), srpc::RpcForwarder(rpcNetwork) { } FORWARD_SRPC_METHOD_0(DummyRpcClient, rpc0); FORWARD_SRPC_METHOD_1(DummyRpcClient, rpc1, Int32, p1); FORWARD_SRPC_METHOD_2(DummyRpcClient, rpc2, RInt32, p1, RInt32, p2); FORWARD_SRPC_METHOD_3(DummyRpcClient, rpc3, RInt32, p1, RInt32, p2, RInt32, p3); FORWARD_SRPC_METHOD_4(DummyRpcClient, rpc4, RInt32, p1, RInt32, p2, RInt32, p3, RInt32, p4); FORWARD_SRPC_METHOD_5(DummyRpcClient, rpc5, RInt32, p1, RInt32, p2, RInt32, p3, RInt32, p4, RInt32, p5); FORWARD_SRPC_METHOD_6(DummyRpcClient, rpc6, RInt32, p1, RInt32, p2, RInt32, p3, RInt32, p4, RInt32, p5, RInt32, p6); FORWARD_SRPC_METHOD_7(DummyRpcClient, rpc7, RInt32, p1, RInt32, p2, RInt32, p3, RInt32, p4, RInt32, p5, RInt32, p6, RInt32, p7); FORWARD_SRPC_METHOD_2(DummyRpcClient, rpcBits, RInt15, p1, RInt31, p2); FORWARD_SRPC_METHOD_0(DummyRpcClient, rpcFailed); void DummyRpcClient::onForwarding(const srpc::RRpcId& rpcId) { lastRpcId_ = rpcId; }
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 32 ] ] ]
1a072717eec51d0502cae78bf7f36bf4c8044cc8
b63cad17af550bc7150431b7b0d639a46a129d82
/mcscript-attribute-handler.h
39062204b1166cfe71775b1aa68dd64876ebab28
[]
no_license
cjus/msgCourier
90463028b5e6222dd5c804215fa43bc518c4a539
075ff724316fd28c21d842726b694806d82bf53b
refs/heads/master
2021-01-10T19:41:02.306930
2010-09-05T18:47:24
2010-09-05T18:47:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,577
h
/* mcscript-attribute-handler.h Copyright (C) 2005 Carlos Justiniano mcscript-attribute-handler.h 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. mcscript-attribute-handler.h was developed by Carlos Justiniano for use on the ChessBrain Project (http://www.chessbrain.net) and is now 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 mcscript-attribute-handler.h; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /** @file mcscript-attribute-handler.h @brief Message Courier Script Handlers @author Carlos Justiniano @attention Copyright (C) 2005 Carlos Justiniano, GNU GPL Licence (see source file header) Message Courier Script Handlers. */ #ifndef _MCSCRIPT_ATTRIBUTE_HANDLER_H #define _MCSCRIPT_ATTRIBUTE_HANDLER_H #include <string> #include "mcscript.h" /********************* * Attribute Handler * *********************/ class cMCAttributeHandler : public cMCScriptKeywordHandler { public: int Process(cMCScript *pMCScript, cXMLLiteParser *pXML, std::string *pOutputBuffer) { return 0; } }; #endif //_MCSCRIPT_ATTRIBUTE_HANDLER_H
[ [ [ 1, 47 ] ] ]
6d2560ce0e07412be6caf2d97f15fbd9cb19c144
942b88e59417352fbbb1a37d266fdb3f0f839d27
/src/argss/XP/tilemapautotiles.cxx
794d68dd19ebe0678bf71457426fa1a4cbe47c00
[ "BSD-2-Clause" ]
permissive
take-cheeze/ARGSS...
2c1595d924c24730cc714d017edb375cfdbae9ef
2f2830e8cc7e9c4a5f21f7649287cb6a4924573f
refs/heads/master
2016-09-05T15:27:26.319404
2010-12-13T09:07:24
2010-12-13T09:07:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,342
cxx
////////////////////////////////////////////////////////////////////////////////// /// ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf) /// All rights reserved. /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions are met: /// * Redistributions of source code must retain the above copyright /// notice, this list of conditions and the following disclaimer. /// * Redistributions in binary form must reproduce the above copyright /// notice, this list of conditions and the following disclaimer in the /// documentation and/or other materials provided with the distribution. /// /// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY /// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED /// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE /// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY /// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES /// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; /// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND /// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT /// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS /// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// Headers //////////////////////////////////////////////////////////// #include <argss/bitmap.hxx> #include "tilemapautotiles.hxx" namespace ARGSS { namespace ATilemapAutotiles { //////////////////////////////////////////////////////////// /// Global Variables //////////////////////////////////////////////////////////// VALUE id; //////////////////////////////////////////////////////////// /// ARGSS TilemapAutotiles ruby functions //////////////////////////////////////////////////////////// VALUE rinitialize(VALUE self) { rb_iv_set(self, "@autotiles", rb_ary_new2(8)); return self; } VALUE raref(VALUE self, VALUE index) { return rb_ary_entry(rb_iv_get(self, "@autotiles"), NUM2INT(index)); } VALUE raset(VALUE self, VALUE index, VALUE bitmap) { Check_Classes_N(bitmap, ARGSS::ABitmap::getID()); rb_ary_store(rb_iv_get(self, "@autotiles"), NUM2INT(index), bitmap); return bitmap; } //////////////////////////////////////////////////////////// /// ARGSS TilemapAutotiles initialize //////////////////////////////////////////////////////////// void Init() { id = rb_define_class("TilemapAutotiles", rb_cObject); static FuncTable funcTable = { { ARGSS_FUNC(initialize), 0 }, { "[]", RubyFunc(raref), 1 }, { "[]=", RubyFunc(raset), 2 }, }; defineMethods(id, funcTable); } //////////////////////////////////////////////////////////// /// ARGSS TilemapAutotiles new ruby instance //////////////////////////////////////////////////////////// VALUE New() { return rb_class_new_instance(0, 0, id); } } // namespace ATilemapAutotiles } // namespace ARGSS
[ "takeshi@takeshi-laptop.(none)", "[email protected]" ]
[ [ [ 1, 27 ], [ 32, 32 ], [ 41, 41 ] ], [ [ 28, 31 ], [ 33, 40 ], [ 42, 79 ] ] ]
29118422eb3dddc25ef3ae59a192ce9d15262bc6
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/v0-1/engine/ui/src/MainMenuWindow.cpp
01bae29ca94db3f774a55713fd260fc5813f0454
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,452
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include <boost/bind.hpp> #include "UiPrerequisites.h" #include "UiSubsystem.h" #include "CoreSubsystem.h" #include "ConfigurationManager.h" #include "MainMenuWindow.h" using namespace CEGUI; using namespace Ogre; namespace rl { MainMenuWindow::MainMenuWindow() : CeGuiWindow("mainmenuwindow.xml", WND_MOUSE_INPUT), mActiveModule("") { getWindow("MainMenu/EngineVersion")->setText( ConfigurationManager::getSingleton().getEngineVersionString()+ " ("+StringConverter::toString(ConfigurationManager::getSingleton().getEngineBuildNumber())+")"); getWindow("MainMenu/Game/Start")->subscribeEvent( MenuItem::EventClicked, boost::bind(&MainMenuWindow::handleStart, this)); getWindow("MainMenu/Game/Quit")->subscribeEvent( MenuItem::EventClicked, boost::bind(&MainMenuWindow::handleQuit, this)); fillModules(); } void MainMenuWindow::fillModules() { MenuBase* modulesMenu = getMenu("MainMenu/Modules/Menu"); Ogre::StringVector modules = CoreSubsystem::getSingleton().getActivatableModules(); mActiveModule = CoreSubsystem::getSingleton().getActiveAdventureModule(); if (mActiveModule == "") mActiveModule = *modules.begin(); for(Ogre::StringVector::iterator mod = modules.begin(); mod != modules.end(); mod++) { MenuItem* it = static_cast<MenuItem*>( CEGUI::WindowManager::getSingleton().createWindow("RastullahLook/MenuItem", getNamePrefix()+"MainMenu/Modules/" + *mod)); it->setText(*mod); modulesMenu->addItem(it); if ((*mod) == mActiveModule) it->setText(*mod+" *"); it->subscribeEvent( MenuItem::EventClicked, boost::bind(&MainMenuWindow::handleChooseModule, this, it, *mod)); } } bool MainMenuWindow::handleChooseModule(MenuItem* it, Ogre::String module) { MenuBase* modulesMenu = getMenu("MainMenu/Modules/Menu"); ItemEntry* itOld = NULL; for (size_t i=0; i<modulesMenu->getItemCount(); i++) { ItemEntry* curr = modulesMenu->getItemFromIndex(i); if (curr->getText().compare(mActiveModule+" *") == 0) { itOld = curr; break; } } itOld->setText(mActiveModule); mActiveModule = module; it->setText(module+" *"); return true; } bool MainMenuWindow::handleStart() { setVisible(false); destroyWindow(); CoreSubsystem::getSingleton().startAdventureModule(mActiveModule.c_str()); this->setVisible( false ); return true; } bool MainMenuWindow::handleQuit() { UiSubsystem::getSingleton().requestExit(); return true; } bool MainMenuWindow::handleGraphicOptions() { return true; } bool MainMenuWindow::handleSoundOptions() { return true; } }
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 124 ] ] ]
4d083c2e6f570413822ebc9e172aee617b6b8d1f
e19b72560f44dd99124b49f8437d04e7408c26ac
/VPTree/src/bof_db_region.cpp
32bce543bef331baea99cd3d08e61af4fda0249f
[]
no_license
jbfiot/rangers
d5a588da14e188e0f605758e93c6aaf4616cf4f3
15b88a73e39708e68c6224f9809cd2966f9dbe26
refs/heads/master
2021-01-17T05:25:35.494251
2009-03-20T10:09:26
2009-03-20T10:09:26
38,111,954
0
0
null
null
null
null
UTF-8
C++
false
false
20,769
cpp
#include "bof_db_region.h" using namespace std; #define RANDOM_SET_MAX_LENGTH 100 #define MAX_ROWS_BY_DISTANCE_REQUEST 100 /** * Constructor **/ Bof_db_Region::Bof_db_Region (Feature_db *feature_db, int k, string db_host, string db_username, string db_password, string db_name, string table_name) { this->db_name = db_name; this->db_username = db_username; this->db_password = db_password; this->db_host = db_host; this->table_name = table_name; this->nb_k_centers = k; this->fdb = feature_db; //Server Connexion if (!(db_connection = mysql_init(NULL))) error_and_exit(); if (mysql_real_connect(db_connection,db_host.c_str(),db_username.c_str(),db_password.c_str(),NULL,0,NULL,0)) // Notice we do not specify the database because it might not exists. cout << "SQL server connection: OK"<<endl; else error_and_exit(); //Database creation string db_creation_query = "CREATE DATABASE IF NOT EXISTS "; db_creation_query += db_name; if (!mysql_query(db_connection, db_creation_query.c_str())) cout << "Database creation query: OK"<<endl; else error_and_exit(); //Database selection string db_selection_query = "USE "; db_selection_query += db_name; if (!mysql_query(db_connection, db_selection_query.c_str())) cout << "Database selection query: OK"<<endl; else error_and_exit(); //Table creation string table_creation_query = "CREATE TABLE IF NOT EXISTS "; table_creation_query += table_name; table_creation_query += " (Bof_Region_ID int NOT NULL auto_increment,"; for (unsigned int i=1; i<=this->nb_k_centers; i++) { table_creation_query += "Coeff"; table_creation_query += to_string(i); table_creation_query += " DOUBLE NOT NULL,"; } table_creation_query += " Parent int DEFAULT 0, Direction int DEFAULT 0, Mu double, Son1 int DEFAULT 0, Son2 int DEFAULT 0,"; table_creation_query += " PRIMARY KEY(Bof_Region_ID))"; if (!mysql_query(db_connection, table_creation_query.c_str())) cout << "Table creation query: OK."<<endl; else error_and_exit(); } /** * Destructor */ Bof_db_Region::~Bof_db_Region() { mysql_close(db_connection); cout << "Closing connection: OK."<<endl; } /** * Error function (display error and exit program). **/ void Bof_db_Region::error_and_exit() { printf("Error %u: %s\n", mysql_errno(db_connection), mysql_error(db_connection)); system("pause"); exit(4); } /** * Add-Bag of Features function (add a line to the table). **/ void Bof_db_Region::add_bof(Bof_Region bag) { Vector histogram; bag.get_histogram(histogram); string add_bof_region_query = "INSERT INTO "; add_bof_region_query += table_name; add_bof_region_query += " ("; for (unsigned int i=0; i<this->nb_k_centers; i++) { add_bof_region_query += "Coeff"; add_bof_region_query += to_string(i+1); if (i != this->nb_k_centers - 1) add_bof_region_query += ","; } add_bof_region_query += ") VALUES ("; for (unsigned int i=0; i<this->nb_k_centers; i++) { add_bof_region_query += to_string(histogram[i]); if (i != this->nb_k_centers - 1) add_bof_region_query += ","; } add_bof_region_query += ")"; if (mysql_query(db_connection, add_bof_region_query.c_str())) error_and_exit(); } /** * PARTIE CONSTRUCTION DE L'ARBRE **/ /** * Sélectionne un random set aléatoire de résultats parmi les résultats de la requete: * PARENT = parent et DIRECTION = direction **/ void Bof_db_Region::select_random_set_indexes(int index_parent, int direction, std::vector<Vector> &sample_set, std::vector<int> &random_indexes, unsigned int not_this_one) { //1- Compter le nombre de résultats de la requete int nb = this->count_elems(index_parent, direction, not_this_one); //RECUPERATION DU CONTENU //Declaration des pointeurs de structure MYSQL_RES *result = NULL; MYSQL_ROW row = NULL; //2- Sélectionner un random set sur la liste des indexes sample_set.resize(min(RANDOM_SET_MAX_LENGTH,nb)); random_indexes.resize(min(RANDOM_SET_MAX_LENGTH,nb)); string random_query = "SELECT Bof_Region_ID, "; for (unsigned int k=1; k<=nb_k_centers;k++) { random_query+="Coeff"; random_query+=to_string(k); if (k!= nb_k_centers) random_query+=" ,"; } random_query+=" FROM "; random_query+=table_name; random_query+=" WHERE Parent = "; random_query+=to_string(index_parent); random_query+=" and Direction = "; random_query+=to_string(direction); if (not_this_one != 0) { random_query += " and BoF_Region_ID != "; random_query += to_string(not_this_one); } random_query+=" ORDER BY RAND() LIMIT "; random_query+=to_string(RANDOM_SET_MAX_LENGTH); if (!mysql_query(db_connection, random_query.c_str())) { //cout << "Random query (Random) : OK"<<endl; } else error_and_exit(); result = mysql_use_result(db_connection); int i=0; Vector res; res.resize(nb_k_centers); while(row = mysql_fetch_row(result)) { //Primary key of random result random_indexes[i] = strtodouble(row[0]); //Random BOF for (int j=0; j<nb_k_centers;j++) res[j] = strtodouble(row[j+1]); sample_set[i] = res; i++; } //Liberation du jeu de resultat mysql_free_result(result); } /** * Sélectionne la racine du VP-Tree **/ unsigned int Bof_db_Region::select_vp(int index_parent, int direction, Bof_Region &root) { std::vector<Vector> sample_set; std::vector<int> random_indexes_candidates; select_random_set_indexes(index_parent, direction, sample_set, random_indexes_candidates); double best_spread = 0; unsigned int best_candidate = random_indexes_candidates[0]; root = Bof_Region(sample_set[0], this->fdb); if (random_indexes_candidates.size() == 1) //Il n'a qu'un seul élément dans l'ensemble return best_candidate; std::vector<Vector> rand_set_for_med_test; for (int i=0; i<sample_set.size(); ++i) { //Sélection d'un set aléatoire de l'espace qui nous intéresse Bof_Region candidate_region(sample_set[i], this->fdb); std::vector<int> rand_set_for_med_test_indexes; select_random_set_indexes(index_parent, direction, rand_set_for_med_test, rand_set_for_med_test_indexes, random_indexes_candidates[i]); //Précalcul des distances entre le candidat et les régions du sample_set Vector distances_p_rand_set; distances_p_rand_set.resize(rand_set_for_med_test.size()); for (int j=0; j<distances_p_rand_set.size(); ++j) { Bof_Region random_region(rand_set_for_med_test[j], this->fdb); double tmp = candidate_region - random_region; distances_p_rand_set[j] = tmp; } //Calcul de la variance de cet ensemble de distances (calculée avec la médiane) double median = distances_p_rand_set.compute_median(); double spread = distances_p_rand_set.compute_second_moment(median); //cout << "Répartition des distances: " << distances_p_rand_set // << " spread: " << spread << " median: " << median << endl; if (spread > best_spread) { best_spread = spread; best_candidate = random_indexes_candidates[i]; root = candidate_region; } rand_set_for_med_test.clear(); } return best_candidate; } void Bof_db_Region::build_tree() { //Initialisation des champs temporaires string set_son_query = "UPDATE "; set_son_query += table_name; set_son_query += " SET Parent=0, Direction=0, Son1=0, Son2=0, Mu=0"; mysql_query(db_connection, set_son_query.c_str()); //Fonction récursive construisant l'arbre make_one_step(0,0); } void Bof_db_Region::make_one_step(int index_parent, int direction) { static int compt=0; cout << endl << "--------------------------------" << endl; cout << "ITERATION " << compt << ": Parent " << index_parent << " direction " << direction << endl; cout << "--------------------------------" << endl; compt ++; //1- Sélectionner la racine parmi un random set Bof_Region root; unsigned int median_index = select_vp(index_parent, direction, root); cout << "RACINE CHOISIE: " << median_index << endl; //2- Choisir la distance critique: // C'est la médiane des distances du noeud à tous les éléments de l'ensemble //2-1) Calcul des distances à la racone dans la database this->update_distances(index_parent, direction, root); //2-2) Calcul de la médiane par la database double mu = this->get_median(index_parent, direction); cout << "Seuil choisi : " << mu << endl; //3- Set parent and directions to nodes of the set this->set_parent_direction_fields(index_parent, direction, mu, median_index); //4- Mise à jour du Son correspondant pour le parent if (index_parent != 0) this->set_son_value(index_parent, direction, median_index); //5- Mise à jour du Mu pour la racine trouvée this->set_mu_value(median_index, mu); //6- Mise à jour du parent de la racine this->set_parent_direction(median_index, index_parent, direction); //7- Obtenir le nombre de noeuds à gauche et à droite int nb_son_1 = this->count_elems(median_index, 1); int nb_son_2 = this->count_elems(median_index, 2); //Si pas de noeud dans le sous-arbre de gauche... if (nb_son_1 == 0) { //On met 0 comme sous-arbre de de gauche this->set_son_value(median_index, 1, 0); } //Si pas de noeud dans le sous-arbre de gauche... if (nb_son_2 == 0) { //On met 0 comme sous-arbre de de gauche this->set_son_value(median_index, 2, 0); } cout << "Répartition : " << nb_son_1 << " | " << nb_son_2 << endl; //4- Si il y a au moins un élément dans le sous-arbre de gauche if (nb_son_1>0) make_one_step(median_index, 1); // Si il y a au moins un élément dans le sous-arbre de droite if (nb_son_2>0) make_one_step(median_index, 2); } /** * Update les champs Son1 ou Son2 du parent **/ void Bof_db_Region::set_son_value(int index_parent, int direction, int index_median) { string son; if (direction == 1) son = "Son1"; else son = "Son2"; string set_son_query = "UPDATE "; set_son_query += table_name; set_son_query += " SET "; set_son_query += son; set_son_query += "="; set_son_query += to_string(index_median); set_son_query += " WHERE Bof_Region_ID="; set_son_query += to_string(index_parent); if (!mysql_query(db_connection, set_son_query.c_str())) { //cout << "Set Son Value Query: OK"<<endl; } else error_and_exit(); } /** * Insère les distances à la racine dans le champ mu **/ void Bof_db_Region::update_distances(int parent, int direction, Bof_Region &root) { Vector distances; Vector ids; int offset = 0; while (true) { //###################################### // Sélection des 1000 premières régions //###################################### MYSQL_RES *result = NULL; MYSQL_ROW row = NULL; string distances_query = "SELECT Bof_Region_ID, "; for (unsigned int k=1; k<=nb_k_centers;k++) { distances_query += " Coeff"; distances_query += to_string(k); if (k!= nb_k_centers) distances_query += " ,"; else distances_query += " FROM "; } distances_query += table_name; distances_query += " WHERE parent = "; distances_query += to_string(parent); distances_query += " and direction = "; distances_query += to_string(direction); distances_query += " LIMIT "; distances_query += to_string(MAX_ROWS_BY_DISTANCE_REQUEST); distances_query += " OFFSET "; distances_query += to_string(offset); if (!mysql_query(db_connection, distances_query.c_str())) { //cout << "# of distances of query: OK" << endl; } else error_and_exit(); result = mysql_use_result(db_connection); unsigned int num_champs = mysql_num_fields(result); //on stocke les valeurs de la ligne choisie ids.clear(); distances.clear(); int nb_results = 0; while (row = mysql_fetch_row(result)) { ids.push_back(strtodouble(row[0])); //On fait une boucle pour avoir la valeur de chaque champ Vector feat; for (int i = 1; i < num_champs; i++) feat.push_back(strtodouble(row[i])); double dist = Bof_Region(feat, this->fdb) - root; distances.push_back(dist); nb_results ++; } if (nb_results == 0) //Mise à jour des distances finie! break; //######################################## // Insertion des 1000 distances calculées //######################################## string distances_insertion_query = "UPDATE "; distances_insertion_query += table_name; distances_insertion_query += " SET Mu = CASE Bof_Region_ID "; for (int i=0; i<nb_results; ++i) { distances_insertion_query += " WHEN "; distances_insertion_query += to_string(ids[i]); distances_insertion_query += " THEN "; distances_insertion_query += to_string(distances[i]); } distances_insertion_query += " ELSE Mu END"; if (mysql_query(db_connection, distances_insertion_query.c_str())) error_and_exit(); mysql_free_result(result); if (nb_results != MAX_ROWS_BY_DISTANCE_REQUEST) //Il n'y a pas plus de 1000 résultats => break; offset += nb_results; } } /** * Calcul de la médiane par le serveur SQL (prend en paramètres le nombre de décimales) * Nécessite d'installer la fonction médiane de UDF **/ double Bof_db_Region::get_median(int parent, int direction) { // REQUETE SQL string get_median_query = "SELECT median(Mu,10) FROM "; // 10 : nb de chiffres significatifs de la fonction median get_median_query += table_name; get_median_query += " WHERE Parent="; get_median_query += to_string(parent); get_median_query += " AND Direction="; get_median_query += to_string(direction); if (!mysql_query(db_connection, get_median_query.c_str())) { //cout << "Get median query: OK"<<endl; } else error_and_exit(); //RECUPERATION DU CONTENU //Declaration des pointeurs de structure MYSQL_RES *result = NULL; MYSQL_ROW row = NULL; //On met le jeu de resultat dans le pointeur result result = mysql_use_result(db_connection); row = mysql_fetch_row(result); double median = strtodouble(row[0]); //Liberation du jeu de resultat mysql_free_result(result); return median; } /** * Met à jour les champs Parent et Direction des noeuds membres de l'ensemble considéré **/ void Bof_db_Region::set_parent_direction_fields(int parent, int direction, double median, int index_median) { string set_son_query = "UPDATE "; set_son_query += table_name; set_son_query += " SET Parent="; set_son_query += to_string(index_median); set_son_query += ", Direction=(SIGN(Mu-"; set_son_query += to_string(median); set_son_query += ")+1)/2+1"; set_son_query += " WHERE Parent="; set_son_query += to_string(parent); set_son_query += " AND Direction="; set_son_query += to_string(direction); if (!mysql_query(db_connection, set_son_query.c_str())) { //cout << "Set Parent and Direction fields query: OK"<<endl; } else error_and_exit(); } /** * Update le champ Mu de la racine trouvée **/ void Bof_db_Region::set_mu_value(int index_root, double median) { string set_son_query = "UPDATE "; set_son_query += table_name; set_son_query += " SET Mu="; set_son_query += to_string(median); set_son_query += " WHERE Bof_Region_ID="; set_son_query += to_string(index_root); if (!mysql_query(db_connection, set_son_query.c_str())) { //cout << "Add-bof-query: OK"<<endl; } else error_and_exit(); } /** * Obtenir le nombre de noeuds dans chaque sous-arbre **/ int Bof_db_Region::count_elems(int parent, int direction, unsigned int not_this_one) { string set_son_query = "SELECT COUNT(*) FROM "; set_son_query += table_name; if (parent != -1) { set_son_query += " WHERE Parent="; set_son_query += to_string(parent); set_son_query += " AND Direction="; set_son_query += to_string(direction); } if (not_this_one != 0) { set_son_query += " AND BOF_Region_ID != "; set_son_query += to_string(not_this_one); } if (!mysql_query(db_connection, set_son_query.c_str())) { //cout << "Count elements query: OK"<<endl; } else error_and_exit(); //RECUPERATION DU CONTENU //Declaration des pointeurs de structure MYSQL_RES *result = NULL; MYSQL_ROW row = NULL; //On met le jeu de resultat dans le pointeur result result = mysql_use_result(db_connection); row = mysql_fetch_row(result); int nb = strtodouble(row[0]); //Liberation du jeu de resultat mysql_free_result(result); return nb; } /** * Change le champ parent à la ligne index **/ void Bof_db_Region::set_parent_direction(int index, int index_parent, int direction) { string set_son_query = "UPDATE "; set_son_query += table_name; set_son_query += " SET Parent="; set_son_query += to_string(index_parent); set_son_query += " ,Direction="; set_son_query += to_string(direction); set_son_query += " WHERE Bof_Region_ID="; set_son_query += to_string(index); if (!mysql_query(db_connection, set_son_query.c_str())) { //cout << "Set Son Value Query: OK"<<endl; } else error_and_exit(); } void Bof_db_Region::get_bof_number(int index, Bof_Region &res, double &mu, double &son1, double &son2) { //RECUPERATION DU CONTENU //Declaration des pointeurs de structure MYSQL_RES *result = NULL; MYSQL_ROW row = NULL; string random_query = "SELECT Mu, Son1, Son2, "; for (unsigned int k=1; k<=this->nb_k_centers;k++) { random_query+=" Coeff"; random_query+=to_string(k); if (k!= this->nb_k_centers) random_query+=" ,"; } random_query += " FROM "; random_query += table_name; random_query+=" WHERE Bof_Region_ID = "; random_query+=to_string(index); if (!mysql_query(db_connection, random_query.c_str())) { //cout << "Random query (Random) : OK"<<endl; } else error_and_exit(); result = mysql_use_result(db_connection); Vector histo_centers; histo_centers.resize(this->nb_k_centers); row = mysql_fetch_row(result); if (!row) { cout << "Pas de bof ayant le numero " << index << endl; error_and_exit(); } mu = strtodouble(row[0]); son1 = strtodouble(row[1]); son2 = strtodouble(row[2]); for (int j=0; j<this->nb_k_centers;j++) histo_centers[j] = strtodouble(row[j+3]); res = Bof_Region(histo_centers, this->fdb); //Liberation du jeu de resultat mysql_free_result(result); } unsigned int Bof_db_Region::get_root_node() { //RECUPERATION DU CONTENU //Declaration des pointeurs de structure MYSQL_RES *result = NULL; MYSQL_ROW row = NULL; string random_query = "SELECT Bof_Region_ID FROM "; random_query += table_name; random_query+=" WHERE Parent = 0"; if (mysql_query(db_connection, random_query.c_str())) error_and_exit(); result = mysql_use_result(db_connection); row = mysql_fetch_row(result); unsigned int root_index = strtodouble(row[0]); //Liberation du jeu de resultat mysql_free_result(result); return root_index; } unsigned int Bof_db_Region::find_nearest_leaf(Bof_Region &bof) { cout << endl << "Recherche dans le VP-Tree..." << endl; //Déclaration des variables de la fonction unsigned int root_index = this->get_root_node(); cout << "Le parent est le noeud " << root_index << endl << endl; std::vector<unsigned int> nodes_to_search; nodes_to_search.push_back(root_index); bool first = true; double distance_max = INT_MAX; unsigned int nearest = 0; int noeuds_parcourus = 0; //Tant qu'il y a des noeuds dans lesquels rechercher... while (!nodes_to_search.empty()) { noeuds_parcourus++; unsigned int search_node = nodes_to_search.back(); nodes_to_search.pop_back(); cout << "Recherche dans le sous-arbre " << search_node << endl; Bof_Region root_bof; double mu, son1, son2; this->get_bof_number(search_node, root_bof, mu, son1, son2); double dist_to_node = root_bof - bof; if (dist_to_node < distance_max) { nearest = search_node; distance_max = dist_to_node; } //Si on est au tout en haut de l'arbre, on recherche dans les deux sous-arbres if (first) { nodes_to_search.push_back(son1); nodes_to_search.push_back(son2); distance_max = dist_to_node; first = false; cout << endl; continue; } //Si la distance est inférieure au seuil + distance_max, on recherche à l'intérieur if ((dist_to_node < mu + distance_max) && (son1 !=0 )) { nodes_to_search.push_back(son1); cout << "Recherche dans le sous-arbre gauche" << endl; } //Si la distance est supérieure au seuil - distance_max, on recherche à l'extérieur if ((dist_to_node > mu - distance_max) && (son2 != 0)) { nodes_to_search.push_back(son2); cout << "Recherche dans le sous-arbre droit" << endl; } cout << endl; } cout << noeuds_parcourus << " / " << this->count_elems(-1, 0, 0) << " noeuds parcourus!" << endl; cout << "Le BOF le plus proche est le " << nearest << endl; cout << "La distance minimale est: " << distance_max << endl; return nearest; }
[ [ [ 1, 828 ] ] ]
a2320babb2cf1aeb56bae3240769df593edb2442
10c14a95421b63a71c7c99adf73e305608c391bf
/gui/kernel/qpalette.h
e8f083acc463ed9739e82232031317ea9bd34370
[]
no_license
eaglezzb/wtlcontrols
73fccea541c6ef1f6db5600f5f7349f5c5236daa
61b7fce28df1efe4a1d90c0678ec863b1fd7c81c
refs/heads/master
2021-01-22T13:47:19.456110
2009-05-19T10:58:42
2009-05-19T10:58:42
33,811,815
0
0
null
null
null
null
UTF-8
C++
false
false
13,249
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 QPALETTE_H #define QPALETTE_H #include <QtGui/qwindowdefs.h> #include <QtGui/qcolor.h> #include <QtGui/qbrush.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifdef QT3_SUPPORT class QColorGroup; #endif class QPalettePrivate; //class QVariant; class Q_GUI_EXPORT QPalette { // Q_GADGET // Q_ENUMS(ColorGroup ColorRole) public: QPalette(); QPalette(const QColor &button); QPalette(Qt::GlobalColor button); QPalette(const QColor &button, const QColor &window); QPalette(const QBrush &windowText, const QBrush &button, const QBrush &light, const QBrush &dark, const QBrush &mid, const QBrush &text, const QBrush &bright_text, const QBrush &base, const QBrush &window); QPalette(const QColor &windowText, const QColor &window, const QColor &light, const QColor &dark, const QColor &mid, const QColor &text, const QColor &base); #ifdef QT3_SUPPORT QT3_SUPPORT_CONSTRUCTOR QPalette(const QColorGroup &active, const QColorGroup &disabled, const QColorGroup &inactive); #endif QPalette(const QPalette &palette); ~QPalette(); QPalette &operator=(const QPalette &palette); //operator QVariant() const; // Do not change the order, the serialization format depends on it enum ColorGroup { Active, Disabled, Inactive, NColorGroups, Current, All, Normal = Active }; enum ColorRole { WindowText, Button, Light, Midlight, Dark, Mid, Text, BrightText, ButtonText, Base, Window, Shadow, Highlight, HighlightedText, Link, LinkVisited, // ### Qt 5: remove AlternateBase, NoRole, // ### Qt 5: value should be 0 or -1 ToolTipBase, ToolTipText, NColorRoles = ToolTipText + 1, Foreground = WindowText, Background = Window // ### Qt 5: remove }; inline ColorGroup currentColorGroup() const { return static_cast<ColorGroup>(current_group); } inline void setCurrentColorGroup(ColorGroup cg) { current_group = cg; } inline const QColor &color(ColorGroup cg, ColorRole cr) const { return brush(cg, cr).color(); } const QBrush &brush(ColorGroup cg, ColorRole cr) const; inline void setColor(ColorGroup cg, ColorRole cr, const QColor &color); inline void setColor(ColorRole cr, const QColor &color); inline void setBrush(ColorRole cr, const QBrush &brush); bool isBrushSet(ColorGroup cg, ColorRole cr) const; void setBrush(ColorGroup cg, ColorRole cr, const QBrush &brush); void setColorGroup(ColorGroup cr, const QBrush &windowText, const QBrush &button, const QBrush &light, const QBrush &dark, const QBrush &mid, const QBrush &text, const QBrush &bright_text, const QBrush &base, const QBrush &window); bool isEqual(ColorGroup cr1, ColorGroup cr2) const; inline const QColor &color(ColorRole cr) const { return color(Current, cr); } inline const QBrush &brush(ColorRole cr) const { return brush(Current, cr); } inline const QBrush &foreground() const { return brush(WindowText); } inline const QBrush &windowText() const { return brush(WindowText); } inline const QBrush &button() const { return brush(Button); } inline const QBrush &light() const { return brush(Light); } inline const QBrush &dark() const { return brush(Dark); } inline const QBrush &mid() const { return brush(Mid); } inline const QBrush &text() const { return brush(Text); } inline const QBrush &base() const { return brush(Base); } inline const QBrush &alternateBase() const { return brush(AlternateBase); } inline const QBrush &toolTipBase() const { return brush(ToolTipBase); } inline const QBrush &toolTipText() const { return brush(ToolTipText); } inline const QBrush &background() const { return brush(Window); } inline const QBrush &window() const { return brush(Window); } inline const QBrush &midlight() const { return brush(Midlight); } inline const QBrush &brightText() const { return brush(BrightText); } inline const QBrush &buttonText() const { return brush(ButtonText); } inline const QBrush &shadow() const { return brush(Shadow); } inline const QBrush &highlight() const { return brush(Highlight); } inline const QBrush &highlightedText() const { return brush(HighlightedText); } inline const QBrush &link() const { return brush(Link); } inline const QBrush &linkVisited() const { return brush(LinkVisited); } #ifdef QT3_SUPPORT inline QT3_SUPPORT QPalette copy() const { QPalette p = *this; p.detach(); return p; } QT3_SUPPORT QColorGroup normal() const; inline QT3_SUPPORT void setNormal(const QColorGroup &cg) { setColorGroup(Active, cg); } QT3_SUPPORT QColorGroup active() const; QT3_SUPPORT QColorGroup disabled() const; QT3_SUPPORT QColorGroup inactive() const; inline QT3_SUPPORT void setActive(const QColorGroup &cg) { setColorGroup(Active, cg); } inline QT3_SUPPORT void setDisabled(const QColorGroup &cg) { setColorGroup(Disabled, cg); } inline QT3_SUPPORT void setInactive(const QColorGroup &cg) { setColorGroup(Inactive, cg); } #endif bool operator==(const QPalette &p) const; inline bool operator!=(const QPalette &p) const { return !(operator==(p)); } bool isCopyOf(const QPalette &p) const; int serialNumber() const; qint64 cacheKey() const; QPalette resolve(const QPalette &) const; inline uint resolve() const { return resolve_mask; } inline void resolve(uint mask) { resolve_mask = mask; } private: void setColorGroup(ColorGroup cr, const QBrush &windowText, const QBrush &button, const QBrush &light, const QBrush &dark, const QBrush &mid, const QBrush &text, const QBrush &bright_text, const QBrush &base, const QBrush &alternate_base, const QBrush &window, const QBrush &midlight, const QBrush &button_text, const QBrush &shadow, const QBrush &highlight, const QBrush &highlighted_text, const QBrush &link, const QBrush &link_visited); void setColorGroup(ColorGroup cr, const QBrush &windowText, const QBrush &button, const QBrush &light, const QBrush &dark, const QBrush &mid, const QBrush &text, const QBrush &bright_text, const QBrush &base, const QBrush &alternate_base, const QBrush &window, const QBrush &midlight, const QBrush &button_text, const QBrush &shadow, const QBrush &highlight, const QBrush &highlighted_text, const QBrush &link, const QBrush &link_visited, const QBrush &toolTipBase, const QBrush &toolTipText); #ifdef QT3_SUPPORT friend class QColorGroup; void setColorGroup(ColorGroup, const QColorGroup &); QColorGroup createColorGroup(ColorGroup) const; #endif void init(); void detach(); QPalettePrivate *d; uint current_group : 4; uint resolve_mask : 28; friend Q_GUI_EXPORT QDataStream &operator<<(QDataStream &s, const QPalette &p); }; inline void QPalette::setColor(ColorGroup acg, ColorRole acr, const QColor &acolor) { setBrush(acg, acr, QBrush(acolor)); } inline void QPalette::setColor(ColorRole acr, const QColor &acolor) { setColor(All, acr, acolor); } inline void QPalette::setBrush(ColorRole acr, const QBrush &abrush) { setBrush(All, acr, abrush); } #ifdef QT3_SUPPORT class Q_GUI_EXPORT QColorGroup : public QPalette { public: inline QColorGroup() : QPalette() {} inline QColorGroup(const QBrush &foreground, const QBrush &button, const QBrush &light, const QBrush &dark, const QBrush &mid, const QBrush &text, const QBrush &bright_text, const QBrush &base, const QBrush &background) : QPalette(foreground, button, light, dark, mid, text, bright_text, base, background) {} inline QColorGroup(const QColor &foreground, const QColor &background, const QColor &light, const QColor &dark, const QColor &mid, const QColor &text, const QColor &base) : QPalette(foreground, background, light, dark, mid, text, base) {} inline QColorGroup(const QColorGroup &cg) : QPalette(cg) {} inline QColorGroup(const QPalette &pal) : QPalette(pal) {} bool operator==(const QColorGroup &other) const; inline bool operator!=(const QColorGroup &other) const { return !(operator==(other)); } operator QVariant() const; inline QT3_SUPPORT const QColor &foreground() const { return color(WindowText); } inline QT3_SUPPORT const QColor &button() const { return color(Button); } inline QT3_SUPPORT const QColor &light() const { return color(Light); } inline QT3_SUPPORT const QColor &dark() const { return color(Dark); } inline QT3_SUPPORT const QColor &mid() const { return color(Mid); } inline QT3_SUPPORT const QColor &text() const { return color(Text); } inline QT3_SUPPORT const QColor &base() const { return color(Base); } inline QT3_SUPPORT const QColor &background() const { return color(Window); } inline QT3_SUPPORT const QColor &midlight() const { return color(Midlight); } inline QT3_SUPPORT const QColor &brightText() const { return color(BrightText); } inline QT3_SUPPORT const QColor &buttonText() const { return color(ButtonText); } inline QT3_SUPPORT const QColor &shadow() const { return color(Shadow); } inline QT3_SUPPORT const QColor &highlight() const { return color(Highlight); } inline QT3_SUPPORT const QColor &highlightedText() const { return color(HighlightedText); } inline QT3_SUPPORT const QColor &link() const { return color(Link); } inline QT3_SUPPORT const QColor &linkVisited() const { return color(LinkVisited); } }; // // #ifndef QT_NO_DATASTREAM // Q_GUI_EXPORT QT3_SUPPORT QDataStream &operator<<(QDataStream &ds, const QColorGroup &cg); // Q_GUI_EXPORT QT3_SUPPORT QDataStream &operator>>(QDataStream &ds, QColorGroup &cg); // #endif inline QColorGroup QPalette::inactive() const { return createColorGroup(Inactive); } inline QColorGroup QPalette::disabled() const { return createColorGroup(Disabled); } inline QColorGroup QPalette::active() const { return createColorGroup(Active); } inline QColorGroup QPalette::normal() const { return createColorGroup(Active); } #endif /***************************************************************************** QPalette stream functions *****************************************************************************/ // #ifndef QT_NO_DATASTREAM // Q_GUI_EXPORT QDataStream &operator<<(QDataStream &ds, const QPalette &p); // Q_GUI_EXPORT QDataStream &operator>>(QDataStream &ds, QPalette &p); // #endif // QT_NO_DATASTREAM QT_END_NAMESPACE QT_END_HEADER #endif // QPALETTE_H
[ "zhangyinquan@0feb242a-2539-11de-a0d7-251e5865a1c7" ]
[ [ [ 1, 262 ] ] ]
0093648ad28b3a4e52538db673919ec8eefbd409
9df4b47eb2d37fd7f08b8e723e17f733fd21c92b
/plugintemplate/serverplugin/serverplugin_engine.cpp
04efaa00f0826fae8ae0e3d120a2ea49e5b4f0f5
[]
no_license
sn4k3/sourcesdk-plugintemplate
d5a806f8793ad328b21cf8e7af81903c98b07143
d89166b79a92b710d275c817be2fb723f6be64b5
refs/heads/master
2020-04-09T07:11:55.754168
2011-01-23T22:58:09
2011-01-23T22:58:09
32,112,282
1
0
null
null
null
null
ISO-8859-1
C++
false
false
28,847
cpp
//========= Copyright © 2010-2011, Tiago Conceição, All rights reserved. ============ // Plugin Template // // Please Read (LICENSE.txt) and (README.txt) // Dont Forget Visit: // (http://www.sourceplugins.com) -> VPS Plugins // (http://www.sourcemm.net) (http://forums.alliedmods.net/forumdisplay.php?f=52) - MMS Plugins // //=================================================================================== #include "includes/default.h" #include PLUGIN_MAIN_INCLUDE // Interfaces from the engine IVEngineServer *VAR_IFACE_ENGINE = NULL; // helper functions (messaging clients, loading content, making entities, running commands, etc) IGameEventManager2 *VAR_IFACE_GAMEEVENTMANAGER = NULL; // game events interface IEffects *VAR_IFACE_EFFECTS = NULL; IPlayerInfoManager *VAR_IFACE_PLAYERINFOMANAGER = NULL; // game dll interface to interact with players IBotManager *VAR_IFACE_BOTMANAGER = NULL; // game dll interface to interact with bots IServerPluginHelpers *VAR_IFACE_SERVERPLUGINHELPERS = NULL; // special 3rd party plugin helpers from the engine IUniformRandomStream *VAR_IFACE_RANDOMSTREAM = NULL; // Random IFileSystem *VAR_IFACE_FILESYSTEM = NULL; // File I/O ICvar *VAR_IFACE_ICVAR = NULL; // CVars IVoiceServer *VAR_IFACE_VOICESERVER = NULL; // Voice server IEngineTrace *VAR_IFACE_ENGINETRACE = NULL; // Engine trace IServerGameClients *VAR_IFACE_SERVERCLIENTS = NULL; // Server clients IServerGameEnts *VAR_IFACE_SERVERGAMEENTS = NULL; // Server entities INetworkStringTableContainer *VAR_IFACE_NETWORKSTRINGTABLE = NULL; // String tables INetworkStringTable *downloadablestable = NULL; // Downloads IServerGameDLL *VAR_IFACE_GAMESERVERDLL = NULL; // Game server dll IEngineSound *VAR_IFACE_SOUNDS = NULL; // sound CGlobalVars *VAR_IFACE_GLOBALVARS = NULL; // Globals #ifdef WIN32 #pragma warning( disable : 4706 ) //C4706: assignment within conditional expression #endif #ifdef SOURCEMM #ifdef SM_HOOK_PLUGINCALLBACK_SERVERACTIVATE SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int); #endif #ifdef SM_HOOK_PLUGINCALLBACK_GAMEFRAME SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, 0, bool); #endif #ifdef USE_IFACE_SERVERCLIENTS #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTACTIVE SH_DECL_HOOK2_void(IServerGameClients, ClientActive, SH_NOATTRIB, 0, edict_t *, bool); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTDISCONNECT SH_DECL_HOOK1_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, edict_t *); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTPUTINSERVER SH_DECL_HOOK2_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, edict_t *, char const *); #endif #ifdef SM_HOOK_PLUGINCALLBACK_SETCOMMANDCLIENT SH_DECL_HOOK1_void(IServerGameClients, SetCommandClient, SH_NOATTRIB, 0, int); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTSETTINGSCHANGED SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, edict_t *); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTCONNECT SH_DECL_HOOK5(IServerGameClients, ClientConnect, SH_NOATTRIB, 0, bool, edict_t *, const char*, const char *, char *, int); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTCOMMAND #if SOURCE_ENGINE >= SE_ORANGEBOX SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &); #else SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *); #endif #endif #ifdef SM_HOOK_PLUGINCALLBACK_NETWORKIDVALIDATED SH_DECL_HOOK2_void(IServerGameClients, NetworkIDValidated, SH_NOATTRIB, 0, const char *, const char *); #endif #endif #endif /** * Something like this is needed to register cvars/CON_COMMANDs. */ class BaseAccessor : public IConCommandBaseAccessor { public: bool RegisterConCommandBase(ConCommandBase *pCommandBase) { const char *name = pCommandBase->GetName(); unsigned int len = strlen(name); if(len > 0) { if(pCommandBase->IsCommand()) { if(LIB_STRING_CLASS::StrLeftEq(name, PLUGIN_CONCOMMAND_NAME_PREFIX)) { //unsigned int prefixlen = strlen(PLUGIN_CONCOMMAND_NAME_PREFIX); //prefixedname = CStringLib::SubStr(name, prefixlen, len); VAR_PLUGIN_CONVARS->concommands.AddToTail((ConCommand*)pCommandBase); } } else { if(LIB_STRING_CLASS::StrLeftEq(name, PLUGIN_CONVAR_NAME_PREFIX)) { //unsigned int prefixlen = strlen(PLUGIN_CONVAR_NAME_PREFIX); //prefixedname = CStringLib::SubStr(name, prefixlen, len); VAR_PLUGIN_CONVARS->convars.AddToTail((ConVar*)pCommandBase); } } } #ifdef SOURCEMM /* Always call META_REGCVAR instead of going through the engine. */ return META_REGCVAR(pCommandBase); #else #if SOURCE_ENGINE <= SE_DARKMESSIAH pCommandBase->AddFlags( FCVAR_PLUGIN ); #endif // Unlink from plugin only list pCommandBase->SetNext(NULL); //Msg("CONVAR: %s\n", pCommandBase->GetName()); // Link to engine's list instead #if SOURCE_ENGINE <= SE_DARKMESSIAH VAR_IFACE_ICVAR->RegisterConCommandBase( pCommandBase ); #else VAR_IFACE_ICVAR->RegisterConCommand( pCommandBase ); #endif #endif return true; } } s_BaseAccessor; //--------------------------------------------------------------------------------- // Purpose: constructor/destructor //--------------------------------------------------------------------------------- SERVERPLUGIN_ENGINE_CLASS::SERVERPLUGIN_ENGINE_CLASS() { m_iClientCommandIndex = 0; } SERVERPLUGIN_ENGINE_CLASS::~SERVERPLUGIN_ENGINE_CLASS() { } #ifdef SOURCEMM void SERVERPLUGIN_ENGINE_CLASS::OnVSPListening(IServerPluginCallbacks *iface) { SERVERPLUGIN_CALLBACKS_VAR = iface; } /** * @brief Called when all plugins have been loaded. * * This is called after DLLInit(), and thus the mod has been mostly initialized. * It is also safe to assume that all other (automatically loaded) plugins are now * ready to start interacting, because they are all loaded. * MMS ONLY */ void SERVERPLUGIN_ENGINE_CLASS::AllPluginsLoaded() { } #endif //--------------------------------------------------------------------------------- // Purpose: called when the plugin is loaded, load the interface we need from the engine //--------------------------------------------------------------------------------- #ifdef SOURCEMM bool SERVERPLUGIN_ENGINE_CLASS::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlength, bool late) #else bool SERVERPLUGIN_ENGINE_CLASS::Load(CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory ) #endif { #ifdef SOURCEMM PLUGIN_SAVEVARS(); CreateInterfaceFn interfaceFactory = ismm->GetEngineFactory(); CreateInterfaceFn gameServerFactory = ismm->GetServerFactory(); #endif PLUGIN_GET_INTERFACE_CURRENT(interfaceFactory, VAR_IFACE_ENGINE, IVEngineServer, INTERFACEVERSION_VENGINESERVER) PLUGIN_GET_INTERFACE_CURRENT(gameServerFactory, VAR_IFACE_PLAYERINFOMANAGER, IPlayerInfoManager, INTERFACEVERSION_PLAYERINFOMANAGER) PLUGIN_GET_INTERFACE_CURRENT(interfaceFactory, VAR_IFACE_SERVERPLUGINHELPERS, IServerPluginHelpers, INTERFACEVERSION_ISERVERPLUGINHELPERS) #if SOURCE_ENGINE <= SE_DARKMESSIAH PLUGIN_GET_INTERFACE_CURRENT(interfaceFactory, VAR_IFACE_FILESYSTEM, IFileSystem, FILESYSTEM_INTERFACE_VERSION); PLUGIN_GET_INTERFACE_CURRENT(interfaceFactory, VAR_IFACE_ICVAR, ICvar, CVAR_INTERFACE_VERSION); #endif #ifdef USE_IFACE_BOTMANAGER PLUGIN_GET_INTERFACE_CURRENT(gameServerFactory, VAR_IFACE_BOTMANAGER, IBotManager, INTERFACEVERSION_PLAYERBOTMANAGER); #endif #ifdef USE_IFACE_VOICESERVER PLUGIN_GET_INTERFACE_CURRENT(interfaceFactory, VAR_IFACE_VOICESERVER, IVoiceServer, INTERFACEVERSION_VOICESERVER); #endif #ifdef USE_IFACE_GAMEEVENTMANAGER PLUGIN_GET_INTERFACE_CURRENT(interfaceFactory, VAR_IFACE_GAMEEVENTMANAGER, IGameEventManager2, INTERFACEVERSION_GAMEEVENTSMANAGER2) #endif #ifdef USE_IFACE_EFFECTS PLUGIN_GET_INTERFACE_ANY(gameServerFactory, VAR_IFACE_EFFECTS, IEffects, IEFFECTS_INTERFACE_VERSION) #endif #ifdef USE_IFACE_RANDOMSTREAM PLUGIN_GET_INTERFACE_CURRENT(interfaceFactory, VAR_IFACE_RANDOMSTREAM, IUniformRandomStream, VENGINE_SERVER_RANDOM_INTERFACE_VERSION) #endif #ifdef USE_IFACE_ENGINETRACE PLUGIN_GET_INTERFACE_ANY(interfaceFactory, VAR_IFACE_ENGINETRACE, IEngineTrace, INTERFACEVERSION_ENGINETRACE_SERVER) #endif #ifdef USE_IFACE_SERVERCLIENTS PLUGIN_GET_INTERFACE_ANY(gameServerFactory, VAR_IFACE_SERVERCLIENTS, IServerGameClients, INTERFACEVERSION_SERVERGAMECLIENTS) #endif #ifdef USE_IFACE_SERVERGAMEENTS PLUGIN_GET_INTERFACE_ANY(gameServerFactory, VAR_IFACE_SERVERGAMEENTS, IServerGameEnts, INTERFACEVERSION_SERVERGAMEENTS) #endif PLUGIN_GET_INTERFACE_ANY(gameServerFactory, VAR_IFACE_GAMESERVERDLL, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL) /*"ServerGameDLL006"*/ #ifdef USE_IFACE_NETWORKSTRINGTABLE PLUGIN_GET_INTERFACE_CURRENT(interfaceFactory, VAR_IFACE_NETWORKSTRINGTABLE, INetworkStringTableContainer, INTERFACENAME_NETWORKSTRINGTABLESERVER) #endif #ifdef USE_IFACE_SOUNDS PLUGIN_GET_INTERFACE_CURRENT(interfaceFactory, VAR_IFACE_SOUNDS, IEngineSound, IENGINESOUND_SERVER_INTERFACE_VERSION) #endif #if SOURCE_ENGINE >= SE_ORANGEBOX ConnectTier1Libraries( &interfaceFactory, 1 ); ConnectTier2Libraries( &interfaceFactory, 1 ); VAR_IFACE_ICVAR = g_pCVar; VAR_IFACE_FILESYSTEM = g_pFullFileSystem; #else g_pCVar = VAR_IFACE_ICVAR; #endif #ifdef SOURCEMM /* Load the VSP listener. This is usually needed for IServerPluginHelpers. */ if ((SERVERPLUGIN_CALLBACKS_VAR = ismm->GetVSPInfo(NULL)) == NULL) { ismm->AddListener(this, this); ismm->EnableVSPListener(); } VAR_IFACE_GLOBALVARS = ismm->GetCGlobals(); #ifdef SM_HOOK_PLUGINCALLBACK_SERVERACTIVATE SH_ADD_HOOK_MEMFUNC(IServerGameDLL, ServerActivate, VAR_IFACE_GAMESERVERDLL, this, &SERVERPLUGIN_ENGINE_CLASS::ServerActivate, true); #endif #ifdef SM_HOOK_PLUGINCALLBACK_GAMEFRAME SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, VAR_IFACE_GAMESERVERDLL, this, &SERVERPLUGIN_ENGINE_CLASS::GameFrame, true); #endif #ifdef USE_IFACE_SERVERCLIENTS #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTACTIVE SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientActive, VAR_IFACE_SERVERCLIENTS, this, &SERVERPLUGIN_ENGINE_CLASS::ClientActive, true); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTDISCONNECT SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientDisconnect, VAR_IFACE_SERVERCLIENTS, this, &SERVERPLUGIN_ENGINE_CLASS::ClientDisconnect, true); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTPUTINSERVER SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientPutInServer, VAR_IFACE_SERVERCLIENTS, this, &SERVERPLUGIN_ENGINE_CLASS::ClientPutInServer, true); #endif #ifdef SM_HOOK_PLUGINCALLBACK_SETCOMMANDCLIENT SH_ADD_HOOK_MEMFUNC(IServerGameClients, SetCommandClient, VAR_IFACE_SERVERCLIENTS, this, &SERVERPLUGIN_ENGINE_CLASS::SetCommandClient, true); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTSETTINGSCHANGED SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientSettingsChanged, VAR_IFACE_SERVERCLIENTS, this, &SERVERPLUGIN_ENGINE_CLASS::ClientSettingsChanged, false); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTCONNECT SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientConnect, VAR_IFACE_SERVERCLIENTS, this, &SERVERPLUGIN_ENGINE_CLASS::ClientConnect, false); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTCOMMAND SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientCommand, VAR_IFACE_SERVERCLIENTS, this, &SERVERPLUGIN_ENGINE_CLASS::ClientCommand, false); #endif #ifdef SM_HOOK_PLUGINCALLBACK_NETWORKIDVALIDATED SH_ADD_HOOK_MEMFUNC(IServerGameClients, NetworkIDValidated, VAR_IFACE_SERVERCLIENTS, this, &SERVERPLUGIN_ENGINE_CLASS::NetworkIDValidated, true); #endif #endif #else SERVERPLUGIN_CALLBACKS_VAR = this; VAR_IFACE_GLOBALVARS = VAR_IFACE_PLAYERINFOMANAGER->GetGlobalVars(); #endif // Assign classes if(!PLUGIN_GLOBALS_CLASS::InitInterfaces(interfaceFactory, gameServerFactory)) return false; // Assign classes LIB_LIBRARIES_CLASS::Assign(); // Set some globals VAR_PLUGIN_GLOBALS->iMaxclients = VAR_IFACE_GLOBALVARS->maxClients; VAR_IFACE_ENGINE->GetGameDir(VAR_PLUGIN_GLOBALS->szGameDir, 1024); VAR_PLUGIN_GLOBALS->szGameFolder = LIB_STRING_CLASS::StrGetLastPath(VAR_PLUGIN_GLOBALS->szGameDir); VAR_PLUGIN_GLOBALS->szGameName = VAR_IFACE_GAMESERVERDLL->GetGameDescription(); MathLib_Init( 2.2f, 2.2f, 0.0f, 2 ); #if SOURCE_ENGINE >= SE_ORANGEBOX ConVar_Register(0, &s_BaseAccessor); #else ConCommandBaseMgr::OneTimeInit(&s_BaseAccessor); #endif VAR_PLUGIN_GLOBALS->bPluginLoaded = true; #ifdef PYTHON isPythonEnabled = EnablePython(); VAR_PLUGIN_PYTHON->OnPythonLoad(isPythonEnabled); #ifdef PYTHON_DIE_ON_FAIL if(PYTHON_DIE_ON_FAIL && !isPythonEnabled) return false; #endif #endif return PLUGIN_VAR->Load(interfaceFactory, gameServerFactory); } //--------------------------------------------------------------------------------- // Purpose: called when the plugin is unloaded (turned off) //--------------------------------------------------------------------------------- #ifdef SOURCEMM bool SERVERPLUGIN_ENGINE_CLASS::Unload(char *error, size_t maxlen) #else void SERVERPLUGIN_ENGINE_CLASS::Unload( void ) #endif { //gameeventmanager->RemoveListener( this ); // make sure we are unloaded from the event system #ifdef SOURCEMM #ifdef SM_HOOK_PLUGINCALLBACK_SERVERACTIVATE SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, ServerActivate, VAR_IFACE_GAMESERVERDLL, this, &SERVERPLUGIN_ENGINE_CLASS::ServerActivate, true); #endif #ifdef SM_HOOK_PLUGINCALLBACK_GAMEFRAME SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, VAR_IFACE_GAMESERVERDLL, this, &SERVERPLUGIN_ENGINE_CLASS::GameFrame, true); #endif #ifdef USE_IFACE_SERVERCLIENTS #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTACTIVE SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientActive, serverclients, this, &SERVERPLUGIN_ENGINE_CLASS::ClientActive, true); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTDISCONNECT SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientDisconnect, serverclients, this, &SERVERPLUGIN_ENGINE_CLASS::ClientDisconnect, true); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTPUTINSERVER SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientPutInServer, serverclients, this, &SERVERPLUGIN_ENGINE_CLASS::ClientPutInServer, true); #endif #ifdef SM_HOOK_PLUGINCALLBACK_SETCOMMANDCLIENT SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, SetCommandClient, serverclients, this, &SERVERPLUGIN_ENGINE_CLASS::SetCommandClient, true); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTSETTINGSCHANGED SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientSettingsChanged, serverclients, this, &SERVERPLUGIN_ENGINE_CLASS::ClientSettingsChanged, false); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTCONNECT SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientConnect, serverclients, this, &SERVERPLUGIN_ENGINE_CLASS::ClientConnect, false); #endif #ifdef SM_HOOK_PLUGINCALLBACK_CLIENTCOMMAND SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientCommand, serverclients, this, &SERVERPLUGIN_ENGINE_CLASS::ClientCommand, false); #endif #ifdef SM_HOOK_PLUGINCALLBACK_NETWORKIDVALIDATED SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, NetworkIDValidated, serverclients, this, &SERVERPLUGIN_ENGINE_CLASS::NetworkIDValidated, false); #endif #endif #endif #ifdef USE_LIB_EASYADMIN #ifdef SETTING_LIB_EASYADMIN_FILE #ifdef SETTING_LIB_EASYADMIN_LOADFROM #ifdef SETTING_LIB_EASYADMIN_AUTOSAVE if(SETTING_LIB_EASYADMIN_FILE && SETTING_LIB_EASYADMIN_AUTOSAVE) { switch(SETTING_LIB_EASYADMIN_LOADFROM) { case LIB_EASYADMIN_CLASS::TextFile: VAR_LIB_EASYADMIN->SaveToFile(SETTING_LIB_EASYADMIN_FILE); break; case LIB_EASYADMIN_CLASS::Keyvalues: VAR_LIB_EASYADMIN->SaveToKeyvalue(SETTING_LIB_EASYADMIN_FILE); break; case LIB_EASYADMIN_CLASS::IniFile: VAR_LIB_EASYADMIN->SaveToIni(SETTING_LIB_EASYADMIN_FILE); break; } } #endif #endif #endif #endif PLUGIN_VAR->Unload(); #if SOURCE_ENGINE >= SE_ORANGEBOX ConVar_Unregister( ); DisconnectTier2Libraries( ); DisconnectTier1Libraries( ); #endif LIB_LIBRARIES_CLASS::UnAssign(); CMD_PAUSE; } //--------------------------------------------------------------------------------- // Purpose: called when the plugin is paused (i.e should stop running but isn't unloaded) //--------------------------------------------------------------------------------- #ifdef SOURCEMM bool SERVERPLUGIN_ENGINE_CLASS::Pause(char *error, size_t maxlen) #else void SERVERPLUGIN_ENGINE_CLASS::Pause( void ) #endif { PLUGIN_VAR->Pause(); CMD_PAUSE; } //--------------------------------------------------------------------------------- // Purpose: called when the plugin is unpaused (i.e should start executing again) //--------------------------------------------------------------------------------- #ifdef SOURCEMM bool SERVERPLUGIN_ENGINE_CLASS::Unpause(char *error, size_t maxlen) #else void SERVERPLUGIN_ENGINE_CLASS::UnPause( void ) #endif { PLUGIN_VAR->UnPause(); CMD_PAUSE; } //--------------------------------------------------------------------------------- // Purpose: the name of this plugin, returned in "plugin_print" command //--------------------------------------------------------------------------------- #ifdef SOURCEMM const char *SERVERPLUGIN_ENGINE_CLASS::GetDescription() #else const char *SERVERPLUGIN_ENGINE_CLASS::GetPluginDescription( void ) #endif { #ifdef SOURCEMM return PLUGIN_ABOUT; #endif return PLUGIN_DESCRIPTION; } //--------------------------------------------------------------------------------- // Purpose: called on level start //--------------------------------------------------------------------------------- #ifdef SOURCEMM void SERVERPLUGIN_ENGINE_CLASS::OnLevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background) #else void SERVERPLUGIN_ENGINE_CLASS::LevelInit(char const *pMapName) #endif { VAR_PLUGIN_GLOBALS->szCurrentMap = pMapName; VAR_PLUGIN_GLOBALS->iLevelChanges++; #ifdef USE_LIB_DOWNLOAD VAR_LIB_DOWNLOAD->DispatchDownloads(); #endif if(VAR_LIB_PLAYERMNGR) VAR_LIB_PLAYERMNGR->Reset(); #ifdef USE_LIB_TIMER VAR_LIB_TIMER->Reset(); #endif PLUGIN_VAR->LevelInit(pMapName, VAR_PLUGIN_GLOBALS->szOldMap); } //--------------------------------------------------------------------------------- // Purpose: called on level start, when the server is ready to accept client connections // edictCount is the number of entities in the level, clientMax is the max client count //--------------------------------------------------------------------------------- void SERVERPLUGIN_ENGINE_CLASS::ServerActivate(edict_t *pEdictList, int edictCount, int clientMax) { PLUGIN_VAR->ServerActivate(pEdictList, edictCount, clientMax); } //--------------------------------------------------------------------------------- // Purpose: called once per server frame, do recurring work here (like checking for timeouts) //--------------------------------------------------------------------------------- void SERVERPLUGIN_ENGINE_CLASS::GameFrame(bool simulating) { #ifdef USE_LIB_TIMER VAR_LIB_TIMER->CheckTimers(); #endif PLUGIN_VAR->GameFrame(simulating); } //--------------------------------------------------------------------------------- // Purpose: called on level end (as the server is shutting down or going to a new map) //--------------------------------------------------------------------------------- #ifdef SOURCEMM void SERVERPLUGIN_ENGINE_CLASS::OnLevelShutdown() #else void SERVERPLUGIN_ENGINE_CLASS::LevelShutdown( void ) // !!!!this can get called multiple times per map change #endif { #ifdef USE_IFACE_GAMEEVENTMANAGER if(VAR_IFACE_GAMEEVENTMANAGER) VAR_IFACE_GAMEEVENTMANAGER->RemoveListener(VAR_PLUGIN_GAMEEVENTS); #endif if(VAR_PLUGIN_GLOBALS->szCurrentMap) VAR_PLUGIN_GLOBALS->szOldMap = LIB_STRING_CLASS::StrNew(VAR_PLUGIN_GLOBALS->szCurrentMap); PLUGIN_VAR->LevelShutdown(); } //--------------------------------------------------------------------------------- // Purpose: called when a client spawns into a server (i.e as they begin to play) //--------------------------------------------------------------------------------- #ifdef SOURCEMM void SERVERPLUGIN_ENGINE_CLASS::ClientActive(edict_t *pEntity, bool bLoadGame) #else void SERVERPLUGIN_ENGINE_CLASS::ClientActive(edict_t *pEntity) #endif { if(VAR_LIB_PLAYERMNGR) VAR_LIB_PLAYERMNGR->AddClient(pEntity); PLUGIN_VAR->ClientActive(pEntity); } //--------------------------------------------------------------------------------- // Purpose: called when a client leaves a server (or is timed out) //--------------------------------------------------------------------------------- void SERVERPLUGIN_ENGINE_CLASS::ClientDisconnect(edict_t *pEntity) { if(VAR_LIB_PLAYERMNGR) VAR_LIB_PLAYERMNGR->RemoveClient(pEntity); PLUGIN_VAR->ClientDisconnect(pEntity); } //--------------------------------------------------------------------------------- // Purpose: called on //--------------------------------------------------------------------------------- void SERVERPLUGIN_ENGINE_CLASS::ClientPutInServer(edict_t *pEntity, char const *playername) { PLUGIN_VAR->ClientPutInServer(pEntity, playername); } //--------------------------------------------------------------------------------- // Purpose: called on level start //--------------------------------------------------------------------------------- void SERVERPLUGIN_ENGINE_CLASS::SetCommandClient(int index) { m_iClientCommandIndex = index; PLUGIN_VAR->SetCommandClient(index); } //--------------------------------------------------------------------------------- // Purpose: called when the client change a setting (i.e name) //--------------------------------------------------------------------------------- void SERVERPLUGIN_ENGINE_CLASS::ClientSettingsChanged(edict_t *pEdict) { PLUGIN_VAR->ClientSettingsChanged(pEdict); } //--------------------------------------------------------------------------------- // Purpose: called when a client joins a server //--------------------------------------------------------------------------------- #ifdef SOURCEMM bool SERVERPLUGIN_ENGINE_CLASS::ClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen) #else PLUGIN_RESULT SERVERPLUGIN_ENGINE_CLASS::ClientConnect(bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen) #endif { #ifdef SOURCEMM bool *bAllowConnect = (bool*)true; PLUGIN_RESULT result = PLUGIN_VAR->ClientConnect(bAllowConnect, pEntity, pszName, pszAddress, reject, maxrejectlen); if(result == PLUGIN_STOP) return false; return true; #else return PLUGIN_VAR->ClientConnect(bAllowConnect, pEntity, pszName, pszAddress, reject, maxrejectlen); #endif } //--------------------------------------------------------------------------------- // Purpose: called when a client types in a command (only a subset of commands however, not CON_COMMAND's) //--------------------------------------------------------------------------------- CMD_PLUGIN_RESULT SERVERPLUGIN_ENGINE_CLASS::ENGINE_ClientCommand(pEntity) { if (!pEntity || pEntity->IsFree()) CMD_CONTINUE; #ifdef USE_LIB_MENU if(LIB_STRING_CLASS::FStrEq(args.Arg(0), "menuselect")) { if(VAR_LIB_MENU->ClientCommand_MenuSelected(pEntity, atoi(args.Arg(1)))) CMD_OVERRIDE; } #endif #ifndef SOURCEMM return #endif #if SOURCE_ENGINE <= SE_DARKMESSIAH PLUGIN_VAR->ClientCommand(pEntity); #else PLUGIN_VAR->ClientCommand(pEntity, args); #endif } //--------------------------------------------------------------------------------- // Purpose: called when a client is authenticated //--------------------------------------------------------------------------------- CMD_PLUGIN_RESULT SERVERPLUGIN_ENGINE_CLASS::NetworkIDValidated(const char *pszUserName, const char *pszNetworkID) { #ifndef SOURCEMM return #endif PLUGIN_VAR->NetworkIDValidated(pszUserName, pszNetworkID); } //--------------------------------------------------------------------------------- // Purpose: called when a cvar value query is finished //--------------------------------------------------------------------------------- #if SOURCE_ENGINE >= SE_ORANGEBOX void SERVERPLUGIN_ENGINE_CLASS::OnQueryCvarValueFinished(QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue) { //Msg( "Cvar query (cookie: %d, status: %d) - name: %s, value: %s\n", iCookie, eStatus, pCvarName, pCvarValue ); PLUGIN_VAR->OnQueryCvarValueFinished(iCookie, pPlayerEntity, eStatus, pCvarName, pCvarValue); } #endif //--------------------------------------------------------------------------------- // Purpose: called when an event is fired //--------------------------------------------------------------------------------- /*void SERVERPLUGIN_ENGINE_CLASS::FireGameEvent( IGameEvent *event ) { const char * name = event->GetName(); }*/ const char *SERVERPLUGIN_ENGINE_CLASS::GetName() { return PLUGIN_NAME; } const char *SERVERPLUGIN_ENGINE_CLASS::GetVersion() { return PLUGIN_VERSION; } const char *SERVERPLUGIN_ENGINE_CLASS::GetAuthor() { return PLUGIN_ACTOR; } const char *SERVERPLUGIN_ENGINE_CLASS::GetURL() { return PLUGIN_URL; } const char *SERVERPLUGIN_ENGINE_CLASS::GetLicense() { return PLUGIN_LICENSE; } const char *SERVERPLUGIN_ENGINE_CLASS::GetDate() { return __DATE__; } const char *SERVERPLUGIN_ENGINE_CLASS::GetLogTag() { return PLUGIN_NAME; } // // The plugin is a static singleton that is exported as an interface // SERVERPLUGIN_ENGINE_CLASS SERVERPLUGIN_ENGINE_VAR; #ifdef SOURCEMM PLUGIN_EXPOSE(SERVERPLUGIN_ENGINE_CLASS, SERVERPLUGIN_ENGINE_VAR); #else EXPOSE_SINGLE_INTERFACE_GLOBALVAR(SERVERPLUGIN_ENGINE_CLASS, IServerPluginCallbacks, INTERFACEVERSION_ISERVERPLUGINCALLBACKS, SERVERPLUGIN_ENGINE_VAR); #if SOURCE_ENGINE >= SE_ORANGEBOX #ifdef PLUGIN_USE_SOURCEHOOK SourceHook::Impl::CSourceHookImpl g_SourceHook; #endif #else #ifdef PLUGIN_USE_SOURCEHOOK SourceHook::CSourceHookImpl g_SourceHook; #endif #endif #ifdef PLUGIN_USE_SOURCEHOOK SourceHook::ISourceHook *g_SHPtr = &g_SourceHook; int g_PLID = PLUGIN_SOURCEHOOK_ID; #endif #endif IServerPluginCallbacks *SERVERPLUGIN_CALLBACKS_VAR = NULL; int SERVERPLUGIN_ENGINE_CLASS::FormatIface(char iface[], unsigned int maxlength) // From metamod { int length = (int)strlen(iface); int i; int num = 0; for (i = length - 1; i >= 0; i--) { if (!isdigit(iface[i])) { if (i != length - 1) { num = 1; } break; } } if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) ) { return -1; } if (i != length - 1) { num = atoi(&(iface[++i])); } num++; snprintf(&(iface[i]), 4, "%03d", num); return num; } void *SERVERPLUGIN_ENGINE_CLASS::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret) // From metamod { char _if[256]; /* assume no interface goes beyond this */ size_t len = strlen(iface); int num = 0; void *pf = NULL; if (max > IFACE_MAXNUM) { max = IFACE_MAXNUM; } if (len + 4 > sizeof(_if)) { if (ret) { *ret = IFACE_FAILED; } return NULL; } strcpy(_if, iface); do { if ((pf = (fn)(_if, ret)) != NULL) { break; } if (num > max) { break; } } while ((num = FormatIface(_if, len+1))); return pf; } void *SERVERPLUGIN_ENGINE_CLASS::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min) // From metamod { char buffer[256]; /* assume no interface will go beyond this */ size_t len = strlen(iface); int ret; /* just in case something doesn't handle NULL properly */ if (len > sizeof(buffer) - 4) { return NULL; } strcpy(buffer, iface); if (min != -1) { char *ptr = &buffer[len - 1]; int digits = 0; while (isdigit(*ptr) && digits <=3) { *ptr = '\0'; digits++; ptr--; } if (digits != 3) { /* for now, assume this is an error */ strcpy(buffer, iface); } else { char num[4]; min = (min == 0) ? 1 : min; snprintf(num, sizeof(num), "%03d", min); strcat(buffer, num); } } return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret); }
[ "[email protected]@2dd402b7-31f5-573d-f87e-a7bc63fa017b" ]
[ [ [ 1, 784 ] ] ]
496c0683c52e08e2c8c220a801e89678a22058ce
7ede4710c51ee2cad90589e274a5bd587cfcd706
/lsystem-main/d0lsystem.cpp
9bf9e5f9fb11103562b8470197d243febca4ee57
[]
no_license
sid1980/l-system-for-osg
7809b0315d4fd7bcfd49fd11129a273f49ea51d1
4931cc1cb818ee7c9d4d25d17ffdaa567a93e8fa
refs/heads/master
2023-03-16T00:21:40.562005
2011-01-09T16:33:46
2011-01-09T16:33:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,302
cpp
#include "precompiled.h" #include "d0lsystem.h" #include "log.h" using namespace AP_LSystem; D0LSystem::D0LSystem( AbstractFile * file) : LSystem( file ) { this->loadFromFile( file ); } bool D0LSystem::transcribe(multimap<char, Rule> &rules) { int j=0; char * buffer = NULL; LongString * newWord = new LongString( ); multimap<char, Rule>::iterator pRuleIt; for(unsigned int i = 0; i < m_Word->length(); i++ ) { Log::get()->incModuleCounter(); // mozna dodat kontrolu estli jde o pismeno pRuleIt = rules.find( (*m_Word)[i]); // not found if( pRuleIt == rules.end() ) { j = i; buffer = m_Word->getSymbol(i); if(buffer) newWord->append(buffer,i-j+1); } // found else { Log::get()->incRewritingCounter(); // add successor newWord->append( (*pRuleIt->second.staticStrings.begin())->str, (*pRuleIt->second.staticStrings.begin())->length ); } } if(m_Word) delete m_Word; m_Word = newWord; // processCutSymbol(); return true; } void D0LSystem::processPredecessor(Rule & r, string * rule, string::iterator & it) { // process a rule // example: A->BC // predecessor // example: A r.strictPredecessor = *it++; // transcryption sign // example: -> if( (*it++ != '-') || (*it++ != '>') ) { throw ParsingException("Symbol \'->\' was expected!"); } } void D0LSystem::processRuleSuccessor(Rule & r, string * rule, string::iterator & it) { // look for opening bracket - end of static string // each rule has to start with static string r.addStaticString(rule, it); // insert new rule into map with rules this->m_Rules.insert(std::make_pair< char, Rule >(r.strictPredecessor, r )); } void D0LSystem::processHomomorphismSuccessor(Rule & r, string * hom, string::iterator & it) { // homomorphism successor // example: +F(x) r.addStaticString( hom, it ); // insert new rule into map with rules this->m_Homomorphisms.insert(std::make_pair< char, Rule >(r.strictPredecessor, r )); }
[ "[email protected]@3a20e578-abf7-dd4e-6256-36cca5c9e6b5" ]
[ [ [ 1, 90 ] ] ]
6c38c83ac38a0b7c052288194d5d7b23dd1eb3ab
7e68ef369eff945f581e22595adecb6b3faccd0e
/code/linux/minifw/selectreactor.cpp
509e9b812bb6dfb6282577c4785e2c5f4a2322e2
[]
no_license
kimhmadsen/mini-framework
700bb1052227ba18eee374504ff90f41e98738d2
d1983a68c6b1d87e24ef55ca839814ed227b3956
refs/heads/master
2021-01-01T05:36:55.074091
2008-12-16T00:33:10
2008-12-16T00:33:10
32,415,758
0
0
null
null
null
null
UTF-8
C++
false
false
4,038
cpp
#include "stdafx.h" #include "selectreactor.h" SelectReactor* SelectReactor::instance_ = 0; SelectReactor::SelectReactor(void) { sed = new SynchEventDemux(); } SelectReactor::~SelectReactor(void) { } Reactor* SelectReactor::instance(void) { if( instance_ == 0 ) { instance_ = new SelectReactor(); } return instance_; } void SelectReactor::RegisterHandler(EventHandler *eh, Event_Type et) { EventTuple *tempEventTupleVector = new EventTuple(); tempEventTupleVector->eventhandler = eh; tempEventTupleVector->eventtype = et; if(!IsEventHandle(tempEventTupleVector)) listOfEvents.push_back(tempEventTupleVector); } void SelectReactor::RegisterHandler(HANDLE h, EventHandler *eh, Event_Type et) { } void SelectReactor::RemoveHandler(EventHandler *eh, Event_Type et) { EventTuple *tempEventTupleVector = new EventTuple(); tempEventTupleVector->eventhandler = eh; tempEventTupleVector->eventtype = et; for(unsigned int i = 0; i <listOfEvents.size(); i++) if(tempEventTupleVector->eventhandler == listOfEvents.at(i)->eventhandler && tempEventTupleVector->eventtype == listOfEvents.at(i)->eventtype) { EventTuple *memCleanUp = listOfEvents.at(i); listOfEvents.erase(listOfEvents.begin()+i); delete memCleanUp; break; } } void SelectReactor::RemoveHandler(HANDLE h, Event_Type et) const { } void SelectReactor::HandleEvents(struct timeval *timeout) { ConvertFDsToSets(readFDs,writeFDs, exceptFDs); int handleMaximum = FD_SETSIZE; int result = sed->select( handleMaximum, &readFDs, &writeFDs, &exceptFDs, timeout); if(result == SOCKET_ERROR) printf("ERROR"); //printf("ERROR: %d\n", WSAGetLastError()); // comment out if porting, WSAGetLastError is winsock.h else if (result == 0) printf("No result\n"); // Timeout errors perhaps? else { std::vector<EventTuple*> *tempEventTupleVector = new std::vector<EventTuple*>; std::vector<EventTuple*>::iterator iteration = listOfEvents.begin(); while(iteration != listOfEvents.end()) { EventTuple *tuple = new EventTuple(); tuple->eventhandler = (*iteration)->eventhandler; tuple->eventtype = (*iteration)->eventtype; tempEventTupleVector->push_back(tuple); iteration++; } for (int i = 0; i <= handleMaximum-1 && result > 0 && i < (int)tempEventTupleVector->size(); i++) { EventHandler *handlerUpcoming = tempEventTupleVector->at(i)->eventhandler; HANDLE handle = handlerUpcoming->GetHandle(); if (FD_ISSET(handle, &readFDs) ) { handlerUpcoming->HandleEvent(handle, READ_EVENT); result--; } else if (FD_ISSET(handle, &writeFDs) ) { handlerUpcoming->HandleEvent(handle, WRITE_EVENT); result--; } else if (FD_ISSET(handle, &exceptFDs) ) { result--; } } //Memory clean-up std::vector<EventTuple*>::iterator iterationMore = tempEventTupleVector->begin(); while(iterationMore != tempEventTupleVector->end()) { EventTuple *temp = *iterationMore++; delete temp; } tempEventTupleVector->clear(); } } bool SelectReactor::IsEventHandle(EventTuple* t) { for(unsigned int i = 0; i <listOfEvents.size(); i++) if(t->eventhandler == listOfEvents.at(i)->eventhandler && t->eventtype == listOfEvents.at(i)->eventtype) return true; else return false; return false; } void SelectReactor::ConvertFDsToSets(fd_set &readFDs, fd_set &writeFDs, fd_set &exceptFDs) { FD_ZERO(&readFDs); FD_ZERO(&writeFDs); FD_ZERO(&exceptFDs); for (unsigned int i = 0; i < listOfEvents.size(); i++) { if(listOfEvents.at(i)->eventtype == READ_EVENT) FD_SET((SOCKET)listOfEvents.at(i)->eventhandler->GetHandle(), &readFDs); else if (listOfEvents.at(i)->eventtype == WRITE_EVENT) FD_SET((SOCKET)listOfEvents.at(i)->eventhandler->GetHandle(), &writeFDs); else if (listOfEvents.at(i)->eventtype == TIMEOUT_EVENT) FD_SET((SOCKET)listOfEvents.at(i)->eventhandler->GetHandle(), &exceptFDs); } }
[ "mariasolercliment@77f6bdef-6155-0410-8b08-fdea0229669f" ]
[ [ [ 1, 141 ] ] ]
ac98f6f1a539afa88c0553c67bef9c10ef9ff0c0
8b3186e126ac2d19675dc19dd473785de97068d2
/bmt_prod/core/event.cpp
af2af30552afe7a9b428f2ab2a68968446657d55
[]
no_license
leavittx/revenge
e1fd7d6cd1f4a1fb1f7a98de5d16817a0c93da47
3389148f82e6434f0619df47c076c60c8647ed86
refs/heads/master
2021-01-01T17:28:26.539974
2011-08-25T20:25:14
2011-08-25T20:25:14
618,159
2
0
null
null
null
null
UTF-8
C++
false
false
417
cpp
#include "event.h" float Event::getValue() { int time = g_system.getTime(); float value = 0.0f; if (time >= m_time && time < m_time + m_length) { value = (time - m_time) / (float)m_length; } else if (time >= m_time + m_length) { value = 1.0f; } else { value = 0.0f; } return value; } bool Event::hasPassed() { int time = g_system.getTime(); return time >= m_time; }
[ [ [ 1, 27 ] ] ]
9cab94d5892eadcc41c78c03cb44aec33bc5f3c6
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/ThirdParty/luabind/src/exception_handler.cpp
c96a7149c8e327e51f588d88c8e7bd5e6d176810
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
2,037
cpp
// Copyright Daniel Wallin 2005. 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) #define LUABIND_BUILDING #include <luabind/config.hpp> #include <luabind/exception_handler.hpp> #include <luabind/error.hpp> #include <stdexcept> namespace luabind { namespace detail { namespace { exception_handler_base* handler_chain = 0; void push_exception_string( lua_State* L, char const* exception, char const* what ) { lua_pushstring( L, exception ); lua_pushstring( L, ": '" ); lua_pushstring( L, what ); lua_pushstring( L, "'" ); lua_concat( L, 4 ); } } void exception_handler_base::try_next( lua_State* L ) const { if ( next ) next->handle( L ); else throw; } LUABIND_API void handle_exception_aux( lua_State* L ) { try { if ( handler_chain ) handler_chain->handle( L ); else throw; } catch ( error const& ) {} catch ( std::logic_error const& e ) { push_exception_string( L, "std::logic_error", e.what() ); } catch ( std::runtime_error const& e ) { push_exception_string( L, "std::runtime_error", e.what() ); } catch ( std::exception const& e ) { push_exception_string( L, "std::exception", e.what() ); } catch ( char const* str ) { push_exception_string( L, "c-string", str ); } catch ( ... ) { lua_pushstring( L, "Unknown C++ exception" ); } } LUABIND_API void register_exception_handler( exception_handler_base* handler ) { if ( !handler_chain ) handler_chain = handler; else { exception_handler_base* p = handler_chain; for ( ; p->next; p = p->next ) ; handler->next = 0; p->next = handler; } } } } // namespace luabind::detail
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 90 ] ] ]
343514bf11cbbb3e6fc2481e382f4394a467d189
740ed7e8d98fc0af56ee8e0832e3bd28f08cf362
/src/game/megaman_demo/states/BusterC2ShotRight.cpp
6f3cdba38fd65620246f9c87b478a5b1c351de61
[]
no_license
fgervais/armconsoledemogame
420c53f926728b30fe1723733de2f32961a6a6d9
9158c0e684db16c4327b51aec45d1e4eed96b2d4
refs/heads/master
2021-01-10T11:27:43.912609
2010-07-29T18:53:06
2010-07-29T18:53:06
44,270,121
0
0
null
null
null
null
UTF-8
C++
false
false
2,356
cpp
/* * BusterShotRight.cpp * * Created on: 2010-06-07 * Author: Emile */ #include "BusterC2ShotRight.h" #include "Bitmap.h" #include "Buster.h" #include "Physics.h" #include "Environment.h" #include <iostream> using namespace std; BusterState* BusterC2ShotRight::instance = 0; BusterC2ShotRight::BusterC2ShotRight(uint32_t animationWidth, uint32_t animationHeight, Bitmap** animationanimationFrames, uint32_t numberOfFrame, Bitmap** animationMasks) : BusterState(animationWidth, animationHeight, animationanimationFrames, numberOfFrame, animationMasks) { } BusterC2ShotRight::~BusterC2ShotRight() { } BusterState* BusterC2ShotRight::getInstance() { if(instance == 0) { Bitmap** animationFrames = new Bitmap*[5]; animationFrames[0] = new Bitmap("src/display/state/BusterC1ShotRight/1.bmp"); animationFrames[1] = new Bitmap("src/display/state/BusterC1ShotRight/2.bmp"); animationFrames[2] = new Bitmap("src/display/state/BusterC1ShotRight/3.bmp"); animationFrames[3] = new Bitmap("src/display/state/BusterC1ShotRight/4.bmp"); animationFrames[4] = new Bitmap("src/display/state/BusterC1ShotRight/5.bmp"); Bitmap** animationMasks = new Bitmap*[5]; animationMasks[0] = new Bitmap("src/display/state/BusterC1ShotRight/mask1.bmp"); animationMasks[1] = new Bitmap("src/display/state/BusterC1ShotRight/mask2.bmp"); animationMasks[2] = new Bitmap("src/display/state/BusterC1ShotRight/mask3.bmp"); animationMasks[3] = new Bitmap("src/display/state/BusterC1ShotRight/mask4.bmp"); animationMasks[4] = new Bitmap("src/display/state/BusterC1ShotRight/mask5.bmp"); instance = new BusterC2ShotRight(40, 32, animationFrames, 5, animationMasks); } //instance->reset(); return instance; } /* BASE CLASS FUNCTION OVERRIDE */ void BusterC2ShotRight::initialize(Buster* sprite) { if(sprite->getVelocityX() < 0) { // If we are already moving left, skip the first frame sprite->getCurrentFrame(); } else { // This is the hard coded Shot speed // TODO could be (should be?) somewhere defined else? sprite->setVelocity(sprite->getCurrentSpeed(), 0); } } void BusterC2ShotRight::update(Buster* sprite) { // Update current frame if(sprite->getCurrentFrame() == 3) { sprite->setCurrentFrame(3); } else { sprite->incCurrentFrame(); } }
[ "fournierseb2@051cbfc0-75b8-dce1-6088-688cefeb9347" ]
[ [ [ 1, 74 ] ] ]
6ccc7aa4e9a372b492ecfabf49a302dfd9fec083
77aa13a51685597585abf89b5ad30f9ef4011bde
/dep/src/boost/boost/detail/sp_counted_base_cw_x86.hpp
741c961bed68fbeb4d96433115fdb0415c96eaa9
[]
no_license
Zic/Xeon-MMORPG-Emulator
2f195d04bfd0988a9165a52b7a3756c04b3f146c
4473a22e6dd4ec3c9b867d60915841731869a050
refs/heads/master
2021-01-01T16:19:35.213330
2009-05-13T18:12:36
2009-05-14T03:10:17
200,849
8
10
null
null
null
null
UTF-8
C++
false
false
3,259
hpp
#ifndef BOOST_DETAIL_SP_COUNTED_BASE_CW_X86_HPP_INCLUDED #define BOOST_DETAIL_SP_COUNTED_BASE_CW_X86_HPP_INCLUDED // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif // // detail/sp_counted_base_cw_x86.hpp - CodeWarrion on 486+ // // Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd. // Copyright 2004-2005 Peter Dimov // Copyright 2005 Rene Rivera // // 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) // // // Lock-free algorithm by Alexander Terekhov // // Thanks to Ben Hitchings for the #weak + (#shared != 0) // formulation // #include <boost/detail/sp_typeinfo.hpp> namespace boost { namespace detail { inline int atomic_exchange_and_add( int * pw, int dv ) { // int r = *pw; // *pw += dv; // return r; asm { mov esi, [pw] mov eax, dv lock xadd dword ptr [esi], eax } } inline void atomic_increment( int * pw ) { //atomic_exchange_and_add( pw, 1 ); asm { mov esi, [pw] lock inc dword ptr [esi] } } inline int atomic_conditional_increment( int * pw ) { // int rv = *pw; // if( rv != 0 ) ++*pw; // return rv; asm { mov esi, [pw] mov eax, dword ptr [esi] L0: test eax, eax je L1 mov ebx, eax inc ebx lock cmpxchg dword ptr [esi], ebx jne L0 L1: } } class sp_counted_base { private: sp_counted_base( sp_counted_base const & ); sp_counted_base & operator= ( sp_counted_base const & ); int use_count_; // #shared int weak_count_; // #weak + (#shared != 0) public: sp_counted_base(): use_count_( 1 ), weak_count_( 1 ) { } virtual ~sp_counted_base() // nothrow { } // dispose() is called when use_count_ drops to zero, to release // the resources managed by *this. virtual void dispose() = 0; // nothrow // destroy() is called when weak_count_ drops to zero. virtual void destroy() // nothrow { delete this; } virtual void * get_deleter( sp_typeinfo const & ti ) = 0; void add_ref_copy() { atomic_increment( &use_count_ ); } bool add_ref_lock() // true on success { return atomic_conditional_increment( &use_count_ ) != 0; } void release() // nothrow { if( atomic_exchange_and_add( &use_count_, -1 ) == 1 ) { dispose(); weak_release(); } } void weak_add_ref() // nothrow { atomic_increment( &weak_count_ ); } void weak_release() // nothrow { if( atomic_exchange_and_add( &weak_count_, -1 ) == 1 ) { destroy(); } } long use_count() const // nothrow { return static_cast<int const volatile &>( use_count_ ); } }; } // namespace detail } // namespace boost #endif // #ifndef BOOST_DETAIL_SP_COUNTED_BASE_GCC_X86_HPP_INCLUDED
[ "pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88" ]
[ [ [ 1, 158 ] ] ]
d6ade02b1e2c2d10fbefd26ed7c428d85bf099b2
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/interprocess/example/doc_private_node_allocator.cpp
29bae5e503d0433c3e021eadf7a1e48a1c36f453
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,905
cpp
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006-2007. 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/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #include <boost/interprocess/detail/config_begin.hpp> #include <boost/interprocess/detail/workaround.hpp> //[doc_private_node_allocator #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/allocators/private_node_allocator.hpp> #include <cassert> //<- #include "../test/get_process_id_name.hpp" //-> using namespace boost::interprocess; int main () { //Remove shared memory on construction and destruction struct shm_remove { //<- #if 1 shm_remove() { shared_memory_object::remove(test::get_process_id_name()); } ~shm_remove(){ shared_memory_object::remove(test::get_process_id_name()); } #else //-> shm_remove() { shared_memory_object::remove("MySharedMemory"); } ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); } //<- #endif //-> } remover; //Create shared memory //<- #if 1 managed_shared_memory segment(create_only, test::get_process_id_name(), //segment name 65536); #else //-> managed_shared_memory segment(create_only, "MySharedMemory", //segment name 65536); //<- #endif //-> //Create a private_node_allocator that allocates ints from the managed segment //The number of chunks per segment is the default value typedef private_node_allocator<int, managed_shared_memory::segment_manager> private_node_allocator_t; private_node_allocator_t allocator_instance(segment.get_segment_manager()); //Create another private_node_allocator. private_node_allocator_t allocator_instance2(segment.get_segment_manager()); //Although the segment manager address //is the same, this private_node_allocator will have its own pool so //"allocator_instance2" CAN'T deallocate nodes allocated by "allocator_instance". //"allocator_instance2" is NOT equal to "allocator_instance" assert(allocator_instance != allocator_instance2); //Create another node_allocator using copy-constructor. private_node_allocator_t allocator_instance3(allocator_instance2); //This allocator is also unequal to allocator_instance2 assert(allocator_instance2 != allocator_instance3); //Pools are destroyed with the allocators return 0; } //] #include <boost/interprocess/detail/config_end.hpp>
[ "metrix@Blended.(none)" ]
[ [ [ 1, 80 ] ] ]
33e2ff66499b3aa5df95d6746db6ccf3fb27e28b
bda7b365b5952dc48827a8e8d33d11abd458c5eb
/Runnable_PS3/snaviutil.cpp
945c0667b4767a188c6b9a93fdd6ac936615b303
[]
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
8,341
cpp
/* SCE CONFIDENTIAL * PlayStation(R)3 Programmer Tool Runtime Library 330.001 * Copyright (C) 2010 Sony Computer Entertainment Inc. * All Rights Reserved. */ #define __CELL_ASSERT__ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <sys/process.h> #include <sys/ppu_thread.h> #include <sys/paths.h> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <sysutil/sysutil_sysparam.h> #include <sys/sys_time.h> #include <cell/pad.h> #include "snaviutil.h" // for global char gCellSnaviUtilTempBufferForAdjstPath[256]; #define DPRINTF(x) static bool sIsInitialized = false; static bool sIsNavigatorEnable = false; static bool sIsInitPad = false; static const char *sSpawnPath = 0; static const char *sSpawnName = 0; static const char *sSnaviPath = 0; const int32_t PAD_MAX = 7; const int32_t MAIN_PRIO = 1001; const char SIGN_DATA[] = "SNAVI_SPAWN_DATA"; const size_t SIGN_DATA_SIZE = 17; const size_t SPAWN_STACK_MAX = 0x1000; // 4KB const int32_t CellSnaviUtilSnaviContext_VERSION = 1; typedef struct CellSnaviUtilNavigateInfo{ const char *name; const char *navi_path; const char *sample_path; } CellSnaviUtilNavigateInfo; typedef struct CellSnaviUtilSnaviContext{ char signature[32]; int32_t version; int32_t offset; int32_t size; CellSnaviUtilNavigateInfo info; } CellSnaviUtilSnaviContext; // static function static void naviutil_init(void); static void exit_callback(void); static void sysutil_exit_callback(uint64_t status, uint64_t param, void* userinfo); static sys_addr_t get_stack_addr(void); static bool is_exit_input(const CellPadData *pPad); // public function bool cellSnaviUtilCheckValidation(const CellSnaviUtilSnaviContext *info); bool cellSnaviUtilGetSnaviContext(CellSnaviUtilNavigateInfo **pp_info); int32_t cellSnaviUtilSetSnaviContext(CellSnaviUtilNavigateInfo *info, char *buffer, size_t size); void cellSnaviUtilGetStackInfo(sys_addr_t *addr, size_t *size); void naviutil_init(void) { /* check info set by the navigator */ CellSnaviUtilNavigateInfo *pinfo; bool ret = cellSnaviUtilGetSnaviContext(&pinfo); if(ret){ sIsNavigatorEnable = true; sSpawnName = pinfo->name; sSpawnPath = pinfo->sample_path; sSnaviPath = pinfo->navi_path; /* catch exit */ atexit(exit_callback); /* catch exit by the PS button */ cellSysutilRegisterCallback(3, sysutil_exit_callback, NULL); printf("Execute from Navigator: %s\n", sSpawnName); printf(" Sample Home: %s\n", sSpawnPath); }else{ DPRINTF("Navigator Disabled.\n"); } sIsInitialized = true; } bool is_exit_input(const CellPadData *pPad) { if(!pPad) return false; if(pPad->len == 0) return false; bool ret = (pPad->button[CELL_PAD_BTN_OFFSET_DIGITAL1] & CELL_PAD_CTRL_START && pPad->button[CELL_PAD_BTN_OFFSET_DIGITAL1] & CELL_PAD_CTRL_SELECT && pPad->button[CELL_PAD_BTN_OFFSET_DIGITAL2] & CELL_PAD_CTRL_R1 && pPad->button[CELL_PAD_BTN_OFFSET_DIGITAL2] & CELL_PAD_CTRL_L1 && pPad->button[CELL_PAD_BTN_OFFSET_DIGITAL2] & CELL_PAD_CTRL_R2 && pPad->button[CELL_PAD_BTN_OFFSET_DIGITAL2] & CELL_PAD_CTRL_L2); return ret; } bool cellSnaviUtilIsExitRequested(const CellPadData *pPad) { if(!sIsInitialized){ naviutil_init(); } if(!sIsNavigatorEnable) return false; if(pPad == 0){ CellPadInfo2 pad_info; int32_t cr = cellPadGetInfo2(&pad_info); if(cr == CELL_PAD_ERROR_UNINITIALIZED && sIsInitPad == false){ cellPadInit(PAD_MAX); cr = cellPadGetInfo2(&pad_info); sIsInitPad = true; } if(cr != CELL_PAD_OK) return false; /* check all pad */ for(uint32_t i = 0; i < pad_info.max_connect; ++i){ if((pad_info.port_status[i] && CELL_PAD_STATUS_CONNECTED)==0) continue; CellPadData cpd; int32_t err = cellPadGetData(i, &cpd); if(err != CELL_PAD_OK) continue; if(is_exit_input(&cpd)){ return true; } } }else{ return is_exit_input(pPad); } return false; } const char* cellSnaviUtilAdjustPath(const char* app_home_path, char* buffer) { if(buffer == 0) return app_home_path; if(app_home_path == 0) return app_home_path; if(!sIsInitialized){ naviutil_init(); } if(!sIsNavigatorEnable) return app_home_path; if(strncmp(app_home_path, SYS_APP_HOME, strlen(SYS_APP_HOME)) == 0){ strcpy(buffer, sSpawnPath); strcat(buffer, app_home_path + strlen(SYS_APP_HOME)); printf(" Adjust Path: %s -> %s\n", app_home_path, buffer); return buffer; } return app_home_path; } void exit_callback(void) { if(!sIsInitialized){ naviutil_init(); } if(!sIsNavigatorEnable) return; if(sIsInitPad){ cellPadEnd(); } bool file_exists = false; const char *fname = sSnaviPath; { int fd = open(fname, O_RDONLY); if(fd > 0){ file_exists = true; close(fd); } } if(!file_exists) return; /* refer to the data received when starting this program */ sys_addr_t data = 0; size_t data_size = 0; cellSnaviUtilGetStackInfo(&data, &data_size); /* excute navigator */ exitspawn(fname, 0, 0, data, data_size, MAIN_PRIO, SYS_PROCESS_PRIMARY_STACK_SIZE_32K); } void sysutil_exit_callback(uint64_t status, uint64_t param, void* userdata) { (void) param; (void) userdata; switch(status) { case CELL_SYSUTIL_REQUEST_EXITGAME: /* don't return to the navigator if it ended with the PS button */ sIsNavigatorEnable = false; break; case CELL_SYSUTIL_DRAWING_BEGIN: case CELL_SYSUTIL_DRAWING_END: default: break; } } sys_addr_t get_stack_addr(void) { sys_addr_t addr; sys_ppu_thread_stack_t stack_info; sys_ppu_thread_get_stack_information(&stack_info); addr = stack_info.pst_addr + stack_info.pst_size - SPAWN_STACK_MAX; return addr; } void cellSnaviUtilGetStackInfo(sys_addr_t *addr, size_t *size) { if(addr) *addr = get_stack_addr(); if(size) *size = SPAWN_STACK_MAX; } bool cellSnaviUtilCheckValidation(const CellSnaviUtilSnaviContext *context) { if(!context) return false; int32_t cmp = strncmp(context->signature, SIGN_DATA, SIGN_DATA_SIZE - 1); return (cmp == 0); } bool cellSnaviUtilGetSnaviContext(CellSnaviUtilNavigateInfo **pp_info) { sys_addr_t addr = get_stack_addr(); CellSnaviUtilSnaviContext *context = (CellSnaviUtilSnaviContext *)addr; *pp_info = &context->info; CellSnaviUtilNavigateInfo *ret_info = *pp_info; ret_info->name = 0; ret_info->navi_path = 0; ret_info->sample_path = 0; /* invalid context */ if(!cellSnaviUtilCheckValidation(context)) return false; /* set ptr */ char *ptr_info = (char *)(addr + context->offset); /* get navigator path */ ret_info->navi_path = ptr_info; ptr_info += strlen(ret_info->navi_path) + 1; /* get sample name */ ret_info->name = ptr_info; ptr_info += strlen(ret_info->name) + 1; /* get sample path */ ret_info->sample_path = ptr_info; ptr_info += strlen(ret_info->sample_path) + 1; return true; } int32_t cellSnaviUtilSetSnaviContext(CellSnaviUtilNavigateInfo *info, char *buffer, size_t size) { /* calc size */ size_t path_len = strlen(info->navi_path) + 1; size_t name_len = strlen(info->name) + 1; size_t sample_len = strlen(info->sample_path) + 1; size_t header_size = sizeof(CellSnaviUtilSnaviContext); size_t info_size = sample_len + name_len + path_len + 1; size_t all_size = info_size + header_size; /* buffer shortage */ if(all_size > size){ return size - all_size; } if(!buffer) return 0; char *ptr = buffer; /* set context */ CellSnaviUtilSnaviContext *context = (CellSnaviUtilSnaviContext *)ptr; /* set signature */ memmove(context->signature, SIGN_DATA, SIGN_DATA_SIZE); /* set header */ context->version = CellSnaviUtilSnaviContext_VERSION; context->offset = sizeof(CellSnaviUtilSnaviContext); context->size = info_size; ptr += context->offset; /* set info */ memmove(ptr, info->navi_path, path_len); ptr += path_len; memmove(ptr, info->name, name_len); ptr += name_len; memmove(ptr, info->sample_path, sample_len); ptr += sample_len; ptr[0] = '\0'; return all_size; }
[ "leavesmaple@383b229b-c81f-2bc2-fa3f-61d2d0c0fe69" ]
[ [ [ 1, 344 ] ] ]
05de26dc5e892aafd08a4fefcd32814ec615ef9b
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestnote/inc/bctestnoteappUi.h
795e08cd107981c5e445a4a919688b4d06a12d96
[]
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,214
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Declares test bc for note control appui. * */ #ifndef C_CBCTESTNOTEAPPUI_H #define C_CBCTESTNOTEAPPUI_H #include <aknviewappui.h> class CBCTestNoteView; /** * Application UI class */ class CBCTestNoteAppUi : public CAknViewAppUi { public: // Constructors and destructor /** * ctor */ CBCTestNoteAppUi(); /** * symbian 2nd ctor */ void ConstructL(); /** * dtor */ virtual ~CBCTestNoteAppUi(); private: // From CEikAppUi /** * From CEikAppUi */ void HandleCommandL( TInt aCommand ); private: // data /** * pointer to the view. * own */ CBCTestNoteView* iView; }; #endif // C_CBCTESTNOTEAPPUI_H
[ "none@none" ]
[ [ [ 1, 66 ] ] ]
24c79899fd2d809c9f3b395ead7c69533c0e44d7
acdd40ba1461a72c5bcf79b83a70fd236641015d
/inc/MainForm.h
c30317317a6aeec1aa342eeec6e16639c23e9729
[]
no_license
drstrangecode/Bada_ListView_AddRemove_SampleApp
2967e2154c0cc4809127ec3bd1b354e0c8a057db
a15484476eaa37a6f439bc09f62601e3f2701151
refs/heads/master
2016-09-06T13:29:28.344256
2011-12-11T14:26:58
2011-12-11T14:26:58
2,612,798
1
0
null
null
null
null
UTF-8
C++
false
false
2,674
h
#ifndef _MAINFORM_H_ #define _MAINFORM_H_ #include <FBase.h> #include <FUi.h> #include <FGraphics.h> #include <FApp.h> class MainForm : public Osp::Ui::Controls::Form, public Osp::Ui::IActionEventListener, public Osp::Ui::Controls::IListViewItemEventListener, public Osp::Ui::Controls::IListViewItemProvider { // Construction public: MainForm(void); virtual ~MainForm(void); bool Initialize(void); static const int ID_FORMAT_STRING = 100; static const int ID_FORMAT_BITMAP = 101; static const int ACTION_ID_ADD_ITEM = 101; static const int ACTION_ID_DELETE_LAST_ITEM = 102; // Implementation protected: Osp::Ui::Controls::ListView *pListView; public: virtual result OnInitializing(void); virtual result OnTerminating(void); // IActionEventListener virtual void OnActionPerformed(const Osp::Ui::Control & source, int actionId); // IListViewItemEventListener virtual void OnListViewContextItemStateChanged(Osp::Ui::Controls::ListView &listView, int itemIndex, int elementId, Osp::Ui::Controls::ListContextItemStatus state); virtual void OnListViewItemStateChanged(Osp::Ui::Controls::ListView &listView, int itemIndex, int elementId, Osp::Ui::Controls::ListItemStatus state); virtual void OnListViewItemSwept(Osp::Ui::Controls::ListView &listView, int itemIndex, Osp::Ui::Controls::SweepDirection direction); virtual void OnListViewItemLongPressed(Osp::Ui::Controls::ListView & listView, int itemIndex, int elementId, bool & invokeListViewItemCallback); // IListViewItemProvider virtual int GetItemCount(); virtual Osp::Ui::Controls::ListItemBase* CreateItem(int itemIndex, int itemWidth); virtual bool DeleteItem(int itemIndex, Osp::Ui::Controls::ListItemBase* pItem, int itemWidth); }; #endif //_MAINFORM_H_
[ [ [ 1, 67 ] ] ]
40e1b580d151dc5f931b7500943455f423f7ebe2
701f9ab221639b56c28417ee6f6ee984acb24142
/Src/Force Engine/Game/Game.cpp
d9b226a612d0a3da1b042fb4d2a7839ff22b63e3
[]
no_license
nlelouche/desprog1
2397130e427b4ada83721ecbb1a131682bc73187
71c7839675698e74ca43dd26c4af752e309dccb6
refs/heads/master
2021-01-22T06:33:14.083467
2010-02-26T16:18:39
2010-02-26T16:18:39
32,653,851
0
0
null
null
null
null
UTF-8
C++
false
false
2,216
cpp
/**************************************************************************** Force Engine v0.5 Creado: 28/03/08 Clase: Game.cpp Hecho by: German Battiston AKA Melkor ****************************************************************************/ //--------------------------------------------------------------------------- #include "Game.h" #include <sstream> //--------------------------------------------------------------------------- using namespace std; //--------------------------------------------------------------------------- Game::Game(HINSTANCE hInstance) : m_hInstance(hInstance), m_pkInput(NULL), m_pkTimer(new Timer()), m_pkGraphics(new Graphics()), m_pkWindow(new Window(hInstance)) { /*****/ } //--------------------------------------------------------------------------- Game::~Game() { /*****/ } //--------------------------------------------------------------------------- bool Game::Init() { if(!m_pkWindow->createWindow(800,600)) { return false; } if(!m_pkGraphics->InitDX(m_pkWindow)) { return false; } m_pkInput = new DirectInput(m_pkWindow->m_hInstance, m_pkWindow->m_hWnd); if(!m_pkInput->Init()) { return false; } if(!onInit()) { return false; } m_pkTimer->firstMeasure(); return onInit(); } //--------------------------------------------------------------------------- bool Game::Loop() { assert(m_pkTimer); m_pkTimer->Measure(); m_pkInput->Reacquire(); m_pkGraphics->Clear(); m_pkGraphics->BeginScene(); onLoop(); // Nombre del Engine y Frames Per Second stringstream s; s << "Force Engine v0.5 Beta | FPS: " << m_pkTimer->getFPS(); m_pkWindow->SetWindowTitle(s.str().c_str()); m_pkGraphics->EndScene(); m_pkGraphics->Present(); return true; } //--------------------------------------------------------------------------- bool Game::deInit() { delete m_pkGraphics; m_pkGraphics = NULL; delete m_pkWindow; m_pkWindow = NULL; delete m_pkTimer; m_pkTimer = NULL; m_pkInput->deInit(); delete m_pkInput; m_pkInput = NULL; return true; } //---------------------------------------------------------------------------
[ "gersurfer@a82ef5f6-654a-0410-99b4-23d68ab79cb1" ]
[ [ [ 1, 106 ] ] ]
7bcd1bce5f7c39938f7d0e9bce278b37a8bfefe0
1d2705c9be9ee0f974c224eb794f2f8a9e9a3d50
/octavetest/main.cpp
fee9773f22ae380bbc5ed4aef718bc98aac9229d
[]
no_license
llvllrbreeze/alcorapp
dfe2551f36d346d73d998f59d602c5de46ef60f7
3ad24edd52c19f0896228f55539aa8bbbb011aac
refs/heads/master
2021-01-10T07:36:01.058011
2008-12-16T12:51:50
2008-12-16T12:51:50
47,865,136
0
0
null
null
null
null
UTF-8
C++
false
false
39,903
cpp
#define LTEST6 #ifdef LTEST0 // solving A * X = B // using driver function gesv() #include <cstddef> #include <iostream> #include <complex> #include <boost/numeric/bindings/lapack/gesv.hpp> #include <boost/numeric/bindings/traits/ublas_matrix.hpp> #include <boost/numeric/bindings/traits/std_vector.hpp> #include "utils.h" namespace ublas = boost::numeric::ublas; namespace lapack = boost::numeric::bindings::lapack; using std::size_t; using std::cout; using std::endl; typedef std::complex<double> cmpx_t; typedef ublas::matrix<double, ublas::column_major> m_t; typedef ublas::matrix<cmpx_t, ublas::column_major> cm_t; int main() { cout << endl; cout << "real system:" << endl << endl; size_t n = 5; m_t a (n, n); // system matrix size_t nrhs = 2; m_t x (n, nrhs), b (n, nrhs); // b -- right-hand side matrix std::vector<int> ipiv (n); // pivot vector init_symm (a); // [n n-1 n-2 ... 1] // [n-1 n n-1 ... 2] // a = [n-2 n-1 n ... 3] // [ ... ] // [1 2 ... n-1 n] m_t aa (a); // copy of a, because a is `lost' after gesv() for (int i = 0; i < x.size1(); ++i) { x (i, 0) = 1.; x (i, 1) = 2.; } b = prod (a, x); print_m (a, "A"); cout << endl; print_m (b, "B"); cout << endl; lapack::gesv (a, ipiv, b); // solving the system, b contains x print_m (b, "X"); cout << endl; x = prod (aa, b); print_m (x, "B = A X"); cout << endl; //////////////////////////////////////////////////////// cout << endl; cout << "complex system:" << endl << endl; cm_t ca (3, 3), cb (3, 1), cx (3, 1); std::vector<int> ipiv2 (3); ca (0, 0) = cmpx_t (3, 0); ca (0, 1) = cmpx_t (4, 2); ca (0, 2) = cmpx_t (-7, 5); ca (1, 0) = cmpx_t (4, -2); ca (1, 1) = cmpx_t (-5, 0); ca (1, 2) = cmpx_t (0, -3); ca (2, 0) = cmpx_t (-7, -5); ca (2, 1) = cmpx_t (0, 3); ca (2, 2) = cmpx_t (2, 0); print_m (ca, "CA"); cout << endl; for (int i = 0; i < cx.size1(); ++i) cx (i, 0) = cmpx_t (1, -1); cb = prod (ca, cx); print_m (cb, "CB"); cout << endl; int ierr = lapack::gesv (ca, ipiv2, cb); if (ierr == 0) print_m (cb, "CX"); else cout << "matrix is singular" << endl; cout << endl; getchar(); } #endif #ifdef LTEST1 Permission to copy, use, modify, sell and distribute this software is granted provided this copyright notice appears in all copies. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. Copyright Toon Knapen, Karl Meerbergen #include "random.hpp" #include <boost/numeric/bindings/lapack/geqrf.hpp> #include <boost/numeric/bindings/lapack/ormqr.hpp> #include <boost/numeric/bindings/traits/ublas_matrix.hpp> #include <boost/numeric/bindings/traits/ublas_vector.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/io.hpp> #include <iostream> #include <limits> namespace ublas = boost::numeric::ublas; namespace lapack = boost::numeric::bindings::lapack; // Randomize a matrix template <typename M> void randomize(M& m) { typedef typename M::size_type size_type ; typedef typename M::value_type value_type ; size_type size1 = m.size1() ; size_type size2 = m.size2() ; for (size_type i=0; i<size2; ++i) { for (size_type j=0; j<size1; ++j) { m(j,i) = random_value< value_type >() ; } } } // randomize() template <typename T> struct transpose { static const char value ; }; template <typename T> const char transpose<T>::value = 'T'; template <typename T> struct transpose< std::complex<T> > { static const char value ; }; template <typename T> const char transpose< std::complex<T> >::value = 'C'; template <typename M> ublas::triangular_adaptor<const M, ublas::upper> upper_part(const M& m) { return ublas::triangular_adaptor<const M, ublas::upper>( m ); } template <typename T, typename W> int do_memory_type(int n, W workspace) { typedef typename boost::numeric::bindings::traits::type_traits<T>::real_type real_type ; typedef std::complex< real_type > complex_type ; typedef ublas::matrix<T, ublas::column_major> matrix_type ; typedef ublas::vector<T> vector_type ; // Set matrix matrix_type a( n, n ); vector_type tau( n ); randomize( a ); matrix_type a2( a ); // Compute QR factorization. lapack::geqrf( a, tau, workspace ) ; // Apply the orthogonal transformations to a2 lapack::ormqr( 'L', transpose<T>::value, a, tau, a2, workspace ); // The upper triangular parts of a and a2 must be equal. if (norm_frobenius( upper_part( a - a2 ) ) > std::numeric_limits<real_type>::epsilon() * 10.0 * norm_frobenius( upper_part( a ) ) ) return 255 ; return 0 ; } // do_value_type() template <typename T> int do_value_type() { const int n = 8 ; if (do_memory_type<T,lapack::optimal_workspace>( n, lapack::optimal_workspace() ) ) return 255 ; if (do_memory_type<T,lapack::minimal_workspace>( n, lapack::minimal_workspace() ) ) return 255 ; ublas::vector<T> work( n ); do_memory_type<T, lapack::detail::workspace1<ublas::vector<T> > >( n, lapack::workspace(work) ); return 0; } // do_value_type() int main() { // Run tests for different value_types if (do_value_type<float>()) return 255; if (do_value_type<double>()) return 255; if (do_value_type< std::complex<float> >()) return 255; if (do_value_type< std::complex<double> >()) return 255; std::cout << "Regression test succeeded\n" ; getchar(); return 0; } #endif #ifdef LTEST2 // Permission to copy, use, modify, sell and // distribute this software is granted provided this copyright notice appears // in all copies. This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // Copyright Toon Knapen, Karl Meerbergen #include "random.hpp" #include <boost/numeric/ublas/vector_proxy.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <boost/numeric/bindings/traits/ublas_vector.hpp> #include <boost/numeric/bindings/traits/ublas_matrix.hpp> #include <boost/numeric/bindings/traits/std_vector.hpp> #include <boost/numeric/bindings/blas/blas1.hpp> #include <vector> #include <complex> #include <iostream> #include <limits> #include <cmath> // Randomize a vector (using functions from random.hpp) template <typename V> void randomize(V& v) { for (typename V::size_type i=0; i<v.size(); ++i) v[i] = random_value< typename V::value_type >() ; } // randomize() float abs_sum_value( float const& f ) { using namespace std ; return abs(f) ; } double abs_sum_value( double const& f ) { using namespace std ; return abs(f) ; } float abs_sum_value( std::complex< float > const& f ) { using namespace std ; return abs(f.real()) + abs(f.imag()) ; } double abs_sum_value( std::complex< double > const& f ) { using namespace std ; return abs(f.real()) + abs(f.imag()) ; } template <typename V> typename boost::numeric::bindings::traits::type_traits<typename V::value_type>::real_type abs_sum( V const& v) { typedef typename boost::numeric::bindings::traits::type_traits<typename V::value_type>::real_type real_type ; real_type sum( 0.0 ) ; for ( typename V::size_type i=0; i<v.size(); ++i ) { sum += abs_sum_value( v[i] ) ; } return sum ; } // Blas operations using one vector. template <typename T> struct OneVector { boost::numeric::ublas::vector<T> v_ref_ ; // Initialize : set reference vector (ublas) OneVector() : v_ref_( 10 ) { randomize(v_ref_); } template <typename V> int operator()(V& v) const { using namespace boost::numeric::bindings::blas ; typedef typename V::value_type value_type ; typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ; // Copy vector from reference for (typename V::size_type i=0; i<v_ref_.size(); ++i) v[i] = v_ref_(i); // Test blas routines and compare with reference real_type nrm = nrm2( v ); if ( std::abs(nrm - norm_2(v_ref_)) > std::numeric_limits< real_type >::epsilon() * norm_2(v_ref_)) { std::cout << "nrm2 : " << std::abs(nrm - norm_2(v_ref_)) << " > " << std::numeric_limits< real_type >::epsilon() * norm_2(v_ref_) << std::endl ; return 255 ; } nrm = asum( v ); if ( std::abs(nrm - abs_sum(v_ref_)) > std::numeric_limits< real_type >::epsilon() * abs_sum(v_ref_)) { std::cout << "asum : " << std::abs(nrm - abs_sum(v_ref_)) << " > " << std::numeric_limits< real_type >::epsilon() * abs_sum(v_ref_) << std::endl ; return 255 ; } scal( value_type(2.0), v ); for (typename V::size_type i=0; i<v_ref_.size(); ++i) if (std::abs( v[i] - real_type(2.0)*v_ref_(i) ) > real_type(2.0)*std::abs(v_ref_(i))) return 255 ; return 0; } // Return the size of a vector. size_t size() const {return v_ref_.size();} }; // Operations with two vectors. template <typename T, typename V> struct BaseTwoVectorOperations { typedef T value_type ; typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ; typedef boost::numeric::ublas::vector<T> ref_vector_type ; // Initialize: select the first vector and set the reference vectors (ublas) BaseTwoVectorOperations(V& v, const ref_vector_type& v1_ref, const ref_vector_type& v2_ref) : v_( v ) , v1_ref_( v1_ref ) , v2_ref_( v2_ref ) {} // Copy the 2nd reference vector into w. template <typename W> void copy_vector(W& w) const { for (size_t i=0; i<size(); ++i) { w[i] = v2_ref_(i); } } // copy_vector() // Get the size of a vector. size_t size() const {return v_.size();} // Data members. V& v_ ; const ref_vector_type& v1_ref_, v2_ref_ ; }; template <typename T, typename V> struct TwoVectorOperations { } ; template <typename V> struct TwoVectorOperations< float, V> : BaseTwoVectorOperations<float,V> { typedef typename V::value_type value_type ; typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ; typedef typename BaseTwoVectorOperations<float,V>::ref_vector_type ref_vector_type ; TwoVectorOperations(V& v, const ref_vector_type& v1_ref, const ref_vector_type& v2_ref) : BaseTwoVectorOperations<float,V>( v, v1_ref, v2_ref ) {} // Perform the tests of blas functions and compare with reference template <typename W> int operator()(W& w) const { using namespace boost::numeric::bindings::blas ; copy_vector(w); // Test blas routines value_type prod = dot( this->v_, w ); if ( std::abs(prod - inner_prod( this->v1_ref_, this->v2_ref_ )) > std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ; axpy( value_type(2.0), this->v_, w ); for (size_t i=0; i<this->size(); ++i) if ( std::abs(w[i] - (this->v2_ref_(i) + value_type(2.0)*this->v1_ref_(i))) > std::numeric_limits< real_type >::epsilon() * std::abs(w[i])) return 255 ; scal( value_type(0.0), w ) ; copy( this->v_, w ) ; for (size_t i=0; i<this->size(); ++i) { if ( std::abs( w[i] - this->v_[i] ) != 0.0 ) return 255 ; } return 0; } }; template <typename V> struct TwoVectorOperations< double, V> : BaseTwoVectorOperations<double,V> { typedef typename V::value_type value_type ; typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ; typedef typename BaseTwoVectorOperations<double,V>::ref_vector_type ref_vector_type ; TwoVectorOperations(V& v, const ref_vector_type& v1_ref, const ref_vector_type& v2_ref) : BaseTwoVectorOperations<double,V>( v, v1_ref, v2_ref ) {} // Perform the tests of blas functions and compare with reference template <typename W> int operator()(W& w) const { using namespace boost::numeric::bindings::blas ; copy_vector( w ); // Test blas routines value_type prod = dot( this->v_, w ); if ( std::abs(prod - inner_prod( this->v1_ref_, this->v2_ref_ )) > std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ; axpy( value_type(2.0), this->v_, w ); for (size_t i=0; i<this->size(); ++i) if ( std::abs(w[i] - (this->v2_ref_(i) + value_type(2.0)*this->v1_ref_(i))) > std::numeric_limits< real_type >::epsilon() * std::abs(w[i])) return 255 ; copy_vector( w ) ; scal( value_type(-1.0), w ) ; ::boost::numeric::bindings::blas::copy( this->v_, w ) ; for (size_t i=0; i<this->size(); ++i) { if ( w[i] != this->v_[i] ) return 255 ; } return 0; } }; template <typename V> struct TwoVectorOperations< std::complex<float>, V> : BaseTwoVectorOperations< std::complex<float>, V> { typedef typename V::value_type value_type ; typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ; typedef typename BaseTwoVectorOperations<std::complex<float>,V>::ref_vector_type ref_vector_type ; TwoVectorOperations(V& v, const ref_vector_type& v1_ref, const ref_vector_type& v2_ref) : BaseTwoVectorOperations< std::complex<float>, V>( v, v1_ref, v2_ref ) {} // Perform the tests of blas functions and compare with reference template <typename W> int operator()(W& w) const { using namespace boost::numeric::bindings::blas ; copy_vector( w ); // Test blas routines value_type prod = dotc( this->v_, w ); if ( std::abs(prod - inner_prod( conj(this->v1_ref_), this->v2_ref_ )) > std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ; prod = dotu( this->v_, w ); if ( std::abs(prod - inner_prod( this->v1_ref_, this->v2_ref_ )) > std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ; axpy( value_type(2.0), this->v_, w ); for (size_t i=0; i<this->size(); ++i) if ( std::abs(w[i] - (this->v2_ref_(i) + value_type(2.0)*this->v1_ref_(i))) > std::numeric_limits< real_type >::epsilon() * std::abs(w[i])) return 255 ; scal( value_type(0.0), w ) ; copy( this->v_, w ) ; for (size_t i=0; i<this->size(); ++i) { if ( std::abs( w[i] - this->v_[i] ) != 0.0 ) return 255 ; } return 0; } }; template <typename V> struct TwoVectorOperations< std::complex<double>, V> : BaseTwoVectorOperations< std::complex<double>, V> { typedef typename V::value_type value_type ; typedef typename boost::numeric::bindings::traits::type_traits<value_type>::real_type real_type ; typedef typename BaseTwoVectorOperations<std::complex<double>,V>::ref_vector_type ref_vector_type ; TwoVectorOperations(V& v, const ref_vector_type& v1_ref, const ref_vector_type& v2_ref) : BaseTwoVectorOperations< std::complex<double>, V>( v, v1_ref, v2_ref ) {} // Perform the tests of blas functions and compare with reference template <typename W> int operator()(W& w) const { using namespace boost::numeric::bindings::blas ; copy_vector( w ); // Test blas routines value_type prod = dotc( this->v_, w ); if ( std::abs(prod - inner_prod( conj(this->v1_ref_), this->v2_ref_ )) > std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ; prod = dotu( this->v_, w ); if ( std::abs(prod - inner_prod( this->v1_ref_, this->v2_ref_ )) > std::numeric_limits< real_type >::epsilon() * std::abs(prod)) return 255 ; axpy( value_type(2.0), this->v_, w ); for (size_t i=0; i<this->size(); ++i) if ( std::abs(w[i] - (this->v2_ref_(i) + value_type(2.0)*this->v1_ref_(i))) > std::numeric_limits< real_type >::epsilon() * std::abs(w[i])) return 255 ; scal( value_type(0.0), w ) ; copy( this->v_, w ) ; for (size_t i=0; i<this->size(); ++i) { if ( std::abs( w[i] - this->v_[i] ) != 0.0 ) return 255 ; } return 0; } }; // Run the tests for different types of vectors. template <typename T, typename F> int different_vectors(const F& f) { // Do test for different types of vectors { std::cout << " ublas::vector\n" ; boost::numeric::ublas::vector< T > v(f.size()); if (f( v )) return 255 ; } { std::cout << " std::vector\n" ; std::vector<T> v_ref(f.size()); if (f( v_ref )) return 255 ; } { std::cout << " ublas::vector_range\n" ; typedef boost::numeric::ublas::vector< T > vector_type ; vector_type v(f.size()*2); boost::numeric::ublas::vector_range< vector_type > vr(v, boost::numeric::ublas::range(1,1+f.size())); if (f( vr )) return 255 ; } { typedef boost::numeric::ublas::matrix< T, boost::numeric::ublas::column_major > matrix_type ; matrix_type m(f.size(),f.size()) ; std::cout << " ublas::matrix_column\n" ; boost::numeric::ublas::matrix_column< matrix_type > m_c( m, 2 ); if (f( m_c )) return 255 ; std::cout << " ublas::matrix_row\n" ; boost::numeric::ublas::matrix_row< matrix_type > m_r( m, 1 ); if (f( m_r )) return 255 ; } return 0; } // different_vectors() // This is the functor that selects the first vector of the tests that use two vectors. template <typename T> struct TwoVector { TwoVector() : v1_ref_( 10 ) , v2_ref_( 10 ) {} template <typename V> int operator() (V& v) const { for (size_t i=0; i<size(); ++i) v[i] = v1_ref_(i) ; return different_vectors<T,TwoVectorOperations<T,V> >( TwoVectorOperations<T,V>(v, v1_ref_, v2_ref_) ) ; } size_t size() const { return v1_ref_.size() ; } boost::numeric::ublas::vector<T> v1_ref_ ; boost::numeric::ublas::vector<T> v2_ref_ ; }; // TwoVector // Run the test for a specific value_type T. template <typename T> int do_value_type() { // Tests for functions with one vector argument. std::cout << " one argument\n"; if (different_vectors<T,OneVector<T> >(OneVector<T> ())) return 255 ; // Tests for functions with two vector arguments. std::cout << " two arguments\n"; if (different_vectors<T,TwoVector<T> >(TwoVector<T>())) return 255; return 0; } // do_value_type() int main() { // Run regression for Real/Complex std::cout << "float\n"; if (do_value_type<float>() ) return 255 ; std::cout << "double\n"; if (do_value_type<double>() ) return 255 ; std::cout << "complex<float>\n"; if (do_value_type<std::complex<float> >() ) return 255 ; std::cout << "complex<double>\n"; if (do_value_type<std::complex<double> >() ) return 255 ; std::cout << "Regression test successful\n" ; return 0 ; } #endif #ifdef LTEST4 // Permission to copy, use, modify, sell and // distribute this software is granted provided this copyright notice appears // in all copies. This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // Copyright Toon Knapen, Karl Meerbergen #include "random.hpp" #include <boost/numeric/bindings/traits/transpose.hpp> #include <boost/numeric/bindings/traits/ublas_vector.hpp> #include <boost/numeric/bindings/traits/ublas_matrix.hpp> #include <boost/numeric/bindings/traits/ublas_symmetric.hpp> #include <boost/numeric/bindings/traits/ublas_hermitian.hpp> #include <boost/numeric/bindings/blas/blas3.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <boost/numeric/ublas/symmetric.hpp> #include <boost/numeric/ublas/hermitian.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/io.hpp> #include <iostream> #include <complex> // Randomize a matrix template <typename M> void randomize(M& m) { typedef typename M::size_type size_type ; typedef typename M::value_type value_type ; size_type size1 = m.size1() ; size_type size2 = m.size2() ; for (size_type i=0; i<size2; ++i) { for (size_type j=0; j<size1; ++j) { m(j,i) = random_value< value_type >() ; } } } // randomize() template <typename T> struct RealDiagonal { template <typename M> void operator() (M& m) const {} }; template <typename T> struct RealDiagonal< std::complex<T> > { template <typename M> void operator() (M& m) const { for (typename M::size_type i=0; i<m.size1(); ++i) { m(i,i) = m(i,i).real(); } } }; template <typename M> boost::numeric::ublas::triangular_adaptor<const M, boost::numeric::ublas::unit_upper> unit_upper_part(const M& m) { return boost::numeric::ublas::triangular_adaptor<const M, boost::numeric::ublas::unit_upper> (m); } template <typename M> boost::numeric::ublas::triangular_adaptor<const M, boost::numeric::ublas::upper> upper_part(const M& m) { return boost::numeric::ublas::triangular_adaptor<const M, boost::numeric::ublas::upper> (m); } template <typename M> boost::numeric::ublas::triangular_adaptor<const M, boost::numeric::ublas::lower> lower_part(const M& m) { return boost::numeric::ublas::triangular_adaptor<const M, boost::numeric::ublas::lower> (m); } // Run over all matrix types and aply a functor to it. template <typename F> int do_matrix_types(const F& f) { using namespace boost::numeric::ublas ; typedef typename F::value_type value_type ; { matrix<value_type,column_major> m( f.size1(), f.size2() ); if (f(m)) return 255; } { typedef matrix<value_type,column_major> matrix_type ; matrix_type m( 2*f.size1(), 2*f.size2() ); matrix_range<matrix_type> m_r( m, range(1,1+f.size1()), range(2,2+f.size2()) ); if (f(m_r)) return 255 ; } return 0; } // do_matrix_types() // Functor to select syrk/herk calls given the two matrix_types template <typename M1> struct Syrk2 { typedef typename M1::value_type value_type ; typedef boost::numeric::ublas::matrix<value_type, boost::numeric::ublas::column_major> ref_matrix_type ; typedef typename boost::numeric::bindings::traits::type_traits< value_type >::real_type real_type ; typedef typename ref_matrix_type::size_type size_type ; Syrk2(const M1& a, const ref_matrix_type& a_ref) : a_( a ), a_ref_( a_ref ) , c_ref_( a_ref_.size1(), a_ref_.size1() ) { randomize( c_ref_ ); RealDiagonal<value_type>() (c_ref_); // Must have real diagonal for herk. } template <typename M> int operator() (M& c) const { using namespace boost::numeric::ublas ; real_type alpha = 2.0 ; real_type beta = -3.0 ; c.assign( c_ref_ ); boost::numeric::bindings::blas::syrk( 'U', 'N', value_type(alpha), a_, value_type(beta), c ) ; if ( norm_frobenius( upper_part( c - (beta*c_ref_ + alpha * prod( a_ref_, trans( a_ref_ ) ) ) ) ) > std::numeric_limits< real_type >::epsilon() * norm_frobenius( upper_part(c) ) ) return 255; c.assign( c_ref_ ); symmetric_adaptor<M, upper> c_s( c ); boost::numeric::bindings::blas::syrk( 'U', 'N', value_type(alpha), a_, value_type(beta), c_s ) ; if ( norm_frobenius( upper_part( c_s - (beta*c_ref_ + alpha * prod( a_ref_, trans( a_ref_ ) ) ) ) ) > std::numeric_limits< real_type >::epsilon() * norm_frobenius( upper_part(c_s) ) ) return 255; c.assign( c_ref_ ); boost::numeric::bindings::blas::herk( 'U', 'N', alpha, a_, beta, c ) ; if ( norm_frobenius( upper_part( c - (beta*c_ref_ + alpha * prod( a_ref_, herm( a_ref_ ) ) ) ) ) > std::numeric_limits< real_type >::epsilon() * norm_frobenius( upper_part(c) ) ) return 255; c.assign( c_ref_ ); hermitian_adaptor<M, upper> c_h( c ); boost::numeric::bindings::blas::herk( 'U', 'N', alpha, a_, beta, c_h ) ; if ( norm_frobenius( upper_part( c_h - (beta*c_ref_ + alpha * prod( a_ref_, herm( a_ref_ ) ) ) ) ) > std::numeric_limits< real_type >::epsilon() * norm_frobenius( upper_part(c_h) ) ) return 255; return 0; } size_type size1() const {return c_ref_.size1() ;} size_type size2() const {return c_ref_.size2() ;} const M1& a_ ; const ref_matrix_type& a_ref_; ref_matrix_type c_ref_; }; // Syrk2 template <typename T> struct Syrk1 { typedef T value_type ; typedef boost::numeric::ublas::matrix<value_type, boost::numeric::ublas::column_major> ref_matrix_type ; typedef typename boost::numeric::bindings::traits::type_traits< value_type >::real_type real_type ; typedef typename ref_matrix_type::size_type size_type ; Syrk1() : a_ref_( 4, 7 ) { randomize( a_ref_ ); } template <typename M> int operator() (M& a) const { typedef Syrk2<M> functor_type ; a.assign( a_ref_ ); return do_matrix_types( functor_type(a, a_ref_) ); } size_type size1() const {return a_ref_.size1();} size_type size2() const {return a_ref_.size2();} ref_matrix_type a_ref_; }; // Syrk1 // Functor to select gemm calls given the three matrix_types template <typename M1, typename M2> struct Gemm3 { typedef typename M1::value_type value_type ; typedef boost::numeric::ublas::matrix<value_type, boost::numeric::ublas::column_major> ref_matrix_type ; typedef typename boost::numeric::bindings::traits::type_traits< value_type >::real_type real_type ; typedef typename ref_matrix_type::size_type size_type ; Gemm3(const M1& a, const M2& b, const ref_matrix_type& a_ref, const ref_matrix_type& b_ref) : a_( a ), b_( b ) , a_ref_( a_ref ), b_ref_( b_ref ), c_ref_( a_ref_.size1(), b_ref_.size2() ) { randomize( c_ref_ ); } template <typename M> int operator() (M& c) const { c.assign( c_ref_ ); value_type alpha = 2.0 ; value_type beta = -3.0 ; boost::numeric::bindings::blas::gemm( 'N', 'N', alpha, a_, b_, beta, c ) ; if ( norm_frobenius( c - (beta*c_ref_ + alpha * prod( a_ref_, b_ref_ ) ) ) > std::numeric_limits< real_type >::epsilon() * norm_frobenius( c ) ) return 255; return 0; } size_type size1() const {return c_ref_.size1() ;} size_type size2() const {return c_ref_.size2() ;} const M1& a_ ; const M2& b_ ; const ref_matrix_type& a_ref_, b_ref_; ref_matrix_type c_ref_; }; // Gemm3 template <typename M1> struct Gemm2 { typedef typename M1::value_type value_type ; typedef boost::numeric::ublas::matrix<value_type, boost::numeric::ublas::column_major> ref_matrix_type ; typedef typename boost::numeric::bindings::traits::type_traits< value_type >::real_type real_type ; typedef typename ref_matrix_type::size_type size_type ; Gemm2(const M1& a, const ref_matrix_type& a_ref) : a_( a ) , a_ref_( a_ref ) , b_ref_( a_ref.size2(), 7 ) { randomize( b_ref_ ); } template <typename M> int operator() (M& b) const { typedef Gemm3<M1,M> functor_type ; b.assign( b_ref_ ); return do_matrix_types( functor_type(a_, b, a_ref_, b_ref_) ); } size_type size1() const {return b_ref_.size1();} size_type size2() const {return b_ref_.size2();} const M1& a_ ; const ref_matrix_type& a_ref_; ref_matrix_type b_ref_; }; // Gemm2 template <typename T> struct Gemm1 { typedef T value_type ; typedef boost::numeric::ublas::matrix<value_type, boost::numeric::ublas::column_major> ref_matrix_type ; typedef typename boost::numeric::bindings::traits::type_traits< value_type >::real_type real_type ; typedef typename ref_matrix_type::size_type size_type ; Gemm1() : a_ref_( 4, 7 ) { randomize( a_ref_ ); } template <typename M> int operator() (M& a) const { typedef Gemm2<M> functor_type ; a.assign( a_ref_ ); return do_matrix_types( functor_type(a, a_ref_) ); } size_type size1() const {return a_ref_.size1();} size_type size2() const {return a_ref_.size2();} ref_matrix_type a_ref_; }; // Gemm1 // Functor to select syrk/herk calls given the two matrix_types template <typename M1> struct Trsm2 { typedef typename M1::value_type value_type ; typedef boost::numeric::ublas::matrix<value_type, boost::numeric::ublas::column_major> ref_matrix_type ; typedef typename boost::numeric::bindings::traits::type_traits< value_type >::real_type real_type ; typedef typename ref_matrix_type::size_type size_type ; Trsm2(M1& c, const ref_matrix_type& b_ref, const ref_matrix_type& c_ref ) : c_( c ), c_ref_( c_ref ), b_ref_( b_ref ) , a_ref_( b_ref_.size1(), c_ref_.size2() ) { randomize( a_ref_ ) ; } template <typename M> int operator() (M& a) const { using namespace boost::numeric::ublas ; real_type alpha = 2.0 ; a.assign( a_ref_ ); boost::numeric::bindings::blas::trsm( 'L', 'U', 'N', 'N', value_type(alpha), b_ref_, a ) ; if ( norm_frobenius( alpha * a_ref_ - prod( upper_part(b_ref_), a ) ) > std::numeric_limits< real_type >::epsilon() * norm_frobenius( upper_part(b_ref_) ) * norm_frobenius( a) ) return 255; a.assign( a_ref_ ); boost::numeric::bindings::blas::trsm( 'R', 'U', 'N', 'N', value_type(alpha), c_, a ) ; if ( norm_frobenius( alpha * a_ref_ - prod( a, upper_part(c_) ) ) > std::numeric_limits< real_type >::epsilon() * norm_frobenius( upper_part(c_) ) * norm_frobenius( a ) ) return 255; a.assign( a_ref_ ); boost::numeric::bindings::blas::trsm( 'R', 'L', 'N', 'N', value_type(alpha), c_, a ) ; if ( norm_frobenius( alpha * a_ref_ - prod( a, lower_part(c_) ) ) > std::numeric_limits< real_type >::epsilon() * norm_frobenius( lower_part(c_) ) * norm_frobenius( a ) ) return 255; a.assign( a_ref_ ); boost::numeric::bindings::blas::trsm( 'L', 'U', 'T', 'N', value_type(alpha), b_ref_, a ) ; if ( norm_frobenius( alpha * a_ref_ - prod( trans(upper_part(b_ref_)), a ) ) > std::numeric_limits< real_type >::epsilon() * norm_frobenius( upper_part(b_ref_) ) * norm_frobenius( a) ) return 255; a.assign( a_ref_ ); boost::numeric::bindings::blas::trsm( 'L', 'U', 'N', 'U', value_type(alpha), b_ref_, a ) ; if ( norm_frobenius( alpha * a_ref_ - prod( unit_upper_part(b_ref_), a ) ) > std::numeric_limits< real_type >::epsilon() * norm_frobenius( unit_upper_part(b_ref_) ) * norm_frobenius( a) ) return 255; return 0; } size_type size1() const {return a_ref_.size1() ;} size_type size2() const {return a_ref_.size2() ;} const M1& c_ ; const ref_matrix_type& c_ref_; const ref_matrix_type& b_ref_; ref_matrix_type a_ref_; } ; // Trsm2 template <typename T> struct Trsm1 { typedef T value_type ; typedef boost::numeric::ublas::matrix<value_type, boost::numeric::ublas::column_major> ref_matrix_type ; typedef typename boost::numeric::bindings::traits::type_traits< value_type >::real_type real_type ; typedef typename ref_matrix_type::size_type size_type ; Trsm1() : b_( 4, 4 ) , c_( 7, 7 ) { randomize( b_ ); randomize( c_ ); for ( std::size_t i=0; i<b_.size1(); ++i ) if ( b_(i,i)==value_type(0.0) ) b_(i,i) = value_type(1.0) ; for ( std::size_t i=0; i<c_.size1(); ++i ) if ( c_(i,i)==value_type(0.0) ) c_(i,i) = value_type(1.0) ; } template <typename M> int operator() (M& c) const { typedef Trsm2<M> functor_type ; return do_matrix_types( functor_type(c, b_, c_) ); } size_type size1() const {return c_.size1();} size_type size2() const {return c_.size2();} ref_matrix_type b_; ref_matrix_type c_; } ; // Trsm1 template <typename T> int do_value_type() { // Gemm test if (do_matrix_types( Gemm1<T>() )) return 255 ; // Syrk and herk test if (do_matrix_types( Syrk1<T>() )) return 255 ; // Trsm test if (do_matrix_types( Trsm1<T>() )) return 255 ; return 0 ; } // do_value_type() int main() { // Test for various value_types if (do_value_type<float>()) return 255 ; if (do_value_type<double>()) return 255 ; if (do_value_type<std::complex<float> >()) return 255 ; if (do_value_type<std::complex<double> >()) return 255 ; std::cout << "Regression test succeeded\n" ; return 0 ; } #endif //LTEST4 #ifdef LTEST5 #include <cstddef> #include <iostream> #include <algorithm> #include <boost/numeric/bindings/lapack/gesvd.hpp> #include <boost/numeric/bindings/traits/ublas_matrix.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <boost/numeric/bindings/traits/ublas_vector.hpp> #include <boost/numeric/bindings/traits/std_vector.hpp> #include "utils.h" namespace ublas = boost::numeric::ublas; namespace lapack = boost::numeric::bindings::lapack; using std::size_t; using std::cout; using std::endl; typedef double real_t; typedef ublas::matrix<real_t, ublas::column_major> m_t; typedef ublas::vector<real_t> v_t; int main() { cout << endl; size_t m = 3, n = 4; size_t minmn = m < n ? m : n; m_t a (m, n); a(0,0) = 2.; a(0,1) = 2.; a(0,2) = 2.; a(0,3) = 2.; a(1,0) = 1.7; a(1,1) = 0.1; a(1,2) = -1.7; a(1,3) = -0.1; a(2,0) = 0.6; a(2,1) = 1.8; a(2,2) = -0.6; a(2,3) = -1.8; m_t a2 (a); // for parts 2 & 3 print_m (a, "A"); cout << endl; v_t s (minmn); m_t u (m, minmn); m_t vt (minmn, n); lapack::gesvd (a, s, u, vt); print_v (s, "s"); cout << endl; print_m (u, "U"); cout << endl; print_m (vt, "V^T"); cout << endl << endl; // part 2 // singular values and singular vectors satisfy A v_i == s_i u_i for (int i = 0; i < minmn; ++i) { cout << "A v_" << i << " == s_" << i << " u_" << i << endl; v_t avi = ublas::prod (a2, ublas::row (vt, i)); print_v (avi); v_t siui = s[i] * ublas::column (u, i); print_v (siui); cout << endl; } cout << endl; // singular values and singular vectors satisfy A^T u_i == s_i v_i for (int i = 0; i < minmn; ++i) { cout << "A^T u_" << i << " == s_" << i << " v_" << i << endl; v_t atui = ublas::prod (trans (a2), ublas::column (u, i)); print_v (atui); v_t sivi = s[i] * ublas::row (vt, i); print_v (sivi); cout << endl; } cout << endl; // part 3 lapack::gesvd (a2, s); print_v (s, "singular values only"); cout << endl; } #endif #ifdef LTEST6 //#define BOOST_NUMERIC_BINDINGS_LAPACK_2 #include <cstddef> #include <iostream> #include <algorithm> #include <boost/numeric/bindings/lapack/gesvd.hpp> #include <boost/numeric/bindings/traits/ublas_matrix.hpp> #include <boost/numeric/bindings/traits/ublas_vector.hpp> #include <boost/numeric/bindings/traits/std_vector.hpp> #include "utils.h" namespace ublas = boost::numeric::ublas; namespace lapack = boost::numeric::bindings::lapack; using std::size_t; using std::cout; using std::endl; typedef double real_t; typedef ublas::matrix<real_t, ublas::column_major> m_t; typedef ublas::vector<real_t> v_t; int main() { cout << endl; size_t m = 3, n = 2; size_t minmn = m < n ? m : n; m_t a (m, n); a(0,0) = 1.; a(0,1) = 1.; a(1,0) = 0.; a(1,1) = 1.; a(2,0) = 1.; a(2,1) = 0.; m_t a2 (a); // for part 2 m_t a3 (a); // for part 3 print_m (a, "A"); cout << endl; v_t s (minmn); m_t u (m, m); m_t vt (n, n); size_t lw; #ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2 lw = lapack::gesvd_work ('O', 'N', 'N', a); cout << "opt NN lw: " << lw << endl; lw = lapack::gesvd_work ('O', 'A', 'A', a); cout << "opt AA lw: " << lw << endl; lw = lapack::gesvd_work ('O', 'S', 'S', a); cout << "opt SS lw: " << lw << endl; lw = lapack::gesvd_work ('O', 'O', 'N', a); cout << "opt ON lw: " << lw << endl; lw = lapack::gesvd_work ('O', 'N', 'O', a); cout << "opt NO lw: " << lw << endl; #endif lw = lapack::gesvd_work ('M', 'A', 'A', a); cout << "min lw: " << lw << endl << endl; #ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2 lw = lapack::gesvd_work ('O', 'A', 'A', a); #endif std::vector<real_t> w (lw); lapack::gesvd ('A', 'A', a, s, u, vt, w); print_v (s, "s"); cout << endl; print_m (u, "U"); cout << endl; print_m (vt, "V^T"); cout << endl; m_t sm (m, n); for (size_t i = 0; i < s.size(); ++i) sm (i,i) = s (i); print_m (sm, "S"); cout << endl; a = ublas::prod (u, m_t (ublas::prod (sm, vt))); print_m (a, "A == U S V^T"); cout << endl; // part 2 cout << endl << "part 2" << endl << endl; #ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2 lapack::gesvd ('A', 'A', a2, s, u, vt); #else lapack::gesvd ('M', 'A', 'A', a2, s, u, vt); #endif print_v (s, "s"); cout << endl; print_m (u, "U"); cout << endl; print_m (vt, "V^T"); cout << endl; for (size_t i = 0; i < s.size(); ++i) sm (i,i) = s (i); print_m (sm, "S"); cout << endl; a2 = ublas::prod (u, m_t (ublas::prod (sm, vt))); print_m (a2, "A == U S V^T"); cout << endl; // part 3 cout << endl << "part 3" << endl << endl; #ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2 cout << "opt lw: " << lapack::gesvd_work ('O', 'N', 'N', a3) << endl << endl; lapack::gesvd (a3, s); #else cout << "min lw: " << lapack::gesvd_work ('M', 'N', 'N', a3) << endl << endl; lapack::gesvd ('M', 'N', 'N', a3, s, u, vt); #endif print_v (s, "singular values only"); cout << endl; cout << endl; } #endif
[ "andrea.carbone@1ffd000b-a628-0410-9a29-793f135cad17" ]
[ [ [ 1, 1261 ] ] ]
e0e185b29f2c5406027e56d596da10ce17e23af9
2403c4aa6404b44881e6bff3eb78d1386b2f82ee
/ gogo-dolo --username [email protected]/PICDolo.h
d4064a795413ba61798f6d0ebc3e4e4560f05983
[]
no_license
duwu/gogo-dolo
8ee505bb07b3cffbfb9e1f5be301b3becc3919f6
a15cbfa5a725a0ed20cba2e76115dc9ab4f6f7bc
refs/heads/master
2016-09-12T17:36:16.027532
2011-05-24T07:30:27
2011-05-24T07:30:27
57,050,398
0
0
null
null
null
null
UTF-8
C++
false
false
1,094
h
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #pragma once #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols #include "FavoritesManager.h" // CPICDoloApp: // See PICDolo.cpp for the implementation of this class // class CPICDoloApp : public CWinAppEx { public: CPICDoloApp(); // Override from CWorkspace virtual void PreLoadState (); CFavoritesManager m_Favorites; // Overrides public: virtual BOOL InitInstance(); virtual int ExitInstance(); // Implementation afx_msg void OnAppAbout(); DECLARE_MESSAGE_MAP() void SaveFile(void); afx_msg void OnAppExit(); }; extern CPICDoloApp theApp;
[ [ [ 1, 46 ] ] ]
6f1f25767941cf35cde7035c3f7cae3e1a84d5b1
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/GameComponent.h
c9afb895eab8ecfe00e0fc862aad1d7d4b85f3a0
[]
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
UHC
C++
false
false
2,025
h
#pragma once #ifndef __HALAK_GAMECOMPONENT_H__ #define __HALAK_GAMECOMPONENT_H__ # include <Halak/FWD.h> # include <Halak/IClassQueryable.h> namespace Halak { /// Game이란 Application을 구성하는 요소의 기반 class. class GameComponent : public IClassQueryable { HKClassFOURCC('G', 'C', 'O', 'M'); public: enum Status { DeadStatus, AliveStatus, ActiveStatus }; public: static const uint UnspecifiedID; public: virtual ~GameComponent(); inline uint32 GetID() const; void SetID(uint32 value); inline Status GetStatus() const; inline bool GetAlive() const; void SetAlive(bool value); inline bool GetActive() const; void SetActive(bool value); virtual ICloneable* QueryCloneableInterface(); virtual const ICloneable* QueryCloneableInterface() const; virtual IUpdateable* QueryUpdateableInterface(); virtual const IUpdateable* QueryUpdateableInterface() const; virtual void* QueryClass(uint32 classID); protected: GameComponent(); GameComponent(uint32 id); virtual void OnStatusChanged(Status old); private: GameNode* node; uint32 id; bool alive; bool active; private: GameComponent(const GameComponent&); GameComponent& operator = (const GameComponent&); friend class GameNode; friend class GameStructure; }; } # include <Halak/GameComponent.inl> #endif
[ [ [ 1, 68 ] ] ]
aff1550afdc43994f7b692a6a6cfa7100281ee28
d504537dae74273428d3aacd03b89357215f3d11
/src/main/main_speech.cpp
72a361a899818b40372cdf891267f489b8e091ea
[]
no_license
h0MER247/e6
1026bf9aabd5c11b84e358222d103aee829f62d7
f92546fd1fc53ba783d84e9edf5660fe19b739cc
refs/heads/master
2020-12-23T05:42:42.373786
2011-02-18T16:16:24
2011-02-18T16:16:24
237,055,477
1
0
null
2020-01-29T18:39:15
2020-01-29T18:39:14
null
UTF-8
C++
false
false
2,789
cpp
#include "../e6/e6_sys.h" #include "../e6/e6_impl.h" #include "../e6/e6_enums.h" #include "../Speech/Speech.h" #include "../Net/Net.h" using e6::uint; //int tuio(e6::Engine * e) //{ // struct Printer : Net::Tuio::Callback // { // void call( int mode, Net::Tuio::Object &o ) // { // switch(mode) // { // case 1 : // printf( "set obj %2i %2i [%3.3f %3.3f %3.3f] [%3.3f %3.3f %3.3f] [%3.3f %3.3f]\n",o.id,o.fi,o.x,o.y,o.a,o.X,o.Y,o.A,o.m,o.r ); // break; // case 2 : // printf( "set cur %2i [%3.3f %3.3f] [%3.3f %3.3f] [%3.3f]\n",o.id,o.x,o.y,o.X,o.Y,o.m ); // break; // } // } // } printer; // // Net::Tuio::Listener * tl = (Net::Tuio::Listener*)e->createInterface("Net","Net.Tuio.Listener"); // tl->start( 3333, printer ); // // for( int ever=1; ever; ever ) // ; // // E_RELEASE(tl); // return 0; //} // int main(int argc, char **argv) { char * in = argc>1 ? argv[1] : 0; uint nal = argc>2 ? atoi(argv[2]) : 0; char *topic = argc>3 ? argv[3] : 0; bool r = false; e6::Engine * e = e6::CreateEngine(); //Speech::Voice * sp = (Speech::Voice*) e->createInterface( "Speech", "Speech.Voice" ); //sp->speak("hello world"); //E_RELEASE(sp); struct SPK : Speech::Recognizer::Listener { virtual uint listen( const char * txt, uint ruleID, uint alternation ) { if ( alternation == (Speech::Recognizer::cbAdaption +9000) ) printf( "adapt %s\n", txt ); else if ( alternation == (Speech::Recognizer::cbHypothesis +9000) ) printf( "hyp. %s\n", txt ); else if ( alternation == (Speech::Recognizer::cbInterference +9000) ) printf( ".... %s\n", txt ); else if ( alternation == (Speech::Recognizer::cbFalseReco +9000) ) printf( "false %s\n", txt ); else if ( ! ruleID ) printf( "%4d a%3d %s\n",ruleID, alternation, txt ); else printf( "%4d ok. %s\n",ruleID, txt ); if ( (ruleID == 253) && (!strcmp( txt, "exit" ) ) ) { printf("\n - bye - \n" ); return 0; } return 1; } } spk; Speech::Recognizer * sr = (Speech::Recognizer*) e->createInterface( "Speech", "Speech.Recognizer" ); if ( in ) sr->loadGrammar( in ); if ( nal < 32 ) sr->enableNumAlternates( nal ); if ( topic ) sr->showUI(topic); //sr->adapt( "foo" ); //sr->adapt( "bar" ); //sr->adapt( "mein kleines schweinchen" ); sr->enableCallBack( Speech::Recognizer::cbRecognition | Speech::Recognizer::cbInterference | Speech::Recognizer::cbFalseReco ); //const char* people[] = {"me","my dog","louisa","mom",0}; //sr->addDynamicRule( 23, people, false ); sr->start( &spk, false ); printf( "..stopped..\n"); E_RELEASE(sr); E_RELEASE(e); return r!=0; }
[ [ [ 1, 110 ] ] ]
c06093a08f17f8a43d07946a586b9872d2f299c3
da9b11cab53e4771eaa6c0d2c885e4331580b2f3
/src/node_id.h
8794943d81880c3f2303991ed9b4b32138b640fe
[]
no_license
ud1/dhtpp
305913dea8f3c65d52bdb872aa6f26f5aca7a9a6
016aa4e0b628f92614e9a38e90461cea8bc4df78
refs/heads/master
2021-01-13T16:44:30.537380
2010-05-31T22:22:55
2010-05-31T22:22:55
77,243,109
0
0
null
null
null
null
UTF-8
C++
false
false
3,389
h
#ifndef DHT_NODE_ID_H #define DHT_NODE_ID_H #include "config.h" #include "types.h" namespace dhtpp { // Big endian struct NodeID { uint8 id[NODE_ID_LENGTH_BYTES]; bool operator <(const NodeID &o) const; bool operator <=(const NodeID &o) const; bool operator >=(const NodeID &o) const { return !(*this < o); } bool operator >(const NodeID &o) const { return !(*this <= o); } bool operator ==(const NodeID &o) const; NodeID &operator+=(const NodeID &o); NodeID &operator+=(unsigned int v); NodeID &operator-=(const NodeID &o); NodeID &operator >>= (uint16 f); NodeID &operator ^= (const NodeID &o); }; inline NodeID operator - (const NodeID &f, const NodeID &s) { NodeID res = f; return res -= s; } inline NodeID operator + (const NodeID &f, const NodeID &s) { NodeID res = f; return res += s; } inline NodeID operator + (const NodeID &f, unsigned int v) { NodeID res = f; return res += v; } inline NodeID operator ^ (const NodeID &f, const NodeID &s) { NodeID res = f; return res ^= s; } inline NodeID operator >> (const NodeID &f, uint16 d) { NodeID res = f; return res >>= d; } inline bool NodeID::operator <(const dhtpp::NodeID &o) const { for (int i = 0; i < NODE_ID_LENGTH_BYTES; ++i) { if (id[i] < o.id[i]) return true; if (id[i] > o.id[i]) return false; } return false; } inline bool NodeID::operator <=(const dhtpp::NodeID &o) const { for (int i = 0; i < NODE_ID_LENGTH_BYTES; ++i) { if (id[i] < o.id[i]) return true; if (id[i] > o.id[i]) return false; } return true; } inline bool NodeID::operator ==(const dhtpp::NodeID &o) const { for (int i = 0; i < NODE_ID_LENGTH_BYTES; ++i) { if (id[i] != o.id[i]) return false; } return true; } inline NodeID &NodeID::operator+=(const NodeID &o) { uint8 a = 0; for (uint16 i = NODE_ID_LENGTH_BYTES; i --> 0; ) { uint16 v = id[i] + o.id[i] + a; id[i] = v & 0xff; a = v >> 8; } return *this; } inline NodeID &NodeID::operator+=(unsigned int d) { uint8 a = 0; for (uint16 i = NODE_ID_LENGTH_BYTES; i --> 0 && (d || a); ) { uint16 v = id[i] + (d & 0xff) + a; id[i] = v & 0xff; a = v >> 8; d >>= 8; } return *this; } inline NodeID &NodeID::operator-=(const NodeID &o) { uint8 a = 0; for (uint16 i = NODE_ID_LENGTH_BYTES; i --> 0; ) { uint16 s = a + o.id[i]; if (id[i] < s) { id[i] += 256 - s; a = 1; } else { id[i] -= s; a = 0; } } return *this; } inline NodeID &NodeID::operator >>= (uint16 f) { uint16 o = f / 8; uint16 bts = f % 8; uint16 ibts = 8 - bts; for (uint16 i = NODE_ID_LENGTH_BYTES; i --> o+1; ) { id[i] = (id[i-o] >> bts) | (id[i-o-1] << ibts); } id[o] = id[0] >> bts; return *this; } inline NodeID &NodeID::operator ^= (const NodeID &o) { for (uint16 i = 0; i < NODE_ID_LENGTH_BYTES; ++i) { id[i] ^= o.id[i]; } return *this; } struct MaxNodeID : public NodeID { MaxNodeID() { for (int i = 0; i < NODE_ID_LENGTH_BYTES; ++i) { id[i] = 0xff; } } }; struct NullNodeID : public NodeID { NullNodeID() { for (int i = 0; i < NODE_ID_LENGTH_BYTES; ++i) { id[i] = 0x00; } } }; } #endif // DHT_NODE_ID_H
[ [ [ 1, 154 ] ] ]
9e77dd22429428e42b80d7ba9a2e92cc182ee6b9
7cdb1c140943de003973dddc694222cb59240bf9
/102-ecological-bin-packing.cpp
344fdfadf37644654d1ba0ac5ef0b919c9d2b51d
[]
no_license
DracoAter/online-judge
784ff24c759384cb95a47f3f6d41127e91e97711
d7b0b302243d6a619c8935e880aa1bac5e0d909f
refs/heads/master
2020-05-16T00:58:56.561588
2011-07-15T20:47:16
2011-07-15T20:47:16
2,055,329
0
0
null
null
null
null
UTF-8
C++
false
false
1,491
cpp
#include <iostream> #define BROWN 0 #define GREEN 1 #define CLEAR 2 using namespace std; int main(){ int bottles[3][3]; string result; int min, tmp; while (cin >> tmp){ bottles[0][0] = tmp; for (int i=0; i<3; i++){ for (int j=0; j<3; j++){ if (i==0 && j==0) continue; cin >> bottles[i][j]; } } min = bottles[0][BROWN]+bottles[1][BROWN]+bottles[0][CLEAR]+bottles[2][CLEAR]+bottles[1][GREEN]+bottles[2][GREEN]; result = "GCB"; if ((tmp = bottles[0][BROWN]+bottles[2][BROWN]+bottles[0][CLEAR]+bottles[1][CLEAR]+bottles[1][GREEN]+bottles[2][GREEN]) <= min ){ min = tmp; result = "GBC"; } if ((tmp = bottles[0][BROWN]+bottles[1][BROWN]+bottles[1][CLEAR]+bottles[2][CLEAR]+bottles[0][GREEN]+bottles[2][GREEN]) <= min ){ min = tmp; result = "CGB"; } if ((tmp = bottles[0][BROWN]+bottles[2][BROWN]+bottles[1][CLEAR]+bottles[2][CLEAR]+bottles[0][GREEN]+bottles[1][GREEN]) <= min ){ min = tmp; result = "CBG"; } if ((tmp = bottles[1][BROWN]+bottles[2][BROWN]+bottles[0][CLEAR]+bottles[1][CLEAR]+bottles[0][GREEN]+bottles[2][GREEN]) <= min ){ min = tmp; result = "BGC"; } if ((tmp = bottles[1][BROWN]+bottles[2][BROWN]+bottles[0][CLEAR]+bottles[2][CLEAR]+bottles[0][GREEN]+bottles[1][GREEN]) <= min ){ min = tmp; result = "BCG"; } cout << result << " " << min << endl; } return 0; }
[ [ [ 1, 49 ] ] ]
cf640e24453744732d498ded9f3f359e7ea35101
72a2eb6600382e79f3a099775c8c2cf924cb7acb
/Minesweeper Game/Old Textbased/UserControl.cpp
f10e1a7f17643a8c63aa2bfd2e059726ce4846a2
[]
no_license
beuville/minesweepersolver
b8d666fd7ffcb5f48be3cc6454e3f2aba5fbe910
7940175a15d356dea243d236559fe16cb9b758e5
refs/heads/master
2021-01-25T07:35:18.270328
2008-12-02T15:21:52
2008-12-02T15:21:52
32,225,286
0
0
null
null
null
null
UTF-8
C++
false
false
1,414
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> #include "UserControl.h" #include "Gameboard.h" using namespace std; /* * constructor */ UserControl::UserControl(){ int x, y, z; printf("board height: "); fgets(input, 1024, stdin); x = atoi(input); printf("board width: "); fgets(input, 1024, stdin); y = atoi(input); printf("num mines: "); fgets(input, 1024, stdin); z = atoi(input); Gameboard *board = new Gameboard(x,y,z); //board->generate(); while(1){ printf(":>: "); fgets(input, 1024, stdin); command = strtok(input, " \t\n"); if(strcmp(command, "printP") == 0) board->print('p'); else if(strcmp(command, "printM") == 0) board->print('m'); else if(strcmp(command, "guess") == 0){ printf("row: "); fgets(input, 1024, stdin); x = atoi(input); printf("column: "); fgets(input, 1024, stdin); y = atoi(input); //board->pickSquare(x, y); board->pickSquare(x, y); } else if(strcmp(command, "pprint") == 0){ for (int i=0; i<4; i++) printf("%d\n", board->getCoordinate('m',i,i)); } else printf("nope\n"); } }
[ "cris.tarr@7e498df5-8955-0410-9177-9339b6f37624" ]
[ [ [ 1, 57 ] ] ]
7f22865d3737c27c3e16b7ed8892b8ca01565572
4df96df7014bf0ffd912ab69142bd3ab8d897a1b
/include/cspVmCore.h
ccf69cadcb1695255b203e6b0138b6d2b921c457
[]
no_license
al-sabr/caspin
25e66369de26e9ac2467109ef20a692e0f508dc7
fd901f1dbec708864ab12e8ce5ed153e33b6e93f
refs/heads/master
2021-12-12T04:55:15.474635
2011-10-10T18:01:37
2011-10-10T18:01:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,990
h
/* ----------------------------------------------------------------------------- Version: MPL 1.1/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is [caspin - AVM2+ Wrapper Library]. The Initial Developer of the Original Code is Fuse-Software (tm). Portions created by the Initial Developer are Copyright (C) 2009-2010 the Initial Developer. All Rights Reserved. Contributor(s): caspin Developer Team Alternatively, the contents of this file may be used under the terms of either the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the MPL, the GPL or the LGPL. ----------------------------------------------------------------------------- */ #ifndef __cspVmCore_H__ #define __cspVmCore_H__ #include "cspPrerequisites.h" namespace csp { //----------------------------------------------------------------------- /** The class that wraps the ActionScript 3 Virtual Machine */ class VmCore : public avmplus::AvmCore { private: typedef std::vector<NativePackageBase*> NativePackageList; typedef std::map<avmplus::Atom, uint> StickyRefMap; //----------------------------------------------------------------------- /** A small class to get access to a protected avmplus::Toplevel member function */ class VmToplevel : public avmplus::Toplevel { public: VmToplevel(avmplus::AbcEnv* abc) : avmplus::Toplevel(abc) {} /** Get a ClassClosure that is contained in the given PoolObject */ inline avmplus::ClassClosure* findClassInPool(int class_id, avmplus::PoolObject* pool) { return avmplus::Toplevel::findClassInPool(class_id, pool); } }; //----------------------------------------------------------------------- public: /** Usually you don't need to call this constructor manually, use the CSP_CREATE_VMCORE macro instead */ VmCore(MMgc::GC* gc); /** Usually you don't need to call this destructor manually, use the CSP_DESTROY_VMCORE macro instead */ virtual ~VmCore(); ///----------------------------------------------------------------------- /// Program / VmCore initialization ///----------------------------------------------------------------------- /** Initialize the garbage collector heap */ static void createGcHeap(); /** Free the garbage collector heap */ static void destroyGcHeap(); /** Add an class package to this VmCore */ int addPackage(NativePackageBase* package); /** Initialize all added class packages */ bool initializePackages(); ///----------------------------------------------------------------------- /// Get ActionScript 3 script definitions (classes, functions, etc.) ///----------------------------------------------------------------------- /** Get a multiname for the given identifier and package */ avmplus::Multiname getMultiname(avmplus::Stringp identifier, avmplus::Stringp package = NULL); /** Get a class closure from the given identifier and package */ avmplus::ClassClosure* getClassClosure(avmplus::Stringp identifier, avmplus::Stringp package = NULL); /** Get a class closure from the given identifier and package */ avmplus::ClassClosure* getClassClosure(const String& identifier, const String& package = ""); /** Get a method definition via its name and the containing script object */ static avmplus::MethodEnv* getMethodEnv(avmplus::ScriptObject* object, avmplus::Stringp method_name); /** Get a method definition via its name and the containing script object */ static avmplus::MethodEnv* getMethodEnv(avmplus::ScriptObject* object, const String& method_name); ///----------------------------------------------------------------------- /// Generic calling of ActionScript 3 functions (static class functions, object methods, etc.) ///----------------------------------------------------------------------- /** Call a method of the given object via a previously obtained method definition @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ static avmplus::Atom callFunction(avmplus::ScriptObject* obj, avmplus::MethodEnv* method_env, int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_2(static avmplus::Atom, callFunction, avmplus::ScriptObject*, avmplus::MethodEnv*); /** Call a method of the given object via its name @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ static avmplus::Atom callFunction(avmplus::ScriptObject* obj, avmplus::Stringp function_name, int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_2(static avmplus::Atom, callFunction, avmplus::ScriptObject*, avmplus::Stringp); /** Call a method of the given object via its name @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ static avmplus::Atom callFunction(avmplus::ScriptObject* obj, const String& function_name, int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_2(static avmplus::Atom, callFunction, avmplus::ScriptObject*, const String&); ///----------------------------------------------------------------------- /// Calling global ActionScript 3 script functions ///----------------------------------------------------------------------- /** Call a global function via a script definition @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ avmplus::Atom callGlobalFunction(avmplus::ClassClosure* class_closure, int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_1(avmplus::Atom, callGlobalFunction, avmplus::ClassClosure*); /** Call a global function via its name @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ avmplus::Atom callGlobalFunction(avmplus::Stringp function_name, avmplus::Stringp package = NULL, int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_2(avmplus::Atom, callGlobalFunction, avmplus::Stringp, avmplus::Stringp); /** Call a global function via its name @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ avmplus::Atom callGlobalFunction(const String& function_name, const String& package = "", int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_2(avmplus::Atom, callGlobalFunction, const String&, const String&); ///----------------------------------------------------------------------- /// Calling static ActionScript 3 class functions ///----------------------------------------------------------------------- /** Call a static function of the given class via its name @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ avmplus::Atom callStaticFunction(avmplus::Stringp class_name, avmplus::Stringp function_name, avmplus::Stringp package = NULL, int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_3(avmplus::Atom, callStaticFunction, avmplus::Stringp, avmplus::Stringp, avmplus::Stringp); /** Call a static function of the given class via its name @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ avmplus::Atom callStaticFunction(const String& class_name, const String& function_name, const String& package = "", int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_3(avmplus::Atom, callStaticFunction, const String&, const String&, const String&); ///----------------------------------------------------------------------- /// Creating ActionScript 3 objects ///----------------------------------------------------------------------- /** Create an object via a previously obtained class definition @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ avmplus::ScriptObject* createObject(avmplus::ClassClosure* class_closure, int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_1(avmplus::ScriptObject*, createObject, avmplus::ClassClosure*); /** Create an object via its class name @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ avmplus::ScriptObject* createObject(avmplus::Stringp class_name, avmplus::Stringp package = NULL, int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_2(avmplus::ScriptObject*, createObject, avmplus::Stringp, avmplus::Stringp); /** Create an object via its class name @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ avmplus::ScriptObject* createObject(const String& class_name, const String& package = "", int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_2(avmplus::ScriptObject*, createObject, const String&, const String&); /** Create an object via its class identifier and package identifier @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ avmplus::ScriptObject* createNativeObject(const uint& native_class_id, const uint& package_id, int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_2(avmplus::ScriptObject*, createNativeObject, const uint&, const uint&); /** Create a builtin ActionScript 3 object via its class identifier @warning If you pass an argument list to this function, keep the first entry of the array empty (i.e. "0") for internal usage */ avmplus::ScriptObject* createBuiltinObject(const uint& builtin_class_id, int num_args = 0, avmplus::Atom* args = NULL); CSP_TEMPLATE_ARG_ARRAY_IMPL_1(avmplus::ScriptObject*, createBuiltinObject, const uint&); ///----------------------------------------------------------------------- /// Managing ActionScript 3 object slots ///----------------------------------------------------------------------- /** Initialize a named attribute of the given object with another object */ static bool setSlotObject(avmplus::ScriptObject* obj, const String& slot_name, avmplus::ScriptObject* slot_obj); /** Get an object that is assigned to another object's child slot by its name */ static avmplus::ScriptObject* getSlotObject(avmplus::ScriptObject* obj, const String& slot_name); /** Try to automatically initialize all child slots of the given object */ static void initializeAllSlots(avmplus::ScriptObject* obj, const bool& recursive = false); /** Add a sticky reference to the given script object to keep it from being garbage collected */ bool stickyObject(avmplus::Atom object); /** Remove the sticky reference to the given script object so it can be garbage collected again */ bool unstickyObject(avmplus::Atom object); ///----------------------------------------------------------------------- /// Convert C++ types to ActionScript 3 types ///----------------------------------------------------------------------- /// base types /** Convert bool to an AS3 Boolean */ inline const avmplus::Atom& toScript(const bool& value) { CSP_ENTER_GC(); if(value) return avmplus::AtomConstants::trueAtom; else return avmplus::AtomConstants::falseAtom; } /** Convert int to an AS3 Integer */ inline avmplus::Stringp toScriptPtr(const int& value) { CSP_ENTER_GC(); return internInt(value); } CSP_CONVERT_TO_ATOM_IMPL(const int&); /** Convert double to an AS3 Number */ inline avmplus::Stringp toScriptPtr(const double& value) { CSP_ENTER_GC(); return internDouble(value); } CSP_CONVERT_TO_ATOM_IMPL(const double&); /// strings /** Convert a char* string to an AS3 String */ inline avmplus::Stringp toScriptPtr(const char* value) { CSP_ENTER_GC(); return internString(newStringLatin1(value)); } CSP_CONVERT_TO_ATOM_IMPL(const char*); /** Convert a std::string to an AS3 String */ inline avmplus::Stringp toScriptPtr(const String& value) { CSP_ENTER_GC(); return internString(newStringLatin1(value.c_str())); } CSP_CONVERT_TO_ATOM_IMPL(const String&); /// UTF strings /** Convert a wchar_t* string to an AS3 String */ inline avmplus::Stringp toScriptPtr(const wchar_t* value) { CSP_ENTER_GC(); return internStringUTF8((const char*)value); } CSP_CONVERT_TO_ATOM_IMPL(const wchar_t*); /** Convert a std::wstring to an AS3 UTF-String */ inline avmplus::Stringp toScriptPtr(const WString& value) { CSP_ENTER_GC(); return internStringUTF8((const char*)value.c_str()); } CSP_CONVERT_TO_ATOM_IMPL(const WString&); ///----------------------------------------------------------------------- /// Convert ActionScript 3 types to C++ types ///----------------------------------------------------------------------- /// base types /** Convert an AS3 Boolean to bool */ static inline bool atomToBool(const avmplus::Atom& atom) { return (boolean(atom) != 0); } /// strings /** Convert an AS3 String to a std::string */ String toString(avmplus::Stringp str); /// UTF strings /** Convert an AS3 UTF-String to a std::wstring */ WString toUTFString(avmplus::Stringp str); ///----------------------------------------------------------------------- /// ActionScript 3 code execution ///----------------------------------------------------------------------- /** Execute the given ABC file */ bool executeFile(const String& filename); /** Execute some ActionScript 3 byte code from the given memory buffer */ bool executeByteCode(const char* buf, size_t len); /** Compile and execute the given ActionScript 3 code string (!!!EXPERIMENTAL!!!) */ bool executeString(const String& code); ///----------------------------------------------------------------------- /// avmplus Accessors ///----------------------------------------------------------------------- /** Get the avmplus Toplevel that is associated with this VmCore */ VmToplevel* getToplevel() const; /** Get the avmplus Domain that is associated with this VmCore */ avmplus::Domain* getDomain() const; /** Get the avmplus DomainEnv that is associated with this VmCore */ avmplus::DomainEnv* getDomainEnv() const; ///----------------------------------------------------------------------- /// Add / remove output listeners ///----------------------------------------------------------------------- /** Add an OutputListener to this virtual machine */ bool addListener(OutputListener* listener); /** Remove an OutputListener from this virtual machine */ bool removeListener(OutputListener* listener); ///----------------------------------------------------------------------- /// Set / get custom data ///----------------------------------------------------------------------- /** Assign a user specified object to this VmCore */ void setUserData(void* data); /** Get the user specified object that has been assigned to this VmCore */ void* getUserData() const; ///----------------------------------------------------------------------- /// Print / throw ActionScript 3 exceptions ///----------------------------------------------------------------------- /** Internal method for printing ActionScript 3 exceptions */ void printException(avmplus::Exception* exception); /** Internal method for throwing ActionScript 3 exceptions */ void throwException(const String& message); private: void* mUserData; OutputLogger* mOutputLogger; static MMgc::EnterFrame* mEF; VmToplevel* mToplevel; avmplus::Domain* mDomain; avmplus::DomainEnv* mDomainEnv; avmplus::ArrayObject* mStickyRefArray; StickyRefMap mStickyRefMap; int mNextPackageID; NativePackageList mPackages; // overridden avmplus::String* readFileForEval(avmplus::String* referencingFilename, avmplus::String* filename); void interrupt(avmplus::Toplevel *env, avmplus::AvmCore::InterruptReason reason); void stackOverflow(avmplus::Toplevel *env); inline int32_t getDefaultAPI() { return 0; } #ifdef DEBUGGER /** Create a debugger object */ virtual avmplus::Debugger* createDebugger(int tracelevel); /** Create a profiler object */ virtual avmplus::Profiler* createProfiler(); #endif }; //----------------------------------------------------------------------- } #endif
[ [ [ 1, 362 ] ] ]
293b1c9134a991ccaaebcb0581a1a57a732dae95
14a00dfaf0619eb57f1f04bb784edd3126e10658
/Lab1/main.cpp
4266fee65915fb359b67702209e1fc9fdb550e94
[]
no_license
SHINOTECH/modanimation
89f842262b1f552f1044d4aafb3d5a2ce4b587bd
43d0fde55cf75df9d9a28a7681eddeb77460f97c
refs/heads/master
2021-01-21T09:34:18.032922
2010-04-07T12:23:13
2010-04-07T12:23:13
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,010
cpp
/************************************************************************************************* * * Modeling and animation (TNM079) 2007 * Code base for lab assignments. Copyright: * Gunnar Johansson ([email protected]) * Ken Museth ([email protected]) * Michael Bang Nielsen ([email protected]) * Ola Nilsson ([email protected]) * Andreas Söderström ([email protected]) * *************************************************************************************************/ #include <cstdlib> #include <iostream> #include <string> #include <exception> #include "GUI.h" using namespace std; static const int defaultScreenWidth = 800; static const int defaultScreenHeight = 600; GUI mainGUI; //----------------------------------------------------------------------------- void displayFunc() { mainGUI.displayFunc(); } //----------------------------------------------------------------------------- void winReshapeFunc(int newWidth, int newHeight) { mainGUI.winReshapeFunc(newWidth, newHeight); } //----------------------------------------------------------------------------- void mouseFunc(int button, int action, int mouseX, int mouseY) { mainGUI.mouseFunc(button, action, mouseX, mouseY); } //----------------------------------------------------------------------------- void mouseActiveMotionFunc(int mouseX, int mouseY) { mainGUI.mouseActiveMotionFunc(mouseX, mouseY); } //----------------------------------------------------------------------------- void mousePassiveMotionFunc(int mouseX, int mouseY) { mainGUI.mousePassiveMotionFunc(mouseX, mouseY); } //----------------------------------------------------------------------------- void keyboardUpFunc(unsigned char keycode, int mouseX, int mouseY) { mainGUI.keyboardUpFunc(keycode, mouseX, mouseY); } //----------------------------------------------------------------------------- void keyboardFunc(unsigned char keycode, int mouseX, int mouseY) { mainGUI.keyboardFunc(keycode, mouseX, mouseY); } //----------------------------------------------------------------------------- void specialFunc(int keycode, int mouseX, int mouseY) { mainGUI.specialFunc(keycode, mouseX, mouseY); } //----------------------------------------------------------------------------- void idleFunc() { mainGUI.update(); } //----------------------------------------------------------------------------- int main(int argc, char** argv) { glutInit (&argc, argv); mainGUI.init(); // glut callback functions glutDisplayFunc(displayFunc); glutReshapeFunc(winReshapeFunc); glutMouseFunc(mouseFunc); glutMotionFunc(mouseActiveMotionFunc); glutPassiveMotionFunc(mousePassiveMotionFunc); //glutKeyboardUpFunc(keyboardUpFunc); glutKeyboardFunc(keyboardFunc); glutSpecialFunc(specialFunc); glutIdleFunc(idleFunc); // Start main loop glutMainLoop(); return 0; }
[ "jpjorge@da195381-492e-0410-b4d9-ef7979db4686" ]
[ [ [ 1, 101 ] ] ]
493a6c6d08b58d5fc19c7723fb1014e13da5a2a9
171daeea8e21d62e4e1ea549f94fcf638c542c25
/JiangChen/SNARC MMOCAP 091109/real time1107/real time 1016/MainFrm.h
c079e81e5a4b16a75c52b3aa4af3dcb4a80c5580
[]
no_license
sworldy/snarcmotioncapture
b8c848ee64212cfb38f002bdd183bf4b6257a9c7
d4f57f0b7e2ecda6375c11eaa7f6a6b6d3d0af21
refs/heads/master
2021-01-13T02:02:54.097775
2011-08-07T16:46:24
2011-08-07T16:46:24
33,110,437
0
0
null
null
null
null
UTF-8
C++
false
false
3,811
h
/////////////////////////////////////////////////////////////////////////////// // // MainFrm.h : interface of the CMainFrame class // // Purpose: Implementation of Main Window of Hierarchical Animation System // // Created: // JL 9/1/97 // Modified: // JL 7/10/99 Created skeleton Demo for Oct 99 GDMag // /////////////////////////////////////////////////////////////////////////////// // // Copyright 1999 Jeff Lander, All Rights Reserved. // For educational purposes only. // Please do not republish in electronic or print form without permission // Thanks - [email protected] // /////////////////////////////////////////////////////////////////////////////// #if !defined(AFX_MAINFRM_H__4B0629BD_2696_11D1_83A0_004005308EB5__INCLUDED_) #define AFX_MAINFRM_H__4B0629BD_2696_11D1_83A0_004005308EB5__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "HierWin.h" #include "OGLView.h" #include "Skeleton.h" #include "LoadAnimation.h" class CMainFrame : public CFrameWnd { protected: // create from serialization only DECLARE_DYNCREATE(CMainFrame) // Attributes public: CString m_ClassName; HCURSOR m_HArrow; CHierWin m_HierWin; COGLView m_OGLView; BOOL m_Wireframe; int m_Animation_Direction; // USED FOR FORWARD/BACK PLAYBACK int m_AnimSpeed; // SPEED OF PLAYBACK IN FPS BOOL m_Animating; // for elapsed timing calculations DWORD m_StartTime,m_ElapsedTime,m_previousElapsedTime; // Operations public: CMainFrame(); // The Timing Member Functions // The following are used in timing calulations DWORD ElapsedTime( void ) { return( m_ElapsedTime - m_StartTime );} DWORD ElapsedTimeRender( void ) { return( m_ElapsedTime-m_previousElapsedTime);} // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMainFrame) public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); //}}AFX_VIRTUAL // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // control bar embedded members CStatusBar m_wndStatusBar; CToolBar m_wndToolBar; t_Bone m_Skeleton; // Generated message map functions protected: //{{AFX_MSG(CMainFrame) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnAddBone(); afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnPaint(); afx_msg void OnWhichogl(); afx_msg void OnFileOpen(); afx_msg void OnSkeletonResetskeleton(); afx_msg void OnViewOutline(); afx_msg void OnUpdateViewOutline(CCmdUI* pCmdUI); afx_msg void OnFileOpencharactermesh(); afx_msg void OnViewViewskeleton(); afx_msg void OnUpdateViewViewskeleton(CCmdUI* pCmdUI); afx_msg void OnFileSave(); afx_msg void OnViewDrawdeformed(); afx_msg void OnUpdateViewDrawdeformed(CCmdUI* pCmdUI); afx_msg void OnSkeletonSetrestpose(); afx_msg void OnSkeletonSetboneweights(); afx_msg void OnFileOpenweight(); afx_msg void OnSkeletonClearselectedweights(); afx_msg void OnStop(); afx_msg void OnPlayForward(); afx_msg void OnPlayBack(); afx_msg void OnForwardFrame(); afx_msg void OnBackFrame(); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: afx_msg void OnAnimationLoadanimation(); afx_msg void OnAnimationPlay(); }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif
[ "macrotao86@4a66b584-afee-11de-9d1a-45ab25924541" ]
[ [ [ 1, 126 ] ] ]
b3475466c6de0b51f7441cdb4c3109f21527b0b7
58cda2daf1b9b27a1177c9dd45b27f195fa85ee1
/trunk/KTV/baselib/sources/MyButton.cpp
4480ea85c3c1d46a1c1917758c782c0eb2026013
[]
no_license
sinojelly/disklvp
25329e063a611a19ca8e7e4bfc7df297535132bd
d6f6ce24e8aab0588e071a3fb8dc320d306d8c1f
refs/heads/master
2016-09-06T17:34:09.243481
2010-05-17T15:44:30
2010-05-17T15:44:30
33,052,355
0
0
null
null
null
null
UTF-8
C++
false
false
3,727
cpp
#include "../headers/MyButton.h" MyButton::MyButton(const QString& name,QImage* p_image,int x,int y,QWidget *parent) : QWidget(parent,Qt::FramelessWindowHint){ this->setCursor(Qt::PointingHandCursor); this->_name = name; this->_p_image = p_image; this->setGeometry(x,y,this->_p_image->width(),this->_p_image->height()); this->_initial(); } MyButton::MyButton(const ButtonItemParameter& param,QWidget *parent,QImage* p_image) : QWidget(parent,Qt::FramelessWindowHint){ this->setCursor(Qt::PointingHandCursor); this->_name = param.Name(); if(p_image) this->_p_image = p_image; else this->_p_image = param.GetImage(); this->setGeometry(param.Left(),param.Top(),this->_p_image->width(),this->_p_image->height()); this->_initial(); // add by jelly this->_x = param.Left(); this->_y = param.Top(); } MyButton::~MyButton(){ delete this->_p_image; if(this->_p_font) delete this->_p_font; if(this->_p_pen) delete this->_p_pen; } void MyButton::_initial(){ this->_p_font = 0; this->_p_pen = 0; this->_x = 0; this->_y = 0; this->_enabled = true; } QString MyButton::Name() const{ return this->_name; } void MyButton::SetImage(QImage* p_image){ if(this->_p_image) delete this->_p_image; this->_p_image = p_image; this->setGeometry(this->_x,this->_y,this->_p_image->width(),this->_p_image->height()); //this->repaint(); this->update(); } const QImage* MyButton::Image() const{ return this->_p_image; } void MyButton::paintEvent(QPaintEvent *enent){ QPainter painter; if(this->_p_image->isNull()){ return; } painter.begin(this); painter.drawImage(QPoint(0,0),*this->_p_image); if(!this->_text.isEmpty()){ if(this->_p_font) painter.setFont(*this->_p_font); if(this->_p_pen) painter.setPen(*this->_p_pen); painter.drawText(this->_x,this->_y,this->_text); } painter.end(); } void MyButton::mousePressEvent(QMouseEvent *event){ if(!this->IsEnabled()) return; emit click(); } void MyButton::SetFont(QFont* p_font){ if(this->_p_font) delete this->_p_font; this->_p_font = p_font; } void MyButton::SetPen(QPen* p_pen){ if(this->_p_pen) delete this->_p_pen; this->_p_pen = p_pen; } void MyButton::SetText(const QString& text){ this->_text = text;//trUtf8(text); //this->repaint(); this->update(); } void MyButton::SetTextPoint(int x,int y){ this->_x = x; this->_y = y; } bool MyButton::IsEnabled(){ return this->_enabled; } void MyButton::Enabled(){ this->_enabled = true; this->setCursor(Qt::PointingHandCursor); } void MyButton::Disabled(){ this->_enabled = false; this->setCursor(Qt::ArrowCursor); } /************************************************************/ StarButton::StarButton(const QString& name,QImage* p_image,int x,int y,QWidget *parent) : MyButton(name,p_image,x,y,parent) { this->_p_imageStar = 0; this->_pic_x = 2; this->_pic_y = 2; } StarButton::StarButton(const ButtonItemParameter& param,QWidget* parent,QImage* p_image) : MyButton(param,parent,p_image) { this->_p_imageStar = 0; this->_pic_x = 2; this->_pic_y = 2; } void StarButton::SetImage(const QString& file,int x,int y){ if(this->_p_imageStar) delete this->_p_imageStar; this->_p_imageStar = new QImage(file); this->_pic_x = x; this->_pic_y = y; //this->repaint(); this->update(); } StarButton::~StarButton(){ if(this->_p_imageStar) delete this->_p_imageStar; } void StarButton::paintEvent(QPaintEvent* event){ MyButton::paintEvent(event); QPainter painter; if(!this->_p_imageStar || this->_p_imageStar->isNull()){ return; } painter.begin(this); painter.drawImage(QPoint(this->_pic_x,this->_pic_y),*this->_p_imageStar); painter.end(); }
[ "[email protected]", "liulanggoukk@localhost" ]
[ [ [ 1, 43 ], [ 46, 79 ], [ 82, 119 ], [ 122, 136 ] ], [ [ 44, 45 ], [ 80, 81 ], [ 120, 121 ] ] ]
6c51c6c97caecfa6f7bf9952b87195866c10c731
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/projects/MainUI/GuiLib1.5/GuiImageLinkButton.h
ddf0acbb2144b30d6dcec2fa55b07b7e61173375
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
UTF-8
C++
false
false
2,084
h
/**************************************************************************** * * * GuiToolKit * * (MFC extension) * * Created by Francisco Campos G. www.beyondata.com [email protected] * *--------------------------------------------------------------------------* * * * This program is free software;so you are free to use it any of your * * applications (Freeware, Shareware, Commercial),but leave this header * * intact. * * * * These files are provided "as is" without warranty of any kind. * * * * GuiToolKit is forever FREE CODE !!!!! * * * *--------------------------------------------------------------------------* * Created by: Francisco Campos G. * * Bug Fixes and improvements : (Add your name) * * -Francisco Campos * * * ****************************************************************************/ #pragma once #include "guitoolbutton.h" class CGuiImageLinkButton : public CGuiToolButton { DECLARE_DYNAMIC(CGuiImageLinkButton) public: CGuiImageLinkButton(void); virtual ~CGuiImageLinkButton(void); //esta funcion identa la cadenade caracteres a la derecha en el caso //que no exista imagen void AjustRightText(INT_PTR nIdent){m_iDent=nIdent;} protected: CFont m_cfontSelect; CFont m_cfontNormal; CRect rectletra; INT_PTR m_iDent; protected: DECLARE_MESSAGE_MAP() public: virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); afx_msg void OnMouseMove(UINT nFlags, CPoint point); }; class CGuiScrollButton : public CGuiToolButton { public: CGuiScrollButton(void); virtual ~CGuiScrollButton(void); protected: DECLARE_MESSAGE_MAP() BOOL m_bMouserOvernew; public: afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnTimer(UINT nIDEvent); };
[ [ [ 1, 65 ] ] ]
fc66d60980c55a2727d680d4ff4dd532d6d3fcd6
bf0684ce69d618b1bbad5e2b4d8c8d4c79c1048b
/boot/log/include/StringLog.h
a4bce1255f6665f20f287dd3e6515640cf15ec1d
[ "BSD-3-Clause" ]
permissive
cider-load-test/devon
485829d3ad8c980eeeb352a594571e4ff69711aa
5b11265e5eae3db7bfaeb49543a2a6293bd15557
refs/heads/master
2021-12-02T07:24:11.497854
2010-08-07T09:16:40
2010-08-07T09:16:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,180
h
#ifndef DEVON_STRINGLOG_H #define DEVON_STRINGLOG_H // Devon #include <Devon/Log.h> // STL #include <sstream> namespace Devon { // ************************************************************************************************ class StringLog : public Log { public: StringLog() : Log(mStringStream) { } StringLog(std::string& string) : Log(mStringStream), mStringStream(string) { } std::stringstream& GetStream() { return mStringStream; } std::string GetString() const { return mStringStream.str(); } std::string ReleaseString() { std::string result = mStringStream.str(); mStringStream.seekp(std::ios_base::beg); return result; } protected: std::stringstream mStringStream; }; // ************************************************************************************************ Log& NewStringLog(); std::string ReleaseStringLog(StringLog& log); // ************************************************************************************************ } // namespace Devon #endif // DEVON_STRINGLOG_H
[ [ [ 1, 53 ] ] ]
bd4897fcb934aa77187dd045420d47171893c982
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Samples/LightningBolts/App.cpp
aaa6f37c79bec92c0301e024aa92d2cb57309212
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
4,603
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: App.cpp Version: 0.03 --------------------------------------------------------------------------- */ #include "App.h" #include "nGENE.h" #include "NodeLightning.h" using nGENE::Nature::NodeLightning; #include <sstream> void App::createApplication() { FrameworkWin32::createApplication(); m_pMouse->setSensitivity(0.02f); m_pPartitioner = new ScenePartitionerQuadTree(); SceneManager* sm = Engine::getSingleton().getSceneManager(0); sm->setScenePartitioner(m_pPartitioner); Renderer& renderer = Renderer::getSingleton(); renderer.setClearColour(0); renderer.setCullingMode(CULL_CW); uint anisotropy = 0; renderer.getDeviceRender().testCapabilities(CAPS_MAX_ANISOTROPY, &anisotropy); for(uint i = 0; i < 8; ++i) renderer.setAnisotropyLevel(i, anisotropy); CameraThirdPerson* cam; cam = (CameraThirdPerson*)sm->createCamera(L"CameraThirdPerson", L"Camera"); cam->setVelocity(10.0f); cam->setPosition(Vector3(0.0f, 1.0f, 0.0f)); cam->setDistanceFromTarget(50.0f); m_pCamera = cam; // Create boxes PrefabBox* pBox = NULL; Material* matCrate = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"crate"); uint count = 0; for(float z = -12.0f; z < 12.0f; z += 3.0f) { for(float x = -12.0f; x < 12.0f; x += 3.0f) { wstringstream name; name << L"Box_" << count++; pBox = sm->createBox(4.0f, 4.0f, 4.0f); pBox->setPosition(x * 5.0f, 1.5f, z * 5.0f); uint surfaceID = 0; pBox->getSurface(surfaceID)->setMaterial(matCrate); sm->getRootNode()->addChild(name.str(), pBox); } } // Create lightning static NodeLightning bolt; bolt.setCreator(sm); bolt.init(); bolt.setMinBranchLength(8.0f); bolt.setPosition(0.0f, 0.0f, 0.0f); bolt.setEndPoint(Vector3(0.0f, 0.0f, 0.0f)); bolt.setBranchesNum(400); bolt.setOffset(45.0f); bolt.setColour(Colour(128, 255, 128)); bolt.setStartPoint(Vector3(-70.0f, 70.0f, 0.0f)); bolt.setPause(50.0f); bolt.setWidth(0.25f); bolt.setBolt2Alpha(4.0f); bolt.setSegmentsNum(8); bolt.setUpdateFrequency(200); bolt.setBranchSpread(55.0f); bolt.setMaxFlash(0.0f); sm->getRootNode()->addChild(L"Bolt", bolt); cam->setTarget(Vector3(0.0f, 0.0f, 0.0f)); Engine::getSingleton().setActiveCamera(cam); // Create ground Plane pl(Vector3::UNIT_Y, Point(0.0f, 0.0f, 0.0f)); PrefabPlane* pGround = sm->createPlane(pl, Vector2(800.0f, 800.0f)); pGround->setPosition(0.0f, 0.0, 0.0f); Surface* pSurface = pGround->getSurface(L"Base"); Material* matGround = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"parallaxMap"); pSurface->setMaterial(matGround); sm->getRootNode()->addChild(L"GroundPlane", pGround); // Create light NodeLight* pLight = sm->createLight(LT_POINT); pLight->setPosition(-14.0f, 18.0f, -20.0f); pLight->setDirection(Vector3(0.7f, -0.9f, 1.0f)); pLight->setDrawDebug(false); Colour clrWorld = Colour::COLOUR_WHITE; pLight->setColour(clrWorld); pLight->setRadius(180.0f); sm->getRootNode()->addChild(L"Light", pLight); renderer.addLight(pLight); // Add input listener m_pInputListener = new MyInputListener(); m_pInputListener->setApp(this); InputSystem::getSingleton().addInputListener(m_pInputListener); // Add frame listener m_pFrameListener = new MyFrameListener(); Renderer::getSingleton().addFrameListener(m_pFrameListener); // Set window caption Window* pWindow = Renderer::getSingleton().getWindow(0); pWindow->setWindowCaption(L"Lightning Bolts"); // Create GUI m_pFont = new GUIFont(L"gui_default_font.fnt"); GUIManager::getSingleton().setFont(m_pFont); GUIManager::getSingleton().addWindow(&m_Window); GUIManager::getSingleton().setActiveMaterial(MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"gui_default_active")); GUIManager::getSingleton().setInactiveMaterial(MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"gui_default_inactive")); } //---------------------------------------------------------------------- CameraThirdPerson* App::getCamera() const { return m_pCamera; } //---------------------------------------------------------------------- int main() { App app; app.createApplication(); app.run(); app.shutdown(); return 0; } //----------------------------------------------------------------------
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 151 ] ] ]
424dded3ec246e03e72575d7e9db7f7100ea2d0a
5fb9b06a4bf002fc851502717a020362b7d9d042
/developertools/GumpEditor/ST_SplitterWnd.cpp
700ff3f6b8391a03bb66d372481fda6ef1330c20
[]
no_license
bravesoftdz/iris-svn
8f30b28773cf55ecf8951b982370854536d78870
c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4
refs/heads/master
2021-12-05T18:32:54.525624
2006-08-21T13:10:54
2006-08-21T13:10:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,428
cpp
// Project : general base class // Compiler : Visual C++ 5.0 / 6.0 // Plattform : Windows 95/98, Windows NT 3.51/4.0/2000 // File : ST_SplitterWnd.cpp // Programmer : dz, SoftToys // Copyright : 2001 SoftToys // Contact : [email protected] // Description : base class for handling splitter windows // History : 02.Sept. 2001 Version 1.0 // #include "stdafx.h" //#include "SplitterWndTest.h" #include "ST_SplitterWnd.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// ST_SplitterWnd::ST_SplitterWnd(int nLevel/* = 0*/) : m_nHiddenCol(-1),m_nHiddenRow(-1), m_sRegKey(_T("SplitterWnd")) , m_nLevel(nLevel) { m_nPaneSize[0] = 100; m_nPaneSize[1] = 100; m_nPaneMinSize[0] = 10; m_nPaneMinSize[1] = 10; m_pSubSplitterWnd[0] = NULL; m_pSubSplitterWnd[1] = NULL; m_nCurrentView[0] = 0; m_nCurrentView[1] = 0; } ST_SplitterWnd::~ST_SplitterWnd() { SaveToRegistry(); } bool ST_SplitterWnd::Create(CWnd* pParentWnd, CRuntimeClass* pView1, CRuntimeClass* pView2, CCreateContext* pContext, bool bVertical,int nID) { int nRow, nCol; m_bVertical = bVertical; if (bVertical) { nRow = 1; nCol = 2; } else { nRow = 2; nCol = 1; } VERIFY(CreateStatic(pParentWnd,nRow,nCol,WS_CHILD|WS_VISIBLE|WS_BORDER,nID)); if (pView1 != NULL) { VERIFY(CreateView(0,0,pView1,CSize(100,100),pContext)); } if (pView2 != NULL) { if (bVertical) { VERIFY(CreateView(0,1,pView2,CSize(100,100),pContext)); } else { VERIFY(CreateView(1,0,pView2,CSize(100,100),pContext)); } } return(true); } void ST_SplitterWnd::SetInitialStatus() { int c,r; CString sSubKey; sSubKey.Format(_T("Panes_%d"),m_nLevel); CString s; s = AfxGetApp()->GetProfileString(m_sRegKey,sSubKey,_T("-1 150 -1 150")); sscanf(s,_T("%d %d %d %d"),&c,&m_nPaneSize[0],&r,&m_nPaneSize[1]); if (IsSplittverticaly()) { SetColumnInfo(0,m_nPaneSize[0],m_nPaneMinSize[0]); SetColumnInfo(1,m_nPaneSize[1],m_nPaneMinSize[1]); if (c > -1) ToggleSide(c); if (c == -1) RecalcLayout(); } else { SetRowInfo(0,m_nPaneSize[0],m_nPaneMinSize[0]); SetRowInfo(1,m_nPaneSize[1],m_nPaneMinSize[1]); if (r > -1) ToggleSide(r); if (r == -1) RecalcLayout(); } if (m_pSubSplitterWnd[0] != NULL) m_pSubSplitterWnd[0]->SetInitialStatus(); if (m_pSubSplitterWnd[1] != NULL) m_pSubSplitterWnd[1]->SetInitialStatus(); } void ST_SplitterWnd::SaveToRegistry() { CString s; CString sSubKey; sSubKey.Format(_T("Panes_%d"),m_nLevel); RememberSize(); if (m_nPaneSize[0] == -1) m_nPaneSize[0] = 100; if (m_nPaneSize[1] == -1) m_nPaneSize[1] = 100; s.Format(_T("%d %d %d %d"),m_nHiddenCol,m_nPaneSize[0],m_nHiddenRow,m_nPaneSize[1]); AfxGetApp()->WriteProfileString(m_sRegKey,sSubKey,s); if (m_pSubSplitterWnd[0] != NULL) m_pSubSplitterWnd[0]->SaveToRegistry(); if (m_pSubSplitterWnd[1] != NULL) m_pSubSplitterWnd[1]->SaveToRegistry(); } bool ST_SplitterWnd::IsSideHidden(int nSide /* = LEFT_SIDE */) { if (IsSplittverticaly()) { if (m_nHiddenCol == nSide) { return(true); } } else { if (m_nHiddenRow == nSide) { return(true); } } return(false); } void ST_SplitterWnd::ShowColumn() { ASSERT_VALID(this); ASSERT(m_nCols < m_nMaxCols); ASSERT(m_nHiddenCol != -1); int colNew = m_nHiddenCol; m_nHiddenCol = -1; m_nCols++; // add a column ASSERT(m_nCols == m_nMaxCols); // fill the hidden column int col; for (int row = 0; row < m_nRows; row++) { CWnd* pPaneShow = GetDlgItem( AFX_IDW_PANE_FIRST + row * 16 + m_nCols); ASSERT(pPaneShow != NULL); pPaneShow->ShowWindow(SW_SHOWNA); for (col = m_nCols - 2; col >= colNew; col--) { CWnd* pPane = GetPane(row, col); ASSERT(pPane != NULL); pPane->SetDlgCtrlID(IdFromRowCol(row, col + 1)); } pPaneShow->SetDlgCtrlID(IdFromRowCol(row, colNew)); } // new panes have been created -- recalculate layout RecalcLayout(); } void ST_SplitterWnd::HideColumn(int colHide) { ASSERT_VALID(this); ASSERT(m_nCols > 1); ASSERT(colHide < m_nCols); ASSERT(m_nHiddenCol == -1); if (m_nHiddenCol != -1) return; RememberSize(); m_nHiddenCol = colHide; // if the column has an active window -- change it int rowActive, colActive; if (GetActivePane(&rowActive, &colActive) != NULL && colActive == colHide) { if (++colActive >= m_nCols) colActive = 0; SetActivePane(rowActive, colActive); } // hide all column panes for (int row = 0; row < m_nRows; row++) { CWnd* pPaneHide = GetPane(row, colHide); ASSERT(pPaneHide != NULL); pPaneHide->ShowWindow(SW_HIDE); pPaneHide->SetDlgCtrlID( AFX_IDW_PANE_FIRST + row * 16 + m_nCols); for (int col = colHide + 1; col < m_nCols; col++) { CWnd* pPane = GetPane(row, col); ASSERT(pPane != NULL); pPane->SetDlgCtrlID(IdFromRowCol(row, col - 1)); } } m_nCols--; m_pColInfo[m_nCols].nCurSize = m_pColInfo[colHide].nCurSize; RecalcLayout(); } void ST_SplitterWnd::ShowRow() { ASSERT_VALID(this); ASSERT(m_nRows < m_nMaxRows); ASSERT(m_nHiddenRow != -1); int rowNew = m_nHiddenRow; m_nHiddenRow = -1; m_nRows++; // add a row ASSERT(m_nRows == m_nMaxRows); // fill the hidden row int row; for (int col = 0; col < m_nCols; col++) { CWnd* pPaneShow = GetDlgItem( AFX_IDW_PANE_FIRST + m_nRows * 16 + col); ASSERT(pPaneShow != NULL); pPaneShow->ShowWindow(SW_SHOWNA); for (row = m_nRows - 2; row >= rowNew; row--) { CWnd* pPane = GetPane(row, col); ASSERT(pPane != NULL); pPane->SetDlgCtrlID(IdFromRowCol(row + 1, col)); } pPaneShow->SetDlgCtrlID(IdFromRowCol(rowNew, col)); } // new panes have been created -- recalculate layout RecalcLayout(); } void ST_SplitterWnd::HideRow(int rowHide) { ASSERT_VALID(this); ASSERT(m_nRows > 1); ASSERT(rowHide < m_nRows); ASSERT(m_nHiddenRow == -1); if (m_nHiddenRow != -1) return; RememberSize(); m_nHiddenRow = rowHide; // if the column has an active window -- change it int rowActive, colActive; if (GetActivePane(&rowActive, &colActive) != NULL && rowActive == rowHide) { if (++rowActive >= m_nRows) rowActive = 0; SetActivePane(rowActive, colActive); } // hide all row panes for (int col = 0; col < m_nCols; col++) { CWnd* pPaneHide = GetPane(rowHide, col); ASSERT(pPaneHide != NULL); pPaneHide->ShowWindow(SW_HIDE); pPaneHide->SetDlgCtrlID( AFX_IDW_PANE_FIRST + m_nRows * 16); for (int row = rowHide + 1; row < m_nRows; row++) { CWnd* pPane = GetPane(row, col); ASSERT(pPane != NULL); pPane->SetDlgCtrlID(IdFromRowCol(row - 1, col)); } } m_nRows--; m_pRowInfo[m_nRows].nCurSize = m_pRowInfo[rowHide].nCurSize; RecalcLayout(); } void ST_SplitterWnd::ToggleSide(int rc) { if (IsSplittverticaly()) { if (m_nHiddenCol == -1) { // can only hide this row, if the other row in not hidden HideColumn(rc); } else if (m_nHiddenCol == rc) { // show this row, only if this row is hidden ShowColumn(); } } else { if (m_nHiddenRow == -1) { // can only hide this column, if the other colum in not hidden HideRow(rc); } else if (m_nHiddenRow == rc) { // show this column, only if this column is hidden ShowRow(); } } } void ST_SplitterWnd::RememberSize() { if (m_pSubSplitterWnd[0] != NULL) m_pSubSplitterWnd[0]->RememberSize(); if (m_pSubSplitterWnd[1] != NULL) m_pSubSplitterWnd[1]->RememberSize(); if (IsSplittverticaly()) { if (m_nHiddenCol == -1) { // if not hidden GetColumnInfo(0,m_nPaneSize[0],m_nPaneMinSize[0]); GetColumnInfo(1,m_nPaneSize[1],m_nPaneMinSize[1]); } } else { if (m_nHiddenRow == -1) { // if not hidden GetRowInfo(0,m_nPaneSize[0],m_nPaneMinSize[0]); GetRowInfo(1,m_nPaneSize[1],m_nPaneMinSize[1]); } } } ST_SplitterWnd* ST_SplitterWnd::AddSubDivision(int nSide, CRuntimeClass* pView1,CRuntimeClass* pView2,CCreateContext* pContext,bool bVertical) { ASSERT((nSide == 0) || (nSide == 1)); ASSERT(m_pSubSplitterWnd[nSide] == NULL); int nRow, nCol; SideToRowCol(nSide,&nRow,&nCol); int nID = IdFromRowCol(nRow,nCol); m_pSubSplitterWnd[nSide] = new ST_SplitterWnd(m_nLevel+1); m_pSubSplitterWnd[nSide]->Create(this,pView1,pView2,pContext,bVertical,nID); return(m_pSubSplitterWnd[nSide]); } bool ST_SplitterWnd::HideView(int nRow,int nCol) { CWnd* pWnd = GetPane(nRow,nCol); if (!pWnd) return(false); pWnd->SetDlgCtrlID(0); pWnd->ShowWindow(SW_HIDE); return(true); } bool ST_SplitterWnd::ShowView(int nRow,int nCol,CWnd* pWnd) { pWnd->SetDlgCtrlID(IdFromRowCol(nRow, nCol)); pWnd->ShowWindow(SW_SHOW); return(true); } int ST_SplitterWnd::AddView(int nSide, CRuntimeClass * pViewClass, CCreateContext* pContext) { int nRow, nCol; SideToRowCol(nSide,&nRow,&nCol); // hide the current view of the pane if there is a view attached already if (GetDlgItem(IdFromRowCol(nRow, nCol))) { HideView(nRow, nCol); } // create the new view, if fail, set the previous view current if (CreateView(nRow, nCol, pViewClass, CSize(10,10), pContext) == 0) return -1; // get and store the new view CWnd* pWnd = GetPane(nRow, nCol); m_views[nSide].push_back(pWnd); m_nCurrentView[nSide] = m_views[nSide].size() - 1; ShowView(nRow, nCol,pWnd); RedrawWindow(); return(m_nCurrentView[nSide]); } void ST_SplitterWnd::SwitchToView(int nSide,int nViewIX /* = -1 */) { // if the View is -1 then just use the next view... if (nViewIX == -1) { nViewIX = m_nCurrentView[nSide] + 1; if (nViewIX >= m_views[nSide].size()) nViewIX = 0; // rollover to first view } CWnd* pWnd = m_views[nSide][nViewIX]; int nRow, nCol; if (IsSideHidden(LEFT_SIDE)) { nRow = 0; nCol = 0; } else { SideToRowCol(nSide,&nRow,&nCol); } HideView(nRow, nCol); ShowView(nRow, nCol, pWnd); m_nCurrentView[nSide] = nViewIX; RecalcLayout(); RedrawWindow(); }
[ "sience@a725d9c3-d2eb-0310-b856-fa980ef11a19" ]
[ [ [ 1, 417 ] ] ]
2abd1a2842a5da0fd39270a7fbc81b1e6fa4d7c0
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/contrib/ncterrain2/src/ncterrain2/nterrainnode_main.cc
c25b13446413d6c35da56fbbd3a526ec4c32fd43
[]
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
5,576
cc
//------------------------------------------------------------------------------ // nterrainnode_main.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "ncterrain2/nterrainnode.h" #include "gfx2/ngfxserver2.h" #include "resource/nresourceserver.h" #include "misc/nwatched.h" nNebulaScriptClass(nTerrainNode, "nmaterialnode"); //------------------------------------------------------------------------------ /** */ nTerrainNode::nTerrainNode() : refResourceServer("/sys/servers/resource"), maxPixelError(5.0f), maxTexelSize(1.0f) { // empty } //------------------------------------------------------------------------------ /** */ nTerrainNode::~nTerrainNode() { if (this->AreResourcesValid()) { this->UnloadResources(); } } //------------------------------------------------------------------------------ /** Load resources needed by this object. */ bool nTerrainNode::LoadResources() { if (nMaterialNode::LoadResources()) { if ((!this->refChunkLodTree.isvalid()) && (!this->chunkFilename.IsEmpty())) { nChunkLodTree* tree = (nChunkLodTree*) this->refResourceServer->NewResource("nchunklodtree", 0, nResource::Other); n_assert(tree); if (!tree->IsValid()) { tree->SetFilename(this->chunkFilename); tree->SetTqtFilename(this->texQuadFile.Get()); tree->SetDisplayMode(nGfxServer2::Instance()->GetDisplayMode()); tree->SetCamera(nGfxServer2::Instance()->GetCamera()); tree->SetMaxPixelError(this->maxPixelError); tree->SetMaxTexelSize(this->maxTexelSize); tree->SetTerrainScale(this->terrainScale); tree->SetTerrainOrigin(this->terrainOrigin); if (!tree->Load()) { n_printf("nTerrainNode: Error loading .chu file %s\n", this->chunkFilename.Get()); tree->Release(); return false; } } this->refChunkLodTree = tree; this->SetLocalBox(tree->GetBoundingBox()); } return true; } return false; } //------------------------------------------------------------------------------ /** Unload resources. */ void nTerrainNode::UnloadResources() { nMaterialNode::UnloadResources(); if (this->refChunkLodTree.isvalid()) { this->refChunkLodTree->Release(); this->refChunkLodTree.invalidate(); } } //------------------------------------------------------------------------------ /** Indicate to scene server that we provide geometry */ bool nTerrainNode::HasGeometry() const { return true; } //------------------------------------------------------------------------------ /** Update geometry, set as current mesh in the gfx server and call nGfxServer2::DrawIndexed(). - 15-Jan-04 floh AreResourcesValid()/LoadResource() moved to scene server */ bool nTerrainNode::RenderGeometry(nSceneServer* sceneServer, nRenderContext* renderContext) { n_assert(sceneServer); n_assert(renderContext); nWatched watchNumMeshesRendered("terrainNumMeshesRendered", nArg::Int); nWatched watchNumTexturesRendered("terrainNumTexturesRendered", nArg::Int); nWatched watchNumMeshesAllocated("terrainNumMeshesAllocated", nArg::Int); nWatched watchNumTexturesAllocated("terrainNumTexturesAllocated", nArg::Int); nGfxServer2* gfxServer = nGfxServer2::Instance(); // only render if resource is available (may not be // available yet if async resource loading enabled) if (!this->refChunkLodTree->IsValid()) { return false; } // update and render the chunk lod tree const matrix44& view = gfxServer->GetTransform(nGfxServer2::InvView); this->refChunkLodTree->Update(view.pos_component()); // render in 2 passes, far and near because of limited z buffer precision const float farZ = 160000.0f; nCamera2 camera = gfxServer->GetCamera(); nCamera2 origCamera = camera; // render far pass and near pass with different near/far planes to // workaround zbuffer precision problems nChunkLodTree* chunkLodTree = this->refChunkLodTree.get(); chunkLodTree->BeginRender(); camera.SetNearPlane(origCamera.GetFarPlane() * 0.9f); camera.SetFarPlane(farZ); gfxServer->SetCamera(camera); chunkLodTree->Render(gfxServer->GetShader(), gfxServer->GetTransform(nGfxServer2::Projection), gfxServer->GetTransform(nGfxServer2::ModelViewProjection)); gfxServer->Clear(nGfxServer2::DepthBuffer, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0); camera.SetNearPlane(origCamera.GetNearPlane()); camera.SetFarPlane(origCamera.GetFarPlane()); gfxServer->SetCamera(camera); chunkLodTree->Render(gfxServer->GetShader(), gfxServer->GetTransform(nGfxServer2::Projection), gfxServer->GetTransform(nGfxServer2::ModelViewProjection)); chunkLodTree->EndRender(); watchNumMeshesRendered->SetI(chunkLodTree->GetNumMeshesRendered()); watchNumTexturesRendered->SetI(chunkLodTree->GetNumTexturesRendered()); watchNumMeshesAllocated->SetI(chunkLodTree->GetNumMeshesAllocated()); watchNumTexturesAllocated->SetI(chunkLodTree->GetNumTexturesAllocated()); gfxServer->SetCamera(origCamera); return true; }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 156 ] ] ]
1a190d923beecd67c60045050bfb9c7614cc85f7
97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a
/3dc/avp/win95/iofocus.cpp
6988bb69922590919e4199639df0e19ae4d65a5c
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
SR-dude/AvP-Wine
2875f7fd6b7914d03d7f58e8f0ec4793f971ad23
41a9c69a45aacc2c345570ba0e37ec3dc89f4efa
refs/heads/master
2021-01-23T02:54:33.593334
2011-09-17T11:10:07
2011-09-17T11:10:07
2,375,686
1
0
null
null
null
null
UTF-8
C++
false
false
1,935
cpp
/******************************************************************* * * DESCRIPTION: iofocus.cpp * * AUTHOR: David Malcolm * * HISTORY: Created 21/11/97 * *******************************************************************/ /* Includes ********************************************************/ #include "3dc.h" #include "iofocus.h" #include "gadget.h" #include "avp_menus.h" #include "psnd.h" extern "C" { #define UseLocalAssert Yes #include "ourasert.h" /* Version settings ************************************************/ /* Constants *******************************************************/ /* Macros **********************************************************/ /* Imported function prototypes ************************************/ extern int InGameMenusAreRunning(void); /* Imported data ***************************************************/ /* Exported globals ************************************************/ /* Internal type definitions ***************************************/ /* Internal function prototypes ************************************/ /* Internal globals ************************************************/ static OurBool iofocus_AcceptTyping = No; /* Exported function definitions ***********************************/ OurBool IOFOCUS_AcceptControls(void) { return !iofocus_AcceptTyping; } OurBool IOFOCUS_AcceptTyping(void) { return iofocus_AcceptTyping; } void IOFOCUS_Toggle(void) { #if CONSOLE_DEBUGGING_COMMANDS_ACTIVATED||!(PREDATOR_DEMO||MARINE_DEMO||ALIEN_DEMO) if(InGameMenusAreRunning()) return;; iofocus_AcceptTyping = !iofocus_AcceptTyping; if (iofocus_AcceptTyping) { Sound_Play(SID_CONSOLE_ACTIVATES,NULL); } else { Sound_Play(SID_CONSOLE_DEACTIVATES,NULL); RemoveTheConsolePlease(); } #endif } /* Internal function definitions ***********************************/ };
[ "a_jagers@ANTHONYJ.(none)" ]
[ [ [ 1, 76 ] ] ]
98063bdad93da8b45f5e32dbf457d5162953e327
3d7fc34309dae695a17e693741a07cbf7ee26d6a
/aluminizer/DopplerTempCalibration.h
6f6ecd3d1c094e2e3540ef0c6c67bb02ba08ac18
[ "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,051
h
#pragma once #include "ExperimentPage.h" #include "CalibrationPage.h" using namespace std; class ExpQubit; class DopplerTempCalibration : public CalibrationPage { public: DopplerTempCalibration(const string& sPageName, ExperimentsSheet* pSheet); //called once when the experiment is first started virtual void InitExperimentStart(); virtual void DidCalibration(const calibration_item*, numerics::FitObject*); virtual unsigned num_columns() { return 6; } virtual bool acceptCalibrationPlot(calibration_item* ci, data_plot*); virtual data_plot* get_data_plot(calibration_item* ci, const std::string& sTitle); virtual void PostCreateGUI(); protected: virtual bool needsBottomSpacer() { return false; } protected: std::vector<calibration_item> cal; ExpQubit* pCal[2]; GUI_double Wait; GUI_combo CalType; GUI_int Sideband; GUI_double rsb_min, rsb_max, rsb_height; GUI_double bsb_min, bsb_max, bsb_height; GUI_double n_bar; std::vector<data_plot*> data_plots; QHBoxLayout* plot_grid; };
[ "trosen@814e38a0-0077-4020-8740-4f49b76d3b44" ]
[ [ [ 1, 52 ] ] ]
ee22fb70bb665232197f84aeaae6875ad006e287
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/qwt/include/qwt_compass.h
cb0bb74fa3d8bc0f0a9761972643bab749887510
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,120
h
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- ***************************** * Qwt Widget Library * Copyright (C) 1997 Josef Wilgen * Copyright (C) 2002 Uwe Rathmann * * This library is free software; you can redistribute it and/or * modify it under the terms of the Qwt License, Version 1.0 *****************************************************************************/ #ifndef QWT_COMPASS_H #define QWT_COMPASS_H 1 #include <qstring.h> #include <qmap.h> #include "qwt_dial.h" #if defined(QWT_TEMPLATEDLL) #if defined(QT_NO_STL) || QT_VERSION < 0x040000 || QT_VERSION > 0x040001 /* Unfortunately Qt 4.0.0/Qt 4.0.1 contains uncompilable code in the STL adaptors of qmap.h. The declaration below instantiates this code resulting in compiler errors. If you really need the map to be exported, remove the condition above and fix the qmap.h */ // MOC_SKIP_BEGIN template class QWT_EXPORT QMap<double, QString>; // MOC_SKIP_END #endif #endif class QwtCompassRose; /*! \brief A Compass Widget QwtCompass is a widget to display and enter directions. It consists of a scale, an optional needle and rose. \image html compass.gif \note The examples/dials example shows how to use QwtCompass. */ class QWT_EXPORT QwtCompass: public QwtDial { Q_OBJECT public: explicit QwtCompass( QWidget* parent = NULL); virtual ~QwtCompass(); void setRose(QwtCompassRose *rose); const QwtCompassRose *rose() const; QwtCompassRose *rose(); const QMap<double, QString> &labelMap() const; QMap<double, QString> &labelMap(); void setLabelMap(const QMap<double, QString> &map); protected: virtual QwtText scaleLabel(double value) const; virtual void drawRose(QPainter *, const QPoint &center, int radius, double north, QPalette::ColorGroup) const; virtual void drawScaleContents(QPainter *, const QPoint &center, int radius) const; virtual void keyPressEvent(QKeyEvent *); private: class PrivateData; PrivateData *d_data; }; #endif
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 80 ] ] ]
91091520983d4b2dc9b95227ae0faa2d59353292
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D10/D3D10ShaderResourceView1.cpp
c8b7da794826376c7a6874ae39f1337fddc5ffdf
[]
no_license
midnite8177/phever
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
45529e80ebf707e7299887165821ca360aa1907d
refs/heads/master
2020-05-16T21:59:24.201346
2010-07-12T23:51:53
2010-07-12T23:51:53
34,965,829
3
2
null
null
null
null
UTF-8
C++
false
false
503
cpp
// Copyright (c) Microsoft Corporation. All rights reserved. #include "stdafx.h" #include "D3D10ShaderResourceView1.h" using namespace Microsoft::WindowsAPICodePack::DirectX::Direct3D10; ShaderResourceViewDescription1 ShaderResourceView1::Description1::get() { ShaderResourceViewDescription1 desc; pin_ptr<ShaderResourceViewDescription1> ptr = &desc; GetInterface<ID3D10ShaderResourceView1>()->GetDesc1((D3D10_SHADER_RESOURCE_VIEW_DESC1*)ptr); return desc; }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 17 ] ] ]
689061c25caf057fc5ca6a7b5a935f73639f7527
6ee200c9dba87a5d622c2bd525b50680e92b8dab
/Autumn/Engine/Camera/Camera.h
9bd2f389b7f170029d460fa6a0eb4101300862b3
[]
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
1,813
h
#ifndef _CAMERA_ #define _CAMERA_ #ifndef _VECTOR3_ #include "Core/Math/Vector3.h" #endif #ifndef _MATRIX4X4_ #include "Core/Math/Matrix4x4.h" #endif #ifndef _TIME_MANAGER_ #include "Engine/Manager/TimeManager.h" #endif class Camera { protected: bool m_bUsePerspective; float m_fAspect; float m_fZNear; float m_fZFar; float m_fFov; float m_fLeft; float m_fRight; float m_fBottom; float m_fTop; Vector3 m_vPos; Vector3 m_vAt; Vector3 m_vUp; Matrix4x4 m_mProjection; Matrix4x4 m_mView; public: Camera(); virtual ~Camera(); virtual HRESULT Create(); virtual HRESULT Destroy(); inline Vector3 GetPos() const { return m_vPos; } inline void SetPos(Vector3 val) { m_vPos = val; } inline Vector3 GetLookAt() const { return m_vAt; } inline void SetLookAt(Vector3 val) { m_vAt = val; } inline Vector3 GetUp() const { return m_vUp; } inline void SetUp(Vector3 val) { m_vUp = val; } inline bool IsPerspectiveProj() const { return m_bUsePerspective; } void SetAspect(float _fAspect); void BuildProjectionMatrix(float _fFov, float _fAspect, float _fZNear, float _fZFar); void BuildProjectionMatrix(float _fLeft, float _fRight, float _fBottom, float _fTop, float _fZNear, float _fZFar); void SetView(Vector3 _Pos, Vector3 _At, Vector3 _Up); void BuildViewMatrix(); void Translate(const Vector3 & _v); Vector3 GetLooktAtDirection() const; Vector3 GetLateralDirection() const; void Update( const TimeInfo & _sTimeInfo ); Matrix4x4 GetViewProj() const; inline Matrix4x4 GetView() const { return m_mView; } inline Matrix4x4 GetProj() const { return m_mProjection; } inline float GetFOV() const { return m_fFov; } inline float GetAspect() const { return m_fAspect; } }; #endif // _CAMERA_
[ "edouard.roge@ab19582e-f48f-11de-8f43-4547254af6c6" ]
[ [ [ 1, 71 ] ] ]
460439714d5d0d62e282d3101ed52adc080a6501
ea2786bfb29ab1522074aa865524600f719b5d60
/MultimodalSpaceShooter/src/gui/Widget.h
4e7d997b8c274fb18f1b15f6137c234d745c18c8
[]
no_license
jeremysingy/multimodal-space-shooter
90ffda254246d0e3a1e25558aae5a15fed39137f
ca6e28944cdda97285a2caf90e635a73c9e4e5cd
refs/heads/master
2021-01-19T08:52:52.393679
2011-04-12T08:37:03
2011-04-12T08:37:03
1,467,691
0
1
null
null
null
null
UTF-8
C++
false
false
609
h
#ifndef WIDGET_H #define WIDGET_H #include <SFML/Window/Event.hpp> #include <SFML/Graphics/RenderTarget.hpp> #include "input/MultimodalListener.h" ////////////////////////////////////////////////// /// Abstract class for every widgets ////////////////////////////////////////////////// class Widget { public: Widget(); virtual void onEvent(const sf::Event& event); virtual void onMultimodalEvent(Multimodal::Event event); virtual void update(float frameTime) = 0; virtual void draw(sf::RenderTarget& window) const = 0; }; #endif // WIDGET_H
[ [ [ 1, 22 ] ] ]
0fba92b4bbea9c5dbb7acfa3529084d0b93618b8
21da454a8f032d6ad63ca9460656c1e04440310e
/src/wcpp/io/wsiByteArrayInputStream.h
480cf8db12c7df0726cf856aaa9d34a9ffdd32cc
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
259
h
#ifndef __wsiByteArrayInputStream_h__ #define __wsiByteArrayInputStream_h__ #include "wsiInputStream.h" class wsiByteArrayInputStream : public wsiInputStream { public: static const ws_iid sIID; }; #endif // __wsByteArrayInputStream_h__
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 14 ] ] ]
c07ed0ecf46b16b94864d19ceb87249226fe6a43
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/persistence2/engine/core/src/MeshAnimation.cpp
e5c63c48288fecd07445d76bd7042b2b651ba7e6
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
ISO-8859-3
C++
false
false
3,346
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "stdinc.h" //precompiled header #include "MeshAnimation.h" #include "Exception.h" #include "AnimationManager.h" #include "ActorManager.h" #include "MeshObject.h" #include "ScriptWrapper.h" using namespace Ogre; namespace rl { MeshAnimation::MeshAnimation( Ogre::AnimationState* animState, MeshObject* mesh, Ogre::Real speed, unsigned int timesToPlay, bool paused ) : BaseAnimation( animState->getLength(), speed, timesToPlay, paused ), mMeshObject( mesh ) { setAnimationState(animState); mAnimation = static_cast<Entity*>(mMeshObject->getMovableObject())->getSkeleton() ->getAnimation(animState->getAnimationName()); } MeshAnimation::~MeshAnimation() { if( mAnimState != NULL ) mAnimState->setEnabled(false); } void MeshAnimation::setAnimationState( Ogre::AnimationState* animState ) { if( animState == 0 ) Throw( NullPointerException,"Ogre::AnimationState darf nicht null sein" ); mAnimState = animState; if( mTimesToPlay != 1 ) mAnimState->setLoop( true ); // Wenn die Zeit negativ ist, beginnen wir am Ende if( mSpeed < 0 ) mAnimState->setTimePosition( mAnimState->getLength() ); mAnimState->setEnabled( true ); } void MeshAnimation::setSpeed( Ogre::Real speed ) { // Eventuell auf Anfang/Ende setzen if( speed < 0 && mAnimState->getTimePosition() == 0 ) mAnimState->setTimePosition( mAnimState->getLength() ); else if( speed > 0 && mAnimState->getTimePosition() == mAnimState->getLength() ) mAnimState->setTimePosition( 0 ); BaseAnimation::setSpeed(speed); } MeshObject* MeshAnimation::getMeshObject() { return mMeshObject; } void MeshAnimation::resetTimesPlayed() { // Zurückspulen if( mSpeed < 0 ) mAnimState->setTimePosition( mLength ); else if( mSpeed > 0 ) mAnimState->setTimePosition( 0 ); BaseAnimation::resetTimesPlayed(); } // Gewicht (Einfluss) der Animation Ogre::Real MeshAnimation::getWeight(void) const { return mAnimState->getWeight(); } void MeshAnimation::setWeight(Ogre::Real weight) { mAnimState->setWeight( weight ); if( weight > 0.0 && !mAnimState->getEnabled() ) mAnimState->setEnabled(true); else if( weight <= 0.00001 && mAnimState->getEnabled() ) mAnimState->setEnabled(false); } void MeshAnimation::doAddTime(Ogre::Real timePassed) { mAnimState->addTime( timePassed ); } void MeshAnimation::setLoop( bool loop ) { mAnimState->setLoop(loop); } Ogre::AnimationState* MeshAnimation::getAnimationState() const { return mAnimState; } }
[ "timm@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 125 ] ] ]
0d4cccfde237ecaf08050c4ab4305ce94ec69888
1536bdbfb912d9bec8cea8c85d144033570bcb62
/agent/browser/ie/urlBlast/urlBlastDlg.cpp
c4f40608434bebc2eab7453a4d500e0661810028
[]
no_license
sdo-ops/WebPageTest-mirror-
ad6efec365471072ce62b6ecaa4c1eb4f2808794
16bcff6e67a49bc84611cedd3f2d7224893ef021
refs/heads/master
2020-12-24T13:28:49.940398
2011-02-20T16:37:45
2011-02-20T16:37:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
50,891
cpp
// urlBlastDlg.cpp : implementation file // #include "stdafx.h" #include "urlBlast.h" #include "urlBlastDlg.h" #include <WtsApi32.h> #include <Iphlpapi.h> #include <Winsock2.h> #include <math.h> #include <Userenv.h> #include "crash.h" #ifdef _DEBUG #define new DEBUG_NEW #endif /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ CurlBlastDlg::CurlBlastDlg(CWnd* pParent /*=NULL*/) : CDialog(CurlBlastDlg::IDD, pParent) , start(0) , freq(0) , firstIdleTime(0) , firstKernelTime(0) , firstUserTime(0) , lastIdleTime(0) , lastKernelTime(0) , lastUserTime(0) , logFile(_T("")) , startupDelay(1000) , threadCount(1) , computerName(_T("")) , aliveFile(_T("")) , testType(0) , rebootInterval(0) , clearCacheInterval(-1) , labID(0) , dialerID(0) , connectionType(0) , uploadLogsInterval(0) , lastUpload(0) , testID(0) , configID(0) , timeout(0) , experimental(0) , running(false) , minInterval(5) , screenShotErrors(0) , checkOpt(1) , bDrWatson(false) , ifIndex(0) , accountBase(_T("user")) , password(_T("2dialit")) , browserWidth(1024) , browserHeight(768) , debug(0) , urlManager(log) , pipeIn(0) , pipeOut(0) , ec2(0) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); // handle crash events crashLog = &log; SetUnhandledExceptionFilter(CrashFilter); // create a NULL DACL we will re-use everywhere we do file access ZeroMemory(&nullDacl, sizeof(nullDacl)); nullDacl.nLength = sizeof(nullDacl); nullDacl.bInheritHandle = FALSE; if( InitializeSecurityDescriptor(&SD, SECURITY_DESCRIPTOR_REVISION) ) if( SetSecurityDescriptorDacl(&SD, TRUE,(PACL)NULL, FALSE) ) nullDacl.lpSecurityDescriptor = &SD; // randomize the random number generator FILETIME ft; GetSystemTimeAsFileTime(&ft); srand(ft.dwLowDateTime); // get the computer name TCHAR buff[MAX_COMPUTERNAME_LENGTH + 1]; DWORD len = _countof(buff); if( GetComputerName(buff, &len) ) computerName = buff; // let our process kill processes from other users HANDLE hToken; if( OpenProcessToken( GetCurrentProcess() , TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY , &hToken) ) { TOKEN_PRIVILEGES tp; if( LookupPrivilegeValue( NULL , SE_DEBUG_NAME, &tp.Privileges[0].Luid ) ) { tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken , FALSE , &tp , 0 , (PTOKEN_PRIVILEGES) 0 , 0 ) ; } CloseHandle(hToken); } } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CurlBlastDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_STATUS, status); DDX_Control(pDX, IDC_RATE, rate); DDX_Control(pDX, IDC_CPU, cpu); DDX_Control(pDX, IDC_REBOOT, rebooting); } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ BEGIN_MESSAGE_MAP(CurlBlastDlg, CDialog) ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_WM_CLOSE() ON_WM_TIMER() ON_MESSAGE(MSG_UPDATE_UI, OnUpdateUI) ON_MESSAGE(MSG_CONTINUE_STARTUP, OnContinueStartup) END_MESSAGE_MAP() /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ BOOL CurlBlastDlg::OnInitDialog() { CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // set the window title (include the machine name) CString title = computerName + _T(" - URL Blast"); SetWindowText(title); // disable font smoothing SystemParametersInfo(SPI_SETFONTSMOOTHING, FALSE, NULL, SPIF_UPDATEINIFILE); // start up minimized ShowWindow(SW_MINIMIZE); LoadSettings(); SetupScreen(); rebooting.SetWindowText(_T("")); status.SetWindowText(_T("Starting up...")); SetTimer(1,startupDelay,NULL); return TRUE; // return TRUE unless you set the focus to a control } /*----------------------------------------------------------------------------- // 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 CurlBlastDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } /*----------------------------------------------------------------------------- // The system calls this function to obtain the cursor to display while the user drags // the minimized window. -----------------------------------------------------------------------------*/ HCURSOR CurlBlastDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CurlBlastDlg::OnCancel() { } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CurlBlastDlg::OnOK() { } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CurlBlastDlg::OnClose() { log.Trace(_T("OnClose()")); CWaitCursor w; KillTimer(1); KillTimer(2); status.SetWindowText(_T("Waiting to exit...")); // signal and wait for all of the workers to finish KillWorkers(); // upload our current log files UploadLogs(); // shut down the url manager urlManager.Stop(); crashLog = NULL; CDialog::OnOK(); } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CurlBlastDlg::OnTimer(UINT_PTR nIDEvent) { switch( nIDEvent ) { case 1: // startup delay { KillTimer(nIDEvent); DoStartup(); } break; case 2: // periodic timer { // close any open dialog windows CloseDialogs(); // see if it is time to upload the log files CheckUploadLogs(); // see if it is time to reboot CheckReboot(); // do we need to exit? CheckExit(); // see if we need to update the "alive" file WriteAlive(); // kill any debug windows that are open KillProcs(); // update the UI PostMessage(MSG_UPDATE_UI); } break; } } typedef HRESULT (STDAPICALLTYPE* DLLREGISTERSERVER)(void); /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ unsigned __stdcall ClearCachesThreadProc( void* arg ) { CurlBlastDlg * dlg = (CurlBlastDlg *)arg; if( dlg ) dlg->ClearCaches(); return 0; } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CurlBlastDlg::DoStartup(void) { QueryPerformanceFrequency((LARGE_INTEGER *)&freq); log.dialerId = dialerID; log.labID = labID; log.LogEvent(event_Started); log.LogMachineInfo(); // register pagetest if we have a dll locally TCHAR pagetest[MAX_PATH]; if( GetModuleFileName(NULL, pagetest, _countof(pagetest)) ) { lstrcpy( PathFindFileName(pagetest), _T("pagetest.dll") ); HMODULE hPagetest = LoadLibrary(pagetest); if( hPagetest ) { status.SetWindowText(_T("Registering pagetest...")); DLLREGISTERSERVER proc = (DLLREGISTERSERVER)GetProcAddress(hPagetest, "DllRegisterServer"); if( proc ) proc(); FreeLibrary(hPagetest); } } // disable the DNS cache status.SetWindowText(_T("Disabling DNS cache...")); DisableDNSCache(); // set the OS to not boost foreground processes HKEY hKey; if( SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\PriorityControl"), 0, KEY_SET_VALUE, &hKey)) ) { DWORD val = 0x18; RegSetValueEx(hKey, _T("Win32PrioritySeparation"), 0, REG_DWORD, (LPBYTE)&val, sizeof(val)); RegCloseKey(hKey); } // clear the caches on a background thread HANDLE hThread = (HANDLE)_beginthreadex(0, 0, ::ClearCachesThreadProc, this, 0, 0); if( hThread ) CloseHandle(hThread); // run a periodic timer for doing housekeeping work SetTimer(2, 500, NULL); } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CurlBlastDlg::KillWorkers(void) { // signal all of the workers to stop CURLBlaster * blaster; for( int i = 0; i < workers.GetCount(); i++ ) { blaster = workers[i]; if( blaster ) blaster->Stop(); } // now delete all of the workers (which will cause a blocking wait until it is actually finished) for( int i = 0; i < workers.GetCount(); i++ ) { blaster = workers[i]; if( blaster ) delete blaster; } // clear the array workers.RemoveAll(); // wipe out any IP addresses we added while( !ipContexts.IsEmpty() ) { ULONG context = ipContexts.RemoveHead(); DeleteIPAddress(context); } } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ LRESULT CurlBlastDlg::OnUpdateUI(WPARAM wParal, LPARAM lParam) { // only update every 100ms at most static DWORD lastTime = 0; static DWORD lastCount = 0; DWORD tick = GetTickCount(); if( lastTime && (tick - lastTime > 100) ) { __int64 now; QueryPerformanceCounter((LARGE_INTEGER *)&now); // update the count of url's hit so far DWORD count = 0; for( int i = 0; i < workers.GetCount(); i++ ) { CURLBlaster * blaster = workers[i]; if( blaster ) count += blaster->count; } // calculate the rate if( start ) { if( count != lastCount ) { lastCount = count; CString buff; buff.Format(_T("Completed %d URLs...\n"), count); CString stat; urlManager.GetStatus(stat); buff += stat; status.SetWindowText(buff); double sec = (double)(now - start) / (double)freq; if( sec != 0.0 ) { double ups = (double)count / sec; DWORD upd = (DWORD)(ups * 60.0 * 60.0 * 24.0); buff.Format(_T("Rate: %d urls/day"), upd); rate.SetWindowText(buff); } } } else { start = now; lastUpload = start; } // calculate the CPU usage __int64 idleTime, kernelTime, userTime; if( GetSystemTimes((FILETIME*)&idleTime, (FILETIME*)&kernelTime, (FILETIME*)&userTime) ) { if( firstIdleTime ) { __int64 idle = idleTime - firstIdleTime; __int64 kernel = kernelTime - firstKernelTime; __int64 user = userTime - firstUserTime; __int64 sys = kernel + user; if( sys ) { int avg = (int)( (sys - idle) * 100 / sys ); idle = idleTime - lastIdleTime; kernel = kernelTime - lastKernelTime; user = userTime - lastUserTime; sys = kernel + user; if( sys ) { int last = (int)( ((kernel + user) - idle) * 100 / (kernel + user) ); CString buff; buff.Format(_T("CPU Usage: %d%% (%d%% instantaneous)"), avg, last); cpu.SetWindowText(buff); } } } else { firstIdleTime = idleTime; firstKernelTime = kernelTime; firstUserTime = userTime; } lastIdleTime = idleTime; lastKernelTime = kernelTime; lastUserTime = userTime; } } lastTime = tick; return 0; } /*----------------------------------------------------------------------------- Load the settings from urlBlaster.ini in the same directory as the exe -----------------------------------------------------------------------------*/ void CurlBlastDlg::LoadSettings(void) { USES_CONVERSION; TCHAR buff[1024]; TCHAR iniFile[MAX_PATH]; iniFile[0] = 0; GetModuleFileName(NULL, iniFile, _countof(iniFile)); lstrcpy( PathFindFileName(iniFile), _T("urlBlast.ini") ); startupDelay = GetPrivateProfileInt(_T("Configuration"), _T("Startup Delay"), 10, iniFile) * 1000; threadCount = GetPrivateProfileInt(_T("Configuration"), _T("Thread Count"), 1, iniFile); timeout = GetPrivateProfileInt(_T("Configuration"), _T("Timeout"), 120, iniFile); testType = GetPrivateProfileInt(_T("Configuration"), _T("Test Type"), 4, iniFile); rebootInterval = GetPrivateProfileInt(_T("Configuration"), _T("Reboot Interval"), 0, iniFile); clearCacheInterval = GetPrivateProfileInt(_T("Configuration"), _T("Clear Cache Interval"), 0, iniFile); labID = GetPrivateProfileInt(_T("Configuration"), _T("Lab ID"), -1, iniFile); dialerID = GetPrivateProfileInt(_T("Configuration"), _T("Dialer ID"), 0, iniFile); connectionType = GetPrivateProfileInt(_T("Configuration"), _T("Connection Type"), -1, iniFile); uploadLogsInterval = GetPrivateProfileInt(_T("Configuration"), _T("Upload logs interval"), 0, iniFile); experimental = GetPrivateProfileInt(_T("Configuration"), _T("Experimental"), 0, iniFile); minInterval = GetPrivateProfileInt(_T("Configuration"), _T("Min Interval"), 5, iniFile); screenShotErrors = GetPrivateProfileInt(_T("Configuration"), _T("Screen Shot Errors"), 0, iniFile); checkOpt = GetPrivateProfileInt(_T("Configuration"), _T("Check Optimizations"), 1, iniFile); browserWidth = GetPrivateProfileInt(_T("Configuration"), _T("Browser Width"), 1024, iniFile); browserHeight = GetPrivateProfileInt(_T("Configuration"), _T("Browser Height"), 768, iniFile); debug = GetPrivateProfileInt(_T("Configuration"), _T("debug"), 0, iniFile); pipeIn = GetPrivateProfileInt(_T("Configuration"), _T("pipe in"), 1, iniFile); pipeOut = GetPrivateProfileInt(_T("Configuration"), _T("pipe out"), 2, iniFile); ec2 = GetPrivateProfileInt(_T("Configuration"), _T("ec2"), 0, iniFile); log.debug = debug; // Default to 1 thread if it was set to zero if( !threadCount ) threadCount = 1; // stop using these as soon as is humanly possible - it's an ugly hack and we now have the connection type // explicitly in the config file testID = GetPrivateProfileInt(_T("Configuration"), _T("Test ID"), 0, iniFile); configID = GetPrivateProfileInt(_T("Configuration"), _T("Config ID"), 0, iniFile); // account informatiion if( GetPrivateProfileString(_T("Configuration"), _T("account"), _T(""), buff, _countof(buff), iniFile ) ) accountBase = buff; if( GetPrivateProfileString(_T("Configuration"), _T("password"), _T(""), buff, _countof(buff), iniFile ) ) password = buff; // pre and post launch commands if( GetPrivateProfileString(_T("Configuration"), _T("pre launch"), _T(""), buff, _countof(buff), iniFile ) ) preLaunch = buff; if( GetPrivateProfileString(_T("Configuration"), _T("post launch"), _T(""), buff, _countof(buff), iniFile ) ) postLaunch = buff; // dynatrace path if( GetPrivateProfileString(_T("Configuration"), _T("dynaTrace"), _T(""), buff, _countof(buff), iniFile ) ) dynaTrace = buff; if( GetPrivateProfileString(_T("Configuration"), _T("Log File"), _T("c:\\urlBlast"), buff, _countof(buff), iniFile ) ) { logFile = buff; logFile.Replace(_T("%MACHINE%"), computerName); urlManager.SetLogFile(logFile); } log.SetLogFile(logFile); if( GetPrivateProfileString(_T("Configuration"), _T("Event Text"), _T(""), buff, _countof(buff), iniFile ) ) customEventText = buff; double objectSampleRate = 100.0; if( GetPrivateProfileString(_T("Configuration"), _T("Object Sample Rate"), _T("100.0"), buff, _countof(buff), iniFile ) ) objectSampleRate = _tstof(buff); if( GetPrivateProfileString(_T("Configuration"), _T("Upload log file"), _T(""), buff, _countof(buff), iniFile ) ) { CString uploadLogFile = buff; // add the test ID and config ID as necessary CString id; id.Format(_T("%d"), testID); uploadLogFile.Replace(_T("%TESTID%"), id); id.Format(_T("%d"), configID); uploadLogFile.Replace(_T("%CONFIGID%"), id); uploadLogFiles.Add(uploadLogFile); } // get any additional upload log files int index = 2; TCHAR val[34]; while( GetPrivateProfileString(_T("Configuration"), CString(_T("Upload log file ")) + _itot(index, val, 10), _T(""), buff, _countof(buff), iniFile ) ) { CString uploadLogFile = buff; // add the test ID and config ID as necessary CString id; id.Format(_T("%d"), testID); uploadLogFile.Replace(_T("%TESTID%"), id); id.Format(_T("%d"), configID); uploadLogFile.Replace(_T("%CONFIGID%"), id); uploadLogFiles.Add(uploadLogFile); index++; } if( GetPrivateProfileString(_T("Configuration"), _T("Alive File"), _T(""), buff, _countof(buff), iniFile ) ) { aliveFile = buff; aliveFile.Replace(_T("%MACHINE%"), computerName); } if( GetPrivateProfileString(_T("Configuration"), _T("Url List"), _T(""), buff, _countof(buff), iniFile ) ) { urlManager.SetUrlList(buff); urlManager.SetObjectSampleRate(objectSampleRate); } if( GetPrivateProfileString(_T("Configuration"), _T("Url Files Dir"), _T(""), buff, _countof(buff), iniFile ) ) { CString dir = buff; if( dir.Right(1) != '\\' ) dir += "\\"; urlManager.SetFilesDir(dir); } if( GetPrivateProfileString(_T("Configuration"), _T("Url Files Url"), _T(""), buff, _countof(buff), iniFile ) ) { CString http = buff; if( http.Right(1) != '/' ) http += "/"; urlManager.SetHttp(http); } if( GetPrivateProfileString(_T("Configuration"), _T("Location Key"), _T(""), buff, _countof(buff), iniFile ) ) urlManager.SetHttpKey(buff); if( GetPrivateProfileString(_T("Configuration"), _T("Proxy"), _T(""), buff, _countof(buff), iniFile ) ) urlManager.SetHttpProxy(buff); if( GetPrivateProfileInt(_T("Configuration"), _T("No Update"), 0, iniFile ) ) urlManager.SetNoUpdate(true); if( GetPrivateProfileString(_T("Configuration"), _T("Location"), _T(""), buff, _countof(buff), iniFile ) ) urlManager.SetHttpLocation(buff); if( GetPrivateProfileString(_T("Configuration"), _T("Crawler Config"), _T(""), buff, _countof(buff), iniFile ) ) urlManager.SetCrawlerConfig(buff); if( GetPrivateProfileString(_T("Configuration"), _T("Crawler Files Dir"), _T(""), buff, _countof(buff), iniFile ) ) urlManager.SetCrawlerFilesDir(buff); // set up the global url manager settings urlManager.SetMinInterval(minInterval); urlManager.SetTestType(testType); urlManager.SetCheckOpt(checkOpt); // see if we need to figure out the Dialer ID or Lab ID from the machine name if( !dialerID ) { // find the index of the first number in the machine name int index = -1; int len = computerName.GetLength(); for( int i = 0; i < len && index == -1; i++ ) if( _istdigit(computerName[i]) ) index = i; if( !dialerID && index != -1 ) dialerID = _ttol(computerName.Right(len - index)); if( !labID ) { CString baseName = computerName.Left(index); labID = GetPrivateProfileInt(_T("Labs"), baseName, -1, iniFile); } } // make sure the directory for the log file exists TCHAR szDir[MAX_PATH]; lstrcpy(szDir, (LPCTSTR)logFile); LPTSTR szFile = PathFindFileName(szDir); *szFile = 0; if( lstrlen(szDir) > 3 ) SHCreateDirectoryEx(NULL, szDir, NULL); // get the machine's IP addresses addresses.RemoveAll(); if( threadCount > 1 ) { PMIB_IPADDRTABLE pIPAddrTable; DWORD dwSize = sizeof(MIB_IPADDRTABLE); pIPAddrTable = (MIB_IPADDRTABLE*)malloc(dwSize); if( pIPAddrTable ) { DWORD ret = GetIpAddrTable(pIPAddrTable, &dwSize, TRUE); if( ret == ERROR_INSUFFICIENT_BUFFER) { free( pIPAddrTable ); pIPAddrTable = (MIB_IPADDRTABLE *) malloc ( dwSize ); if(pIPAddrTable) ret = GetIpAddrTable(pIPAddrTable, &dwSize, TRUE); } if( ret == NO_ERROR ) { // figure out which interface has the default gateway on it (we only want those addresses) IPAddr ipAddr = 0x0100A398; // 152.163.0.1 DWORD iface; if( GetBestInterface(ipAddr, &iface) == NO_ERROR ) { ifIndex = iface; for( DWORD i = 0; i < pIPAddrTable->dwNumEntries; i++ ) { if( pIPAddrTable->table[i].dwIndex == iface ) { in_addr addr; addr.S_un.S_addr = pIPAddrTable->table[i].dwAddr; addresses.Add(A2T(inet_ntoa(addr))); } } } } if( pIPAddrTable ) free(pIPAddrTable); } } // see if we need to get the EC2 configuration if( ec2 ) GetEC2Config(); // adjust the clear cache interval and reboot interval +- 20% to level out the dialers if( clearCacheInterval ) clearCacheInterval = clearCacheInterval + (rand() % (int)((double)clearCacheInterval * 0.4)) - (int)((double)clearCacheInterval * 0.2); if( rebootInterval ) rebootInterval = rebootInterval + (rand() % (int)((double)rebootInterval * 0.4)) - (int)((double)rebootInterval * 0.2); } /*----------------------------------------------------------------------------- Check to see if it is time to reboot -----------------------------------------------------------------------------*/ bool CurlBlastDlg::CheckReboot(bool force) { bool ret = false; // force a reboot if we are having issues (like not checking for work for 30 minutes) if( urlManager.NeedReboot() ) force = true; bool reboot = force; if( force || (rebootInterval && start && testType != 6) ) { __int64 now; QueryPerformanceCounter((LARGE_INTEGER *)&now); int minutes = (DWORD)(((now - start) / freq) / 60); int remaining = 0; if( minutes < rebootInterval ) remaining = rebootInterval - minutes; // check to see if we're having browsing problems and if so, force a reboot // all threads must have had 2 consecutive errors before we decide to reboot // CURLBlaster * blaster; bool rebootErrors = false; /* if( workers.GetCount() ) { rebootErrors = true; for( int i = 0; i < workers.GetCount() && rebootErrors; i++ ) { blaster = workers[i]; if( blaster && blaster->sequentialErrors < 2 ) rebootErrors = false; } } */ if( rebootErrors ) log.LogEvent(event_SequentialErrors); if( remaining && !rebootErrors ) { CString buff; buff.Format(_T("Rebooting in %d minute(s)"), remaining); rebooting.SetWindowText(buff); } else if( running ) reboot = true; if( reboot ) { ret = true; // shut everything down and reboot CWaitCursor w; KillTimer(1); KillTimer(2); rebooting.SetWindowText(_T("Rebooting NOW!")); status.SetWindowText(_T("Preparing to reboot...")); // signal and wait for all of the workers to finish KillWorkers(); if( rebootErrors ) log.LogEvent(event_Reboot, 1, _T("Error count exceeded")); else log.LogEvent(event_Reboot); // upload our current log files UploadLogs(); // ok, do the actual reboot HANDLE hToken; if( OpenProcessToken( GetCurrentProcess() , TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY , &hToken) ) { TOKEN_PRIVILEGES tp; if( LookupPrivilegeValue( NULL , SE_SHUTDOWN_NAME , &tp.Privileges[0].Luid ) ) { tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken , FALSE , &tp , 0 , (PTOKEN_PRIVILEGES) 0 , 0 ) ; } CloseHandle(hToken); } InitiateSystemShutdown( NULL, _T("URL Blast reboot interval expired."), 0, TRUE, TRUE ); } } return ret; } /*----------------------------------------------------------------------------- Check to see if we need to write out the alive file (every 60 seconds if one is configured) -----------------------------------------------------------------------------*/ void CurlBlastDlg::WriteAlive(void) { static DWORD lastWrite = 0; if( aliveFile.GetLength() ) { DWORD now = GetTickCount(); if( now < lastWrite || now - lastWrite > 60000 || !lastWrite ) { // make sure the directory for the alive file exists TCHAR szDir[MAX_PATH]; lstrcpy(szDir, (LPCTSTR)aliveFile); LPTSTR szFile = PathFindFileName(szDir); *szFile = 0; if( lstrlen(szDir) > 3 ) SHCreateDirectoryEx(NULL, szDir, NULL); lastWrite = now; HANDLE hFile = CreateFile(aliveFile, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &nullDacl, CREATE_ALWAYS, 0, 0); if( hFile != INVALID_HANDLE_VALUE ) CloseHandle(hFile); } } } /*----------------------------------------------------------------------------- Check to see if we need to upload our log files -----------------------------------------------------------------------------*/ void CurlBlastDlg::CheckUploadLogs(void) { if( uploadLogsInterval && lastUpload && testType != 6 ) { __int64 now; QueryPerformanceCounter((LARGE_INTEGER *)&now); int elapsed = (int)(((now - lastUpload) / freq) / 60); if( elapsed >= uploadLogsInterval ) { // record this even if it didn't work so we don't try again right away lastUpload = now; // make sure we're not going to reboot soon (which would also upload the log files) // otherwise just let the reboot do the upload bool upload = true; if( rebootInterval && start ) { int minutes = (DWORD)(((now - start) / freq) / 60); int remaining = 0; if( minutes < rebootInterval ) remaining = rebootInterval - minutes; if( remaining < (uploadLogsInterval / 2) ) upload = false; } // upload the actual log files if( upload ) UploadLogs(); } } } /*----------------------------------------------------------------------------- Upload the log files -----------------------------------------------------------------------------*/ void CurlBlastDlg::UploadLogs(void) { bool ok = false; status.SetWindowText(_T("Uploading log files...")); // make sure they are really supposed to be uploaded if( uploadLogsInterval && uploadLogFiles.GetCount() ) { // make sure all of the logs exist (even if they are empty) HANDLE hFile = CreateFile(logFile + _T("_IEWPG.txt"), GENERIC_READ | GENERIC_WRITE, 0, &nullDacl, OPEN_ALWAYS, 0, 0); if( hFile != INVALID_HANDLE_VALUE ) CloseHandle(hFile); hFile = CreateFile(logFile + _T("_IEWTR.txt"), GENERIC_READ | GENERIC_WRITE, 0, &nullDacl, OPEN_ALWAYS, 0, 0); if( hFile != INVALID_HANDLE_VALUE ) CloseHandle(hFile); hFile = CreateFile(logFile + _T("_log.txt"), GENERIC_READ | GENERIC_WRITE, 0, &nullDacl, OPEN_ALWAYS, 0, 0); if( hFile != INVALID_HANDLE_VALUE ) CloseHandle(hFile); // build the date part of the file name CTime t = CTime::GetCurrentTime(); // open (and lock) the local log files DWORD startMS = GetTickCount(); HANDLE hSrc1 = INVALID_HANDLE_VALUE; do { hSrc1 = CreateFile(logFile + _T("_IEWPG.txt"), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if( hSrc1 == INVALID_HANDLE_VALUE ) Sleep(100); }while( hSrc1 == INVALID_HANDLE_VALUE && GetTickCount() < startMS + 10000 ); if( hSrc1 != INVALID_HANDLE_VALUE ) { startMS = GetTickCount(); HANDLE hSrc2 = INVALID_HANDLE_VALUE; do { hSrc2 = CreateFile(logFile + _T("_IEWTR.txt"), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if( hSrc2 == INVALID_HANDLE_VALUE ) Sleep(100); }while( hSrc2 == INVALID_HANDLE_VALUE && GetTickCount() < startMS + 10000 ); if( hSrc2 != INVALID_HANDLE_VALUE ) { startMS = GetTickCount(); HANDLE hSrc3 = INVALID_HANDLE_VALUE; do { hSrc3 = CreateFile(logFile + _T("_log.txt"), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if( hSrc3 == INVALID_HANDLE_VALUE ) Sleep(100); }while( hSrc3 == INVALID_HANDLE_VALUE && GetTickCount() < startMS + 10000 ); if( hSrc3 != INVALID_HANDLE_VALUE ) { // loop through all of the log files for( int index = 0; index < uploadLogFiles.GetCount(); index++ ) { CString uploadLogFile = uploadLogFiles[index]; // build the destination log file root CString destFile = uploadLogFile; destFile.Replace(_T("%MACHINE%"), computerName); destFile.Replace(_T("%DATE%"), (LPCTSTR)t.Format(_T("%Y%m%d"))); destFile.Replace(_T("%TIME%"), (LPCTSTR)t.Format(_T("%H%M%S"))); // make sure the directory for the log file exists TCHAR szDir[MAX_PATH]; lstrcpy(szDir, (LPCTSTR)destFile); LPTSTR szFile = PathFindFileName(szDir); *szFile = 0; if( lstrlen(szDir) > 3 ) SHCreateDirectoryEx(NULL, szDir, NULL); // open (and lock) the remote log files startMS = GetTickCount(); HANDLE hDest1 = INVALID_HANDLE_VALUE; do { hDest1 = CreateFile(destFile + _T("_IEWPG.txt"), GENERIC_WRITE, 0, &nullDacl, OPEN_ALWAYS, 0, 0); if( hDest1 == INVALID_HANDLE_VALUE ) Sleep(100); }while( hDest1 == INVALID_HANDLE_VALUE && GetTickCount() < startMS + 10000 ); if( hDest1 != INVALID_HANDLE_VALUE ) { startMS = GetTickCount(); HANDLE hDest2 = INVALID_HANDLE_VALUE; do { hDest2 = CreateFile(destFile + _T("_IEWTR.txt"), GENERIC_WRITE, 0, &nullDacl, OPEN_ALWAYS, 0, 0); if( hDest2 == INVALID_HANDLE_VALUE ) Sleep(100); }while( hDest2 == INVALID_HANDLE_VALUE && GetTickCount() < startMS + 10000 ); if( hDest2 != INVALID_HANDLE_VALUE ) { startMS = GetTickCount(); HANDLE hDest3 = INVALID_HANDLE_VALUE; do { hDest3 = CreateFile(destFile + _T("_log.txt"), GENERIC_WRITE, 0, &nullDacl, OPEN_ALWAYS, 0, 0); if( hDest3 == INVALID_HANDLE_VALUE ) Sleep(100); }while( hDest3 == INVALID_HANDLE_VALUE && GetTickCount() < startMS + 10000 ); if( hDest3 != INVALID_HANDLE_VALUE ) { // move to the beginning of the source files SetFilePointer(hSrc1, 0, 0, FILE_BEGIN); SetFilePointer(hSrc2, 0, 0, FILE_BEGIN); SetFilePointer(hSrc3, 0, 0, FILE_BEGIN); // move to the end of the output files (in case they already existed) SetFilePointer(hDest1, 0, 0, FILE_END); SetFilePointer(hDest2, 0, 0, FILE_END); SetFilePointer(hDest3, 0, 0, FILE_END); // copy the log files over BYTE buff[8192]; DWORD bytes, written; while( ReadFile(hSrc1, buff, sizeof(buff), &bytes, 0) && bytes ) WriteFile(hDest1, buff, bytes, &written, 0); while( ReadFile(hSrc2, buff, sizeof(buff), &bytes, 0) && bytes ) WriteFile(hDest2, buff, bytes, &written, 0); while( ReadFile(hSrc3, buff, sizeof(buff), &bytes, 0) && bytes ) WriteFile(hDest3, buff, bytes, &written, 0); ok = true; CloseHandle(hDest3); } CloseHandle(hDest2); } CloseHandle(hDest1); } } // truncate the source files (only if the upload was successful) if( ok ) { SetFilePointer(hSrc1, 0, 0, FILE_BEGIN); SetFilePointer(hSrc2, 0, 0, FILE_BEGIN); SetFilePointer(hSrc3, 0, 0, FILE_BEGIN); SetEndOfFile(hSrc1); SetEndOfFile(hSrc2); SetEndOfFile(hSrc3); } CloseHandle(hSrc3); } CloseHandle(hSrc2); } CloseHandle(hSrc1); } } if( ok ) log.LogEvent(event_LogUpload); else log.LogEvent(event_LogUpload, 1); log.LogMachineInfo(); } /*----------------------------------------------------------------------------- Kill any Dr. Watson windows that are open (we already killed the browser process) -----------------------------------------------------------------------------*/ void CurlBlastDlg::KillProcs(void) { #ifndef _DEBUG WTS_PROCESS_INFO * proc = NULL; DWORD count = 0; if( WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &proc, &count) ) { for( DWORD i = 0; i < count; i++ ) { bool terminate = false; // check for Dr. Watson if( !lstrcmpi(PathFindFileName(proc[i].pProcessName), _T("dwwin.exe")) ) { if( !bDrWatson ) { log.LogEvent(event_KilledDrWatson); bDrWatson = true; } terminate = true; } else if(lstrcmpi(PathFindFileName(proc[i].pProcessName), _T("iexplore.exe"))) { // kill any processes that belong to our test users thaat we did not launch (and that aren't IE) CURLBlaster * blaster; for( int j = 0; j < workers.GetCount() && !terminate; j++ ) { blaster = workers[j]; if( blaster ) { EnterCriticalSection( &(blaster->cs) ); // make sure it's not the browser we launched if( proc[i].ProcessId != blaster->browserPID && blaster->userSID && proc[i].pUserSid && IsValidSid(blaster->userSID) && IsValidSid(proc[i].pUserSid) ) { // see if the SID matches if( EqualSid(proc[i].pUserSid, blaster->userSID ) ) terminate = true; } LeaveCriticalSection( &(blaster->cs) ); } } } if( terminate ) { HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, proc[i].ProcessId); if( hProc ) { TerminateProcess(hProc, 0); CloseHandle(hProc); } } } WTSFreeMemory(proc); } #endif } /*----------------------------------------------------------------------------- Close any dialog windows that may be open -----------------------------------------------------------------------------*/ void CurlBlastDlg::CloseDialogs(void) { // if there are any explorer windows open, disable this code (for local debugging and other work) if( !::FindWindow(_T("CabinetWClass"), NULL ) ) { HWND hDesktop = ::GetDesktopWindow(); HWND hWnd = ::GetWindow(hDesktop, GW_CHILD); TCHAR szClass[100]; TCHAR szTitle[1025]; CArray<HWND> hDlg; const TCHAR * szKeepOpen[] = { _T("urlblast") , _T("url blast") , _T("task manager") , _T("aol pagetest") , _T("choose file") , _T("network delay simulator") , _T("shut down windows") }; // build a list of dialogs to close while(hWnd) { if(hWnd != m_hWnd) { if(::IsWindowVisible(hWnd)) if(::GetClassName(hWnd, szClass, 100)) if((!lstrcmp(szClass,_T("#32770"))||!lstrcmp(szClass,_T("Internet Explorer_Server")))) // check window title for all classes { bool bKill = true; // make sure it is not in our list of windows to keep if(::GetWindowText( hWnd, szTitle, 1024)) { log.Trace(_T("Killing Dialog: %s"), szTitle); _tcslwr_s(szTitle, _countof(szTitle)); for(int i = 0; i < _countof(szKeepOpen) && bKill; i++) { if(_tcsstr(szTitle, szKeepOpen[i])) bKill = false; } // do we have to terminate the process that owns it? if( !lstrcmp(szTitle, _T("server busy")) ) { log.Trace(_T("Terminating process")); DWORD pid; GetWindowThreadProcessId(hWnd, &pid); HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pid); if( hProcess ) { TerminateProcess(hProcess, 0); CloseHandle(hProcess); } } } if(bKill) hDlg.Add(hWnd); } } hWnd = ::GetWindow(hWnd, GW_HWNDNEXT); } // close all of the dialogs for(int i = 0; i < hDlg.GetSize(); i++) { //see if there is an OK button HWND hOk = ::FindWindowEx(hDlg[i], 0, 0, _T("OK")); if( hOk ) { int id = ::GetDlgCtrlID(hOk); if( !id ) id = IDOK; ::PostMessage(hDlg[i],WM_COMMAND,id,0); } else ::PostMessage(hDlg[i],WM_CLOSE,0,0); } } } /*----------------------------------------------------------------------------- See if we need to exit -----------------------------------------------------------------------------*/ void CurlBlastDlg::CheckExit(void) { if( running && testType == 6 ) if( urlManager.Done() ) { log.Trace(_T("CheckExit() - exiting")); // if we are crawling, do we need to upload logs or reboot? if( testType == 6 ) { if( rebootInterval && start ) CheckReboot(true); else OnClose(); } else OnClose(); } } /*----------------------------------------------------------------------------- Disable the DNS caching service -----------------------------------------------------------------------------*/ void CurlBlastDlg::DisableDNSCache(void) { // only disable the DNS cache if we are running more than one thread, otherwise we'll just rely on the dns flush if( threadCount > 1 ) { SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if( scm ) { SC_HANDLE svc = OpenService(scm, _T("dnscache"), GENERIC_READ | GENERIC_EXECUTE); if( svc ) { // stop the service SERVICE_STATUS status; if( ControlService(svc, SERVICE_CONTROL_STOP, &status) ) { // wait for it to actually stop while( status.dwCurrentState != SERVICE_STOPPED ) { Sleep(500); if( !QueryServiceStatus(svc, &status) ) status.dwCurrentState = SERVICE_STOPPED; } } CloseServiceHandle(svc); } CloseServiceHandle(scm); } } } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CurlBlastDlg::ClearCaches(void) { bool forceClear = false; // find any user.machine name directories that indicate a user profile gone bad WIN32_FIND_DATA fd; CString dir = _T("C:\\Documents and Settings"); TCHAR path[MAX_PATH]; DWORD len = _countof(path); if( GetProfilesDirectory( path, &len ) ) dir = path; dir += _T("\\"); HANDLE hFind = FindFirstFile(dir + _T("user*.*"), &fd); if( hFind != INVALID_HANDLE_VALUE ) { do { if( lstrlen(PathFindExtension(fd.cFileName)) > 1 ) forceClear = true; }while(!forceClear && FindNextFile(hFind, &fd)); FindClose(hFind); } if( forceClear || clearCacheInterval > 0 ) { COleDateTime currentDate(time(0)); DATE date = 1; HKEY hKey; if( SUCCEEDED(RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\AOL\\UrlBlast"), 0, 0, 0, KEY_READ | KEY_WRITE, 0, &hKey, 0))) { bool clear = true; DWORD bytes = sizeof(date); if( SUCCEEDED(RegQueryValueEx(hKey, _T("Cache Cleared Date"), 0, 0, (LPBYTE)&date, &bytes)) ) { COleDateTime lastClear(date); COleDateTimeSpan elapsed = currentDate - lastClear; if(elapsed.GetDays() < clearCacheInterval) clear = false; } if( forceClear || clear ) { // delete the user profiles status.SetWindowText(_T("Clearing browser caches...")); hFind = FindFirstFile(dir + _T("user*.*"), &fd); if( hFind != INVALID_HANDLE_VALUE ) { do { TCHAR path[MAX_PATH + 1]; DWORD len = sizeof(path); memset(path, 0, sizeof(path)); lstrcpy(path, dir); lstrcat(path, fd.cFileName); SHFILEOPSTRUCT op; memset(&op, 0, sizeof(op)); op.wFunc = FO_DELETE; op.pFrom = path; op.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR; SHFileOperation(&op); }while(FindNextFile(hFind, &fd)); FindClose(hFind); } // defrag the hard drive status.SetWindowText(_T("Defragmenting the hard drive...")); Defrag(); // store the time things were cleared date = currentDate; RegSetValueEx(hKey, _T("Cache Cleared Date"), 0, REG_BINARY, (LPBYTE)&date, sizeof(date)); log.LogEvent(event_ProfilesReset); log.LogMachineInfo(); } RegCloseKey(hKey); } } // continue the startup process PostMessage(MSG_CONTINUE_STARTUP); } /*----------------------------------------------------------------------------- Defrag the hard drive -----------------------------------------------------------------------------*/ void CurlBlastDlg::Defrag(void) { TCHAR cmd[100]; lstrcpy( cmd, _T("defrag c: -f -v") ); STARTUPINFO si; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); PROCESS_INFORMATION pi; if( CreateProcess(NULL, cmd, 0, 0, FALSE, 0, 0, 0, &si, &pi) ) { WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } } /*----------------------------------------------------------------------------- Background processing is complete, start up the actual testing -----------------------------------------------------------------------------*/ LRESULT CurlBlastDlg::OnContinueStartup(WPARAM wParal, LPARAM lParam) { // flag as running and see if we need to reboot if( !CheckReboot() ) { // start up the url manager urlManager.Start(); // create all of the workers status.SetWindowText(_T("Starting workers...")); // see if we had enough addresses to use (we need one extra if we are binding to specific addresses) if( addresses.GetCount() <= threadCount ) addresses.RemoveAll(); CRect desktop(0,0,browserWidth,browserHeight); // launch the worker threads DWORD useBitBlt = 0; if( threadCount == 1 ) useBitBlt = 1; HANDLE * cacheHandles = new HANDLE[threadCount]; HANDLE * runHandles = new HANDLE[threadCount]; for( int i = 0; i < threadCount; i++ ) { CString buff; buff.Format(_T("Starting user%d..."), i+1); status.SetWindowText(buff); CURLBlaster * blaster = new CURLBlaster(m_hWnd, log); workers.Add(blaster); cacheHandles[i] = blaster->hClearedCache; runHandles[i] = blaster->hRun; // pass on configuration information blaster->errorLog = logFile; blaster->testType = testType; blaster->urlManager = &urlManager; blaster->labID = labID; blaster->dialerID = dialerID; blaster->connectionType = connectionType; blaster->timeout = timeout; blaster->experimental = experimental; blaster->desktop = desktop; blaster->customEventText= customEventText; blaster->screenShotErrors = screenShotErrors; blaster->accountBase = accountBase; blaster->password = password; blaster->preLaunch = preLaunch; blaster->postLaunch = postLaunch; blaster->dynaTrace = dynaTrace; blaster->pipeIn = pipeIn; blaster->pipeOut = pipeOut; blaster->useBitBlt = useBitBlt; // force 1024x768 for screen shots blaster->pos.right = browserWidth; blaster->pos.bottom = browserHeight; // hand an address to the thread to use (hand them out backwards) if( !addresses.IsEmpty() ) blaster->ipAddress = addresses[addresses.GetCount() - i - 1]; blaster->Start(i+1); } status.SetWindowText(_T("Clearing caches...")); // wait for all of the threads to finish clearing their caches WaitForMultipleObjects(threadCount, cacheHandles, TRUE, INFINITE); // start the threads running (1/2 second apart) for( int i = 0; i < threadCount; i++ ) { CString buff; buff.Format(_T("Starting user%d..."), i+1); status.SetWindowText(buff); SetEvent(runHandles[i]); Sleep(500); } delete [] cacheHandles; delete [] runHandles; // send a UI update message PostMessage(MSG_UPDATE_UI); status.SetWindowText(_T("Running...")); } running = true; return 0; } /*----------------------------------------------------------------------------- Set the screen resolution if it is currently too low -----------------------------------------------------------------------------*/ void CurlBlastDlg::SetupScreen(void) { DEVMODE mode; memset(&mode, 0, sizeof(mode)); mode.dmSize = sizeof(mode); CStringA settings; DWORD x = 0, y = 0, bpp = 0; // Go through the possible modes to find the best candidate (>=1024x768 with the highest bpp) int index = 0; while( EnumDisplaySettings( NULL, index, &mode) ) { index++; if( mode.dmPelsWidth >= (DWORD)browserWidth && mode.dmPelsHeight >= (DWORD)browserHeight && mode.dmBitsPerPel > bpp ) { x = mode.dmPelsWidth; y = mode.dmPelsHeight; bpp = mode.dmBitsPerPel; } } // get the current settings if( x && y && bpp && EnumDisplaySettings( NULL, ENUM_CURRENT_SETTINGS, &mode) ) { if( mode.dmPelsWidth < x || mode.dmPelsHeight < y || mode.dmBitsPerPel < bpp ) { DEVMODE newMode; memcpy(&newMode, &mode, sizeof(mode)); newMode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; newMode.dmBitsPerPel = bpp; newMode.dmPelsWidth = x; newMode.dmPelsHeight = y; ChangeDisplaySettings( &newMode, CDS_UPDATEREGISTRY | CDS_GLOBAL ); } } } /*----------------------------------------------------------------------------- Dynamically configure the location and server for an EC2 instance -----------------------------------------------------------------------------*/ void CurlBlastDlg::GetEC2Config() { log.Trace(_T("GetEC2Config")); CString server, location, locationKey; CString userData; if( GetUrlText(_T("http://169.254.169.254/latest/user-data"), userData) ) { int pos = 0; do{ CString token = userData.Tokenize(_T(" &"), pos).Trim(); if( token.GetLength() ) { int split = token.Find(_T('='), 0); if( split > 0 ) { CString key = token.Left(split).Trim(); CString value = token.Mid(split + 1).Trim(); if( key.GetLength() ) { if( !key.CompareNoCase(_T("wpt_server")) && value.GetLength() ) server = CString(_T("http://")) + value + _T("/work/"); else if( !key.CompareNoCase(_T("wpt_location")) && value.GetLength() ) location = value; else if( !key.CompareNoCase(_T("wpt_key")) ) locationKey = value; else if( !key.CompareNoCase(_T("wpt_threads")) && value.GetLength() ) threadCount = _ttol(value); else if( !key.CompareNoCase(_T("wpt_timeout")) && value.GetLength() ) timeout = _ttol(value); else if( !key.CompareNoCase(_T("wpt_reboot_interval")) && value.GetLength() ) rebootInterval = _ttol(value); else if( !key.CompareNoCase(_T("wpt_defrag_interval")) && value.GetLength() ) clearCacheInterval = _ttol(value); } } } }while(pos > 0); } if( location.IsEmpty() ) { // build the location name automatically from the availability zone CString zone; if( GetUrlText(_T("http://169.254.169.254/latest/meta-data/placement/availability-zone"), zone) ) { int pos = zone.Find('-'); if( pos ) { pos = zone.Find('-', pos + 1); if( pos ) { // figure out the browser version TCHAR buff[1024]; CRegKey key; CString ieVer; if( SUCCEEDED(key.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer"), KEY_READ)) ) { DWORD len = _countof(buff); if( SUCCEEDED(key.QueryStringValue(_T("Version"), buff, &len)) ) { ieVer = buff; ieVer.Trim(); ULONG ver = _ttol(ieVer); ieVer.Format(_T("%d"), ver); location = CString(_T("ec2-")) + zone.Left(pos).Trim() + CString(_T("-IE")) + ieVer; } } } } } } CString instance; GetUrlText(_T("http://169.254.169.254/latest/meta-data/instance-id"), instance); instance = instance.Trim(); log.Trace(_T("EC2 server: %s"), (LPCTSTR)server); log.Trace(_T("EC2 location: %s"), (LPCTSTR)location); log.Trace(_T("EC2 locationKey: %s"), (LPCTSTR)locationKey); log.Trace(_T("EC2 Instance ID: %s"), (LPCTSTR)instance); if( !server.IsEmpty() ) urlManager.SetHttp(server); if( !location.IsEmpty() ) urlManager.SetHttpLocation(location); if( !locationKey.IsEmpty() ) urlManager.SetHttpKey(locationKey); if( !instance.IsEmpty() ) urlManager.SetHttpEC2Instance(instance); } /*----------------------------------------------------------------------------- Get a string response from the given url (used for querying the EC2 instance config) -----------------------------------------------------------------------------*/ bool CurlBlastDlg::GetUrlText(CString url, CString &response) { bool ret = false; try { // set up the session CInternetSession * session = new CInternetSession(); if( session ) { DWORD timeout = 10000; session->SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, sizeof(timeout), 0); session->SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, &timeout, sizeof(timeout), 0); CInternetFile * file = (CInternetFile *)session->OpenURL(url); if( file ) { char buff[4097]; DWORD len = sizeof(buff) - 1; UINT bytes = 0; do { bytes = file->Read(buff, len); if( bytes ) { ret = true; buff[bytes] = 0; // NULL-terminate it response += CA2T(buff); } }while( bytes ); file->Close(); delete file; } session->Close(); delete session; } } catch(CInternetException * e) { e->Delete(); } catch(...) { } log.Trace(_T("EC2 '%s' -> '%s'"), (LPCTSTR)url, (LPCTSTR)response); return ret; }
[ "[email protected]@aac4e670-4c05-fb8f-3594-08f7db841d5f" ]
[ [ [ 1, 1672 ] ] ]
b88ab0ef18b4ffa89bca7f8264c1c35e67034f51
b8fbe9079ce8996e739b476d226e73d4ec8e255c
/src/engine/rb_ui/jcheckbox.h
b9872b1eb6d926b8492960984932905eef466b00
[]
no_license
dtbinh/rush
4294f84de1b6e6cc286aaa1dd48cf12b12a467d0
ad75072777438c564ccaa29af43e2a9fd2c51266
refs/heads/master
2021-01-15T17:14:48.417847
2011-06-16T17:41:20
2011-06-16T17:41:20
41,476,633
1
0
null
2015-08-27T09:03:44
2015-08-27T09:03:44
null
UTF-8
C++
false
false
892
h
//****************************************************************************/ // File: JCheckBox.h // Date: 02.09.2005 // Author: Ruslan Shestopalyuk //****************************************************************************/ #ifndef __JCHECKBOX_H__ #define __JCHECKBOX_H__ //****************************************************************************/ // Class: JCheckBox // Desc: Boolean button //****************************************************************************/ class JCheckBox : public JButton { public: JCheckBox (); virtual void Render (); void Check ( bool bCheck = true ); bool IsChecked () const { return IsPressed(); } expose( JCheckBox ) { parent(JButton); } }; // class JCheckBox #endif // __JCHECKBOX_H__
[ [ [ 1, 29 ] ] ]
a72ff4b4d8d00f908ef1da5be2f11af4ccec2e49
bfdfb7c406c318c877b7cbc43bc2dfd925185e50
/engine/hyBytecode.h
57ebb895a9f82de4d52748170b29d4026e73c5b8
[ "MIT" ]
permissive
ysei/Hayat
74cc1e281ae6772b2a05bbeccfcf430215cb435b
b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0
refs/heads/master
2020-12-11T09:07:35.606061
2011-08-01T12:38:39
2011-08-01T12:38:39
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,956
h
/* -*- coding: sjis-dos; -*- */ /* * copyright 2010 FUKUZAWA Tadashi. All rights reserved. */ #ifndef m_HYBYTECODE_H_ #define m_HYBYTECODE_H_ #include "hyClass.h" #include "hySignature.h" #include "hyBytecodeIf.h" #include "hyDebugSourceInfo.h" namespace Hayat { namespace Engine { class CodePtr; class MethodPtr; class Context; class StringBuffer; class Bytecode : public Hayat::Common::BytecodeIf { friend class GC; friend class CodeManager; public: Bytecode(void); virtual ~Bytecode(); void* operator new(size_t size); void operator delete(void* p); bool readFile(const char* fname, void (*loadedCallback)(const char*) = NULL); void setBytecode(const hyu8* buf, hyu32 size); // size分のメモリを自分で確保し、bufからコピーして、setBytecodeする void takeBytecode(const hyu8* buf, hyu32 size); void finalize(void); void initCodePtr(CodePtr* ptr) const; const hyu8* getString(hyu32 offs) const; bool bHaveString(const hyu8* str) const { return (str >= m_stringTable && str < m_stringTable + m_stringTableSize); } const Signature::Sig_t* getSignatureBytes(hyu16 id) const; hyu32 getSignatureBytesLen(hyu16 id) const; hyu8 getSignatureArity(hyu16 id) const; const HClass* mainClass(void) const { return m_mainClass; } bool haveBytecode(void) const { return (m_bytecodeBuf != NULL); } const hyu8* codeStartAddr(void) const { return m_bytecodeBuf; } const hyu8* codeEndAddr(void) const { return m_bytecodeEndAddr; } bool isInCodeAddr(const hyu8* ptr) const { return (m_bytecodeBuf <= ptr) && (ptr < m_bytecodeEndAddr); } SymbolID_t bytecodeSymbol(void) const { return (SymbolID_t)m_mySymbol; } void changeBytecodeSymbol(SymbolID_t asName); // リンクバイトコードも含めてトップレベルクラスを検索する const HClass* searchClass(SymbolID_t classSym) const; // リンクバイトコードも含めてトップレベルメソッドを検索する bool searchMethod(MethodPtr* pMethodPtr, SymbolID_t methodSym, Signature* pSig) const; // リンクバイトコードも含めてトップレベル定数を検索 Value* getConstVarAddr(SymbolID_t varSym) const; // リンクバイトコードに対して再帰的に initLinkBytecode(context, true)を実行し、 // setInitialized()を実行していない状態でかつbExecがtrueなら、 // execBytecodeTop()を実行してsetInitialized()を実行する。 void initLinkBytecode(Context* context, bool bExec = false); void setInitialized(void) { m_initializedFlag = true; } protected: const HClass* m_searchClass(SymbolID_t classSym) const; bool m_searchMethod(MethodPtr* pMethodPtr, SymbolID_t methodSym, Signature* pSig) const; Value* m_getConstVarAddr(SymbolID_t varSym) const; public: void m_GC_mark_staticVar(void); protected: hyu8* m_fileBuf; const HClass* m_mainClass; const hyu8* m_bytecodeBuf; hyu32 m_bytecodeSize; const hyu8* m_bytecodeEndAddr; hyu32 m_stringTableSize; const hyu8* m_stringTable; hyu32 m_signatureTableNum; const hyu32* m_signatureTableOffs; const hyu8* m_signatureTable; const hyu8* m_signatureArityTable; // シンボルは、通常はファイル名の拡張子を ".hyb" にして // シンボル化したもの。 "filename.hy" → :"filename.hyb" SymbolID_t m_mySymbol; hyu16 m_numLinkBytecodes; const SymbolID_t* m_linkBytecodes; bool m_initializedFlag; // バイトコード初期化をしたか #ifdef HY_ENABLE_BYTECODE_RELOAD public: // バイトコードリロード時の旧クラスのデータを新クラスに移す void copyClassDataTo(Bytecode* dest, bool bCopyClassVar, bool bCopyConstVar); protected: BMap<const HClass*, const HClass*> m_generationMap; #endif #ifdef HMD_DEBUG protected: DebugInfos m_debugInfos; static bool m_bReadDebugInf; public: void debugGetInfo(StringBuffer* sb, const hyu8* ptr) const; void debugGetInfo(char* buf, hyu32 bufSize, const hyu8* ptr) const; // バイトコード*.hybの読み込みと同時に、デバッグ情報*.hdbも // 読み込む場合は setFlagReadDebugInfo(true) とする。 // *.hdbは、Debug::setDebugMemPool()で指定したメモリ領域に読む。 // 指定がなければgMemPoolに読む。 static void setFlagReadDebugInfo(bool flag) { m_bReadDebugInf = flag; } #else public: void debugGetInfo(StringBuffer* sb, const hyu8* ptr) const; void debugGetInfo(char* buf, hyu32 bufSize, const hyu8* ptr) const; static void setFlagReadDebugInfo(bool) {} #endif }; } } #endif /* m_HYBYTECODE_H_ */
[ [ [ 1, 148 ] ] ]
de014aa2025acd0d51a78f2066595e03d9b38153
ccc3e2995bc64d09b9e88fea8c1c7e2029a60ed8
/SO/Trabalhos/Trabalho 3/tmp_src/31401/LoggerDLL/Trabalho3/LoggerDLL.cpp
a716c90efb8cf2fed47c29411eb06d97ae30cd94
[]
no_license
masterzdran/semestre5
e559e93017f5e40c29e9f28466ae1c5822fe336e
148d65349073f8ae2f510b5659b94ddf47adc2c7
refs/heads/master
2021-01-25T10:05:42.513229
2011-02-20T17:46:14
2011-02-20T17:46:14
35,061,115
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
10,434
cpp
#define loggerdll_build #include "LoggerDLL.h" #include <tchar.h> #include <stdio.h> #include <locale.h> #include "Include\SesError.h" typedef struct{ DWORD _pageLimit; DWORD _pageNbr; DWORD _pageSize; LPVOID _loggerBase; DWORD _startPtr; DWORD _endPtr; }LogDef; #define __DEFAULT_SIZE__ 1024 //Default Log Size /* static DWORD _pageLimit = 0; //number of pages static DWORD _pageNbr = 0; //number of pages allocced static DWORD _pageSize = 0; //size of the page static LPVOID _loggerBase = NULL; //address of the base virtual alloc static LPTSTR _loggerBaseFree = NULL; //address of the nextpage static LPTSTR _loggerNextFreeByte = NULL; static LPTSTR _loggerNextClearByte = NULL; //address of the oldest byte */ //TLS Entry DWORD tlsIDX = -1; //Routine to Treat The exption and INT PageFaultExceptionFilter(DWORD dwCode, LPEXCEPTION_POINTERS info){ // If the exception is not a page fault, exit. if (dwCode != EXCEPTION_ACCESS_VIOLATION){ printf("Exception code = %d\n", dwCode); return EXCEPTION_EXECUTE_HANDLER; } // If the reserved pages are used up, exit. LogDef* logger = (LogDef*)TlsGetValue(tlsIDX); if (logger->_pageNbr >= logger->_pageLimit){ printf("Exception: out of pages\n"); return EXCEPTION_EXECUTE_HANDLER; } // Otherwise, commit another page. LPVOID lpvResult = VirtualAlloc( logger->_loggerBase, // next page to commit logger-> _pageSize, // page size, in bytes MEM_COMMIT, // allocate a committed page PAGE_READWRITE); // read/write access if (lpvResult == NULL ){ printf("VirtualAlloc failed\n"); return EXCEPTION_EXECUTE_HANDLER; }else { printf ("Allocating another page.\n"); } // Increment the page count logger->_pageNbr++; // Continue execution where the page fault occurred. return EXCEPTION_CONTINUE_EXECUTION; } VOID resetValues() { LogDef* logger = (LogDef*)TlsGetValue(tlsIDX); logger->_endPtr = logger->_startPtr = 0; } static void _DLL_TlsInit() { if ((tlsIDX = TlsAlloc()) == -1) RaiseException(UNABLE_TLS_ALLOC,0,0,NULL); } static void _DLL_TlsEnd() { if( tlsIDX != -1) if( !TlsFree(tlsIDX) ) RaiseException(UNABLE_TLS_FREE,0,0,NULL); } static LogDef* _TlsInit() { LogDef* p = new LogDef[1]; p->_endPtr = p->_startPtr = p->_pageNbr = 0; p->_pageLimit = p->_pageSize = 0 ; p->_loggerBase = 0; if (! TlsSetValue(tlsIDX, p)) RaiseException(UNABLE_TLS_SET_VALUE,0,0,NULL); return p; } static void _TlsClose() { LogDef* p = (LogDef*)TlsGetValue(tlsIDX); if ( p ) { delete p; p=NULL; if ( !TlsSetValue(tlsIDX, p) ) RaiseException(UNABLE_TLS_SET_VALUE,0,0,NULL); } } static BOOL isEmpty(){ LogDef* values = (LogDef*)TlsGetValue(tlsIDX); return (values->_startPtr == values->_endPtr); } static BOOL isFull(){ LogDef* values = (LogDef*)TlsGetValue(tlsIDX); return (values->_endPtr+1 == values->_startPtr); } /** * Uma função para a iniciação do suporte do registo de histórico de informação, * da tarefa que invoca a função, onde deve ser recebido a dimensão máxima admitida (CreateThreadLog(…)) ; * */ void WINAPI CreateThreadLog(DWORD bytes){ if (bytes == 0) RaiseException(INVALID_SIZE_TO_BUFFER,0,0,NULL); LogDef* logger = (LogDef*)TlsGetValue(tlsIDX); SYSTEM_INFO systemInfo ; GetSystemInfo(&systemInfo); logger->_pageSize = systemInfo.dwPageSize; logger->_pageLimit = bytes/logger->_pageSize + 1; logger->_loggerBase = VirtualAlloc(NULL , logger->_pageLimit * logger->_pageSize , MEM_RESERVE , PAGE_NOACCESS); if (logger->_loggerBase == NULL) RaiseException(UNABLE_VIRTUAL_ALLOC,0,0,NULL); //Reseting the buffer pointers, acknowledging the buffer is empty at start. logger->_endPtr = logger->_startPtr = logger->_pageNbr = 0; } /** * Uma função para adicionar informação ao registo de histórico (AppendThreadLog(…)); * */ void WINAPI AppendThreadLog(LPTSTR message){ if (message == NULL) RaiseException(NULL_POINTER_EXPECTION,0,0,NULL); LogDef* logger = (LogDef*)TlsGetValue(tlsIDX); if (logger->_loggerBase == NULL) CreateThreadLog(__DEFAULT_SIZE__); DWORD size = _tcsclen(message); //Usar controlo de excepções //Usar memcopy para copiar a mensagem para o endereço de _loggerBaseFree //Se falhar a excepção chamar a função que vai fazer commit da proxima pagina //ou paginas suficientes para agregar as páginas //Actualizar o valor de _loggerBaseFree para o proximo byte apos ter sido colocada a mensagem if (isFull()) RaiseException(BUFFER_FULL,0,0,NULL); __try { _memccpy((LPVOID)( (int)logger->_loggerBase + (logger->_endPtr)),message,0,size); logger->_endPtr = (logger->_endPtr + size)%(logger->_pageSize * logger->_pageLimit); } __except ( PageFaultExceptionFilter( GetExceptionCode(),GetExceptionInformation() ) ) { //one more page commited } } /** * Uma função para que permita libertar um bloco de informação mais antigo * (segundo a lógica de um buffer circular), * e.g. FreeThreadLog(…, nBytes) o que significa que o espaço dos nBytes mais antigos é libertado; * 1ª versão libertar só espaço não havendo preocupação com as págians commit * 2ª versão fazer uncommit das respectivas páginas mas tendo o cuidado de apenas fazer uncommit de páginas * que estejam totalmente “vazias”. * */ void WINAPI FreeThreadLog(DWORD bytes){ if (bytes == 0 ) RaiseException(BUFFER_SIZE_EMPTY,0,0,NULL); //VirtualFree: para libertar os bytes indicados //se a pagina estiver toda disponivel fazer release //controlar o espaço com buffer circular //Admitindo que bytes é sempre inferior ao total do buffer if (isEmpty()) RaiseException(BUFFER_EMPTY,0,0,NULL); LogDef* logger = (LogDef*)TlsGetValue(tlsIDX); if (bytes > (logger->_pageLimit * logger->_pageSize)) RaiseException(BUFFER_SIZE_OVERFLOW,0,0,NULL); //Relallocating the pointers DWORD releasedPtr = (bytes + logger->_startPtr) % (logger->_pageLimit * logger->_pageSize); //if start pointer is greater than end pointer, is beacause the end pointer has flipped in the circular buffer if (logger->_startPtr > logger->_endPtr){ //if the future pointer is less than the start pointer is because the size in bytes is greater than the allocated space. //Realocation of the pointer if (releasedPtr < logger->_startPtr) releasedPtr = logger->_endPtr; }else{ //if future pointer is greater than end pointer or lesser than the start pointer //reallocate the pointer if (releasedPtr > logger->_endPtr || releasedPtr < logger->_startPtr) releasedPtr = logger->_endPtr; } //Decommiting the space. DWORD startPageIdx = logger->_startPtr / logger->_pageSize; DWORD endPageIdx = releasedPtr / logger->_pageSize; if (startPageIdx != endPageIdx){ BOOL freeLog; LPVOID freeAddr = logger->_loggerBase; for (;startPageIdx < endPageIdx; ((startPageIdx++)%(logger->_pageLimit))){ freeAddr =(LPVOID)( (int)logger->_loggerBase + startPageIdx * logger->_pageSize); freeLog = VirtualFree(freeAddr, 2 ,MEM_DECOMMIT); if (!freeLog){ _tprintf(TEXT("Error while decommiting: %d"),GetLastError()); RaiseException(RESET_THREAD_LOG_INSUCCESS,0,0,NULL); }else{ logger->_pageNbr--; } } } } /** * Uma função para libertar todos os recursos ocupados pelo registo de histórico (ResetThreadLog(…)); * */ BOOL WINAPI ResetThreadLog(){ LogDef* logger = (LogDef*)TlsGetValue(tlsIDX); if (!VirtualFree(logger->_loggerBase,0, MEM_DECOMMIT)) RaiseException(RESET_THREAD_LOG_INSUCCESS,0,0,NULL); resetValues(); return TRUE; } /** * Uma função para libertar o suporte do registo de histórico (DestroyThreadLog(…)). * */ BOOL WINAPI DestroyThreadLog(){ LogDef* logger = (LogDef*)TlsGetValue(tlsIDX); if (!VirtualFree((logger->_loggerBase), 0 ,MEM_RELEASE)) RaiseException(DESTROY_THREAD_LOG_INSUCCESS,0,0,NULL); return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////// Função DllMain /////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) { BOOL Result = TRUE; _tsetlocale(LC_ALL, _T("portuguese_portugal")); switch (fdwReason) { case DLL_PROCESS_ATTACH: // A DDL está a ser mapeada no espaço de endereçamento do processo _tprintf(_T("LoggerDLL.dll: A DDL está a ser mapeada no espaço de endereçamento do processo\n")); _tprintf(_T("0x%p\n"), hinstDLL); if ((tlsIDX = TlsAlloc()) == -1) { Result = FALSE; break; } //Atribuir espaço na entrada do thread corrente Result = _TlsInit() != NULL; break; case DLL_THREAD_ATTACH: // Está a ser criada uma thread _tprintf(_T("LoggerDLL.dll: Está a ser criada uma thread\n")); //Atribuir espaço na entrada TLS do thread corrente _TlsInit(); break; case DLL_THREAD_DETACH: // Existe uma thread a terminar (sem ser através do TerminateThread _tprintf(_T("LoggerDLL.dll: Existe uma thread a terminar (sem ser através do TerminateThread)\n")); //Libertar espaço ocupado pelo thread na entrada TLS _TlsClose(); break; case DLL_PROCESS_DETACH: // A DLL está a ser desmapeada do espaço de endereçamento do processo _tprintf(_T("LoggerDLL.dll: A DLL está a ser desmapeada do espaço de endereçamento do processo\n")); //Libertar espaço ocupado pelo thread na entrada TLS _TlsClose(); //Fechar a entrada de TLS no processo if( !TlsFree(tlsIDX) ) Result = FALSE; break; default: _tprintf(_T("LoggerDLL.dll: DllMain chamada com um motivo desconhecido (%ld)\n"), fdwReason); Result = FALSE; } return Result; // Utilizado apenas para DLL_PROCESS_ATTACH }
[ "nuno.cancelo@b139f23c-5e1e-54d6-eab5-85b03e268133", "[email protected]@b139f23c-5e1e-54d6-eab5-85b03e268133" ]
[ [ [ 1, 15 ], [ 17, 31 ], [ 33, 45 ], [ 47, 65 ], [ 68, 68 ], [ 70, 71 ], [ 74, 118 ], [ 120, 136 ], [ 138, 151 ], [ 154, 154 ], [ 160, 171 ], [ 173, 307 ] ], [ [ 16, 16 ], [ 32, 32 ], [ 46, 46 ], [ 66, 67 ], [ 69, 69 ], [ 72, 73 ], [ 119, 119 ], [ 137, 137 ], [ 152, 153 ], [ 155, 159 ], [ 172, 172 ] ] ]
86b71b5e38ae72c8b6ad05be9652e3cbe21c13e8
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/inc/mathlib/nmath.h
deac6a0629716e62e26fca592736eb23c5bbe618
[]
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
7,866
h
#ifndef N_MATH_H #define N_MATH_H //------------------------------------------------------------------------------ /** General math functions and macros. (C) 2003 RadonLabs GmbH - 07-Jun-05 kims Added 'n_atan2', 'n_exp', 'n_floor', 'n_ceil' and 'n_pow' macros. */ #include <math.h> #include <stdlib.h> #ifdef _MSC_VER #define isnan _isnan #define isinf _isinf #endif #ifndef PI #define PI (3.1415926535897932384626433832795028841971693993751f) #endif #ifndef HALFPI #define HALFPI (1.5707963267948966192313216916395f) #endif #ifndef TWOPI #define TWOPI (6.283185307179586476925286766558f) #endif #define N_PI PI #define N_HALFPI HALFPI #define N_TWOPI TWOPI #ifndef TINY #define TINY (0.0000001f) #endif #define N_TINY TINY #define n_max(a,b) (((a) > (b)) ? (a) : (b)) #define n_min(a,b) (((a) < (b)) ? (a) : (b)) #define n_abs(a) (((a)<0.0f) ? (-(a)) : (a)) #define n_sgn(a) (((a)<0.0f) ? (-1) : (1)) #define n_deg2rad(d) (((d)*PI)/180.0f) #define n_rad2deg(r) (((r)*180.0f)/PI) #define n_sin(x) (float(sin(x))) #define n_cos(x) (float(cos(x))) #define n_tan(x) (float(tan(x))) #define n_atan(x) (float(atan(x))) #define n_atan2(x,y) (float(atan2(x,y))) #define n_exp(x) (float(exp(x))) #define n_floor(x) (float(floor(x))) #define n_ceil(x) (float(ceil(x))) #define n_pow(x,y) (float(pow(x,y))) //------------------------------------------------------------------------------ /** log2() function. */ const float LN_2 = 0.693147180559945f; inline float n_log2(float f) { return logf(f) / LN_2; } //------------------------------------------------------------------------------ /** Integer clamping. */ inline int n_iclamp(int val, int minVal, int maxVal) { if (val < minVal) return minVal; else if (val > maxVal) return maxVal; else return val; } //------------------------------------------------------------------------------ /** acos with value clamping. */ inline float n_acos(float x) { if(x > 1.0f) x = 1.0f; if(x < -1.0f) x = -1.0f; return (float)acos(x); } //------------------------------------------------------------------------------ /** asin with value clamping. */ inline float n_asin(float x) { if(x > 1.0f) x = 1.0f; if(x < -1.0f) x = -1.0f; return (float)asin(x); } //------------------------------------------------------------------------------ /** Safe sqrt. */ inline float n_sqrt(float x) { if (x < 0.0f) x = (float) 0.0f; return (float) sqrt(x); } //------------------------------------------------------------------------------ /** A fuzzy floating point equality check */ inline bool n_fequal(float f0, float f1, float tol) { float f = f0-f1; if ((f>(-tol)) && (f<tol)) return true; else return false; } //------------------------------------------------------------------------------ /** A fuzzy floating point less-then check. */ inline bool n_fless(float f0, float f1, float tol) { if ((f0-f1)<tol) return true; else return false; } //------------------------------------------------------------------------------ /** A fuzzy floating point greater-then check. */ inline bool n_fgreater(float f0, float f1, float tol) { if ((f0-f1)>tol) return true; else return false; } //------------------------------------------------------------------------------ /** fast float to int conversion (always truncates) see http://www.stereopsis.com/FPU.html for a discussion. NOTE: this works only on x86 endian machines. */ inline long n_ftol(float val) { double v = double(val) + (68719476736.0*1.5); return ((long*)&v)[0] >> 16; } //------------------------------------------------------------------------------ /** Smooth a new value towards an old value using a change value. */ inline float n_smooth(float newVal, float curVal, float maxChange) { float diff = newVal - curVal; if (fabs(diff) > maxChange) { if (diff > 0.0f) { curVal += maxChange; if (curVal > newVal) { curVal = newVal; } } else if (diff < 0.0f) { curVal -= maxChange; if (curVal < newVal) { curVal = newVal; } } } else { curVal = newVal; } return curVal; } //------------------------------------------------------------------------------ /** Clamp a value against lower und upper boundary. */ inline float n_clamp(float val, float lower, float upper) { if (val < lower) return lower; else if (val > upper) return upper; else return val; } //------------------------------------------------------------------------------ /** Saturate a value (clamps between 0.0f and 1.0f) */ inline float n_saturate(float val) { if (val < 0.0f) return 0.0f; else if (val > 1.0f) return 1.0f; else return val; } //------------------------------------------------------------------------------ /** Return a pseudo random number between 0 and 1. */ inline float n_rand() { return float(rand()) / float(RAND_MAX); } //------------------------------------------------------------------------------ /** Chop float to int. */ inline int n_fchop(float f) { // FIXME! return int(f); } //------------------------------------------------------------------------------ /** Round float to integer. */ inline int n_frnd(float f) { return n_fchop(floorf(f + 0.5f)); } //------------------------------------------------------------------------------ /** Linearly interpolate between 2 values: ret = x + l * (y - x) */ inline float n_lerp(float x, float y, float l) { return x + l * (y - x); } //------------------------------------------------------------------------------ /** Template-based linear interpolation function used by nIpolKeyArray that can be specialized for any type. */ template<class TYPE> inline void lerp(TYPE & result, const TYPE & val0, const TYPE & val1, float lerpVal) { n_error("Unimplemented lerp function!"); } //------------------------------------------------------------------------------ /** */ template<> inline void lerp<int>(int & result, const int & val0, const int & val1, float lerpVal) { result = n_frnd((float)val0 + (((float)val1 - (float)val0) * lerpVal)); } //------------------------------------------------------------------------------ /** */ template<> inline void lerp<float>(float & result, const float & val0, const float & val1, float lerpVal) { result = val0 + ((val1 - val0) * lerpVal); } //------------------------------------------------------------------------------ /** Normalize an angular value into the range rad(0) to rad(360). */ inline float n_normangle(float a) { while(a < 0.0f) { a += n_deg2rad(360.0f); } if (a >= n_deg2rad(360.0f)) { a = fmodf(a, n_deg2rad(360.0f)); } return a; } //------------------------------------------------------------------------------ /** Normalize an angular value into the range [ -PI, PI ] */ inline float n_normalangle2( float a ) { while( a > N_PI ) { a -= N_TWOPI; } while( a < -N_PI ) { a += N_TWOPI; } return a; } //------------------------------------------------------------------------------ #endif
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 316 ] ] ]
90ba71c5091784e94efc0e8d4e43eaa0b8979a26
e06c28b396351593f75722bcd5b57ca7a6004868
/ext/LZMAEncoder.cpp
5461fadcef0cef7df9a139d1697d4e4c65316393
[]
no_license
taf2/ruby-lzma
5c78c403bde88d49527ee41a28c6045dfd94e971
edd53fed204c6a05956d69396974665ce1246189
refs/heads/master
2020-12-25T03:20:24.879180
2010-02-23T02:53:15
2010-02-23T02:53:15
531,285
2
0
null
null
null
null
UTF-8
C++
false
false
43,401
cpp
// LZMA/Encoder.cpp #include "StdAfx.h" #include "Defs.h" #include "StreamUtils.h" #include "LZMAEncoder.h" // for minimal compressing code size define these: // #define COMPRESS_MF_BT // #define COMPRESS_MF_BT4 #if !defined(COMPRESS_MF_BT) && !defined(COMPRESS_MF_PAT) && !defined(COMPRESS_MF_HC) #define COMPRESS_MF_BT #define COMPRESS_MF_PAT #define COMPRESS_MF_HC #endif #ifdef COMPRESS_MF_BT #if !defined(COMPRESS_MF_BT2) && !defined(COMPRESS_MF_BT3) && !defined(COMPRESS_MF_BT4) && !defined(COMPRESS_MF_BT4B) #define COMPRESS_MF_BT2 #define COMPRESS_MF_BT3 #define COMPRESS_MF_BT4 #define COMPRESS_MF_BT4B #endif #ifdef COMPRESS_MF_BT2 #include "BinTree2.h" #endif #ifdef COMPRESS_MF_BT3 #include "BinTree3.h" #endif #ifdef COMPRESS_MF_BT4 #include "BinTree4.h" #endif #ifdef COMPRESS_MF_BT4B #include "BinTree4b.h" #endif #endif #ifdef COMPRESS_MF_PAT #include "Pat2.h" #include "Pat2H.h" #include "Pat3H.h" #include "Pat4H.h" #include "Pat2R.h" #endif #ifdef COMPRESS_MF_HC #include "HC3.h" #include "HC4.h" #endif #ifdef COMPRESS_MF_MT #include "MT.h" #endif namespace NCompress { namespace NLZMA { const int kDefaultDictionaryLogSize = 22; const UInt32 kNumFastBytesDefault = 0x20; enum { kBT2, kBT3, kBT4, kBT4B, kPat2, kPat2H, kPat3H, kPat4H, kPat2R, kHC3, kHC4 }; static const wchar_t *kMatchFinderIDs[] = { L"BT2", L"BT3", L"BT4", L"BT4B", L"PAT2", L"PAT2H", L"PAT3H", L"PAT4H", L"PAT2R", L"HC3", L"HC4" }; Byte g_FastPos[1024]; class CFastPosInit { public: CFastPosInit() { Init(); } void Init() { const Byte kFastSlots = 20; int c = 2; g_FastPos[0] = 0; g_FastPos[1] = 1; for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++) { UInt32 k = (1 << ((slotFast >> 1) - 1)); for (UInt32 j = 0; j < k; j++, c++) g_FastPos[c] = slotFast; } } } g_FastPosInit; void CLiteralEncoder2::Encode(NRangeCoder::CEncoder *rangeEncoder, Byte symbol) { UInt32 context = 1; int i = 8; do { i--; UInt32 bit = (symbol >> i) & 1; _encoders[context].Encode(rangeEncoder, bit); context = (context << 1) | bit; } while(i != 0); } void CLiteralEncoder2::EncodeMatched(NRangeCoder::CEncoder *rangeEncoder, Byte matchByte, Byte symbol) { UInt32 context = 1; int i = 8; do { i--; UInt32 bit = (symbol >> i) & 1; UInt32 matchBit = (matchByte >> i) & 1; _encoders[0x100 + (matchBit << 8) + context].Encode(rangeEncoder, bit); context = (context << 1) | bit; if (matchBit != bit) { while(i != 0) { i--; UInt32 bit = (symbol >> i) & 1; _encoders[context].Encode(rangeEncoder, bit); context = (context << 1) | bit; } break; } } while(i != 0); } UInt32 CLiteralEncoder2::GetPrice(bool matchMode, Byte matchByte, Byte symbol) const { UInt32 price = 0; UInt32 context = 1; int i = 8; if (matchMode) { do { i--; UInt32 matchBit = (matchByte >> i) & 1; UInt32 bit = (symbol >> i) & 1; price += _encoders[0x100 + (matchBit << 8) + context].GetPrice(bit); context = (context << 1) | bit; if (matchBit != bit) break; } while (i != 0); } while(i != 0) { i--; UInt32 bit = (symbol >> i) & 1; price += _encoders[context].GetPrice(bit); context = (context << 1) | bit; } return price; }; namespace NLength { void CEncoder::Init(UInt32 numPosStates) { _choice.Init(); _choice2.Init(); for (UInt32 posState = 0; posState < numPosStates; posState++) { _lowCoder[posState].Init(); _midCoder[posState].Init(); } _highCoder.Init(); } void CEncoder::Encode(NRangeCoder::CEncoder *rangeEncoder, UInt32 symbol, UInt32 posState) { if(symbol < kNumLowSymbols) { _choice.Encode(rangeEncoder, 0); _lowCoder[posState].Encode(rangeEncoder, symbol); } else { _choice.Encode(rangeEncoder, 1); if(symbol < kNumLowSymbols + kNumMidSymbols) { _choice2.Encode(rangeEncoder, 0); _midCoder[posState].Encode(rangeEncoder, symbol - kNumLowSymbols); } else { _choice2.Encode(rangeEncoder, 1); _highCoder.Encode(rangeEncoder, symbol - kNumLowSymbols - kNumMidSymbols); } } } UInt32 CEncoder::GetPrice(UInt32 symbol, UInt32 posState) const { if(symbol < kNumLowSymbols) return _choice.GetPrice0() + _lowCoder[posState].GetPrice(symbol); UInt32 price = _choice.GetPrice1(); if(symbol < kNumLowSymbols + kNumMidSymbols) { price += _choice2.GetPrice0(); price += _midCoder[posState].GetPrice(symbol - kNumLowSymbols); } else { price += _choice2.GetPrice1(); price += _highCoder.GetPrice(symbol - kNumLowSymbols - kNumMidSymbols); } return price; } } CEncoder::CEncoder(): _numFastBytes(kNumFastBytesDefault), _distTableSize(kDefaultDictionaryLogSize * 2), _posStateBits(2), _posStateMask(4 - 1), _numLiteralPosStateBits(0), _numLiteralContextBits(3), _dictionarySize(1 << kDefaultDictionaryLogSize), _dictionarySizePrev(UInt32(-1)), _numFastBytesPrev(UInt32(-1)), _matchFinderIndex(kBT4), #ifdef COMPRESS_MF_MT _multiThread(false), #endif _writeEndMark(false) { _maxMode = false; _fastMode = false; } HRESULT CEncoder::Create() { if (!_rangeEncoder.Create(1 << 20)) return E_OUTOFMEMORY; if (!_matchFinder) { switch(_matchFinderIndex) { #ifdef COMPRESS_MF_BT #ifdef COMPRESS_MF_BT2 case kBT2: _matchFinder = new NBT2::CMatchFinderBinTree; break; #endif #ifdef COMPRESS_MF_BT3 case kBT3: _matchFinder = new NBT3::CMatchFinderBinTree; break; #endif #ifdef COMPRESS_MF_BT4 case kBT4: _matchFinder = new NBT4::CMatchFinderBinTree; break; #endif #ifdef COMPRESS_MF_BT4B case kBT4B: _matchFinder = new NBT4B::CMatchFinderBinTree; break; #endif #endif #ifdef COMPRESS_MF_PAT case kPat2: _matchFinder = new NPat2::CPatricia; break; case kPat2H: _matchFinder = new NPat2H::CPatricia; break; case kPat3H: _matchFinder = new NPat3H::CPatricia; break; case kPat4H: _matchFinder = new NPat4H::CPatricia; break; case kPat2R: _matchFinder = new NPat2R::CPatricia; break; #endif #ifdef COMPRESS_MF_HC case kHC3: _matchFinder = new NHC3::CMatchFinderHC; break; case kHC4: _matchFinder = new NHC4::CMatchFinderHC; break; #endif } if (_matchFinder == 0) return E_OUTOFMEMORY; #ifdef COMPRESS_MF_MT if (_multiThread && !(_fastMode && (_matchFinderIndex == kHC3 || _matchFinderIndex == kHC4))) { CMatchFinderMT *mfSpec = new CMatchFinderMT; if (mfSpec == 0) return E_OUTOFMEMORY; CMyComPtr<IMatchFinder> mf = mfSpec; RINOK(mfSpec->SetMatchFinder(_matchFinder)); _matchFinder.Release(); _matchFinder = mf; } #endif } if (!_literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits)) return E_OUTOFMEMORY; if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes) return S_OK; RINOK(_matchFinder->Create(_dictionarySize, kNumOpts, _numFastBytes, kMatchMaxLen * 2 + 1 - _numFastBytes)); _dictionarySizePrev = _dictionarySize; _numFastBytesPrev = _numFastBytes; return S_OK; } static bool AreStringsEqual(const wchar_t *base, const wchar_t *testString) { while (true) { wchar_t c = *testString; if (c >= 'a' && c <= 'z') c -= 0x20; if (*base != c) return false; if (c == 0) return true; base++; testString++; } } static int FindMatchFinder(const wchar_t *s) { for (int m = 0; m < (int)(sizeof(kMatchFinderIDs) / sizeof(kMatchFinderIDs[0])); m++) if (AreStringsEqual(kMatchFinderIDs[m], s)) return m; return -1; } STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *properties, UInt32 numProperties) { for (UInt32 i = 0; i < numProperties; i++) { const PROPVARIANT &prop = properties[i]; switch(propIDs[i]) { case NCoderPropID::kNumFastBytes: { if (prop.vt != VT_UI4) return E_INVALIDARG; UInt32 numFastBytes = prop.ulVal; if(numFastBytes < 5 || numFastBytes > kMatchMaxLen) return E_INVALIDARG; _numFastBytes = numFastBytes; break; } case NCoderPropID::kAlgorithm: { if (prop.vt != VT_UI4) return E_INVALIDARG; UInt32 maximize = prop.ulVal; _fastMode = (maximize == 0); _maxMode = (maximize >= 2); break; } case NCoderPropID::kMatchFinder: { if (prop.vt != VT_BSTR) return E_INVALIDARG; int matchFinderIndexPrev = _matchFinderIndex; int m = FindMatchFinder(prop.bstrVal); if (m < 0) return E_INVALIDARG; _matchFinderIndex = m; if (_matchFinder && matchFinderIndexPrev != _matchFinderIndex) { _dictionarySizePrev = UInt32(-1); _matchFinder.Release(); } break; } #ifdef COMPRESS_MF_MT case NCoderPropID::kMultiThread: { if (prop.vt != VT_BOOL) return E_INVALIDARG; bool newMultiThread = (prop.boolVal == VARIANT_TRUE); if (newMultiThread != _multiThread) { _dictionarySizePrev = UInt32(-1); _matchFinder.Release(); } _multiThread = newMultiThread; break; } #endif case NCoderPropID::kDictionarySize: { const int kDicLogSizeMaxCompress = 28; if (prop.vt != VT_UI4) return E_INVALIDARG; UInt32 dictionarySize = prop.ulVal; if (dictionarySize < UInt32(1 << kDicLogSizeMin) || dictionarySize > UInt32(1 << kDicLogSizeMaxCompress)) return E_INVALIDARG; _dictionarySize = dictionarySize; UInt32 dicLogSize; for(dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++) if (dictionarySize <= (UInt32(1) << dicLogSize)) break; _distTableSize = dicLogSize * 2; break; } case NCoderPropID::kPosStateBits: { if (prop.vt != VT_UI4) return E_INVALIDARG; UInt32 value = prop.ulVal; if (value > (UInt32)NLength::kNumPosStatesBitsEncodingMax) return E_INVALIDARG; _posStateBits = value; _posStateMask = (1 << _posStateBits) - 1; break; } case NCoderPropID::kLitPosBits: { if (prop.vt != VT_UI4) return E_INVALIDARG; UInt32 value = prop.ulVal; if (value > (UInt32)kNumLitPosStatesBitsEncodingMax) return E_INVALIDARG; _numLiteralPosStateBits = value; break; } case NCoderPropID::kLitContextBits: { if (prop.vt != VT_UI4) return E_INVALIDARG; UInt32 value = prop.ulVal; if (value > (UInt32)kNumLitContextBitsMax) return E_INVALIDARG; _numLiteralContextBits = value; break; } case NCoderPropID::kEndMarker: { if (prop.vt != VT_BOOL) return E_INVALIDARG; SetWriteEndMarkerMode(prop.boolVal == VARIANT_TRUE); break; } default: return E_INVALIDARG; } } return S_OK; } STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) { const UInt32 kPropSize = 5; Byte properties[kPropSize]; properties[0] = (_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits; for (int i = 0; i < 4; i++) properties[1 + i] = Byte(_dictionarySize >> (8 * i)); return WriteStream(outStream, properties, kPropSize, NULL); } STDMETHODIMP CEncoder::SetOutStream(ISequentialOutStream *outStream) { _rangeEncoder.SetStream(outStream); return S_OK; } STDMETHODIMP CEncoder::ReleaseOutStream() { _rangeEncoder.ReleaseStream(); return S_OK; } HRESULT CEncoder::Init() { CBaseState::Init(); // RINOK(_matchFinder->Init(inStream)); _rangeEncoder.Init(); for(int i = 0; i < kNumStates; i++) { for (UInt32 j = 0; j <= _posStateMask; j++) { _isMatch[i][j].Init(); _isRep0Long[i][j].Init(); } _isRep[i].Init(); _isRepG0[i].Init(); _isRepG1[i].Init(); _isRepG2[i].Init(); } _literalEncoder.Init(); // _repMatchLenEncoder.Init(); { for(UInt32 i = 0; i < kNumLenToPosStates; i++) _posSlotEncoder[i].Init(); } { for(UInt32 i = 0; i < kNumFullDistances - kEndPosModelIndex; i++) _posEncoders[i].Init(); } _lenEncoder.Init(1 << _posStateBits); _repMatchLenEncoder.Init(1 << _posStateBits); _posAlignEncoder.Init(); _longestMatchWasFound = false; _optimumEndIndex = 0; _optimumCurrentIndex = 0; _additionalOffset = 0; return S_OK; } HRESULT CEncoder::MovePos(UInt32 num) { for (;num != 0; num--) { _matchFinder->DummyLongestMatch(); RINOK(_matchFinder->MovePos()); _additionalOffset++; } return S_OK; } UInt32 CEncoder::Backward(UInt32 &backRes, UInt32 cur) { _optimumEndIndex = cur; UInt32 posMem = _optimum[cur].PosPrev; UInt32 backMem = _optimum[cur].BackPrev; do { if (_optimum[cur].Prev1IsChar) { _optimum[posMem].MakeAsChar(); _optimum[posMem].PosPrev = posMem - 1; if (_optimum[cur].Prev2) { _optimum[posMem - 1].Prev1IsChar = false; _optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2; _optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2; } } UInt32 posPrev = posMem; UInt32 backCur = backMem; backMem = _optimum[posPrev].BackPrev; posMem = _optimum[posPrev].PosPrev; _optimum[posPrev].BackPrev = backCur; _optimum[posPrev].PosPrev = cur; cur = posPrev; } while(cur != 0); backRes = _optimum[0].BackPrev; _optimumCurrentIndex = _optimum[0].PosPrev; return _optimumCurrentIndex; } /* inline UInt32 GetMatchLen(const Byte *data, UInt32 back, UInt32 limit) { back++; for(UInt32 i = 0; i < limit && data[i] == data[i - back]; i++); return i; } */ /* Out: (lenRes == 1) && (backRes == 0xFFFFFFFF) means Literal */ HRESULT CEncoder::GetOptimum(UInt32 position, UInt32 &backRes, UInt32 &lenRes) { if(_optimumEndIndex != _optimumCurrentIndex) { const COptimal &optimum = _optimum[_optimumCurrentIndex]; lenRes = optimum.PosPrev - _optimumCurrentIndex; backRes = optimum.BackPrev; _optimumCurrentIndex = optimum.PosPrev; return S_OK; } _optimumCurrentIndex = 0; _optimumEndIndex = 0; // test it; UInt32 lenMain; if (!_longestMatchWasFound) { RINOK(ReadMatchDistances(lenMain)); } else { lenMain = _longestMatchLength; _longestMatchWasFound = false; } UInt32 reps[kNumRepDistances]; UInt32 repLens[kNumRepDistances]; UInt32 repMaxIndex = 0; UInt32 i; for(i = 0; i < kNumRepDistances; i++) { reps[i] = _repDistances[i]; repLens[i] = _matchFinder->GetMatchLen(0 - 1, reps[i], kMatchMaxLen); if (i == 0 || repLens[i] > repLens[repMaxIndex]) repMaxIndex = i; } if(repLens[repMaxIndex] >= _numFastBytes) { backRes = repMaxIndex; lenRes = repLens[repMaxIndex]; return MovePos(lenRes - 1); } if(lenMain >= _numFastBytes) { backRes = _matchDistances[_numFastBytes] + kNumRepDistances; lenRes = lenMain; return MovePos(lenMain - 1); } Byte currentByte = _matchFinder->GetIndexByte(0 - 1); _optimum[0].State = _state; Byte matchByte; matchByte = _matchFinder->GetIndexByte(0 - _repDistances[0] - 1 - 1); UInt32 posState = (position & _posStateMask); _optimum[1].Price = _isMatch[_state.Index][posState].GetPrice0() + _literalEncoder.GetPrice(position, _previousByte, !_state.IsCharState(), matchByte, currentByte); _optimum[1].MakeAsChar(); _optimum[1].PosPrev = 0; for (i = 0; i < kNumRepDistances; i++) _optimum[0].Backs[i] = reps[i]; UInt32 matchPrice = _isMatch[_state.Index][posState].GetPrice1(); UInt32 repMatchPrice = matchPrice + _isRep[_state.Index].GetPrice1(); if(matchByte == currentByte) { UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState); if(shortRepPrice < _optimum[1].Price) { _optimum[1].Price = shortRepPrice; _optimum[1].MakeAsShortRep(); } } if(lenMain < 2) { backRes = _optimum[1].BackPrev; lenRes = 1; return S_OK; } UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0(); if (lenMain <= repLens[repMaxIndex]) lenMain = 0; UInt32 len; for(len = 2; len <= lenMain; len++) { _optimum[len].PosPrev = 0; _optimum[len].BackPrev = _matchDistances[len] + kNumRepDistances; _optimum[len].Price = normalMatchPrice + GetPosLenPrice(_matchDistances[len], len, posState); _optimum[len].Prev1IsChar = false; } if (lenMain < repLens[repMaxIndex]) lenMain = repLens[repMaxIndex]; for (; len <= lenMain; len++) _optimum[len].Price = kIfinityPrice; for(i = 0; i < kNumRepDistances; i++) { UInt32 repLen = repLens[i]; for(UInt32 lenTest = 2; lenTest <= repLen; lenTest++) { UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(i, lenTest, _state, posState); COptimal &optimum = _optimum[lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = 0; optimum.BackPrev = i; optimum.Prev1IsChar = false; } } } UInt32 cur = 0; UInt32 lenEnd = lenMain; while(true) { cur++; if(cur == lenEnd) { lenRes = Backward(backRes, cur); return S_OK; } position++; COptimal &curOptimum = _optimum[cur]; UInt32 posPrev = curOptimum.PosPrev; CState state; if (curOptimum.Prev1IsChar) { posPrev--; if (curOptimum.Prev2) { state = _optimum[curOptimum.PosPrev2].State; if (curOptimum.BackPrev2 < kNumRepDistances) state.UpdateRep(); else state.UpdateMatch(); } else state = _optimum[posPrev].State; state.UpdateChar(); } else state = _optimum[posPrev].State; if (posPrev == cur - 1) { if (curOptimum.IsShortRep()) state.UpdateShortRep(); else state.UpdateChar(); /* if (curOptimum.Prev1IsChar) for(int i = 0; i < kNumRepDistances; i++) reps[i] = _optimum[posPrev].Backs[i]; */ } else { UInt32 pos; if (curOptimum.Prev1IsChar && curOptimum.Prev2) { posPrev = curOptimum.PosPrev2; pos = curOptimum.BackPrev2; state.UpdateRep(); } else { pos = curOptimum.BackPrev; if (pos < kNumRepDistances) state.UpdateRep(); else state.UpdateMatch(); } const COptimal &prevOptimum = _optimum[posPrev]; if (pos < kNumRepDistances) { reps[0] = prevOptimum.Backs[pos]; UInt32 i; for(i = 1; i <= pos; i++) reps[i] = prevOptimum.Backs[i - 1]; for(; i < kNumRepDistances; i++) reps[i] = prevOptimum.Backs[i]; } else { reps[0] = (pos - kNumRepDistances); for(UInt32 i = 1; i < kNumRepDistances; i++) reps[i] = prevOptimum.Backs[i - 1]; } } curOptimum.State = state; for(UInt32 i = 0; i < kNumRepDistances; i++) curOptimum.Backs[i] = reps[i]; UInt32 newLen; RINOK(ReadMatchDistances(newLen)); if(newLen >= _numFastBytes) { _longestMatchLength = newLen; _longestMatchWasFound = true; lenRes = Backward(backRes, cur); return S_OK; } UInt32 curPrice = curOptimum.Price; // Byte currentByte = _matchFinder->GetIndexByte(0 - 1); // Byte matchByte = _matchFinder->GetIndexByte(0 - reps[0] - 1 - 1); const Byte *data = _matchFinder->GetPointerToCurrentPos() - 1; Byte currentByte = *data; Byte matchByte = data[(size_t)0 - reps[0] - 1]; UInt32 posState = (position & _posStateMask); UInt32 curAnd1Price = curPrice + _isMatch[state.Index][posState].GetPrice0() + _literalEncoder.GetPrice(position, data[(size_t)0 - 1], !state.IsCharState(), matchByte, currentByte); COptimal &nextOptimum = _optimum[cur + 1]; bool nextIsChar = false; if (curAnd1Price < nextOptimum.Price) { nextOptimum.Price = curAnd1Price; nextOptimum.PosPrev = cur; nextOptimum.MakeAsChar(); nextIsChar = true; } UInt32 matchPrice = curPrice + _isMatch[state.Index][posState].GetPrice1(); UInt32 repMatchPrice = matchPrice + _isRep[state.Index].GetPrice1(); if(matchByte == currentByte && !(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0)) { UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState); if(shortRepPrice <= nextOptimum.Price) { nextOptimum.Price = shortRepPrice; nextOptimum.PosPrev = cur; nextOptimum.MakeAsShortRep(); // nextIsChar = false; } } /* if(newLen == 2 && _matchDistances[2] >= kDistLimit2) // test it maybe set 2000 ? continue; */ UInt32 numAvailableBytesFull = _matchFinder->GetNumAvailableBytes() + 1; numAvailableBytesFull = MyMin(kNumOpts - 1 - cur, numAvailableBytesFull); UInt32 numAvailableBytes = numAvailableBytesFull; if (numAvailableBytes < 2) continue; if (numAvailableBytes > _numFastBytes) numAvailableBytes = _numFastBytes; if (numAvailableBytes >= 3 && !nextIsChar) { // try Literal + rep0 UInt32 backOffset = reps[0] + 1; UInt32 temp; for (temp = 1; temp < numAvailableBytes; temp++) if (data[temp] != data[(size_t)temp - backOffset]) break; UInt32 lenTest2 = temp - 1; if (lenTest2 >= 2) { CState state2 = state; state2.UpdateChar(); UInt32 posStateNext = (position + 1) & _posStateMask; UInt32 nextRepMatchPrice = curAnd1Price + _isMatch[state2.Index][posStateNext].GetPrice1() + _isRep[state2.Index].GetPrice1(); // for (; lenTest2 >= 2; lenTest2--) { while(lenEnd < cur + 1 + lenTest2) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice( 0, lenTest2, state2, posStateNext); COptimal &optimum = _optimum[cur + 1 + lenTest2]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = false; } } } } for(UInt32 repIndex = 0; repIndex < kNumRepDistances; repIndex++) { // UInt32 repLen = _matchFinder->GetMatchLen(0 - 1, reps[repIndex], newLen); // test it; UInt32 backOffset = reps[repIndex] + 1; if (data[0] != data[(size_t)0 - backOffset] || data[1] != data[(size_t)1 - backOffset]) continue; UInt32 lenTest; for (lenTest = 2; lenTest < numAvailableBytes; lenTest++) if (data[lenTest] != data[(size_t)lenTest - backOffset]) break; UInt32 lenTestTemp = lenTest; do { while(lenEnd < cur + lenTest) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState); COptimal &optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = repIndex; optimum.Prev1IsChar = false; } } while(--lenTest >= 2); lenTest = lenTestTemp; if (_maxMode) { UInt32 lenTest2 = lenTest + 1; UInt32 limit = MyMin(numAvailableBytesFull, lenTest2 + _numFastBytes); for (; lenTest2 < limit; lenTest2++) if (data[lenTest2] != data[(size_t)lenTest2 - backOffset]) break; lenTest2 -= lenTest + 1; if (lenTest2 >= 2) { CState state2 = state; state2.UpdateRep(); UInt32 posStateNext = (position + lenTest) & _posStateMask; UInt32 curAndLenCharPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + _isMatch[state2.Index][posStateNext].GetPrice0() + _literalEncoder.GetPrice(position + lenTest, data[(size_t)lenTest - 1], true, data[(size_t)lenTest - backOffset], data[lenTest]); state2.UpdateChar(); posStateNext = (position + lenTest + 1) & _posStateMask; UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[state2.Index][posStateNext].GetPrice1(); UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); // for(; lenTest2 >= 2; lenTest2--) { UInt32 offset = lenTest + 1 + lenTest2; while(lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice( 0, lenTest2, state2, posStateNext); COptimal &optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = repIndex; } } } } } // for(UInt32 lenTest = 2; lenTest <= newLen; lenTest++) if (newLen > numAvailableBytes) newLen = numAvailableBytes; if (newLen >= 2) { if (newLen == 2 && _matchDistances[2] >= 0x80) continue; UInt32 normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0(); while(lenEnd < cur + newLen) _optimum[++lenEnd].Price = kIfinityPrice; for(UInt32 lenTest = newLen; lenTest >= 2; lenTest--) { UInt32 curBack = _matchDistances[lenTest]; UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); COptimal &optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = curBack + kNumRepDistances; optimum.Prev1IsChar = false; } if (_maxMode && (lenTest == newLen || curBack != _matchDistances[lenTest + 1])) { // Try Match + Literal + Rep0 UInt32 backOffset = curBack + 1; UInt32 lenTest2 = lenTest + 1; UInt32 limit = MyMin(numAvailableBytesFull, lenTest2 + _numFastBytes); for (; lenTest2 < limit; lenTest2++) if (data[lenTest2] != data[(size_t)lenTest2 - backOffset]) break; lenTest2 -= lenTest + 1; if (lenTest2 >= 2) { CState state2 = state; state2.UpdateMatch(); UInt32 posStateNext = (position + lenTest) & _posStateMask; UInt32 curAndLenCharPrice = curAndLenPrice + _isMatch[state2.Index][posStateNext].GetPrice0() + _literalEncoder.GetPrice(position + lenTest, data[(size_t)lenTest - 1], true, data[(size_t)lenTest - backOffset], data[lenTest]); state2.UpdateChar(); posStateNext = (position + lenTest + 1) & _posStateMask; UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[state2.Index][posStateNext].GetPrice1(); UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); // for(; lenTest2 >= 2; lenTest2--) { UInt32 offset = lenTest + 1 + lenTest2; while(lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice( 0, lenTest2, state2, posStateNext); COptimal &optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = curBack + kNumRepDistances; } } } } } } } } static inline bool ChangePair(UInt32 smallDist, UInt32 bigDist) { const int kDif = 7; return (smallDist < (UInt32(1) << (32-kDif)) && bigDist >= (smallDist << kDif)); } HRESULT CEncoder::ReadMatchDistances(UInt32 &lenRes) { lenRes = _matchFinder->GetLongestMatch(_matchDistances); if (lenRes == _numFastBytes) lenRes += _matchFinder->GetMatchLen(lenRes, _matchDistances[lenRes], kMatchMaxLen - lenRes); _additionalOffset++; return _matchFinder->MovePos(); } HRESULT CEncoder::GetOptimumFast(UInt32 position, UInt32 &backRes, UInt32 &lenRes) { UInt32 lenMain; if (!_longestMatchWasFound) { RINOK(ReadMatchDistances(lenMain)); } else { lenMain = _longestMatchLength; _longestMatchWasFound = false; } UInt32 repLens[kNumRepDistances]; UInt32 repMaxIndex = 0; for(UInt32 i = 0; i < kNumRepDistances; i++) { repLens[i] = _matchFinder->GetMatchLen(0 - 1, _repDistances[i], kMatchMaxLen); if (i == 0 || repLens[i] > repLens[repMaxIndex]) repMaxIndex = i; } if(repLens[repMaxIndex] >= _numFastBytes) { backRes = repMaxIndex; lenRes = repLens[repMaxIndex]; return MovePos(lenRes - 1); } if(lenMain >= _numFastBytes) { backRes = _matchDistances[_numFastBytes] + kNumRepDistances; lenRes = lenMain; return MovePos(lenMain - 1); } while (lenMain > 2) { if (!ChangePair(_matchDistances[lenMain - 1], _matchDistances[lenMain])) break; lenMain--; } if (lenMain == 2 && _matchDistances[2] >= 0x80) lenMain = 1; UInt32 backMain = _matchDistances[lenMain]; if (repLens[repMaxIndex] >= 2) { if (repLens[repMaxIndex] + 1 >= lenMain || repLens[repMaxIndex] + 2 >= lenMain && (backMain > (1<<12))) { backRes = repMaxIndex; lenRes = repLens[repMaxIndex]; return MovePos(lenRes - 1); } } if (lenMain >= 2) { RINOK(ReadMatchDistances(_longestMatchLength)); if (_longestMatchLength >= 2 && ( (_longestMatchLength >= lenMain && _matchDistances[lenMain] < backMain) || _longestMatchLength == lenMain + 1 && !ChangePair(backMain, _matchDistances[_longestMatchLength]) || _longestMatchLength > lenMain + 1 || _longestMatchLength + 1 >= lenMain && lenMain >= 3 && ChangePair(_matchDistances[lenMain - 1], backMain) ) ) { _longestMatchWasFound = true; backRes = UInt32(-1); lenRes = 1; return S_OK; } for(UInt32 i = 0; i < kNumRepDistances; i++) { UInt32 repLen = _matchFinder->GetMatchLen(0 - 1, _repDistances[i], kMatchMaxLen); if (repLen >= 2 && repLen + 1 >= lenMain) { _longestMatchWasFound = true; backRes = UInt32(-1); lenRes = 1; return S_OK; } } backRes = backMain + kNumRepDistances; lenRes = lenMain; return MovePos(lenMain - 2); } backRes = UInt32(-1); lenRes = 1; return S_OK; } STDMETHODIMP CEncoder::InitMatchFinder(IMatchFinder *matchFinder) { _matchFinder = matchFinder; return S_OK; } HRESULT CEncoder::Flush(UInt32 nowPos) { ReleaseMFStream(); WriteEndMarker(nowPos & _posStateMask); _rangeEncoder.FlushData(); return _rangeEncoder.FlushStream(); } void CEncoder::WriteEndMarker(UInt32 posState) { // This function for writing End Mark for stream version of LZMA. // In current version this feature is not used. if (!_writeEndMark) return; _isMatch[_state.Index][posState].Encode(&_rangeEncoder, 1); _isRep[_state.Index].Encode(&_rangeEncoder, 0); _state.UpdateMatch(); UInt32 len = kMatchMinLen; // kMatchMaxLen; _lenEncoder.Encode(&_rangeEncoder, len - kMatchMinLen, posState); UInt32 posSlot = (1 << kNumPosSlotBits) - 1; UInt32 lenToPosState = GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(&_rangeEncoder, posSlot); UInt32 footerBits = 30; UInt32 posReduced = (UInt32(1) << footerBits) - 1; _rangeEncoder.EncodeDirectBits(posReduced >> kNumAlignBits, footerBits - kNumAlignBits); _posAlignEncoder.ReverseEncode(&_rangeEncoder, posReduced & kAlignMask); } HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) { _needReleaseMFStream = false; CCoderReleaser coderReleaser(this); RINOK(SetStreams(inStream, outStream, inSize, outSize)); while(true) { UInt64 processedInSize; UInt64 processedOutSize; Int32 finished; RINOK(CodeOneBlock(&processedInSize, &processedOutSize, &finished)); if (finished != 0) return S_OK; if (progress != 0) { RINOK(progress->SetRatioInfo(&processedInSize, &processedOutSize)); } } } HRESULT CEncoder::SetStreams(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize) { _inStream = inStream; _finished = false; RINOK(Create()); RINOK(SetOutStream(outStream)); RINOK(Init()); // CCoderReleaser releaser(this); /* if (_matchFinder->GetNumAvailableBytes() == 0) return Flush(); */ if (!_fastMode) { FillPosSlotPrices(); FillDistancesPrices(); FillAlignPrices(); } _lenEncoder.SetTableSize(_numFastBytes + 1 - kMatchMinLen); _lenEncoder.UpdateTables(1 << _posStateBits); _repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - kMatchMinLen); _repMatchLenEncoder.UpdateTables(1 << _posStateBits); lastPosSlotFillingPos = 0; nowPos64 = 0; return S_OK; } HRESULT CEncoder::CodeOneBlock(UInt64 *inSize, UInt64 *outSize, Int32 *finished) { if (_inStream != 0) { RINOK(_matchFinder->Init(_inStream)); _needReleaseMFStream = true; _inStream = 0; } *finished = 1; if (_finished) return S_OK; _finished = true; UInt64 progressPosValuePrev = nowPos64; if (nowPos64 == 0) { if (_matchFinder->GetNumAvailableBytes() == 0) return Flush(UInt32(nowPos64)); UInt32 len; // it's not used RINOK(ReadMatchDistances(len)); UInt32 posState = UInt32(nowPos64) & _posStateMask; _isMatch[_state.Index][posState].Encode(&_rangeEncoder, 0); _state.UpdateChar(); Byte curByte = _matchFinder->GetIndexByte(0 - _additionalOffset); _literalEncoder.GetSubCoder(UInt32(nowPos64), _previousByte)->Encode(&_rangeEncoder, curByte); _previousByte = curByte; _additionalOffset--; nowPos64++; } if (_matchFinder->GetNumAvailableBytes() == 0) return Flush(UInt32(nowPos64)); while(true) { #ifdef _NO_EXCEPTIONS if (_rangeEncoder.Stream.ErrorCode != S_OK) return _rangeEncoder.Stream.ErrorCode; #endif UInt32 pos; UInt32 posState = UInt32(nowPos64) & _posStateMask; UInt32 len; HRESULT result; if (_fastMode) result = GetOptimumFast(UInt32(nowPos64), pos, len); else result = GetOptimum(UInt32(nowPos64), pos, len); RINOK(result); if(len == 1 && pos == 0xFFFFFFFF) { _isMatch[_state.Index][posState].Encode(&_rangeEncoder, 0); Byte curByte = _matchFinder->GetIndexByte(0 - _additionalOffset); CLiteralEncoder2 *subCoder = _literalEncoder.GetSubCoder(UInt32(nowPos64), _previousByte); if(!_state.IsCharState()) { Byte matchByte = _matchFinder->GetIndexByte(0 - _repDistances[0] - 1 - _additionalOffset); subCoder->EncodeMatched(&_rangeEncoder, matchByte, curByte); } else subCoder->Encode(&_rangeEncoder, curByte); _state.UpdateChar(); _previousByte = curByte; } else { _isMatch[_state.Index][posState].Encode(&_rangeEncoder, 1); if(pos < kNumRepDistances) { _isRep[_state.Index].Encode(&_rangeEncoder, 1); if(pos == 0) { _isRepG0[_state.Index].Encode(&_rangeEncoder, 0); if(len == 1) _isRep0Long[_state.Index][posState].Encode(&_rangeEncoder, 0); else _isRep0Long[_state.Index][posState].Encode(&_rangeEncoder, 1); } else { _isRepG0[_state.Index].Encode(&_rangeEncoder, 1); if (pos == 1) _isRepG1[_state.Index].Encode(&_rangeEncoder, 0); else { _isRepG1[_state.Index].Encode(&_rangeEncoder, 1); _isRepG2[_state.Index].Encode(&_rangeEncoder, pos - 2); } } if (len == 1) _state.UpdateShortRep(); else { _repMatchLenEncoder.Encode(&_rangeEncoder, len - kMatchMinLen, posState); _state.UpdateRep(); } UInt32 distance = _repDistances[pos]; if (pos != 0) { for(UInt32 i = pos; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; } } else { _isRep[_state.Index].Encode(&_rangeEncoder, 0); _state.UpdateMatch(); _lenEncoder.Encode(&_rangeEncoder, len - kMatchMinLen, posState); pos -= kNumRepDistances; UInt32 posSlot = GetPosSlot(pos); UInt32 lenToPosState = GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(&_rangeEncoder, posSlot); if (posSlot >= kStartPosModelIndex) { UInt32 footerBits = ((posSlot >> 1) - 1); UInt32 base = ((2 | (posSlot & 1)) << footerBits); UInt32 posReduced = pos - base; if (posSlot < kEndPosModelIndex) NRangeCoder::ReverseBitTreeEncode(_posEncoders + base - posSlot - 1, &_rangeEncoder, footerBits, posReduced); else { _rangeEncoder.EncodeDirectBits(posReduced >> kNumAlignBits, footerBits - kNumAlignBits); _posAlignEncoder.ReverseEncode(&_rangeEncoder, posReduced & kAlignMask); if (!_fastMode) if (--_alignPriceCount == 0) FillAlignPrices(); } } UInt32 distance = pos; for(UInt32 i = kNumRepDistances - 1; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; } _previousByte = _matchFinder->GetIndexByte(len - 1 - _additionalOffset); } _additionalOffset -= len; nowPos64 += len; if (!_fastMode) if (nowPos64 - lastPosSlotFillingPos >= (1 << 9)) { FillPosSlotPrices(); FillDistancesPrices(); lastPosSlotFillingPos = nowPos64; } if (_additionalOffset == 0) { *inSize = nowPos64; *outSize = _rangeEncoder.GetProcessedSize(); if (_matchFinder->GetNumAvailableBytes() == 0) return Flush(UInt32(nowPos64)); if (nowPos64 - progressPosValuePrev >= (1 << 12)) { _finished = false; *finished = 0; return S_OK; } } } } STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) { #ifndef _NO_EXCEPTIONS try { #endif return CodeReal(inStream, outStream, inSize, outSize, progress); #ifndef _NO_EXCEPTIONS } catch(const COutBufferException &e) { return e.ErrorCode; } catch(...) { return E_FAIL; } #endif } void CEncoder::FillPosSlotPrices() { for (UInt32 lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++) { UInt32 posSlot; for (posSlot = 0; posSlot < kEndPosModelIndex && posSlot < _distTableSize; posSlot++) _posSlotPrices[lenToPosState][posSlot] = _posSlotEncoder[lenToPosState].GetPrice(posSlot); for (; posSlot < _distTableSize; posSlot++) _posSlotPrices[lenToPosState][posSlot] = _posSlotEncoder[lenToPosState].GetPrice(posSlot) + ((((posSlot >> 1) - 1) - kNumAlignBits) << NRangeCoder::kNumBitPriceShiftBits); } } void CEncoder::FillDistancesPrices() { for (UInt32 lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++) { UInt32 i; for (i = 0; i < kStartPosModelIndex; i++) _distancesPrices[lenToPosState][i] = _posSlotPrices[lenToPosState][i]; for (; i < kNumFullDistances; i++) { UInt32 posSlot = GetPosSlot(i); UInt32 footerBits = ((posSlot >> 1) - 1); UInt32 base = ((2 | (posSlot & 1)) << footerBits); _distancesPrices[lenToPosState][i] = _posSlotPrices[lenToPosState][posSlot] + NRangeCoder::ReverseBitTreeGetPrice(_posEncoders + base - posSlot - 1, footerBits, i - base); } } } void CEncoder::FillAlignPrices() { for (UInt32 i = 0; i < kAlignTableSize; i++) _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); _alignPriceCount = kAlignTableSize; } }}
[ [ [ 1, 1504 ] ] ]