blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
sequencelengths
1
16
author_lines
sequencelengths
1
16
0088cf64b565a2543217bf2fe488bce861bd4721
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Include/Nuclex/Video/Texture.h
81b3f68bc71aa0b655143eb87ed40853d90ddfdf
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
1,833
h
//  // // # # ### # # -= Nuclex Library =-  // // ## # # # ## ## Texture.h - Surface for polygon rendering  // // ### # # ###  // // # ### # ### Special surface which is to be used for polygon rendering  // // # ## # # ## ##  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #ifndef NUCLEX_IMAGE_TEXTURE_H #define NUCLEX_IMAGE_TEXTURE_H #include "Nuclex/Nuclex.h" #include "Nuclex/Video/Surface.h" namespace Nuclex { namespace Video { //  // //  Nuclex::Video::Texture  // //  // /// Texture surface /** */ class Texture : public Surface { public: /// Destructor NUCLEX_API virtual ~Texture() {} // // Texture implementation // public: /// Precache the texture /** Tries to precache the texture in the video card's memory. This method does not guarantee anything, but provides a hint at the renderer to prepare this texture for rendering asap */ NUCLEX_API virtual void precache() = 0; }; }} // namespace Nuclex::Video #endif // NUCLEX_VIDEO_TEXTURE_H
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 43 ] ] ]
b9dabab981c82a340eaf98d23da31211d5995b3b
74b0667a0585cfef6eca1ddc0e31424cce1031a1
/officevillagers/_Source/main.cpp
585755ab6521ff8b797ce362a1c5c769601d30ba
[]
no_license
IPv6/officevillagers
14e599f27beba5023dd89d28d5c5ad2c10b814ae
94ab3660c71e59099fd6a2d9c0465c0a9ef905e0
refs/heads/master
2020-05-20T11:29:17.509396
2008-09-19T02:00:31
2008-09-19T02:00:31
32,118,932
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,852
cpp
// stdafx.cpp : source file that includes just the standard includes // JewelResonance.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" #include "engineBindings.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[]=__FILE__; #endif void _RunMain() { try { CGameImplementation* client=new CGameImplementation(); RunGameLoop(client); }catch(CGameRotorError& error){ GfxMessageBox(toString("Error occured!\n'%s'",error.getError())); } } int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { BOOL bStarted=1; #ifdef USE_CUSTOMCRASH_DLG //_CRTIMP _CRT_ALLOC_HOOK __cdecl _CrtSetAllocHook(_CRT_ALLOC_HOOK hookFunctionPtr); //set_unexpected(CustomUnexpectedHandler); //set_terminate(CustomUnexpectedHandler); //_set_se_translator( trans_func );//void trans_func( unsigned int u, EXCEPTION_POINTERS* pExp ) __try{ _RunMain(); }__except(CustomUnexpectedFilter(GetExceptionCode(),GetExceptionInformation())){ return 1; } #else _RunMain(); #endif return 0; } /*// Make VC Express to build Win32 Step 3: Update the Visual C++ directories in the Projects and Solutions section in the Options dialog box. Add the paths to the appropriate subsection: * Executable files: C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Bin * Include files: C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Include * Library files: C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Lib Note: Alternatively, you can update the Visual C++ Directories by modifying the VCProjectEngine.dll.express.config file located in the \vc\vcpackages subdirectory of the Visual C++ Express install location. Please make sure that you also delete the file "vccomponents.dat" located in the "%USERPROFILE%\Local Settings\Application Data\Microsoft\VCExpress\8.0" if it exists before restarting Visual C++ Express Edition. Step 4: Update the corewin_express.vsprops file. One more step is needed to make the Win32 template work in Visual C++ Express. You need to edit the corewin_express.vsprops file (found in C:\Program Files\Microsoft Visual Studio 8\VC\VCProjectDefaults) and Change the string that reads: AdditionalDependencies="kernel32.lib" to AdditionalDependencies="kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib" Step 5: Generate and build a Win32 application to test your paths. In Visual C++ Express, the Win32 Windows Application type is disabled in the Win32 Application Wizard. To enable that type, you need to edit the file AppSettings.htm file located in the folder “%ProgramFiles%\Microsoft Visual Studio 8\VC\VCWizards\AppWiz\Generic\Application\html\1033\". In a text editor comment out lines 441 - 444 by putting a // in front of them as shown here: // WIN_APP.disabled=true; // WIN_APP_LABEL.disabled=true; // DLL_APP.disabled=true; // DLL_APP_LABEL.disabled=true; Save and close the file and open Visual C++ Express. From the File menu, click New Project. In the New Project dialog box, expand the Visual C++ node in the Product Types tree and then click Win32. Click on the Win32 Console Application template and then give your project a name and click OK. In the Win32 Application Wizard dialog box, make sure that Windows application is selected as the Application type and the ATL is not selected. Click the Finish button to generate the project. As a final step, test your project by clicking the Start button in the IDE or by pressing F5. Your Win32 application should build and run. */
[ "wplabs@5873e4e3-2a54-0410-bc5d-d38544d033f4" ]
[ [ [ 1, 87 ] ] ]
ba8d6ac45ee831b8ba58ecb55b56fd0a29aef3e2
adb2ebb4b7f74f62228c7dd9ca1441ee95297243
/Engine_Index/Engine_index.cpp
52936cb5d31547cc2776fdad1e3270b4abb0b201
[]
no_license
BackupTheBerlios/blazefilesearch-svn
5984480677ad0a7ae64c082e16dde4e7b2394c2c
b910de6af6f1ae8e018f06a484a8b6d9c4c2f280
refs/heads/master
2021-01-22T17:53:29.216195
2005-03-05T05:17:38
2005-03-05T05:17:38
40,608,509
0
0
null
null
null
null
UTF-8
C++
false
false
546
cpp
#include "Engine_index.h" #include <cstring> using namespace std; // Mangling prevention #ifdef __cplusplus extern "C" { #endif #include "Engine_global.h" int init(const char *indexName, const char *indexDir, const bool usesMultipleFiles, const blazeEngine_storageOpts *storesWhat, const bool isUserReadable) { // First, check what the index should store // (if storesWhat NULL, assume all metadata is stored if (storesWhat == NULL) { } else { } } // Mangling prevention #ifdef __cplusplus } #endif
[ "hyperfusion@8d202536-25f0-0310-b7fd-af1e855a3320" ]
[ [ [ 1, 31 ] ] ]
759dc42329162edc89539885d087a0f4c229618b
50e6ba037f1c60e5342c707a9d4223ac379a8047
/BTHandler.cpp
afcce2f20cfd40bd4b70a3cf436cc9f00e4965a6
[]
no_license
buryhuang/blueplus
299bbe23efa93f9d3acceeedccd5e8194cb71891
7843ccfa4b8fc773c6de1992acb9c9bb805671ed
refs/heads/master
2021-05-06T15:59:40.471142
2011-05-31T06:50:46
2011-05-31T06:50:46
113,696,936
1
0
null
null
null
null
UTF-8
C++
false
false
1,135
cpp
/** \addtogroup application * @{ */ #include "BTHandler.h" #include "BTDeviceManager.h" #include <iostream> CBTHandler::CBTHandler(void) { } CBTHandler::~CBTHandler(void) { } void CBTHandler::OnDeviceDiscovered(BTH_ADDR deviceAddr, int deviceClass, wstring deviceName, bool paired) { wcout<<hex<<deviceAddr<<" - "<<deviceName<<endl; if(DEF_BTDEV_MGR->RegisterDevice(deviceAddr, deviceClass, deviceName, paired)!=TRUE){ wcout<<L"Registering failed"<<endl; if(DEF_BTDEV_MGR->UpdateDevice(deviceAddr, deviceClass, deviceName, paired)!=TRUE){ wcout<<L"Updating failed"<<endl; } } if(RunSearchServices(deviceAddr)==FALSE){ Utils::ShowError(L"CBTHandler::OnDeviceDiscovered"); } } void CBTHandler::OnServiceDiscovered(BTH_ADDR deviceAddr, vector<ServiceRecord> serviceList) { for(vector<ServiceRecord>::iterator vi=serviceList.begin();vi!=serviceList.end();vi++){ wcout<<vi->serviceInstanceName <<L"-"<<vi->comment <<L"-"<<vi->sockaddrBth.btAddr <<L"-"<<vi->sockaddrBth.port <<endl; } DEF_BTDEV_MGR->UpdateServices(deviceAddr, serviceList); } /** @}*/
[ [ [ 1, 45 ] ] ]
8862daf55abe874e32f6be7edd88e46ddadc8a60
1193b8d2ab6bb40ce2adbf9ada5b3d1124f1abb3
/branches/mapmodule/libsonetto/include/SonettoScriptFile.h
4be8c549d1fcd202a74bdb5737bcffec27955771
[]
no_license
sonetto/legacy
46bb60ef8641af618d22c08ea198195fd597240b
e94a91950c309fc03f9f52e6bc3293007c3a0bd1
refs/heads/master
2021-01-01T16:45:02.531831
2009-09-10T21:50:42
2009-09-10T21:50:42
32,183,635
0
2
null
null
null
null
UTF-8
C++
false
false
2,808
h
/*----------------------------------------------------------------------------- Copyright (c) 2009, Sonetto Project Developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Sonetto Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -----------------------------------------------------------------------------*/ #ifndef SONETTO_SCRIPTFILE_H #define SONETTO_SCRIPTFILE_H // Forward declarations namespace Sonetto { class ScriptFile; } #include <OgreResourceManager.h> #include "SonettoPrerequisites.h" #include "SonettoSharedPtr.h" namespace Sonetto { typedef std::vector<char> ScriptData; class SONETTO_API ScriptFile : public Ogre::Resource { public: ScriptFile(Ogre::ResourceManager *creator,const Ogre::String &name, Ogre::ResourceHandle handle,const Ogre::String &group, bool isManual = false,Ogre::ManualResourceLoader *loader = 0) : Ogre::Resource(creator,name,handle,group,isManual,loader) {} virtual ~ScriptFile(); ScriptData &_getScriptData() { return mScriptData; } size_t calculateSize() const; protected: // Ogre::Resource interface implementation void loadImpl(); void unloadImpl(); ScriptData mScriptData; }; typedef SharedPtr<ScriptFile> ScriptFilePtr; } // namespace #endif // SONETTO_SCRIPTFILE_H
[ [ [ 1, 73 ] ] ]
59571f9eef5119b0b6f5883de93a80fb9090b1df
8a3fce9fb893696b8e408703b62fa452feec65c5
/业余时间学习笔记/CrashDumper/CrashDumper/DumperLog.cpp
1379fd0ba7ac757aa92538bb4a1f6bd4c69700a7
[]
no_license
win18216001/tpgame
bb4e8b1a2f19b92ecce14a7477ce30a470faecda
d877dd51a924f1d628959c5ab638c34a671b39b2
refs/heads/master
2021-04-12T04:51:47.882699
2011-03-08T10:04:55
2011-03-08T10:04:55
42,728,291
0
2
null
null
null
null
GB18030
C++
false
false
4,716
cpp
#include "StdAfx.h" #include "DumperLog.h" #include <DbgHelp.h> #define WriteLogFile(filename,context) \ { \ ofstream out(filename,ios::app); \ out << context << std::endl; \ out.close(); \ } namespace Dump { DumperLog::DumperLog(void) { } DumperLog::~DumperLog(void) { } void DumperLog::DumpCallStack(PCONTEXT pcontext , BOOL bWriteVarables , HANDLE hProcess) { WriteLogFile( "dumplog.txt" ,"\r\n Call Stack:\r\n\r\n" ); DWORD machineType =0; STACKFRAME sf; memset( & sf, 0 , sizeof(sf) ); sf.AddrPC.Offset = pcontext->Eip; sf.AddrPC.Mode = AddrModeFlat; sf.AddrStack.Offset = pcontext->Esp; sf.AddrStack.Mode= AddrModeFlat; sf.AddrFrame.Offset = pcontext->Esp; sf.AddrFrame.Mode = AddrModeFlat; machineType = IMAGE_FILE_MACHINE_I386; int i = 0; for(;;) { if( !StackWalk(machineType,hProcess,GetCurrentThread(),&sf,pcontext ,0,SymFunctionTableAccess,SymGetModuleBase,0)) { break; } if ( 0 == sf.AddrFrame.Offset) { break; } i++; BYTE symbolBuf[ sizeof( SYMBOL_INFO) + 1024]; PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)symbolBuf; pSymbol->SizeOfStruct = sizeof( symbolBuf); pSymbol->MaxNameLen = 1024; DWORD64 symDisplacement = 0; /// 获取符号 if ( SymFromAddr( hProcess,sf.AddrPC.Offset ,&symDisplacement,pSymbol) ) { if ( bWriteVarables ) { WriteLogFile("dumplog.txt",TEXT("%4d Function : %hs\r\n\t\t\t\t\t(+0x%I64x)##[Address : 0x%08x]##[Frame : 0x%08x]"),i, pSymbol->Name,symDisplacement,sf.AddrPC.Offset,sf.AddrFrame.Offset); } else { //WriteLogFile("dumplog.txt",TEXT("%4d Function :%hs"),i,pSymbol->Name); } } /// 没有找到 else { TCHAR szModule[MAX_PATH] = TEXT(""); TCHAR section[IMAGE_SIZEOF_SHORT_NAME +1 ] = TEXT(""); DWORD offset = 0; MEMORY_BASIC_INFORMATION mbi; do { if ( !VirtualQuery( UlongToPtr( sf.AddrPC.Offset) ,&mbi , sizeof(mbi))) { break; } HMODULE hMod = (HMODULE)mbi.AllocationBase; int num = 0; if ( !( num=GetModuleFileName( hMod , szModule , static_cast<DWORD>( num )) ) ) { cerr << " num = " << num << std::endl; break; } /// dos 文件头 PIMAGE_DOS_HEADER pDosHdr = (PIMAGE_DOS_HEADER)hMod; /// nt 文件头 PIMAGE_NT_HEADERS pNtHdr =(PIMAGE_NT_HEADERS)(hMod + pDosHdr->e_lfanew); /// section头 PIMAGE_SECTION_HEADER pSection = IMAGE_FIRST_SECTION( pNtHdr ); /// rva地址 DWORD rva = (DWORD)sf.AddrPC.Offset - PtrToUlong( hMod); for ( WORD i = 0 ; i < pNtHdr->FileHeader.NumberOfSections ; i++ , pSection++) { DWORD sectionStar = pSection->VirtualAddress; DWORD sectionEnd = sectionStar + max( pSection->SizeOfRawData ,pSection->Misc.VirtualSize); // rva落在了section if ( (rva >= sectionStar) && (rva <= sectionEnd)) { _tcsncpy( section , reinterpret_cast<LPCTSTR>(pSection->Name),IMAGE_SIZEOF_SHORT_NAME); section[ IMAGE_SIZEOF_SHORT_NAME ] = 0; offset = 0; break; } } } while (0); if ( bWriteVarables ) { char str[1000]; sprintf_s(str,"%4d Function : [Module :%s ] ## [ Section: %8s offset 0: x%08x] ",i,szModule,section,offset);;//"%4d Function : %hs\r\n\t\t\t\t\t(+0x%I64x)##[Address : 0x%08x]##[Frame : 0x%08x]",i,pSymbol->Name,symDisplacement,sf.AddrPC.Offset,sf.AddrFrame.Offset); WriteLogFile("dumplog.txt",str); } else { //WriteLogFile("dumplog.txt",TEXT("%4d Function : [Module :%s ] ## [ Section: %8s offset 0: x%08x] "),i,szModule,section,offset); } } if ( bWriteVarables ) { IMAGEHLP_LINE LlineInfo = { sizeof(IMAGEHLP_LINE) }; DWORD dwLineDispment; if (SymGetLineFromAddr(hProcess,sf.AddrPC.Offset,&dwLineDispment,&LlineInfo)) { WriteLogFile("dumplog.txt",TEXT("[Source File : %s ]"),LlineInfo.FileName); WriteLogFile("dumplog.txt",TEXT("[Source Line : %d ]"),LlineInfo.LineNumber); } } } } // EXCEPTION_POINTERS* pExp, DWORD dwExpCode int DumperLog::CrashDumper(EXCEPTION_POINTERS* lpEp, DWORD dwExceptionCode, char *dumpfilename) { HANDLE hProcess = GetCurrentThread(); PEXCEPTION_RECORD lpx = lpEp->ExceptionRecord; PCONTEXT lpContext = lpEp->ContextRecord; SymSetOptions(SYMOPT_DEFERRED_LOADS); if( !SymInitialize(GetCurrentProcess(),0,true) ) return 0; CONTEXT trash= *lpContext; DumpCallStack(&trash,true,hProcess); return 0; } }
[ [ [ 1, 181 ] ] ]
a976fc1d4e8c6c553af27b3fe5ba7a1a99e326e5
71ffdff29137de6bda23f02c9e22a45fe94e7910
/KillaCoptuz3000/src/Objects/CCombatant.cpp
83a715ae70a84a5b76c33089e65ef69ea9630187
[]
no_license
anhoppe/killakoptuz3000
f2b6ecca308c1d6ebee9f43a1632a2051f321272
fbf2e77d16c11abdadf45a88e1c747fa86517c59
refs/heads/master
2021-01-02T22:19:10.695739
2009-03-15T21:22:31
2009-03-15T21:22:31
35,839,301
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,832
cpp
// *************************************************************** // CCombatant version: 1.0 · date: 06/09/2007 // ------------------------------------------------------------- // // ------------------------------------------------------------- // Copyright (C) 2007 - All Rights Reserved // *************************************************************** // // *************************************************************** #include "KillaCoptuz3000/src/Objects/CCombatant.h" #include "KillaCoptuz3000/src/CObjectStorage.h" CCombatant::CCombatant() { m_activeWeapon = 0; m_trackIndex = 0; } #if(PRODUCT == KK3000) bool CCombatant::load(TiXmlNode* t_nodePtr) { TiXmlNode* a_nodePtr = 0; TiXmlElement* a_elemPtr = 0; CWeapon* a_weaponPtr = 0; std::string a_str; unsigned int a_weaponId = 0; m_scriptPtr = 0; // load object specific content CObject::load(t_nodePtr); // Loop over all weapons for(a_nodePtr = t_nodePtr->FirstChild("weapon"); a_nodePtr; a_nodePtr = t_nodePtr->IterateChildren("weapon", a_nodePtr)) { a_weaponId = CObjectStorage::getInstance().add(a_nodePtr, e_weapon, m_id); m_weaponList.push_back(a_weaponId); m_children .push_back(a_weaponId); // Player weapons don't autotrack if (getType() == e_player) { ((CWeapon*)(CObjectStorage::getInstance().m_objectMap[a_weaponId]))->m_isTracking = false; } } return true; } #else bool CCombatant::load(TiXmlNode* t_nodePtr) { TiXmlNode* a_nodePtr = 0; TiXmlElement* a_elemPtr = 0; CWeapon* a_weaponPtr = 0; std::string a_str; unsigned int a_weaponId = 0; m_scriptPtr = 0; // load object specific content CObject::load(t_nodePtr); // // Loop over all weapons // for(a_nodePtr = t_nodePtr->FirstChild("weapon"); a_nodePtr; a_nodePtr = t_nodePtr->IterateChildren("weapon", a_nodePtr)) // { // a_weaponId = CObjectStorage::getInstance().add(a_nodePtr, e_weapon, m_id); // m_weaponList.push_back(a_weaponId); // m_children .push_back(a_weaponId); // // // Player weapons don't autotrack // if (getType() == e_player) // { // ((CWeapon*)(CObjectStorage::getInstance().m_objectMap[a_weaponId]))->m_isTracking = false; // } // } return true; } #endif void CCombatant::fireWeapon() { #if(PRODUCT == KK3000) if (m_activeWeapon < m_weaponList.size()) { ((CWeapon*)(CObjectStorage::getInstance().m_objectMap[m_weaponList[m_activeWeapon]]))->fire(); } #endif } void CCombatant::nextWeapon() { m_activeWeapon++; m_activeWeapon = m_activeWeapon % m_weaponList.size(); }
[ "anhoppe@9386d06f-8230-0410-af72-8d16ca8b68df" ]
[ [ [ 1, 102 ] ] ]
093df851251fc5a36722d4058551be9a4f72411f
999b44927f28a5d5924bd7e552d27d48f66222c0
/include/COLLADASWRotate.h
2635c1e61588813d94ce67d8665bf3aa9546d235
[]
no_license
zakharov/KDLCollada
4a9c7e8f6467fa0b8a2458690015b7cc5c22fe4b
87ef1db551be1727e3608df60d411287085faadc
refs/heads/master
2021-01-23T05:30:22.283377
2011-09-13T11:36:30
2011-09-13T11:36:30
2,076,603
1
1
null
null
null
null
UTF-8
C++
false
false
1,893
h
/* Copyright (c) 2011 Alexey Zakharov email alexey.zakharov at gmail.com This file is part of KDLColladaParser. Licensed under the MIT Open Source License, for details please see LICENSE file or the website http://www.opensource.org/licenses/mit-license.php */ #ifndef __COLLADASTREAMWRITER_ROTATE_H__ #define __COLLADASTREAMWRITER_ROTATE_H__ #include "COLLADASWPrerequisites.h" #include "COLLADASWStreamWriter.h" #include "COLLADASWExtraTechnique.h" #include "COLLADASWConstants.h" namespace COLLADASW { /** A class that hold all information about an @a \<joint\> element.*/ class Rotate : public ElementWriter, public BaseExtraTechnique { private: // LibraryJoints should be able to call the add() method. friend class LibraryKinematicsModels; double mX; double mY; double mZ; double mW; String mRotateSid; protected: /** Adds the joint information. */ void add() const; public: /** * Constructor * @param cameraId The id of the camera. * @param cameraName The name of the camera. */ Rotate ( StreamWriter* streamWriter, double x = 0, double y = 0, double z = 0, double w = 0, const String& rotateSid = ElementWriter::EMPTY_STRING); /** Copy constructor **/ Rotate (const Rotate& orig); /** Destructor */ virtual ~Rotate() { } const String& getRotateSid() const { return mRotateSid; } double getX() const { return mX; } double getY() const { return mY; } double getZ() const { return mZ; } double getW() const { return mW; } }; } //namespace COLLADASW #endif //__COLLADASTREAMWRITER_ROTATE_H__
[ [ [ 1, 75 ] ] ]
f459df395c197eba1618ba04eaf0109c569aae47
acf0e8a6d8589532d5585b28ec61b44b722bf213
/mod_eval_panfilter/component_value_transl.h
ed710440ee693417ebd3df9237e9227dd8d0d0d0
[]
no_license
mchouza/ngpd
0f0e987a95db874b3cde4146364bf1d69cf677cb
5cca5726910bfc97844689f1f40c94b27e0fb9f9
refs/heads/master
2016-09-06T02:09:32.007855
2008-04-06T14:17:55
2008-04-06T14:17:55
35,064,755
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,843
h
// // Copyright (c) 2008, Mariano M. Chouza // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * The names of the contributors may not be used to endorse or promote // products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // //============================================================================= // component_value_transl.h //----------------------------------------------------------------------------- // Creado por Mariano M. Chouza | Agregado a NGPD el 6 de abril de 2008 //============================================================================= #ifndef COMPONENT_VALUE_TRANSL_H #define COMPONENT_VALUE_TRANSL_H /// Clase encargada de traducir un entero representando una posición en una /// serie de valores de componentes al valor efectivo class ComponentValueTransl { public: /// Construye una instancia en base a una tolerancia en partes por mil /// dada ComponentValueTransl(int tolerance); /// Devuelve el valor del componente en base a un índice teniendo /// en cuenta la tolerancia previamente establecida double GetComponentValue(unsigned index) const; /// Obtengo el máximo índice para la tolerancia establecida int GetMaxIndex() const; private: /// Tolerancia int tolerance_; /// Puntero indicando la tabla utilizada int* table_; /// Cantidad de valores por década que tiene la tabla utilizada int valuesPerDec_; /// Cantidad de décadas soportada int cantDec_; }; #endif
[ "mchouza@b858013c-4649-0410-a850-dde43e08a396" ]
[ [ [ 1, 71 ] ] ]
d1d8ba432018679ff077ac30f83690364fb562a6
77d0b0ac21a9afdf667099c3cad0f9bbb483dc25
/include/iglu/twindow.h
09497e70c902d4f7952729f39a8cf78d7d4df49b
[]
no_license
martinribelotta/oneshot
21e218bbdfc310bad4a531dcd401ad28625ead75
81bde2718b6dac147282cce8a1c945187b0b2ccf
refs/heads/master
2021-05-27T23:29:43.732068
2010-05-24T04:36:10
2010-05-24T04:36:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,700
h
/* * IGLU Iterfaz Grafica Libre del Usuario. * Copyright (C) 2005 Martin Alejandro Ribelotta * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _igluTWindow_h #define _igluTWindow_h #include <iglu/tctainer.h> #include <iglu/tbutton.h> #include <iglu/tmenu.h> #define WinBorder (3) #define WinTitleH (Ht*2) class TWindow: public TContainer { protected: // TCharButton *xb; TView *resizearea, *titleBar; TPoint minimumSize; public: TMenuBar *menu; char *title; TWindow (TRect& r, char *s); virtual void getClientArea (TRect& r, int rel=1); void setMenuWindow (TMenuBar *m); virtual void GotFocus (); virtual void LostFocus (); virtual void Hide (); virtual void Show (); virtual void insert (TView *q); virtual void detach (TView *q); virtual void Draw (); virtual void DrawDecorate (); virtual void HandleEvent (TEvent& e); virtual void resize( int w, int h ); }; #endif
[ [ [ 1, 58 ] ] ]
d3646a99daa9673d39d3d37402b679699f332c41
deb8ef49795452ff607023c6bce8c3e8ed4c8360
/Projects/UAlbertaBot/Source/micromanagement/BurrowManager.h
b89c286b247f6b761528033d85f44bbe0971cbbf
[]
no_license
timburr1/ou-skynet
f36ed7996c21f788a69e3ae643b629da7d917144
299a95fae4419429be1d04286ea754459a9be2d6
refs/heads/master
2020-04-19T22:58:46.259980
2011-12-06T20:10:34
2011-12-06T20:10:34
34,360,542
0
0
null
null
null
null
UTF-8
C++
false
false
505
h
#ifndef BURROWMANAGER_H_ #define BURROWMANAGER_H_ #include <Common.h> #include <BWAPI.h> #include "../MapGrid.h" #include "../UnitInfoState.h" class BurrowManager { BurrowManager(); int hydraRange; static BurrowManager * instance; void doBurrow(BWAPI::Unit * unit, UnitVector & enemyNear); public: BWAPI::Unit * exception; static BurrowManager * getInstance(); void update(); void clearExceptions(); void addException(BWAPI::Unit * unit); }; #endif
[ "[email protected]@ce23f72d-95c0-fd94-fabd-fc6dce850bd1" ]
[ [ [ 1, 32 ] ] ]
48153c00a2ca41e21241e5bfeb8b129451901dca
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/ParticleUniverse/src/ParticleEventHandlers/ParticleUniverseDoPlacementParticleEventHandler.cpp
505cc39f05d79f6ae3972febc62479a034eabb0a
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,973
cpp
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #include "ParticleUniversePCH.h" #ifndef PARTICLE_UNIVERSE_EXPORTS #define PARTICLE_UNIVERSE_EXPORTS #endif #include "ParticleEventHandlers/ParticleUniverseDoPlacementParticleEventHandler.h" #include "ParticleUniversePhysicsActor.h" namespace ParticleUniverse { // Constants const unsigned int DoPlacementParticleEventHandler::DEFAULT_NUMBER_OF_PARTICLES = 1; //----------------------------------------------------------------------- DoPlacementParticleEventHandler::DoPlacementParticleEventHandler(void) : ParticleEventHandler(), TechniqueListener(), mForceEmitterName(Ogre::StringUtil::BLANK), mNumberOfParticles(DEFAULT_NUMBER_OF_PARTICLES), mPosition(Ogre::Vector3::ZERO), mFound(false), mAlwaysUsePosition(true), mEmitter(0), mTechnique(0) { } //----------------------------------------------------------------------- DoPlacementParticleEventHandler::~DoPlacementParticleEventHandler(void) { // We cannot remove this listener from mTechnique, because it is undetermined whether the ParticleTechnique // still exist. } //----------------------------------------------------------------------- void DoPlacementParticleEventHandler::_handle (ParticleTechnique* particleTechnique, Particle* particle, Ogre::Real timeElapsed) { if (!particle) return; #ifdef PU_PHYSICS // Do not assume that the contact point is always used if a physics engine is used. if (!mAlwaysUsePosition && particle->physicsActor) { mPosition = particle->physicsActor->contactPoint; // Store the contact point to spawn new particles on that position. } else { mPosition = particle->position; // Store the particles' position to spawn new particles on that position. } #else mPosition = particle->position; // Store the particles' position to spawn new particles on that position. #endif // PU_PHYSICS if (!mFound) { ParticleTechnique* technique = particleTechnique; ParticleEmitter* emitter = particleTechnique->getEmitter(mForceEmitterName); if (!emitter) { // Search all techniques in this ParticleSystem for an emitter with the correct name ParticleSystem* system = particleTechnique->getParentSystem(); size_t size = system->getNumTechniques(); for(size_t i = 0; i < size; ++i) { technique = system->getTechnique(i); emitter = technique->getEmitter(mForceEmitterName); if (emitter) break; } } if (emitter) { mTechnique = technique; mEmitter = emitter; if (mTechnique) { mTechnique->addTechniqueListener(this); } mFound = true; } else { return; } } // Emit 1 or more particles if (mTechnique) { mTechnique->forceEmission(mEmitter, mNumberOfParticles); } } //----------------------------------------------------------------------- void DoPlacementParticleEventHandler::particleEmitted(ParticleTechnique* particleTechnique, Particle* particle) { if (particle && mEmitter == particle->parentEmitter) { particle->position = mPosition; } } //----------------------------------------------------------------------- void DoPlacementParticleEventHandler::setForceEmitterName(const Ogre::String& forceEmitterName) { mForceEmitterName = forceEmitterName; } //----------------------------------------------------------------------- ParticleEmitter* DoPlacementParticleEventHandler::getForceEmitter(void) const { return mEmitter; } //----------------------------------------------------------------------- void DoPlacementParticleEventHandler::removeAsListener(void) { // Reset some values and remove this as a listener from the old technique. if (mTechnique) { mTechnique->removeTechniqueListener(this); } mFound = false; mEmitter = 0; mTechnique = 0; } //----------------------------------------------------------------------- void DoPlacementParticleEventHandler::copyAttributesTo (ParticleEventHandler* eventHandler) { ParticleEventHandler::copyAttributesTo(eventHandler); DoPlacementParticleEventHandler* doPlacementParticleEventHandler = static_cast<DoPlacementParticleEventHandler*>(eventHandler); doPlacementParticleEventHandler->setForceEmitterName(mForceEmitterName); doPlacementParticleEventHandler->setNumberOfParticles(mNumberOfParticles); doPlacementParticleEventHandler->mAlwaysUsePosition = mAlwaysUsePosition; } }
[ [ [ 1, 145 ] ] ]
7af349821ad7c87e3ce28674a86db6a9df10e01f
50f94444677eb6363f2965bc2a29c09f8da7e20d
/Src/EmptyProject/SkillManager.cpp
bd8a79faf65dcc7fb745ae2fe934a65bd558fd3e
[]
no_license
gasbank/poolg
efd426db847150536eaa176d17dcddcf35e74e5d
e73221494c4a9fd29c3d75fb823c6fb1983d30e5
refs/heads/master
2020-04-10T11:56:52.033568
2010-11-04T19:31:00
2010-11-04T19:31:00
1,051,621
1
0
null
null
null
null
UTF-8
C++
false
false
795
cpp
#include "EmptyProjectPCH.h" #include "SkillManager.h" #include "Skill.h" IMPLEMENT_SINGLETON( SkillManager ) SkillManager::SkillManager(void) { } SkillManager::~SkillManager(void) { unregisterAllSkills(); } void SkillManager::registerSkill( Skill* skill ) { if ( m_skillMap.find( skill->getSkillName() ) == m_skillMap.end() ) { m_skillMap[ skill->getSkillName() ] = skill; } else { throw std::runtime_error( "Duplicate skill name is registered." ); } } void SkillManager::unregisterAllSkills() { EpSafeReleaseAllMap( m_skillMap ); } const Skill* SkillManager::getSkill( const char* skillName ) const { SkillMap::const_iterator cit = m_skillMap.find( skillName ); if ( cit != m_skillMap.end() ) return cit->second; else return 0; }
[ [ [ 1, 40 ] ] ]
46e3531b7827ff93e16a87960915cabee9e754c6
de98f880e307627d5ce93dcad1397bd4813751dd
/Sls/WiFiEnginner.h
a9fa5b4c4537a50727a6c547679f2ca68029d5f2
[]
no_license
weimingtom/sls
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
refs/heads/master
2021-01-10T22:20:55.638757
2011-03-19T06:23:49
2011-03-19T06:23:49
44,464,621
2
0
null
null
null
null
UTF-8
C++
false
false
12,047
h
#ifndef WIFI_ENGINNER_H_ #define WIFI_ENGINNER_H_ #define WLAN_MAX_NAME_LENGTH 256 #define DOT11_SSID_MAX_LENGTH 32 // 32 bytes #define WLAN_NOTIFICATION_SOURCE_ACM 8 typedef struct _DOT11_SSID { ULONG uSSIDLength; UCHAR ucSSID[DOT11_SSID_MAX_LENGTH]; } DOT11_SSID, * PDOT11_SSID; typedef enum _DOT11_BSS_TYPE { dot11_BSS_type_infrastructure = 1, dot11_BSS_type_independent = 2, dot11_BSS_type_any = 3 } DOT11_BSS_TYPE, * PDOT11_BSS_TYPE; typedef DWORD WLAN_REASON_CODE, *PWLAN_REASON_CODE; typedef enum _DOT11_PHY_TYPE { dot11_phy_type_unknown = 0, dot11_phy_type_any = dot11_phy_type_unknown, dot11_phy_type_fhss = 1, dot11_phy_type_dsss = 2, dot11_phy_type_irbaseband = 3, dot11_phy_type_ofdm = 4, dot11_phy_type_hrdsss = 5, dot11_phy_type_erp = 6, dot11_phy_type_ht = 7, dot11_phy_type_IHV_start = 0x80000000, dot11_phy_type_IHV_end = 0xffffffff } DOT11_PHY_TYPE, * PDOT11_PHY_TYPE; #define WLAN_MAX_PHY_TYPE_NUMBER 8 typedef ULONG WLAN_SIGNAL_QUALITY, *PWLAN_SIGNAL_QUALITY; typedef struct _NDIS_OBJECT_HEADER { UCHAR Type; UCHAR Revision; USHORT Size; } NDIS_OBJECT_HEADER, *PNDIS_OBJECT_HEADER; typedef enum _DOT11_AUTH_ALGORITHM { DOT11_AUTH_ALGO_80211_OPEN = 1, DOT11_AUTH_ALGO_80211_SHARED_KEY = 2, DOT11_AUTH_ALGO_WPA = 3, DOT11_AUTH_ALGO_WPA_PSK = 4, DOT11_AUTH_ALGO_WPA_NONE = 5, // used in NatSTA only DOT11_AUTH_ALGO_RSNA = 6, DOT11_AUTH_ALGO_RSNA_PSK = 7, DOT11_AUTH_ALGO_IHV_START = 0x80000000, DOT11_AUTH_ALGO_IHV_END = 0xffffffff } DOT11_AUTH_ALGORITHM, * PDOT11_AUTH_ALGORITHM; typedef struct DOT11_AUTH_ALGORITHM_LIST { #define DOT11_AUTH_ALGORITHM_LIST_REVISION_1 1 NDIS_OBJECT_HEADER Header; ULONG uNumOfEntries; ULONG uTotalNumOfEntries; DOT11_AUTH_ALGORITHM AlgorithmIds[1]; } DOT11_AUTH_ALGORITHM_LIST, * PDOT11_AUTH_ALGORITHM_LIST; typedef enum _DOT11_CIPHER_ALGORITHM { DOT11_CIPHER_ALGO_NONE = 0x00, DOT11_CIPHER_ALGO_WEP40 = 0x01, DOT11_CIPHER_ALGO_TKIP = 0x02, DOT11_CIPHER_ALGO_CCMP = 0x04, DOT11_CIPHER_ALGO_WEP104 = 0x05, DOT11_CIPHER_ALGO_WPA_USE_GROUP = 0x100, DOT11_CIPHER_ALGO_RSN_USE_GROUP = 0x100, DOT11_CIPHER_ALGO_WEP = 0x101, DOT11_CIPHER_ALGO_IHV_START = 0x80000000, DOT11_CIPHER_ALGO_IHV_END = 0xffffffff } DOT11_CIPHER_ALGORITHM, * PDOT11_CIPHER_ALGORITHM; typedef struct _WLAN_AVAILABLE_NETWORK { WCHAR strProfileName[WLAN_MAX_NAME_LENGTH]; DOT11_SSID dot11Ssid; DOT11_BSS_TYPE dot11BssType; ULONG uNumberOfBssids; BOOL bNetworkConnectable; WLAN_REASON_CODE wlanNotConnectableReason; ULONG uNumberOfPhyTypes; DOT11_PHY_TYPE dot11PhyTypes[WLAN_MAX_PHY_TYPE_NUMBER]; // bMorePhyTypes is set to TRUE if the PHY types for the network // exceeds WLAN_MAX_PHY_TYPE_NUMBER. // In this case, uNumerOfPhyTypes is WLAN_MAX_PHY_TYPE_NUMBER and the // first WLAN_MAX_PHY_TYPE_NUMBER PHY types are returned. BOOL bMorePhyTypes; WLAN_SIGNAL_QUALITY wlanSignalQuality; BOOL bSecurityEnabled; DOT11_AUTH_ALGORITHM dot11DefaultAuthAlgorithm; DOT11_CIPHER_ALGORITHM dot11DefaultCipherAlgorithm; DWORD dwFlags; DWORD dwReserved; } WLAN_AVAILABLE_NETWORK, *PWLAN_AVAILABLE_NETWORK; typedef enum _WLAN_NOTIFICATION_ACM { wlan_notification_acm_start = 0, wlan_notification_acm_autoconf_enabled, wlan_notification_acm_autoconf_disabled, wlan_notification_acm_background_scan_enabled, wlan_notification_acm_background_scan_disabled, wlan_notification_acm_bss_type_change, wlan_notification_acm_power_setting_change, wlan_notification_acm_scan_complete, wlan_notification_acm_scan_fail, wlan_notification_acm_connection_start, wlan_notification_acm_connection_complete, wlan_notification_acm_connection_attempt_fail, wlan_notification_acm_filter_list_change, wlan_notification_acm_interface_arrival, wlan_notification_acm_interface_removal, wlan_notification_acm_profile_change, wlan_notification_acm_profile_name_change, wlan_notification_acm_profiles_exhausted, wlan_notification_acm_network_not_available, wlan_notification_acm_network_available, wlan_notification_acm_disconnecting, wlan_notification_acm_disconnected, wlan_notification_acm_adhoc_network_state_change, wlan_notification_acm_end } WLAN_NOTIFICATION_ACM, *PWLAN_NOTIFICATION_ACM; typedef struct _WLAN_AVAILABLE_NETWORK_LIST { DWORD dwNumberOfItems; DWORD dwIndex; WLAN_AVAILABLE_NETWORK Network[1]; } WLAN_AVAILABLE_NETWORK_LIST, *PWLAN_AVAILABLE_NETWORK_LIST; typedef enum _WLAN_INTERFACE_STATE { wlan_interface_state_not_ready, wlan_interface_state_connected, wlan_interface_state_ad_hoc_network_formed, wlan_interface_state_disconnecting, wlan_interface_state_disconnected, wlan_interface_state_associating, wlan_interface_state_discovering, wlan_interface_state_authenticating } WLAN_INTERFACE_STATE, *PWLAN_INTERFACE_STATE; typedef struct _WLAN_INTERFACE_INFO { GUID InterfaceGuid; WCHAR strInterfaceDescription[WLAN_MAX_NAME_LENGTH]; WLAN_INTERFACE_STATE isState; } WLAN_INTERFACE_INFO, *PWLAN_INTERFACE_INFO; typedef struct _WLAN_INTERFACE_INFO_LIST { DWORD dwNumberOfItems; DWORD dwIndex; WLAN_INTERFACE_INFO InterfaceInfo[1]; } WLAN_INTERFACE_INFO_LIST, *PWLAN_INTERFACE_INFO_LIST; typedef enum _WLAN_CONNECTION_MODE { wlan_connection_mode_profile = 0, wlan_connection_mode_temporary_profile, wlan_connection_mode_discovery_secure, wlan_connection_mode_discovery_unsecure, wlan_connection_mode_auto, wlan_connection_mode_invalid } WLAN_CONNECTION_MODE, *PWLAN_CONNECTION_MODE; #define DOT11_RATE_SET_MAX_LENGTH 126 typedef struct _WLAN_RATE_SET { ULONG uRateSetLength; USHORT usRateSet[DOT11_RATE_SET_MAX_LENGTH]; } WLAN_RATE_SET, *PWLAN_RATE_SET; typedef UCHAR DOT11_MAC_ADDRESS[6]; typedef DOT11_MAC_ADDRESS * PDOT11_MAC_ADDRESS; typedef struct _WLAN_BSS_ENTRY { DOT11_SSID dot11Ssid; ULONG uPhyId; DOT11_MAC_ADDRESS dot11Bssid; DOT11_BSS_TYPE dot11BssType; DOT11_PHY_TYPE dot11BssPhyType; LONG lRssi; ULONG uLinkQuality; BOOLEAN bInRegDomain; USHORT usBeaconPeriod; ULONGLONG ullTimestamp; ULONGLONG ullHostTimestamp; USHORT usCapabilityInformation; ULONG ulChCenterFrequency; WLAN_RATE_SET wlanRateSet; ULONG ulIeOffset; ULONG ulIeSize; } WLAN_BSS_ENTRY, *PWLAN_BSS_ENTRY; typedef struct _WLAN_BSS_LIST { DWORD dwTotalSize; DWORD dwNumberOfItems; WLAN_BSS_ENTRY wlanBssEntries[1]; } WLAN_BSS_LIST, *PWLAN_BSS_LIST; typedef struct DOT11_BSSID_LIST { #define DOT11_BSSID_LIST_REVISION_1 1 NDIS_OBJECT_HEADER Header; ULONG uNumOfEntries; ULONG uTotalNumOfEntries; DOT11_MAC_ADDRESS BSSIDs[1]; } DOT11_BSSID_LIST, * PDOT11_BSSID_LIST; typedef struct _WLAN_CONNECTION_PARAMETERS { WLAN_CONNECTION_MODE wlanConnectionMode; LPCWSTR strProfile; PDOT11_SSID pDot11Ssid; PDOT11_BSSID_LIST pDesiredBssidList; DOT11_BSS_TYPE dot11BssType; DWORD dwFlags; } WLAN_CONNECTION_PARAMETERS, *PWLAN_CONNECTION_PARAMETERS; typedef struct _WLAN_NOTIFICATION_DATA { DWORD NotificationSource; DWORD NotificationCode; GUID InterfaceGuid; DWORD dwDataSize; PVOID pData; } WLAN_NOTIFICATION_DATA, *PWLAN_NOTIFICATION_DATA; typedef struct _WLAN_RAW_DATA { DWORD dwDataSize; BYTE DataBlob[1]; } WLAN_RAW_DATA, *PWLAN_RAW_DATA; #define WLAN_API_VERSION_1_0 1 #define WLAN_CONNECTION_HIDDEN_NETWORK 0x00000001 #define WLAN_CONNECTION_ADHOC_JOIN_ONLY 0x00000002 #define WLAN_CONNECTION_IGNORE_PRIVACY_BIT 0x00000004 #define WLAN_CONNECTION_EAPOL_PASSTHROUGH 0x00000008 typedef VOID ( WINAPI *WLAN_NOTIFICATION_CALLBACK )( PWLAN_NOTIFICATION_DATA data, PVOID context ); VOID WINAPI WlanNotificationCallback ( PWLAN_NOTIFICATION_DATA data, PVOID context ); class CWiFiEnginner { private: static CWiFiEnginner *iInstance; CWiFiEnginner(); ~CWiFiEnginner(); private: typedef DWORD (WINAPI *WLANOPENHANDLE)(DWORD dwClientVersion, PVOID pReserved, PDWORD pdwNegotiatedVersion, PHANDLE phClientHandle); typedef DWORD (WINAPI *WLANENUMINTERFACES)(HANDLE hClientHandle, PVOID pReserved, PWLAN_INTERFACE_INFO_LIST *ppInterfaceList); typedef DWORD (WINAPI *WLANCLOSEHANDLE)(HANDLE hClientHandle, PVOID pReserved); typedef DWORD (WINAPI *WLANSCAN)(HANDLE hClientHandle,const GUID *pInterfaceGuid,const PDOT11_SSID pDot11Ssid,const PWLAN_RAW_DATA pIeData,PVOID pReserved); typedef DWORD (WINAPI *WLANGETNETWORKBSSLIST)( HANDLE hClientHandle,const GUID *pInterfaceGuid, const PDOT11_SSID pDot11Ssid,DOT11_BSS_TYPE dot11BssType,BOOL bSecurityEnabled,PVOID pReserved,PWLAN_BSS_LIST *ppWlanBssList); typedef DWORD (WINAPI *WLANGETAVAILABLENETWORKLIST)( HANDLE hClientHandle, const GUID *pInterfaceGuid, DWORD dwFlags, PVOID pReserved, PWLAN_AVAILABLE_NETWORK_LIST *ppAvailableNetworkList ); typedef DWORD (WINAPI *WLANCONNECT)( HANDLE hClientHandle, const GUID *pInterfaceGuid, const PWLAN_CONNECTION_PARAMETERS pConnectionParameters, PVOID pReserved ); typedef DWORD (WINAPI *WLANGETPROFILE)( HANDLE hClientHandle, const GUID *pInterfaceGuid, LPCWSTR strProfileName, PVOID pReserved, LPWSTR *pstrProfileXml, DWORD *pdwFlags, PDWORD pdwGrantedAccess ); typedef DWORD (WINAPI *WLANDISCONNECT)( HANDLE hClientHandle, const GUID *pInterfaceGuid, PVOID pReserved ); typedef DWORD (WINAPI *WLANREGISTERNOTIFICATION)( HANDLE hClientHandle, DWORD dwNotifSource, BOOL bIgnoreDuplicate, WLAN_NOTIFICATION_CALLBACK funcCallback, PVOID pCallbackContext, PVOID pReserved, PDWORD pdwPrevNotifSource ); typedef DWORD (WINAPI *WLANSETPROFILE)( HANDLE hClientHandle, const GUID *pInterfaceGuid, DWORD dwFlags, LPCWSTR strProfileXml, LPCWSTR strAllUserProfileSecurity, BOOL bOverwrite, PVOID pReserved, DWORD *pdwReasonCode ); typedef DWORD (*WLANREASONCODETOSTRING)( DWORD dwReasonCode, DWORD dwBufferSize, PWCHAR pStringBuffer, PVOID pReserved ); typedef DWORD (*WLANREASONCODETOSTRING)( DWORD dwReasonCode, DWORD dwBufferSize, PWCHAR pStringBuffer, PVOID pReserved ); typedef DWORD (WINAPI *WLANDELETEPROFILE)( HANDLE hClientHandle, const GUID *pInterfaceGuid, LPCWSTR strProfileName, PVOID pReserved ); private: HANDLE iWifiHandle; HMODULE iLib; WLANCLOSEHANDLE WlanCloseHandle; WLANENUMINTERFACES WlanEnumInterfaces; WLANSCAN WlanScan; WLANGETNETWORKBSSLIST WlanGetNetworkBssList; WLANGETAVAILABLENETWORKLIST WlanGetAvailableNetworkList; WLANCONNECT WlanConnect; WLANGETPROFILE WlanGetProfile; WLANDISCONNECT WlanDisconnect; WLANSETPROFILE WlanSetProfile; WLANREASONCODETOSTRING WlanReasonCodeToString; WLANREGISTERNOTIFICATION WlanRegisterNotification; WLANDELETEPROFILE WlanDeleteProfile; GUID iInterfaceGuid; PWLAN_INTERFACE_INFO_LIST iAvailableInterfaces; WLAN_INTERFACE_STATE iInterfaceState; public: BOOL InitLib(); static CWiFiEnginner *GetInstance(); static void Destroy(); PWLAN_AVAILABLE_NETWORK_LIST ScanWifi(); BOOL WiFiConnection(PWLAN_AVAILABLE_NETWORK netInfo,char *shareKey); private: BOOL WifiSetProfile(PWLAN_AVAILABLE_NETWORK netInfo,char *shareKey); }; #endif
[ [ [ 1, 363 ] ] ]
50867f38efdc659562ad5c1920170a873208866e
444a151706abb7bbc8abeb1f2194a768ed03f171
/trunk/ENIGMAsystem/SHELL/Graphics_Systems/OpenGL/GSscreen.cpp
ed4065e64dab89c7b9c68996de537325b230e7e3
[]
no_license
amorri40/Enigma-Game-Maker
9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6
c6b701201b6037f2eb57c6938c184a5d4ba917cf
refs/heads/master
2021-01-15T11:48:39.834788
2011-11-22T04:09:28
2011-11-22T04:09:28
1,855,342
1
1
null
null
null
null
UTF-8
C++
false
false
7,534
cpp
/** Copyright (C) 2008-2011 Josh Ventura *** *** This file is a part of the ENIGMA Development Environment. *** *** ENIGMA 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, version 3 of the license or any later version. *** *** This application and its source code is distributed AS-IS, 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 code. If not, see <http://www.gnu.org/licenses/> **/ #include <string> #include "OpenGLHeaders.h" #include "GSbackground.h" #include "GSscreen.h" #include "GSd3d.h" using namespace std; #include "../../Universal_System/var4.h" #define __GETR(x) (((unsigned int)x & 0x0000FF)) #define __GETG(x) (((unsigned int)x & 0x00FF00) >> 8) #define __GETB(x) (((unsigned int)x & 0xFF0000) >> 16) #include "../../Universal_System/roomsystem.h" #include "../../Universal_System/instance_system.h" #include "../../Universal_System/graphics_object.h" #include "../../Universal_System/depth_draw.h" #include "../../Platforms/platforms_mandatory.h" #include "../graphics_mandatory.h" using namespace enigma; static inline void draw_back() { //Draw backgrounds for (int back_current=0; back_current<7; back_current++) { if (background_visible[back_current] == 1) { // if (background_stretched) draw_background_stretched(back, x, y, w, h); draw_background_tiled(background_index[back_current], background_x[back_current], background_y[back_current]); } // background_foreground, background_index, background_x, background_y, background_htiled, // background_vtiled, background_hspeed, background_vspeed; } } namespace enigma { extern std::map<int,roomstruct*> roomdata; } void screen_redraw() { if (!view_enabled) { glViewport(0, 0, window_get_width(), window_get_height()); // Possible bug glLoadIdentity(); glScaled(1, -1, 1); glOrtho(-1, room_width, -1, room_height, 0, 1); // possible bug if (background_showcolor) { int clearcolor = ((int)background_color) & 0x00FFFFFF; glClearColor(__GETR(clearcolor) / 255.0, __GETG(clearcolor) / 255.0, __GETB(clearcolor) / 255.0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } draw_back(); for (enigma::diter dit = drawing_depths.rbegin(); dit != drawing_depths.rend(); dit++) { //loop tiles for(std::vector<tile>::size_type i = 0; i != dit->second.tiles.size(); i++) { tile t = dit->second.tiles[i]; draw_background_part(t.bckid, t.bgx, t.bgy, t.width, t.height, t.roomX, t.roomY); } for (enigma::instance_event_iterator = dit->second.draw_events->next; enigma::instance_event_iterator != NULL; enigma::instance_event_iterator = enigma::instance_event_iterator->next) enigma::instance_event_iterator->inst->myevent_draw(); } } else { for (view_current = 0; view_current < 7; view_current++) { if (view_visible[(int)view_current]) { int vc = (int)view_current; int vob = (int)view_object[vc]; if (vob != -1) { object_basic *instanceexists = fetch_instance_by_int(vob); if (instanceexists) { object_planar* vobr = (object_planar*)instanceexists; int vobx = (int)(vobr->x), voby = (int)(vobr->y); //int bbl=*vobr.x+*vobr.bbox_left,bbr=*vobr.x+*vobr.bbox_right,bbt=*vobr.y+*vobr.bbox_top,bbb=*vobr.y+*vobr.bbox_bottom; //if (bbl<view_xview[vc]+view_hbor[vc]) view_xview[vc]=bbl-view_hbor[vc]; if (vobx < view_xview[vc] + view_hborder[vc]) view_xview[vc] = vobx - view_hborder[vc]; else if (vobx > view_xview[vc] + view_wview[vc] - view_hborder[vc]) view_xview[vc] = vobx + view_hborder[vc] - view_wview[vc]; if (voby < view_yview[vc] + view_vborder[vc]) view_yview[vc] = voby - view_vborder[vc]; else if (voby > view_yview[vc] + view_hview[vc] - view_vborder[vc]) view_yview[vc] = voby + view_vborder[vc] - view_hview[vc]; if (view_xview[vc] < 0) view_xview[vc] = 0; else if (view_xview[vc] > room_width - view_wview[vc]) view_xview[vc] = room_width - view_wview[vc]; if (view_yview[vc] < 0) view_yview[vc] = 0; else if (view_yview[vc] > room_height - view_hview[vc]) view_yview[vc] = room_height - view_hview[vc]; } } glViewport((int)view_xport[vc], (int)view_yport[vc], (int)view_wport[vc], (int)view_hport[vc]); glLoadIdentity(); glScaled(1, -1, 1); glOrtho(view_xview[vc] - 1, view_wview[vc] + view_xview[vc], view_yview[vc] - 1, view_hview[vc] + view_yview[vc], 0, 1); // possible bug if (background_showcolor) { int clearcolor = ((int)background_color) & 0x00FFFFFF; glClearColor(__GETR(clearcolor) / 255.0, __GETG(clearcolor) / 255.0, __GETB(clearcolor) / 255.0, 1); glClear(GL_COLOR_BUFFER_BIT); } draw_back(); for (enigma::diter dit = drawing_depths.rbegin(); dit != drawing_depths.rend(); dit++) { //loop tiles for(std::vector<tile>::size_type i = 0; i != dit->second.tiles.size(); i++) { tile t = dit->second.tiles[i]; if (t.roomX + t.width < view_xview[vc] || t.roomY + t.height < view_yview[vc] || t.roomX > view_xview[vc] + view_wview[vc] || t.roomY > view_yview[vc] + view_hview[vc]) continue; draw_background_part(t.bckid, t.bgx, t.bgy, t.width, t.height, t.roomX, t.roomY); } //loop instances for (enigma::instance_event_iterator = dit->second.draw_events->next; enigma::instance_event_iterator != NULL; enigma::instance_event_iterator = enigma::instance_event_iterator->next) enigma::instance_event_iterator->inst->myevent_draw(); } } } } }
[ [ [ 1, 169 ] ] ]
89c3a99e09989c85102ce4ebd81ccaa6b96d80c0
847cccd728e768dc801d541a2d1169ef562311cd
/externalLibs/angelscript/source/as_objecttype.cpp
7f62fecc6dd827c15e9f255954d4373dfc632afa
[]
no_license
aadarshasubedi/Ocerus
1bea105de9c78b741f3de445601f7dee07987b96
4920b99a89f52f991125c9ecfa7353925ea9603c
refs/heads/master
2021-01-17T17:50:00.472657
2011-03-25T13:26:12
2011-03-25T13:26:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,498
cpp
/* AngelCode Scripting Library Copyright (c) 2003-2010 Andreas Jonsson This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. The original version of this library can be located at: http://www.angelcode.com/angelscript/ Andreas Jonsson [email protected] */ // // as_objecttype.cpp // // A class for storing object type information // #include <stdio.h> #include "as_config.h" #include "as_objecttype.h" #include "as_configgroup.h" #include "as_scriptengine.h" BEGIN_AS_NAMESPACE #ifdef AS_MAX_PORTABILITY static void ObjectType_AddRef_Generic(asIScriptGeneric *gen) { asCObjectType *self = (asCObjectType*)gen->GetObject(); self->AddRef(); } static void ObjectType_Release_Generic(asIScriptGeneric *gen) { asCObjectType *self = (asCObjectType*)gen->GetObject(); self->Release(); } static void ObjectType_GetRefCount_Generic(asIScriptGeneric *gen) { asCObjectType *self = (asCObjectType*)gen->GetObject(); *(int*)gen->GetAddressOfReturnLocation() = self->GetRefCount(); } static void ObjectType_SetGCFlag_Generic(asIScriptGeneric *gen) { asCObjectType *self = (asCObjectType*)gen->GetObject(); self->SetGCFlag(); } static void ObjectType_GetGCFlag_Generic(asIScriptGeneric *gen) { asCObjectType *self = (asCObjectType*)gen->GetObject(); *(bool*)gen->GetAddressOfReturnLocation() = self->GetGCFlag(); } static void ObjectType_EnumReferences_Generic(asIScriptGeneric *gen) { asCObjectType *self = (asCObjectType*)gen->GetObject(); asIScriptEngine *engine = *(asIScriptEngine**)gen->GetAddressOfArg(0); self->EnumReferences(engine); } static void ObjectType_ReleaseAllHandles_Generic(asIScriptGeneric *gen) { asCObjectType *self = (asCObjectType*)gen->GetObject(); asIScriptEngine *engine = *(asIScriptEngine**)gen->GetAddressOfArg(0); self->ReleaseAllHandles(engine); } #endif void RegisterObjectTypeGCBehaviours(asCScriptEngine *engine) { // Register the gc behaviours for the object types int r; engine->objectTypeBehaviours.engine = engine; engine->objectTypeBehaviours.flags = asOBJ_REF | asOBJ_GC; engine->objectTypeBehaviours.name = "_builtin_objecttype_"; #ifndef AS_MAX_PORTABILITY r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_ADDREF, "void f()", asMETHOD(asCObjectType,AddRef), asCALL_THISCALL); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_RELEASE, "void f()", asMETHOD(asCObjectType,Release), asCALL_THISCALL); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_GETREFCOUNT, "int f()", asMETHOD(asCObjectType,GetRefCount), asCALL_THISCALL); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_SETGCFLAG, "void f()", asMETHOD(asCObjectType,SetGCFlag), asCALL_THISCALL); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_GETGCFLAG, "bool f()", asMETHOD(asCObjectType,GetGCFlag), asCALL_THISCALL); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_ENUMREFS, "void f(int&in)", asMETHOD(asCObjectType,EnumReferences), asCALL_THISCALL); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_RELEASEREFS, "void f(int&in)", asMETHOD(asCObjectType,ReleaseAllHandles), asCALL_THISCALL); asASSERT( r >= 0 ); #else r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_ADDREF, "void f()", asFUNCTION(ObjectType_AddRef_Generic), asCALL_GENERIC); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_RELEASE, "void f()", asFUNCTION(ObjectType_Release_Generic), asCALL_GENERIC); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_GETREFCOUNT, "int f()", asFUNCTION(ObjectType_GetRefCount_Generic), asCALL_GENERIC); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_SETGCFLAG, "void f()", asFUNCTION(ObjectType_SetGCFlag_Generic), asCALL_GENERIC); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_GETGCFLAG, "bool f()", asFUNCTION(ObjectType_GetGCFlag_Generic), asCALL_GENERIC); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_ENUMREFS, "void f(int&in)", asFUNCTION(ObjectType_EnumReferences_Generic), asCALL_GENERIC); asASSERT( r >= 0 ); r = engine->RegisterBehaviourToObjectType(&engine->objectTypeBehaviours, asBEHAVE_RELEASEREFS, "void f(int&in)", asFUNCTION(ObjectType_ReleaseAllHandles_Generic), asCALL_GENERIC); asASSERT( r >= 0 ); #endif } asCObjectType::asCObjectType() { engine = 0; refCount.set(0); derivedFrom = 0; acceptValueSubType = true; acceptRefSubType = true; } asCObjectType::asCObjectType(asCScriptEngine *engine) { this->engine = engine; refCount.set(0); derivedFrom = 0; acceptValueSubType = true; acceptRefSubType = true; } int asCObjectType::AddRef() { gcFlag = false; return refCount.atomicInc(); } int asCObjectType::Release() { gcFlag = false; return refCount.atomicDec(); } int asCObjectType::GetRefCount() { return refCount.get(); } bool asCObjectType::GetGCFlag() { return gcFlag; } void asCObjectType::SetGCFlag() { gcFlag = true; } asCObjectType::~asCObjectType() { // Release the object type held by the templateSubType if( templateSubType.GetObjectType() ) templateSubType.GetObjectType()->Release(); if( derivedFrom ) derivedFrom->Release(); asUINT n; for( n = 0; n < properties.GetLength(); n++ ) if( properties[n] ) { if( flags & asOBJ_SCRIPT_OBJECT ) { // Release the config group for script classes that are being destroyed asCConfigGroup *group = engine->FindConfigGroupForObjectType(properties[n]->type.GetObjectType()); if( group != 0 ) group->Release(); } asDELETE(properties[n],asCObjectProperty); } properties.SetLength(0); ReleaseAllFunctions(); for( n = 0; n < enumValues.GetLength(); n++ ) { if( enumValues[n] ) asDELETE(enumValues[n],asSEnumValue); } enumValues.SetLength(0); } bool asCObjectType::Implements(const asCObjectType *objType) const { if( this == objType ) return true; for( asUINT n = 0; n < interfaces.GetLength(); n++ ) if( interfaces[n] == objType ) return true; return false; } bool asCObjectType::DerivesFrom(const asCObjectType *objType) const { if( this == objType ) return true; asCObjectType *base = derivedFrom; while( base ) { if( base == objType ) return true; base = base->derivedFrom; } return false; } // interface const char *asCObjectType::GetName() const { return name.AddressOf(); } // interface asDWORD asCObjectType::GetFlags() const { return flags; } // interface asUINT asCObjectType::GetSize() const { return size; } // interface int asCObjectType::GetTypeId() const { // We need a non const pointer to create the asCDataType object. // We're not breaking anything here because this function is not // modifying the object, so this const cast is safe. asCObjectType *ot = const_cast<asCObjectType*>(this); return engine->GetTypeIdFromDataType(asCDataType::CreateObject(ot, false)); } // interface int asCObjectType::GetSubTypeId() const { // TODO: template: This method should allow indexing multiple template subtypes if( flags & asOBJ_TEMPLATE ) { return engine->GetTypeIdFromDataType(templateSubType); } // Only template types have sub types return asERROR; } int asCObjectType::GetInterfaceCount() const { return (int)interfaces.GetLength(); } asIObjectType *asCObjectType::GetInterface(asUINT index) const { return interfaces[index]; } // internal bool asCObjectType::IsInterface() const { if( (flags & asOBJ_SCRIPT_OBJECT) && size == 0 ) return true; return false; } asIScriptEngine *asCObjectType::GetEngine() const { return engine; } int asCObjectType::GetFactoryCount() const { return (int)beh.factories.GetLength(); } int asCObjectType::GetFactoryIdByIndex(int index) const { if( index < 0 || (unsigned)index >= beh.factories.GetLength() ) return asINVALID_ARG; return beh.factories[index]; } int asCObjectType::GetFactoryIdByDecl(const char *decl) const { if( beh.factories.GetLength() == 0 ) return asNO_FUNCTION; // Let the engine parse the string and find the appropriate factory function return engine->GetFactoryIdByDecl(this, decl); } int asCObjectType::GetMethodCount() const { return (int)methods.GetLength(); } int asCObjectType::GetMethodIdByIndex(int index) const { if( index < 0 || (unsigned)index >= methods.GetLength() ) return asINVALID_ARG; return methods[index]; } int asCObjectType::GetMethodIdByName(const char *name) const { int id = -1; for( size_t n = 0; n < methods.GetLength(); n++ ) { if( engine->scriptFunctions[methods[n]]->name == name ) { if( id == -1 ) id = methods[n]; else return asMULTIPLE_FUNCTIONS; } } if( id == -1 ) return asNO_FUNCTION; return id; } int asCObjectType::GetMethodIdByDecl(const char *decl) const { // Get the module from one of the methods if( methods.GetLength() == 0 ) return asNO_FUNCTION; asCModule *mod = engine->scriptFunctions[methods[0]]->module; if( mod == 0 ) { if( engine->scriptFunctions[methods[0]]->funcType == asFUNC_INTERFACE ) return engine->GetMethodIdByDecl(this, decl, 0); return asNO_MODULE; } return engine->GetMethodIdByDecl(this, decl, mod); } asIScriptFunction *asCObjectType::GetMethodDescriptorByIndex(int index) const { if( index < 0 || (unsigned)index >= methods.GetLength() ) return 0; return engine->scriptFunctions[methods[index]]; } int asCObjectType::GetPropertyCount() const { return (int)properties.GetLength(); } int asCObjectType::GetPropertyTypeId(asUINT prop) const { if( prop >= properties.GetLength() ) return asINVALID_ARG; return engine->GetTypeIdFromDataType(properties[prop]->type); } const char *asCObjectType::GetPropertyName(asUINT prop) const { if( prop >= properties.GetLength() ) return 0; return properties[prop]->name.AddressOf(); } asIObjectType *asCObjectType::GetBaseType() const { return derivedFrom; } int asCObjectType::GetPropertyOffset(asUINT prop) const { if( prop >= properties.GetLength() ) return 0; return properties[prop]->byteOffset; } int asCObjectType::GetBehaviourCount() const { // Count the number of behaviours (except factory functions) int count = 0; if( beh.destruct ) count++; if( beh.addref ) count++; if( beh.release ) count++; if( beh.gcGetRefCount ) count++; if( beh.gcSetFlag ) count++; if( beh.gcGetFlag ) count++; if( beh.gcEnumReferences ) count++; if( beh.gcReleaseAllReferences ) count++; if( beh.templateCallback ) count++; if( beh.listFactory ) count++; // For reference types, the factories are also stored in the constructor // list, so it is sufficient to enumerate only those count += (int)beh.constructors.GetLength(); count += (int)beh.operators.GetLength() / 2; return count; } int asCObjectType::GetBehaviourByIndex(asUINT index, asEBehaviours *outBehaviour) const { // Find the correct behaviour int count = 0; if( beh.destruct && count++ == (int)index ) // only increase count if the behaviour is registered { if( outBehaviour ) *outBehaviour = asBEHAVE_DESTRUCT; return beh.destruct; } if( beh.addref && count++ == (int)index ) { if( outBehaviour ) *outBehaviour = asBEHAVE_ADDREF; return beh.addref; } if( beh.release && count++ == (int)index ) { if( outBehaviour ) *outBehaviour = asBEHAVE_RELEASE; return beh.release; } if( beh.gcGetRefCount && count++ == (int)index ) { if( outBehaviour ) *outBehaviour = asBEHAVE_GETREFCOUNT; return beh.gcGetRefCount; } if( beh.gcSetFlag && count++ == (int)index ) { if( outBehaviour ) *outBehaviour = asBEHAVE_SETGCFLAG; return beh.gcSetFlag; } if( beh.gcGetFlag && count++ == (int)index ) { if( outBehaviour ) *outBehaviour = asBEHAVE_GETGCFLAG; return beh.gcGetFlag; } if( beh.gcEnumReferences && count++ == (int)index ) { if( outBehaviour ) *outBehaviour = asBEHAVE_ENUMREFS; return beh.gcEnumReferences; } if( beh.gcReleaseAllReferences && count++ == (int)index ) { if( outBehaviour ) *outBehaviour = asBEHAVE_RELEASEREFS; return beh.gcReleaseAllReferences; } if( beh.templateCallback && count++ == (int)index ) { if( outBehaviour ) *outBehaviour = asBEHAVE_TEMPLATE_CALLBACK; return beh.templateCallback; } if( beh.listFactory && count++ == (int)index ) { if( outBehaviour ) *outBehaviour = asBEHAVE_LIST_FACTORY; return beh.listFactory; } // For reference types, the factories are also stored in the constructor // list, so it is sufficient to enumerate only those if( index - count < beh.constructors.GetLength() ) { if( outBehaviour ) *outBehaviour = asBEHAVE_CONSTRUCT; return beh.constructors[index - count]; } else count += (int)beh.constructors.GetLength(); if( index - count < beh.operators.GetLength() / 2 ) { index = 2*(index - count); if( outBehaviour ) *outBehaviour = static_cast<asEBehaviours>(beh.operators[index]); return beh.operators[index + 1]; } return asINVALID_ARG; } // interface const char *asCObjectType::GetConfigGroup() const { asCConfigGroup *group = engine->FindConfigGroupForObjectType(this); if( group == 0 ) return 0; return group->groupName.AddressOf(); } // internal asCObjectProperty *asCObjectType::AddPropertyToClass(const asCString &name, const asCDataType &dt, bool isPrivate) { asASSERT( dt.CanBeInstanciated() ); asASSERT( !IsInterface() ); // Store the properties in the object type descriptor asCObjectProperty *prop = asNEW(asCObjectProperty); prop->name = name; prop->type = dt; prop->isPrivate = isPrivate; int propSize; if( dt.IsObject() ) { propSize = dt.GetSizeOnStackDWords()*4; if( !dt.IsObjectHandle() ) prop->type.MakeReference(true); } else propSize = dt.GetSizeInMemoryBytes(); // Add extra bytes so that the property will be properly aligned if( propSize == 2 && (size & 1) ) size += 1; if( propSize > 2 && (size & 3) ) size += 4 - (size & 3); prop->byteOffset = size; size += propSize; properties.PushLast(prop); // Make sure the struct holds a reference to the config group where the object is registered asCConfigGroup *group = engine->FindConfigGroupForObjectType(prop->type.GetObjectType()); if( group != 0 ) group->AddRef(); return prop; } // internal void asCObjectType::ReleaseAllHandles(asIScriptEngine *) { ReleaseAllFunctions(); } // internal void asCObjectType::ReleaseAllFunctions() { beh.factory = 0; beh.copyfactory = 0; for( asUINT a = 0; a < beh.factories.GetLength(); a++ ) { if( engine->scriptFunctions[beh.factories[a]] ) engine->scriptFunctions[beh.factories[a]]->Release(); } beh.factories.SetLength(0); beh.construct = 0; beh.copyconstruct = 0; for( asUINT b = 0; b < beh.constructors.GetLength(); b++ ) { if( engine->scriptFunctions[beh.constructors[b]] ) engine->scriptFunctions[beh.constructors[b]]->Release(); } beh.constructors.SetLength(0); if( beh.templateCallback ) engine->scriptFunctions[beh.templateCallback]->Release(); beh.templateCallback = 0; if( beh.listFactory ) engine->scriptFunctions[beh.listFactory]->Release(); beh.listFactory = 0; if( beh.destruct ) engine->scriptFunctions[beh.destruct]->Release(); beh.destruct = 0; if( beh.addref ) engine->scriptFunctions[beh.addref]->Release(); beh.addref = 0; if( beh.release ) engine->scriptFunctions[beh.release]->Release(); beh.release = 0; if( beh.copy ) engine->scriptFunctions[beh.copy]->Release(); beh.copy = 0; if( beh.gcEnumReferences ) engine->scriptFunctions[beh.gcEnumReferences]->Release(); beh.gcEnumReferences = 0; if( beh.gcGetFlag ) engine->scriptFunctions[beh.gcGetFlag]->Release(); beh.gcGetFlag = 0; if( beh.gcGetRefCount ) engine->scriptFunctions[beh.gcGetRefCount]->Release(); beh.gcGetRefCount = 0; if( beh.gcReleaseAllReferences ) engine->scriptFunctions[beh.gcReleaseAllReferences]->Release(); beh.gcReleaseAllReferences = 0; if( beh.gcSetFlag ) engine->scriptFunctions[beh.gcSetFlag]->Release(); beh.gcSetFlag = 0; for( asUINT e = 1; e < beh.operators.GetLength(); e += 2 ) { if( engine->scriptFunctions[beh.operators[e]] ) engine->scriptFunctions[beh.operators[e]]->Release(); } beh.operators.SetLength(0); for( asUINT c = 0; c < methods.GetLength(); c++ ) { if( engine->scriptFunctions[methods[c]] ) engine->scriptFunctions[methods[c]]->Release(); } methods.SetLength(0); for( asUINT d = 0; d < virtualFunctionTable.GetLength(); d++ ) { if( virtualFunctionTable[d] ) virtualFunctionTable[d]->Release(); } virtualFunctionTable.SetLength(0); } // internal void asCObjectType::EnumReferences(asIScriptEngine *) { for( asUINT a = 0; a < beh.factories.GetLength(); a++ ) if( engine->scriptFunctions[beh.factories[a]] ) engine->GCEnumCallback(engine->scriptFunctions[beh.factories[a]]); for( asUINT b = 0; b < beh.constructors.GetLength(); b++ ) if( engine->scriptFunctions[beh.constructors[b]] ) engine->GCEnumCallback(engine->scriptFunctions[beh.constructors[b]]); if( beh.templateCallback ) engine->GCEnumCallback(engine->scriptFunctions[beh.templateCallback]); if( beh.listFactory ) engine->GCEnumCallback(engine->scriptFunctions[beh.listFactory]); if( beh.destruct ) engine->GCEnumCallback(engine->scriptFunctions[beh.destruct]); if( beh.addref ) engine->GCEnumCallback(engine->scriptFunctions[beh.addref]); if( beh.release ) engine->GCEnumCallback(engine->scriptFunctions[beh.release]); if( beh.copy ) engine->GCEnumCallback(engine->scriptFunctions[beh.copy]); if( beh.gcEnumReferences ) engine->GCEnumCallback(engine->scriptFunctions[beh.gcEnumReferences]); if( beh.gcGetFlag ) engine->GCEnumCallback(engine->scriptFunctions[beh.gcGetFlag]); if( beh.gcGetRefCount ) engine->GCEnumCallback(engine->scriptFunctions[beh.gcGetRefCount]); if( beh.gcReleaseAllReferences ) engine->GCEnumCallback(engine->scriptFunctions[beh.gcReleaseAllReferences]); if( beh.gcSetFlag ) engine->GCEnumCallback(engine->scriptFunctions[beh.gcSetFlag]); for( asUINT e = 1; e < beh.operators.GetLength(); e += 2 ) if( engine->scriptFunctions[beh.operators[e]] ) engine->GCEnumCallback(engine->scriptFunctions[beh.operators[e]]); for( asUINT c = 0; c < methods.GetLength(); c++ ) if( engine->scriptFunctions[methods[c]] ) engine->GCEnumCallback(engine->scriptFunctions[methods[c]]); for( asUINT d = 0; d < virtualFunctionTable.GetLength(); d++ ) if( virtualFunctionTable[d] ) engine->GCEnumCallback(virtualFunctionTable[d]); } END_AS_NAMESPACE
[ [ [ 1, 726 ] ] ]
3493161cf4e5cfe61c5333be71c7200942940809
8e4d21a99d0ce5413eab7a083544aff9f944b26f
/include/NthKeyboardController.h
b9a85cb0c0268c62998aabd99d5e8481dfa12cb7
[]
no_license
wangjunbao/nontouchsdk
957612b238b8b221b4284efb377db220bd41186a
81ab8519ea1af45dbb7ff66c6784961f14f9930c
refs/heads/master
2021-01-23T13:57:20.020732
2010-10-31T12:03:49
2010-10-31T12:03:49
34,656,556
0
0
null
null
null
null
UTF-8
C++
false
false
429
h
/* * NthKeyboardController.h * CopyRight @South China Institute of Software Engineering,.GZU * Author: * 2010/10/20 */ #ifndef NTHKEYBOARDCONTROLLER_H #define NTHKEYBOARDCONTROLLER_H #ifdef DLL_FILE class _declspec(dllexport) NthKeyboardController #else class _declspec(dllimport) NthKeyboardController #endif { public: NthKeyboardController(void); ~NthKeyboardController(void); }; #endif
[ "tinya0913@6b3f5b0f-ac10-96f7-b72e-cc4b20d3e213" ]
[ [ [ 1, 24 ] ] ]
f7321591214fc2db486f756019f36020e4284e49
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Collide/Query/Collector/RayCollector/hkpAllRayHitCollector.inl
60fd21bdea442c80941363580f448feabcbdb467
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
1,502
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ void hkpAllRayHitCollector::reset() { m_hits.clear(); hkpRayHitCollector::reset(); } hkpAllRayHitCollector::hkpAllRayHitCollector() { reset(); } hkpAllRayHitCollector::~hkpAllRayHitCollector() { } const hkArray<hkpWorldRayCastOutput>& hkpAllRayHitCollector::getHits() const { return m_hits; } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 48 ] ] ]
342a5b8ebeae54dd67e31a9f78e500d5c6bfc7eb
46885801c2459416e82517f93b7d452d78b33aff
/source/script/tolua.h
efe0dcd7914d2fef83c909f7377d29130c9cf062
[]
no_license
libercv/smallengine
aabe92d4743789e8eab4a65d86d5a838ddc2aded
c1645fb99db213b419a81d4815a6645e1be89fe9
refs/heads/master
2021-01-10T08:09:05.991405
2009-04-01T14:52:59
2009-04-01T14:52:59
36,439,082
0
0
null
null
null
null
ISO-8859-10
C++
false
false
182
h
// ņapita para no tener que tocar bindings.h cada vez que usamos toluaexe.exe #include "lua/tolua.h" #include "../log.h" #include "../stategame.h" using namespace Small;
[ "daviddq@3342a6a6-5e2d-0410-95e1-bf50fdd259a6" ]
[ [ [ 1, 8 ] ] ]
4feb4bd3cf224d6bd0f592fcfcb97dda98aab6e1
a36d7a42310a8351aa0d427fe38b4c6eece305ea
/test_all/SceneImpTest.cpp
2827a50b74106f165d8f9f319f4b16883c0b433f
[]
no_license
newpolaris/mybilliard01
ca92888373c97606033c16c84a423de54146386a
dc3b21c63b5bfc762d6b1741b550021b347432e8
refs/heads/master
2020-04-21T06:08:04.412207
2009-09-21T15:18:27
2009-09-21T15:18:27
39,947,400
0
0
null
null
null
null
UTF-8
C++
false
false
3,376
cpp
#include "StdAfx.h" #include "my_gtest.h" #include "../core_billiard/my_render_imp.h" namespace my_render_imp { class SceneImpTest : public testing::Test { protected: virtual void SetUp() { scene = new SceneImp(); } virtual void TearDown() { delete scene; } SceneImp * scene; static wstring getFilename() { return L"../asset/duck.dae"; } }; TEST_F( SceneImpTest, Constructor ) { ASSERT_TRUE( scene ); } TEST_F( SceneImpTest, Load ) { const bool succeed1 = scene->load( getFilename() ); ASSERT_TRUE( succeed1 ); } TEST_F( SceneImpTest, Load_wrongfile ) { const bool fail1 = scene->load( L"NoFile.dae" ); ASSERT_FALSE( fail1 ); } TEST_F( SceneImpTest, Unload ) { ASSERT_TRUE( scene->load( getFilename() ) ); ASSERT_NE( 0u, scene->getNumberOfVisualScene() ); ASSERT_NE( 0u, scene->getNumberOfNode() ); scene->unload(); ASSERT_EQ( 0u, scene->getNumberOfVisualScene() ); ASSERT_EQ( 0u, scene->getNumberOfNode() ); } TEST_F( SceneImpTest, GetNumberOfVisualScene ) { ASSERT_TRUE( scene->load( getFilename() ) ); ASSERT_EQ( 1u, scene->getNumberOfVisualScene() ); } TEST_F( SceneImpTest, GetVisualSceneByIndex ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetVisualSceneByID ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetDefaultVisualScene ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetCurrentVisualScene ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, SetCurrentVisualScene ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetNumberOfNode ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetNodeByIndex ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetNodeByID ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetNumberOfGeometry ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetGeometryByIndex ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetGeometryByID ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetGeometryByName ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetNumberOfCamera ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetCameraByIndex ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetCameraByID ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, GetCameraByName ) { ASSERT_TRUE( scene->load( getFilename() ) ); } TEST_F( SceneImpTest, IsUpAxisXYZ ) { ASSERT_TRUE( scene->load( getFilename() ) ); ASSERT_FALSE( scene->isUpAxisX() ); ASSERT_TRUE( scene->isUpAxisY() ); ASSERT_FALSE( scene->isUpAxisZ() ); } }
[ "wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635" ]
[ [ [ 1, 110 ] ] ]
e88d261202c9ec329b69d143e140f521b0143800
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/UILayer/ToolbarCtrls/TbcAdvance.h
2c3a99a91d9360fd42598a2f5d82d2642c132f1f
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
622
h
#pragma once // CTbcAdvance #include "ToolBarCtrlZ.h" #include "Localizee.h" class CTbcAdvance : public CToolBarCtrlZ, public CLocalizee { DECLARE_DYNAMIC(CTbcAdvance) LOCALIZEE_WND_CANLOCALIZE() public: CTbcAdvance(); virtual ~CTbcAdvance(); virtual void Localize(); protected: enum {BUTTON_COUNT = 3}; void InitImageList(); int m_iConnectServerStatus; CString GetConnectServerText(); protected: DECLARE_MESSAGE_MAP() public: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnDestroy(); LRESULT OnTbEnableButton(WPARAM wParam, LPARAM lParam); };
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 32 ] ] ]
c51ac74184c463f80366063ebb9ddf12bd630cd7
061348a6be0e0e602d4a5b3e0af28e9eee2d257f
/Source/Base/Event/Producers/OSGMethodDescription.inl
9bb377d951e6924d830d391d26092f7e750258eb
[]
no_license
passthefist/OpenSGToolbox
4a76b8e6b87245685619bdc3a0fa737e61a57291
d836853d6e0647628a7dd7bb7a729726750c6d28
refs/heads/master
2023-06-09T22:44:20.711657
2010-07-26T00:43:13
2010-07-26T00:43:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,485
inl
/*---------------------------------------------------------------------------*\ * OpenSGToolbox * * * * * * * * * * www.vrac.iastate.edu * * * * Authors: David Kabala * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ #ifndef _OSGMETHODDESCRIPTIONIMPL_INL_ #define _OSGMETHODDESCRIPTIONIMPL_INL_ OSG_BEGIN_NAMESPACE inline MethodDescription::MethodDescription(const std::string &szName, const std::string &Description, const UInt32 uiMethodId, const TypeBase &EventArgumentType, FunctorAccessMethod fAccessFunctor) : _szName (szName ), _Description (Description ), _MethodId (uiMethodId ), _EventArgumentType (EventArgumentType ), _fAccessFunctor (fAccessFunctor) { } inline MethodDescription::MethodDescription(const MethodDescription &source) : _szName (source._szName ), _Description (source._Description ), _MethodId (source._MethodId ), _EventArgumentType (source._EventArgumentType ), _fAccessFunctor (source._fAccessFunctor ) { } inline MethodDescription::~MethodDescription(void) { } inline const Char8 *MethodDescription::getCName(void) const { return _szName.c_str(); } inline const std::string &MethodDescription::getName(void) const { return _szName; } inline const std::string &MethodDescription::getDescription(void) const { return _Description; } inline UInt32 MethodDescription::getMethodId(void) const { return _MethodId; } inline void MethodDescription::setMethodId(UInt32 uiMethodId) { _MethodId = uiMethodId; } inline const TypeBase &MethodDescription::getEventArgumentType (void) const { return _EventArgumentType; } inline void MethodDescription::setAccessFunctor(FunctorAccessMethod fAccessFunctor) { _fAccessFunctor = fAccessFunctor; } inline FunctorAccessMethod MethodDescription::getAccessFunctor(void) { return _fAccessFunctor; } inline bool MethodDescription::isValid(void) const { return (this != NULL && !_szName.empty()) ? true : false; } OSG_END_NAMESPACE #endif /* _OSGMETHODDESCRIPTIONIMPL_INL_ */
[ [ [ 1, 34 ], [ 37, 41 ], [ 43, 52 ], [ 54, 67 ], [ 69, 71 ], [ 73, 76 ], [ 83, 114 ], [ 116, 120 ] ], [ [ 35, 36 ], [ 42, 42 ], [ 53, 53 ], [ 68, 68 ], [ 72, 72 ], [ 77, 82 ], [ 115, 115 ] ] ]
9841cf5561a1d5db967018e057f7e801b7cbf744
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/WayFinder/symbian-r6/Nav2UiProtHandler.h
6c85d0dabc49e16b2e3eb20803012b537ae7298a
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,230
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef NAV2_UI_PROT_HANDLER_H #define NAV2_UI_PROT_HANDLER_H class CNav2UiProtHandler : public CBase { public: static TBool SendSearchMessL( CWayFinderAppUi* aWayFinderUI, const TDesC& searchString, const TDesC& searchCity, const TDesC& cityId, TInt countryId, TInt32 lat, TInt32 lon); static TBool SendCategorySearchMessL( CWayFinderAppUi* aWayFinderUI, const char* categoryString, const TDesC& searchCity, const TDesC& cityId, TInt countryId, TInt32 lat, TInt32 lon); private: }; #endif /* NAV2_UI_PROT_HANDLER_H */
[ [ [ 1, 42 ] ] ]
f073684748b09acfb78016ca006bc1984d97fd27
27bde5e083cf5a32f75de64421ba541b3a23dd29
/source/Character.cpp
de48801164121045d88f3bf433021c3183d0c6aa
[]
no_license
jbsheblak/fatal-inflation
229fc6111039aff4fd00bb1609964cf37e4303af
5d6c0a99e8c4791336cf529ed8ce63911a297a23
refs/heads/master
2021-03-12T19:22:31.878561
2006-10-20T21:48:17
2006-10-20T21:48:17
32,184,096
0
0
null
null
null
null
UTF-8
C++
false
false
4,065
cpp
//--------------------------------------------------- // Name: Game : Character // Desc: a character on the field // Author: John Sheblak // Contact: [email protected] //--------------------------------------------------- #include "Character.h" #include "GameXExt.h" #include "GameConstants.h" #include "Util/Tuner.h" namespace Game { bool Character::Init( int32_t* pos ) { //load the images if( !( mBalloonImg = GetImage( "textures/balloon.tga" ) ) ) return false; if( !( mBodyImg = GetImage( "textures/body.tga" ) ) ) return false; mPos[0] = pos[0]; mPos[1] = pos[1]; mBalloonInflation = 1.0f; mState = kState_Alive; UpdateBBox(); return true; } void Character::MoveToPosition( int32_t x, int32_t y ) { if( mState != kState_Alive ) return; mPos[0] = x; mPos[1] = y; UpdateBBox(); } void Character::MoveByDelta( int32_t dx, int32_t dy ) { //if( mState != kState_Alive ) // return; mPos[0] += dx; mPos[1] += dy; // This assumes that the balloon is spherical! if( mPos[0] < ( mBalloonInflation * mBalloonImg->GetWidth()/2 ) ) mPos[0] = (int32_t)(mBalloonInflation * mBalloonImg->GetWidth()/2); if( mPos[0] > (int32_t)( kWindowWidth - mBalloonInflation * mBalloonImg->GetWidth()/2 ) ) mPos[0] = (int32_t)( kWindowWidth - mBalloonInflation * mBalloonImg->GetWidth()/2 ); if( mPos[1] < ( mBalloonInflation * mBalloonImg->GetHeight()/2 ) ) mPos[1] = (int32_t)( mBalloonInflation * mBalloonImg->GetHeight()/2 ); if( mPos[1] > (int32_t)( kWindowHeight - mBalloonInflation * mBalloonImg->GetHeight()/2 ) ) mPos[1] = (int32_t)( kWindowHeight - mBalloonInflation * mBalloonImg->GetHeight()/2 ); UpdateBBox(); } void Character::InflateBalloon( F32 amt ) { if( mState != kState_Alive ) return; const F32 kInflationMin = gTuner.GetFloat( "kInflationMin" ); const F32 kInflationMax = gTuner.GetFloat( "kInflationMax" ); mBalloonInflation += amt; if( mBalloonInflation < kInflationMin ) mBalloonInflation = kInflationMin; if( mBalloonInflation > kInflationMax ) mBalloonInflation = kInflationMax; UpdateBBox(); } void Character::Pop() { mState = kState_Popped; mDieFadeAlpha = 1.0f; mDieFadeImg = GetImage( "textures/dieFade.tga" ); } void Character::Update( F32 curTime ) { if( mState == kState_Alive ) { F32 kGravity = 10.0f; const F32 kBuoyancy = gTuner.GetFloat( "kBuoyancy" ); int32_t dy = (int32_t)(kGravity + mBalloonInflation * kBuoyancy ); if( !dy ) dy += 2; MoveByDelta( 0, dy ); } } void Character::Draw() { int32_t width = (int32_t)(mBalloonImg->GetWidth() * mBalloonInflation); int32_t height = (int32_t)(mBalloonImg->GetHeight() * mBalloonInflation); GameX.DrawImage( mBalloonImg, mPos[0] - width/2, mPos[1] - height/2, 0.0f, mBalloonInflation ); int32_t bodyX = mPos[0] - mBodyImg->GetWidth()/2; int32_t bodyY = mPos[1] + height/2; GameX.DrawImage( mBodyImg, bodyX, bodyY ); if( mState == kState_Popped ) { if( mDieFadeAlpha <= 0 ) { mState = kState_Dead; } else if( mDieFadeImg ) { GameX.DrawImage( mDieFadeImg, mPos[0] - mDieFadeImg->GetWidth()/2, mPos[1] - mDieFadeImg->GetHeight()/2 ); } } } BoundingBoxf* Character::GetBBox() { return &mBBox; } Character::State Character::GetState() { return mState; } bool Character::Collide( const BoundingBoxf& bbox ) { F32 pos [] = { (F32)mPos[0], (F32)mPos[1] }; return bbox.Collide( mBalloonImg->GetWidth() * mBalloonInflation * 0.5f, pos ); } void Character::UpdateBBox() { mBBox.mX = mPos[0] - ( mBalloonImg->GetWidth() * mBalloonInflation ) / 2; mBBox.mY = mPos[1] - ( mBalloonImg->GetHeight() * mBalloonInflation ) / 2; mBBox.mWidth = mBalloonImg->GetWidth() * mBalloonInflation; mBBox.mHeight = mBalloonImg->GetHeight() * mBalloonInflation; } }; //end Game
[ "jbsheblak@5660b91f-811d-0410-8070-91869aa11e15" ]
[ [ [ 1, 162 ] ] ]
a411b3544a4b79e7836404d9bf68b0cb8a49629a
1cf1543cd5460621f530f730a4f3969cfa74197c
/Const.cpp
b274e7a6d9f02238a70702726fc1010ed19eef45
[]
no_license
derpepe/sysprog
042048d0c8f30fb26f0fb79a024530f67a852ca9
2fa6fb3b7c7f53b3fa8ff6aeb74d8d3e3331ba61
refs/heads/master
2021-01-18T14:01:45.742680
2010-02-23T22:23:25
2010-02-23T22:23:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,442
cpp
#include "Const.h" tokenType Const::stateTypeToTokenType(stateType state) { tokenType myResult = TOKEN_UNKNOWN; switch(state) { case STATE_IDENTIFIER: myResult = TOKEN_IDENTIFIER; break; case STATE_INTEGER: myResult = TOKEN_INTEGER; break; case STATE_SIGN: case STATE_SIGN_OPENBRACE: myResult = TOKEN_SIGN; break; case STATE_REAL: case STATE_REAL_EXTENDED: myResult = TOKEN_REAL; break; case STATE_COMMENT: myResult = TOKEN_COMMENT; break; } return myResult; } std::string Const::tokenTypeAsString(tokenType type) { std::string myResult; switch(type) { case TOKEN_ERROR: myResult = "Error"; break; case TOKEN_IDENTIFIER: myResult = "Identifier"; break; case TOKEN_INTEGER: myResult = "Integer"; break; case TOKEN_SIGN: myResult = "Sign"; break; case TOKEN_REAL: myResult = "Real"; break; case TOKEN_READ: myResult = "Read"; break; case TOKEN_WRITE: myResult = "Write"; break; case TOKEN_COMMENT: myResult = "Comment"; break; case TOKEN_PLUS: myResult = "Plus"; break; case TOKEN_MINUS: myResult = "Minus"; break; case TOKEN_SLASH: myResult = "Slash"; break; case TOKEN_STAR: myResult = "Star"; break; case TOKEN_SMALLER: myResult = "Lesser"; break; case TOKEN_GREATER: myResult = "Greater"; break; case TOKEN_ASSIGN: myResult = "Assign"; break; case TOKEN_EXCLAMATIONMARK: myResult = "Exclamation Mark"; break; case TOKEN_AND: myResult = "And"; break; case TOKEN_SEMICOLON: myResult = "Semicolon"; break; case TOKEN_COLON: myResult = "Colon"; break; case TOKEN_BRACE_OPEN: myResult = "Opening Bracket"; break; case TOKEN_BRACE_CLOSE: myResult = "Closing Bracket"; break; case TOKEN_CURLY_BRACE_OPEN: myResult = "Opening Brace"; break; case TOKEN_CURLY_BRACE_CLOSE: myResult = "Closing Brace"; break; case TOKEN_SQUARED_BRACKET_OPEN: myResult = "Opening Square Bracket"; break; case TOKEN_SQUARED_BRACKET_CLOSE: myResult = "Closing Square Bracket"; break; // Erweiterung aus Aufgabe 2 case TOKEN_IF: myResult = "if"; break; case TOKEN_ELSE: myResult = "else"; break; case TOKEN_WHILE: myResult = "while"; break; case TOKEN_INT: myResult = "int"; break; case TOKEN_FLOAT: myResult = "float"; break; // default: myResult = "UNKNOWN"; break; } return myResult; } std::string Const::stateTypeAsString(stateType state) { std::string myResult; switch(state) { case STATE_UNKNOWN : myResult = "Unknown"; break; case STATE_ERROR : myResult = "Error"; break; case STATE_START : myResult = "Start"; break; case STATE_IDENTIFIER : myResult = "Identifier"; break; case STATE_INTEGER : myResult = "Integer"; break; case STATE_SIGN : myResult = "Sign"; break; case STATE_DOT : myResult = "Dot"; break; case STATE_REAL : myResult = "Real"; break; case STATE_REAL_E : myResult = "Real E"; break; case STATE_REAL_PLUSMINUS : myResult = "Real Plus/Minus"; break; case STATE_REAL_EXTENDED : myResult = "Real Extended"; break; case STATE_SIGN_OPENBRACE : myResult = "Sign Openbrace"; break; case STATE_IN_COMMENT : myResult = "In Comment"; break; case STATE_ALMOST_COMMENT : myResult = "Almost Comment"; break; case STATE_COMMENT : myResult = "Comment"; break; default: myResult = "UNKNOWN"; break; } return myResult; }
[ [ [ 1, 104 ] ] ]
08414d6a921c24e0d7d0502aec83ba5472b42d1e
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/Limn/LimnDW/Common/LimnModel_DiamondWizard_EfficiencyCurve.h
320eed29a0feef120a24290d00fe659184a63d2b
[]
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
3,437
h
#pragma once // //------------------------------------------------------------------------------------------------------- // // DIAMOND WIZARD SPECIFIC - EFFICIENCY CURVE // // Parameter Access Class class C_ModelParameters_DiamondWizard_EfficiencyCurve: public CLimn_ModelData_Base { public: C_ModelParameters_DiamondWizard_EfficiencyCurve(void) : CLimn_ModelData_Base(&sm_Common) { m_nSGs=0; }; C_ModelParameters_DiamondWizard_EfficiencyCurve(double* ModelParams, int nSG) : CLimn_ModelData_Base(&sm_Common, ModelParams) // usually called from parameter passing { //m_pData=ModelParams; Initialise(nSG); } ~C_ModelParameters_DiamondWizard_EfficiencyCurve(void) { }; static CLimn_ModelData_Common sm_Common; CDoubleRef OversizeStreamID; CDoubleRef WaterSplit; CDoubleRef FeSiSplit; CDoubleRef Alpha; CDoubleRef Rf; CVectorRef D50c; CDoubleRef DiamondD50c; bool Product1IsOversize() { return OversizeStreamID() < 1.5 ? true : false ; }; void Initialise(int nSGs) { CLimn_ModelData_Base::Initialise(); m_nSGs = nSGs; OversizeStreamID .Initialise(this, "OversizeStreamID", 1, "", true); WaterSplit .Initialise(this, "WaterSplit", 0.25, "Frac(.)"); FeSiSplit .Initialise(this, "FeSiSplit", 0.25, "Frac(.)"); Alpha .Initialise(this, "Alpha", 10, ""); Rf .Initialise(this, "Rf", 0, ""); D50c .Initialise(this, "D50", m_nSGs, DI_SG, "D50c", 10, "L(mm)"); DiamondD50c .Initialise(this, "DiamondD50c", 10, "L(mm)"); }; protected: int m_nSGs; }; // // Limn callable model C_LINKAGE DLLMODEL int _Model_DiamondWizard_EfficiencyCurve (int nRows, int nColumns, int nParameters, int nReturns, double* ModelParams, double* ModelReturn, double* CombinedFeed, double* Product1, double* Product2, double* Product3, double* Product4, double* Product5, double* Product6 ) ; // // Error information C_LINKAGE int DLLMODEL _Error_DiamondWizard_EfficiencyCurve ( int errorIndex, LPSTR errorBuffer ) ; // // Parameter information C_LINKAGE int DLLMODEL _Parameter_DiamondWizard_EfficiencyCurve ( int parameterIndex, LPSTR parameterInfoBuffer ) ; //
[ [ [ 1, 78 ] ] ]
d72908c0a58b5c8d4a3c94b90b61e33fa05d6825
2d212a074917aad8c57ed585e6ce8e2073aa06c6
/cgworkshop/src/GUI/Box.h
d6412f8c7ee1a171e0833b81c8abec319ac58bce
[]
no_license
morsela/cgworkshop
b31c9ec39419edcedfaed81468c923436528e538
cdf9ef2a9b2d9c389279fe0e38fb9c8bc1d86d89
refs/heads/master
2021-07-29T01:37:24.739450
2007-09-09T13:44:54
2007-09-09T13:44:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,500
h
#ifndef _H_BOX_H_ #define _H_BOX_H_ #include <cv.h> #include <GL/glut.h> #define COLOR_OFFSET 0 #define LINE_OFFSET 100 #define BUTTON_OFFSET 200 #define CHOSSEN_COLOR_BOX_MARGIN 2.0 #define MARGIN_SIZE 8 #define BOX_MARGIN_SIZE 5 #define UNDEFINED -1 class CBox { public: enum EBoxType { TYPE_COLOR_BOX, TYPE_LINE_BOX, TYPE_BUTTON_BOX }; public: CBox(int nID, float x, float y, float width, float height, EBoxType type): m_x(x),m_y(y),m_width(width),m_height(height),m_fChosen(false),m_nID(nID),m_type(type) {} ~CBox() {} virtual void Draw() = 0; void Reset() { m_fChosen = false; } void Choose() { m_fChosen = true; } bool Choose(float x, float y); bool IsChosen() { return m_fChosen; } int GetID() { return m_nID; } EBoxType GetType() { return m_type; } protected: EBoxType m_type; int m_nID; bool m_fChosen; float m_x; float m_y; float m_width; float m_height; }; class CColorBox : public CBox { public: CColorBox(int nID, float x, float y, float width, float height, CvScalar& color): CBox(nID,x,y,width, height,TYPE_COLOR_BOX), m_color(color) {} ~CColorBox() {} void Draw(); CvScalar & GetColor() { return m_color; } protected: CvScalar m_color; }; class CLineBox : public CBox { protected: static const int INNER_LINE_MARGIN_WIDTH = 5; public: CLineBox(int nID, float x, float y, float width, float height, int nLineWidth): CBox(nID,x,y,width, height, TYPE_LINE_BOX), m_nLineWidth(nLineWidth) {} ~CLineBox() {} void Draw(); int GetLineWidth() const { return m_nLineWidth; } protected: int m_nLineWidth; }; class CButtonBox : public CBox { public: enum EButtonCommand { command_Colorize_A = 0, command_Colorize_B, command_Colorize_C, command_Clear, command_Save, command_Load, command_Quit, command_Max }; protected: static const int INNER_LINE_MARGIN_WIDTH = 5; static const int TEXT_MARGIN = 2; public: CButtonBox(int nID, float x, float y, float width, float height, EButtonCommand command, char * cmdString): CBox(nID,x,y,width, height, TYPE_BUTTON_BOX), m_command(command) { strcpy(m_pszString, cmdString); } ~CButtonBox() {} void Draw(); int GetCommand() const { return m_command; } protected: char m_pszString[256]; EButtonCommand m_command; }; #endif //_H_BOX_H_
[ "morsela@60b542fb-872c-0410-bfbb-43802cb78f6e" ]
[ [ [ 1, 136 ] ] ]
c2f0f01a1edd703aee5e36efdcfcdce61907661d
018ded69bef54d0c92c05922dd14bf2b835e0c1a
/mfctest_backup/mfctest/mfctest.h
6337b3fdb298506aa000b45ad582b57b736ec4e0
[]
no_license
JerryAi/gamepipe-arcade-ui
adfd3f90f1e2bd2c2ed2e0773f8ed3f39bb51eed
bfb630db752b7c6dec6abf8b06fe037d95ab68db
refs/heads/master
2021-01-22T07:04:09.313697
2010-04-16T02:08:30
2010-04-16T02:08:30
39,057,009
0
0
null
null
null
null
GB18030
C++
false
false
495
h
// mfctest.h : PROJECT_NAME 应用程序的主头文件 // #pragma once #ifndef __AFXWIN_H__ #error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件" #endif #include "resource.h" // 主符号 // CmfctestApp: // 有关此类的实现,请参阅 mfctest.cpp // class CmfctestApp : public CWinAppEx { public: CmfctestApp(); // 重写 public: virtual BOOL InitInstance(); // 实现 DECLARE_MESSAGE_MAP() }; extern CmfctestApp theApp;
[ "willyujenhuang@c7cd5111-5711-00b0-e4a8-d5dc6a703e49" ]
[ [ [ 1, 32 ] ] ]
e756832535e0d77bde313baa6bdf8dc5c6c8b8cb
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/plugins/GSdx/GSDirtyRect.cpp
d2e0ed0b3b6ef7766fc83a211ecd378e5d118fa0
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
2,115
cpp
/* * Copyright (C) 2007-2009 Gabest * http://www.gabest.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, 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 GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #include "StdAfx.h" #include "GSDirtyRect.h" GSDirtyRect::GSDirtyRect() : psm(PSM_PSMCT32) { left = top = right = bottom = 0; } GSDirtyRect::GSDirtyRect(const GSVector4i& r, uint32 psm) : psm(psm) { left = r.left; top = r.top; right = r.right; bottom = r.bottom; } GSVector4i GSDirtyRect::GetDirtyRect(const GIFRegTEX0& TEX0) { GSVector4i r; GSVector2i src = GSLocalMemory::m_psm[psm].bs; if(psm != TEX0.PSM) { GSVector2i dst = GSLocalMemory::m_psm[TEX0.PSM].bs; r.left = MulDiv(left, dst.x, src.x); r.top = MulDiv(top, dst.y, src.y); r.right = MulDiv(right, dst.x, src.x); r.bottom = MulDiv(bottom, dst.y, src.y); } else { r = GSVector4i(left, top, right, bottom).ralign<GSVector4i::Outside>(src); } return r; } // GSVector4i GSDirtyRectList::GetDirtyRectAndClear(const GIFRegTEX0& TEX0, const GSVector2i& size) { if(!empty()) { GSVector4i r(INT_MAX, INT_MAX, 0, 0); for(list<GSDirtyRect>::iterator i = begin(); i != end(); i++) { r = r.runion(i->GetDirtyRect(TEX0)); } clear(); GSVector2i bs = GSLocalMemory::m_psm[TEX0.PSM].bs; return r.ralign<GSVector4i::Outside>(bs).rintersect(GSVector4i(0, 0, size.x, size.y)); } return GSVector4i::zero(); }
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 84 ] ] ]
c4bfbda5b18adae39bf281d62e53e3862c21c840
58ef4939342d5253f6fcb372c56513055d589eb8
/LemonTangram/source/TangImage/src/ImageElement.cpp
9a0a73b42a2085a510573a392daf94f20ff9b818
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
UTF-8
C++
false
false
2,136
cpp
/* ============================================================================ Name : ImageElement.cpp Author : zengcity Version : 1.0 Copyright : Your copyright notice Description : CImageElement implementation ============================================================================ */ #include "ImageElement.h" #include "MacroUtil.h" #include <eikenv.h> CImageElement::CImageElement() :iCenterX(0),iCenterY(0),iBitmapLoad(NULL),iBitmapRotate(NULL),iBitmapMask(NULL), iState(KImageStateNone),iDegree(0),iSelected(EFalse),iFlip(EFalse) { // No implementation required } CImageElement::~CImageElement() { SAFE_DELETE(iBitmapLoad); SAFE_DELETE(iBitmapRotate); SAFE_DELETE(iBitmapMask); } CImageElement* CImageElement::NewLC() { CImageElement* self = new (ELeave)CImageElement(); CleanupStack::PushL(self); self->ConstructL(); return self; } CImageElement* CImageElement::NewL() { CImageElement* self=CImageElement::NewLC(); CleanupStack::Pop(); // self; return self; } void CImageElement::ConstructL() { } void CImageElement::SetPoistion(const TPoint& aPoint) { iCenterX = aPoint.iX; iCenterY = aPoint.iY; } void CImageElement::SetPointion(TInt aX,TInt aY) { iCenterX = aX; iCenterY = aY; } void CImageElement::Draw(CBitmapContext& aGc) { if (iBitmapRotate && iBitmapMask) { TInt x,y; x = iCenterX + iOffsetX; y = iCenterY + iOffsetY; TRect rect( TPoint( 0,0 ),iBitmapRotate->SizeInPixels() ); aGc.BitBltMasked(TPoint(x,y),iBitmapRotate, rect,iBitmapMask,ETrue); } } void CImageElement::Draw(CBitmapContext& aGc, TInt aScrollX, TInt aScrollY) { if (iBitmapRotate && iBitmapMask) { TInt x,y; x = iCenterX + iOffsetX + aScrollX; y = iCenterY + iOffsetY + aScrollY; TRect rect( TPoint( 0,0 ),iBitmapRotate->SizeInPixels() ); aGc.BitBltMasked(TPoint(x,y),iBitmapRotate, rect,iBitmapMask,ETrue); } } void CImageElement::SetDegree(TInt aDegree) { iDegree = aDegree; if (iDegree > 360) iDegree -= 360; else if(iDegree < 0) iDegree += 360; }
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 93 ] ] ]
306af2780b39c82705d50d24d6d728e3862b8a20
7347ab0d3daab6781af407d43ac29243daeae438
/src/being.cpp
b7f445d99ce72378e56476828d6a3ce90dee2db1
[]
no_license
suprafun/smalltowns
e096cdfc11e329674a7f76486452f4cd58ddaace
c722da7dd3a1d210d07f22a6c322117b540e63da
refs/heads/master
2021-01-10T03:09:47.664318
2011-06-03T01:22:29
2011-06-03T01:22:29
50,808,558
0
0
null
null
null
null
UTF-8
C++
false
false
12,218
cpp
/********************************************* * * Author: David Athay * * License: New BSD License * * Copyright (c) 2008, CT Games * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the CT Games name nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * * * Date of file creation: 09-02-25 * * $Id$ * ********************************************/ #include "being.h" #include "resourcemanager.h" #include "map.h" #include "graphics/animation.h" #include "graphics/graphics.h" #include "graphics/texture.h" #include "resources/bodypart.h" #include "utilities/log.h" #include <sstream> #include <cmath> namespace ST { // tile relative direction int getDirection(const Point &start, const Point &end) { int x = start.x - end.x; int y = start.y - end.y; if (x > 0) { if (y > 0) return DIRECTION_NORTHWEST; else if (y < 0) return DIRECTION_SOUTHWEST; return DIRECTION_WEST; } else if (x < 0) { if (y > 0) return DIRECTION_NORTHEAST; else if (y < 0) return DIRECTION_SOUTHEAST; return DIRECTION_EAST; } if (y > 0) return DIRECTION_NORTH; return DIRECTION_SOUTH; } Being::Being(int id, const std::string &name, Texture *avatar): AnimatedNode(name, avatar), mId(id) { look.hair = 0; look.face = 0; look.body = 0; look.chest = 0; look.legs = 0; look.feet = 0; look.gender = 0; look.hairColour.r = 0; look.hairColour.g = 0; look.hairColour.b = 0; look.eyeColour.r = 0; look.eyeColour.g = 0; look.eyeColour.b = 0; look.skinColour.r = 0; look.skinColour.g = 0; look.skinColour.b = 0; mAnchor = 16; mNPC = false; mTileChanged = false; } Being::~Being() { } std::string Being::getName() { return mName; } unsigned int Being::getId() const { return mId; } void Being::logic(int ms) { AnimatedNode::logic(ms); //TODO: Being processing switch (mState) { case STATE_IDLE: break; case STATE_MOVING: move(ms); break; } } void Being::setState(int state) { mState = state; } int Being::getState() { return mState; } void Being::setAnimation(const std::string &name) { // delete any old animation that was set delete mSetAnimation; mSetAnimation = NULL; // if name is empty, unset the animation if (name.empty()) { mUpdateTime = 0; return; } // get existing animation Animation *body = resourceManager->getAnimation(look.body, name); if (!body) return; // get existing animation Animation *hair = resourceManager->getAnimation(look.hair, name); if (!hair) return; // get existing animation Animation *chest = resourceManager->getAnimation(look.chest, name); Animation *legs = resourceManager->getAnimation(look.legs, name); Animation *feet = resourceManager->getAnimation(look.feet, name); // create new animation to store the new frames mSetAnimation = new Animation; unsigned int frames = body->getFrames(); frames = std::min(frames, hair->getFrames()); // create new frames and store them in the animation for (unsigned int i = 0; i < frames; ++i) { std::map<int, Texture*> textures; textures[PART_BODY] = body->getTexture(); textures[PART_HAIR] = hair->getTexture(); if (chest) textures[PART_CHEST] = chest->getTexture(); if (legs) textures[PART_LEGS] = legs->getTexture(); if (feet) textures[PART_FEET] = feet->getTexture(); Texture *tex = graphicsEngine->createAvatarFrame(mId, i+1, textures, mDirection); mSetAnimation->addTexture(tex); body->nextFrame(); hair->nextFrame(); if (chest) chest->nextFrame(); if (legs) legs->nextFrame(); if (feet) feet->nextFrame(); } // set the update rate based on number of frames per second mUpdateTime = 1000 / mSetAnimation->getFrames(); } bool Being::calculateNextDestination(const Point &finish) { int hops = 0; int dir = DIRECTION_NORTH; int hw = mWidth >> 1; int mapHeight = mapEngine->getTileHeight(); int hmh = mapHeight >> 1; // set start point mLastPosition.x = mPosition.x; mLastPosition.y = mPosition.y; // empty any previous path mWaypoints.clear(); Point wayPos = getTilePosition(); Point endPos = finish; Point screenPos = {0,0}; // keep moving a tile towards destination until reached while(hops < 20) { if (wayPos.x == endPos.x && wayPos.y == endPos.y) { break; } // find a direction to move closer to the end point dir = getDirection(wayPos, endPos); // find the tile inbetween wayPos = getNextTile(wayPos, dir); // translate to screen position and store that screenPos = mapEngine->convertTileToPixel(wayPos); screenPos.x += hw >> 1; screenPos.y += hmh; mWaypoints.push_back(screenPos); ++hops; } return (hops < 20); } bool Being::calculateNextDestination() { return calculateNextDestination(mDestination); } void Being::move(int ms) { Pointf nextPos; Point nextDest; Point movePos; Point srcTile; Point destTile; float speed = 50.0f; float distx = 0.0f; float disty = 0.0f; float distance = 0.0f; float time = 0.0f; // check theres waypoints if (mWaypoints.size() == 0) { return; } // check if reached way point if (mPosition.x == mWaypoints[0].x && mPosition.y == mWaypoints[0].y) { mWaypoints.pop_front(); if (mWaypoints.size() == 0) { mDirection = -1; setAnimation(""); setState(STATE_IDLE); return; } } // set the next destination nextDest = mWaypoints[0]; // calculate next position by taking the last position and // destination and finding position after travelling since last frame distx = nextDest.x - mLastPosition.x; disty = nextDest.y - mLastPosition.y; // avoid divide by 0 distance = distx * distx + disty * disty; if (distance < 1 && distance > -1) { mPosition.x = mWaypoints[0].x; mPosition.y = mWaypoints[0].y; return; } distance = sqrtf(distance); time = ms / 1000.0f; speed *= time; if (speed > distance) speed = distance; nextPos.x = mLastPosition.x + (distx / distance) * speed; nextPos.y = mLastPosition.y + (disty / distance) * speed; movePos.x = nextPos.x; movePos.y = nextPos.y; // compare to last tile position to see if changed which tile being is on srcTile = mapEngine->convertPixelToTile(mLastPosition.x, mLastPosition.y); destTile = mapEngine->convertPixelToTile(movePos.x, movePos.y); if (srcTile.x != destTile.x || srcTile.y != destTile.y) { mTileChanged = true; graphicsEngine->sort(); } else { mTileChanged = false; } moveNode(&movePos); // check if direction changed, so we can turn the being and change its animation srcTile = destTile; destTile = mapEngine->convertPixelToTile(nextDest.x, nextDest.y); if (srcTile.x != destTile.x || srcTile.y != destTile.y) { int dir = getDirection(srcTile, destTile); if (mDirection != dir) { turnNode(dir); changeAnimation(); } } mLastPosition = nextPos; } Point Being::getNextTile(const Point &pt, int dir) { Point pos = mapEngine->walkMap(pt, dir); int attempts = 2; int diff = 1; // keep trying a different direction till valid tile found // or until maximum number of attempts failed while (attempts > 0 && mapEngine->blocked(pos)) { dir += diff; pos = mapEngine->walkMap(pt, dir); // count down so it doesnt loop forever --attempts; // make it try different direction next time diff = -diff; // check for greater or less than minimum and maximum direction if (dir < DIRECTION_NORTH) dir = DIRECTION_NORTHWEST; if (dir > DIRECTION_NORTHWEST) dir = DIRECTION_NORTH; } return pos; } void Being::saveDestination(const Point &pos) { mDestination = pos; } void Being::changeAnimation() { std::stringstream str; // create the string for new animation // check gender // check direction // check state // final string will look like maleSEwalk if (look.body == 1) // TODO: fix this, server should send gender str << "male"; else str << "female"; // direction is tile based switch (mDirection) { case DIRECTION_WEST: str << "NW"; break; case DIRECTION_NORTH: case DIRECTION_NORTHWEST: str << "NE"; break; case DIRECTION_SOUTHWEST: case DIRECTION_SOUTH: str << "SW"; break; case DIRECTION_SOUTHEAST: case DIRECTION_EAST: case DIRECTION_NORTHEAST: str << "SE"; break; default: str << "SE"; break; } if (mState == STATE_MOVING) str << "walk"; setAnimation(str.str()); } bool Being::tileChanged() const { return mTileChanged; } }
[ "ko2fan@2ae5cb60-8703-11dd-9899-c7ba65f7c4c7" ]
[ [ [ 1, 438 ] ] ]
06d19f2dc8bb6f47b021c83b58ca67af2fb53a26
67c2e1ce81b343952e96b09e2eaf1ddc7f3888fc
/Dependencies/LiteSQL/src/generator/ui/ui.h
c14fc2b8a0d95df703039eef40e23ce94a8b3721
[ "BSD-3-Clause" ]
permissive
aclysma/Helium
806c5a3954ecd162a1a7137562bd0f71e084423a
a009248596b2e537ccb8e7c3e587628b8bda8b7a
refs/heads/master
2021-01-18T05:31:57.004647
2011-06-07T04:49:10
2011-06-07T04:49:10
1,301,697
1
0
null
null
null
null
UTF-8
C++
false
false
7,545
h
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version Apr 16 2008) // http://www.wxformbuilder.org/ // // PLEASE DO LITESQL_L("NOT") EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #ifndef __ui__ #define __ui__ #include <wx/cshelp.h> #include <wx/intl.h> #include <wx/string.h> #include <wx/stattext.h> #include <wx/gdicmn.h> #include <wx/font.h> #include <wx/colour.h> #include <wx/settings.h> #include <wx/textctrl.h> #include <wx/choice.h> #include <wx/sizer.h> #include <wx/panel.h> #include <wx/checkbox.h> #include <wx/listctrl.h> #include <wx/button.h> #include <wx/dialog.h> #include <wx/filepicker.h> #include <wx/checklst.h> #include <wx/gauge.h> #include <wx/treectrl.h> #include <wx/notebook.h> #include <wx/splitter.h> /////////////////////////////////////////////////////////////////////////// namespace ui { /////////////////////////////////////////////////////////////////////////////// /// Class ObjectPanel /////////////////////////////////////////////////////////////////////////////// class ObjectPanel : public wxPanel { private: protected: wxStaticText* lblName; wxTextCtrl* m_textCtrlName; wxStaticText* lblInherits; wxChoice* m_choiceInheritsFrom; public: ObjectPanel( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 300,80 ), long style = wxTAB_TRAVERSAL ); ~ObjectPanel(); }; /////////////////////////////////////////////////////////////////////////////// /// Class FieldPanel /////////////////////////////////////////////////////////////////////////////// class FieldPanel : public wxPanel { private: protected: wxStaticText* lblName; wxTextCtrl* m_textCtrlName; wxStaticText* lblFieldtype; wxChoice* m_choiceFieldtype; wxStaticText* lblDefault; wxTextCtrl* m_textCtrlDefaultValue; wxStaticText* lblIndexed; wxCheckBox* m_checkBoxIndexed; wxStaticText* lblUnique; wxCheckBox* m_checkBoxUnique; wxStaticText* lblValues; wxListCtrl* m_listValues; wxStaticText* m_staticText20; wxButton* m_btnAdd; wxButton* m_btnRemove; // Virtual event handlers, overide them in your derived class virtual void OnAddValue( wxCommandEvent& event ){ event.Skip(); } virtual void OnRemoveValue( wxCommandEvent& event ){ event.Skip(); } public: FieldPanel( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 338,302 ), long style = wxTAB_TRAVERSAL ); ~FieldPanel(); }; /////////////////////////////////////////////////////////////////////////////// /// Class MethodPanel /////////////////////////////////////////////////////////////////////////////// class MethodPanel : public wxPanel { private: protected: wxStaticText* lblName; wxTextCtrl* m_textCtrlName; public: MethodPanel( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 300,164 ), long style = wxTAB_TRAVERSAL ); ~MethodPanel(); }; /////////////////////////////////////////////////////////////////////////////// /// Class RelationPanel /////////////////////////////////////////////////////////////////////////////// class RelationPanel : public wxPanel { private: protected: wxStaticText* lblName; wxTextCtrl* m_textCtrlName; wxStaticText* lblObject1; wxChoice* m_choiceObject1; wxStaticText* lblObject2; wxChoice* m_choiceObject2; public: RelationPanel( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 318,120 ), long style = wxTAB_TRAVERSAL ); ~RelationPanel(); }; /////////////////////////////////////////////////////////////////////////////// /// Class DatabasePanel /////////////////////////////////////////////////////////////////////////////// class DatabasePanel : public wxPanel { private: protected: wxStaticText* m_staticName; wxTextCtrl* m_textName; wxStaticText* m_staticNamespace; wxTextCtrl* m_textNamespace; wxStaticText* m_staticInclude; wxTextCtrl* m_textInclude; public: DatabasePanel( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 300,120 ), long style = wxTAB_TRAVERSAL ); ~DatabasePanel(); }; /////////////////////////////////////////////////////////////////////////////// /// Class AboutDialog /////////////////////////////////////////////////////////////////////////////// class AboutDialog : public wxDialog { private: protected: wxStaticText* m_staticText4; wxStaticText* m_staticText5; wxButton* m_btnClose; public: AboutDialog( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 345,320 ), long style = wxDEFAULT_DIALOG_STYLE ); ~AboutDialog(); }; /////////////////////////////////////////////////////////////////////////////// /// Class GeneratePanel /////////////////////////////////////////////////////////////////////////////// class GeneratePanel : public wxPanel { private: protected: wxStaticText* m_staticOutputDir; wxDirPickerCtrl* m_dirPickerOutputDir; wxStaticText* m_staticGenerators; wxCheckListBox* m_checkListGenerators; wxButton* m_buttonRun; wxGauge* m_gaugeRunProgress; // Virtual event handlers, overide them in your derived class virtual void OnRunClick( wxCommandEvent& event ){ event.Skip(); } public: GeneratePanel( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 400,210 ), long style = wxTAB_TRAVERSAL ); ~GeneratePanel(); }; /////////////////////////////////////////////////////////////////////////////// /// Class ModelTreePanel /////////////////////////////////////////////////////////////////////////////// class ModelTreePanel : public wxPanel { private: protected: wxSplitterWindow* m_mainSplitter; wxPanel* m_treePanel; wxTreeCtrl* m_modelTreeCtrl; wxPanel* m_detailPanel; wxNotebook* m_detailNotebook; // Virtual event handlers, overide them in your derived class virtual void OnTreeDeleteItem( wxTreeEvent& event ){ event.Skip(); } virtual void OnTreeItemActivated( wxTreeEvent& event ){ event.Skip(); } virtual void OnTreeItemGetTooltip( wxTreeEvent& event ){ event.Skip(); } virtual void OnTreeItemMenu( wxTreeEvent& event ){ event.Skip(); } virtual void OnTreeSelChanged( wxTreeEvent& event ){ event.Skip(); } virtual void OnTreeSelChanging( wxTreeEvent& event ){ event.Skip(); } public: ModelTreePanel( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 642,547 ), long style = wxTAB_TRAVERSAL ); ~ModelTreePanel(); void m_mainSplitterOnIdle( wxIdleEvent& ) { m_mainSplitter->SetSashPosition( 0 ); m_mainSplitter->Disconnect( wxEVT_IDLE, wxIdleEventHandler( ModelTreePanel::m_mainSplitterOnIdle ), NULL, this ); } }; } // namespace ui #endif //__ui__
[ [ [ 1, 232 ] ] ]
f634057d2569ccefd853a71ba6bba42146040eb1
3d7d8969d540b99a1e53e00c8690e32e4d155749
/EngSrc/IEImageDecoder.cpp
f698e0e74f9e089ce730ae34e52e235618d4e39f
[]
no_license
SymbianSource/oss.FCL.sf.incubator.photobrowser
50c4ea7142102068f33fc62e36baab9d14f348f9
818b5857895d2153c4cdd653eb0e10ba6477316f
refs/heads/master
2021-01-11T02:45:51.269916
2010-10-15T01:18:29
2010-10-15T01:18:29
70,931,013
0
0
null
null
null
null
UTF-8
C++
false
false
4,468
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "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: Juha Kauppinen, Mika Hokkanen * * Description: Photo Browser * */ // Include files #include "IEImageDecoder.h" // ========================== MEMBER FUNCTIONS ============================= // CIEImageDecoder* CIEImageDecoder::NewL(RFs& aFileServer, MDecodingObserver& aObserver) { CIEImageDecoder* self = new (ELeave) CIEImageDecoder(aFileServer, aObserver); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(); return self; } CIEImageDecoder::~CIEImageDecoder() { if(iImageDecoder) { delete iImageDecoder; iImageDecoder = NULL; } if(iExtImageDecoder) { delete iExtImageDecoder; iExtImageDecoder = NULL; } if(iVisualFrame) { delete iVisualFrame; iVisualFrame = NULL; } } //EPriorityIdle, EPriorityLow, EPriorityStandard, EPriorityUserInput, EPriorityHigh CIEImageDecoder::CIEImageDecoder(RFs& aFileServer, MDecodingObserver& aObserver) : CActive(EPriorityStandard), iFileServer(aFileServer), iObserver(aObserver), iSrcPtr(NULL, 0, 0) { } void CIEImageDecoder::ConstructL() { CActiveScheduler::Add(this); iDecoderBusy = EFalse; iDecode2Yuv = EFalse; iDecode2Bitmap = EFalse; iNumOfBitmaps = 0; } void CIEImageDecoder::RunL() { TPtr8 ptr = iVisualFrame->DataPtrL(); TInt dataSize = ptr.Size(); TUint8* bufU = (TUint8*) ptr.Ptr(); if(iDecode2Yuv) { iDecode2Yuv = EFalse; //iObserver.YuvImageReadyL(iStatus.Int()); } if(iDecode2Bitmap) { iDecode2Bitmap = EFalse; iObserver.BitmapReadyL(iStatus.Int()); } iDecoderBusy = EFalse; } void CIEImageDecoder::DoCancel() { } void CIEImageDecoder::GetImageSizeL(const TFileName aFileName, TSize& aSize) { if(iImageDecoder) { delete iImageDecoder; iImageDecoder = NULL; } iImageDecoder = CImageDecoder::FileNewL(iFileServer, aFileName); TFrameInfo frameInfo = iImageDecoder->FrameInfo(); aSize.iWidth = frameInfo.iOverallSizeInPixels.iWidth; aSize.iHeight = frameInfo.iOverallSizeInPixels.iHeight; delete iImageDecoder; iImageDecoder = NULL; } void CIEImageDecoder::ConvertJpeg2YuvL(const TDesC& aSourceFile, HBufC8& aBuffer, const TImageForamt /*aImageFormat*/) { TInt fileSize = 0; TInt blocks = 0; iDecoderBusy = ETrue; iDecode2Yuv = ETrue; if(iExtImageDecoder) { delete iExtImageDecoder; iExtImageDecoder = NULL; } iExtImageDecoder = CExtJpegDecoder::FileNewL(iFileServer, aSourceFile); TFrameInfo frameInfo = iExtImageDecoder->FrameInfo(); TInt width = frameInfo.iOverallSizeInPixels.iWidth; TInt height = frameInfo.iOverallSizeInPixels.iHeight; /*if(width%2 != 0) width++; if(height%2 != 0) height++;*/ TPtr8 bufPtr = aBuffer.Des(); iBufU = (TUint8*)bufPtr.Ptr(); if(iVisualFrame) { delete iVisualFrame; iVisualFrame = NULL; } iVisualFrame = CVisualFrame::NewL(bufPtr, TSize(width, height), CVisualFrame::EFormatYUV420Planar); iExtImageDecoder->ConvertL(&iStatus, iVisualFrame, blocks); if(!IsActive()) SetActive(); } void CIEImageDecoder::ConvertJpeg2BitmapL(CFbsBitmap& aDestBitmap, TDesC8& aSourceData) { TInt frameNumber = 0; iDecoderBusy = ETrue; iDecode2Bitmap = ETrue; TInt dataSize = aSourceData.Size(); iSrcPtr.Set((TUint8*)aSourceData.Ptr(), aSourceData.Size(), aSourceData.Size()); if(iImageDecoder) { delete iImageDecoder; iImageDecoder = NULL; } iImageDecoder = CImageDecoder::DataNewL(iFileServer, iSrcPtr); iImageDecoder->Convert(&iStatus, aDestBitmap, frameNumber); iNumOfBitmaps++; if(!IsActive()) SetActive(); } TPtr8 CIEImageDecoder::GetVisualFrame() { return iVisualFrame->DataPtrL(); } void CIEImageDecoder::CancelDecoding() { if(iDecoderBusy) { if(iImageDecoder) iImageDecoder->Cancel(); if(iExtImageDecoder) iExtImageDecoder->Cancel(); } if(IsActive()) Cancel(); } // EOF
[ "none@none" ]
[ [ [ 1, 214 ] ] ]
8008652bddd9e65634d2e6509a03da63e3139864
2b80036db6f86012afcc7bc55431355fc3234058
/docs/core/examples/lists_implementation.cpp
a27571e0d9d5d884b182540d6149e6b3b2db7478
[ "BSD-3-Clause" ]
permissive
leezhongshan/musikcube
d1e09cf263854bb16acbde707cb6c18b09a0189f
e7ca6a5515a5f5e8e499bbdd158e5cb406fda948
refs/heads/master
2021-01-15T11:45:29.512171
2011-02-25T14:09:21
2011-02-25T14:09:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,471
cpp
// test_project.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <core/Library/LocalDB.h> #include <core/Query/Lists.h> #include <core/MetadataValue.h> // The GenreListWindow is an example class that represent // the visual list of genres class GenreListWindow : public sigslot::has_slots<> { public: // The list should contain a vector to store the MetadataValues musik::core::MetadataValueVector genres; // The callback method when artists are retrieved void OnGernes(musik::core::MetadataValueVector *newGenres,bool clear); GenreListWindow(); void SelectGenre(int position); }; // The ArtistListWindow is an example class that represent // the visual list of artists class ArtistListWindow : public sigslot::has_slots<> { public: // The list should contain a vector to store the MetadataValues musik::core::MetadataValueVector artists; // The callback method when artists are retrieved void OnArtists(musik::core::MetadataValueVector *newArtists,bool clear); ArtistListWindow(); void SelectArtist(int position); }; // The ViewWindow is an example of a view that contain // a genre list, a artist list and a list of tracks (not yet) class ViewWindow{ public: // The view has only one query, the Query::Lists musik::core::Query::Lists listQuery; GenreListWindow genreWindow; ArtistListWindow artistWindow; void SendQuery(); }; // For the ease of the example, we make the library and the view (ViewWindow) global musik::core::Library::LocalDB library; ViewWindow view; ///////////////////////////////////////////////////////////// // Constructing the GenreListWindow GenreListWindow::GenreListWindow(){ // The constructor in this example connects the slots to the query view.listQuery.OnMetadataEvent("genre").connect(this,&GenreListWindow::OnGernes); } ArtistListWindow::ArtistListWindow(){ // The constructor in this example connects the slots to the query view.listQuery.OnMetadataEvent("artist").connect(this,&ArtistListWindow::OnArtists); } void GenreListWindow::OnGernes(musik::core::MetadataValueVector *newGenres,bool clear){ if(clear){ // If the clear flag is set, erase all genres this->genres.clear(); } // Append the incoming genres. this->genres.insert(this->genres.end(),newGenres->begin(),newGenres->end()); } void ArtistListWindow::OnArtists(musik::core::MetadataValueVector *newArtists,bool clear){ if(clear){ // If the clear flag is set, erase all genres this->artists.clear(); } // Append the incoming artists. this->artists.insert(this->artists.end(),newArtists->begin(),newArtists->end()); } void ViewWindow::SendQuery(){ // In this example I will send the QUERY_WAIT so that the AddQuery // will hold until the query is parsed. This is not the recommended way. See Library::Base::OnQueryQueueStart library.AddQuery(this->listQuery,QUERY_AUTOCALLBACK|QUERY_WAIT); } void GenreListWindow::SelectGenre(int position){ // User selected position in the list // add selection to the query view.listQuery.SelectMetadata("genre",this->genres[position]->id); // should check if this exists first // Send the query to update the other lists view.SendQuery(); } void ArtistListWindow::SelectArtist(int position){ // User selected position in the list // add selection to the query view.listQuery.SelectMetadata("artist",this->artists[position]->id); // should check if this exists first // Send the query to update the other lists view.SendQuery(); } int _tmain(int argc, _TCHAR* argv[]){ // Start by starting up the library library.Startup(); // Send an empty query to the library. // This will make the Query::Lists list all metadata that are connected (genres and artists in this case) view.SendQuery(); // Lets assume that this could be a gui application // I added the SelectArtist and SelectGenre to the lists // to simulate that a user clicks on the genre/artist // Lets assume that the user selects the 3rd position in the genre list view.genreWindow.SelectGenre(3); // This will send the genre to the selection in the query and send the query to the library // Since the metakey "genre" is now selected, the Query::Lists will not query for // genres anymore and the callbacks for artists will only be called. system("PAUSE"); return 0; }
[ "onnerby@6a861d04-ae47-0410-a6da-2d49beace72e" ]
[ [ [ 1, 145 ] ] ]
e66c208302c33cabda76f705d76bd022a1914cc4
dda0d7bb4153bcd98ad5e32e4eac22dc974b8c9d
/tests/stdafx.cpp
3261c2e8ad5e4d93e1ed321f8fb59950f740acbe
[ "BSD-3-Clause" ]
permissive
systembugtj/crash-report
abd45ceedc08419a3465414ad9b3b6a5d6c6729a
205b087e79eb8ed7a9b6a7c9f4ac580707e9cb7e
refs/heads/master
2021-01-19T07:08:04.878028
2011-04-05T04:03:54
2011-04-05T04:03:54
35,228,814
1
0
null
null
null
null
UTF-8
C++
false
false
2,103
cpp
/************************************************************************************* This file is a part of CrashRpt library. CrashRpt is Copyright (c) 2003, Michael Carruth All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************************/ // stdafx.cpp : source file that includes just the standard includes // testapp.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" #if (_ATL_VER < 0x0700) #include <atlimpl.cpp> #endif //(_ATL_VER < 0x0700)
[ "[email protected]@9307afbf-8b4c-5d34-949b-c69a0924eb0b" ]
[ [ [ 1, 41 ] ] ]
4089468419e03048440f550c984f3cf9e672b0a2
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Vehicle/DriverInput/hkpVehicleDriverInput.h
0fd43f20624478cb7a8d5f62a85e0f446f582b1b
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
4,270
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKVEHICLE_DRIVERINPUT_hkVehicleDRIVERINPUT_XML_H #define HKVEHICLE_DRIVERINPUT_hkVehicleDRIVERINPUT_XML_H #include <Common/Base/hkBase.h> class hkpVehicleInstance; /// class hkpVehicleDriverInputStatus : public hkReferencedObject { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_VEHICLE); HK_DECLARE_REFLECTION(); hkpVehicleDriverInputStatus() {} virtual ~hkpVehicleDriverInputStatus() { } // Empty, so that we have a base type ptr (of at least some proper type) // to serialize in and back in again. public: hkpVehicleDriverInputStatus(hkFinishLoadedObjectFlag f) : hkReferencedObject(f) { } /// Clone this input. virtual hkpVehicleDriverInputStatus* clone() const = 0; }; /// This class is an abstraction for the input of a driver to the controls of the /// vehicle. State variables that store the input to the steering wheel, pedals, /// and handbrake that this component calculates are stored in the hkpVehicleInstance. /// Note that this component can be associated with a /// device in the computer (such as a joystick or steering wheel), but can also be /// associated with an AI controller, or a replay sequence. class hkpVehicleDriverInput : public hkReferencedObject { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_VEHICLE); HK_DECLARE_REFLECTION(); /// Container for data output by the driver input calculations. struct FilteredDriverInputOutput { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_VEHICLE, hkpVehicleDriverInput::FilteredDriverInputOutput ); /// The input from the accelerator. hkReal m_acceleratorPedalInput; /// The input from the brake. hkReal m_brakePedalInput; /// The input from the steering wheel. hkReal m_steeringWheelInput; /// Indicates if the handbrake is on. hkBool m_handbrakeOn; /// Indicates that we think the vehicle is trying to reverse. /// /// True if we are not in autoreverse mode, then we are tyring to reverse only /// when the driver hits the Reverse Button. /// /// Otherwise, true if the break has been pressed and we are moving backwards, /// or /// - if we are reversing and moving we keep reversing /// - if we are reversing but stopped we keep reversing if the brake is pressed /// - if we are reversing, stopped and no brake is pressed, we don't reverse any more /// /// Finally, if we are not reversing, we start reversing only if we are stopped and pressing the brake hkBool m_tryingToReverse; }; // // Methods // hkpVehicleDriverInput() {} /// Calculates the effect of the driver's input on the vehicle. virtual void calcDriverInput(const hkReal deltaTime, const hkpVehicleInstance* vehicle, const hkpVehicleDriverInputStatus* deviceStatus, FilteredDriverInputOutput& filteredInputOut) = 0; hkpVehicleDriverInput(hkFinishLoadedObjectFlag flag) : hkReferencedObject(flag) {} }; #endif // HKVEHICLE_DRIVERINPUT_hkVehicleDRIVERINPUT_XML_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 111 ] ] ]
17e6bdef3861939b607ca0f85a22b10ad35cea69
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_void_returns_pass.cpp
bd148c8a389ddb446b916c292815579408354071
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
cpp
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004, // by libs/config/tools/generate // Copyright John Maddock 2002-4. // Use, modification and distribution are 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/libs/config for the most recent version. // Test file for macro BOOST_NO_VOID_RETURNS // This file should compile, if it does not then // BOOST_NO_VOID_RETURNS needs to be defined. // see boost_no_void_returns.ipp for more details // Do not edit this file, it was generated automatically by // ../tools/generate from boost_no_void_returns.ipp on // Sun Jul 25 11:47:49 GMTDT 2004 // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifndef BOOST_NO_VOID_RETURNS #include "boost_no_void_returns.ipp" #else namespace boost_no_void_returns = empty_boost; #endif int main( int, char *[] ) { return boost_no_void_returns::test(); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 39 ] ] ]
4e31b16bd3f5eba09b64c0d9b0a8dcfb043affc1
928b250a42ffbe1d1c1009b4af7fd3f6a1f46266
/forlijia/ForlijiaEx/ForlijiaEx/MatchAddress.h
cb2b7282c5d7e776ce1626f2fafafbfa34d7179b
[]
no_license
jimcoly/comyitian
81044cc6e5d06613e1f2bda8b658457e8337ab8f
6f70e202907be1071d3310bfe1441567ebffed1e
refs/heads/master
2020-05-31T17:54:26.448254
2011-09-01T07:28:07
2011-09-01T07:28:07
33,866,360
0
0
null
null
null
null
UTF-8
C++
false
false
97
h
#pragma once class MatchAddress { public: MatchAddress(void); ~MatchAddress(void); };
[ "sdy63420@3919fc08-f352-11de-9907-777483041811" ]
[ [ [ 1, 8 ] ] ]
5eca8717a4e35f9e33e296e117f2ac9ccc52a59f
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Include/CComboBoxExt.h
37b155af1c259b619098dca567c1ac9425b07216
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
788
h
/* CComboBoxExt.h Classe per il combo con auto-completamento. Luca Piergentili, 08/09/00 [email protected] Tratta da: Autocompleting combo-box, like the URL edit box in netscape, Copyright (c) 1998 by Chris Maunder (modifiche minori). */ #ifndef _CCOMBOBOXEXT_H #define _CCOMBOBOXEXT_H 1 #include "window.h" /* CComboBoxExt */ class CComboBoxExt : public CComboBox { public: CComboBoxExt(); virtual ~CComboBoxExt() {} virtual BOOL PreTranslateMessage (MSG* pMsg); inline void SetNotify (HWND hWndParent,UINT nMsg) {m_hWndParent = hWndParent; m_nMsg = nMsg;} protected: void OnEditUpdate (void); private: HWND m_hWndParent; UINT m_nMsg; BOOL m_bAutoComplete; DECLARE_MESSAGE_MAP() }; #endif // _CCOMBOBOXEXT_H
[ [ [ 1, 38 ] ] ]
52eee2613f64b6958506954797e8c424aab4cb41
01fa2d8a6dead72c3f05e22b9e63942b4422214f
/src/test/foundation/introspection.cpp
9bbd08bbe6c723adb3c2d085c15affdf59066514
[]
no_license
AlekseiCherkes/ttscpp
693f7aac56ae59cf2555b0852eb26a6f96a4dbe3
e3976e6f5e4f5a7923effa95b25c8ba2031ae9f1
refs/heads/master
2021-01-10T20:36:58.267873
2011-12-17T10:00:24
2011-12-17T10:00:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
479
cpp
#include "gtest.hpp" #include "foundation/introspection.hpp" //-------------------------------------------------------------------------------------------------- //using namespace testing; //using namespace tts::engine; //-------------------------------------------------------------------------------------------------- TEST(Introspection, Test1) { } //--------------------------------------------------------------------------------------------------
[ [ [ 1, 18 ] ] ]
9c3b5710bb90acea1cdb4a05eb74b54f61d60390
1caba14ec096b36815b587f719dda8c963d60134
/tags/start/smx/libsmx/qscgi.cpp
b73eb84fcff7da67314ac18d66a70bbf37a6f501
[]
no_license
BackupTheBerlios/smx-svn
0502dff1e494cffeb1c4a79ae8eaa5db647e5056
7955bd611e88b76851987338b12e47a97a327eaf
refs/heads/master
2021-01-10T19:54:39.450497
2009-03-01T12:24:56
2009-03-01T12:24:56
40,749,397
0
0
null
null
null
null
UTF-8
C++
false
false
3,231
cpp
// psmx.cpp : Defines the entry point for the console application. // #ifdef unix #define NO_LOAD_SCHED #endif #define NO_LOAD_TSET #include "stdafx.h" #include "qstr.h" #include "qobj.h" #include "qctx.h" #include "opt.h" #include "libs.h" #include "qscgi.h" int main(int argc, char* argv[], char* envp[]) { // Declare the variables needed setarg(&argc, argv); if (argc > 1) { qCtxTmp global((qCtx *)NULL); qEnvCGI env(NULL, stdout, 1024); global.SetEnv(&env); global.MapArgv(argc, argv, "arg"); global.MapObj(argc, "num-args"); LoadAllLibs(&global); qCtxTmp ctx(&global); env.SetSessionCtx(&ctx); char *p_opt; while ((p_opt = getopt("m*odule"))) { ctx.Eval("module", p_opt); } if (getoptbool("e*xpand")) { CStr toParse = argv[1]; int i; for (i = 2; i < argc; ++i) { toParse << ' ' << argv[i]; } qStrReadBuf in(toParse); ctx.ParseTry(&in, &env); } else { bool cgi = getoptbool("c*gi") != 0; bool path = getoptbool("p*ath") != 0; CStr file = argv[1]; if (path) { char *fp; SearchPath( NULL, // search path argv[1], // file name ".cmd", // file extension MAX_PATH, // size of buffer file.Grow(MAX_PATH).GetBuffer(), // found file name buffer &fp // file component ); } FILE *fp = fopen(file, "r"); if (fp) { qEnvCGI env(fp, stdout, 1024); ctx.SetEnv(&env); env.SetSessionCtx(&ctx); char *p_opt; while ((p_opt = getopt("m*odule"))) { ctx.Eval("module", p_opt); } if (cgi) { ctx.ParseTry(&env, env.GetBuf()); env.PutS("Content-length: "); env.PutN(env.GetBuf()->Length()); env.PutS("\n\n"); env.PutS(*env.GetBuf()); } else { ctx.ParseTry(&env, &env); } fclose(fp); } } ctx.Clear(); global.Clear(); #ifdef unix if (isatty(1)) { fflush(stdout); write(1, "\n", 1); } #endif } else { printf("USAGE : psx [-c*gi] <\"file\"> : expand file [optionally with http headers]\n" " psx -e*xpand <\"macro\"> : expand macro inline, output to stdout\n" ); } return 0; } #ifndef linux #include "shlwapi.h" #endif qEnvCGI::qEnvCGI(FILE *script, FILE *out, int newBufSize) { myIn = script; myOut = out; myBufSize = newBufSize; } CStr qEnvCGI::GetHeader(const char *name) { CStr buf = name; char *p = buf.GetBuffer(); if (p) { while (*p) { if (*p == '-') *p = '_'; else *p = toupper(*p); ++p; } const char *env = getenv(strupr(buf.GetBuffer())); return CStr(env); } else { return 0; } } CStr qEnvCGI::MapFullPath(const char *path) { CStr path1 = GetHeader("PATH_TRANSLATED"); CStr path2 = path; path1.RTrim(); CStr path3(path1.Length()+path2.Length()+1); PathCombine(path3.GetBuffer(),path1,path2); path1.Grow(path3.Length()); PathCanonicalize(path1.GetBuffer(),path3.GetBuffer()); PathMakePretty(path1.GetBuffer()); path1.Shrink(); return path1; } bool qEnvCGI::Flush() { // todo : rebind stream to context parser return false; }
[ "(no author)@407f561b-fe63-0410-8234-8332a1beff53" ]
[ [ [ 1, 157 ] ] ]
84007c2f2ab34692848f1538117d0997a8cf8fcc
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/AccountServer/BillingMgrJP2.cpp
64240dc827de1122ced188e2a69d5ef28793baf1
[]
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
4,234
cpp
#include "stdafx.h" #include "BillingMgrJP2.h" #include "MsgHdr.h" #include "account.h" #include "DBManager.h" #include "dpsrvr.h" #include "dpdbsrvr.h" extern CAccountMng g_AccountMng; extern CDbManager g_DbManager; extern CDPSrvr g_dpSrvr; extern CDPDBSrvr g_dpDbSrvr; /////////////////////////////////////////////////////////////////////// // CBillingMgrJP2 /////////////////////////////////////////////////////////////////////// CBillingMgrJP2::CBillingMgrJP2() { m_iBillingFreePass = 0; } CBillingMgrJP2::~CBillingMgrJP2() { } BOOL CBillingMgrJP2::SetConfig( BILLING_ENUM id, DWORD data ) { switch( id ) { case BID_FREEPASS: m_iBillingFreePass = (int)data; break; } return TRUE; } // 초기화: 빌링 서버와의 연결 객체를 할당해 둔다. bool CBillingMgrJP2::Init( HWND hWnd ) { ::SetTimer( hWnd, IDT_KICKOUT, 1000 * 60, NULL ); return true; } // 할당된 자원을 반납한다. void CBillingMgrJP2::Release() { safe_delete( this ); } // 빌링정보를 검사한다. BYTE CBillingMgrJP2::CheckAccount( int nType, DWORD dwKey, const char* szAccount, const char* szAddr ) { if( nType != m_iBillingFreePass ) // 무료유저? { // 유료유저는 디비에 쿼리 g_DbManager.PostBillingQuery( szAccount, dwKey, 1 ); return ACCOUNT_BILLING_WAIT_ACK; } else { // 무료유저는 TRACE char szTrace[1024]; sprintf( szTrace, "FreePass - Account:%s fCheck:%d", szAccount, nType ); OutputDebugString( szTrace ); return ACCOUNT_CHECK_OK; } } // 빌링에 관련된 윈도우 메세지가 처리되게 한다. BOOL CBillingMgrJP2::PreTranslateMessage( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { switch( message ) { case WM_TIMER: { switch( wParam ) { case IDT_KICKOUT: g_AccountMng.KickOutCheck(); return TRUE; } } break; } return FALSE; } // void CBillingMgrJP2::OnTimer( CAccount* pAccount ) { if( pAccount->m_fCheck == m_iBillingFreePass ) // 무료사용자 skip return; CTime tm = 0; if( pAccount->m_TimeOverDays == tm ) // login 미처리자 or timeover skip return; CTime cur = CTime::GetCurrentTime(); if( pAccount->m_TimeOverDays <= cur ) // timerover 처리 { pAccount->m_TimeOverDays = 0; g_dpSrvr.CloseExistingConnection( pAccount->m_lpszAccount, ERROR_BILLING_TIME_OVER ); } else { // 남은 시간 통지 CTimeSpan ts = pAccount->m_TimeOverDays - cur; if ( ts.GetTotalMinutes() >= 59 && ts.GetTotalMinutes() <= 61 && pAccount->m_nStatus != ACCOUNT_STATUS_NOTIFIED && pAccount->m_fRoute == TRUE ) { pAccount->m_nStatus = ACCOUNT_STATUS_NOTIFIED; g_dpDbSrvr.SendOneHourNotify( pAccount ); // TRANS에 보낸다. } } } // sp 리턴값 설명: // fError(결과),fText(결과를 문자열로),fTime(endday까지의시간을 초로) // 예: 0,OK,540530 void CBillingMgrJP2::OnDBQuery( CQuery& query, tagDB_OVERLAPPED_PLUS* pOV ) { long lResult = SUCCESS; CTime endDay = CTime::GetCurrentTime(); sprintf( pOV->szQuery, "BILLING_STR '%s'", pOV->szAccount ); #if defined(_DEBUG) CTimeSpan timeSpan( 2, 0, 0, 0 ); endDay += timeSpan; #else if( query.Exec( pOV->szQuery ) ) { if( query.Fetch() ) { int fError = query.GetInt( "fError" ); switch( fError ) { case 0: { int nSecs = query.GetInt( "fTime" ); CTimeSpan timeSpan( 0, 0, 0, nSecs ); endDay += timeSpan; lResult = SUCCESS; } break; case 1: lResult = TIME_OVER; break; case 2: lResult = BILLING_INFO_FAILED; break; default: lResult = OTHER_ERROR; break; } } else { lResult = BILLING_INFO_FAILED; } } else { lResult = DATABASE_ERROR; WriteLog( "%s, %d\r\n\t%s", __FILE__, __LINE__, pOV->szQuery ); } #endif BILLING_INFO result; result.szAccount = pOV->szAccount; result.dwKey = pOV->dwKey; result.lResult = lResult; result.pTimeOverDays = &endDay; // endDay는 lResult가 SUCCESS인 경우에만 설정되면 된다. g_AccountMng.SendBillingResult( &result ); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 180 ] ] ]
77a1e498748f62921a14feaf87b0320132200d89
df2224596a6b24f9a320fc8313c0ed6f161970db
/HapticDevice.h
345022c964111095546e965a9aca824e296cd1b2
[]
no_license
arnaringib/uni-iceland-haptic
d38f463c3c15792a6184f1136670eeb5edd787c2
57ac9d79a15d4da53082d3504b1f99457604bbaa
refs/heads/master
2021-01-01T16:25:08.104447
2010-05-20T21:20:18
2010-05-20T21:20:18
32,108,051
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,094
h
// // Þessi klasi sér um alla virkni stafsins // getur tekið alla þá stafi sem virka með H3D. // #ifndef _HATPICDEVICE_H #define _HATPICDEVICE_H #include <H3D/X3D.h> #include <H3D/DeviceInfo.h> #include <H3D/H3DHapticsDevice.h> #include <H3D/AnyDevice.h> #include <H3D/HapticsRenderers.h> using namespace std; using namespace H3D; class HapticDevice{ public: HapticDevice(); ~HapticDevice(); // Notkun: hdevice->setupDevice(); // Fyrir: hdevice er bendir á HapticDevice hlut, // og stafur er tengdur við tölvuna. // Eftir: Búið er tengjast stafnum void setupDevice(); // Notkun: hdevice->enableDevice(); // Fyrir: hdevice er bendir á HapticDevice hlut, // og búið að tengjast stafnum. // Eftir: Búið er að virka stafinn. void enableDevice(); // Notkun: hdevice->disableDevice(); // Fyrir: hdevice er bendir á HapticDevice hlut, // og búið að virkja stafinn. // Eftir: Búið er að af virkja stafinn. void disableDevice(); // Notkun: err = hdevice->getLastErrorMsg(); // Fyrir: hdevice er bendir á HapticDevice hlut, // err er string. // Eftir: err inniheldur síðasta villuboði // frá stafnum. string &getLastErrorMsg(); // Notkun: en = hdevice->enabled(); // Fyrir: hdevice er bendir á HapticDevice hlut, // en er bool. // Eftir: en er satt ef og aðeins ef // stafurinn er virkur, annars ósatt. bool enabled(); // Notkun: hdevice->setPosition(position); // Fyrir: hdevice er bendir á HapticDevice hlut, // position er Vec3f. // Eftir: stafurinn er stilltur á position hnit. void setPosition(const Vec3f &position); // Notkun: node = hdevice->getNode(); // Fyrir: hdevice er bendir á HapticDevice hlut, // node er Node hlutur. // Eftir: node inniheldur HapticDevice hnút. Node* getNode(void); private: AutoRef< Node > deviceSetup; string deviceinfo_string; bool enable; string lastErrorMsg; DeviceInfo *di; H3DHapticsDevice *hdev; }; #endif
[ "arnaringib@cfee87e8-01ee-11df-bfb3-7781b9cb07ea" ]
[ [ [ 1, 76 ] ] ]
9f45961f1062129a3fd2e75f8817711b60c9113e
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/VisualizationContainer.h
eed8278cc61a761298f9dd3e049d4600c971c0a3
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
1,977
h
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * 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, 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 GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #ifndef _CVisualizationContainer_h_ #define _CVisualizationContainer_h_ #pragma once //#include "IVisualizationContainer.h" class MediaPlayer; class CVisualizationContainer:public CWnd { public: CVisualizationContainer(): m_pMediaPlayer(NULL), m_WaitToStopVis(0), m_windowStyle(0), m_windowExStyle(0), m_windowParent(0), m_bFullScreen(FALSE) {} virtual ~CVisualizationContainer(); virtual void SetMediaPlayer(MediaPlayer* pPlayer); private: afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnTimer(UINT_PTR nIDEvent); DECLARE_MESSAGE_MAP() void UpdateVisualization(); private: BOOL SetFullScreen(BOOL bFullScreen); MediaPlayer* m_pMediaPlayer; INT m_WaitToStopVis; BOOL m_bFullScreen; DWORD m_windowStyle; DWORD m_windowExStyle; CWnd* m_windowParent; CRect m_rcWindow; protected: virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); public: afx_msg void OnDestroy(); }; #endif
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 69 ] ] ]
97b73843a15fbdb95f6ae6b08c96f90bf97e412a
fcdb20ca7772fef4526583876070977a2db17fe1
/classes/Player.cpp
6924e068629a45fba28c30cd089e162d81cb7fcb
[]
no_license
brosner/college-monopoly
ef3e286d3da52b3502a216746ccc0ba6e6d042cc
18722337b20461835046860a089ea4dd59a3a3ab
refs/heads/master
2020-04-14T03:04:01.432659
2010-10-16T21:26:01
2010-10-16T21:26:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,496
cpp
#include "Player.h" Player::Player() { this->playerInit(); } Player::Player(std::string sName) { this->playerInit(); this->setPlayerName(sName); } Player::Player(std::string sName,Space **startPos) { this->playerInit(); this->setPlayerName(sName); this->setCurrSpace(startPos); } Player::~Player() { } std::string Player::getPlayerName() { return this->sPlayerName; } void Player::setPlayerName(std::string sName) { this->sPlayerName = sName; } /** * getCash() returns how much money * this player owns. */ int Player::getCash() { return this->iCash; } /** * addCash() will add iAmount to the * player's total cash flow. */ void Player::addCash(int iAmount) { this->iCash += iAmount; } /** * takeCash() will substract iAmount of * the player's cash flow. */ void Player::takeCash(int iAmount) { this->iCash -= iAmount; } Space ** Player::getCurrSpace() { return this->currSpace; } void Player::setCurrSpace(Space **space) { this->currSpace = space; } /** * getStrategy() will return the player's * investment strategy. */ int Player::getStrategy() { return this->iStrategy; } /** * setStrategy() will set the player's * investment strategy to iStrategy. */ void Player::setStrategy(int iStrategy) { if(iStrategy == 0) { __int64 seed; QueryPerformanceCounter((LARGE_INTEGER *)&seed); srand((unsigned int)seed); iStrategy = (rand() % 3) + 1; } this->iStrategy = iStrategy; }
[ [ [ 1, 84 ] ] ]
3cb1a12fe7d7564a08d3683959fb3cb4eee4fc48
efc8e21a70b1b561152cf451cb01b2816d2bed49
/examples/3DCellSegmentation/LevelSetBasedCellSegmentation/LevelSetBasedCellSegmentation.cxx
fc6b05e32d87de3350fc2a0687e4cd606e784a4c
[]
no_license
xiaochengcike/midas-journal-321
250fa5a1267e48ae3651557c8cb9039db1b09c2e
104bc2cc86967b5af96449000336d58e809b95ea
refs/heads/master
2020-03-31T15:57:50.135005
2011-08-22T13:23:47
2011-08-22T13:23:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,091
cxx
#include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkLevelSetBasedCellSegmentation.h" #include "itkCastImageFilter.h" #include <map> #include <fstream> #include <stdio.h> int main( int argc, char* argv[] ) { if( argc < 4 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " featureImage seedfile cellSegmentImage" << std::endl; return EXIT_FAILURE; } const unsigned int Dimension = 3; typedef itk::Image< unsigned short, Dimension > CompImage; typedef itk::Image< float, Dimension > FeatureImage; typedef itk::ImageFileReader< FeatureImage > ReaderType; typedef itk::ImageFileWriter< CompImage > WriterType; typedef itk::LevelSetBasedCellSegmentation< FeatureImage,CompImage > FilterType; ReaderType::Pointer reader_feature = ReaderType::New(); reader_feature->SetFileName( argv[1] ); reader_feature->Update(); FeatureImage::Pointer featureImg = reader_feature->GetOutput(); typedef FeatureImage::IndexType ImageIndexType; ImageIndexType idx; float val; FilterType::Pointer filter = FilterType::New(); filter->SetInput( featureImg ); filter->SetLargestCellRadius( 8.0 ); // in real coordinates filter->SetSeedValue( 2.0 ); filter->SetIterations( 500 ); filter->SetPropagationScaling( 3 ); filter->SetCurvatureScaling( 1 ); filter->SetAdvectionScaling( 3 ); filter->SetMaxRMSChange( 0.001 ); std::fstream infile; infile.open(argv[2],std::ios::in); while( !infile.eof() ) { infile >> val; for( unsigned int i = 0; i < Dimension; i++) { infile >> idx[i]; } filter->seeds[val] = static_cast<ImageIndexType>( idx ); } infile.close(); filter->Update(); WriterType::Pointer writer = WriterType::New(); writer->SetInput( filter->GetOutput() ); writer->SetFileName( argv[3] ); try { writer->Update(); } catch ( itk::ExceptionObject e ) { std::cerr << "Error: " << e << std::endl; } return EXIT_SUCCESS; }
[ [ [ 1, 76 ] ] ]
1ef401ba7316e143a3edb4177ac8594032b37059
8a223ca4416c60f4ad302bc045a182af8b07c2a5
/Orders-ListeningFakeProblem-Cpp/Support-GTest-Cpp/include/ILStringUtils.h
9185043f0a99a96bed525e6773db40432e54d336
[ "BSD-3-Clause" ]
permissive
sinojelly/sinojelly
8a773afd0fcbae73b1552a217ed9cee68fc48624
ee40852647c6a474a7add8efb22eb763a3be12ff
refs/heads/master
2016-09-06T18:13:28.796998
2010-03-06T13:22:12
2010-03-06T13:22:12
33,052,404
0
0
null
null
null
null
UTF-8
C++
false
false
3,181
h
/// *************************************************************************** /// Copyright (c) 2009, Industrial Logic, Inc., All Rights Reserved. /// /// This code is the exclusive property of Industrial Logic, Inc. It may ONLY be /// used by students during Industrial Logic's workshops or by individuals /// who are being coached by Industrial Logic on a project. /// /// This code may NOT be copied or used for any other purpose without the prior /// written consent of Industrial Logic, Inc. /// **************************************************************************** #ifndef STRING_UTILS_H_ #define STRING_UTILS_H_ #include <string> #include <cstring> namespace IL { inline bool stringEndsWith(const std::string& stringToSearch, const std::string& searchData) { return stringToSearch.rfind(searchData) == stringToSearch.length() - searchData.length(); } inline bool stringBeginsWith(const std::string& stringToSearch, const std::string& searchData) { return stringToSearch.find(searchData) == 0; } inline bool stringContains(const std::string& stringToSearch, const std::string& searchData) { return stringToSearch.find(searchData) != std::string::npos; } inline std::string stringUpperCase(const std::string& inString) { std::string result; for (std::string::size_type i = 0; i < inString.length(); i++) if (inString[i] >= 'a' && inString[i] <= 'z') result += inString[i] + 'A' - 'a'; else result += inString[i]; return result; } inline bool stringEndsWithCaseInsensitive(const std::string& stringToSearch, const std::string& searchData) { return stringUpperCase(stringToSearch).rfind(stringUpperCase(searchData)) != std::string::npos; } inline std::string numToString(int i) { char buffer[88]; sprintf(buffer, "%d", i); return std::string(buffer); } inline bool argvContains(int argc, char * argv[], const std::string& searchString) { for (int i = 0; i < argc; i++ ) if (std::string(argv[i]) == searchString) return true; return false; } inline std::string trimSpaces(const std::string str) { std::string result = str; size_t firstNonSpace = result.find_first_not_of(" \t"); if (firstNonSpace != std::string::npos) result.erase(0, firstNonSpace); size_t lastNonSpace = result.find_last_not_of(" \t"); if (lastNonSpace != std::string::npos) result.erase(lastNonSpace + 1); else result.clear(); return result; } inline std::string removeStringPrefix(const std::string& prefix, const std::string& operand) { if (prefix.length() == 0 || operand.length() == 0) return operand; size_t pos = operand.find(prefix); if (pos != 0) return operand; std::string result = operand; result.erase(0, prefix.length()); return result; } inline std::string removeStringSuffix(const std::string& suffix, const std::string& operand) { if (suffix.length() == 0 || operand.length() == 0) return operand; size_t pos = operand.rfind(suffix); if (pos != operand.length() - suffix.length()) return operand; std::string result = operand; result.erase(pos); return result; } } // namespace IL #endif
[ "chenguodong@localhost" ]
[ [ [ 1, 114 ] ] ]
be0fc76eee3b2a055c3588ffcd797cc984f8ffa1
ee4944add70cdbac9fa6c18a9760a03859a4a3ef
/source/main.cpp
662496fc923678b67eca7e35636f73419c83e799
[]
no_license
Megazig/CustomSystemMenu
5d7bf86f1df6b0c1a105f7e4c773b000bf31ab9d
eec35f44d33e7bbf234867e2dfbe76186537a8e4
refs/heads/master
2021-01-24T06:41:18.274616
2009-08-16T03:08:26
2009-08-16T03:08:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
50,591
cpp
/* Wii System Menu Replacement */ #include "../GRRLIB/GRRLIB/GRRLIB.h" #include "../GRRLIB/GRRLIB/GRRLIB_addon.h" //#include "../ftp/ftpii.c" #include <stdlib.h> #include <wiiuse/wpad.h> #include <fat.h> #include <gccore.h> #include <stdio.h> #include <math.h> #include <string.h> #include <mxml.h> #include <sys/dir.h> #include <dirent.h> #include <asndlib.h> #include <mp3player.h> #include <gcmodplay.h> //#include "dol_launcher.h" char Current_Directory[255], Skin_Directory[255]; GRRLIB_texImg *Spr_BlankChannel, *Spr_SelectedChannel, *Spr_Font, *Spr_MaskChannel; float view_xview, view_yview, view_hspeed, view_xview_to; int Snd_MainMenu, Snd_Startup, FOCUS; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Functions // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool file_exists(char *filename) { FILE *tmpFile; tmpFile = fopen(filename,"r"); if (tmpFile == NULL) { fclose(tmpFile); return false; } else { fclose(tmpFile); return true; } }; void Load_Configuaration() { } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Controls // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PlayerPad { public: int X, Y, Channel, Rumble_Time; float Angle; u32 PadDown,PadHeld; ir_t IR; orient_t OR; GRRLIB_texImg *Spr_Pointer; bool WPAD_POWER; PlayerPad(int WPAD_CHANNEL, const char *Image) { Spr_Pointer = GRRLIB_LoadTextureFromFile(Image); Channel = WPAD_CHANNEL; Rumble_Time=0; WPAD_POWER = false; }; ~PlayerPad() { GRRLIB_FreeTexture(Spr_Pointer); }; void Update() { WPAD_SetVRes(0, 640,480); WPAD_ScanPads(); WPAD_IR(Channel, &IR); WPAD_Orientation(Channel, &OR); X=IR.sx-200; Y=IR.sy-250; Angle=OR.roll; PadDown = WPAD_ButtonsDown(0); PadHeld = WPAD_ButtonsHeld(0); GRRLIB_DrawImg(X-40, Y-40, Spr_Pointer, Angle, 1, 1, 0x10101040 ); GRRLIB_DrawImg(X-48, Y-48, Spr_Pointer, Angle, 1, 1, 0xFFFFFFFF ); if (Rumble_Time > 1) { WPAD_Rumble(Channel, 1); Rumble_Time -= 1; } else WPAD_Rumble(Channel, 0); }; int GetX() {return X;} int GetY() {return Y;} }; PlayerPad *PlayerOne; PlayerPad *PlayerTwo; PlayerPad *PlayerThree; PlayerPad *PlayerFour; void PowerBttn(s32 chan) { if (chan==0) PlayerOne->WPAD_POWER = true; if (chan==1) PlayerOne->WPAD_POWER = true; if (chan==2) PlayerOne->WPAD_POWER = true; if (chan==3) PlayerOne->WPAD_POWER = true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // GUI System // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class GUI_System { public: GRRLIB_texImg *Spr_ButtonLeft, *Spr_ButtonRight, *Spr_ButtonCenter, *Spr_MessageBox, *Spr_WindowTopLeft, *Spr_WindowTopCenter, *Spr_WindowTopRight, *Spr_WindowCenterLeft, *Spr_WindowCenter, *Spr_WindowCenterRight, *Spr_WindowBottomLeft, *Spr_WindowBottomCenter, *Spr_WindowBottomRight; bool Debug; char DebugLog[255]; int Line, Line_Position; FILE *DebugLogFile; GUI_System() { Spr_ButtonLeft = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/ButtonLeft.png"); Spr_ButtonRight = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/ButtonRight.png"); Spr_ButtonCenter = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/ButtonCenter.png"); Spr_WindowTopLeft = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/WindowTopLeft.png"); Spr_WindowTopRight = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/WindowTopRight.png"); Spr_WindowTopCenter = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/WindowTopCenter.png"); Spr_WindowCenterLeft = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/WindowCenterLeft.png"); Spr_WindowCenterRight = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/WindowCenterRight.png"); Spr_WindowCenter = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/WindowCenter.png"); Spr_WindowBottomLeft = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/WindowBottomLeft.png"); Spr_WindowBottomRight = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/WindowBottomRight.png"); Spr_WindowBottomCenter = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/WindowBottomCenter.png"); Spr_MessageBox = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/MessageBox.png"); Spr_Font = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/FONT.png"); GRRLIB_InitTileSet( Spr_Font, 8, 16, 32 ); Line = 0; Line_Position = 0; PlayerOne->Update(); Debug=true; DebugLogFile = fopen("SYS/ErrorLog.txt","w"); fputs ("// Log File For Riiplacemy System Menu \r\n", DebugLogFile); }; ~GUI_System() { if (Debug == true) fclose(DebugLogFile); GRRLIB_FreeTexture(Spr_ButtonLeft); GRRLIB_FreeTexture(Spr_ButtonRight); GRRLIB_FreeTexture(Spr_ButtonCenter); GRRLIB_FreeTexture(Spr_MessageBox); GRRLIB_FreeTexture(Spr_WindowTopLeft); GRRLIB_FreeTexture(Spr_WindowTopCenter); GRRLIB_FreeTexture(Spr_WindowTopRight); GRRLIB_FreeTexture(Spr_WindowCenterLeft); GRRLIB_FreeTexture(Spr_WindowCenter); GRRLIB_FreeTexture(Spr_WindowCenterRight); GRRLIB_FreeTexture(Spr_WindowBottomLeft); GRRLIB_FreeTexture(Spr_WindowBottomCenter); GRRLIB_FreeTexture(Spr_WindowBottomRight); }; void Step() { }; bool ButtonRumble; bool DrawButton(int X, int Y, int Width) { unsigned int BX=X; if (PlayerOne->X > X && PlayerOne->Y > Y && PlayerOne->X < X+Width && PlayerOne->Y < (int)(Y+Spr_ButtonLeft->h)) { if (ButtonRumble == false) { ButtonRumble = true; PlayerOne->Rumble_Time = 10; }; GRRLIB_DrawImg(X-(Spr_ButtonLeft->w*0.2), Y-(Spr_ButtonLeft->h*0.1), Spr_ButtonLeft, 0, 1.2, 1.2, 0xFFFFFFFF ); for(BX=X+(Spr_ButtonLeft->w); BX<X+Width-(Spr_ButtonCenter->w*1.2); BX+=(Spr_ButtonCenter->w*1.2)) GRRLIB_DrawImg(BX, Y-(Spr_ButtonCenter->h*0.1), Spr_ButtonCenter, 0, 1.2, 1.2, 0xFFFFFFFF ); GRRLIB_DrawImg(BX, Y-(Spr_ButtonRight->h*0.1), Spr_ButtonRight, 0, 1.2, 1.2, 0xFFFFFFFF ); if (PlayerOne->PadDown & WPAD_BUTTON_A) return true; else return false; } else { ButtonRumble = false; GRRLIB_DrawImg(X, Y, Spr_ButtonLeft, 0, 1, 1, 0xFFFFFFFF ); for(BX=X+Spr_ButtonLeft->w; BX<X+Width-Spr_ButtonCenter->w; BX+=Spr_ButtonCenter->w) GRRLIB_DrawImg(BX, Y, Spr_ButtonCenter, 0, 1, 1, 0xFFFFFFFF ); GRRLIB_DrawImg(BX, Y, Spr_ButtonRight, 0, 1, 1, 0xFFFFFFFF ); return false; }; }; void Draw_Window(int X, int Y, int width, int height, u8 alpha) { u32 color = GRRLIB_GetColor(255,255,255,alpha); width = (width-(Spr_WindowTopRight->w-Spr_WindowTopLeft->w)); width = floor(width/Spr_WindowTopCenter->w)*Spr_WindowTopCenter->w; width += (Spr_WindowTopRight->w+Spr_WindowTopLeft->w); height = (height-(Spr_WindowBottomLeft->h-Spr_WindowTopLeft->h)); height = floor(height/Spr_WindowCenterLeft->h)*Spr_WindowCenterLeft->h; height += (Spr_WindowBottomLeft->h+Spr_WindowTopLeft->h); GRRLIB_DrawImg(X, Y, Spr_WindowTopLeft, 0, 1, 1, color ); GRRLIB_DrawImg(X+width-Spr_WindowTopRight->w, Y, Spr_WindowTopRight, 0, 1, 1, color); GRRLIB_DrawImg(X, Y+height-Spr_WindowBottomLeft->h, Spr_WindowBottomLeft, 0, 1, 1, color ); GRRLIB_DrawImg(X+width-Spr_WindowBottomRight->w, Y+height-Spr_WindowBottomRight->h, Spr_WindowBottomRight, 0, 1, 1, color ); unsigned int WX,WY; for(WX = X+Spr_WindowTopLeft->w; WX < X+width-Spr_WindowTopRight->w; WX += Spr_WindowTopCenter->w) { GRRLIB_DrawImg(WX, Y, Spr_WindowTopCenter, 0, 1, 1, color ); GRRLIB_DrawImg(WX, Y+height-Spr_WindowBottomCenter->h, Spr_WindowBottomCenter, 0, 1, 1, color ); } for(WY = Y+Spr_WindowTopLeft->h; WY < Y+height-Spr_WindowBottomLeft->h; WY += Spr_WindowCenterLeft->h) { GRRLIB_DrawImg(X, WY, Spr_WindowCenterLeft, 0, 1, 1, color ); GRRLIB_DrawImg(X+width-Spr_WindowCenterRight->w, WY, Spr_WindowCenterRight, 0, 1, 1, color ); } }; void Draw_Tooltip(int X, int Y, int width, int height, u8 alpha, char *text) { u32 color = GRRLIB_GetColor(255,255,255,alpha); width -= (Spr_WindowTopRight->w+Spr_WindowTopLeft->w); width = floor(width/Spr_WindowTopCenter->w)*Spr_WindowTopCenter->w; width += (Spr_WindowTopRight->w+Spr_WindowTopLeft->w); height -=(Spr_WindowBottomLeft->h+Spr_WindowTopLeft->h); height = floor(height/Spr_WindowCenterLeft->h)*Spr_WindowCenterLeft->h; height += (Spr_WindowBottomLeft->h+Spr_WindowTopLeft->h); GRRLIB_DrawImg(X, Y, Spr_WindowTopLeft, 0, 1, 1, color); GRRLIB_DrawImg(X+width-Spr_WindowTopRight->w, Y, Spr_WindowTopRight, 0, 1, 1, color); GRRLIB_DrawImg(X, Y+height-Spr_WindowBottomLeft->h, Spr_WindowBottomLeft, 0, 1, 1, color ); GRRLIB_DrawImg(X+width-Spr_WindowBottomRight->w, Y+height-Spr_WindowBottomRight->h, Spr_WindowBottomRight, 0, 1, 1, color ); unsigned int WX,WY; for(WX = X+Spr_WindowTopLeft->w; WX < X+width-Spr_WindowTopRight->w; WX += Spr_WindowTopCenter->w) { GRRLIB_DrawImg(WX, Y, Spr_WindowTopCenter, 0, 1, 1, color ); GRRLIB_DrawImg(WX, Y+height-Spr_WindowBottomCenter->h, Spr_WindowBottomCenter, 0, 1, 1, color ); } for(WY = Y+Spr_WindowTopLeft->h; WY < Y+height-Spr_WindowBottomLeft->h; WY += Spr_WindowCenterLeft->h) { GRRLIB_DrawImg(X, WY, Spr_WindowCenterLeft, 0, 1, 1, color ); GRRLIB_DrawImg(X+width-Spr_WindowCenterRight->w, WY, Spr_WindowCenterRight, 0, 1, 1, color ); } GRRLIB_Printf(X+Spr_WindowCenterRight->w,Y+(height/3),Spr_Font,color,1,text); }; void ShowMessage(const char *MessageString) { int stage=0, XX=120, YY=480; GRRLIB_texImg *Spr_Screen = GRRLIB_CreateEmptyTexture(640, 480); GRRLIB_Screen2Texture(Spr_Screen); PlayerOne->Update(); while(PlayerOne->PadDown != WPAD_BUTTON_PLUS) { GRRLIB_DrawImg(0, 0, Spr_Screen, 0, 1, 1, 0xFFFFFFFF ); switch(stage) { case 0: GRRLIB_DrawImg(XX, YY, Spr_MessageBox, 0, 1, 1, 0xFFFFFFFF ); GRRLIB_Printf(XX+32,YY+80,Spr_Font,0x000000FF,1,MessageString); DrawButton(XX+100,YY+200,200); if (YY > 120) YY -= 40; else stage = 1; break; case 1: GRRLIB_DrawImg(XX, YY, Spr_MessageBox, 0, 1, 1, 0xFFFFFFFF ); GRRLIB_Printf(XX+32,YY+80,Spr_Font,0x000000FF,1,MessageString); if (DrawButton(XX+100,YY+200,200)) stage = 2; break; case 2: GRRLIB_DrawImg(XX, YY, Spr_MessageBox, 0, 1, 1, 0xFFFFFFFF ); GRRLIB_Printf(XX+32,YY+80,Spr_Font,0x000000FF,1,MessageString); DrawButton(XX+100,YY+200,200); if (YY >-280) YY-=40; else stage = 3; break; }; if (stage == 3) break; PlayerOne->Update(); GRRLIB_Render(); }; GRRLIB_FreeTexture(Spr_Screen); }; int GetInteger() { return 1; }; void GetString() { }; void AddLog(const char *text) { if (Debug==true) { sprintf(DebugLog,"%s \r\n",text); fputs(DebugLog,DebugLogFile); }; }; }; GUI_System *GUI; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Sound System // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static MODPlay modplay; class SND_Resource { public: unsigned long FileSize; int Type; /**< Type of sound 0=mod 1=mp3 2=wav 3=pcm 4=ogg */ bool Loop; bool Isplaying; char *Data; SND_Resource(char *filename) { GUI->AddLog("Creating Sound"); Loop = false; Isplaying = false; Type = -1; size_t result; FILE *f=fopen(filename, "rb"); Data = NULL; if (f == NULL) { GUI->AddLog("[FAILED] Could Not Find File"); fclose(f); } else { fseek (f , 0, SEEK_END); FileSize = ftell (f); rewind(f); Data = (char*) malloc (sizeof(char)*FileSize); if (Data!=NULL) { result = fread (Data,1,FileSize,f); if (result == FileSize) { GUI->AddLog("Loaded Successfully"); GUI->AddLog("Checking Extention"); if (strstr(filename,".mod") != NULL) {Type = 0; GUI->AddLog("Sound is a Mod File");} if (strstr(filename,".mp3") != NULL) {Type = 1; GUI->AddLog("Sound is a MP3 File");} if (strstr(filename,".wav") != NULL) {Type = 2; GUI->AddLog("Sound is a Wav File");} if (strstr(filename,".pcm") != NULL) {Type = 3; GUI->AddLog("Sound is a PCM File");} if (strstr(filename,".ogg") != NULL) {Type = 4; GUI->AddLog("Sound is a OGG File");} if (Type == -1) { GUI->AddLog("[FAILED] Could not figure out the type based on extention. Make sure the extenstion is lower case."); free(Data); Data = NULL; }; } else { GUI->AddLog("[FAILED] Reading From Disk"); free(Data); Data = NULL; }; } else GUI->AddLog("[FAILED] Allocating Memory"); fclose(f); }; }; ~SND_Resource() { //if (Data!=NULL) //free(Data); }; }; class SND_System { public: SND_Resource *Sounds[50]; int Current_New_Index; bool MODPLAY_ISPLAYING, MP3_ISPLAYING; SND_System() { GUI->AddLog("[OK] Initializing sound system."); int i; AUDIO_Init(NULL); ASND_Init(); MODPlay_Init(&modplay); MP3Player_Init(); Current_New_Index = 0; MODPLAY_ISPLAYING = false; MP3_ISPLAYING =false; for(i=0;i<50;i++) Sounds[i]=NULL; GUI->AddLog("Success"); }; ~SND_System() { int i; if (MODPLAY_ISPLAYING) MODPlay_Stop(&modplay); if (MP3_ISPLAYING) MP3Player_Stop(); for(i=0;i<50;i++) if (Sounds[i]->Data != NULL) free(Sounds[i]->Data); }; int AddSound(char *filename) { GUI->AddLog("[OK] Adding Sound"); if (Sounds[Current_New_Index] == NULL) { int this_index = Current_New_Index; SND_Update_New_Index(); Sounds[this_index] = new SND_Resource(filename); if (Sounds[this_index]->Data == NULL) { delete Sounds[this_index]; return -1; }; return this_index; } else { GUI->AddLog("[Failed] Sound Index Exists Already"); return -1; }; }; bool DeleteSound(int index) { if (index == -1) return false; if (Sounds[index] == NULL) return false; delete Sounds[index]; Sounds[index] = NULL; return true; }; bool PlaySound(int index) { GUI->AddLog("[OK] Playing Sound"); if (index == -1) return false; if (Sounds[index] == NULL) return false; if (Sounds[index]->Data == NULL) return false; MODPLAY_ISPLAYING = false; MP3_ISPLAYING = false; if (Sounds[index]->Type == 0) { GUI->AddLog("Is a Mod File"); if (MODPLAY_ISPLAYING) MODPlay_Stop(&modplay); if (MP3_ISPLAYING) MP3Player_Stop(); GUI->AddLog("Stopped existing music"); MODPlay_SetMOD(&modplay, Sounds[index]->Data); MODPlay_Start(&modplay); MODPlay_SetVolume(&modplay, 100, 100); GUI->AddLog("Success"); Sounds[index]->Isplaying = true; Sounds[index]->Loop = false; MODPLAY_ISPLAYING = true; return true; }; if (Sounds[index]->Type == 1) { GUI->AddLog("Is a MP3 File"); if (MODPLAY_ISPLAYING) MODPlay_Stop(&modplay); if (MP3_ISPLAYING) MP3Player_Stop(); GUI->AddLog("Stopped existing music"); MP3Player_PlayBuffer(Sounds[index]->Data,Sounds[index]->FileSize,NULL); MP3Player_Volume(255); GUI->AddLog("Success"); Sounds[index]->Isplaying = true; Sounds[index]->Loop = false; MP3_ISPLAYING = true; return true; }; return false; }; bool LoopSound(int index) { GUI->AddLog("[OK] Loop Sound"); if (index == -1) return false; if (Sounds[index] == NULL) return false; if (Sounds[index]->Data == NULL) return false; PlaySound(index); Sounds[index]->Loop = true; return true; }; bool StopSound(int index) { GUI->AddLog("[OK] Stopping Sound"); if (index == -1) return false; if (Sounds[index] == NULL) return false; if (Sounds[index]->Data == NULL) return false; if (Sounds[index]->Type == 0) { GUI->AddLog("Is a Mod File"); if (MODPLAY_ISPLAYING) MODPlay_Stop(&modplay); if (MP3_ISPLAYING) MP3Player_Stop(); Sounds[index]->Isplaying = false; Sounds[index]->Loop = false; MP3_ISPLAYING = false; MODPLAY_ISPLAYING = false; return true; }; if (Sounds[index]->Type == 1) { GUI->AddLog("Is a MP3 File"); if (MODPLAY_ISPLAYING) MODPlay_Stop(&modplay); if (MP3_ISPLAYING) MP3Player_Stop(); Sounds[index]->Isplaying = false; Sounds[index]->Loop = false; MODPLAY_ISPLAYING = false; MP3_ISPLAYING = false; return true; }; return false; }; void StopAllSound() { int i; for(i=0;i<50;i++) StopSound(i); }; bool SoundIsplaying(int index) { if (index == -1) return false; if (Sounds[index] == NULL) return false; return Sounds[index]->Isplaying; }; void SND_Update_New_Index() { Current_New_Index += 1; }; }; SND_System *SoundSystem; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Channel System // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class Animation { public: GRRLIB_texImg *Spr_Resources[10]; int Image_Startx[10], Image_Time[10], Image_Starty[10], Image_TransitionIn[10], Image_TransitionInStart[10], Image_TransitionInLength[10], Image_TransitionStep[10], Image_TransitionOut[10], Image_TransitionOutStart[10], Image_TransitionOutLength[10], Image_TransitionTotal[10], Snd_Resource, Type; float Image_X[10], Image_Y[10], Image_Xscale[10], Image_Yscale[10], Image_Alpha[10]; bool Channel_Exists; char Directory[260]; Animation(const char *ChannelDirectory) { GUI->AddLog("Creating Animation"); Type = -1; int i; for(i=0;i<10;i+=1) {Spr_Resources[i] = NULL; Image_Startx[i] = 0; Image_Starty[i] = 0; Image_Time[i] = 9999; Image_Alpha[i] = 255; Image_Xscale[i] = 1; Image_Yscale[i] = 1;}; Channel_Exists = false; Snd_Resource = NULL; sprintf(Directory,"%s",ChannelDirectory); char FileName[260]; sprintf(FileName,"%s/Animation.xml",ChannelDirectory); if (file_exists(FileName)) Load_Animated_Icon(); sprintf(FileName,"%s/AlbumArt.png",ChannelDirectory); if (file_exists(FileName)) Load_MP3_Album(); }; ~Animation() { GUI->AddLog("Deleting Animation"); int i; for(i=0;i<10;i+=1) { if (Spr_Resources[i]!=NULL){}; GRRLIB_FreeTexture(Spr_Resources[i]); }; }; void Draw_Animated_Icon(int X, int Y) { GRRLIB_ClipDrawing( X, Y, 128,96 ); int i; for(i=0;i<10;i+=1) { if (Spr_Resources[i]!=NULL) { Image_Time[i]+=1; if (Image_Time[i] > Image_TransitionTotal[i]) { Image_Time[i] = 0; Image_Alpha[i] = 255; Image_Xscale[i] = 1; Image_Yscale[i] = 1; Image_X[i]=Image_Startx[i]; Image_Y[i]=Image_Starty[i]; switch(Image_TransitionIn[i]) { case 0: Image_Alpha[i]=0; break; case 1: Image_X[i]=128; break; case 2: Image_Y[i]=96; break; case 3: Image_X[i]=-((float)Spr_Resources[i]->w); break; case 4: Image_Y[i]=-((float)Spr_Resources[i]->h); break; }; } //Transition in effect if (Image_Time[i] > Image_TransitionInStart[i] && Image_Time[i] <= Image_TransitionInStart[i]+Image_TransitionInLength[i]) { switch(Image_TransitionIn[i]) { case 0: Image_Alpha[i]+=(float)255/(Image_TransitionInLength[i]); if (Image_Alpha[i] > 255) Image_Alpha[i] = 255; break; case 1: Image_X[i]-=(float)(128-Image_Startx[i])/(Image_TransitionInLength[i]); break; case 2: Image_Y[i]-=(float)(96-Image_Starty[i])/(Image_TransitionInLength[i]); break; case 3: Image_X[i]+=(float)(Image_Startx[i]+Spr_Resources[i]->w)/(Image_TransitionInLength[i]); break; case 4: Image_Y[i]+=(float)(Image_Starty[i]+Spr_Resources[i]->h)/(Image_TransitionInLength[i]); break; }; }; if (Image_Time[i] == Image_TransitionInStart[i]+Image_TransitionInLength[i]+1) { Image_Alpha[i] = 255; Image_Xscale[i] = 1; Image_Yscale[i] = 1; Image_X[i]=Image_Startx[i]; Image_Y[i]=Image_Starty[i]; }; //Transition Step //Transition Out if (Image_Time[i] >= Image_TransitionOutStart[i] && Image_Time[i] <= Image_TransitionOutStart[i]+Image_TransitionOutLength[i]) { switch(Image_TransitionOut[i]) { case 0: Image_Alpha[i]-=(float)255/(Image_TransitionOutLength[i]); if (Image_Alpha[i] < 0) Image_Alpha[i] = 0; break; case 1: Image_X[i]+=(float)(128-Image_Startx[i])/(Image_TransitionOutLength[i]); break; case 2: Image_Y[i]+=(float)(96-Image_Starty[i])/(Image_TransitionOutLength[i]); break; case 3: Image_X[i]-=(float)(Image_Startx[i]+Spr_Resources[i]->w)/(Image_TransitionOutLength[i]); break; case 4: Image_Y[i]-=(float)(Image_Starty[i]+Spr_Resources[i]->h)/(Image_TransitionOutLength[i]); break; }; }; if (Image_Time[i] == Image_TransitionOutStart[i]+Image_TransitionOutLength[i]+1) { Image_Alpha[i] = 255; Image_Xscale[i] = 1; Image_Yscale[i] = 1; Image_X[i]=128; Image_Y[i]=96; }; //End of transtions GRRLIB_DrawImg(X+Image_X[i], Y+Image_Y[i], Spr_Resources[i], 0, Image_Xscale[i], Image_Yscale[i], GRRLIB_GetColor(255,255,255,round(Image_Alpha[i])) ); }; }; GRRLIB_ClipReset(); }; private: void Load_Animated_Icon() { Type = 0; mxml_node_t *tree; mxml_node_t *data; mxml_node_t *main; int i; char XML_Filepath[255]; sprintf(XML_Filepath,"%s/Animation.XML",Directory); FILE *XML_File = fopen(XML_Filepath, "rb"); fseek (XML_File , 0, SEEK_END); long settings_size = ftell (XML_File); rewind (XML_File); if (settings_size > 0) { tree = mxmlLoadFile(NULL, XML_File, MXML_NO_CALLBACK); fclose(XML_File); char Image_Filename[255]="", Tag[6]=""; sprintf(Image_Filename,"%s/folderMusic.mod",Directory); Snd_Resource = SoundSystem->AddSound(Image_Filename); main = mxmlFindElement(tree, tree, "main", NULL, NULL, MXML_DESCEND); for(i=0;i<10;i+=1) { sprintf(Tag,"image%i",i); data = mxmlFindElement(tree, main, Tag, NULL, NULL, MXML_DESCEND); if (mxmlElementGetAttr(data,"filename") != NULL) { sprintf(Image_Filename,"%s/%s",Directory,mxmlElementGetAttr(data,"filename")); if (file_exists(Image_Filename)) { Spr_Resources[i] = GRRLIB_LoadTextureFromFile(Image_Filename); Channel_Exists = true; if (mxmlElementGetAttr(data,"x")!=NULL && mxmlElementGetAttr(data,"y")!=NULL && mxmlElementGetAttr(data,"in_fx")!=NULL && mxmlElementGetAttr(data,"in_fx_start")!=NULL && mxmlElementGetAttr(data,"step_fx")!=NULL && mxmlElementGetAttr(data,"out_fx")!=NULL && mxmlElementGetAttr(data,"out_fx_start")!=NULL && mxmlElementGetAttr(data,"out_fx_time")!=NULL && mxmlElementGetAttr(data,"loop_time")!=NULL) { Image_Startx[i] = atoi(mxmlElementGetAttr(data,"x")); Image_Starty[i] = atoi(mxmlElementGetAttr(data,"y")); Image_TransitionIn[i] = atoi(mxmlElementGetAttr(data,"in_fx")); Image_TransitionInStart[i] = atoi(mxmlElementGetAttr(data,"in_fx_start")); Image_TransitionInLength[i] = atoi(mxmlElementGetAttr(data,"in_fx_time")); Image_TransitionStep[i] = atoi(mxmlElementGetAttr(data,"step_fx")); Image_TransitionOut[i] = atoi(mxmlElementGetAttr(data,"out_fx")); Image_TransitionOutStart[i] = atoi(mxmlElementGetAttr(data,"out_fx_start")); Image_TransitionOutLength[i] = atoi(mxmlElementGetAttr(data,"out_fx_time")); Image_TransitionTotal[i] = atoi(mxmlElementGetAttr(data,"loop_time")); }; } else GUI->AddLog("[Failed] Invalid reference to an image in the xml file"); }; mxmlDelete(data); }; mxmlDelete(tree); }; }; void Load_MP3_Album() { Type = 1; Channel_Exists = true; char Image_Filename[260]; sprintf(Image_Filename,"%s/AlbumArt.png",Directory); Spr_Resources[0] = GRRLIB_LoadTextureFromFile(Image_Filename); }; }; class Channel { public: Animation *My_Animation; int XX,YY, Xto, Yto, MyId, MyNameBubble; float X,Y, MySelected, MP3_Xscale, MP3_Xscalespeed; char MyPath[255]; bool Dragging, MP3_Flip; Channel() { MySelected=1; MyId = -1; Dragging = false; X = 0; Y = 0; Xto = 320; Yto = 240; MP3_Flip=false; MP3_Xscale=1; MP3_Xscalespeed=0; MyNameBubble = 0; My_Animation = NULL; }; ~Channel() { if (My_Animation != NULL) delete My_Animation; }; int Handle() { if (My_Animation == NULL) return -1; int Returning=-1; XX = X-view_xview; YY = Y-view_yview; switch(My_Animation->Type) { case -1: GRRLIB_DrawImg(XX, YY, Spr_BlankChannel, 0, 1, 1, 0xFFFFFFFF); break; case 0: Returning=Draw_Animated_Icon(); break; case 1: Returning=Draw_Mp3_Album(); break; case 2: Returning=Draw_RSS_Feed(); break; case 3: Returning=Draw_Photo_Frame(); break; }; // Handle Dragging if (Dragging == true) { Xto = view_xview+(PlayerOne->X-64); Yto = view_yview+(PlayerOne->Y-48); if (Xto < 0) Xto = 0; if (Xto > 2816) Xto = 2816; if (Yto < 0) Yto = 0; if (Yto > 224) Yto = 224; GRRLIB_DrawImg(Xto-view_xview, Yto-view_yview, Spr_BlankChannel, 0, 1, 1, 0xFFFFFF55); Xto = 64+(round(Xto/Spr_MaskChannel->w)*Spr_MaskChannel->w); Yto = 32+(round(Yto/Spr_MaskChannel->h)*Spr_MaskChannel->h); }; if (Dragging == false && (Xto != X || Yto != Y)) { if (X != Xto) X+= (float)((Xto-X)/5); if (Y != Yto) Y+= (float)((Yto-Y)/5); if (X > Xto-30 && X < Xto+30) X = Xto; if (Y > Yto-30 && Y < Yto+30) Y = Yto; GRRLIB_DrawImg(Xto-view_xview, Yto-view_yview, Spr_BlankChannel, 0, 1, 1, 0xFFFFFF99); }; return Returning; }; private: int Draw_Animated_Icon() { // Handle Drawing My_Animation->Draw_Animated_Icon(XX,YY); GRRLIB_DrawImg(XX, YY, Spr_MaskChannel, 0, 1, 1, 0xFFFFFFFF); if (MySelected < 1) { GRRLIB_DrawImg(XX+(MySelected*12), YY+(MySelected*10), Spr_SelectedChannel, 0, (1-(MySelected/5)), (1-(MySelected/10)), GRRLIB_GetColor(100, 255, 100, (1-MySelected)*255) ); MySelected += 0.05; }; if (MyNameBubble > 0) MyNameBubble -= 20; if (MyNameBubble > 100) { if (MyNameBubble > 355) MyNameBubble = 355; GUI->Draw_Tooltip(XX,YY+96,150,80,MyNameBubble-100,MyPath+9); }; //Handle Player Cursor if (PlayerOne->X > XX && PlayerOne->Y > YY && PlayerOne->X < XX+128 && PlayerOne->Y < YY+96) { MySelected=0; MyNameBubble+=40; return MyId; } else return -1; }; int Draw_Mp3_Album() { if (My_Animation->Spr_Resources[0]==NULL) return -1; int width=180*MP3_Xscale; int height=180; if (!MP3_Flip) GRRLIB_DrawImg(XX, YY, My_Animation->Spr_Resources[0], 0, (float)width/My_Animation->Spr_Resources[0]->w, (float)height/My_Animation->Spr_Resources[0]->h, 0xFFFFFFFF); if (MP3_Flip) GRRLIB_Rectangle(XX, YY, width, height, 0xFFFFFFFF, true); if (MP3_Xscale < 0) {MP3_Flip=!MP3_Flip; MP3_Xscalespeed = -MP3_Xscalespeed;}; if (MP3_Xscale > 1) {MP3_Xscale = 1; MP3_Xscalespeed = 0;}; MP3_Xscale += MP3_Xscalespeed; if (PlayerOne->X > XX && PlayerOne->Y > YY && PlayerOne->X < XX+width && PlayerOne->Y < YY+height) { MySelected=0; if (PlayerOne->PadDown & WPAD_BUTTON_A) { MP3_Xscalespeed = -0.1; }; return -1; } else return -1; }; int Draw_RSS_Feed() { return -1; }; int Draw_Dvd_Channel() { return -1; }; int Draw_Photo_Frame() { return -1; }; }; class Channel_System { private: int NextEmptyChannel; void Update_NextEmptyChannel() { NextEmptyChannel = 0; while(Channels[NextEmptyChannel]->My_Animation != NULL) NextEmptyChannel+=1; }; public: Channel *Channels[200]; Channel_System() { int i; for(i=0;i<200;i++) Channels[i] = new Channel(); NextEmptyChannel = 0; }; ~Channel_System() { Clear_All_Channel(); }; ///////////////////////////////////////////////////////////////////////////////////////////// int Add_Channel(const char *Directory) { GUI->AddLog("[OK] Creating Channel"); int this_channel=NextEmptyChannel; Channels[this_channel]->My_Animation = new Animation(Directory); if (Channels[this_channel]->My_Animation->Channel_Exists == false) {GUI->AddLog("[Failed] Loading failed."); Clear_Channel(this_channel); return -1; }; GUI->AddLog("Success"); sprintf(Channels[this_channel]->MyPath,"%s",Directory); Channels[this_channel]->MySelected=1; Channels[this_channel]->MyId = this_channel; Channels[this_channel]->Dragging = false; Channels[this_channel]->X = -300; Channels[this_channel]->Y = -300; Channels[this_channel]->Xto = 64+(128*this_channel); Channels[this_channel]->Yto = 32; Update_NextEmptyChannel(); return this_channel; }; void Clear_Channel(int Channel_Index) { GUI->AddLog("[OK] Deleting Channel"); if (Channels[Channel_Index] == NULL) return; if (Channels[Channel_Index]->My_Animation == NULL) return; delete Channels[Channel_Index]->My_Animation; Channels[Channel_Index]->My_Animation = NULL; Channels[Channel_Index]->MyId = -1; Channels[Channel_Index]->MySelected=1; Channels[Channel_Index]->MyId = Channel_Index; Channels[Channel_Index]->Dragging = false; Channels[Channel_Index]->X = -1000; Channels[Channel_Index]->Y = -1000; Channels[Channel_Index]->Xto = 320; Channels[Channel_Index]->Yto = 240; sprintf(Channels[Channel_Index]->MyPath,"//"); Channels[Channel_Index] = NULL; }; void Clear_All_Channel() { int i; for(i=0;i<200;i++) if (Channels[i] != NULL && Channels[i]->My_Animation != NULL) { delete Channels[i]->My_Animation; Channels[i]->My_Animation = NULL; Channels[i]->MyId = -1; Channels[i]->MySelected=1; Channels[i]->MyId = -1; Channels[i]->Dragging = false; Channels[i]->X = -1000; Channels[i]->Y = -1000; Channels[i]->Xto = 320; Channels[i]->Yto = 240; sprintf(Channels[i]->MyPath,"//"); Channels[i] = NULL; }; }; ///////////////////////////////////////////////////////////////////////////////////////////// bool Channel_Set_Dragging(int Channel_Index, bool Action) { if (Channel_Index == -1) return false; if (Channels[Channel_Index]->My_Animation == NULL) return false; Channels[Channel_Index]->Dragging = Action; return true; }; int Channel_Get_X(int Channel_Index) { if (Channel_Index == -1) return -1; if (Channels[Channel_Index]->My_Animation == NULL) return -1; return Channels[Channel_Index]->X; }; int Channel_Get_Y(int Channel_Index) { if (Channel_Index == -1) return -1; if (Channels[Channel_Index]->My_Animation == NULL) return -1; return Channels[Channel_Index]->Y; }; int Channel_Get_Sound(int Channel_Index) { if (Channel_Index == -1) return -1; if (Channels[Channel_Index]->My_Animation == NULL) return -1; return Channels[Channel_Index]->My_Animation->Snd_Resource; }; int Handle_Channel(int Channel_Index) { if (Channel_Index == -1) return -1; if (Channels[Channel_Index]->My_Animation == NULL) return -1; return Channels[Channel_Index]->Handle(); }; ///////////////////////////////////////////////////////////////////////////////////////////// bool SetDirectoryToChannel(int Channel_Index) { if (Channel_Index == -1) return false; if (Channels[Channel_Index] == NULL) return false; sprintf(Current_Directory,"%s",Channels[Channel_Index]->MyPath); return true; }; }; Channel_System *ChannelSystem; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Main Loop // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class MainBrowser { public: GRRLIB_texImg *Spr_Transition, *Transition_Image, *Spr_Wallpaper, *Spr_Background; int MenuType, MenuTypeTo, Alpha, Selected, Transition_Id, Transition_Previous, Dragging, Transition_Type, MainChannels[48], SubChannels[48]; float Transition_X, Transition_Y, TranX, TranY, Transition_PreviousX, Transition_PreviousY; u32 Color; MainBrowser() { //Define Menutypes MenuType = 0; //Load GUI material Spr_Transition = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/Transition.png"); Spr_Wallpaper = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/Wallpaper.png"); Spr_Background = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/Background.png"); //Initialize Variables MenuType = 0; MenuTypeTo = 0; Alpha = 255; Dragging = -1; Selected = -1; Transition_Id=-1; Transition_Previous=-1; view_xview = 0; view_xview_to = 0; view_hspeed = 0; view_yview = 0; Transition_Type = -1; FOCUS = 0; int i; for(i=0;i<48;i++) { MainChannels[i]=-1; SubChannels[i]=-1; } MainChannels[0] = ChannelSystem->Add_Channel("sys/chnl/Super Mario Brothers 1"); MainChannels[1] = ChannelSystem->Add_Channel("sys/chnl/Super Mario Brothers 2"); MainChannels[2] = ChannelSystem->Add_Channel("sys/chnl/Super Mario Brothers 3"); //Initialize SOUND SoundSystem->PlaySound(Snd_Startup); while(true) { //Main Loop for the Browser /* Handle Type of Menu MenuType_Step() */ int i; switch(MenuType) { //Initialize case 0: //GRRLIB_FillScreen(0x505050ff); GRRLIB_DrawImg(0, 0, Spr_Background, 0, 1, 1, 0xFFFFFFFF); GRRLIB_DrawImg(0, 0, Spr_Wallpaper, 0, 1, 1, 0xFFFFFFFF); GRRLIB_DrawImg(-view_xview+512, view_yview, Spr_Wallpaper, 0, 1, 1, 0xFFFFFFFF); Alpha -= 5; if (Alpha < 6) { Transition_Id=-1; Alpha = 0; MenuType = 1; Selected = -1; Dragging = -1; Transition_Type = -1; }; for(i=0;i<48;i++) ChannelSystem->Handle_Channel(MainChannels[i]); Color = GRRLIB_GetColor(0, 0, 0, Alpha); GRRLIB_Rectangle(0,0,640,480,Color,true); break; //Main Menu case 1: //GRRLIB_FillScreen(0x505050ff); GRRLIB_DrawImg(0, 0, Spr_Background, 0, 1, 1, 0xFFFFFFFF); GRRLIB_DrawImg(-view_xview, view_yview, Spr_Wallpaper, 0, 1, 1, 0xFFFFFFFF); GRRLIB_DrawImg(-view_xview+512, view_yview, Spr_Wallpaper, 0, 1, 1, 0xFFFFFFFF); GRRLIB_DrawImg(-view_xview+1024, view_yview, Spr_Wallpaper, 0, 1, 1, 0xFFFFFFFF); GRRLIB_DrawImg(-view_xview+1536, view_yview, Spr_Wallpaper, 0, 1, 1, 0xFFFFFFFF); GRRLIB_DrawImg(-view_xview+2048, view_yview, Spr_Wallpaper, 0, 1, 1, 0xFFFFFFFF); GRRLIB_DrawImg(-view_xview+2560, view_yview, Spr_Wallpaper, 0, 1, 1, 0xFFFFFFFF); if (!MP3Player_IsPlaying()) SoundSystem->PlaySound(Snd_MainMenu); int Returned; Selected = -1; for(i=0;i<48;i++) { Returned = ChannelSystem->Handle_Channel(MainChannels[i]); if (Returned != -1) Selected = Returned; }; break; //Channel Folderview case 2: GRRLIB_FillScreen(0x701050ff); GRRLIB_DrawImg(0, 0, Spr_Transition, 0, 1, 1, 0x000000FF); break; }; if (FOCUS == -1) { Alpha += 3; if (Alpha >255) break; Color = GRRLIB_GetColor(0, 0, 0, Alpha); GRRLIB_Rectangle(0,0,640,480,Color,true); }; /* Handle services FTP_Update() Audio_Update() Power_Handling() */ PlayerOne->Update(); PlayerTwo->Update(); PlayerThree->Update(); PlayerFour->Update(); if (PlayerOne->WPAD_POWER && FOCUS != -1) { FOCUS = -1; Alpha = 0; PlayerOne->WPAD_POWER = false; }; /* Handle Transitions */ if (FOCUS == 0) { if (Transition_Id != -1) { if (MenuType!=0) { switch(Transition_Type) { case 0: TransitionZoomIn(); break; case 1: TransitionZoomOut(); break; }; }; } else { /* Handle Controls */ switch(MenuType) { case 0: break; case 1: if (Selected!=-1) { if (PlayerOne->PadDown & WPAD_BUTTON_A) { if (PlayerOne->PadHeld & WPAD_BUTTON_B) { Dragging = Selected; ChannelSystem->Channel_Set_Dragging(Selected,true); } else { MenuTypeTo = 2; Transition_Type = 0; Alpha = 0; Transition_Id=Selected; Transition_X=ChannelSystem->Channel_Get_X(Transition_Id); Transition_Y=ChannelSystem->Channel_Get_Y(Transition_Id); Transition_PreviousX=Transition_X; Transition_PreviousY=Transition_Y; TranX=Transition_X/255; TranY=Transition_Y/255; }; }; }; if (Dragging != -1) { if ((PlayerOne->PadHeld & WPAD_BUTTON_A) && (PlayerOne->PadHeld & WPAD_BUTTON_A)) { if (PlayerOne->X > 590) if (view_xview == view_xview_to) view_xview_to += 512; if (PlayerOne->X < 50) if (view_xview == view_xview_to) view_xview_to -= 512; } else { ChannelSystem->Channel_Set_Dragging(Dragging,false); }; }; if (view_xview_to > 2048) view_xview_to = 2048; if (view_xview_to < 0) view_xview_to = 0; if (PlayerOne->PadDown & WPAD_BUTTON_PLUS) if (view_xview == view_xview_to) view_xview_to += 512; if (PlayerOne->PadDown & WPAD_BUTTON_MINUS) if (view_xview == view_xview_to) view_xview_to -= 512; if (view_xview_to > view_xview) view_hspeed += 1.5; if (view_xview_to < view_xview) view_hspeed -= 1.5; if (view_hspeed > 0 && view_xview > view_xview_to-view_hspeed) { view_hspeed = 0; view_xview = view_xview_to; }; if (view_hspeed < 0 && view_xview < view_xview_to-view_hspeed) { view_hspeed = 0; view_xview = view_xview_to; }; view_xview += view_hspeed; break; case 2: if (PlayerOne->PadDown & WPAD_BUTTON_B) { MenuTypeTo = 1; Transition_Type = 1; Alpha = 255; Transition_Id=Transition_Previous; Transition_X=0; Transition_Y=0; TranX=Transition_PreviousX/255; TranY=Transition_PreviousY/255; }; break; }; }; }; GUI->Step(); GRRLIB_Render(); }; }; ~MainBrowser() { GRRLIB_FreeTexture(Spr_Transition); GRRLIB_FreeTexture(Spr_Wallpaper); }; void TransitionZoomIn() { //step Alpha+=15; if (Alpha > 255) { SoundSystem->PlaySound(ChannelSystem->Channel_Get_Sound(Transition_Id)); MP3Player_Volume(255); MODPlay_SetVolume(&modplay, 100, 100); Transition_Previous = Transition_Id; Transition_Id = -1; } else { MODPlay_SetVolume(&modplay, 100-(Alpha/2.5), 100-(Alpha/2.5)); MP3Player_Volume(255-(Alpha)); if (Alpha > 119 && MenuType!=MenuTypeTo) { MenuType = MenuTypeTo; ChannelSystem->SetDirectoryToChannel(Transition_Id); }; if (Alpha < 128) Color = GRRLIB_GetColor(255,255,255,255); else Color = GRRLIB_GetColor(255,255,255,255-Alpha); GRRLIB_DrawImg(Transition_X, Transition_Y, Spr_BlankChannel, 0, 1+((float)Alpha/63.7), 1+((f32)Alpha/63.7), Color); if (Alpha < 128) Color = GRRLIB_GetColor(0,0,0,Alpha*2); else { Color = 0x000000FF; }; GRRLIB_Rectangle(0, 0, Transition_X, 480,Color,true); GRRLIB_Rectangle(Transition_X, 0, 640-Transition_X, Transition_Y,Color,true); GRRLIB_Rectangle(Transition_X, Transition_Y+(480*(0.2+((f32)Alpha/318.75))), 640-Transition_X, 390,Color,true); GRRLIB_Rectangle(Transition_X+(640*(0.2+((f32)Alpha/318.75))), Transition_Y, 640-Transition_X, (480*(0.2+((f32)Alpha/318.75))),Color,true); GRRLIB_DrawImg(Transition_X, Transition_Y, Spr_Transition, 0, 0.2+((float)Alpha/318.75), 0.2+((f32)Alpha/318.75), Color); Transition_X-=TranX*15; Transition_Y-=TranY*15; }; }; void TransitionZoomOut() { //step Alpha-=15; if (Alpha < 0) { SoundSystem->StopSound(ChannelSystem->Channel_Get_Sound(Transition_Id)); MP3Player_Volume(255); MODPlay_SetVolume(&modplay, 100, 100); SoundSystem->PlaySound(Snd_MainMenu); Transition_Id = -1; Transition_Previous=-1; } else { MODPlay_SetVolume(&modplay, (Alpha/2.5), (Alpha/2.5)); MP3Player_Volume(Alpha); if (Alpha < 136 && MenuType!=MenuTypeTo) { MenuType = MenuTypeTo; sprintf(Current_Directory,"sys/chnl"); }; if (Alpha > 128) Color = GRRLIB_GetColor(255,255,255,255-Alpha); else Color = GRRLIB_GetColor(255,255,255,255); GRRLIB_DrawImg(Transition_X, Transition_Y, Spr_BlankChannel, 0, 1+((float)Alpha/63.7), 1+((f32)Alpha/63.7), Color); if (Alpha > 128) Color = 0x000000FF; else { Color = GRRLIB_GetColor(0,0,0,Alpha*2); }; GRRLIB_Rectangle(0, 0, Transition_X, 480,Color,true); GRRLIB_Rectangle(Transition_X, 0, 640-Transition_X, Transition_Y,Color,true); GRRLIB_Rectangle(Transition_X, Transition_Y+(480*(0.2+((f32)Alpha/318.75))), 640-Transition_X, 390,Color,true); GRRLIB_Rectangle(Transition_X+(640*(0.2+((f32)Alpha/318.75))), Transition_Y, 640-Transition_X, (480*(0.2+((f32)Alpha/318.75))),Color,true); GRRLIB_DrawImg(Transition_X, Transition_Y, Spr_Transition, 0, 0.2+((float)Alpha/318.75), 0.2+((f32)Alpha/318.75), Color); Transition_X+=TranX*15; Transition_Y+=TranY*15; }; }; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Health and Safety // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class HealthAndSafety { public: int Stage, Alpha; GRRLIB_texImg *Spr_Hands; HealthAndSafety() { Stage=0; Alpha=0; Spr_Hands = GRRLIB_LoadTextureFromFile("SYS/GFX/HANDS.png"); while(true) { switch(Stage) { case 0: if (Alpha < 245) Alpha += 10; else if (PlayerOne->PadDown & WPAD_BUTTON_A) {Stage = 1; PlayerOne->Rumble_Time = 10;}; PlayerOne->Update(); GRRLIB_DrawImg(0, 0, Spr_Hands , 0, 1, 1, GRRLIB_GetColor(255, 255, 255, Alpha)); break; case 1: if (Alpha > 10) Alpha -= 10; else Stage = 2; PlayerOne->Update(); GRRLIB_DrawImg(0, 0, Spr_Hands , 0, 1, 1, GRRLIB_GetColor(255, 255, 255, Alpha)); break; }; GRRLIB_Render(); if (Stage == 2) break; }; }; ~HealthAndSafety() { GRRLIB_FreeTexture(Spr_Hands); }; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Intro Clip // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ChannelFadeIn { public: int Stage, Alpha_Main, Alpha, XX, YY; u32 Color; ChannelFadeIn() { Alpha=0; Alpha_Main=0; XX=0; YY=0; Stage=0; while(true) { switch(Stage) { case 0: Alpha = Alpha_Main; for(XX=64;XX<512;XX+=128) for(YY=60;YY<338;YY+=96) { if (Alpha < 0) Alpha = 0; if (Alpha > 255) Color = GRRLIB_GetColor(75, 75, 75, 255); else Color = GRRLIB_GetColor(75, 75, 75, Alpha); GRRLIB_DrawImg(XX, YY, Spr_BlankChannel, 0, 1, 1, Color ); if (Alpha < 255) Alpha+=10; }; Alpha_Main+=5; if (Alpha_Main > 280) Stage = 1; break; case 1: Alpha = Alpha_Main; for(XX=64;XX<512;XX+=128) for(YY=60;YY<338;YY+=96) { if (Alpha < 0) Alpha = 0; if (Alpha > 255) Color = GRRLIB_GetColor(75, 75, 75, 255); else Color = GRRLIB_GetColor(75, 75, 75, Alpha); GRRLIB_DrawImg(XX, YY, Spr_BlankChannel, 0, 1, 1, Color ); Alpha-=10; }; Alpha_Main-=5; if (Alpha_Main < 0) Stage = 2; break; }; GRRLIB_Render(); if (Stage == 2) break; }; }; ~ChannelFadeIn() {}; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Entry Point // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int main() { GRRLIB_Init(); GRRLIB_SetAntiAliasing(false); WPAD_Init(); WPAD_SetIdleTimeout(60); WPAD_SetDataFormat(WPAD_CHAN_0, WPAD_FMT_BTNS_ACC_IR); WPAD_SetDataFormat(WPAD_CHAN_1, WPAD_FMT_BTNS_ACC_IR); WPAD_SetDataFormat(WPAD_CHAN_2, WPAD_FMT_BTNS_ACC_IR); WPAD_SetDataFormat(WPAD_CHAN_3, WPAD_FMT_BTNS_ACC_IR); PlayerOne=new PlayerPad(WPAD_CHAN_0,"SYS/SKN/Default/Player1_Point.png"); PlayerTwo=new PlayerPad(WPAD_CHAN_1,"SYS/SKN/Default/Player2_Point.png"); PlayerThree=new PlayerPad(WPAD_CHAN_2,"SYS/SKN/Default/Player3_Point.png"); PlayerFour=new PlayerPad(WPAD_CHAN_3,"SYS/SKN/Default/Player4_Point.png"); HealthAndSafety *HAS = new HealthAndSafety(); delete HAS; GUI = new GUI_System(); ChannelSystem=new Channel_System(); SoundSystem = new SND_System(); Spr_BlankChannel = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/Channel.png"); Spr_SelectedChannel = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/ChannelSelected.png"); Spr_MaskChannel = GRRLIB_LoadTextureFromFile("SYS/SKN/Default/ChannelMask.png"); char SND_Filename[255]=""; sprintf(SND_Filename,"SYS/SKN/Default/SND/MainMenu.mp3"); Snd_MainMenu = SoundSystem->AddSound(SND_Filename); sprintf(SND_Filename,"SYS/SKN/Default/SND/Startup.mp3"); Snd_Startup = SoundSystem->AddSound(SND_Filename); ChannelFadeIn *CFI = new ChannelFadeIn(); delete CFI; sprintf(Current_Directory,"sys/chnl"); WPAD_SetPowerButtonCallback(PowerBttn); MainBrowser *MB = new MainBrowser(); delete MB; //delete ChannelSystem; // need to fix throws exception when this is called does not make it to ~Channel_System(); //delete SoundSystem; // need to fix - freezes when using free() delete GUI; delete PlayerOne; delete PlayerTwo; delete PlayerThree; delete PlayerFour; GRRLIB_FreeTexture(Spr_BlankChannel); GRRLIB_FreeTexture(Spr_SelectedChannel); GRRLIB_FreeTexture(Spr_Font); GRRLIB_Exit(); // Be a good boy, clear the memory allocated by GRRLIB return 0; }; //
[ "megazig@megazig-desktop.(none)" ]
[ [ [ 1, 1564 ] ] ]
1a8a6aab666c6d65d613dfaf94af59fbaf8e39f7
a96e0816f6880d9560d6ae4074ef48ca17514348
/cg-maze-src/student_view2d.h
0e6db5447ca1c893d4dbcad584fad620c3172d6d
[]
no_license
kassaus/cg-paba-2011
faafe4eb351afea972d47105353de8a177657002
45fb0f764562df45a1e09e1ef579c15c089224f5
refs/heads/master
2016-09-01T23:17:55.207855
2011-07-01T22:05:11
2011-07-01T22:05:11
32,128,305
0
0
null
null
null
null
UTF-8
C++
false
false
2,245
h
/* Labirinto para Computacao Grafica (CG). (C) 2010 Pedro Freire (www.pedrofreire.com) Licenca Creative Commons: Atribuicao - Uso Nao-Comercial - Partilha nos termos da mesma Licenca http://creativecommons.org/licenses/by-nc-sa/2.5/pt/ Computer Graphics Maze. (C) 2010 Pedro Freire (www.pedrofreire.com) All comments in Portuguese. Creative Commons license: Attribution - Noncommercial - Share Alike http://creativecommons.org/licenses/by-nc-sa/2.5/pt/deed.en_US ============================================================================= #### Podes alterar este ficheiro ############################################ ============================================================================= */ #ifndef VIEW2D_H #define VIEW2D_H #include <QtOpenGL> #include "map.h" #include "compass.h" // Isto e' quer a largura quer a altura, porque vamos usar um quadrado // (em termos de coordenadas) e o OpenGL faz a conversao para o rectangulo // visivel. #define VIEW2D_SIZE 100.0 // Estas coordenadas (com o 0,0 ao centro) facilitam o calculo das coordenadas // da vista, ja' que te^m uma simetria ao centro #define VIEW2D_LEFT (-VIEW2D_SIZE / 2.0) #define VIEW2D_RIGHT ( VIEW2D_SIZE / 2.0) #define VIEW2D_TOP ( VIEW2D_SIZE / 2.0) #define VIEW2D_BOTTOM (-VIEW2D_SIZE / 2.0) // Numero de celulas do mapa desenhadas no ecra #define VIEW2D_DEPTH 100 // Cores #define VIEW2D_COLOR_3UB_CEILING 0xBD, 0xBE, 0xC0 #define VIEW2D_COLOR_3UB_WALL 0xB8, 0xB8, 0xF0 // 0x99, 0x99, 0xCB #define VIEW2D_COLOR_3UB_WALL_OUTLINE 0x99, 0x99, 0xCB #define VIEW2D_COLOR_3UB_DOOR_OPEN VIEW2D_COLOR_3UB_WALL // Nao usada #define VIEW2D_COLOR_3UB_DOOR_CLOSED VIEW2D_COLOR_3UB_WALL // Nao usada #define VIEW2D_COLOR_3UB_FLOOR 0xB1, 0x89, 0x4E // 0x66, 0x4F, 0x2D #define VIEW2D_COLOR_3UB_PLAYER1 0xFF, 0x33, 0x33 // Nao usada class View2D { private: Map *map; void drawWall( GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2 ); public: View2D( Map *map ); // Atencao que "map" pode ser NULL! void resize( int view_width, int view_height ); void paint( int x, int y, Compass compass ); }; #endif // VIEW2D_H
[ "antonio.gaspar.lourenco@6f8a15bf-34ff-41e7-c7d0-ef52abd84952" ]
[ [ [ 1, 66 ] ] ]
9b762f342cc94b11946b2b9c842a8c599b5d9734
b957e10ed5376dbe85c07bdef1f510f641984a1a
/Graphics.h
743bfe68f021f825f7f80d92ffc8e26ffa0d82f5
[]
no_license
alexjshank/motors
063245c206df936a886f72a22f0f15c78e1129cb
7193b729466d8caece267f0b8ddbf16d99c13f8a
refs/heads/master
2016-09-10T15:47:20.906269
2009-11-04T18:41:21
2009-11-04T18:41:21
33,394,870
0
0
null
null
null
null
UTF-8
C++
false
false
856
h
#include "task.h" #include <SDL.h> #include <SDL_opengl.h> #include <GL/gl.h> // Header File For The OpenGL32 Library #include <GL/glu.h> // Header File For The GLu32 Library #include "vector.h" #include "printer.h" // text printing (ie- font rendering) #ifndef __GRAPHICS__H__ #define __GRAPHICS__H__ class Graphics : public Task { public: Graphics(void); ~Graphics(void); bool init(); void pause(); bool stop(); void run(); int LoadTexture(const char *filename); Printer text; }; void DrawCube(Vector pos, Vector scale); void DrawQuad(Vector,Vector); void DrawSkybox(); extern PFNGLFOGCOORDFEXTPROC glFogCoordfEXT; extern PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB; extern PFNGLACTIVETEXTUREARBPROC glActiveTextureARB; extern PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTextureARB; #endif
[ "alexjshank@0c9e2a0d-1447-0410-93de-f5a27bb8667b" ]
[ [ [ 1, 39 ] ] ]
45b558385c9460bb4bdc97de34038a0c54bcaeb4
9a2957092fa62363f6f1fe564a06fa2bac56beae
/src/exponencial.h
6534247e0fd6c3eef031ea20ea33402bd35fe65c
[]
no_license
rafaelol/ad20102
3e6f15eb978cfa696f59a84631d47f03228e3d85
04743452e2de7740dcdd5765ff857fba7ef913f4
refs/heads/master
2021-01-19T00:18:52.764072
2010-11-25T16:41:17
2010-11-25T16:41:17
32,990,179
0
0
null
null
null
null
UTF-8
C++
false
false
2,798
h
#ifndef EXPONENCIAL_H_ #define EXPONENCIAL_H_ #include <cstdlib> #include <cmath> #include <sys/time.h> namespace TrabalhoAD { /** * \brief A classe DistExponencial representa um gerador pseudo-aleatório de tempos entre chegadas exponencialmente distribuídas. * * A semente que inicalizou a classe ficará sempre guardada. Desta forma, * será possível recupera-la e repetir os testes de forma precisa para verificar * o funcionamento do simulador. \n * * A geração é feita através da função inversa da PDF da distribuição * exponencial. \n * * \warning Esta classe não utiliza métodos tradicionais como srand() e rand() * para a geração de números pseudo-aleatórios e sim as funções * drand48_r() e srand48_r() pois, além delas retornarem um número pseudo-aleatório * uniformemente distribuído entre [0.0, 1.0), estas funções são re-entrantes, o que * evita problemas no caso do simulador, onde teremos mais de um classe deste tipo gerando * tempos de chegada concomitantemente. Estes métodos não estão presentes nativamente no * MingW, assim, para compilar o código em ambiente Windows, é necessário ferramentas como * o CygWin. */ class DistExponencial { private: long int m_semente; /**< Guarda a semente inicial, importante para garantirmos a uniformidade dos testes */ struct drand48_data m_estado_prng; /**< Guarda o estado do gerador de números pseudo-aleatórios */ double m_taxa; /**< Taxa lambda */ bool m_deterministico; /**< Indica se o gerador deve rodar em modo determinístico ou não. */ /** * Reversa da função exponencial. * * \param prob Probabilidade [0.0, 1.0) */ double inversa(double prob); public: /** * Construtor da classe DistExponencial. \n * Este construtor irá inicializar o gerador de números pseudo-aleatórios com o valor de gettimeofday(). \n * * \param taxa Taxa lambda da distribuição exponencial. */ DistExponencial(double taxa); /** * Construtor da classe DistExponencial. * * \param taxa Taxa lambda da distribuição exponencial. * \param semente Semente inicial do gerador. */ DistExponencial(double taxa, long int semente); /** * Retorna a semente inicial do gerador acoplado a esta distribuição exponencial */ long int semente() const; /** * Retorna o tempo até a próxima chegada. */ double proxima_chegada(); /** * Ativa ou desativa o modo deterministico. * * \param ativado TRUE para ativar o modo determinístico, FALSE para desativar. */ void determistico(bool ativado); }; } #endif //EXPONENCIAL_H_
[ "bruno.buss@07721b43-8a56-793e-f54c-8f9880f99319", "rafaoliveiralopes@07721b43-8a56-793e-f54c-8f9880f99319", "yanko.oliveira@07721b43-8a56-793e-f54c-8f9880f99319", "[email protected]@07721b43-8a56-793e-f54c-8f9880f99319" ]
[ [ [ 1, 8 ], [ 10, 10 ], [ 36, 37 ], [ 44, 44 ], [ 53, 53 ], [ 61, 61 ], [ 66, 66 ], [ 68, 68 ], [ 72, 72 ], [ 76, 76 ], [ 79, 82 ] ], [ [ 9, 9 ], [ 11, 13 ], [ 15, 17 ], [ 19, 20 ], [ 29, 32 ], [ 34, 35 ], [ 38, 43 ], [ 45, 52 ], [ 54, 60 ], [ 62, 65 ], [ 67, 67 ], [ 69, 70 ], [ 78, 78 ] ], [ [ 14, 14 ], [ 18, 18 ], [ 21, 28 ], [ 33, 33 ] ], [ [ 71, 71 ], [ 73, 75 ], [ 77, 77 ] ] ]
682639626ecdc7b72334bea7309178ee57d7b518
cfa6cdfaba310a2fd5f89326690b5c48c6872a2a
/Sources/Server/M-Server Manager/M-Server Manager/M-Server ManagerView.h
f98c9b733f2da12e47fc96ee51e34679607dad12
[]
no_license
asdlei00/project-jb
1cc70130020a5904e0e6a46ace8944a431a358f6
0bfaa84ddab946c90245f539c1e7c2e75f65a5c0
refs/heads/master
2020-05-07T21:41:16.420207
2009-09-12T03:40:17
2009-09-12T03:40:17
40,292,178
0
0
null
null
null
null
UHC
C++
false
false
2,021
h
// M-Server ManagerView.h : CMServerManagerView 클래스의 인터페이스 // #pragma once #include "LogDlg.h" #include "UserDlg.h" #include "afxwin.h" class CMServerManagerView : public CFormView { protected: // serialization에서만 만들어집니다. CMServerManagerView(); DECLARE_DYNCREATE(CMServerManagerView) public: enum{ IDD = IDD_MSERVERMANAGER_FORM }; // 특성입니다. public: CMServerManagerDoc* GetDocument() const; // 작업입니다. public: CBrush m_Brush; // 재정의입니다. public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다. virtual void OnInitialUpdate(); // 생성 후 처음 호출되었습니다. // 구현입니다. public: virtual ~CMServerManagerView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: CMFCTabCtrl m_mfcTab; void OnTabColor(); afx_msg LONG OnClientReceive(UINT wParam, LONG lParam); afx_msg LONG OnClientConnect(UINT wParam, LONG lParam); afx_msg LONG OnClientClose(UINT wParam, LONG lParam); afx_msg LONG OnClientAccept(UINT wParam, LONG lParam); afx_msg LONG OnClientNetDown(UINT wParam, LONG lParam); // 생성된 메시지 맵 함수 protected: afx_msg void OnFilePrintPreview(); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); DECLARE_MESSAGE_MAP() public: afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); CStatic m_stcTab; afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnAccountManage(); afx_msg void OnButtonAccountManage256(); afx_msg void OnButtonRun(); afx_msg void OnButtonStop(); }; #ifndef _DEBUG // M-Server ManagerView.cpp의 디버그 버전 inline CMServerManagerDoc* CMServerManagerView::GetDocument() const { return reinterpret_cast<CMServerManagerDoc*>(m_pDocument); } #endif
[ [ [ 1, 64 ], [ 69, 75 ] ], [ [ 65, 68 ] ] ]
0e04e19c74e749d83c746fd781b62f5d77ae34c5
df238aa31eb8c74e2c208188109813272472beec
/BCGInclude/BCGPStatic.h
a3b098fb1f2bf2d2003d90abdea4348488745226
[]
no_license
myme5261314/plugin-system
d3166f36972c73f74768faae00ac9b6e0d58d862
be490acba46c7f0d561adc373acd840201c0570c
refs/heads/master
2020-03-29T20:00:01.155206
2011-06-27T15:23:30
2011-06-27T15:23:30
39,724,191
0
0
null
null
null
null
UTF-8
C++
false
false
1,788
h
#if !defined(AFX_BCGPSTATIC_H__A34CC2CA_E7ED_4D03_93F4_E2513841C22C__INCLUDED_) #define AFX_BCGPSTATIC_H__A34CC2CA_E7ED_4D03_93F4_E2513841C22C__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of the BCGControlBar Library // Copyright (C) 1998-2008 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // // BCGPStatic.h : header file // #include "BCGCBPro.h" ///////////////////////////////////////////////////////////////////////////// // CBCGPStatic window class BCGCBPRODLLEXPORT CBCGPStatic : public CStatic { // Construction public: CBCGPStatic(); // Attributes public: BOOL m_bOnGlass; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBCGPStatic) //}}AFX_VIRTUAL // Implementation public: virtual ~CBCGPStatic(); // Generated message map functions protected: //{{AFX_MSG(CBCGPStatic) afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnPaint(); //}}AFX_MSG afx_msg LRESULT OnBCGSetControlAero (WPARAM, LPARAM); afx_msg LRESULT OnSetText (WPARAM, LPARAM lp); DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BCGPSTATIC_H__A34CC2CA_E7ED_4D03_93F4_E2513841C22C__INCLUDED_)
[ "myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5" ]
[ [ [ 1, 66 ] ] ]
e288b868b272a48b5174976812a23c8d270949c5
188058ec6dbe8b1a74bf584ecfa7843be560d2e5
/GodDK/mutex.h
a42f667c087c31bc53fee152ecfc9e7e7a73a735
[]
no_license
mason105/red5cpp
636e82c660942e2b39c4bfebc63175c8539f7df0
fcf1152cb0a31560af397f24a46b8402e854536e
refs/heads/master
2021-01-10T07:21:31.412996
2007-08-23T06:29:17
2007-08-23T06:29:17
36,223,621
0
0
null
null
null
null
UTF-8
C++
false
false
3,547
h
/* * Copyright (c) 2004 Beeyond Software Holding BV * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*!\file mutex.h * \brief MUTually EXclusive lock class. * \author Bob Deblier <[email protected]> * \ingroup CXX_m */ #ifndef _CLASS_BEECRYPT_MUTEX_H #define _CLASS_BEECRYPT_MUTEX_H #include "beecrypt/api.h" #ifdef __cplusplus #if HAVE_ERRNO_H # include <errno.h> #endif namespace beecrypt { class BEECRYPTCXXAPI mutex { private: bc_mutex_t _lock; public: inline void init() throw (char*) { #if WIN32 _lock = CreateMutex((LPSECURITY_ATTRIBUTES) 0, FALSE, (LPCSTR) 0); if (!_lock) throw "CreateMutex failed"; #else register int rc; # if HAVE_SYNCH_H if ((rc = mutex_init(&_lock, USYNC_THREAD, 0))) throw strerror(rc); # elif HAVE_PTHREAD_H if ((rc = pthread_mutex_init(&_lock, 0))) throw strerror(rc); # else # error # endif #endif } inline void lock() throw (char*) { #if WIN32 if (WaitForSingleObject(_lock, INFINITE) == WAIT_OBJECT_0) return; throw "WaitForSingleObject failed"; #else register int rc; # if HAVE_SYNCH_H if ((rc = mutex_lock(&_lock))) throw strerror(rc); # elif HAVE_PTHREAD_H if ((rc = pthread_mutex_lock(&_lock))) throw strerror(rc); # else # error # endif #endif } inline bool trylock() throw (char*) { #if WIN32 switch (WaitForSingleObject(_lock, 0)) { case WAIT_TIMEOUT: return false; case WAIT_OBJECT_0: return true; default: throw "WaitForSingleObbject failed"; } #else register int rc; # if HAVE_SYNCH_H if ((rc = mutex_trylock(&_lock)) == 0) return true; if (rc == EBUSY) return false; throw strerror(rc); # elif HAVE_PTHREAD_H if ((rc = pthread_mutex_trylock(&_lock)) == 0) return true; if (rc == EBUSY) return false; throw strerror(rc); # else # error # endif #endif } inline void unlock() throw (char*) { #if WIN32 if (!ReleaseMutex(_lock)) throw "ReleaseMutex failed"; #else register int rc; # if HAVE_SYNCH_H if ((rc = mutex_unlock(&_lock))) throw strerror(rc); # elif HAVE_PTHREAD_H if ((rc = pthread_mutex_unlock(&_lock))) throw strerror(rc); # else # error # endif #endif } inline void destroy() throw (char*) { #if WIN32 if (!CloseHandle(_lock)) throw "CloseHandle failed"; #else register int rc; # if HAVE_SYNCH_H if ((rc = mutex_destroy(&_lock))) throw strerror(rc); # elif HAVE_PTHREAD_H if ((rc = pthread_mutex_destroy(&_lock))) throw strerror(rc); # else # error # endif #endif } }; } #endif #endif
[ "soaris@46205fef-a337-0410-8429-7db05d171fc8" ]
[ [ [ 1, 157 ] ] ]
3f275c1739a4477a4082edbc7d39d1ac23ecd03b
c8ab6c440f0e70e848c5f69ccbbfd9fe2913fbad
/bowling/include/cyclone/pfgen.cpp
fbe8563fc0974c0aac4714d9f6950b1ac14726ce
[]
no_license
alyshamsy/power-bowling
2b6426cfd4feb355928de95f1840bd39eb88de0b
dd650b2a8e146f6cdf7b6ce703801b96360a90fe
refs/heads/master
2020-12-24T16:50:09.092801
2011-05-12T14:37:15
2011-05-12T14:37:15
32,115,585
0
0
null
null
null
null
UTF-8
C++
false
false
7,036
cpp
/* * Implementation file for the particle force generators. * * Part of the Cyclone physics system. * * Copyright (c) Icosagon 2003. All Rights Reserved. * * This software is distributed under licence. Use of this software * implies agreement with all terms and conditions of the accompanying * software licence. */ ///>ParticleFGUpdate #include <cyclone/pfgen.h> using namespace cyclone; ///<ParticleFGUpdate ///>ParticleFGUpdate void ParticleForceRegistry::updateForces(real duration) { Registry::iterator i = registrations.begin(); for (; i != registrations.end(); i++) { i->fg->updateForce(i->particle, duration); } } void ParticleForceRegistry::add(Particle* particle, ParticleForceGenerator *fg) { ParticleForceRegistry::ParticleForceRegistration registration; registration.particle = particle; registration.fg = fg; registrations.push_back(registration); } ///<ParticleFGUpdate ParticleGravity::ParticleGravity(const Vector3& gravity) : gravity(gravity) { } ///>GravityPFG void ParticleGravity::updateForce(Particle* particle, real duration) { // Check that we do not have infinite mass if (!particle->hasFiniteMass()) return; // Apply the mass-scaled force to the particle particle->addForce(gravity * particle->getMass()); } ///<GravityPFG ParticleDrag::ParticleDrag(real k1, real k2) : k1(k1), k2(k2) { } ///>DragPFG void ParticleDrag::updateForce(Particle* particle, real duration) { Vector3 force; particle->getVelocity(&force); // Calculate the total drag coefficient real dragCoeff = force.magnitude(); dragCoeff = k1 * dragCoeff + k2 * dragCoeff * dragCoeff; // Calculate the final force and apply it force.normalise(); force *= -dragCoeff; particle->addForce(force); } ///<DragPFG ParticleSpring::ParticleSpring(Particle *other, real sc, real rl) : other(other), springConstant(sc), restLength(rl) { } ///>SpringPFG void ParticleSpring::updateForce(Particle* particle, real duration) { // Calculate the vector of the spring Vector3 force; particle->getPosition(&force); force -= other->getPosition(); // Calculate the magnitude of the force real magnitude = force.magnitude(); magnitude = real_abs(magnitude - restLength); magnitude *= springConstant; // Calculate the final force and apply it force.normalise(); force *= -magnitude; particle->addForce(force); } ///<SpringPFG ParticleBuoyancy::ParticleBuoyancy(real maxDepth, real volume, real waterHeight, real liquidDensity) : maxDepth(maxDepth), volume(volume), waterHeight(waterHeight), liquidDensity(liquidDensity) { } ///>BoyancyPFG void ParticleBuoyancy::updateForce(Particle* particle, real duration) { // Calculate the submersion depth real depth = particle->getPosition().y; // Check if we're out of the water if (depth >= waterHeight + maxDepth) return; Vector3 force(0,0,0); // Check if we're at maximum depth if (depth <= waterHeight - maxDepth) { force.y = liquidDensity * volume; particle->addForce(force); return; } // Otherwise we are partly submerged force.y = liquidDensity * volume * (depth - maxDepth - waterHeight) / 2 * maxDepth; particle->addForce(force); } ///<BoyancyPFG ParticleBungee::ParticleBungee(Particle *other, real sc, real rl) : other(other), springConstant(sc), restLength(rl) { } ///>BungeePFG void ParticleBungee::updateForce(Particle* particle, real duration) { // Calculate the vector of the spring Vector3 force; particle->getPosition(&force); force -= other->getPosition(); // Check if the bungee is compressed real magnitude = force.magnitude(); if (magnitude <= restLength) return; // Calculate the magnitude of the force magnitude = springConstant * (restLength - magnitude); // Calculate the final force and apply it force.normalise(); force *= -magnitude; particle->addForce(force); } ///<BungeePFG ParticleFakeSpring::ParticleFakeSpring(Vector3 *anchor, real sc, real d) : anchor(anchor), springConstant(sc), damping(d) { } ///>FakeSpringPFG void ParticleFakeSpring::updateForce(Particle* particle, real duration) { // Check that we do not have infinite mass if (!particle->hasFiniteMass()) return; // Calculate the relative position of the particle to the anchor Vector3 position; particle->getPosition(&position); position -= *anchor; // Calculate the constants and check they are in bounds. real gamma = 0.5f * real_sqrt(4 * springConstant - damping*damping); if (gamma == 0.0f) return; Vector3 c = position * (damping / (2.0f * gamma)) + particle->getVelocity() * (1.0f / gamma); // Calculate the target position Vector3 target = position * real_cos(gamma * duration) + c * real_sin(gamma * duration); target *= real_exp(-0.5f * duration * damping); // Calculate the resulting acceleration and therefore the force Vector3 accel = (target - position) * (1.0f / duration*duration) - particle->getVelocity() * duration; particle->addForce(accel * particle->getMass()); } ///<FakeSpringPFG ParticleAnchoredSpring::ParticleAnchoredSpring() { } ParticleAnchoredSpring::ParticleAnchoredSpring(Vector3 *anchor, real sc, real rl) : anchor(anchor), springConstant(sc), restLength(rl) { } void ParticleAnchoredSpring::init(Vector3 *anchor, real springConstant, real restLength) { ParticleAnchoredSpring::anchor = anchor; ParticleAnchoredSpring::springConstant = springConstant; ParticleAnchoredSpring::restLength = restLength; } ///>ASpringPFG void ParticleAnchoredBungee::updateForce(Particle* particle, real duration) { // Calculate the vector of the spring Vector3 force; particle->getPosition(&force); force -= *anchor; // Calculate the magnitude of the force real magnitude = force.magnitude(); if (magnitude < restLength) return; magnitude = magnitude - restLength; magnitude *= springConstant; // Calculate the final force and apply it force.normalise(); force *= -magnitude; particle->addForce(force); } void ParticleAnchoredSpring::updateForce(Particle* particle, real duration) { // Calculate the vector of the spring Vector3 force; particle->getPosition(&force); force -= *anchor; // Calculate the magnitude of the force real magnitude = force.magnitude(); magnitude = real_abs(magnitude - restLength); magnitude *= springConstant; // Calculate the final force and apply it force.normalise(); force *= -magnitude; particle->addForce(force); } ///<ASpringPFG
[ "aly.shamsy@71b57f4a-8c0b-a9ba-d1fe-6729e2c2215a" ]
[ [ [ 1, 256 ] ] ]
adbbbfda0683f3694974700f51bbd2d7a8bfd9d6
bd89d3607e32d7ebb8898f5e2d3445d524010850
/connectivitylayer/isce/isirouter_dll/src/isicltransceiver.cpp
5c31c233d55c90ec3442fdc35ebba99e8596b224
[]
no_license
wannaphong/symbian-incubation-projects.fcl-modemadaptation
9b9c61ba714ca8a786db01afda8f5a066420c0db
0e6894da14b3b096cffe0182cedecc9b6dac7b8d
refs/heads/master
2021-05-30T05:09:10.980036
2010-10-19T10:16:20
2010-10-19T10:16:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
30,610
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include <kernel.h> // For Kern #include <pn_const.h> // For PN_OBJ_ROUTING_REQ #include <phonetisi.h> // For ISI_HEADER_OFFSET_... #include <commisi.h> // For COMMON_ISA_... #include "isirouter.h" // For DISIRouter #include "isiroutertrace.h" // For C_TRACE, ASSERT_RESET.. and fault codes #include "misirouterlinkif.h" // For MISIRouterLinkIf #include "isihelpers.h" // For GET_SENDER_DEV... #include "memapi.h" // For MemApi #include <trxdefs.h> // For ETrxTest... #include "isicltransceiver.h" // For DISICLTransceiver #include <nsisi.h> // For PN_NAMESERVICE... #include "isirouterservice.h" // For DIsiRouterService #include "isimsgqueue.h" // For DISIMsgQueue #include "iscnokiadefinitions.h" // For EIscNokiaUsbPhonetLink #ifdef USE_MEDIAAPI #include <pn_isimedia_const.h> // For PN_DEV_PC #endif /* USE_MEDIAAPI */ // Faults enum TISICLTransceiverFaults { EISICLTransceiverMemAllocFailure = 0x01, EISICLTransceiverMemAllocFailure1, EISICLTransceiverMemAllocFailure2, EISICLTransceiverMemAllocFailure3, EISICLTransceiverMemAllocFailure4, EISICLTransceiverMemAllocFailure5, EISICLTransceiverMemAllocFailure6, EISICLTransceiverMemAllocFailure7, EISICLTransceiverMemAllocFailure8, #ifdef USE_MEDIAAPI EISICLTransceiverMemAllocFailure9, EISICLTransceiverMemAllocFailure10, #endif /* USE_MEDIAAPI */ EISICLTransceiverNotSupportedMedia, EISICLTransceiverOverTheLimits, EISICLTransceiverNULLPtr, EISICLTransceiverNULLPtr2, EISICLTransceiverNULLPtr3, EISICLTransceiverNULLPtr4, EISICLTransceiverNULLPtr5, EISICLTransceiverNULLPtr6, EISICLTransceiverNULLPtr7, EISICLTransceiverNotSupportedDevice, EISICLTransceiverDeviceConnection, EISICLTransceiverCommIsaEntityNotReachableResp, EISICLTransceiverNotThreadContext, EISICLTransceiverMutexCreateFailed, EISICLTransceiverMutexWaitFailed, EISICLTransceiverMutexWaitFailed2, }; // Constants const TInt KDfcPriority( 5 ); DMutex* DISICLTransceiver::iDynamicDeviceTableMutex = NULL; _LIT8( KISICLTransceiverMutex, "ISICLTransceiverMutex" ); DISICLTransceiver::DISICLTransceiver( DISIRouter& aRouter, TDfcQue* aThreadPtr ) : iShRouter( aRouter ) { C_TRACE( ( _T( "DISICLTransceiver::DISICLTransceiver>" ) ) ); ASSERT_RESET_ALWAYS( aThreadPtr, ( EISICLTransceiverNULLPtr7 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); iShStateChangedDfc = new TDfc( StateChangedDfc, this, aThreadPtr, KDfcPriority ); ASSERT_RESET_ALWAYS( iShStateChangedDfc, ( EISICLTransceiverMemAllocFailure6 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); iRxQueueDfc = new TDfc( RxQueueDfc, this, aThreadPtr, KDfcPriority ); ASSERT_RESET_ALWAYS( iShStateChangedDfc, ( EISICLTransceiverMemAllocFailure8 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); DISIDevice* dev = new DISIDevice( PN_DEV_MODEM, MISIRouterLinkIf::CreateLinkF( this, PN_MEDIA_MODEM_HOST_IF, ETrxSharedMemory) ); ASSERT_RESET_ALWAYS( dev, ( EISICLTransceiverMemAllocFailure3 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); iShDevices.Append( dev ); #ifdef USE_MEDIAAPI DISIDevice* dev2 = new DISIDevice( PN_DEV_PC, // append to dynamic table if needed MISIRouterLinkIf::CreateLinkF( this, PN_MEDIA_USB, ETrxUSB ) ); ASSERT_RESET_ALWAYS( dev2, ( EISICLTransceiverMemAllocFailure9 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); iShDevices.Append( dev2 ); DISIDevice* dev4 = new DISIDevice( PN_DEV_PC, // append to dynamic table if needed MISIRouterLinkIf::CreateLinkF( this, PN_MEDIA_BT, ETrxBT ) ); ASSERT_RESET_ALWAYS( dev4, ( EISICLTransceiverMemAllocFailure10 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); iShDevices.Append( dev4 ); #endif /* USE_MEDIAAPI */ DISIDevice* dev3 = new DISIDevice( PN_DEV_DUMMYIST, MISIRouterLinkIf::CreateLinkF( this, PN_MEDIA_TEST, ETrxTest ) ); ASSERT_RESET_ALWAYS( dev3, ( EISICLTransceiverMemAllocFailure5 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); iShDevices.Append( dev3 ); iRouterService = new DIsiRouterService( *this ); ASSERT_RESET_ALWAYS( iRouterService, ( EISICLTransceiverMemAllocFailure2 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); iRxQueue = new DISIMsgQueue( KISIMainRxQueueSize ); ASSERT_RESET_ALWAYS( iRxQueue, ( EISICLTransceiverMemAllocFailure7 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); TInt err( Kern::MutexCreate( iDynamicDeviceTableMutex, KISICLTransceiverMutex, KMutexOrdGeneral0 ) ); ASSERT_RESET_ALWAYS( ( KErrNone == err ), ( EISICLTransceiverMutexCreateFailed | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); #ifdef USE_MEDIAAPI iDevPcLastSendTrxId = EAmountOfTrxs; //put a maxvalue iDevPcLastActiveTrxId = EAmountOfTrxs; //put a maxvalue #endif /* USE_MEDIAAPI */ C_TRACE( ( _T( "DISICLTransceiver::DISICLTransceiver<" ) ) ); } DISICLTransceiver::~DISICLTransceiver() { C_TRACE( ( _T( "DISICLTransceiver::~DISICLTransceiver>" ) ) ); iShDevices.ResetAndDestroy(); if ( iRouterService ) { delete iRouterService; iRouterService = NULL; } if ( iShStateChangedDfc ) { iShStateChangedDfc->Cancel(); delete iShStateChangedDfc; iShStateChangedDfc = NULL; } if( iRxQueue ) { C_TRACE( ( _T( "DISICLTransceiver::ResetQueues 0x%x iRxQueue 0x%x" ), this, iRxQueue ) ); while( iRxQueue->Count() ) { MemApi::DeallocBlock( iRxQueue->Get() ); } } if( iRxQueueDfc ) { C_TRACE( ( _T( "DISIUserChannel::~DISIUserChannel 0x%x iRxQueueDfc 0x%x" ), this, iRxQueueDfc ) ); iRxQueueDfc->Cancel(); delete iRxQueueDfc; iRxQueueDfc = NULL; } C_TRACE( ( _T( "DISICLTransceiver::~DISICLTransceiver<" ) ) ); } TInt DISICLTransceiver::SendCommIsaEntityNotReachableResp( TDes8& aNotDeliveredMessage ) { C_TRACE( ( _T( "DISICLTransceiver::SendCommIsaEntityNotReachableResp 0x%x>" ), &aNotDeliveredMessage ) ); const TUint8* notDeliveredMsgPtr( aNotDeliveredMessage.Ptr() ); TInt error = KErrAlreadyExists; // Avoid COMM_ISA_ENTITY_NOT_REACHABLE_RESP loop. if( ( notDeliveredMsgPtr[ ISI_HEADER_OFFSET_MESSAGEID ] == COMMON_MESSAGE ) && ( ( notDeliveredMsgPtr[ ISI_HEADER_OFFSET_SUBMESSAGEID ] == COMM_ISA_ENTITY_NOT_REACHABLE_RESP ) || ( notDeliveredMsgPtr[ ISI_HEADER_OFFSET_SUBMESSAGEID ] == COMM_SERVICE_NOT_IDENTIFIED_RESP ) ) ) { C_TRACE( ( _T( "DISICLTransceiver Not sending another CommIsaEntityNotReachableResp 0x%x 0x%x" ), &aNotDeliveredMessage, notDeliveredMsgPtr[ ISI_HEADER_OFFSET_SUBMESSAGEID ] ) ); } else { // Follows COMM specification: 000.031 TUint8 length( ISI_HEADER_SIZE + SIZE_COMMON_MESSAGE_COMM_ISA_ENTITY_NOT_REACHABLE_RESP ); TDes8& respMsg = MemApi::AllocBlock( length ); ASSERT_RESET_ALWAYS( length > ISI_HEADER_OFFSET_MESSAGEID, ( EISICLTransceiverOverTheLimits | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); TUint8* respMsgPtr = const_cast<TUint8*>( respMsg.Ptr() ); // We start to append from transaction id. respMsg.SetLength( ISI_HEADER_OFFSET_TRANSID ); // Get the header until messageid from prev. message. // Just turn receiver and sender device and object vice versa. respMsgPtr[ ISI_HEADER_OFFSET_MEDIA ] = notDeliveredMsgPtr[ ISI_HEADER_OFFSET_MEDIA ]; SET_RECEIVER_DEV( respMsgPtr, GET_SENDER_DEV( aNotDeliveredMessage ) ); SET_SENDER_DEV ( respMsgPtr, GET_RECEIVER_DEV( aNotDeliveredMessage ) ); respMsgPtr[ ISI_HEADER_OFFSET_RESOURCEID ] = notDeliveredMsgPtr[ ISI_HEADER_OFFSET_RESOURCEID ]; SET_LENGTH( respMsgPtr, ( length - PN_HEADER_SIZE ) ); SET_RECEIVER_OBJ( respMsgPtr, GET_SENDER_OBJ( aNotDeliveredMessage ) ); SET_SENDER_OBJ( respMsgPtr, GET_RECEIVER_OBJ( aNotDeliveredMessage ) ); // Set from undelivered message respMsg.Append( notDeliveredMsgPtr[ ISI_HEADER_OFFSET_TRANSID ] ); // Message Identifier respMsg.Append( COMMON_MESSAGE ); // Sub message Identifier. respMsg.Append( COMM_ISA_ENTITY_NOT_REACHABLE_RESP ); // Not Delivered Message from original message. respMsg.Append( notDeliveredMsgPtr[ ISI_HEADER_OFFSET_MESSAGEID ] ); // Status respMsg.Append( COMM_ISA_ENTITY_NOT_AVAILABLE );// different status in a case of device not existing // Filler const TUint8 KFiller( 0x00 ); respMsg.Append( KFiller ); // Filler respMsg.Append( KFiller ); // Filler respMsg.Append( KFiller ); error = RouteISIMessage( respMsg, EFalse ); // Programming error in this function if below assert is raised ASSERT_RESET_ALWAYS( KErrNone == error, ( EISICLTransceiverCommIsaEntityNotReachableResp | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); } MemApi::DeallocBlock( aNotDeliveredMessage ); C_TRACE( ( _T( "DISICLTransceiver::SendCommIsaEntityNotReachableResp 0x%x<" ), &aNotDeliveredMessage ) ); return error; } // This is called in 1...N thread contextes void DISICLTransceiver::ReceiveISIMessage( const TDesC8& aMessage, const TUint8 aTrxId ) { C_TRACE( ( _T( "DISICLTransceiver::ReceiveMsg 0x%x 0x%x 0x%x>" ), this, &aMessage, aTrxId ) ); // Can only be called from thread context. ASSERT_THREAD_CONTEXT_ALWAYS( ( EISICLTransceiverNotThreadContext | EDISIUserChannelTraceId << KClassIdentifierShift ) ); TUint8 txDevId = GET_SENDER_DEV( aMessage.Ptr() ); if ( DynamicDevice( txDevId ) ) { TUint8 staticDevId(0); const TInt count( iShDevices.Count() ); TInt index(0); TBool staticDeviceFound(EFalse); MISIRouterLinkIf* Link = NULL; while( !staticDeviceFound && ( index < count ) ) { C_TRACE( ( _T( "DISICLTransceiver::ReceiveMsg find static device for trx 0x%x index %d" ), aTrxId, index ) ); DISIDevice* tmpDevice = iShDevices[ index ]; ASSERT_RESET_ALWAYS( tmpDevice, ( EISICLTransceiverNULLPtr4 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); tmpDevice->LockDeviceFM(); Link = tmpDevice->GetLink(); if( Link->GetTrxId() == aTrxId ) { staticDevId = tmpDevice->GetDeviceIdentifier(); tmpDevice->FreeDeviceFM(); C_TRACE( ( _T( "DISICLTransceiver::ReceiveMsg static device 0x%x trx 0x%x" ), this, &aMessage, aTrxId ) ); staticDeviceFound = ETrue; } else { tmpDevice->FreeDeviceFM(); } index++; } #ifdef USE_MEDIAAPI if ( PN_DEV_PC == GET_SENDER_DEV( aMessage.Ptr() )) { C_TRACE( ( _T( "DISICLTransceiver::ReceiveMsg 0x%x 0x%x trx id = %d<" ), this, &aMessage, (Link->GetTrxId()) ) ); iDevPcLastActiveTrxId = iDevPcLastSendTrxId; iDevPcLastSendTrxId = Link->GetTrxId(); } #endif /* USE_MEDIAAPI */ UpdateDynamicDeviceTable( txDevId, staticDevId ); } // else static device. No need to save trxId iRxQueue->Add( aMessage ); iRxQueueDfc->Enque(); C_TRACE( ( _T( "DISICLTransceiver::ReceiveMsg 0x%x 0x%x 0x%x<" ), this, &aMessage, aTrxId ) ); } void DISICLTransceiver::RxQueueDfc( TAny* aPtr // Pointer to this object. ) { C_TRACE( ( _T( "DISICLTransceiver::RxQueueDfc ->" ) ) ); DISICLTransceiver& tmp = *reinterpret_cast<DISICLTransceiver*>( aPtr ); if( tmp.iRxQueue->Count() > 0 ) { TDes8& msg( tmp.iRxQueue->Get() ); tmp.RouteISIMessage( msg, EFalse ); // Check here too to avoid unnecessary dfc queuing. if( tmp.iRxQueue->Count() > 0 ) { C_TRACE( ( _T( "DISICLTransceiver::RxQueueDfc enque RxQueueDfc" ) ) ); tmp.iRxQueueDfc->Enque(); } } C_TRACE( ( _T( "DISICLTransceiver::RxQueueDfc <-" ) ) ); } TInt DISICLTransceiver::RouteISIMessage( TDes8& aMessage, TBool aDynamicSenderCheckNeeded ) { C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage 0x%x 0x%x> len %d" ), &aMessage, aDynamicSenderCheckNeeded, aMessage.Length() ) ); const TUint8* msgPtr = aMessage.Ptr(); ISIMESSAGE_TRACE( aMessage ); TInt error( ValidateISIMessage( aMessage ) ); if( KErrNone != error ) { TRACE_ASSERT_ALWAYS; C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage invalid message 0x%x" ), &aMessage ) ); MemApi::DeallocBlock( aMessage ); } else { TBool sendOk( EFalse ); if ( aDynamicSenderCheckNeeded )// Save dynamic device ids from PN_DEV_OWN { C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage from ISI Router" ) ) ); TUint8 txDeviceIdentifier = GET_SENDER_DEV( aMessage ); if ( DynamicDevice( txDeviceIdentifier ) ) { C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage from ISI Router Dynamic Dev" ) ) ); UpdateDynamicDeviceTable( txDeviceIdentifier, PN_DEV_OWN ); #ifndef USE_MEDIAAPI ASSERT_RESET_ALWAYS( txDeviceIdentifier == PN_DEV_PC, 0xdeaddead );// only supported PN_DEV_PC with EIscNokiaUsbPhonetLink #endif /* USE_MEDIAAPI */ } } TUint8 rxDeviceIdentifier = GET_RECEIVER_DEV( aMessage ); C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage rxDeviceIdentifier 0x%x" ), rxDeviceIdentifier ) ); if ( DynamicDevice( rxDeviceIdentifier ) ) { DynamicToStaticDevice( rxDeviceIdentifier ); C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage rxDeviceIdentifier after 0x%x" ), rxDeviceIdentifier ) ); } if( rxDeviceIdentifier == PN_DEV_OWN ) { C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage PN_DEV_OWN 0x%x" ), &aMessage ) ); TUint16 objId(0xffff); #ifndef USE_MEDIAAPI if ( GET_RECEIVER_DEV( aMessage ) == PN_DEV_PC ) { C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage to PN_DEV_PC in PN_DEV_OWN" )) ); objId = EIscNokiaUsbPhonetLink; } else { objId = GET_RECEIVER_OBJ( aMessage ); } #endif /* USE_MEDIAAPI */ #ifdef USE_MEDIAAPI objId = GET_RECEIVER_OBJ( aMessage ); #endif /* USE_MEDIAAPI */ sendOk = iShRouter.Receive( aMessage, objId ); C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage PN_DEV_OWN 0x%x ok %d" ), &aMessage, sendOk ) ); } else { C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage Not PN_DEV_OWN 0x%x" ), &aMessage ) ); MISIRouterLinkIf* link = NULL; const TInt count( iShDevices.Count() ); for( TInt index( 0 ); index < count; index++ ) { DISIDevice* tmpDevice = iShDevices[ index ]; ASSERT_RESET_ALWAYS( tmpDevice, ( EISICLTransceiverNULLPtr4 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); tmpDevice->LockDeviceFM(); if( tmpDevice->GetDeviceIdentifier() == rxDeviceIdentifier ) { link = tmpDevice->GetLink(); tmpDevice->FreeDeviceFM(); #ifndef USE_MEDIAAPI sendOk = link->Send( aMessage ); break; #endif /* USE_MEDIAAPI */ #ifdef USE_MEDIAAPI if ( GET_RECEIVER_DEV( aMessage ) == PN_DEV_PC ) { C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage PN_DEV_PC %d, %d" ), link->GetTrxId(), iDevPcLastSendTrxId ) ); if(iDevPcLastSendTrxId < EAmountOfTrxs) { if ( link->GetTrxId() == iDevPcLastSendTrxId ) { if (link->StateConnected()) { C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage PN_DEV_PC %d, Msg mediaid 0x%x" ), link->GetTrxId(), msgPtr[ ISI_HEADER_OFFSET_MEDIA ] ) ); sendOk = link->Send( aMessage ); break; } } } else { break; } } else { sendOk = link->Send( aMessage ); break; } #endif /* USE_MEDIAAPI */ } else { tmpDevice->FreeDeviceFM(); } } C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage Not PN_DEV_OWN ok %d" ), &aMessage, sendOk ) ); } if( !sendOk ) { TRACE_ASSERT_ALWAYS; error = SendCommIsaEntityNotReachableResp( aMessage ); } } C_TRACE( ( _T( "DISICLTransceiver::RouteISIMessage 0x%x<" ), &aMessage ) ); return error; } void DISICLTransceiver::GetDeviceConnectionStates( RArray<TUint8>& aDeviceIdentifierList, const TBool aConnectedDevice ) { C_TRACE( ( _T( "DISICLTransceiver::GetDeviceConnectionStates 0x%x 0x%x>" ), &aDeviceIdentifierList, aConnectedDevice ) ); const TInt count( iShDevices.Count() ); for( TInt index( 0 ); index < count; index++ ) { DISIDevice* tmpDevice = iShDevices[ index ]; ASSERT_RESET_ALWAYS( tmpDevice, ( EISICLTransceiverNULLPtr3 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); tmpDevice->LockDeviceFM(); if( tmpDevice->GetDeviceState() == aConnectedDevice ) { const TUint8 deviceIdentifier( tmpDevice->GetDeviceIdentifier() ); tmpDevice->FreeDeviceFM(); aDeviceIdentifierList.Append( deviceIdentifier ); } else { tmpDevice->FreeDeviceFM(); } } C_TRACE( ( _T( "DISICLTransceiver::GetDeviceConnectionStates 0x%x 0x%x<" ), &aDeviceIdentifierList, aConnectedDevice ) ); } // KErrBadDescriptor, if message length too small // KErrUnderFlow, if message length too big. // KErrCouldNotConnect, if receiver object is out of scope. TInt DISICLTransceiver::ValidateISIMessage( TDes8& aMessage ) { C_TRACE( ( _T( "DISICLTransceiver::ValidateISIMessage 0x%x>" ), &aMessage ) ); const TUint16 descLength( aMessage.Length() ); TInt msgOk( KErrNone ); msgOk = ( ISI_HEADER_OFFSET_MESSAGEID >= descLength ) ? KErrBadDescriptor : msgOk; TRACE_ASSERT_INFO( msgOk == KErrNone, msgOk ); // Get ISI message length after known that the descriptor is big enough. const TUint8* msgPtr( aMessage.Ptr() ); const TUint16 isiMsgLength( GET_LENGTH( msgPtr ) + PN_HEADER_SIZE ); // If the descriptor length is less than ISI message length. msgOk = ( ( msgOk == KErrNone && isiMsgLength > descLength ) ? KErrUnderflow : msgOk ); TRACE_ASSERT_INFO( msgOk == KErrNone, msgOk ); // If the ISI message length is bigger that the largest supported. msgOk = ( ( msgOk == KErrNone && isiMsgLength > KMaxISIMsgSize ) ? KErrUnderflow : msgOk ); TRACE_ASSERT_INFO( msgOk == KErrNone, msgOk ); // If the ISI message length with PN_HEADER_SIZE is less or equal than ISI_HEADER_OFFSET_MESSAGEID. msgOk = ( ( msgOk == KErrNone && isiMsgLength <= ISI_HEADER_OFFSET_MESSAGEID ) ? KErrUnderflow : msgOk ); TRACE_ASSERT_INFO( msgOk == KErrNone, msgOk ); TRACE_ASSERT_INFO( msgOk == KErrNone, isiMsgLength ); TRACE_ASSERT_INFO( msgOk == KErrNone, descLength ); C_TRACE( ( _T( "DISICLTransceiver::ValidateISIMessage %d<" ), msgOk ) ); return msgOk; } // NOTE!! Called with FM held. Not allowed to block or nothing. Not even print traces! // Called in N Thread context void DISICLTransceiver::StateChanged( // None ) { iShStateChangedDfc->Enque(); } void DISICLTransceiver::StateChangedDfc( TAny* aPtr ) { C_TRACE( ( _T( "DISICLTransceiver::StateChangedDfc>" ) ) ); DISICLTransceiver* self = reinterpret_cast<DISICLTransceiver*>( aPtr ); ASSERT_RESET_ALWAYS( self, ( EISICLTransceiverNULLPtr5 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); self->ReadStateChanges(); C_TRACE( ( _T( "DISICLTransceiver::StateChangedDfc<" ) ) ); } void DISICLTransceiver::ReadStateChanges( // None ) { C_TRACE( ( _T( "DISICLTransceiver::ReadStateChanges>" ) ) ); const TInt count( iShDevices.Count() ); for( TInt index( 0 ); index < count; index++ ) { DISIDevice* tmpDevice = iShDevices[ index ]; ASSERT_RESET_ALWAYS( tmpDevice, ( EISICLTransceiverNULLPtr6 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); tmpDevice->LockDeviceFM(); const TBool connected = tmpDevice->GetDeviceState();// tee paremmaksi #ifdef USE_MEDIAAPI MISIRouterLinkIf* link = NULL; link = tmpDevice->GetLink(); #endif /* USE_MEDIAAPI */ if( connected != tmpDevice->GetDeviceOldState() ) { tmpDevice->SetDeviceOldState( connected ); const TUint8 deviceIdentifier = tmpDevice->GetDeviceIdentifier(); tmpDevice->FreeDeviceFM(); #ifdef USE_MEDIAAPI C_TRACE( ( _T( "DISICLTransceiver::ReadStateChanges trxid 0x%x state changed>" ),link->GetTrxId() ) ); if( (link->GetTrxId() == iDevPcLastSendTrxId) && (!connected) ) { C_TRACE( ( _T( "DISICLTransceiver::ReadStateChanges trxid 0x%x disconneted>" ),link->GetTrxId() ) ); iDevPcLastSendTrxId = iDevPcLastActiveTrxId; iDevPcLastActiveTrxId = EAmountOfTrxs; //put a maxvalue } #endif /* USE_MEDIAAPI */ iRouterService->SendDeviceConnectionStateChangedInd( connected, deviceIdentifier ); } else { tmpDevice->FreeDeviceFM(); } } C_TRACE( ( _T( "DISICLTransceiver::ReadStateChanges<" ) ) ); } TBool DISICLTransceiver::DynamicDevice( const TUint8 aDevId ) { C_TRACE( ( _T( "DISICLTransceiver::DynamicDevice 0x%x>" ), aDevId ) ); TBool dynamicDevice(EFalse); switch( aDevId ) { case PN_DEV_MODEM: case PN_DEV_DUMMYIST: case PN_DEV_OWN: { //already set as EFalse break; } default: { dynamicDevice = ETrue; break; } } C_TRACE( ( _T( "DISICLTransceiver::DynamicDevice 0x%x<" ), dynamicDevice ) ); return dynamicDevice; } void DISICLTransceiver::UpdateDynamicDeviceTable( const TUint8 aDynamicDevId, const TUint8 aStaticDevId ) { C_TRACE( ( _T( "DISICLTransceiver::UpdateDynamicDeviceTable 0x%x 0x%x>" ), aDynamicDevId, aStaticDevId) ); TBool deviceExist(EFalse); TInt count(iDynamicDeviceTable.Count()); TInt err( Kern::MutexWait( *iDynamicDeviceTableMutex ) ); ASSERT_RESET_ALWAYS( ( err == KErrNone ), ( EISICLTransceiverMutexWaitFailed2 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); for( TUint8 i = 0; i < count; i++ ) { C_TRACE( ( _T( "DISICLTransceiver::UpdateDynamicDeviceTable find dynamic device %d" ), i) ); if( iDynamicDeviceTable[ i ]->iDynamicDevId == aDynamicDevId ) { C_TRACE( ( _T( "DISICLTransceiver::UpdateDynamicDeviceTable dyn dev exist i = %d aDynamicDevId 0x%x staticDevId 0x%x previous 0x%x" ), i, iDynamicDeviceTable[ i ]->iDynamicDevId, aStaticDevId, iDynamicDeviceTable[ i ]->iStaticDevId ) ); iDynamicDeviceTable[ i ]->iStaticDevId = aStaticDevId; deviceExist = ETrue; break; } } if ( !deviceExist ) { C_TRACE( ( _T( "DISICLTransceiver::UpdateDynamicDeviceTable new dynamic device added 0x%x 0x%x" ), aDynamicDevId, aStaticDevId ) ); iDynamicDeviceTable.Append( new TDynamicDevice( aDynamicDevId, aStaticDevId ) ); } Kern::MutexSignal( *iDynamicDeviceTableMutex ); C_TRACE( ( _T( "DISICLTransceiver::UpdateDynamicDeviceTable 0x%x 0x%x<" ), aDynamicDevId, aStaticDevId) ); } void DISICLTransceiver::DynamicToStaticDevice( TUint8& aRxDev ) { C_TRACE( ( _T( "DISICLTransceiver::DynamicToStaticDevice aRxDev>" ), &aRxDev ) ); TInt err( Kern::MutexWait( *iDynamicDeviceTableMutex ) ); ASSERT_RESET_ALWAYS( ( err == KErrNone ), ( EISICLTransceiverMutexWaitFailed | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); for( TUint8 i = 0; i < iDynamicDeviceTable.Count(); i++ ) { if( iDynamicDeviceTable[ i ]->iDynamicDevId == aRxDev ) { C_TRACE( ( _T( "DISICLTransceiver::DynamicToStaticDevice dyn dev exist i = %d iDynamicDevId 0x%x iStaticDevId 0x%x" ), i, iDynamicDeviceTable[ i ]->iDynamicDevId, iDynamicDeviceTable[ i ]->iStaticDevId) ); aRxDev = iDynamicDeviceTable[ i ]->iStaticDevId; break; } } Kern::MutexSignal( *iDynamicDeviceTableMutex ); C_TRACE( ( _T( "DISICLTransceiver::DynamicToStaticDevice aRxDev<" ), &aRxDev ) ); } DISICLTransceiver::DISIDevice::DISIDevice( const TUint8 aDeviceIdentifier, MISIRouterLinkIf* aLink ) { C_TRACE( ( _T( "DISICLTransceiver::DISIDevice::DISIDevice 0x%x 0x%x 0x%x>" ), aDeviceIdentifier, aLink ) ); iShDeviceIdentifier = aDeviceIdentifier; iShOldDeviceConnectedState = EFalse; ASSERT_RESET_ALWAYS( aLink, ( EISICLTransceiverNULLPtr2 | EDISICLTransceiverTraceId << KClassIdentifierShift ) ); iShLink = aLink; iShDeviceMutex = new NFastMutex(); ASSERT_RESET_ALWAYS( iShDeviceMutex, EISICLTransceiverNULLPtr6 | EDISICLTransceiverTraceId << KClassIdentifierShift ); C_TRACE( ( _T( "DISICLTransceiver::DISIDevice::DISIDevice<" ) ) ); } DISICLTransceiver::DISIDevice::~DISIDevice() { C_TRACE( ( _T( "DISICLTransceiver::DISIDevice::~DISIDevice>" ) ) ); iShLink->Release(); iShLink = NULL; // If not exists faulted already. delete iShDeviceMutex; iShDeviceMutex = NULL; C_TRACE( ( _T( "DISICLTransceiver::DISIDevice::~DISIDevice<" ) ) ); } MISIRouterLinkIf* DISICLTransceiver::DISIDevice::GetLink() { // C_TRACE( ( _T( "DISICLTransceiver::DISIDevice::GetLink<> 0x%x" ), iShLink ) ); return iShLink; } TUint8 DISICLTransceiver::DISIDevice::GetDeviceIdentifier() { // C_TRACE( ( _T( "DISICLTransceiver::DISIDevice::GetDeviceIdentifier<> 0x%x" ), iShDeviceIdentifier ) ); return iShDeviceIdentifier; } TBool DISICLTransceiver::DISIDevice::GetDeviceState() { // C_TRACE( ( _T( "DISICLTransceiver::DISIDevice::GetDeviceState<>" ) ) ); return iShLink->StateConnected(); } TBool DISICLTransceiver::DISIDevice::GetDeviceOldState() { // C_TRACE( ( _T( "DISICLTransceiver::DISIDevice::GetDeviceOldState<> 0x%x" ), iShOldDeviceConnectedState ) ); return iShOldDeviceConnectedState; } void DISICLTransceiver::DISIDevice::SetDeviceOldState( TBool aConnected ) { // C_TRACE( ( _T( "DISICLTransceiver::DISIDevice::SetDeviceOldState<> 0x%x 0x%x" ), iShOldDeviceConnectedState, aConnected ) ); iShOldDeviceConnectedState = aConnected; } void DISICLTransceiver::DISIDevice::LockDeviceFM( // None ) { C_TRACE( ( _T( "DISICLTransceiver::DISIDevice::LockDeviceFM<>" ) ) ); NKern::FMWait( iShDeviceMutex ); } void DISICLTransceiver::DISIDevice::FreeDeviceFM( // None ) { NKern::FMSignal( iShDeviceMutex ); C_TRACE( ( _T( "DISICLTransceiver::DISIDevice::FreeDeviceFM<>" ) ) ); }
[ "dalarub@localhost", "[email protected]", "mikaruus@localhost" ]
[ [ [ 1, 12 ], [ 15, 19 ], [ 39, 44 ], [ 56, 58 ], [ 65, 65 ], [ 72, 73 ], [ 85, 86 ], [ 130, 135 ], [ 153, 153 ], [ 156, 156 ], [ 158, 159 ], [ 169, 169 ], [ 171, 171 ], [ 176, 176 ], [ 184, 184 ], [ 230, 231 ], [ 237, 237 ], [ 244, 244 ], [ 279, 279 ], [ 320, 320 ], [ 323, 323 ], [ 436, 437 ], [ 465, 471 ], [ 473, 486 ], [ 488, 495 ], [ 500, 501 ], [ 527, 527 ], [ 538, 538 ], [ 556, 556 ], [ 568, 568 ], [ 570, 570 ], [ 572, 575 ], [ 599, 601 ], [ 610, 611 ] ], [ [ 13, 14 ], [ 24, 24 ], [ 172, 172 ], [ 179, 179 ], [ 228, 228 ], [ 295, 295 ], [ 324, 324 ], [ 435, 435 ], [ 487, 487 ] ], [ [ 20, 23 ], [ 25, 38 ], [ 45, 55 ], [ 59, 64 ], [ 66, 71 ], [ 74, 84 ], [ 87, 129 ], [ 136, 152 ], [ 154, 155 ], [ 157, 157 ], [ 160, 168 ], [ 170, 170 ], [ 173, 175 ], [ 177, 178 ], [ 180, 183 ], [ 185, 227 ], [ 229, 229 ], [ 232, 236 ], [ 238, 243 ], [ 245, 278 ], [ 280, 294 ], [ 296, 319 ], [ 321, 322 ], [ 325, 434 ], [ 438, 464 ], [ 472, 472 ], [ 496, 499 ], [ 502, 526 ], [ 528, 537 ], [ 539, 555 ], [ 557, 567 ], [ 569, 569 ], [ 571, 571 ], [ 576, 598 ], [ 602, 609 ], [ 612, 703 ] ] ]
8e2ac8ebba9a4f025f4a340f71b0155c24596160
f4b649f3f48ad288550762f4439fcfffddc08d0e
/eRacer/Source/Game/Game.cpp
1b5ce5ed06e43488427aae45c53756a0e8feaff3
[]
no_license
Knio/eRacer
0fa27c8f7d1430952a98ac2896ab8b8ee87116e7
65941230b8bed458548a920a6eac84ad23c561b8
refs/heads/master
2023-09-01T16:02:58.232341
2010-04-26T23:58:20
2010-04-26T23:58:20
506,897
1
0
null
null
null
null
UTF-8
C++
false
false
47
cpp
#include "Game.h" Game* Game::g_Game = NULL;
[ [ [ 1, 2 ] ] ]
a543137fda816aadee49f91f8fbecea7a0f641dd
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/SupportWFLib/symbian/AppHandler.cpp
86de6ce3428ec1ed9db1d990f672ae2b3204e125
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,506
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "AppHandler.h" //CAppHandler #include <e32base.h> //CBase #include <e32std.h> //TDesC #include <eikenv.h> //CEikonEnv #include <apgtask.h> //TApaTask #include <apgcli.h> //RApaLsSession #include "AppObserver.h" //MAppObserver #include "TimeOutTimer.h" //CTimeOutTimer #define KTimeOut (3*1000*1000) CAppHandler::CAppHandler(class MAppObserver* aAppObserver, TInt aLength) : iAppObserver(aAppObserver), iNumAppObjs(aLength) { } void CAppHandler::ConstructL(struct TAppObject** aAppList) { SetAppListL(aAppList, iNumAppObjs); iIndex = 0; iNbrOfRetries = 3; iTimer = CTimeOutTimer::NewL(EPriorityHigh, *this); iGenerator = CAppEventGenerator::NewL(*this); } void CAppHandler::ConstructL() { iIndex = 0; iNumAppObjs = 0; iNbrOfRetries = 3; iTimer = CTimeOutTimer::NewL(EPriorityHigh, *this); iGenerator = CAppEventGenerator::NewL(*this); } CAppHandler::~CAppHandler() { for(TInt i = 0; i < iNumAppObjs; ++i) { delete iAppList[i]; } delete[] iAppList; delete iGenerator; delete iTimer; } class CAppHandler* CAppHandler::NewLC(class MAppObserver* aAppObserver) { class CAppHandler* self = new (ELeave) CAppHandler(aAppObserver, 0); CleanupStack::PushL(self); self->ConstructL(); return self; } class CAppHandler* CAppHandler::NewLC(class MAppObserver* aAppObserver, struct TAppObject** aAppList, TInt aLength) { class CAppHandler* self = new (ELeave) CAppHandler(aAppObserver, aLength); CleanupStack::PushL(self); self->ConstructL(aAppList); return self; } class CAppHandler* CAppHandler::NewL(class MAppObserver* aAppObserver) { class CAppHandler* self = CAppHandler::NewLC(aAppObserver); CleanupStack::Pop(self); return self; } class CAppHandler* CAppHandler::NewL(class MAppObserver* aAppObserver, struct TAppObject** aAppList, TInt aLength) { class CAppHandler* self = CAppHandler::NewLC(aAppObserver, aAppList, aLength); CleanupStack::Pop(self); return self; } void CAppHandler::SetAppListL(struct TAppObject** aAppList, TInt aLength) { // Size of the array iNumAppObjs = aLength; if(iAppList) { delete[] iAppList; iAppList = NULL; } // Allocate necessary space iAppList = new(ELeave) TAppObject*[iNumAppObjs]; // Build a list of installed applications. RApaLsSession apaSession; User::LeaveIfError(apaSession.Connect()); CleanupClosePushL(apaSession); TInt ret = apaSession.GetAllApps(); if(ret != KErrNone) { GenerateEventL(EFailedToInitList); return; } TApaAppInfo appInfo; TInt appIndex = 0; while (apaSession.GetNextApp(appInfo)==KErrNone) { for(TInt i = 0; i < iNumAppObjs; ++i) { if(appInfo.iFullName.CompareF(*aAppList[i]->appName) == 0) { // We found a matching app, add to our list TAppObject* appObj = new(ELeave) TAppObject(); appObj->appName = appInfo.iFullName.AllocL(); appObj->appUid = appInfo.iUid.iUid; appObj->appAction = aAppList[i]->appAction; appObj->pendingAction = ENonePending; iAppList[appIndex] = appObj; appIndex++; } } } iNumAppObjs = appIndex; CleanupStack::PopAndDestroy(&apaSession); } void CAppHandler::ProcessAppListL() { if (!iRunning) { iIndex = 0; iEndTaskIndex = 0; iNbrOfRetries = 3; iRunning = ETrue; GenerateEventL(EStartProcessingApp); } } void CAppHandler::HandleGeneratedEventL(enum TAppProcessEvent aEvent) { switch(aEvent) { case EStartProcessingApp: // Check if app is running. ProcessActions(); break; case EAppIsRunning: // We should notify obeserver. NotifyObserver(); break; case ECheckPendingActions: CheckPendingActions(); break; case EFailedToEndTask: // Timer has expired three times but the // application is still running. Notify // the observer and quit. NotifyObserverEndTaskFailed(); break; case EFinishedProcessingList: iRunning = EFalse; iAppObserver->FinishedProcessingList(); break; case EFailedToInitList: iAppObserver->ListInitFailed(); break; } } void CAppHandler::GenerateEventL(enum TAppProcessEvent aEvent) { iGenerator->SendEventL(aEvent); } void CAppHandler::NotifyObserver() { iAppObserver->AppIsRunning(*iAppList[iIndex]->appName); } void CAppHandler::NotifyObserverEndTaskFailed() { iAppObserver->EndTaskFailed(*iAppList[iEndTaskIndex]->appName); } void CAppHandler::CheckPendingActions() { class TApaTaskList taskList(CEikonEnv::Static()->WsSession()); class TUid uid; struct TAppObject* appObj; for(TInt i = 0; i < iNumAppObjs; ++i) { appObj = iAppList[i]; uid = TUid::Uid(appObj->appUid); class TApaTask task = taskList.FindApp(uid); if(appObj->pendingAction == EEndingApp) { if(task.Exists()) { // App is running iEndTaskIndex = i; iTimer->After(KTimeOut); return; } else { appObj->pendingAction = ENonePending; } } } GenerateEventL(EFinishedProcessingList); } void CAppHandler::ProcessActions() { // New task to end class TApaTaskList taskList(CEikonEnv::Static()->WsSession()); class TUid uid; struct TAppObject* appObj; for(TInt i = 0; i < iNumAppObjs; ++i) { appObj = iAppList[i]; uid = TUid::Uid(appObj->appUid); class TApaTask task = taskList.FindApp(uid); if(!task.Exists()) { // Current task is not running, // continue with next one. continue; } if(appObj->appAction == EEndApp) { // End task. #if defined(NAV2_CLIENT_UIQ) // We have to kill the task on P800, // otherwise the task will not end. task.KillTask(); #else task.EndTask(); #endif appObj->pendingAction = EEndingApp; } else if(appObj->appAction == ENotifyObserver) { // Notify observer and quit processing list. iIndex = i; GenerateEventL(EAppIsRunning); return; } } iTimer->After(KTimeOut); } void CAppHandler::TimerExpired() { if(iNbrOfRetries > 0) { iNbrOfRetries--; GenerateEventL(ECheckPendingActions); return; } GenerateEventL(EFailedToEndTask); }
[ [ [ 1, 270 ] ] ]
028c5c12bf202cd3650c7f533a8c6073a9a9e131
8a4f175db665a326bcc322e3ffe6f4eac4d324da
/tests/TestEngine.cpp
042379753aeb2740debc7f23f7d53729f1c8c80d
[]
no_license
quocble/cubes
51547b3913c477b46d51e5b99ad7592c8199343f
5d071d7c11fb6c337d34716105197ee254f020dd
refs/heads/master
2020-12-25T20:30:55.974889
2011-11-15T07:16:59
2011-11-15T07:16:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,270
cpp
/***************************************************************************** * Networking Library by Glenn Fiedler <[email protected]> * Copyright (c) Sony Computer Entertainment America 2008-2010 ****************************************************************************/ #include "PreCompiled.h" #include "shared/Activation.h" #include "shared/Engine.h" #include "shared/Game.h" #include "shared/Cubes.h" using namespace activation; using namespace engine; using namespace game; SUITE( Activation ) { TEST( test_activation_initial_conditions ) { const float activation_radius = 10.0f; const int grid_width = 20; const int grid_height = 20; const int cell_size = 1; activation::ActivationSystem activationSystem( 1024, activation_radius, grid_width, grid_height, cell_size, 32, 32 ); CHECK( activationSystem.GetEventCount() == 0 ); CHECK( activationSystem.GetX() == 0.0f ); CHECK( activationSystem.GetY() == 0.0f ); CHECK( activationSystem.GetActiveCount() == 0 ); activationSystem.Validate(); CHECK( activationSystem.GetWidth() == grid_width ); CHECK( activationSystem.GetHeight() == grid_height ); CHECK( activationSystem.GetCellSize() == cell_size ); CHECK( activationSystem.IsEnabled() == true ); } TEST( test_activation_activate_deactivate ) { // first we setup the activation system and add some objects to it const float activation_radius = 10.0f; const int grid_width = 100; const int grid_height = 100; const int cell_size = 1; activation::ActivationSystem activationSystem( 1024, activation_radius, grid_width, grid_height, cell_size, 32, 32 ); int id = 1; for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float(-1.0f, 0.0f ), math::random_float(-1.0f, 0.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float( 0.0f,+1.0f ), math::random_float(-1.0f, 0.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float(-1.0f, 0.0f ), math::random_float( 0.0f, 1.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float( 0.0f,+1.0f ), math::random_float( 0.0f, 1.0f ) ); // verify that objects activate and we receive activation events // for each object in the order we expect for ( int i = 0; i < 10; ++i ) activationSystem.Update( 0.1f ); CHECK( activationSystem.GetActiveCount() == 40 ); CHECK( activationSystem.GetEventCount() == 40 ); const int eventCount = activationSystem.GetEventCount(); for ( int i = 0; i < eventCount; ++i ) { const activation::Event & event = activationSystem.GetEvent(i); CHECK( event.type == activation::Event::Activate ); CHECK( event.id == (activation::ObjectId) ( i + 1 ) ); } activationSystem.ClearEvents(); activationSystem.Validate(); for ( int i = 1; i <= 40; ++i ) CHECK( activationSystem.IsActive(i) ); // now if we move the activation point really far away, // the objects should deactivate... { CHECK( activationSystem.GetEventCount() == 0 ); activationSystem.MoveActivationPoint( 1000.0f, 1000.0f ); for ( int i = 0; i < 10; ++i ) activationSystem.Update( 0.1f ); CHECK( activationSystem.GetActiveCount() == 0 ); CHECK( activationSystem.GetEventCount() == 40 ); const int eventCount = activationSystem.GetEventCount(); for ( int i = 0; i < eventCount; ++i ) { const activation::Event & event = activationSystem.GetEvent(i); CHECK( event.type == activation::Event::Deactivate ); CHECK( event.id >= 1 ); CHECK( event.id <= 40 ); } activationSystem.ClearEvents(); activationSystem.Validate(); for ( int i = 1; i <= 40; ++i ) CHECK( !activationSystem.IsActive(i) ); } // when we move back to the origin we expect the objects to reactivate { activationSystem.MoveActivationPoint( 0, 0 ); for ( int i = 0; i < 10; ++i ) activationSystem.Update( 0.1f ); CHECK( activationSystem.GetActiveCount() == 40 ); CHECK( activationSystem.GetEventCount() == 40 ); const int eventCount = activationSystem.GetEventCount(); for ( int i = 0; i < eventCount; ++i ) { const activation::Event & event = activationSystem.GetEvent(i); CHECK( event.type == activation::Event::Activate ); CHECK( event.id >= 1 ); CHECK( event.id <= 40 ); } activationSystem.ClearEvents(); activationSystem.Validate(); for ( int i = 1; i <= 40; ++i ) CHECK( activationSystem.IsActive(i) ); } // move objects from one grid cell to another and verify they stay active CHECK( activationSystem.IsActive( 1 ) ); activationSystem.MoveObject( 1, 0.5f, -0.5f ); activationSystem.Validate(); CHECK( activationSystem.IsActive( 1 ) ); CHECK( activationSystem.GetActiveCount() == 40 ); CHECK( activationSystem.GetEventCount() == 0 ); CHECK( activationSystem.IsActive( 11 ) ); activationSystem.MoveObject( 11, -0.5f, -0.5f ); activationSystem.Validate(); CHECK( activationSystem.IsActive( 11 ) ); CHECK( activationSystem.GetActiveCount() == 40 ); CHECK( activationSystem.GetEventCount() == 0 ); // move an active object out of the activation circle and verify it deactivates CHECK( activationSystem.IsActive( 1 ) ); activationSystem.MoveObject( 1, -15.0f, -15.0f ); for ( int i = 0; i < 10; ++i ) { activationSystem.Validate(); activationSystem.Update( 0.1f ); } CHECK( !activationSystem.IsActive( 1 ) ); CHECK( activationSystem.GetActiveCount() == 39 ); CHECK( activationSystem.GetEventCount() == 1 ); if ( activationSystem.GetEventCount() == 1 ) { const activation::Event & event = activationSystem.GetEvent(0); CHECK( event.type == activation::Event::Deactivate ); CHECK( event.id == 1 ); } activationSystem.ClearEvents(); // move the deactivated object into the activation circle and verify it reactivates CHECK( !activationSystem.IsActive( 1 ) ); activationSystem.MoveObject( 1, 0.0f, 0.0f ); for ( int i = 0; i < 10; ++i ) { activationSystem.Validate(); activationSystem.Update( 0.1f ); } // NETHACK: deactivated object does not seem to have activated here CHECK( activationSystem.IsActive( 1 ) ); CHECK( activationSystem.GetActiveCount() == 40 ); CHECK( activationSystem.GetEventCount() == 1 ); if ( activationSystem.GetEventCount() == 1 ) { const activation::Event & event = activationSystem.GetEvent(0); CHECK( event.type == activation::Event::Activate ); CHECK( event.id == 1 ); } activationSystem.ClearEvents(); activationSystem.Validate(); } TEST( test_activation_enable_disable ) { // first we setup the activation system and add some objects to it const float activation_radius = 10.0f; const int grid_width = 20; const int grid_height = 20; const int cell_size = 1; activation::ActivationSystem activationSystem( 1024, activation_radius, grid_width, grid_height, cell_size, 32, 32 ); int id = 1; for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float(-1.0f, 0.0f ), math::random_float(-1.0f, 0.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float( 0.0f,+1.0f ), math::random_float(-1.0f, 0.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float(-1.0f, 0.0f ), math::random_float( 0.0f, 1.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float( 0.0f,+1.0f ), math::random_float( 0.0f, 1.0f ) ); // now we disable the activation system, pump updates and verify nothing activates... activationSystem.SetEnabled( false ); for ( int i = 0; i < 10; ++i ) activationSystem.Update( 0.1f ); CHECK( activationSystem.GetActiveCount() == 0 ); CHECK( activationSystem.GetEventCount() == 0 ); // enable the activation system, pump updates, objects should now activate... activationSystem.SetEnabled( true ); for ( int i = 0; i < 10; ++i ) activationSystem.Update( 0.1f ); CHECK( activationSystem.GetActiveCount() == 40 ); CHECK( activationSystem.GetEventCount() == 40 ); const int eventCount = activationSystem.GetEventCount(); for ( int i = 0; i < eventCount; ++i ) { const activation::Event & event = activationSystem.GetEvent(i); CHECK( event.type == activation::Event::Activate ); CHECK( event.id == (activation::ObjectId) ( i + 1 ) ); } activationSystem.ClearEvents(); activationSystem.Validate(); for ( int i = 1; i <= 40; ++i ) CHECK( activationSystem.IsActive(i) ); // disable the activation system, pump updates, all objects should deactivate { activationSystem.SetEnabled( false ); for ( int i = 0; i < 10; ++i ) activationSystem.Update( 0.1f ); CHECK( activationSystem.GetActiveCount() == 0 ); CHECK( activationSystem.GetEventCount() == 40 ); const int eventCount = activationSystem.GetEventCount(); for ( int i = 0; i < eventCount; ++i ) { const activation::Event & event = activationSystem.GetEvent(i); CHECK( event.type == activation::Event::Deactivate ); CHECK( event.id >= 1 ); CHECK( event.id <= 40 ); } activationSystem.ClearEvents(); activationSystem.Validate(); for ( int i = 1; i <= 40; ++i ) CHECK( !activationSystem.IsActive(i) ); } } TEST( test_activation_sweep ) { // first we setup the activation system and add some objects to it const float activation_radius = 10.0f; const int grid_width = 50; const int grid_height = 50; const int cell_size = 1; activation::ActivationSystem activationSystem( 1024, activation_radius, grid_width, grid_height, cell_size, 32, 32 ); int id = 1; for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float(-1.0f, 0.0f ), math::random_float(-1.0f, 0.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float( 0.0f,+1.0f ), math::random_float(-1.0f, 0.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float(-1.0f, 0.0f ), math::random_float( 0.0f, 1.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float( 0.0f,+1.0f ), math::random_float( 0.0f, 1.0f ) ); // now we do a slow sweep from left to right and verify objects activate and deactivate *once* only bool activated[40]; memset( activated, 0, sizeof(activated) ); for ( float x = -100.0f; x < +100.0f; x += 0.1f ) { activationSystem.MoveActivationPoint( x, 0.0f ); activationSystem.Update( 0.1f ); const int eventCount = activationSystem.GetEventCount(); for ( int i = 0; i < eventCount; ++i ) { const activation::Event & event = activationSystem.GetEvent(i); CHECK( event.id >= 1 ); CHECK( event.id <= 40 ); if ( event.type == activation::Event::Activate ) { CHECK( !activated[event.id-1] ); activated[event.id-1] = true; } else if ( event.type == activation::Event::Deactivate ) { CHECK( activated[event.id-1] ); activated[event.id-1] = false; } } activationSystem.ClearEvents(); } // now we expect all objects to be inactive, and to have no pending events for ( int i = 0; i < 40; ++i ) CHECK( activated[i] == false ); CHECK( activationSystem.GetEventCount() == 0 ); CHECK( activationSystem.GetActiveCount() == 0 ); } TEST( test_activation_stress_test ) { // first we setup the activation system and add some objects to it const float activation_radius = 10.0f; const int grid_width = 40; const int grid_height = 40; // note: this asserts out if we reduce to 20x20 (need to switch to fixed point...) const int cell_size = 1; activation::ActivationSystem activationSystem( 1024, activation_radius, grid_width, grid_height, cell_size, 32, 32 ); int id = 1; for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float(-1.0f, 0.0f ), math::random_float(-1.0f, 0.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float( 0.0f,+1.0f ), math::random_float(-1.0f, 0.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float(-1.0f, 0.0f ), math::random_float( 0.0f, 1.0f ) ); for ( int i = 0; i < 10; ++i ) activationSystem.InsertObject( id++, math::random_float( 0.0f,+1.0f ), math::random_float( 0.0f, 1.0f ) ); // randomly move objects and the activation point in an attempt to break the system... for ( int i = 0; i < 100; ++i ) { activationSystem.Update( 0.1f ); if ( math::chance( 0.1 ) ) activationSystem.MoveActivationPoint( math::random_float( -20.0f, +20.0f ), math::random_float( -20.0f, +20.0f ) ); int numMoves = math::random( 20 ); for ( int i = 0; i < numMoves; ++i ) { int id = 1 + math::random( 40 ); assert( id >= 1 ); assert( id <= 40 ); activationSystem.MoveObject( id, math::random_float( -20.0f, +20.0f ), math::random_float( -20.0f, +20.0f ) ); } activationSystem.Validate(); activationSystem.ClearEvents(); } // disable the activation system, pump updates, all objects should deactivate activationSystem.SetEnabled( false ); for ( int i = 0; i < 10; ++i ) activationSystem.Update( 0.1f ); CHECK( activationSystem.GetActiveCount() == 0 ); const int eventCount = activationSystem.GetEventCount(); for ( int i = 0; i < eventCount; ++i ) { const activation::Event & event = activationSystem.GetEvent(i); CHECK( event.type == activation::Event::Deactivate ); CHECK( event.id >= 1 ); CHECK( event.id <= 40 ); } activationSystem.ClearEvents(); activationSystem.Validate(); for ( int i = 1; i <= 40; ++i ) CHECK( !activationSystem.IsActive(i) ); } } SUITE( ResponseQueue ) { struct Response { ObjectId id; Response() { id = 0; } Response( ObjectId id ) { this->id = id; } }; TEST( response_queue_initial_conditions ) { ResponseQueue<Response> responseQueue; Response response; CHECK( !responseQueue.PopResponse( response ) ); for ( int i = 0; i < 100; ++i ) CHECK( !responseQueue.AlreadyQueued( i ) ); } TEST( response_queue_pop ) { ResponseQueue<Response> responseQueue; Response a = 10; Response b = 15; Response c = 6; responseQueue.QueueResponse( a ); responseQueue.QueueResponse( b ); responseQueue.QueueResponse( c ); Response response; CHECK( responseQueue.PopResponse( response ) ); CHECK( response.id == a.id ); CHECK( responseQueue.PopResponse( response ) ); CHECK( response.id == b.id ); CHECK( responseQueue.PopResponse( response ) ); CHECK( response.id == c.id ); } TEST( response_queue_clear ) { ResponseQueue<Response> responseQueue; Response a = 10; Response b = 15; Response c = 6; responseQueue.QueueResponse( a ); responseQueue.QueueResponse( b ); responseQueue.QueueResponse( c ); responseQueue.Clear(); Response response; CHECK( !responseQueue.PopResponse( response ) ); for ( int i = 0; i < 100; ++i ) CHECK( !responseQueue.AlreadyQueued( i ) ); } } SUITE( Compression ) { TEST( compress_position ) { math::Vector input(10,100,200.5f); math::Vector output(0,0,0); uint64_t compressed; game::CompressPosition( input, compressed ); game::DecompressPosition( compressed, output ); CHECK_CLOSE( input.x, output.x, 0.001f ); CHECK_CLOSE( input.y, output.y, 0.001f ); CHECK_CLOSE( input.z, output.z, 0.001f ); } TEST( compress_orientation ) { math::Quaternion input(1,0,0,0); math::Quaternion output(0,0,0,0); uint32_t compressed; game::CompressOrientation( input, compressed ); game::DecompressOrientation( compressed, output ); CHECK_CLOSE( input.w, output.w, 0.001f ); CHECK_CLOSE( input.x, output.x, 0.001f ); CHECK_CLOSE( input.y, output.y, 0.001f ); CHECK_CLOSE( input.z, output.z, 0.001f ); } } SUITE( Game ) { void AddCube( game::Instance<cubes::DatabaseObject, cubes::ActiveObject> * gameInstance, float scale, const math::Vector & position, const math::Vector & linearVelocity = math::Vector(0,0,0), const math::Vector & angularVelocity = math::Vector(0,0,0) ) { cubes::DatabaseObject object; object.position = position; object.orientation = math::Quaternion(1,0,0,0); object.scale = scale; object.linearVelocity = linearVelocity; object.angularVelocity = angularVelocity; object.enabled = 1; object.activated = 0; gameInstance->AddObject( object, position.x, position.y ); } TEST( game_initial_conditions ) { game::Instance<cubes::DatabaseObject, cubes::ActiveObject> instance; CHECK( instance.GetLocalPlayer() == -1 ); for ( int i = 0; i < MaxPlayers; ++i ) { CHECK( !instance.IsPlayerJoined(i) ); game::Input input; instance.GetPlayerInput( i, input ); CHECK( input == game::Input() ); CHECK( instance.GetPlayerFocus( i ) == 0 ); } CHECK( instance.GetLocalPlayer() == -1 ); CHECK( !instance.InGame() ); } TEST( game_initialize_shutdown ) { game::Config config; config.cellSize = 4.0f; config.cellWidth = 16; config.cellHeight = 16; game::Instance<cubes::DatabaseObject, cubes::ActiveObject> instance( config ); for ( int i = 0; i < 2; ++i ) { instance.InitializeBegin(); instance.InitializeEnd(); instance.Shutdown(); } } // NETHACK: todo - need to extend this test such that it handles multiple player join and leave // and verifies that player cubes activate/deactivate on join/leave (new behavior) TEST( game_player_join_and_leave ) { game::Config config; config.cellSize = 4.0f; config.cellWidth = 16; config.cellHeight = 16; game::Instance<cubes::DatabaseObject, cubes::ActiveObject> instance( config ); instance.InitializeBegin(); AddCube( &instance, 1.0f, math::Vector(0,0,0) ); AddCube( &instance, 1.0f, math::Vector(0,0,0) ); AddCube( &instance, 1.0f, math::Vector(0,0,0) ); AddCube( &instance, 1.0f, math::Vector(0,0,0) ); instance.InitializeEnd(); for ( int i = 0; i < MaxPlayers; ++i ) { CHECK( !instance.IsPlayerJoined( i ) ); instance.OnPlayerJoined( i ); instance.SetPlayerFocus( i, i + 1 ); CHECK( instance.IsPlayerJoined( i ) ); CHECK( instance.GetPlayerFocus( i ) == ObjectId( i + 1 ) ); } CHECK( !instance.InGame() ); CHECK( instance.GetLocalPlayer() == -1 ); instance.SetLocalPlayer( 1 ); CHECK( instance.GetLocalPlayer() == 1 ); CHECK( instance.InGame() ); for ( int i = 0; i < MaxPlayers; ++i ) { CHECK( instance.IsPlayerJoined( i ) ); instance.OnPlayerLeft( i ); CHECK( !instance.IsPlayerJoined( i ) ); } instance.Shutdown(); CHECK( instance.GetLocalPlayer() == -1 ); CHECK( !instance.InGame() ); for ( int i = 0; i < MaxPlayers; ++i ) { CHECK( !instance.IsPlayerJoined( i ) ); CHECK( instance.GetPlayerFocus( i ) == 0 ); } } TEST( game_object_activation ) { game::Config config; config.cellSize = 4.0f; config.cellWidth = 16; config.cellHeight = 16; game::Instance<cubes::DatabaseObject, cubes::ActiveObject> instance( config ); instance.InitializeBegin(); AddCube( &instance, 1.0f, math::Vector(0,0,0) ); instance.InitializeEnd(); instance.SetFlag( game::FLAG_Pause ); instance.OnPlayerJoined( 0 ); instance.SetPlayerFocus( 0, 1 ); instance.SetLocalPlayer( 0 ); instance.Update(); int numActiveObjects = 0; cubes::ActiveObject activeObjects[1]; instance.CopyActiveObjects( activeObjects, numActiveObjects ); CHECK( numActiveObjects == 1 ); CHECK( instance.IsObjectActive( 1 ) ); instance.OnPlayerLeft( 0 ); instance.Update(); instance.CopyActiveObjects( activeObjects, numActiveObjects ); CHECK( numActiveObjects == 0 ); CHECK( !instance.IsObjectActive( 1 ) ); } TEST( game_object_get_set_state ) { game::Config config; config.cellSize = 4.0f; config.cellWidth = 16; config.cellHeight = 16; game::Instance<cubes::DatabaseObject, cubes::ActiveObject> instance( config ); instance.InitializeBegin(); for ( int i = 0; i < 20; ++i ) { cubes::DatabaseObject object; object.position = math::Vector(0,0,0); object.orientation = math::Quaternion(1,0,0,0); object.scale = ( i == 0 ) ? 1.4f : 0.4f; object.linearVelocity = math::Vector(0,0,0); object.angularVelocity = math::Vector(0,0,0); object.enabled = 1; object.activated = 0; instance.AddObject( object, 0, 0 ); } instance.InitializeEnd(); instance.SetFlag( game::FLAG_Pause ); // join player focused on object 1 to activate some objects instance.OnPlayerJoined( 0 ); instance.SetLocalPlayer( 0 ); instance.SetPlayerFocus( 0, 1 ); instance.Update(); int numActiveObjects = 0; cubes::ActiveObject activeObjects[32]; instance.CopyActiveObjects( activeObjects, numActiveObjects ); CHECK( numActiveObjects > 0 ); // move active objects outside activation distance (except player object) for ( int i = 0; i < numActiveObjects; ++i ) { if ( activeObjects[i].scale < 1.0f ) { activeObjects[i].position.x = 20.0; activeObjects[i].position.y = 20.0; instance.SetObjectState( activeObjects[i].id, activeObjects[i] ); } } // update and verify all non-player objects have deactivated instance.Update(); int after_numActiveObjects = 0; cubes::ActiveObject after_activeObjects[32]; instance.CopyActiveObjects( after_activeObjects, after_numActiveObjects ); CHECK( after_numActiveObjects == 1 ); CHECK( after_activeObjects[0].scale > 1.0f ); // move the objects back in to the origin point const math::Vector origin = instance.GetOrigin(); for ( int i = 0; i < numActiveObjects; ++i ) { activeObjects[i].position.x = origin.x; activeObjects[i].position.y = origin.y; instance.SetObjectState( activeObjects[i].id, activeObjects[i] ); } // verify they activate again instance.Update(); int newActiveCount = instance.GetNumActiveObjects(); CHECK( newActiveCount == numActiveObjects ); for ( int i = 0; i < numActiveObjects; ++i ) { CHECK( instance.IsObjectActive( activeObjects[i].id ) ); } } TEST( game_object_persistence ) { // make sure objects remember their state when they re-activate game::Config config; config.cellSize = 4.0f; config.cellWidth = 16; config.cellHeight = 16; game::Instance<cubes::DatabaseObject, cubes::ActiveObject> instance( config ); instance.InitializeBegin(); for ( int i = 0; i < 20; ++i ) { cubes::DatabaseObject object; object.position = math::Vector( math::random_float( -10.0f, +10.0f ), math::random_float( -10.0f, +10.0f ), 5 ); object.orientation = math::Quaternion(1,0,0,0); object.scale = ( i == 0 ) ? 1.4f : 0.4f; object.linearVelocity = math::Vector(0,0,0); object.angularVelocity = math::Vector(0,0,0); object.enabled = 1; object.activated = 0; instance.AddObject( object, object.position.x, object.position.y ); } instance.InitializeEnd(); instance.SetFlag( game::FLAG_Pause ); // join and activate some objects instance.OnPlayerJoined( 0 ); instance.SetLocalPlayer( 0 ); instance.SetPlayerFocus( 0, 1 ); for ( int i = 0; i < 10; ++i ) instance.Update(); int numActiveObjects = 0; cubes::ActiveObject activeObjects[32]; instance.CopyActiveObjects( activeObjects, numActiveObjects ); CHECK( numActiveObjects > 0 ); // verify player cube is active int focusObjectId = instance.GetPlayerFocus( 0 ); CHECK( focusObjectId >= 0 ); CHECK( instance.IsObjectActive( focusObjectId ) ); // change active object positions and orientations math::Vector origin = instance.GetOrigin(); for ( int i = 0; i < numActiveObjects; ++i ) { CHECK( activeObjects[i].id >= 0 ); if ( activeObjects[i].scale > 1.0f ) { activeObjects[i].position.x = origin.x + ( activeObjects[i].position.x - origin.x ) * 0.5f; activeObjects[i].position.y = origin.y + ( activeObjects[i].position.y - origin.y ) * 0.5f; activeObjects[i].position.z = 0.0f; activeObjects[i].orientation = math::Quaternion( 0.5f, activeObjects[i].position.x, activeObjects[i].position.y, activeObjects[i].position.x + activeObjects[i].position.y ); activeObjects[i].orientation.normalize(); instance.SetObjectState( activeObjects[i].id, activeObjects[i] ); } } // verify all objects are still active for ( int i = 0; i < 5; ++i ) instance.Update(); CHECK( instance.GetNumActiveObjects() == numActiveObjects ); // move player cube away, deactivate objects instance.OnPlayerLeft( 0 ); for ( int i = 0; i < 5; ++i ) instance.Update(); CHECK( instance.GetNumActiveObjects() == 0 ); // rejoin player instance.OnPlayerJoined( 0 ); instance.SetLocalPlayer( 0 ); for ( int i = 0; i < 5; ++i ) instance.Update(); // verify original objects are active and remember their positions and orientations int after_numActiveObjects = 0; cubes::ActiveObject after_activeObjects[32]; instance.CopyActiveObjects( after_activeObjects, after_numActiveObjects ); CHECK( after_numActiveObjects == numActiveObjects ); for ( int i = 0; i < after_numActiveObjects; ++i ) { bool found = false; for ( int j = 0; j < numActiveObjects; ++j ) { if ( after_activeObjects[i].id == activeObjects[j].id ) { found = true; CHECK_CLOSE( after_activeObjects[i].position.x, activeObjects[j].position.x, 0.001f ); CHECK_CLOSE( after_activeObjects[i].position.y, activeObjects[j].position.y, 0.001f ); CHECK_CLOSE( after_activeObjects[i].position.z, activeObjects[j].position.z, 0.001f ); const float cosine = after_activeObjects[i].orientation.w * activeObjects[j].orientation.w + after_activeObjects[i].orientation.x * activeObjects[j].orientation.x + after_activeObjects[i].orientation.y * activeObjects[j].orientation.y + after_activeObjects[i].orientation.z * activeObjects[j].orientation.z; if ( cosine < 0 ) after_activeObjects[i].orientation *= -1; CHECK_CLOSE( after_activeObjects[i].orientation.w, activeObjects[j].orientation.w, 0.03f ); CHECK_CLOSE( after_activeObjects[i].orientation.x, activeObjects[j].orientation.x, 0.03f ); CHECK_CLOSE( after_activeObjects[i].orientation.y, activeObjects[j].orientation.y, 0.03f ); CHECK_CLOSE( after_activeObjects[i].orientation.z, activeObjects[j].orientation.z, 0.03f ); } } CHECK( found ); } } }
[ [ [ 1, 815 ] ] ]
27b933d345fe852b078160b89c4bbf5f9b592ab3
dd296e4ce663222db78a3aa7230cabe4b6620747
/Programs/3dstom2/src/matrix.h
3bd393286b263aae85def4f719fdb6d88ede0f50
[]
no_license
vienis/mcbuddiapfel
42213684b253d7a0dae8b785c58a13853d6c9efd
e4d5c6b91d2f9f3b2d0de011cca3298a4e266d89
refs/heads/master
2021-01-10T02:13:50.149299
2011-01-22T13:56:56
2011-01-22T13:56:56
36,045,662
2
0
null
null
null
null
UTF-8
C++
false
false
5,495
h
#ifndef MATRIX_H #define MATRIX_H #include <cmath> #include "libm2\vec3d.h" #include "libm2\quaternion.h" #undef minor class Matrix { public: float m[4][4]; Matrix() { } Matrix(const Matrix& p) { for (size_t j=0; j<4; j++) { for (size_t i=0; i<4; i++) { m[j][i] = p.m[j][i]; } } } Matrix& operator= (const Matrix& p) { for (size_t j=0; j<4; j++) { for (size_t i=0; i<4; i++) { m[j][i] = p.m[j][i]; } } return *this; } void zero() { for (size_t j=0; j<4; j++) { for (size_t i=0; i<4; i++) { m[j][i] = 0; } } } void unit() { zero(); m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1.0f; } void translation(const Vec3D& tr) { /* 100# 010# 001# 0001 */ unit(); m[0][3]=tr.x; m[1][3]=tr.y; m[2][3]=tr.z; } static const Matrix newTranslation(const Vec3D& tr) { Matrix t; t.translation(tr); return t; } void scale(const Vec3D& sc) { /* #000 0#00 00#0 0001 */ zero(); m[0][0]=sc.x; m[1][1]=sc.y; m[2][2]=sc.z; m[3][3]=1.0f; } static const Matrix newScale(const Vec3D& sc) { Matrix t; t.scale(sc); return t; } void quaternionRotate(const Quaternion& q) { /* ###0 ###0 ###0 0001 */ m[0][0] = 1.0f - 2.0f * q.y * q.y - 2.0f * q.z * q.z; m[0][1] = 2.0f * q.x * q.y + 2.0f * q.w * q.z; m[0][2] = 2.0f * q.x * q.z - 2.0f * q.w * q.y; m[1][0] = 2.0f * q.x * q.y - 2.0f * q.w * q.z; m[1][1] = 1.0f - 2.0f * q.x * q.x - 2.0f * q.z * q.z; m[1][2] = 2.0f * q.y * q.z + 2.0f * q.w * q.x; m[2][0] = 2.0f * q.x * q.z + 2.0f * q.w * q.y; m[2][1] = 2.0f * q.y * q.z - 2.0f * q.w * q.x; m[2][2] = 1.0f - 2.0f * q.x * q.x - 2.0f * q.y * q.y; m[0][3] = m[1][3] = m[2][3] = m[3][0] = m[3][1] = m[3][2] = 0; m[3][3] = 1.0f; } static const Matrix newQuatRotate(const Quaternion& qr) { Matrix t; t.quaternionRotate(qr); return t; } Vec3D operator* (const Vec3D& v) const { Vec3D o; o.x = m[0][0]*v.x + m[0][1]*v.y + m[0][2]*v.z + m[0][3]; o.y = m[1][0]*v.x + m[1][1]*v.y + m[1][2]*v.z + m[1][3]; o.z = m[2][0]*v.x + m[2][1]*v.y + m[2][2]*v.z + m[2][3]; return o; } Matrix operator* (const Matrix& p) const { Matrix o; o.m[0][0] = m[0][0]*p.m[0][0] + m[0][1]*p.m[1][0] + m[0][2]*p.m[2][0] + m[0][3]*p.m[3][0]; o.m[0][1] = m[0][0]*p.m[0][1] + m[0][1]*p.m[1][1] + m[0][2]*p.m[2][1] + m[0][3]*p.m[3][1]; o.m[0][2] = m[0][0]*p.m[0][2] + m[0][1]*p.m[1][2] + m[0][2]*p.m[2][2] + m[0][3]*p.m[3][2]; o.m[0][3] = m[0][0]*p.m[0][3] + m[0][1]*p.m[1][3] + m[0][2]*p.m[2][3] + m[0][3]*p.m[3][3]; o.m[1][0] = m[1][0]*p.m[0][0] + m[1][1]*p.m[1][0] + m[1][2]*p.m[2][0] + m[1][3]*p.m[3][0]; o.m[1][1] = m[1][0]*p.m[0][1] + m[1][1]*p.m[1][1] + m[1][2]*p.m[2][1] + m[1][3]*p.m[3][1]; o.m[1][2] = m[1][0]*p.m[0][2] + m[1][1]*p.m[1][2] + m[1][2]*p.m[2][2] + m[1][3]*p.m[3][2]; o.m[1][3] = m[1][0]*p.m[0][3] + m[1][1]*p.m[1][3] + m[1][2]*p.m[2][3] + m[1][3]*p.m[3][3]; o.m[2][0] = m[2][0]*p.m[0][0] + m[2][1]*p.m[1][0] + m[2][2]*p.m[2][0] + m[2][3]*p.m[3][0]; o.m[2][1] = m[2][0]*p.m[0][1] + m[2][1]*p.m[1][1] + m[2][2]*p.m[2][1] + m[2][3]*p.m[3][1]; o.m[2][2] = m[2][0]*p.m[0][2] + m[2][1]*p.m[1][2] + m[2][2]*p.m[2][2] + m[2][3]*p.m[3][2]; o.m[2][3] = m[2][0]*p.m[0][3] + m[2][1]*p.m[1][3] + m[2][2]*p.m[2][3] + m[2][3]*p.m[3][3]; o.m[3][0] = m[3][0]*p.m[0][0] + m[3][1]*p.m[1][0] + m[3][2]*p.m[2][0] + m[3][3]*p.m[3][0]; o.m[3][1] = m[3][0]*p.m[0][1] + m[3][1]*p.m[1][1] + m[3][2]*p.m[2][1] + m[3][3]*p.m[3][1]; o.m[3][2] = m[3][0]*p.m[0][2] + m[3][1]*p.m[1][2] + m[3][2]*p.m[2][2] + m[3][3]*p.m[3][2]; o.m[3][3] = m[3][0]*p.m[0][3] + m[3][1]*p.m[1][3] + m[3][2]*p.m[2][3] + m[3][3]*p.m[3][3]; return o; } float determinant() const { #define SUB(a,b) (m[2][a]*m[3][b] - m[3][a]*m[2][b]) return m[0][0] * (m[1][1]*SUB(2,3) - m[1][2]*SUB(1,3) + m[1][3]*SUB(1,2)) -m[0][1] * (m[1][0]*SUB(2,3) - m[1][2]*SUB(0,3) + m[1][3]*SUB(0,2)) +m[0][2] * (m[1][0]*SUB(1,3) - m[1][1]*SUB(0,3) + m[1][3]*SUB(0,1)) -m[0][3] * (m[1][0]*SUB(1,2) - m[1][1]*SUB(0,2) + m[1][2]*SUB(0,1)); #undef SUB } const float minor(size_t x, size_t y) const { float s[3][3]; for (size_t j=0, v=0; j<4; j++) { if (j==y) continue; for (size_t i=0, u=0; i<4; i++) { if (i!=x) { s[v][u++] = m[j][i]; } } v++; } #define SUB(a,b) (s[1][a]*s[2][b] - s[2][a]*s[1][b]) return s[0][0] * SUB(1,2) - s[0][1] * SUB(0,2) + s[0][2] * SUB(0,1); #undef SUB } const Matrix adjoint() const { Matrix a; for (size_t j=0; j<4; j++) { for (size_t i=0; i<4; i++) { a.m[i][j] = (((i+j)&1)?-1.0f:1.0f) * minor(i,j); } } return a; } void invert() { Matrix adj = this->adjoint(); float invdet = 1.0f / this->determinant(); for (size_t j=0; j<4; j++) { for (size_t i=0; i<4; i++) { m[j][i] = adj.m[j][i] * invdet; } } } void transpose() { for (size_t j=1; j<4; j++) { for (size_t i=0; i<j; i++) { float f = m[j][i]; m[j][i] = m[i][j]; m[i][j] = f; } } } Matrix& operator*= (const Matrix& p) { return *this = this->operator*(p); } operator float*() { return (float*)this; } }; #endif
[ "[email protected]@af0300bf-f729-58c1-2b4a-178d59e24212" ]
[ [ [ 1, 234 ] ] ]
3b62f532d237b79492620f87e0dd456af2d58dc7
3761dcce2ce81abcbe6d421d8729af568d158209
/include/cybergarage/io/LineNumberReader.h
5237a71d6018c1daa098f9cb32b749a5e24436d9
[ "BSD-3-Clause" ]
permissive
claymeng/CyberLink4CC
af424e7ca8529b62e049db71733be91df94bf4e7
a1a830b7f4caaeafd5c2db44ad78fbb5b9f304b2
refs/heads/master
2021-01-17T07:51:48.231737
2011-04-08T15:10:49
2011-04-08T15:10:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
773
h
/****************************************************************** * * CyberIO for C++ * * Copyright (C) Satoshi Konno 2002-2003 * * File: LineNumberReader.h * * Revision; * * 06/11/03 * - first revision * ******************************************************************/ #ifndef _CIO_LINENUMBERREADER_H_ #define _CIO_LINENUMBERREADER_H_ #include <string> #include <cybergarage/io/BufferedReader.h> namespace CyberIO { class LineNumberReader : public BufferedReader { int lineNum; public: LineNumberReader(Reader *reader) : BufferedReader(reader) { lineNum = -1; } int getLineNumber() { return lineNum; } const char *readLine() { lineNum++; return BufferedReader::readLine(); } }; } #endif
[ "skonno@b944b01c-6696-4570-ab44-a0e08c11cb0e" ]
[ [ [ 1, 50 ] ] ]
a64568d97bb14ad37c7749415fc4bb16cc4f3a83
ecd62ff3b58c304344000881849e70e46eca9dbb
/cpp_names/file_scanner.h
97519bd343c95ef90d69497546a7ca918893bff6
[ "BSD-2-Clause" ]
permissive
paullasarev/cpp-names
e0abbaa6b1297a9b151c43295b5b3db8ba72bb95
9feffd94f8e28008748bef1a9c875466ebe2c097
refs/heads/master
2021-01-10T05:27:27.990830
2011-12-26T18:01:20
2011-12-26T18:01:20
36,063,945
0
0
null
null
null
null
UTF-8
C++
false
false
397
h
#ifndef FILE_SCANNER_H #define FILE_SCANNER_H #include "directory_tree.h" #include "name_info.h" #include <iostream> #include <memory> #include <boost/tr1/memory.hpp> namespace CppNames { class FileScanner { public: virtual bool Scan(std::istream& inputStream, NameInfoSet& names) = 0; }; typedef std::tr1::shared_ptr<FileScanner> FileScannerPtr; } #endif
[ "[email protected]@d4c89ac4-cce6-dfee-ab0c-273009d6406b" ]
[ [ [ 1, 22 ] ] ]
6e957e9886badc7d2a27bfffcfd11802399ef674
155c4955c117f0a37bb9481cd1456b392d0e9a77
/Tessa/TessaInstructions/NewObjectInstruction.h
81ae534cab15850b4808fa874a9c7b3ed2fa283b
[]
no_license
zwetan/tessa
605720899aa2eb4207632700abe7e2ca157d19e6
940404b580054c47f3ced7cf8995794901cf0aaa
refs/heads/master
2021-01-19T19:54:00.236268
2011-08-31T00:18:24
2011-08-31T00:18:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
751
h
namespace TessaInstructions { class NewObjectInstruction : public TessaInstruction { private: /*** * By specification new object properties is a list of alternating name/value pairs * eg newObjectProperties[0] = name of the property * newObjectProperties[1] = the value of newObjectProperties[0] */ ArrayOfInstructions* newObjectProperties; public: NewObjectInstruction(ArrayOfInstructions* newObjectProperties, TessaVM::BasicBlock* insertAtEnd); void print(); void visit(TessaVisitorInterface* tessaVisitor); bool isNewObject(); bool producesValue(); ArrayOfInstructions* getObjectProperties(); int getNumberOfProperties(); List<TessaValue*, LIST_GCObjects>* getOperands(MMgc::GC* gc); }; }
[ [ [ 1, 22 ] ] ]
fbd1b482d91123cdf270f4a23649328b3a3d10dd
51574a600a87ecfaaec8ea0e46b3809884859680
/Test/Test.cpp
5e7d10b1c4afb399b46fcb438fe977f5d8857918
[]
no_license
suilevap/motion-plan
b5ad60a8448b118c3742c8c9c42b29fd5e41ef3e
d9f5693938287f2179ca2cb4eb75bda51b97bbb0
refs/heads/master
2021-01-10T03:29:50.373970
2011-12-20T22:39:55
2011-12-20T22:39:55
49,495,165
0
0
null
null
null
null
UTF-8
C++
false
false
1,556
cpp
// Test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <time.h> #include <Interface.h> #include <InterfaceForTest.h> #include <FileStruct.h> //int _tmain(int argc, _TCHAR* argv[]) //{ // // clock_t time0, time1, times; // //FileStruct f("map2.txt"); // // //char * result = Action(f.GetBuffer()); // //printf(result); // TestPerformance(true); // //TestSparsePerformance(true); // // times = clock(); // time0 = times; // for (int i=1; i < 100000; i++) // { // TestPerformance(false); // //TestSparsePerformance(false); // if (i%1000 == 0) // { // time1 = clock(); // printf("%3dk time: %4d, avg time: %4d\n",i/1000, (time1 - time0), (time1 - times)/(i/1000) ); // time0 = time1; // } // } // getchar(); // return 0; //} int _tmain(int argc, _TCHAR* argv[]) { int cellSize = 16; int w = 40; int h = 100; double map = GenMap(w, h, cellSize); //double quadMap = CreateQuadMap(map); double pathFinder = GenPathFinder(map, w, h, cellSize); //double pathFinder = GenPathFinder(quadMap, w, h, cellSize); clock_t time0, time1, times; FindPathTest(map, pathFinder, w, h, cellSize, true); times = clock(); time0 = times; for (int i=1; i < 100000; i++) { FindPathTest(map, pathFinder, w, h, cellSize, false); if (i%1000 == 0) { time1 = clock(); printf("%3dk time: %4d, avg time: %4d\n",i/1000, (time1 - time0), (time1 - times)/(i/1000) ); time0 = clock(); } } getchar(); return 0; }
[ "suilevap@localhost", "[email protected]" ]
[ [ [ 1, 6 ], [ 8, 44 ], [ 48, 69 ] ], [ [ 7, 7 ], [ 45, 47 ] ] ]
a303d3e4b36cf1b11cb8d1e0257b27e3a8eb7dd2
e08de6b78df1f328ff5297de2c7cb0bb3dab7e39
/9 - Курсовой проект/users/Rezvyakov/src/Data.h
cffdec1685c5aebca98833e9cc52790d5f6aeed8
[]
no_license
kereokerekeke/mai-13-x01
265aede9d81de8ac1869457581872e7fec5f6285
a6a34b032dd4686603ae7193792195fb5cecad06
refs/heads/master
2021-01-10T08:20:17.027622
2011-11-14T19:31:49
2011-11-14T19:31:49
45,355,227
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
3,169
h
#pragma once #define TotalDeviceCount 3 // Доступные типы эмуляторов работы процесса enum EmulatorType { EmulatorType_Predevice, EmulatorType_Indevice, EmulatorType_Postdevice }; // Доступные варианты результата работы процесса в течении выделенного // интервала времени. enum Result { Result_Sleep, Result_Run, Result_Wait, Result_Finish }; // Абстрактный класс эмулятора работы процесса class BaseEmulator; // Класс задаёт шаблон работы одного процесса class ProcessOptions { public: ProcessOptions(int PredeviceTicks, int IndeviceTicks, int WaitDeviceTicks, int DeviceCount, int PostdeviceTicks, int TotalCount, int Priority); int PredeviceTicks; // Время выполнения до захвата устройства int IndeviceTicks; // Время выполнения работы с устройством int WaitDeviceTicks; // Время ожидания формирования результата устройством int DeviceCount; // Кол-во повторений работы с устройством int PostdeviceTicks; // Время выполнения после захвата устройства int TotalCount; // Кол-во полных повторений работы процесса int Priority; // Приоритет процесса }; // Класс эмулирует работу одного процесса по заданному шаблону class Process { public: Process(ProcessOptions* Options); // Конструктор класса protected: ProcessOptions* m_Options; // Шаблон работы процессора int m_CurrentPriority; // Текущий приоритет int InstateTicks; // Отработано тактов в текущем состоянии int TotalStep; // Текущий шаг общий BaseEmulator* m_Emulator; // Текущий эмулятор работы процесса int m_FinishTick; // Время, на котором работа была окончена bool m_NoPrint; // Блокировка вывода статистики Result m_LastResult; // Последний результат работы процесса public: Result DoTick(int TotalTick); // Отработать текущий шаг void PrintState(); // Вывести состояние в последнем вызове void PrintPriority(); // Вывести приоритет в последнем вызове static void PrintSemafore(); // Вывести кол-во свободных устройств int GetFinishTick(); // Время, на котором работа была окончена int GetPriority(); // Приоритет процесса по шаблону Result GetResult(); // Последний результат работы процесса };
[ "ncdinya@c9ba52fc-c71b-11de-8672-e51b9359e43c" ]
[ [ [ 1, 53 ] ] ]
f1f51b01f50ba769dae842d5da697304c84abc08
4a266d6931aa06a2343154cab99d8d5cfdac6684
/csci3081/lab09/Refrigerator.cpp
862d2caa0ae746fcaef3fdce4d1e3ead9a52bcfa
[]
no_license
Magneticmagnum/robotikdude-school
f0185feb6839ad5c5324756fc86f984fce7abdc1
cb39138b500c8bbc533e796225588439dcfa6555
refs/heads/master
2021-01-10T19:01:39.479621
2011-05-17T04:44:47
2011-05-17T04:44:47
35,382,573
0
0
null
null
null
null
UTF-8
C++
false
false
979
cpp
#include "Refrigerator.h" #include <sstream> Refrigerator::Refrigerator() : running_(true), tStateSwitch_(0), totalRunningTime_(0) { } void Refrigerator::tick() { tStateSwitch_++; if (running_) { totalRunningTime_++; if (tStateSwitch_ >= 3) { tStateSwitch_ = 0; running_ = false; std::string message = "Refrigerator turning off. Total energy used by" " refrigerator: "; std::stringstream out; out << getEnergy(); message.append(out.str()); message.append("."); // print(message); } } else { if (tStateSwitch_ >= 9) { tStateSwitch_ = 0; running_ = true; // print("Refrigerator turning on."); } } } double Refrigerator::getPower() const { return REFRIGERATOR_POWER; } double Refrigerator::getEnergy() const { return getPower() * totalRunningTime_; } bool Refrigerator::isRunning() const { return running_; }
[ "robotikdude@e80761d0-8fc2-79d0-c9d0-3546e327c268" ]
[ [ [ 1, 52 ] ] ]
078346c629977e33fd688ed18a7f38b1d6ba14be
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/infostudio/InfoStudio/leftsortdlg.h
b1cc8698c3d6ea7b7c9d82d4d2b4dad81c20e43c
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,794
h
#pragma once #include "Resource.h" extern CInfoManage* _pInfoManage; class CLeftSortDlg : public CDialogImpl<CLeftSortDlg> { public: CLeftSortDlg() { } ~CLeftSortDlg() { } enum {IDD = IDD_LEFTSORTDLG}; BEGIN_MSG_MAP(CLeftSortDlg) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDOK, OnOk) COMMAND_ID_HANDLER(IDCANCEL, OnCancel) MSG_WM_SIZE(OnSize) END_MSG_MAP() BOOL PreTranslateMessage(MSG* pMsg) { if (pMsg->message == WM_KEYDOWN) { if(pMsg->wParam == VK_RETURN) { if(::IsDialogMessage(m_hWnd, pMsg)) return TRUE; } } return FALSE; } LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { Init(); return 0; } LRESULT OnOk(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { return 0; } LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { return 0; } void OnSize(UINT wParam, CSize size) { DefWindowProc(); int cx = size.cx; int cy = size.cy; if (_tree.m_hWnd) _tree.SetWindowPos(NULL, 0, 0, cx , cy, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE); } //funciton void Init() { _tree.Attach( GetDlgItem( IDC_TREE ) ); CRect rc; GetClientRect( &rc ); _tree.SetWindowPos(NULL, 0, 0, rc.Width() , rc.Height(), SWP_NOACTIVATE | SWP_NOZORDER ); for ( int i = 0 ; i < _pInfoManage->_categoryLst.size(); i++ ) { CategoryItem* pItem = _pInfoManage->_categoryLst[i]; HTREEITEM hitem = NULL; TV_INSERTSTRUCT tvis = {0}; tvis.item.mask = TVIF_PARAM | TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE; tvis.hParent = TVI_ROOT; tvis.hInsertAfter = TVI_LAST; tvis.item.iImage = 0; tvis.item.iSelectedImage = 0; tvis.item.lParam = (LPARAM) pItem; tvis.item.pszText = (LPTSTR)pItem->_strCName.GetBuffer(pItem->_strCName.GetLength()); hitem = _tree.InsertItem(&tvis); InsertItem( hitem, pItem ); } } void InsertItem( HTREEITEM hitem, CategoryItem* pItem ) { for ( int i = 0 ; i < pItem->_childItemLst.size(); i++ ) { CategoryItem* pChildItem = pItem->_childItemLst[i]; HTREEITEM hChilditem = NULL; TV_INSERTSTRUCT tvis = {0}; tvis.item.mask = TVIF_PARAM | TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE; tvis.hParent = hitem; tvis.hInsertAfter = TVI_LAST; tvis.item.iImage = 0; tvis.item.iSelectedImage = 0; tvis.item.lParam = (LPARAM) pChildItem; tvis.item.pszText = (LPTSTR)pChildItem->_strCName.GetBuffer(pItem->_strCName.GetLength()); hChilditem = _tree.InsertItem(&tvis); InsertItem( hChilditem, pChildItem ); } } public: CTreeViewCtrl _tree; };
[ "ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 131 ] ] ]
9104f46da53f94d7317c36895a8be8ba09a9278b
2aa5cc5456b48811b7e4dee09cd7d1b019e3f7cc
/engine/texture/material.cpp
3025830fc58e543125b383a91f9f55237c9401dc
[]
no_license
tstivers/eXistenZ
eb2da9d6d58926b99495319080e13f780862fca0
2f5df51fb71d44c3e2689929c9249d10223f8d56
refs/heads/master
2021-09-02T22:50:36.733142
2010-11-16T06:47:24
2018-01-04T00:51:21
116,196,014
0
0
null
null
null
null
UTF-8
C++
false
false
577
cpp
#include "precompiled.h" #include "texture/material.h" namespace texture { }; using namespace texture; Material::Material() { reset(); } Material::Material(D3DCOLOR ambient, D3DXVECTOR3 direction, D3DXCOLOR color) : ambient(ambient) { ZeroMemory(&light, sizeof(D3DLIGHT9)); light.Type = D3DLIGHT_DIRECTIONAL; light.Diffuse = color; light.Direction = direction; } Material::~Material() { } void Material::reset() { ZeroMemory(&light, sizeof(D3DLIGHT9)); ZeroMemory(&ambient, sizeof(D3DCOLOR)); light.Type = D3DLIGHT_DIRECTIONAL; }
[ "tstivers@localhost" ]
[ [ [ 1, 33 ] ] ]
a68450047eaf0acb4cb319dc5f7b1c52e2bf9ac1
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/math/test/compile_test/main.cpp
7768c8889f56512c51a3539ce8d4d64a00ac66f9
[ "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
385
cpp
// Copyright John Maddock 2009. // Use, modification and distribution are 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) extern void check(); int main(int argc, char* /*argv*/ []) { if(argc > 1000) check(); // should never actually be called. return 0; }
[ "metrix@Blended.(none)" ]
[ [ [ 1, 13 ] ] ]
8afa251a2a755c79e4c1ad24e3053f4e85ae2aa5
1493997bb11718d3c18c6632b6dd010535f742f5
/direct_ui/UIlib/UIBase.h
9395e0762ce376058488319b26cd6e89981c19a1
[]
no_license
kovrov/scrap
cd0cf2c98a62d5af6e4206a2cab7bb8e4560b168
b0f38d95dd4acd89c832188265dece4d91383bbb
refs/heads/master
2021-01-20T12:21:34.742007
2010-01-12T19:53:23
2010-01-12T19:53:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,277
h
#if !defined(AFX_UIBASE_H__20050509_3DFB_5C7A_C897_0080AD509054__INCLUDED_) #define AFX_UIBASE_H__20050509_3DFB_5C7A_C897_0080AD509054__INCLUDED_ #pragma once ///////////////////////////////////////////////////////////////////////////////////// // class CPaintManagerUI; #define UI_WNDSTYLE_CONTAINER (0) #define UI_WNDSTYLE_FRAME (WS_VISIBLE | WS_OVERLAPPEDWINDOW) #define UI_WNDSTYLE_CHILD (WS_VISIBLE | WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN) #define UI_WNDSTYLE_DIALOG (WS_VISIBLE | WS_POPUPWINDOW | WS_CAPTION | WS_DLGFRAME | WS_CLIPSIBLINGS | WS_CLIPCHILDREN) #define UI_WNDSTYLE_EX_FRAME (WS_EX_WINDOWEDGE) #define UI_WNDSTYLE_EX_DIALOG (WS_EX_TOOLWINDOW | WS_EX_DLGMODALFRAME) #define UI_CLASSSTYLE_CONTAINER (0) #define UI_CLASSSTYLE_FRAME (CS_VREDRAW | CS_HREDRAW) #define UI_CLASSSTYLE_CHILD (CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS | CS_SAVEBITS) #define UI_CLASSSTYLE_DIALOG (CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS | CS_SAVEBITS) ///////////////////////////////////////////////////////////////////////////////////// // #define ASSERT(expr) _ASSERTE(expr) #ifdef _DEBUG #define TRACE __Trace #define TRACEMSG __TraceMsg #else #define TRACE #define TRACEMSG _T("") #endif void UILIB_API __Trace(LPCTSTR pstrFormat, ...); LPCTSTR __TraceMsg(UINT uMsg); ///////////////////////////////////////////////////////////////////////////////////// // class UILIB_API CRect : public tagRECT { public: CRect(); CRect(const RECT& src); CRect(int iLeft, int iTop, int iRight, int iBottom); int GetWidth() const; int GetHeight() const; void Empty(); void Join(const RECT& rc); void ResetOffset(); void Normalize(); void Offset(int cx, int cy); void Inflate(int cx, int cy); void Deflate(int cx, int cy); void Union(CRect& rc); }; ///////////////////////////////////////////////////////////////////////////////////// // class UILIB_API CSize : public tagSIZE { public: CSize(); CSize(const SIZE& src); CSize(const RECT rc); CSize(int cx, int cy); }; ///////////////////////////////////////////////////////////////////////////////////// // class UILIB_API CPoint : public tagPOINT { public: CPoint(); CPoint(const POINT& src); CPoint(int x, int y); CPoint(LPARAM lParam); }; ///////////////////////////////////////////////////////////////////////////////////// // class UILIB_API CStdPtrArray { public: CStdPtrArray(int iPreallocSize = 0); virtual ~CStdPtrArray(); void Empty(); void Resize(int iSize); bool IsEmpty() const; int Find(LPVOID iIndex) const; bool Add(LPVOID pData); bool SetAt(int iIndex, LPVOID pData); bool InsertAt(int iIndex, LPVOID pData); bool Remove(int iIndex); int GetSize() const; LPVOID* GetData(); LPVOID GetAt(int iIndex) const; LPVOID operator[] (int nIndex) const; protected: LPVOID* m_ppVoid; int m_nCount; int m_nAllocated; }; ///////////////////////////////////////////////////////////////////////////////////// // class UILIB_API CStdValArray { public: CStdValArray(int iElementSize, int iPreallocSize = 0); virtual ~CStdValArray(); void Empty(); bool IsEmpty() const; bool Add(LPCVOID pData); bool Remove(int iIndex); int GetSize() const; LPVOID GetData(); LPVOID GetAt(int iIndex) const; LPVOID operator[] (int nIndex) const; protected: LPBYTE m_pVoid; int m_iElementSize; int m_nCount; int m_nAllocated; }; ///////////////////////////////////////////////////////////////////////////////////// // class UILIB_API CWindowWnd { public: CWindowWnd(); HWND GetHWND() const; operator HWND() const; bool RegisterWindowClass(); bool RegisterSuperclass(); HWND Create(HWND hwndParent, LPCTSTR pstrName, DWORD dwStyle, DWORD dwExStyle, const RECT rc, HMENU hMenu = NULL); HWND Create(HWND hwndParent, LPCTSTR pstrName, DWORD dwStyle, DWORD dwExStyle, int x = CW_USEDEFAULT, int y = CW_USEDEFAULT, int cx = CW_USEDEFAULT, int cy = CW_USEDEFAULT, HMENU hMenu = NULL); HWND Subclass(HWND hWnd); void Unsubclass(); void ShowWindow(bool bShow = true, bool bTakeFocus = true); bool ShowModal(); void Close(); void CenterWindow(); void SetIcon(UINT nRes); protected: virtual LPCTSTR GetWindowClassName() const = 0; virtual LPCTSTR GetSuperClassName() const; virtual UINT GetClassStyle() const; LRESULT SendMessage(UINT uMsg, WPARAM wParam = 0, LPARAM lParam = 0L); LRESULT PostMessage(UINT uMsg, WPARAM wParam = 0, LPARAM lParam = 0L); void ResizeClient(int cx = -1, int cy = -1); virtual LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam); virtual void OnFinalMessage(HWND hWnd); static LRESULT CALLBACK __WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK __ControlProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); protected: HWND m_hWnd; WNDPROC m_OldWndProc; bool m_bSubclassed; }; ///////////////////////////////////////////////////////////////////////////////////// // class UILIB_API CWaitCursor { public: CWaitCursor(); ~CWaitCursor(); protected: HCURSOR m_hOrigCursor; }; ///////////////////////////////////////////////////////////////////////////////////// // class UILIB_API CStdString { public: enum { MAX_LOCAL_STRING_LEN = 63 }; CStdString(); CStdString(const TCHAR ch); CStdString(const CStdString& src); CStdString(LPCTSTR lpsz, int nLen = -1); virtual ~CStdString(); static CStdString RES(UINT nRes); void Empty(); int GetLength() const; bool IsEmpty() const; TCHAR GetAt(int nIndex) const; void Append(LPCTSTR pstr); void Assign(LPCTSTR pstr, int nLength = -1); LPCTSTR GetData(); void SetAt(int nIndex, TCHAR ch); operator LPCTSTR() const; TCHAR operator[] (int nIndex) const; const CStdString& operator=(const CStdString& src); const CStdString& operator=(const TCHAR ch); const CStdString& operator=(LPCTSTR pstr); #ifndef _UNICODE const CStdString& CStdString::operator=(LPCWSTR lpwStr); #endif CStdString operator+(const CStdString& src); CStdString operator+(LPCTSTR pstr); const CStdString& operator+=(const CStdString& src); const CStdString& operator+=(LPCTSTR pstr); const CStdString& operator+=(const TCHAR ch); bool operator == (LPCTSTR str) const; bool operator != (LPCTSTR str) const; bool operator <= (LPCTSTR str) const; bool operator < (LPCTSTR str) const; bool operator >= (LPCTSTR str) const; bool operator > (LPCTSTR str) const; int Compare(LPCTSTR pstr) const; int CompareNoCase(LPCTSTR pstr) const; void MakeUpper(); void MakeLower(); CStdString Left(int nLength) const; CStdString Mid(int iPos, int nLength = -1) const; CStdString Right(int nLength) const; int Find(TCHAR ch, int iPos = 0) const; int Find(LPCTSTR pstr, int iPos = 0) const; int ReverseFind(TCHAR ch) const; int Replace(LPCTSTR pstrFrom, LPCTSTR pstrTo); void ProcessResourceTokens(); int __cdecl Format(LPCTSTR pstrFormat, ...); protected: LPTSTR m_pstr; TCHAR m_szBuffer[MAX_LOCAL_STRING_LEN + 1]; }; #endif // !defined(AFX_UIBASE_H__20050509_3DFB_5C7A_C897_0080AD509054__INCLUDED_)
[ [ [ 1, 281 ] ] ]
e6cbfd629e663aad8513dcda428768c79821feed
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/DynamicTexture2D.h
4a7ec21a57f82b74a54c1754d647ad313b2893e9
[]
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,756
h
#pragma once #ifndef __HALAK_DYNAMICTEXTURE2D_H__ #define __HALAK_DYNAMICTEXTURE2D_H__ # include <Halak/FWD.h> # include <Halak/Texture2D.h> # include <Halak/Rectangle.h> namespace Halak { class DynamicTexture2D : public Texture2D { public: class Locker { public: Locker(); ~Locker(); void* GetBuffer(); int GetPitch() const; private: void SetData(DynamicTexture2DPtr texture, void* buffer, int pitch); private: DynamicTexture2DPtr texture; void* buffer; int pitch; private: Locker(const Locker&); Locker& operator = (const Locker&); friend class DynamicTexture2D; }; public: DynamicTexture2D(GraphicsDevice* graphicsDevice, int width, int height, PixelFormat format); virtual ~DynamicTexture2D(); bool Lock(Locker& outLocker); bool Lock(Locker& outLocker, const Rectangle& rectangle); void Unlock(Locker& outLocker); bool IsLocked() const; PixelFormat GetFormat() const; protected: virtual D3DTextureInfo CreateD3DTexture(); private: int width; int height; PixelFormat format; bool isLocked; }; } #endif
[ [ [ 1, 61 ] ] ]
d982b37397e965d6af29cbd206cbf8a0d55aa85e
3a103ad1fc799ce85943c78bcaf092e34208c0e2
/Source/Material.cpp
3a8389b07903b731f511ee3aebe5d7dd02d9363a
[]
no_license
whirlp00l/rendering
2e93d5c6835e054e85f9710efac27de938cae445
770c2ad19b62fd8dce86ff0ebf2c7ffc829893ca
refs/heads/master
2020-05-16T23:19:16.307640
2010-10-20T22:36:47
2010-10-20T22:36:47
37,064,816
0
0
null
null
null
null
UTF-8
C++
false
false
6,646
cpp
#include "Material.h" #include "DebugMem.h" #include "Lambert.h" #include "Console.h" #include "PointLight.h" #include "Scene.h" #include "Ray.h" #include "WorleyNoise.h" Material::Material() { m_phong_exp = 0.0f; m_refractive_index = 1.0f; m_use_bump_map = false; m_bump_map_noise_maker = NULL; m_type = Material::UNDEFINED; } Material::~Material() { } Vector3 Material::shade(const Ray&, const HitInfo&, const Scene&) const { return Vector3(1.0f, 1.0f, 1.0f); } Vector3 Material::getPhongHighlightContribution( const PointLight * pLight, const Ray& ray, const HitInfo& hit ) const { Vector3 contribution(0,0,0); Vector3 l = pLight->position() - hit.P; l.normalize(); Vector3 viewDir = -ray.d; Vector3 normal = m_use_bump_map ? calcBumpMappedNormal( hit.P, hit.N ) : hit.N; Vector3 lightReflectDir = 2 * dot( l, normal ) * normal - l; // direction to light reflected across normal float viewDirDotReflectDir = dot( viewDir, lightReflectDir ); if( viewDirDotReflectDir > 0 ) contribution += std::max(0.0f, pow(viewDirDotReflectDir, m_phong_exp)) * pLight->color(); return contribution; } Material * Material::loadMaterial( char * fileName ) { char fileNameWithExt[80]; strncpy_s( fileNameWithExt, 80, fileName, _TRUNCATE ); char * endStr = strchr( fileNameWithExt, '\0' ); // add .mtl suffix strncpy_s( endStr, 80 - strlen(fileNameWithExt) - 1, ".mtl", _TRUNCATE ); FILE * fp; fopen_s( &fp, fileNameWithExt, "rb" ); if( !fp ) { debug( "Error: could not open %s for reading.\n", fileNameWithExt ); return NULL; } Vector3 kd(1), ka(0); bool useBumpMap; int octaves, seed; // for bump map noise maker float freq, amp; // for bump map noise maker char buf[80]; while( fgets( buf, 80, fp ) != 0 ) { // this is a comment; skip it if( buf[0] == '#' ) continue; char * space = strchr( buf, ' ' ); if( space ) { *space = '\0'; // ambient term if( strcmp( buf, "Ka" ) == 0 ) { float x, y, z; sscanf_s(space + 1, "%f %f %f\n", &x, &y, &z); ka = Vector3(x,y,z); } // diffuse term else if( strcmp( buf, "Kd" ) == 0 ) { float x, y, z; sscanf_s(space + 1, "%f %f %f\n", &x, &y, &z); kd = Vector3(x,y,z); } // bump mapping information else if( strcmp( buf, "use_bump_map" ) == 0 ) { sscanf_s(space + 1, "%d %f %f %d\n", &octaves, &freq, &amp, &seed); useBumpMap = true; } // else ignore line } // else ignore line } ( void )fclose( fp ); Material * material = new Lambert( kd, ka ); if( useBumpMap ) material->setUseBumpMap( true, octaves, freq, amp, seed ); return material; } void Material::setUseBumpMap( bool useBumpMap, int octaves, float freq, float amp, int seed ) { // use a bump map for this material if( useBumpMap ) { // if we don't already have one, we need to create a noise maker if( !m_bump_map_noise_maker ) { m_bump_map_noise_maker = new CustomizablePerlinNoise( octaves, freq, amp, seed ); } } // DON'T use a bump map for this material else { if( m_use_bump_map ) { delete m_bump_map_noise_maker; m_bump_map_noise_maker = NULL; } } m_use_bump_map = useBumpMap; } Vector3 Material::calcBumpMappedNormal( Vector3 hitPoint, Vector3 origNormal ) const { // if we don't want to use bumpmapping, just return the original normal if( !m_use_bump_map || !m_bump_map_noise_maker ) return origNormal; /* * IDEA: * We want to approximate changing the height of each point that we render on the surface. * If the original point is P and its normal is N, then the new point can be defined as: * P' = P + h * N * where h is a randomly generated height (given by a noise function). * We can define 2 vectors U and V that describe the plane in which point P sits (using its normal N): * U = R x N, V = N x U * where R is some randomly generated vector that is NOT parallel to N. * We can then find dP'/dU and dP'/dV, which define the surface at P', as follows (uses the derivative of the 1st eqn): * dP'/dU = dP/dU + dh/dU * N + h * dN/dU * dP'/dV = dP/dV + dh/dV * N + h * dN/dV * Note that in both of these partial derivatives, the 3rd term in the sum can be ignored * since N does not change with respec to U or V. In other words, * dP'/dU = dP/dU + dh/dU * N * dP'/dV = dP/dV + dh/dV * N * Then our desired bump-mapped normal, N', can be found by taking the cross product of 2 derivates: * N' = dP'/dU x dP'/dV */ // calculate random bump-mapped height with noise function float bumpHeight = m_bump_map_noise_maker->Get( hitPoint.x, hitPoint.y, hitPoint.z ); // find a random vector that we can use to find U (random direction can't be parallel to original normal) Vector3 randomDir; float magCrossProd; float epsilonSquared = epsilon * epsilon; // square epsilon to avoid having to take the sqrt to get the cross product's magnitude do { randomDir.x = rand() / static_cast<double>(RAND_MAX); // yields random value in range [0,1] randomDir.y = rand() / static_cast<double>(RAND_MAX); // yields random value in range [0,1] randomDir.z = rand() / static_cast<double>(RAND_MAX); // yields random value in range [0,1] randomDir.normalize(); Vector3 crossProd = cross( randomDir, origNormal ); magCrossProd = crossProd.length2(); } while( magCrossProd < epsilonSquared ); // now we can calculate U and V Vector3 uDir = cross( randomDir, origNormal ); uDir.normalize(); Vector3 vDir = cross( origNormal, uDir ); vDir.normalize(); // now calculate the partial derivates of P' with respect to U and V Vector3 dPdU = ( ( hitPoint + epsilon * uDir ) - ( hitPoint - epsilon * uDir ) ) / ( 2 * epsilon ); Vector3 dPdV = ( ( hitPoint + epsilon * vDir ) - ( hitPoint - epsilon * vDir ) ) / ( 2 * epsilon ); // calculate the partial derivates of h with respect to U and V Vector3 PUPrime = hitPoint + epsilon * uDir; Vector3 PVPrime = hitPoint + epsilon * vDir; Vector3 dHdU = ( m_bump_map_noise_maker->Get( PUPrime.x, PUPrime.y, PUPrime.z ) - bumpHeight ) / epsilon; Vector3 dHdV = ( m_bump_map_noise_maker->Get( PVPrime.x, PVPrime.y, PVPrime.z ) - bumpHeight ) / epsilon; // now we can calculate dP'/dU and dP'/dV Vector3 dPPrime_dU = dPdU + dHdU * origNormal; Vector3 dPPrime_dV = dPdV + dHdV * origNormal; // finally, calcualte the perturbed normal Vector3 perturbedNormal = cross( dPPrime_dU, dPPrime_dV ); perturbedNormal.normalize(); return perturbedNormal; }
[ "DaStar2B@82a46b14-ece5-f9c8-6756-62631a89e06b" ]
[ [ [ 1, 210 ] ] ]
2779c21f3a21b47dada6a183e1c00220e77a38b6
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/ShaderDX10.cpp
9d3be068216036bb1f2e1fdeec43340f0bbb2b3c
[]
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
12,916
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: ShaderDX10.cpp Version: 0.08 --------------------------------------------------------------------------- */ #include "PrecompiledHeaders.h" #include "ShaderDX10.h" #include "ShaderConstant.h" #include "DX10Mapping.h" #include "RendererDX10.h" namespace nGENE { // Initialize static members TypeInfo ShaderDX10::Type(L"ShaderDX10", &Shader::Type); ShaderDX10::ShaderDX10(const SHADER_DESC& _desc): Shader(_desc), m_pVertexShader(NULL), m_pConstants(NULL), m_pCode(NULL) { } //---------------------------------------------------------------------- ShaderDX10::~ShaderDX10() { cleanup(); } //---------------------------------------------------------------------- void ShaderDX10::cleanup() { NGENE_RELEASE(m_pConstants); NGENE_RELEASE(m_pPixelShader); NGENE_RELEASE(m_pGeometryShader); NGENE_RELEASE(m_pVertexShader); NGENE_RELEASE(m_pCode); } //---------------------------------------------------------------------- void ShaderDX10::bind() const { ID3D10Device* pDevice = reinterpret_cast<ID3D10Device*>(Renderer::getSingleton().getDeviceRender().getDevicePtr()); //m_pConstants->SetDefaults(pDevice); Shader::bind(); switch(m_ShaderDesc.type) { case SHADER_VERTEX: pDevice->VSSetShader(m_pVertexShader); break; case SHADER_GEOMETRY: pDevice->GSSetShader(m_pGeometryShader); break; case SHADER_PIXEL: pDevice->PSSetShader(m_pPixelShader); break; case SHADER_EFFECT: break; default: return; } } //---------------------------------------------------------------------- void ShaderDX10::unbind() const { ID3D10Device* pDevice = reinterpret_cast<ID3D10Device*>(Renderer::getSingleton().getDeviceRender().getDevicePtr()); switch(m_ShaderDesc.type) { case SHADER_VERTEX: pDevice->VSSetShader(NULL); break; case SHADER_GEOMETRY: pDevice->GSSetShader(NULL); break; case SHADER_PIXEL: pDevice->PSSetShader(NULL); break; case SHADER_EFFECT: break; default: return; } } //---------------------------------------------------------------------- void ShaderDX10::createVertexShader() { DeviceRender& pDeviceRender = Renderer::getSingleton().getDeviceRender(); ID3D10Device* pDevice = reinterpret_cast<ID3D10Device*>(pDeviceRender.getDevicePtr()); ID3D10Blob* pErrors = NULL; // Get shader profile m_ShaderDesc.profile = "vs_4_0"; if(!m_ShaderDesc.function.compare("")) m_ShaderDesc.function = "main"; dword flags = 0; if(m_ShaderDesc.debugInfo) flags |= D3D10_SHADER_DEBUG; // Load shader file FileManager& mgr = FileManager::getSingleton(); IFile* pFile = mgr.openFile(m_ShaderDesc.fileName, OPEN_READ | OPEN_BINARY, FT_NORMAL); uint size = pFile->getSize(); char* buffer = new char[size]; pFile->read((char*)buffer, size); mgr.closeFile(m_ShaderDesc.fileName); string stName(m_ShaderDesc.fileName.begin(), m_ShaderDesc.fileName.end()); D3DX10CompileFromMemory(buffer, size, stName.c_str(), NULL, NULL, m_ShaderDesc.function.c_str(), m_ShaderDesc.profile.c_str(), flags, 0, NULL, &m_pCode, &pErrors, NULL); NGENE_DELETE_ARRAY(buffer); if((pErrors) || (!m_pCode)) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"One or more errors occurred while compiling vertex shader"); if(pErrors) { handleErrors(pErrors); NGENE_RELEASE(pErrors); } return; } HRESULT hr; if(FAILED(hr = pDevice->CreateVertexShader((dword*)m_pCode->GetBufferPointer(), m_pCode->GetBufferSize(), &m_pVertexShader))) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"Shader couldn't be created. Reason: %ls", DX10Mapping::getDXErrorDescription(hr)); return; } // m_pConstants->SetDefaults(pDevice); loadConstants(); } //---------------------------------------------------------------------- void ShaderDX10::createGeometryShader() { DeviceRender& pDeviceRender = Renderer::getSingleton().getDeviceRender(); ID3D10Device* pDevice = reinterpret_cast<ID3D10Device*>(pDeviceRender.getDevicePtr()); ID3D10Blob* pErrors = NULL; // Get shader profile m_ShaderDesc.profile = "gs_4_0"; if(!m_ShaderDesc.function.compare("")) m_ShaderDesc.function = "main"; dword flags = 0; if(m_ShaderDesc.debugInfo) flags |= D3D10_SHADER_DEBUG; // Load shader file FileManager& mgr = FileManager::getSingleton(); IFile* pFile = mgr.openFile(m_ShaderDesc.fileName, OPEN_READ | OPEN_BINARY, FT_NORMAL); uint size = pFile->getSize(); char* buffer = new char[size]; pFile->read((char*)buffer, size); mgr.closeFile(m_ShaderDesc.fileName); string stName(m_ShaderDesc.fileName.begin(), m_ShaderDesc.fileName.end()); D3DX10CompileFromMemory(buffer, size, stName.c_str(), NULL, NULL, m_ShaderDesc.function.c_str(), m_ShaderDesc.profile.c_str(), flags, 0, NULL, &m_pCode, &pErrors, NULL); NGENE_DELETE_ARRAY(buffer); if((pErrors) || (!m_pCode)) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"One or more errors occured while compiling geometry shader"); if(pErrors) { handleErrors(pErrors); NGENE_RELEASE(pErrors); } return; } HRESULT hr; if(FAILED(hr = pDevice->CreateGeometryShader((dword*)m_pCode->GetBufferPointer(), m_pCode->GetBufferSize(), &m_pGeometryShader))) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"Shader couldn't be created. Reason: %ls", DX10Mapping::getDXErrorDescription(hr)); } loadConstants(); } //---------------------------------------------------------------------- void ShaderDX10::createPixelShader() { DeviceRender& pDeviceRender = Renderer::getSingleton().getDeviceRender(); ID3D10Device* pDevice = reinterpret_cast<ID3D10Device*>(pDeviceRender.getDevicePtr()); ID3D10Blob* pErrors = NULL; // Get shader profile m_ShaderDesc.profile = "ps_4_0"; if(!m_ShaderDesc.function.compare("")) m_ShaderDesc.function = "main"; dword flags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY; if(m_ShaderDesc.debugInfo) flags |= D3D10_SHADER_DEBUG; // Load shader file FileManager& mgr = FileManager::getSingleton(); IFile* pFile = mgr.openFile(m_ShaderDesc.fileName, OPEN_READ | OPEN_BINARY, FT_NORMAL); uint size = pFile->getSize(); char* buffer = new char[size]; pFile->read((char*)buffer, size); mgr.closeFile(m_ShaderDesc.fileName); string stName(m_ShaderDesc.fileName.begin(), m_ShaderDesc.fileName.end()); D3DX10CompileFromMemory(buffer, size, stName.c_str(), NULL, NULL, m_ShaderDesc.function.c_str(), m_ShaderDesc.profile.c_str(), flags, 0, NULL, &m_pCode, &pErrors, NULL); NGENE_DELETE_ARRAY(buffer); if((pErrors) || (!m_pCode)) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"One or more errors occured while compiling pixel shader"); if(pErrors) { handleErrors(pErrors); NGENE_RELEASE(pErrors); } return; } HRESULT hr; if(FAILED(hr = pDevice->CreatePixelShader((dword*)m_pCode->GetBufferPointer(), m_pCode->GetBufferSize(), &m_pPixelShader))) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"Shader couldn't be created. Reason: %ls", DX10Mapping::getDXErrorDescription(hr)); } loadConstants(); } //---------------------------------------------------------------------- void ShaderDX10::loadConstants() { HRESULT hr; ID3D10ShaderReflection* pReflection = NULL; hr = D3D10ReflectShader((void*)m_pCode->GetBufferPointer(), m_pCode->GetBufferSize(), &pReflection); if(FAILED(hr)) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"Shader reflection could not be obtained. Reason: %ls", DX10Mapping::getDXErrorDescription(hr)); return; } D3D10_SHADER_DESC desc; pReflection->GetDesc(&desc); ID3D10ShaderReflectionConstantBuffer* pConstantBuffer = NULL; uint totalSize = 0; for(uint i = 0; i < desc.BoundResources; ++i) { pConstantBuffer = pReflection->GetConstantBufferByIndex(i); uint count = 0; D3D10_SHADER_BUFFER_DESC bufferDesc; pConstantBuffer->GetDesc(&bufferDesc); if(bufferDesc.Type == D3D10_CT_TBUFFER) continue; count = bufferDesc.Variables; ID3D10ShaderReflectionVariable* pConstant = NULL; D3D10_SHADER_VARIABLE_DESC constantDesc; for(uint j = 0; j < count; ++j) { pConstant = pConstantBuffer->GetVariableByIndex(j); pConstant->GetDesc(&constantDesc); float* pDefault = NULL; if(constantDesc.DefaultValue) { pDefault = new float[constantDesc.Size / 4]; memcpy(pDefault, constantDesc.DefaultValue, constantDesc.Size); } ShaderConstant shaderConstant; shaderConstant.setName(constantDesc.Name); shaderConstant.setValuesCount(constantDesc.Size / 4); shaderConstant.setDefaultValue(pDefault); shaderConstant.setOffset(constantDesc.StartOffset); ShaderConstant* pConstant = new ShaderConstant(shaderConstant); m_pVariables.push_back(pConstant); m_pVariablesRef[pConstant->getName()] = pConstant; totalSize += constantDesc.Size; NGENE_DELETE_ARRAY(pDefault); } } if(totalSize) { DeviceRender& pDeviceRender = Renderer::getSingleton().getDeviceRender(); ID3D10Device* pDevice = reinterpret_cast<ID3D10Device*>(pDeviceRender.getDevicePtr()); D3D10_BUFFER_DESC bufferDesc; bufferDesc.ByteWidth = totalSize; bufferDesc.Usage = D3D10_USAGE_DYNAMIC; bufferDesc.BindFlags = D3D10_BIND_CONSTANT_BUFFER; bufferDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; bufferDesc.MiscFlags = 0; pDevice->CreateBuffer(&bufferDesc, NULL, &m_pConstants); } } //---------------------------------------------------------------------- void ShaderDX10::handleErrors(ID3D10Blob* _errors) { void* buffer = _errors->GetBufferPointer(); string msg = (char*)buffer; wstring msg2 = L"Shader error: "; msg2.append(msg.begin(), msg.end()); Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, msg2.c_str()); } //---------------------------------------------------------------------- void ShaderDX10::createEffect() { } //---------------------------------------------------------------------- void ShaderDX10::setFloat(const string& _name, const float& _value) { ID3D10Buffer* pBuffer = NULL; m_pConstants->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&pBuffer); void* pTemp = pBuffer + m_pVariablesRef[_name]->getOffset(); memcpy(pTemp, &_value, sizeof(float)); m_pConstants->Unmap(); } //---------------------------------------------------------------------- void ShaderDX10::setFloatArray(const string& _name, const float* _values, const uint _count) const { ID3D10Buffer* pBuffer = NULL; m_pConstants->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&pBuffer); void* pTemp = pBuffer + m_pVariablesRef[_name]->getOffset(); memcpy(pTemp, &_values, sizeof(float) * _count); m_pConstants->Unmap(); } //---------------------------------------------------------------------- void ShaderDX10::setMatrix(const string& _name, const Matrix4x4& _mat) { ID3D10Device* pDevice = reinterpret_cast<ID3D10Device*>(Renderer::getSingleton().getDeviceRender().getDevicePtr()); } //---------------------------------------------------------------------- void ShaderDX10::setInteger(const string& _name, const int& _value) { } //---------------------------------------------------------------------- void ShaderDX10::setIntegerArray(const string& _name, const int* _values, const uint _count) const { } //---------------------------------------------------------------------- void ShaderDX10::setBoolean(const string& _name, const bool& _value) { } //---------------------------------------------------------------------- void ShaderDX10::setBooleanArray(const string& _name, const bool* _values, const uint _count) const { } //---------------------------------------------------------------------- }
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 434 ] ] ]
ee9f7edd29fc087844a7e1e2128d8a27366d0d01
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/multiplayer/dmc/dlls/triggers.cpp
485ca62635e36ac7979e1ee661cf144c17ff8927
[]
no_license
joropito/amxxgroup
637ee71e250ffd6a7e628f77893caef4c4b1af0a
f948042ee63ebac6ad0332f8a77393322157fa8f
refs/heads/master
2021-01-10T09:21:31.449489
2010-04-11T21:34:27
2010-04-11T21:34:27
47,087,485
1
0
null
null
null
null
UTF-8
C++
false
false
72,718
cpp
/*** * * Copyright (c) 1996-2002, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ /* ===== triggers.cpp ======================================================== spawn and use functions for editor-placed triggers */ #include "extdll.h" #include "util.h" #include "cbase.h" #include "player.h" #include "saverestore.h" #include "trains.h" // trigger_camera has train functionality #include "gamerules.h" #define SF_TRIGGER_PUSH_START_OFF 2//spawnflag that makes trigger_push spawn turned OFF #define SF_TRIGGER_HURT_TARGETONCE 1// Only fire hurt target once #define SF_TRIGGER_HURT_START_OFF 2//spawnflag that makes trigger_push spawn turned OFF #define SF_TRIGGER_HURT_NO_CLIENTS 8//spawnflag that makes trigger_push spawn turned OFF #define SF_TRIGGER_HURT_CLIENTONLYFIRE 16// trigger hurt will only fire its target if it is hurting a client #define SF_TRIGGER_HURT_CLIENTONLYTOUCH 32// only clients may touch this trigger. extern DLL_GLOBAL BOOL g_fGameOver; extern Vector g_vecTeleMins[ MAX_TELES ]; extern Vector g_vecTeleMaxs[ MAX_TELES ]; extern int g_iTeleNum; extern void SetMovedir(entvars_t* pev); extern Vector VecBModelOrigin( entvars_t* pevBModel ); extern unsigned short g_sTeleport; class CFrictionModifier : public CBaseEntity { public: void Spawn( void ); void KeyValue( KeyValueData *pkvd ); void EXPORT ChangeFriction( CBaseEntity *pOther ); virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); virtual int ObjectCaps( void ) { return CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } static TYPEDESCRIPTION m_SaveData[]; float m_frictionFraction; // Sorry, couldn't resist this name :) }; LINK_ENTITY_TO_CLASS( func_friction, CFrictionModifier ); // Global Savedata for changelevel friction modifier TYPEDESCRIPTION CFrictionModifier::m_SaveData[] = { DEFINE_FIELD( CFrictionModifier, m_frictionFraction, FIELD_FLOAT ), }; IMPLEMENT_SAVERESTORE(CFrictionModifier,CBaseEntity); // Modify an entity's friction void CFrictionModifier :: Spawn( void ) { pev->solid = SOLID_TRIGGER; SET_MODEL(ENT(pev), STRING(pev->model)); // set size and link into world pev->movetype = MOVETYPE_NONE; SetTouch( ChangeFriction ); } // Sets toucher's friction to m_frictionFraction (1.0 = normal friction) void CFrictionModifier :: ChangeFriction( CBaseEntity *pOther ) { if ( pOther->pev->movetype != MOVETYPE_BOUNCEMISSILE && pOther->pev->movetype != MOVETYPE_BOUNCE ) pOther->pev->friction = m_frictionFraction; } // Sets toucher's friction to m_frictionFraction (1.0 = normal friction) void CFrictionModifier :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "modifier")) { m_frictionFraction = atof(pkvd->szValue) / 100.0; pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } // This trigger will fire when the level spawns (or respawns if not fire once) // It will check a global state before firing. It supports delay and killtargets #define SF_AUTO_FIREONCE 0x0001 class CAutoTrigger : public CBaseDelay { public: void KeyValue( KeyValueData *pkvd ); void Spawn( void ); void Precache( void ); void Think( void ); int ObjectCaps( void ) { return CBaseDelay::ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; private: int m_globalstate; USE_TYPE triggerType; }; LINK_ENTITY_TO_CLASS( trigger_auto, CAutoTrigger ); TYPEDESCRIPTION CAutoTrigger::m_SaveData[] = { DEFINE_FIELD( CAutoTrigger, m_globalstate, FIELD_STRING ), DEFINE_FIELD( CAutoTrigger, triggerType, FIELD_INTEGER ), }; IMPLEMENT_SAVERESTORE(CAutoTrigger,CBaseDelay); void CAutoTrigger::KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "globalstate")) { m_globalstate = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "triggerstate")) { int type = atoi( pkvd->szValue ); switch( type ) { case 0: triggerType = USE_OFF; break; case 2: triggerType = USE_TOGGLE; break; default: triggerType = USE_ON; break; } pkvd->fHandled = TRUE; } else CBaseDelay::KeyValue( pkvd ); } void CAutoTrigger::Spawn( void ) { Precache(); } void CAutoTrigger::Precache( void ) { pev->nextthink = gpGlobals->time + 0.1; } void CAutoTrigger::Think( void ) { if ( !m_globalstate || gGlobalState.EntityGetState( m_globalstate ) == GLOBAL_ON ) { SUB_UseTargets( this, triggerType, 0 ); if ( pev->spawnflags & SF_AUTO_FIREONCE ) UTIL_Remove( this ); } } #define SF_RELAY_FIREONCE 0x0001 class CTriggerRelay : public CBaseDelay { public: void KeyValue( KeyValueData *pkvd ); void Spawn( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); int ObjectCaps( void ) { return CBaseDelay::ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; private: USE_TYPE triggerType; }; LINK_ENTITY_TO_CLASS( trigger_relay, CTriggerRelay ); TYPEDESCRIPTION CTriggerRelay::m_SaveData[] = { DEFINE_FIELD( CTriggerRelay, triggerType, FIELD_INTEGER ), }; IMPLEMENT_SAVERESTORE(CTriggerRelay,CBaseDelay); void CTriggerRelay::KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "triggerstate")) { int type = atoi( pkvd->szValue ); switch( type ) { case 0: triggerType = USE_OFF; break; case 2: triggerType = USE_TOGGLE; break; default: triggerType = USE_ON; break; } pkvd->fHandled = TRUE; } else CBaseDelay::KeyValue( pkvd ); } void CTriggerRelay::Spawn( void ) { } void CTriggerRelay::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { SUB_UseTargets( this, triggerType, 0 ); if ( pev->spawnflags & SF_RELAY_FIREONCE ) UTIL_Remove( this ); } //********************************************************** // The Multimanager Entity - when fired, will fire up to 16 targets // at specified times. // FLAG: THREAD (create clones when triggered) // FLAG: CLONE (this is a clone for a threaded execution) #define SF_MULTIMAN_CLONE 0x80000000 #define SF_MULTIMAN_THREAD 0x00000001 class CMultiManager : public CBaseToggle { public: void KeyValue( KeyValueData *pkvd ); void Spawn ( void ); void EXPORT ManagerThink ( void ); void EXPORT ManagerUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); #if _DEBUG void EXPORT ManagerReport( void ); #endif BOOL HasTarget( string_t targetname ); int ObjectCaps( void ) { return CBaseToggle::ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; int m_cTargets; // the total number of targets in this manager's fire list. int m_index; // Current target float m_startTime;// Time we started firing int m_iTargetName [ MAX_MULTI_TARGETS ];// list if indexes into global string array float m_flTargetDelay [ MAX_MULTI_TARGETS ];// delay (in seconds) from time of manager fire to target fire private: inline BOOL IsClone( void ) { return (pev->spawnflags & SF_MULTIMAN_CLONE) ? TRUE : FALSE; } inline BOOL ShouldClone( void ) { if ( IsClone() ) return FALSE; return (pev->spawnflags & SF_MULTIMAN_THREAD) ? TRUE : FALSE; } CMultiManager *Clone( void ); }; LINK_ENTITY_TO_CLASS( multi_manager, CMultiManager ); // Global Savedata for multi_manager TYPEDESCRIPTION CMultiManager::m_SaveData[] = { DEFINE_FIELD( CMultiManager, m_cTargets, FIELD_INTEGER ), DEFINE_FIELD( CMultiManager, m_index, FIELD_INTEGER ), DEFINE_FIELD( CMultiManager, m_startTime, FIELD_TIME ), DEFINE_ARRAY( CMultiManager, m_iTargetName, FIELD_STRING, MAX_MULTI_TARGETS ), DEFINE_ARRAY( CMultiManager, m_flTargetDelay, FIELD_FLOAT, MAX_MULTI_TARGETS ), }; IMPLEMENT_SAVERESTORE(CMultiManager,CBaseToggle); void CMultiManager :: KeyValue( KeyValueData *pkvd ) { // UNDONE: Maybe this should do something like this: //CBaseToggle::KeyValue( pkvd ); // if ( !pkvd->fHandled ) // ... etc. if (FStrEq(pkvd->szKeyName, "wait")) { m_flWait = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else // add this field to the target list { // this assumes that additional fields are targetnames and their values are delay values. if ( m_cTargets < MAX_MULTI_TARGETS ) { char tmp[128]; UTIL_StripToken( pkvd->szKeyName, tmp ); m_iTargetName [ m_cTargets ] = ALLOC_STRING( tmp ); m_flTargetDelay [ m_cTargets ] = atof (pkvd->szValue); m_cTargets++; pkvd->fHandled = TRUE; } } } void CMultiManager :: Spawn( void ) { pev->solid = SOLID_NOT; SetUse ( ManagerUse ); SetThink ( ManagerThink); // Sort targets // Quick and dirty bubble sort int swapped = 1; while ( swapped ) { swapped = 0; for ( int i = 1; i < m_cTargets; i++ ) { if ( m_flTargetDelay[i] < m_flTargetDelay[i-1] ) { // Swap out of order elements int name = m_iTargetName[i]; float delay = m_flTargetDelay[i]; m_iTargetName[i] = m_iTargetName[i-1]; m_flTargetDelay[i] = m_flTargetDelay[i-1]; m_iTargetName[i-1] = name; m_flTargetDelay[i-1] = delay; swapped = 1; } } } } BOOL CMultiManager::HasTarget( string_t targetname ) { for ( int i = 0; i < m_cTargets; i++ ) if ( FStrEq(STRING(targetname), STRING(m_iTargetName[i])) ) return TRUE; return FALSE; } // Designers were using this to fire targets that may or may not exist -- // so I changed it to use the standard target fire code, made it a little simpler. void CMultiManager :: ManagerThink ( void ) { float time; time = gpGlobals->time - m_startTime; while ( m_index < m_cTargets && m_flTargetDelay[ m_index ] <= time ) { FireTargets( STRING( m_iTargetName[ m_index ] ), m_hActivator, this, USE_TOGGLE, 0 ); m_index++; } if ( m_index >= m_cTargets )// have we fired all targets? { SetThink( NULL ); if ( IsClone() ) { UTIL_Remove( this ); return; } SetUse ( ManagerUse );// allow manager re-use } else pev->nextthink = m_startTime + m_flTargetDelay[ m_index ]; } CMultiManager *CMultiManager::Clone( void ) { CMultiManager *pMulti = GetClassPtr( (CMultiManager *)NULL ); edict_t *pEdict = pMulti->pev->pContainingEntity; memcpy( pMulti->pev, pev, sizeof(*pev) ); pMulti->pev->pContainingEntity = pEdict; pMulti->pev->spawnflags |= SF_MULTIMAN_CLONE; pMulti->m_cTargets = m_cTargets; memcpy( pMulti->m_iTargetName, m_iTargetName, sizeof( m_iTargetName ) ); memcpy( pMulti->m_flTargetDelay, m_flTargetDelay, sizeof( m_flTargetDelay ) ); return pMulti; } // The USE function builds the time table and starts the entity thinking. void CMultiManager :: ManagerUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { // In multiplayer games, clone the MM and execute in the clone (like a thread) // to allow multiple players to trigger the same multimanager if ( ShouldClone() ) { CMultiManager *pClone = Clone(); pClone->ManagerUse( pActivator, pCaller, useType, value ); return; } m_hActivator = pActivator; m_index = 0; m_startTime = gpGlobals->time; SetUse( NULL );// disable use until all targets have fired SetThink ( ManagerThink ); pev->nextthink = gpGlobals->time; } #if _DEBUG void CMultiManager :: ManagerReport ( void ) { int cIndex; for ( cIndex = 0 ; cIndex < m_cTargets ; cIndex++ ) { ALERT ( at_console, "%s %f\n", STRING(m_iTargetName[cIndex]), m_flTargetDelay[cIndex] ); } } #endif //*********************************************************** // // Render parameters trigger // // This entity will copy its render parameters (renderfx, rendermode, rendercolor, renderamt) // to its targets when triggered. // // Flags to indicate masking off various render parameters that are normally copied to the targets #define SF_RENDER_MASKFX (1<<0) #define SF_RENDER_MASKAMT (1<<1) #define SF_RENDER_MASKMODE (1<<2) #define SF_RENDER_MASKCOLOR (1<<3) class CRenderFxManager : public CBaseEntity { public: void Spawn( void ); void Use ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); }; LINK_ENTITY_TO_CLASS( env_render, CRenderFxManager ); void CRenderFxManager :: Spawn ( void ) { pev->solid = SOLID_NOT; } void CRenderFxManager :: Use ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if (!FStringNull(pev->target)) { edict_t* pentTarget = NULL; while ( 1 ) { pentTarget = FIND_ENTITY_BY_TARGETNAME(pentTarget, STRING(pev->target)); if (FNullEnt(pentTarget)) break; entvars_t *pevTarget = VARS( pentTarget ); if ( !FBitSet( pev->spawnflags, SF_RENDER_MASKFX ) ) pevTarget->renderfx = pev->renderfx; if ( !FBitSet( pev->spawnflags, SF_RENDER_MASKAMT ) ) pevTarget->renderamt = pev->renderamt; if ( !FBitSet( pev->spawnflags, SF_RENDER_MASKMODE ) ) pevTarget->rendermode = pev->rendermode; if ( !FBitSet( pev->spawnflags, SF_RENDER_MASKCOLOR ) ) pevTarget->rendercolor = pev->rendercolor; } } } class CBaseTrigger : public CBaseToggle { public: void EXPORT TeleportTouch ( CBaseEntity *pOther ); void KeyValue( KeyValueData *pkvd ); void EXPORT MultiTouch( CBaseEntity *pOther ); void EXPORT HurtTouch ( CBaseEntity *pOther ); void EXPORT EnvTouch ( CBaseEntity *pOther ); void EXPORT CDAudioTouch ( CBaseEntity *pOther ); void ActivateMultiTrigger( CBaseEntity *pActivator ); void EXPORT MultiWaitOver( void ); void EXPORT CounterUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void EXPORT ToggleUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void InitTrigger( void ); virtual int ObjectCaps( void ) { return CBaseToggle :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } }; LINK_ENTITY_TO_CLASS( trigger, CBaseTrigger ); /* ================ InitTrigger ================ */ void CBaseTrigger::InitTrigger( ) { // trigger angles are used for one-way touches. An angle of 0 is assumed // to mean no restrictions, so use a yaw of 360 instead. if (pev->angles != g_vecZero) SetMovedir(pev); pev->solid = SOLID_TRIGGER; pev->movetype = MOVETYPE_NONE; SET_MODEL(ENT(pev), STRING(pev->model)); // set size and link into world // if ( CVAR_GET_FLOAT("showtriggers") == 0 ) SetBits( pev->effects, EF_NODRAW ); } // // Cache user-entity-field values until spawn is called. // void CBaseTrigger :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "damage")) { pev->dmg = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "count")) { m_cTriggersLeft = (int) atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "damagetype")) { m_bitsDamageInflict = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseToggle::KeyValue( pkvd ); } class CTriggerHurt : public CBaseTrigger { public: void Spawn( void ); void EXPORT RadiationThink( void ); }; LINK_ENTITY_TO_CLASS( trigger_hurt, CTriggerHurt ); class CTriggerEnvHurt : public CBaseTrigger { public: void Spawn( void ); }; LINK_ENTITY_TO_CLASS( trigger_env_hurt, CTriggerEnvHurt ); // // trigger_monsterjump // class CTriggerMonsterJump : public CBaseTrigger { public: void Spawn( void ); void Touch( CBaseEntity *pOther ); void Think( void ); }; LINK_ENTITY_TO_CLASS( trigger_monsterjump, CTriggerMonsterJump ); void CTriggerMonsterJump :: Spawn ( void ) { SetMovedir ( pev ); InitTrigger (); pev->nextthink = 0; pev->speed = 200; m_flHeight = 150; if ( !FStringNull ( pev->targetname ) ) {// if targetted, spawn turned off pev->solid = SOLID_NOT; UTIL_SetOrigin( pev, pev->origin ); // Unlink from trigger list SetUse( ToggleUse ); } } void CTriggerMonsterJump :: Think( void ) { pev->solid = SOLID_NOT;// kill the trigger for now !!!UNDONE UTIL_SetOrigin( pev, pev->origin ); // Unlink from trigger list SetThink( NULL ); } void CTriggerMonsterJump :: Touch( CBaseEntity *pOther ) { entvars_t *pevOther = pOther->pev; if ( !FBitSet ( pevOther->flags , FL_MONSTER ) ) {// touched by a non-monster. return; } pevOther->origin.z += 1; if ( FBitSet ( pevOther->flags, FL_ONGROUND ) ) {// clear the onground so physics don't bitch pevOther->flags &= ~FL_ONGROUND; } // toss the monster! pevOther->velocity = pev->movedir * pev->speed; pevOther->velocity.z += m_flHeight; pev->nextthink = gpGlobals->time; } //===================================== // // trigger_cdaudio - starts/stops cd audio tracks // class CTriggerCDAudio : public CBaseTrigger { public: void Spawn( void ); virtual void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void PlayTrack( void ); void Touch ( CBaseEntity *pOther ); }; LINK_ENTITY_TO_CLASS( trigger_cdaudio, CTriggerCDAudio ); // // Changes tracks or stops CD when player touches // // !!!HACK - overloaded HEALTH to avoid adding new field void CTriggerCDAudio :: Touch ( CBaseEntity *pOther ) { if ( !pOther->IsPlayer() ) {// only clients may trigger these events return; } PlayTrack(); } void CTriggerCDAudio :: Spawn( void ) { InitTrigger(); } void CTriggerCDAudio::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { PlayTrack(); } void PlayCDTrack( int iTrack ) { edict_t *pClient; // manually find the single player. pClient = g_engfuncs.pfnPEntityOfEntIndex( 1 ); // Can't play if the client is not connected! if ( !pClient ) return; if ( iTrack < -1 || iTrack > 30 ) { ALERT ( at_console, "TriggerCDAudio - Track %d out of range\n" ); return; } if ( iTrack == -1 ) { CLIENT_COMMAND ( pClient, "cd pause\n"); } else { char string [ 64 ]; sprintf( string, "cd play %3d\n", iTrack ); CLIENT_COMMAND ( pClient, string); } } // only plays for ONE client, so only use in single play! void CTriggerCDAudio :: PlayTrack( void ) { //PlayCDTrack( (int)pev->health ); SetTouch( NULL ); UTIL_Remove( this ); } // This plays a CD track when fired or when the player enters it's radius class CTargetCDAudio : public CPointEntity { public: void Spawn( void ); void KeyValue( KeyValueData *pkvd ); virtual void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void Think( void ); void Play( void ); }; LINK_ENTITY_TO_CLASS( target_cdaudio, CTargetCDAudio ); void CTargetCDAudio :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "radius")) { pev->scale = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else CPointEntity::KeyValue( pkvd ); } void CTargetCDAudio :: Spawn( void ) { pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NONE; if ( pev->scale > 0 ) pev->nextthink = gpGlobals->time + 1.0; } void CTargetCDAudio::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { Play(); } // only plays for ONE client, so only use in single play! void CTargetCDAudio::Think( void ) { edict_t *pClient; // manually find the single player. pClient = g_engfuncs.pfnPEntityOfEntIndex( 1 ); // Can't play if the client is not connected! if ( !pClient ) return; pev->nextthink = gpGlobals->time + 0.5; if ( (pClient->v.origin - pev->origin).Length() <= pev->scale ) Play(); } void CTargetCDAudio::Play( void ) { //PlayCDTrack( (int)pev->health ); UTIL_Remove(this); } //===================================== /* ========================== CTriggerEnvHurt Used to represent Slime or Lava ========================== */ void CTriggerEnvHurt :: Spawn( void ) { InitTrigger(); SetTouch ( EnvTouch ); if ( FBitSet (pev->spawnflags, SF_TRIGGER_HURT_START_OFF) )// if flagged to Start Turned Off, make trigger nonsolid. pev->solid = SOLID_NOT; UTIL_SetOrigin( pev, pev->origin ); // Link into the list } // When touched, a hurt trigger does DMG points of damage each half-second void CBaseTrigger :: EnvTouch ( CBaseEntity *pOther ) { float fldmg; if ( !pOther->pev->takedamage ) return; if ( (pev->spawnflags & SF_TRIGGER_HURT_CLIENTONLYTOUCH) && !pOther->IsPlayer() ) { // this trigger is only allowed to touch clients, and this ain't a client. return; } if ( (pev->spawnflags & SF_TRIGGER_HURT_NO_CLIENTS) && pOther->IsPlayer() ) return; // HACKHACK -- In multiplayer, players touch this based on packet receipt. // So the players who send packets later aren't always hurt. Keep track of // how much time has passed and whether or not you've touched that player if ( g_pGameRules->IsMultiplayer() ) { if ( pev->dmgtime > gpGlobals->time ) { if ( gpGlobals->time != pev->pain_finished ) {// too early to hurt again, and not same frame with a different entity if ( pOther->IsPlayer() ) { int playerMask = 1 << (pOther->entindex() - 1); // If I've already touched this player (this time), then bail out if ( pev->impulse & playerMask ) return; // Mark this player as touched // BUGBUG - There can be only 32 players! pev->impulse |= playerMask; } else { return; } } } else { // New clock, "un-touch" all players pev->impulse = 0; if ( pOther->IsPlayer() ) { int playerMask = 1 << (pOther->entindex() - 1); // Mark this player as touched // BUGBUG - There can be only 32 players! pev->impulse |= playerMask; } } } else // Original code -- single player { if ( pev->dmgtime > gpGlobals->time && gpGlobals->time != pev->pain_finished ) {// too early to hurt again, and not same frame with a different entity return; } } //We are in slime if ( m_bitsDamageInflict & DMG_ACID ) { pev->dmg = 4; //Default damage of 4 fldmg = (float)( pev->dmg * pOther->pev->waterlevel ); // pev->damage plus our current waterlevel pev->dmgtime = gpGlobals->time + 1.0; //Next damage in 1 second } //We are in lava else if ( m_bitsDamageInflict & DMG_BURN ) { pev->dmg = 10; //Default damage of 10 fldmg = (float)( pev->dmg * pOther->pev->waterlevel ); // pev->damage plus our current waterlevel if ( pOther->IsPlayer() ) { if ( ( (CBasePlayer *)pOther )->m_iQuakeItems & IT_SUIT) // Wearing the suit slows down the next damage time pev->dmgtime = gpGlobals->time + 1.0; else pev->dmgtime = gpGlobals->time + 0.2; } else pev->dmgtime = gpGlobals->time + 0.2; } if ( fldmg < 0 ) pOther->TakeHealth( -fldmg, m_bitsDamageInflict ); else pOther->TakeDamage( pev, pev, fldmg, m_bitsDamageInflict ); // Store pain time so we can get all of the other entities on this frame pev->pain_finished = gpGlobals->time; if ( pev->target ) { // trigger has a target it wants to fire. if ( pev->spawnflags & SF_TRIGGER_HURT_CLIENTONLYFIRE ) { // if the toucher isn't a client, don't fire the target! if ( !pOther->IsPlayer() ) { return; } } SUB_UseTargets( pOther, USE_TOGGLE, 0 ); if ( pev->spawnflags & SF_TRIGGER_HURT_TARGETONCE ) pev->target = 0; } } // trigger_hurt - hurts anything that touches it. if the trigger has a targetname, firing it will toggle state // //int gfToggleState = 0; // used to determine when all radiation trigger hurts have called 'RadiationThink' void CTriggerHurt :: Spawn( void ) { InitTrigger(); SetTouch ( HurtTouch ); if ( !FStringNull ( pev->targetname ) ) { SetUse ( ToggleUse ); } else { SetUse ( NULL ); } if (m_bitsDamageInflict & DMG_RADIATION) { SetThink ( RadiationThink ); pev->nextthink = gpGlobals->time + RANDOM_FLOAT(0.0, 0.5); } if ( FBitSet (pev->spawnflags, SF_TRIGGER_HURT_START_OFF) )// if flagged to Start Turned Off, make trigger nonsolid. pev->solid = SOLID_NOT; UTIL_SetOrigin( pev, pev->origin ); // Link into the list } // trigger hurt that causes radiation will do a radius // check and set the player's geiger counter level // according to distance from center of trigger void CTriggerHurt :: RadiationThink( void ) { edict_t *pentPlayer; CBasePlayer *pPlayer = NULL; float flRange; entvars_t *pevTarget; Vector vecSpot1; Vector vecSpot2; Vector vecRange; Vector origin; Vector view_ofs; // check to see if a player is in pvs // if not, continue // set origin to center of trigger so that this check works origin = pev->origin; view_ofs = pev->view_ofs; pev->origin = (pev->absmin + pev->absmax) * 0.5; pev->view_ofs = pev->view_ofs * 0.0; pentPlayer = FIND_CLIENT_IN_PVS(edict()); pev->origin = origin; pev->view_ofs = view_ofs; // reset origin if (!FNullEnt(pentPlayer)) { pPlayer = GetClassPtr( (CBasePlayer *)VARS(pentPlayer)); pevTarget = VARS(pentPlayer); // get range to player; vecSpot1 = (pev->absmin + pev->absmax) * 0.5; vecSpot2 = (pevTarget->absmin + pevTarget->absmax) * 0.5; vecRange = vecSpot1 - vecSpot2; flRange = vecRange.Length(); // if player's current geiger counter range is larger // than range to this trigger hurt, reset player's // geiger counter range if (pPlayer->m_flgeigerRange >= flRange) pPlayer->m_flgeigerRange = flRange; } pev->nextthink = gpGlobals->time + 0.25; } // // ToggleUse - If this is the USE function for a trigger, its state will toggle every time it's fired // void CBaseTrigger :: ToggleUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if (pev->solid == SOLID_NOT) {// if the trigger is off, turn it on pev->solid = SOLID_TRIGGER; // Force retouch gpGlobals->force_retouch++; } else {// turn the trigger off pev->solid = SOLID_NOT; } UTIL_SetOrigin( pev, pev->origin ); } // When touched, a hurt trigger does DMG points of damage each half-second void CBaseTrigger :: HurtTouch ( CBaseEntity *pOther ) { float fldmg; if ( !pOther->pev->takedamage ) return; if ( (pev->spawnflags & SF_TRIGGER_HURT_CLIENTONLYTOUCH) && !pOther->IsPlayer() ) { // this trigger is only allowed to touch clients, and this ain't a client. return; } if ( (pev->spawnflags & SF_TRIGGER_HURT_NO_CLIENTS) && pOther->IsPlayer() ) return; // HACKHACK -- In multiplayer, players touch this based on packet receipt. // So the players who send packets later aren't always hurt. Keep track of // how much time has passed and whether or not you've touched that player if ( g_pGameRules->IsMultiplayer() ) { if ( pev->dmgtime > gpGlobals->time ) { if ( gpGlobals->time != pev->pain_finished ) {// too early to hurt again, and not same frame with a different entity if ( pOther->IsPlayer() ) { int playerMask = 1 << (pOther->entindex() - 1); // If I've already touched this player (this time), then bail out if ( pev->impulse & playerMask ) return; // Mark this player as touched // BUGBUG - There can be only 32 players! pev->impulse |= playerMask; } else { return; } } } else { // New clock, "un-touch" all players pev->impulse = 0; if ( pOther->IsPlayer() ) { int playerMask = 1 << (pOther->entindex() - 1); // Mark this player as touched // BUGBUG - There can be only 32 players! pev->impulse |= playerMask; } } } else // Original code -- single player { if ( pev->dmgtime > gpGlobals->time && gpGlobals->time != pev->pain_finished ) {// too early to hurt again, and not same frame with a different entity return; } } // If this is time_based damage (poison, radiation), override the pev->dmg with a // default for the given damage type. Monsters only take time-based damage // while touching the trigger. Player continues taking damage for a while after // leaving the trigger fldmg = pev->dmg * 0.5; // 0.5 seconds worth of damage, pev->dmg is damage/second // JAY: Cut this because it wasn't fully realized. Damage is simpler now. #if 0 switch (m_bitsDamageInflict) { default: break; case DMG_POISON: fldmg = POISON_DAMAGE/4; break; case DMG_NERVEGAS: fldmg = NERVEGAS_DAMAGE/4; break; case DMG_RADIATION: fldmg = RADIATION_DAMAGE/4; break; case DMG_PARALYZE: fldmg = PARALYZE_DAMAGE/4; break; // UNDONE: cut this? should slow movement to 50% case DMG_ACID: fldmg = ACID_DAMAGE/4; break; case DMG_SLOWBURN: fldmg = SLOWBURN_DAMAGE/4; break; case DMG_SLOWFREEZE: fldmg = SLOWFREEZE_DAMAGE/4; break; } #endif if ( fldmg < 0 ) pOther->TakeHealth( -fldmg, m_bitsDamageInflict ); else pOther->TakeDamage( pev, pev, fldmg, m_bitsDamageInflict ); // Store pain time so we can get all of the other entities on this frame pev->pain_finished = gpGlobals->time; // Apply damage every half second pev->dmgtime = gpGlobals->time + 0.5;// half second delay until this trigger can hurt toucher again if ( pev->target ) { // trigger has a target it wants to fire. if ( pev->spawnflags & SF_TRIGGER_HURT_CLIENTONLYFIRE ) { // if the toucher isn't a client, don't fire the target! if ( !pOther->IsPlayer() ) { return; } } SUB_UseTargets( pOther, USE_TOGGLE, 0 ); if ( pev->spawnflags & SF_TRIGGER_HURT_TARGETONCE ) pev->target = 0; } } /*QUAKED trigger_multiple (.5 .5 .5) ? notouch Variable sized repeatable trigger. Must be targeted at one or more entities. If "health" is set, the trigger must be killed to activate each time. If "delay" is set, the trigger waits some time after activating before firing. "wait" : Seconds between triggerings. (.2 default) If notouch is set, the trigger is only fired by other entities, not by touching. NOTOUCH has been obsoleted by trigger_relay! sounds 1) secret 2) beep beep 3) large switch 4) NEW if a trigger has a NETNAME, that NETNAME will become the TARGET of the triggered object. */ class CTriggerMultiple : public CBaseTrigger { public: void Spawn( void ); }; LINK_ENTITY_TO_CLASS( trigger_multiple, CTriggerMultiple ); void CTriggerMultiple :: Spawn( void ) { if (m_flWait == 0) m_flWait = 0.2; InitTrigger(); ASSERTSZ(pev->health == 0, "trigger_multiple with health"); // UTIL_SetOrigin(pev, pev->origin); // SET_MODEL( ENT(pev), STRING(pev->model) ); // if (pev->health > 0) // { // if (FBitSet(pev->spawnflags, SPAWNFLAG_NOTOUCH)) // ALERT(at_error, "trigger_multiple spawn: health and notouch don't make sense"); // pev->max_health = pev->health; //UNDONE: where to get pfnDie from? // pev->pfnDie = multi_killed; // pev->takedamage = DAMAGE_YES; // pev->solid = SOLID_BBOX; // UTIL_SetOrigin(pev, pev->origin); // make sure it links into the world // } // else { SetTouch( MultiTouch ); } } /*QUAKED trigger_once (.5 .5 .5) ? notouch Variable sized trigger. Triggers once, then removes itself. You must set the key "target" to the name of another object in the level that has a matching "targetname". If "health" is set, the trigger must be killed to activate. If notouch is set, the trigger is only fired by other entities, not by touching. if "killtarget" is set, any objects that have a matching "target" will be removed when the trigger is fired. if "angle" is set, the trigger will only fire when someone is facing the direction of the angle. Use "360" for an angle of 0. sounds 1) secret 2) beep beep 3) large switch 4) */ class CTriggerOnce : public CTriggerMultiple { public: void Spawn( void ); }; LINK_ENTITY_TO_CLASS( trigger_once, CTriggerOnce ); void CTriggerOnce::Spawn( void ) { m_flWait = -1; CTriggerMultiple :: Spawn(); } void CBaseTrigger :: MultiTouch( CBaseEntity *pOther ) { entvars_t *pevToucher; pevToucher = pOther->pev; // Only touch clients, monsters, or pushables (depending on flags) if ( ((pevToucher->flags & FL_CLIENT) && !(pev->spawnflags & SF_TRIGGER_NOCLIENTS)) || ((pevToucher->flags & FL_MONSTER) && (pev->spawnflags & SF_TRIGGER_ALLOWMONSTERS)) || (pev->spawnflags & SF_TRIGGER_PUSHABLES) && FClassnameIs(pevToucher,"func_pushable") ) { #if 0 // if the trigger has an angles field, check player's facing direction if (pev->movedir != g_vecZero) { UTIL_MakeVectors( pevToucher->angles ); if ( DotProduct( gpGlobals->v_forward, pev->movedir ) < 0 ) return; // not facing the right way } #endif ActivateMultiTrigger( pOther ); } } // // the trigger was just touched/killed/used // self.enemy should be set to the activator so it can be held through a delay // so wait for the delay time before firing // void CBaseTrigger :: ActivateMultiTrigger( CBaseEntity *pActivator ) { if (pev->nextthink > gpGlobals->time) return; // still waiting for reset time if (!UTIL_IsMasterTriggered(m_sMaster,pActivator)) return; if (FClassnameIs(pev, "trigger_secret")) { if ( pev->enemy == NULL || !FClassnameIs(pev->enemy, "player")) return; gpGlobals->found_secrets++; } if (!FStringNull(pev->noise)) EMIT_SOUND(ENT(pev), CHAN_VOICE, (char*)STRING(pev->noise), 1, ATTN_NORM); // don't trigger again until reset // pev->takedamage = DAMAGE_NO; m_hActivator = pActivator; SUB_UseTargets( m_hActivator, USE_TOGGLE, 0 ); if ( pev->message && pActivator->IsPlayer() ) { UTIL_ShowMessage( STRING(pev->message), pActivator ); // CLIENT_PRINTF( ENT( pActivator->pev ), print_center, STRING(pev->message) ); } if (m_flWait > 0) { SetThink( MultiWaitOver ); pev->nextthink = gpGlobals->time + m_flWait; } else { // we can't just remove (self) here, because this is a touch function // called while C code is looping through area links... SetTouch( NULL ); pev->nextthink = gpGlobals->time + 0.1; SetThink( SUB_Remove ); } } // the wait time has passed, so set back up for another activation void CBaseTrigger :: MultiWaitOver( void ) { // if (pev->max_health) // { // pev->health = pev->max_health; // pev->takedamage = DAMAGE_YES; // pev->solid = SOLID_BBOX; // } SetThink( NULL ); } // ========================= COUNTING TRIGGER ===================================== // // GLOBALS ASSUMED SET: g_eoActivator // void CBaseTrigger::CounterUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_cTriggersLeft--; m_hActivator = pActivator; if (m_cTriggersLeft < 0) return; BOOL fTellActivator = (m_hActivator != 0) && FClassnameIs(m_hActivator->pev, "player") && !FBitSet(pev->spawnflags, SPAWNFLAG_NOMESSAGE); if (m_cTriggersLeft != 0) { if (fTellActivator) { // UNDONE: I don't think we want these Quakesque messages switch (m_cTriggersLeft) { case 1: ALERT(at_console, "Only 1 more to go..."); break; case 2: ALERT(at_console, "Only 2 more to go..."); break; case 3: ALERT(at_console, "Only 3 more to go..."); break; default: ALERT(at_console, "There are more to go..."); break; } } return; } // !!!UNDONE: I don't think we want these Quakesque messages if (fTellActivator) ALERT(at_console, "Sequence completed!"); ActivateMultiTrigger( m_hActivator ); } /*QUAKED trigger_counter (.5 .5 .5) ? nomessage Acts as an intermediary for an action that takes multiple inputs. If nomessage is not set, it will print "1 more.. " etc when triggered and "sequence complete" when finished. After the counter has been triggered "cTriggersLeft" times (default 2), it will fire all of it's targets and remove itself. */ class CTriggerCounter : public CBaseTrigger { public: void Spawn( void ); }; LINK_ENTITY_TO_CLASS( trigger_counter, CTriggerCounter ); void CTriggerCounter :: Spawn( void ) { // By making the flWait be -1, this counter-trigger will disappear after it's activated // (but of course it needs cTriggersLeft "uses" before that happens). m_flWait = -1; if (m_cTriggersLeft == 0) m_cTriggersLeft = 2; SetUse( CounterUse ); } // ====================== TRIGGER_CHANGELEVEL ================================ class CTriggerVolume : public CPointEntity // Derive from point entity so this doesn't move across levels { public: void Spawn( void ); }; LINK_ENTITY_TO_CLASS( trigger_transition, CTriggerVolume ); // Define space that travels across a level transition void CTriggerVolume :: Spawn( void ) { pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NONE; SET_MODEL(ENT(pev), STRING(pev->model)); // set size and link into world pev->model = NULL; pev->modelindex = 0; } // Fires a target after level transition and then dies class CFireAndDie : public CBaseDelay { public: void Spawn( void ); void Precache( void ); void Think( void ); int ObjectCaps( void ) { return CBaseDelay::ObjectCaps() | FCAP_FORCE_TRANSITION; } // Always go across transitions }; LINK_ENTITY_TO_CLASS( fireanddie, CFireAndDie ); void CFireAndDie::Spawn( void ) { pev->classname = MAKE_STRING("fireanddie"); // Don't call Precache() - it should be called on restore } void CFireAndDie::Precache( void ) { // This gets called on restore pev->nextthink = gpGlobals->time + m_flDelay; } void CFireAndDie::Think( void ) { SUB_UseTargets( this, USE_TOGGLE, 0 ); UTIL_Remove( this ); } #define SF_CHANGELEVEL_USEONLY 0x0002 class CChangeLevel : public CBaseTrigger { public: void Spawn( void ); void KeyValue( KeyValueData *pkvd ); void EXPORT UseChangeLevel ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void EXPORT TriggerChangeLevel( void ); void EXPORT ExecuteChangeLevel( void ); void EXPORT TouchChangeLevel( CBaseEntity *pOther ); void ChangeLevelNow( CBaseEntity *pActivator ); static edict_t *FindLandmark( const char *pLandmarkName ); static int ChangeList( LEVELLIST *pLevelList, int maxList ); static int AddTransitionToList( LEVELLIST *pLevelList, int listCount, const char *pMapName, const char *pLandmarkName, edict_t *pentLandmark ); static int InTransitionVolume( CBaseEntity *pEntity, char *pVolumeName ); virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; char m_szMapName[cchMapNameMost]; // trigger_changelevel only: next map char m_szLandmarkName[cchMapNameMost]; // trigger_changelevel only: landmark on next map int m_changeTarget; float m_changeTargetDelay; }; LINK_ENTITY_TO_CLASS( trigger_changelevel, CChangeLevel ); // Global Savedata for changelevel trigger TYPEDESCRIPTION CChangeLevel::m_SaveData[] = { DEFINE_ARRAY( CChangeLevel, m_szMapName, FIELD_CHARACTER, cchMapNameMost ), DEFINE_ARRAY( CChangeLevel, m_szLandmarkName, FIELD_CHARACTER, cchMapNameMost ), DEFINE_FIELD( CChangeLevel, m_changeTarget, FIELD_STRING ), DEFINE_FIELD( CChangeLevel, m_changeTargetDelay, FIELD_FLOAT ), }; IMPLEMENT_SAVERESTORE(CChangeLevel,CBaseTrigger); // // Cache user-entity-field values until spawn is called. // void CChangeLevel :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "map")) { if (strlen(pkvd->szValue) >= cchMapNameMost) ALERT( at_error, "Map name '%s' too long (32 chars)\n", pkvd->szValue ); strcpy(m_szMapName, pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "landmark")) { if (strlen(pkvd->szValue) >= cchMapNameMost) ALERT( at_error, "Landmark name '%s' too long (32 chars)\n", pkvd->szValue ); strcpy(m_szLandmarkName, pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "changetarget")) { m_changeTarget = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "changedelay")) { m_changeTargetDelay = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseTrigger::KeyValue( pkvd ); } /*QUAKED trigger_changelevel (0.5 0.5 0.5) ? NO_INTERMISSION When the player touches this, he gets sent to the map listed in the "map" variable. Unless the NO_INTERMISSION flag is set, the view will go to the info_intermission spot and display stats. */ void CChangeLevel :: Spawn( void ) { if ( FStrEq( m_szMapName, "" ) ) ALERT( at_console, "a trigger_changelevel doesn't have a map" ); if ( FStrEq( m_szLandmarkName, "" ) ) ALERT( at_console, "trigger_changelevel to %s doesn't have a landmark", m_szMapName ); if (!FStringNull ( pev->targetname ) ) { SetUse ( UseChangeLevel ); } InitTrigger(); if ( !(pev->spawnflags & SF_CHANGELEVEL_USEONLY) ) SetTouch( TouchChangeLevel ); // ALERT( at_console, "TRANSITION: %s (%s)\n", m_szMapName, m_szLandmarkName ); } void CChangeLevel :: ExecuteChangeLevel( void ) { MESSAGE_BEGIN( MSG_ALL, SVC_CDTRACK ); WRITE_BYTE( 3 ); WRITE_BYTE( 3 ); MESSAGE_END(); MESSAGE_BEGIN(MSG_ALL, SVC_INTERMISSION); MESSAGE_END(); } FILE_GLOBAL char st_szNextMap[cchMapNameMost]; FILE_GLOBAL char st_szNextSpot[cchMapNameMost]; edict_t *CChangeLevel :: FindLandmark( const char *pLandmarkName ) { edict_t *pentLandmark; pentLandmark = FIND_ENTITY_BY_STRING( NULL, "targetname", pLandmarkName ); while ( !FNullEnt( pentLandmark ) ) { // Found the landmark if ( FClassnameIs( pentLandmark, "info_landmark" ) ) return pentLandmark; else pentLandmark = FIND_ENTITY_BY_STRING( pentLandmark, "targetname", pLandmarkName ); } ALERT( at_error, "Can't find landmark %s\n", pLandmarkName ); return NULL; } //========================================================= // CChangeLevel :: Use - allows level transitions to be // triggered by buttons, etc. // //========================================================= void CChangeLevel :: UseChangeLevel ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { ChangeLevelNow( pActivator ); } void CChangeLevel :: ChangeLevelNow( CBaseEntity *pActivator ) { edict_t *pentLandmark; LEVELLIST levels[16]; ASSERT(!FStrEq(m_szMapName, "")); // Don't work in deathmatch if ( g_pGameRules->IsDeathmatch() ) return; // Some people are firing these multiple times in a frame, disable if ( gpGlobals->time == pev->dmgtime ) return; pev->dmgtime = gpGlobals->time; CBaseEntity *pPlayer = CBaseEntity::Instance( g_engfuncs.pfnPEntityOfEntIndex( 1 ) ); if ( !InTransitionVolume( pPlayer, m_szLandmarkName ) ) { ALERT( at_aiconsole, "Player isn't in the transition volume %s, aborting\n", m_szLandmarkName ); return; } // Create an entity to fire the changetarget if ( m_changeTarget ) { CFireAndDie *pFireAndDie = GetClassPtr( (CFireAndDie *)NULL ); if ( pFireAndDie ) { // Set target and delay pFireAndDie->pev->target = m_changeTarget; pFireAndDie->m_flDelay = m_changeTargetDelay; pFireAndDie->pev->origin = pPlayer->pev->origin; // Call spawn DispatchSpawn( pFireAndDie->edict() ); } } // This object will get removed in the call to CHANGE_LEVEL, copy the params into "safe" memory strcpy(st_szNextMap, m_szMapName); m_hActivator = pActivator; SUB_UseTargets( pActivator, USE_TOGGLE, 0 ); st_szNextSpot[0] = 0; // Init landmark to NULL // look for a landmark entity pentLandmark = FindLandmark( m_szLandmarkName ); if ( !FNullEnt( pentLandmark ) ) { strcpy(st_szNextSpot, m_szLandmarkName); gpGlobals->vecLandmarkOffset = VARS(pentLandmark)->origin; } // ALERT( at_console, "Level touches %d levels\n", ChangeList( levels, 16 ) ); ALERT( at_console, "CHANGE LEVEL: %s %s\n", st_szNextMap, st_szNextSpot ); CHANGE_LEVEL( st_szNextMap, st_szNextSpot ); } // // GLOBALS ASSUMED SET: st_szNextMap // void CChangeLevel :: TouchChangeLevel( CBaseEntity *pOther ) { if (!FClassnameIs(pOther->pev, "player")) return; ChangeLevelNow( pOther ); } // Add a transition to the list, but ignore duplicates // (a designer may have placed multiple trigger_changelevels with the same landmark) int CChangeLevel::AddTransitionToList( LEVELLIST *pLevelList, int listCount, const char *pMapName, const char *pLandmarkName, edict_t *pentLandmark ) { int i; if ( !pLevelList || !pMapName || !pLandmarkName || !pentLandmark ) return 0; for ( i = 0; i < listCount; i++ ) { if ( pLevelList[i].pentLandmark == pentLandmark && strcmp( pLevelList[i].mapName, pMapName ) == 0 ) return 0; } strcpy( pLevelList[listCount].mapName, pMapName ); strcpy( pLevelList[listCount].landmarkName, pLandmarkName ); pLevelList[listCount].pentLandmark = pentLandmark; pLevelList[listCount].vecLandmarkOrigin = VARS(pentLandmark)->origin; return 1; } int BuildChangeList( LEVELLIST *pLevelList, int maxList ) { return CChangeLevel::ChangeList( pLevelList, maxList ); } int CChangeLevel::InTransitionVolume( CBaseEntity *pEntity, char *pVolumeName ) { edict_t *pentVolume; if ( pEntity->ObjectCaps() & FCAP_FORCE_TRANSITION ) return 1; // If you're following another entity, follow it through the transition (weapons follow the player) if ( pEntity->pev->movetype == MOVETYPE_FOLLOW ) { if ( pEntity->pev->aiment != NULL ) pEntity = CBaseEntity::Instance( pEntity->pev->aiment ); } int inVolume = 1; // Unless we find a trigger_transition, everything is in the volume pentVolume = FIND_ENTITY_BY_TARGETNAME( NULL, pVolumeName ); while ( !FNullEnt( pentVolume ) ) { CBaseEntity *pVolume = CBaseEntity::Instance( pentVolume ); if ( pVolume && FClassnameIs( pVolume->pev, "trigger_transition" ) ) { if ( pVolume->Intersects( pEntity ) ) // It touches one, it's in the volume return 1; else inVolume = 0; // Found a trigger_transition, but I don't intersect it -- if I don't find another, don't go! } pentVolume = FIND_ENTITY_BY_TARGETNAME( pentVolume, pVolumeName ); } return inVolume; } // We can only ever move 512 entities across a transition #define MAX_ENTITY 512 // This has grown into a complicated beast // Can we make this more elegant? // This builds the list of all transitions on this level and which entities are in their PVS's and can / should // be moved across. int CChangeLevel::ChangeList( LEVELLIST *pLevelList, int maxList ) { edict_t *pentChangelevel, *pentLandmark; int i, count; count = 0; // Find all of the possible level changes on this BSP pentChangelevel = FIND_ENTITY_BY_STRING( NULL, "classname", "trigger_changelevel" ); if ( FNullEnt( pentChangelevel ) ) return 0; while ( !FNullEnt( pentChangelevel ) ) { CChangeLevel *pTrigger; pTrigger = GetClassPtr((CChangeLevel *)VARS(pentChangelevel)); if ( pTrigger ) { // Find the corresponding landmark pentLandmark = FindLandmark( pTrigger->m_szLandmarkName ); if ( pentLandmark ) { // Build a list of unique transitions if ( AddTransitionToList( pLevelList, count, pTrigger->m_szMapName, pTrigger->m_szLandmarkName, pentLandmark ) ) { count++; if ( count >= maxList ) // FULL!! break; } } } pentChangelevel = FIND_ENTITY_BY_STRING( pentChangelevel, "classname", "trigger_changelevel" ); } if ( gpGlobals->pSaveData && ((SAVERESTOREDATA *)gpGlobals->pSaveData)->pTable ) { CSave saveHelper( (SAVERESTOREDATA *)gpGlobals->pSaveData ); for ( i = 0; i < count; i++ ) { int j, entityCount = 0; CBaseEntity *pEntList[ MAX_ENTITY ]; int entityFlags[ MAX_ENTITY ]; // Follow the linked list of entities in the PVS of the transition landmark edict_t *pent = UTIL_EntitiesInPVS( pLevelList[i].pentLandmark ); // Build a list of valid entities in this linked list (we're going to use pent->v.chain again) while ( !FNullEnt( pent ) ) { CBaseEntity *pEntity = CBaseEntity::Instance(pent); if ( pEntity ) { // ALERT( at_console, "Trying %s\n", STRING(pEntity->pev->classname) ); int caps = pEntity->ObjectCaps(); if ( !(caps & FCAP_DONT_SAVE) ) { int flags = 0; // If this entity can be moved or is global, mark it if ( caps & FCAP_ACROSS_TRANSITION ) flags |= FENTTABLE_MOVEABLE; if ( pEntity->pev->globalname && !pEntity->IsDormant() ) flags |= FENTTABLE_GLOBAL; if ( flags ) { pEntList[ entityCount ] = pEntity; entityFlags[ entityCount ] = flags; entityCount++; if ( entityCount > MAX_ENTITY ) ALERT( at_error, "Too many entities across a transition!" ); } // else // ALERT( at_console, "Failed %s\n", STRING(pEntity->pev->classname) ); } // else // ALERT( at_console, "DON'T SAVE %s\n", STRING(pEntity->pev->classname) ); } pent = pent->v.chain; } for ( j = 0; j < entityCount; j++ ) { // Check to make sure the entity isn't screened out by a trigger_transition if ( entityFlags[j] && InTransitionVolume( pEntList[j], pLevelList[i].landmarkName ) ) { // Mark entity table with 1<<i int index = saveHelper.EntityIndex( pEntList[j] ); // Flag it with the level number saveHelper.EntityFlagsSet( index, entityFlags[j] | (1<<i) ); } // else // ALERT( at_console, "Screened out %s\n", STRING(pEntList[j]->pev->classname) ); } } } return count; } /* go to the next level for deathmatch only called if a time or frag limit has expired */ void NextLevel( void ) { edict_t* pent; CChangeLevel *pChange; // find a trigger_changelevel pent = FIND_ENTITY_BY_CLASSNAME(NULL, "trigger_changelevel"); // go back to start if no trigger_changelevel if (FNullEnt(pent)) { gpGlobals->mapname = ALLOC_STRING("start"); pChange = GetClassPtr( (CChangeLevel *)NULL ); strcpy(pChange->m_szMapName, "start"); } else pChange = GetClassPtr( (CChangeLevel *)VARS(pent)); strcpy(st_szNextMap, pChange->m_szMapName); g_fGameOver = TRUE; if (pChange->pev->nextthink < gpGlobals->time) { pChange->SetThink( CChangeLevel::ExecuteChangeLevel ); pChange->pev->nextthink = gpGlobals->time + 0.1; } } // ============================== LADDER ======================================= class CLadder : public CBaseTrigger { public: void KeyValue( KeyValueData *pkvd ); void Spawn( void ); void Precache( void ); }; LINK_ENTITY_TO_CLASS( func_ladder, CLadder ); void CLadder :: KeyValue( KeyValueData *pkvd ) { CBaseTrigger::KeyValue( pkvd ); } //========================================================= // func_ladder - makes an area vertically negotiable //========================================================= void CLadder :: Precache( void ) { // Do all of this in here because we need to 'convert' old saved games pev->solid = SOLID_NOT; pev->skin = CONTENTS_LADDER; if ( CVAR_GET_FLOAT("showtriggers") == 0 ) { pev->rendermode = kRenderTransTexture; pev->renderamt = 0; } pev->effects &= ~EF_NODRAW; } void CLadder :: Spawn( void ) { Precache(); SET_MODEL(ENT(pev), STRING(pev->model)); // set size and link into world pev->movetype = MOVETYPE_PUSH; } // ========================== A TRIGGER THAT PUSHES YOU =============================== class CTriggerPush : public CBaseTrigger { public: void Spawn( void ); void KeyValue( KeyValueData *pkvd ); void Touch( CBaseEntity *pOther ); }; LINK_ENTITY_TO_CLASS( trigger_push, CTriggerPush ); void CTriggerPush :: KeyValue( KeyValueData *pkvd ) { CBaseTrigger::KeyValue( pkvd ); } /*QUAKED trigger_push (.5 .5 .5) ? TRIG_PUSH_ONCE Pushes the player */ void CTriggerPush :: Spawn( ) { if ( pev->angles == g_vecZero ) pev->angles.y = 360; InitTrigger(); if (pev->speed == 0) pev->speed = 100; if ( FBitSet (pev->spawnflags, SF_TRIGGER_PUSH_START_OFF) )// if flagged to Start Turned Off, make trigger nonsolid. pev->solid = SOLID_NOT; SetUse( ToggleUse ); UTIL_SetOrigin( pev, pev->origin ); // Link into the list } void CTriggerPush :: Touch( CBaseEntity *pOther ) { entvars_t* pevToucher = pOther->pev; // UNDONE: Is there a better way than health to detect things that have physics? (clients/monsters) switch( pevToucher->movetype ) { case MOVETYPE_NONE: case MOVETYPE_PUSH: case MOVETYPE_NOCLIP: case MOVETYPE_FOLLOW: return; } //Only players if ( !pOther->IsPlayer() ) return; if ( pevToucher->solid != SOLID_NOT && pevToucher->solid != SOLID_BSP ) { // Instant trigger, just transfer velocity and remove if (FBitSet(pev->spawnflags, SF_TRIG_PUSH_ONCE)) { pevToucher->velocity = pevToucher->velocity + (pev->speed * pev->movedir); if ( pevToucher->velocity.z > 0 ) pevToucher->flags &= ~FL_ONGROUND; UTIL_Remove( this ); } else { // Push field, transfer to base velocity Vector vecPush = (pev->speed * pev->movedir); if ( pevToucher->flags & FL_BASEVELOCITY ) vecPush = vecPush + pevToucher->basevelocity; pevToucher->basevelocity = vecPush; pevToucher->flags |= FL_BASEVELOCITY; // ALERT( at_console, "Vel %f, base %f\n", pevToucher->velocity.z, pevToucher->basevelocity.z ); } } } //======================================================================================== // TELEPORT TRIGGERS //======================================================================================== //----------------------------------------------------------------------------- // Purpose: Teleport Death entity. Kills anything it touches //----------------------------------------------------------------------------- class CTeleDeath : public CBaseTrigger { public: void Spawn( void ); void EXPORT DeathTouch( CBaseEntity *pOther ); }; LINK_ENTITY_TO_CLASS( teledeath, CTeleDeath ); void CTeleDeath::Spawn( void ) { pev->movetype = MOVETYPE_NONE; pev->solid = SOLID_TRIGGER; pev->angles = g_vecZero; // Owner is the player who's spawned this CBaseEntity *pOwner = CBaseEntity::Instance(pev->owner); if (!pOwner) return; UTIL_SetSize( pev, pOwner->pev->mins - Vector(1,1,1), pOwner->pev->maxs + Vector(1,1,1) ); UTIL_SetOrigin( pev, pev->origin ); SetTouch( DeathTouch ); pev->nextthink = gpGlobals->time + 0.2; SetThink( SUB_Remove ); // Touch still players gpGlobals->force_retouch = 2; } void CTeleDeath::DeathTouch( CBaseEntity *pOther ) { CBaseEntity *pOwner = CBaseEntity::Instance(pev->owner); if ( pOther == pOwner ) return; // frag anyone who teleports in on top of an invincible player if ( pOther->IsPlayer() ) { if ( ((CBasePlayer*)pOther)->m_flInvincibleFinished > gpGlobals->time ) { // Note: This did not work in Quake. Fixed in QUAKECLASSIC. if ( pOwner->IsPlayer() ) { g_szDeathType = "teledeath2"; pOwner->TakeDamage( pOwner->pev, pOwner->pev, 1000, DMG_GENERIC | DMG_ALWAYSGIB); return; } } } if ( pOther->pev->health ) { g_szDeathType = "teledeath"; pOther->TakeDamage( pOther->pev, pOwner->pev, 1000, DMG_GENERIC | DMG_ALWAYSGIB); } } //====================================== // teleport trigger // // QUAKECLASSIC: Different bitflags #define TELE_PLAYER_ONLY 1 #define TELE_SILENT 2 //----------------------------------------------------------------------------- // Purpose: Spawn a teleport fog at the vector specified //----------------------------------------------------------------------------- void CBaseEntity::Spawn_Telefog( Vector vecOrg, CBaseEntity *pOther ) { //Moved to the client PLAYBACK_EVENT_FULL ( FEV_GLOBAL | FEV_NOTHOST, pOther->edict(), g_sTeleport, 0.0, (float *)&vecOrg, (float *)&g_vecZero, 0.0, 0.0, 0, 0, 0, 0); } //----------------------------------------------------------------------------- // Purpose: Kill anything at the teleport destination //----------------------------------------------------------------------------- void CBaseTrigger :: TeleportTouch( CBaseEntity *pOther ) { // no clients allowed? if ( ( pev->spawnflags & TELE_PLAYER_ONLY ) ) { if ( pOther->IsPlayer() ) return; } // only teleport living creatures if (pOther->pev->health <= 0 || pOther->pev->solid != SOLID_SLIDEBOX) return; SUB_UseTargets( this, USE_TOGGLE, 0 ); // put a tfog where the player was Spawn_Telefog(pOther->pev->origin, pOther ); edict_t *pentTarget = NULL; pentTarget = FIND_ENTITY_BY_TARGETNAME( pentTarget, STRING(pev->target) ); if (FNullEnt(pentTarget)) return; // spawn a tfog flash in front of the destination CBaseEntity *pTarget = CBaseEntity::Instance( pentTarget ); UTIL_MakeVectors(pTarget->m_vecTeleAngles); Vector vecNewOrg = pTarget->pev->origin + (gpGlobals->v_forward * 32); pTarget->Spawn_Telefog( vecNewOrg, pOther ); // Spawn teledeath at destination CTeleDeath *pDeath = GetClassPtr( (CTeleDeath *)NULL ); pDeath->pev->owner = pOther->edict(); pDeath->pev->origin = pTarget->pev->origin; pDeath->Spawn(); // May be killed by teleporting onto an invulnerable player if (!pOther->pev->health) { pOther->pev->origin = pTarget->pev->origin; pOther->pev->velocity = (gpGlobals->v_forward * pOther->pev->velocity.x) + (gpGlobals->v_forward * pOther->pev->velocity.y); return; } // Move the player UTIL_SetOrigin( pOther->pev, pTarget->pev->origin ); pOther->pev->angles = pTarget->m_vecTeleAngles; if (pOther->IsPlayer()) { // pOther->pev->fixangle = 1; // turn this way immediately //Err, why is this here? pOther->pev->fuser4 = gpGlobals->time + 0.7; pOther->pev->velocity = gpGlobals->v_forward * 300; } pOther->pev->flags &= ~FL_ONGROUND; } class CTriggerTeleport : public CBaseTrigger { public: void Spawn( void ); }; LINK_ENTITY_TO_CLASS( trigger_teleport, CTriggerTeleport ); void CTriggerTeleport :: Spawn( void ) { InitTrigger(); SetTouch( TeleportTouch ); g_vecTeleMins[ g_iTeleNum ] = pev->absmin; g_vecTeleMaxs[ g_iTeleNum ] = pev->absmax; g_iTeleNum++; if (!(pev->spawnflags & TELE_SILENT)) { PRECACHE_SOUND("ambience/hum1.wav"); UTIL_EmitAmbientSound(ENT(pev), (pev->mins + pev->maxs) * 0.5, "ambience/hum1.wav", 0.5, ATTN_STATIC, 0, 100); } } class CTriggerTeleportDest : public CBaseTrigger { public: void Spawn( void ); }; void CTriggerTeleportDest :: Spawn( void ) { m_vecTeleAngles = pev->angles; pev->angles = g_vecZero; pev->origin.z += 27; UTIL_SetOrigin( pev, pev->origin ); } LINK_ENTITY_TO_CLASS( info_teleport_destination, CTriggerTeleportDest ); //========================================================================== class CTriggerSave : public CBaseTrigger { public: void Spawn( void ); void EXPORT SaveTouch( CBaseEntity *pOther ); }; LINK_ENTITY_TO_CLASS( trigger_autosave, CTriggerSave ); void CTriggerSave::Spawn( void ) { if ( g_pGameRules->IsDeathmatch() ) { REMOVE_ENTITY( ENT(pev) ); return; } InitTrigger(); SetTouch( SaveTouch ); } void CTriggerSave::SaveTouch( CBaseEntity *pOther ) { if ( !UTIL_IsMasterTriggered( m_sMaster, pOther ) ) return; // Only save on clients if ( !pOther->IsPlayer() ) return; SetTouch( NULL ); UTIL_Remove( this ); SERVER_COMMAND( "autosave\n" ); } #define SF_ENDSECTION_USEONLY 0x0001 class CTriggerEndSection : public CBaseTrigger { public: void Spawn( void ); void EXPORT EndSectionTouch( CBaseEntity *pOther ); void KeyValue( KeyValueData *pkvd ); void EXPORT EndSectionUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); }; LINK_ENTITY_TO_CLASS( trigger_endsection, CTriggerEndSection ); void CTriggerEndSection::EndSectionUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { // Only save on clients if ( !pActivator->IsNetClient() ) return; SetUse( NULL ); if ( pev->message ) { g_engfuncs.pfnEndSection(STRING(pev->message)); } UTIL_Remove( this ); } void CTriggerEndSection::Spawn( void ) { if ( g_pGameRules->IsDeathmatch() ) { REMOVE_ENTITY( ENT(pev) ); return; } InitTrigger(); SetUse ( EndSectionUse ); // If it is a "use only" trigger, then don't set the touch function. if ( ! (pev->spawnflags & SF_ENDSECTION_USEONLY) ) SetTouch( EndSectionTouch ); } void CTriggerEndSection::EndSectionTouch( CBaseEntity *pOther ) { // Only save on clients if ( !pOther->IsNetClient() ) return; SetTouch( NULL ); if (pev->message) { g_engfuncs.pfnEndSection(STRING(pev->message)); } UTIL_Remove( this ); } void CTriggerEndSection :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "section")) { // m_iszSectionName = ALLOC_STRING( pkvd->szValue ); // Store this in message so we don't have to write save/restore for this ent pev->message = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseTrigger::KeyValue( pkvd ); } class CTriggerGravity : public CBaseTrigger { public: void Spawn( void ); void EXPORT GravityTouch( CBaseEntity *pOther ); }; LINK_ENTITY_TO_CLASS( trigger_gravity, CTriggerGravity ); void CTriggerGravity::Spawn( void ) { InitTrigger(); SetTouch( GravityTouch ); } void CTriggerGravity::GravityTouch( CBaseEntity *pOther ) { // Only save on clients if ( !pOther->IsPlayer() ) return; pOther->pev->gravity = pev->gravity; } // this is a really bad idea. class CTriggerChangeTarget : public CBaseDelay { public: void KeyValue( KeyValueData *pkvd ); void Spawn( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); int ObjectCaps( void ) { return CBaseDelay::ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; private: int m_iszNewTarget; }; LINK_ENTITY_TO_CLASS( trigger_changetarget, CTriggerChangeTarget ); TYPEDESCRIPTION CTriggerChangeTarget::m_SaveData[] = { DEFINE_FIELD( CTriggerChangeTarget, m_iszNewTarget, FIELD_STRING ), }; IMPLEMENT_SAVERESTORE(CTriggerChangeTarget,CBaseDelay); void CTriggerChangeTarget::KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "m_iszNewTarget")) { m_iszNewTarget = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseDelay::KeyValue( pkvd ); } void CTriggerChangeTarget::Spawn( void ) { } void CTriggerChangeTarget::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { CBaseEntity *pTarget = UTIL_FindEntityByString( NULL, "targetname", STRING( pev->target ) ); if (pTarget) { pTarget->pev->target = m_iszNewTarget; CBaseMonster *pMonster = pTarget->MyMonsterPointer( ); if (pMonster) { pMonster->m_pGoalEnt = NULL; } } } #define SF_CAMERA_PLAYER_POSITION 1 #define SF_CAMERA_PLAYER_TARGET 2 #define SF_CAMERA_PLAYER_TAKECONTROL 4 class CTriggerCamera : public CBaseDelay { public: void Spawn( void ); void KeyValue( KeyValueData *pkvd ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void EXPORT FollowTarget( void ); void Move(void); virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); virtual int ObjectCaps( void ) { return CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } static TYPEDESCRIPTION m_SaveData[]; EHANDLE m_hPlayer; EHANDLE m_hTarget; CBaseEntity *m_pentPath; int m_sPath; float m_flWait; float m_flReturnTime; float m_flStopTime; float m_moveDistance; float m_targetSpeed; float m_initialSpeed; float m_acceleration; float m_deceleration; int m_state; }; LINK_ENTITY_TO_CLASS( trigger_camera, CTriggerCamera ); // Global Savedata for changelevel friction modifier TYPEDESCRIPTION CTriggerCamera::m_SaveData[] = { DEFINE_FIELD( CTriggerCamera, m_hPlayer, FIELD_EHANDLE ), DEFINE_FIELD( CTriggerCamera, m_hTarget, FIELD_EHANDLE ), DEFINE_FIELD( CTriggerCamera, m_pentPath, FIELD_CLASSPTR ), DEFINE_FIELD( CTriggerCamera, m_sPath, FIELD_STRING ), DEFINE_FIELD( CTriggerCamera, m_flWait, FIELD_FLOAT ), DEFINE_FIELD( CTriggerCamera, m_flReturnTime, FIELD_TIME ), DEFINE_FIELD( CTriggerCamera, m_flStopTime, FIELD_TIME ), DEFINE_FIELD( CTriggerCamera, m_moveDistance, FIELD_FLOAT ), DEFINE_FIELD( CTriggerCamera, m_targetSpeed, FIELD_FLOAT ), DEFINE_FIELD( CTriggerCamera, m_initialSpeed, FIELD_FLOAT ), DEFINE_FIELD( CTriggerCamera, m_acceleration, FIELD_FLOAT ), DEFINE_FIELD( CTriggerCamera, m_deceleration, FIELD_FLOAT ), DEFINE_FIELD( CTriggerCamera, m_state, FIELD_INTEGER ), }; IMPLEMENT_SAVERESTORE(CTriggerCamera,CBaseDelay); void CTriggerCamera::Spawn( void ) { pev->movetype = MOVETYPE_NOCLIP; pev->solid = SOLID_NOT; // Remove model & collisions pev->renderamt = 0; // The engine won't draw this model if this is set to 0 and blending is on pev->rendermode = kRenderTransTexture; m_initialSpeed = pev->speed; if ( m_acceleration == 0 ) m_acceleration = 500; if ( m_deceleration == 0 ) m_deceleration = 500; } void CTriggerCamera :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "wait")) { m_flWait = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "moveto")) { m_sPath = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "acceleration")) { m_acceleration = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "deceleration")) { m_deceleration = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseDelay::KeyValue( pkvd ); } void CTriggerCamera::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( !ShouldToggle( useType, m_state ) ) return; // Toggle state m_state = !m_state; if (m_state == 0) { m_flReturnTime = gpGlobals->time; return; } if ( !pActivator || !pActivator->IsPlayer() ) { pActivator = CBaseEntity::Instance(g_engfuncs.pfnPEntityOfEntIndex( 1 )); } m_hPlayer = pActivator; m_flReturnTime = gpGlobals->time + m_flWait; pev->speed = m_initialSpeed; m_targetSpeed = m_initialSpeed; if (FBitSet (pev->spawnflags, SF_CAMERA_PLAYER_TARGET ) ) { m_hTarget = m_hPlayer; } else { m_hTarget = GetNextTarget(); } // Nothing to look at! if ( m_hTarget == NULL ) { return; } if (FBitSet (pev->spawnflags, SF_CAMERA_PLAYER_TAKECONTROL ) ) { ((CBasePlayer *)pActivator)->EnableControl(FALSE); } if ( m_sPath ) { m_pentPath = Instance( FIND_ENTITY_BY_TARGETNAME ( NULL, STRING(m_sPath)) ); } else { m_pentPath = NULL; } m_flStopTime = gpGlobals->time; if ( m_pentPath ) { if ( m_pentPath->pev->speed != 0 ) m_targetSpeed = m_pentPath->pev->speed; m_flStopTime += m_pentPath->GetDelay(); } // copy over player information if (FBitSet (pev->spawnflags, SF_CAMERA_PLAYER_POSITION ) ) { UTIL_SetOrigin( pev, pActivator->pev->origin + pActivator->pev->view_ofs ); pev->angles.x = -pActivator->pev->angles.x; pev->angles.y = pActivator->pev->angles.y; pev->angles.z = 0; pev->velocity = pActivator->pev->velocity; } else { pev->velocity = Vector( 0, 0, 0 ); } SET_VIEW( pActivator->edict(), edict() ); SET_MODEL(ENT(pev), STRING(pActivator->pev->model) ); // follow the player down SetThink( FollowTarget ); pev->nextthink = gpGlobals->time; m_moveDistance = 0; Move(); } void CTriggerCamera::FollowTarget( ) { if (m_hPlayer == NULL) return; if (m_hTarget == NULL || m_flReturnTime < gpGlobals->time) { if (m_hPlayer->IsAlive( )) { SET_VIEW( m_hPlayer->edict(), m_hPlayer->edict() ); ((CBasePlayer *)((CBaseEntity *)m_hPlayer))->EnableControl(TRUE); } SUB_UseTargets( this, USE_TOGGLE, 0 ); pev->avelocity = Vector( 0, 0, 0 ); m_state = 0; return; } Vector vecGoal = UTIL_VecToAngles( m_hTarget->pev->origin - pev->origin ); vecGoal.x = -vecGoal.x; if (pev->angles.y > 360) pev->angles.y -= 360; if (pev->angles.y < 0) pev->angles.y += 360; float dx = vecGoal.x - pev->angles.x; float dy = vecGoal.y - pev->angles.y; if (dx < -180) dx += 360; if (dx > 180) dx = dx - 360; if (dy < -180) dy += 360; if (dy > 180) dy = dy - 360; pev->avelocity.x = dx * 40 * gpGlobals->frametime; pev->avelocity.y = dy * 40 * gpGlobals->frametime; if (!(FBitSet (pev->spawnflags, SF_CAMERA_PLAYER_TAKECONTROL))) { pev->velocity = pev->velocity * 0.8; if (pev->velocity.Length( ) < 10.0) pev->velocity = g_vecZero; } pev->nextthink = gpGlobals->time; Move(); } void CTriggerCamera::Move() { // Not moving on a path, return if (!m_pentPath) return; // Subtract movement from the previous frame m_moveDistance -= pev->speed * gpGlobals->frametime; // Have we moved enough to reach the target? if ( m_moveDistance <= 0 ) { // Fire the passtarget if there is one if ( m_pentPath->pev->message ) { FireTargets( STRING(m_pentPath->pev->message), this, this, USE_TOGGLE, 0 ); if ( FBitSet( m_pentPath->pev->spawnflags, SF_CORNER_FIREONCE ) ) m_pentPath->pev->message = 0; } // Time to go to the next target m_pentPath = m_pentPath->GetNextTarget(); // Set up next corner if ( !m_pentPath ) { pev->velocity = g_vecZero; } else { if ( m_pentPath->pev->speed != 0 ) m_targetSpeed = m_pentPath->pev->speed; Vector delta = m_pentPath->pev->origin - pev->origin; m_moveDistance = delta.Length(); pev->movedir = delta.Normalize(); m_flStopTime = gpGlobals->time + m_pentPath->GetDelay(); } } if ( m_flStopTime > gpGlobals->time ) pev->speed = UTIL_Approach( 0, pev->speed, m_deceleration * gpGlobals->frametime ); else pev->speed = UTIL_Approach( m_targetSpeed, pev->speed, m_acceleration * gpGlobals->frametime ); float fraction = 2 * gpGlobals->frametime; pev->velocity = ((pev->movedir * pev->speed) * fraction) + (pev->velocity * (1-fraction)); } void CClientFog :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "startdist")) { m_iStartDist = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "enddist")) { m_iEndDist = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } void CClientFog :: Spawn ( void ) { pev->movetype = MOVETYPE_NOCLIP; pev->solid = SOLID_NOT; // Remove model & collisions pev->renderamt = 0; // The engine won't draw this model if this is set to 0 and blending is on pev->rendermode = kRenderTransTexture; } LINK_ENTITY_TO_CLASS( env_fog, CClientFog );
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 2716 ] ] ]
53532d335840d88e90a794496e2dbf0c8c61200b
7e68ef369eff945f581e22595adecb6b3faccd0e
/code/minifw/servicehandler.cpp
b33a5806ffd654082130022d2e6919329e63090b
[]
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
52
cpp
#include "StdAfx.h" #include "servicehandler.h"
[ "[email protected]@77f6bdef-6155-0410-8b08-fdea0229669f" ]
[ [ [ 1, 3 ] ] ]
811fc207c119ab5283865d8ead2f7a3ce4549366
5ff30d64df43c7438bbbcfda528b09bb8fec9e6b
/kserver/test/TestDriver.cpp
976b6ae24232c737a3aa84e295274f777467b7de
[]
no_license
lvtx/gamekernel
c80cdb4655f6d4930a7d035a5448b469ac9ae924
a84d9c268590a294a298a4c825d2dfe35e6eca21
refs/heads/master
2016-09-06T18:11:42.702216
2011-09-27T07:22:08
2011-09-27T07:22:08
38,255,025
3
1
null
null
null
null
UTF-8
C++
false
false
1,309
cpp
#include "stdafx.h" #include <kserver/serverbase.h> #include <kserver/test/TestDriver.h> #include <kcore/xml/tinyxml.h> namespace gk { TestDriver::TestDriver() : m_creator( 0 ) , m_xe( 0 ) { } TestDriver::~TestDriver() { Fini(); } bool TestDriver::Init( TestCreator* creator, uint testCount, TiXmlElement* xe ) { K_ASSERT( creator != 0 ); K_ASSERT( testCount > 0 ); K_ASSERT( xe != 0 ); m_creator = creator; m_xe = xe; for ( uint i=0; i<testCount; ++i ) { TestClient* tc = new TestClient; tc->Init( creator, i, xe ); m_tests.push_back( tc ); } return true; } bool TestDriver::Run() { // check for tests and restart if finished uint idx = 0; TestList::iterator i( m_tests.begin() ); TestList::iterator iEnd( m_tests.end() ); for ( ; i != iEnd; ++i ) { TestClient* tc = *i; if ( tc->IsFinished() ) { tc->Fini(); tc->Init( m_creator, idx, m_xe); } ++idx; } m_tests.clear(); return true; } void TestDriver::Fini() { // clear all tests TestList::iterator i( m_tests.begin() ); TestList::iterator iEnd( m_tests.end() ); for ( ; i != iEnd; ++i ) { TestClient* tc = *i; tc->Fini(); delete tc; } m_tests.clear(); m_creator = 0; } } // gk
[ "darkface@localhost" ]
[ [ [ 1, 92 ] ] ]
b563809c035a05512a09b9866ac7d5aa34492416
41371839eaa16ada179d580f7b2c1878600b718e
/UVa/Volume CXII/11219.cpp
4469db33efa040539df5b95b095cb71e7329aba3
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
696
cpp
///////////////////////////////// // 11219 - How old are you? ///////////////////////////////// #include<cstdio> unsigned short int b[3],c[3],age; unsigned int cnum,tnum=0; int main(void){ scanf("%u",&cnum); while(cnum--){ tnum++; scanf("%2hu/%2hu/%4hu\n",&c[0],&c[1],&c[2]); scanf("%2hu/%2hu/%4hu\n",&b[0],&b[1],&b[2]); if(c[2] < b[2] || (c[2] == b[2] && (c[1] < b[1] || (c[1] == b[1] && c[0] < b[0])))) printf("Case #%u: Invalid birth date\n",tnum); else { age = c[2] - b[2]; if(c[1] < b[1] || (c[1] == b[1] && c[0] < b[0])) age--; if(age>130) printf("Case #%u: Check birth date\n",tnum); else printf("Case #%u: %u\n",tnum,age); } } return 0; }
[ [ [ 1, 27 ] ] ]
ded199e5a938210c63081ff81ab0226e95b5b34a
bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2
/Open GL Basic Engine/source/glutFramework/glutFramework/logicBlock.h
b4e15f73aace3ba1a137dc8b4d6668ffcbd1a0b4
[]
no_license
CorwinJV/rvbgame
0f2723ed3a4c1a368fc3bac69052091d2d87de77
a4fc13ed95bd3e5a03e3c6ecff633fe37718314b
refs/heads/master
2021-01-01T06:49:33.445550
2009-11-03T23:14:39
2009-11-03T23:14:39
32,131,378
0
0
null
null
null
null
UTF-8
C++
false
false
2,213
h
#ifndef LOGICBLOCK_H #define LOGICBLOCK_H #include "aiInstructionEnums.h" #include "oglTexture2D.h" #include <vector> #include <string> #include "aiInstructionEnums.h" enum logicBlockState { BS_INACTIVE, BS_ACTIVE, BS_HIGHLIGHTED }; //=============================================== // logicBlock // This struct defines a container for a texture // (icon), a description (like a tool tip), // a point value, and a vector of AiInstructions // enum values. // // These blocks are the building blocks of // execution. struct logicBlock { logicBlock() { blockTexture = NULL; } logicBlock(std::string textureName, int width, int height, std::string description, int byteCost, AiInstructions enumInstruction) { blockTexture = new oglTexture2D(); blockTexture->loadImage(textureName, width, height); blockDescription = description; logicBlock::byteCost = byteCost; logicBlock::enumInstruction = enumInstruction; curButtonState = BS_INACTIVE; isUsable = true; isCurrentlyUsable = true; } ~logicBlock() { delete blockTexture; blockTexture = NULL; } // Copy Constructor: logicBlock(const logicBlock& p) { blockDescription = p.blockDescription; blockTexture = new oglTexture2D(*(p.blockTexture)); instructionList = p.instructionList; byteCost = p.byteCost; enumInstruction = p.enumInstruction; curButtonState = p.curButtonState; isUsable = p.isUsable; isCurrentlyUsable = p.isCurrentlyUsable; } void addInstruction(AiInstructions instr) { instructionList.push_back(instr); } bool checkInBounds(int x, int y, int widthBound, int heightBound) { // dX and dY should be width and height if (((x > blockTexture->mX) && (x < (blockTexture->mX + widthBound))) && (y > blockTexture->mY) && (y < (blockTexture->mY + heightBound))) return true; else return false; } std::string blockDescription; oglTexture2D* blockTexture; std::vector<AiInstructions> instructionList; int byteCost; AiInstructions enumInstruction; logicBlockState curButtonState; bool isUsable; bool isCurrentlyUsable; }; #endif
[ "corwin.j@5457d560-9b84-11de-b17c-2fd642447241" ]
[ [ [ 1, 88 ] ] ]
bda99d03b8d933e6c55afd2f44c0aeb535f3c686
1cc5720e245ca0d8083b0f12806a5c8b13b5cf98
/v107/10763/c.cpp
a3dc2bd3c78ded9554b63b17823968dff1e3c26c
[]
no_license
Emerson21/uva-problems
399d82d93b563e3018921eaff12ca545415fd782
3079bdd1cd17087cf54b08c60e2d52dbd0118556
refs/heads/master
2021-01-18T09:12:23.069387
2010-12-15T00:38:34
2010-12-15T00:38:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
586
cpp
#include <iostream> #include <algorithm> #include <map> using namespace std; #define PI pair<int,int> int main() { int n,i,j,k,val; map<PI,int> m; while((cin >> n) && n) { m.clear(); while(n--) { cin >> i >> j; if(i>j) { val=-1; swap(i,j); } else val=1; PI p = make_pair(i,j); if(m.find(p)!=m.end()) { val += (*(m.find(p))).second; if(val) m[p] = val; else m.erase(p); } else m[p]=val; } if(!m.size()) cout << "YES"<<endl; else cout << "NO" << endl; } return 0; }
[ [ [ 1, 44 ] ] ]
d3e82c01968c2db6290fe7311e18a01bfbc87a29
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKitTools/DumpRenderTree/chromium/TestShell.cpp
d50838436d8c73582924b2eed42b88aa04c57c03
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,114
cpp
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "TestShell.h" #include "DRTDevToolsAgent.h" #include "DRTDevToolsClient.h" #include "LayoutTestController.h" #include "WebViewHost.h" #include "public/WebDataSource.h" #include "public/WebDocument.h" #include "public/WebElement.h" #include "public/WebFrame.h" #include "public/WebHistoryItem.h" #include "public/WebKit.h" #include "public/WebRuntimeFeatures.h" #include "public/WebScriptController.h" #include "public/WebSettings.h" #include "public/WebSize.h" #include "public/WebSpeechInputControllerMock.h" #include "public/WebString.h" #include "public/WebURLRequest.h" #include "public/WebURLResponse.h" #include "public/WebView.h" #include "skia/ext/bitmap_platform_device.h" #include "skia/ext/platform_canvas.h" #include "webkit/support/webkit_support.h" #include "webkit/support/webkit_support_gfx.h" #include <algorithm> #include <cctype> #include <vector> #include <wtf/MD5.h> using namespace WebKit; using namespace std; // Content area size for newly created windows. static const int testWindowWidth = 800; static const int testWindowHeight = 600; // The W3C SVG layout tests use a different size than the other layout tests. static const int SVGTestWindowWidth = 480; static const int SVGTestWindowHeight = 360; static const char layoutTestsPattern[] = "/LayoutTests/"; static const string::size_type layoutTestsPatternSize = sizeof(layoutTestsPattern) - 1; static const char fileUrlPattern[] = "file:/"; static const char fileTestPrefix[] = "(file test):"; static const char dataUrlPattern[] = "data:"; static const string::size_type dataUrlPatternSize = sizeof(dataUrlPattern) - 1; TestShell::TestShell(bool testShellMode) : m_testIsPending(false) , m_testIsPreparing(false) , m_focusedWidget(0) , m_testShellMode(testShellMode) , m_allowExternalPages(false) , m_devTools(0) { WebRuntimeFeatures::enableGeolocation(true); WebRuntimeFeatures::enableIndexedDatabase(true); m_accessibilityController.set(new AccessibilityController(this)); m_layoutTestController.set(new LayoutTestController(this)); m_eventSender.set(new EventSender(this)); m_plainTextController.set(new PlainTextController()); m_textInputController.set(new TextInputController(this)); m_notificationPresenter.set(new NotificationPresenter(this)); m_printer.set(m_testShellMode ? TestEventPrinter::createTestShellPrinter() : TestEventPrinter::createDRTPrinter()); // 30 second is the same as the value in Mac DRT. // If we use a value smaller than the timeout value of // (new-)run-webkit-tests, (new-)run-webkit-tests misunderstands that a // timed-out DRT process was crashed. m_timeout = 30 * 1000; m_drtDevToolsAgent.set(new DRTDevToolsAgent); m_webViewHost = createWebView(); m_webView = m_webViewHost->webView(); m_drtDevToolsAgent->setWebView(m_webView); } TestShell::~TestShell() { // Note: DevTools are closed together with all the other windows in the // windows list. loadURL(GURL("about:blank")); // Call GC twice to clean up garbage. callJSGC(); callJSGC(); // Destroy the WebView before its WebViewHost. m_drtDevToolsAgent->setWebView(0); m_webView->close(); } void TestShell::createDRTDevToolsClient(DRTDevToolsAgent* agent) { m_drtDevToolsClient.set(new DRTDevToolsClient(agent, m_devTools->webView())); } void TestShell::showDevTools() { if (!m_devTools) { WebURL url = webkit_support::GetDevToolsPathAsURL(); if (!url.isValid()) { ASSERT(false); return; } m_devTools = createNewWindow(url); ASSERT(m_devTools); createDRTDevToolsClient(m_drtDevToolsAgent.get()); } m_devTools->show(WebKit::WebNavigationPolicyNewWindow); } void TestShell::closeDevTools() { if (m_devTools) { m_drtDevToolsAgent->reset(); m_drtDevToolsClient.clear(); closeWindow(m_devTools); m_devTools = 0; } } void TestShell::resetWebSettings(WebView& webView) { // Match the settings used by Mac DumpRenderTree, with the exception of // fonts. WebSettings* settings = webView.settings(); #if OS(MAC_OS_X) WebString serif = WebString::fromUTF8("Times"); settings->setCursiveFontFamily(WebString::fromUTF8("Apple Chancery")); settings->setFantasyFontFamily(WebString::fromUTF8("Papyrus")); #else // NOTE: case matters here, this must be 'times new roman', else // some layout tests fail. WebString serif = WebString::fromUTF8("times new roman"); // These two fonts are picked from the intersection of // Win XP font list and Vista font list : // http://www.microsoft.com/typography/fonts/winxp.htm // http://blogs.msdn.com/michkap/archive/2006/04/04/567881.aspx // Some of them are installed only with CJK and complex script // support enabled on Windows XP and are out of consideration here. // (although we enabled both on our buildbots.) // They (especially Impact for fantasy) are not typical cursive // and fantasy fonts, but it should not matter for layout tests // as long as they're available. settings->setCursiveFontFamily(WebString::fromUTF8("Comic Sans MS")); settings->setFantasyFontFamily(WebString::fromUTF8("Impact")); #endif settings->setSerifFontFamily(serif); settings->setStandardFontFamily(serif); settings->setFixedFontFamily(WebString::fromUTF8("Courier")); settings->setSansSerifFontFamily(WebString::fromUTF8("Helvetica")); settings->setDefaultTextEncodingName(WebString::fromUTF8("ISO-8859-1")); settings->setDefaultFontSize(16); settings->setDefaultFixedFontSize(13); settings->setMinimumFontSize(1); settings->setMinimumLogicalFontSize(9); settings->setJavaScriptCanOpenWindowsAutomatically(true); settings->setJavaScriptCanAccessClipboard(true); settings->setDOMPasteAllowed(true); settings->setDeveloperExtrasEnabled(false); settings->setNeedsSiteSpecificQuirks(true); settings->setShrinksStandaloneImagesToFit(false); settings->setUsesEncodingDetector(false); settings->setTextAreasAreResizable(false); settings->setJavaEnabled(false); settings->setAllowScriptsToCloseWindows(false); settings->setXSSAuditorEnabled(false); settings->setDownloadableBinaryFontsEnabled(true); settings->setLocalStorageEnabled(true); settings->setOfflineWebApplicationCacheEnabled(true); settings->setAllowFileAccessFromFileURLs(true); settings->setUserStyleSheetLocation(WebURL()); // LayoutTests were written with Safari Mac in mind which does not allow // tabbing to links by default. webView.setTabsToLinks(false); // Allow those layout tests running as local files, i.e. under // LayoutTests/http/tests/local, to access http server. settings->setAllowUniversalAccessFromFileURLs(true); settings->setJavaScriptEnabled(true); settings->setPluginsEnabled(true); settings->setWebSecurityEnabled(true); settings->setEditableLinkBehaviorNeverLive(); settings->setFontRenderingModeNormal(); settings->setShouldPaintCustomScrollbars(true); settings->setTextDirectionSubmenuInclusionBehaviorNeverIncluded(); settings->setLoadsImagesAutomatically(true); settings->setImagesEnabled(true); #if OS(DARWIN) settings->setEditingBehavior(WebSettings::EditingBehaviorMac); #else settings->setEditingBehavior(WebSettings::EditingBehaviorWin); #endif // FIXME: crbug.com/51879 settings->setAcceleratedCompositingEnabled(false); } void TestShell::runFileTest(const TestParams& params) { ASSERT(params.testUrl.isValid()); m_testIsPreparing = true; m_params = params; string testUrl = m_params.testUrl.spec(); bool inspectorTestMode = testUrl.find("/inspector/") != string::npos || testUrl.find("\\inspector\\") != string::npos; m_webView->settings()->setDeveloperExtrasEnabled(inspectorTestMode); if (testUrl.find("loading/") != string::npos || testUrl.find("loading\\") != string::npos) m_layoutTestController->setShouldDumpFrameLoadCallbacks(true); if (inspectorTestMode) showDevTools(); m_printer->handleTestHeader(testUrl.c_str()); loadURL(m_params.testUrl); m_testIsPreparing = false; waitTestFinished(); } static inline bool isSVGTestURL(const WebURL& url) { return url.isValid() && string(url.spec()).find("W3C-SVG-1.1") != string::npos; } void TestShell::resizeWindowForTest(WebViewHost* window, const WebURL& url) { int width, height; if (isSVGTestURL(url)) { width = SVGTestWindowWidth; height = SVGTestWindowHeight; } else { width = testWindowWidth; height = testWindowHeight; } window->setWindowRect(WebRect(0, 0, width + virtualWindowBorder * 2, height + virtualWindowBorder * 2)); } void TestShell::resetTestController() { resetWebSettings(*webView()); m_accessibilityController->reset(); m_layoutTestController->reset(); m_eventSender->reset(); m_webViewHost->reset(); m_notificationPresenter->reset(); m_drtDevToolsAgent->reset(); if (m_drtDevToolsClient) m_drtDevToolsClient->reset(); } void TestShell::loadURL(const WebURL& url) { m_webViewHost->loadURLForFrame(url, WebString()); } void TestShell::reload() { m_webViewHost->navigationController()->reload(); } void TestShell::goToOffset(int offset) { m_webViewHost->navigationController()->goToOffset(offset); } int TestShell::navigationEntryCount() const { return m_webViewHost->navigationController()->entryCount(); } void TestShell::callJSGC() { m_webView->mainFrame()->collectGarbage(); } void TestShell::setFocus(WebWidget* widget, bool enable) { // Simulate the effects of InteractiveSetFocus(), which includes calling // both setFocus() and setIsActive(). if (enable) { if (m_focusedWidget != widget) { if (m_focusedWidget) m_focusedWidget->setFocus(false); webView()->setIsActive(enable); widget->setFocus(enable); m_focusedWidget = widget; } } else { if (m_focusedWidget == widget) { widget->setFocus(enable); webView()->setIsActive(enable); m_focusedWidget = 0; } } } void TestShell::testFinished() { if (!m_testIsPending) return; m_testIsPending = false; dump(); webkit_support::QuitMessageLoop(); } void TestShell::testTimedOut() { m_printer->handleTimedOut(); testFinished(); } static string dumpDocumentText(WebFrame* frame) { // We use the document element's text instead of the body text here because // not all documents have a body, such as XML documents. WebElement documentElement = frame->document().documentElement(); if (documentElement.isNull()) return string(); return documentElement.innerText().utf8(); } static string dumpFramesAsText(WebFrame* frame, bool recursive) { string result; // Add header for all but the main frame. Skip empty frames. if (frame->parent() && !frame->document().documentElement().isNull()) { result.append("\n--------\nFrame: '"); result.append(frame->name().utf8().data()); result.append("'\n--------\n"); } result.append(dumpDocumentText(frame)); result.append("\n"); if (recursive) { for (WebFrame* child = frame->firstChild(); child; child = child->nextSibling()) result.append(dumpFramesAsText(child, recursive)); } return result; } static void dumpFrameScrollPosition(WebFrame* frame, bool recursive) { WebSize offset = frame->scrollOffset(); if (offset.width > 0 || offset.height > 0) { if (frame->parent()) printf("frame '%s' ", frame->name().utf8().data()); printf("scrolled to %d,%d\n", offset.width, offset.height); } if (!recursive) return; for (WebFrame* child = frame->firstChild(); child; child = child->nextSibling()) dumpFrameScrollPosition(child, recursive); } struct ToLower { char16 operator()(char16 c) { return tolower(c); } }; // FIXME: Eliminate std::transform(), std::vector, and std::sort(). // Returns True if item1 < item2. static bool HistoryItemCompareLess(const WebHistoryItem& item1, const WebHistoryItem& item2) { string16 target1 = item1.target(); string16 target2 = item2.target(); std::transform(target1.begin(), target1.end(), target1.begin(), ToLower()); std::transform(target2.begin(), target2.end(), target2.begin(), ToLower()); return target1 < target2; } static string dumpHistoryItem(const WebHistoryItem& item, int indent, bool isCurrent) { string result; if (isCurrent) { result.append("curr->"); result.append(indent - 6, ' '); // 6 == "curr->".length() } else { result.append(indent, ' '); } string url = item.urlString().utf8(); size_t pos; if (!url.find(fileUrlPattern) && ((pos = url.find(layoutTestsPattern)) != string::npos)) { // adjust file URLs to match upstream results. url.replace(0, pos + layoutTestsPatternSize, fileTestPrefix); } else if (!url.find(dataUrlPattern)) { // URL-escape data URLs to match results upstream. string path = webkit_support::EscapePath(url.substr(dataUrlPatternSize)); url.replace(dataUrlPatternSize, url.length(), path); } result.append(url); if (!item.target().isEmpty()) { result.append(" (in frame \""); result.append(item.target().utf8()); result.append("\")"); } if (item.isTargetItem()) result.append(" **nav target**"); result.append("\n"); const WebVector<WebHistoryItem>& children = item.children(); if (!children.isEmpty()) { // Must sort to eliminate arbitrary result ordering which defeats // reproducible testing. // FIXME: WebVector should probably just be a std::vector!! std::vector<WebHistoryItem> sortedChildren; for (size_t i = 0; i < children.size(); ++i) sortedChildren.push_back(children[i]); std::sort(sortedChildren.begin(), sortedChildren.end(), HistoryItemCompareLess); for (size_t i = 0; i < sortedChildren.size(); ++i) result += dumpHistoryItem(sortedChildren[i], indent + 4, false); } return result; } static void dumpBackForwardList(const TestNavigationController& navigationController, string& result) { result.append("\n============== Back Forward List ==============\n"); for (int index = 0; index < navigationController.entryCount(); ++index) { int currentIndex = navigationController.lastCommittedEntryIndex(); WebHistoryItem historyItem = navigationController.entryAtIndex(index)->contentState(); if (historyItem.isNull()) { historyItem.initialize(); historyItem.setURLString(navigationController.entryAtIndex(index)->URL().spec().utf16()); } result.append(dumpHistoryItem(historyItem, 8, index == currentIndex)); } result.append("===============================================\n"); } string TestShell::dumpAllBackForwardLists() { string result; for (unsigned i = 0; i < m_windowList.size(); ++i) dumpBackForwardList(*m_windowList[i]->navigationController(), result); return result; } void TestShell::dump() { WebScriptController::flushConsoleMessages(); // Dump the requested representation. WebFrame* frame = m_webView->mainFrame(); if (!frame) return; bool shouldDumpAsText = m_layoutTestController->shouldDumpAsText(); bool shouldGeneratePixelResults = m_layoutTestController->shouldGeneratePixelResults(); bool dumpedAnything = false; if (m_params.dumpTree) { dumpedAnything = true; m_printer->handleTextHeader(); // Text output: the test page can request different types of output // which we handle here. if (!shouldDumpAsText) { // Plain text pages should be dumped as text string mimeType = frame->dataSource()->response().mimeType().utf8(); if (mimeType == "text/plain") { shouldDumpAsText = true; shouldGeneratePixelResults = false; } } if (shouldDumpAsText) { bool recursive = m_layoutTestController->shouldDumpChildFramesAsText(); string dataUtf8 = dumpFramesAsText(frame, recursive); if (fwrite(dataUtf8.c_str(), 1, dataUtf8.size(), stdout) != dataUtf8.size()) FATAL("Short write to stdout, disk full?\n"); } else { printf("%s", frame->renderTreeAsText().utf8().data()); bool recursive = m_layoutTestController->shouldDumpChildFrameScrollPositions(); dumpFrameScrollPosition(frame, recursive); } if (m_layoutTestController->shouldDumpBackForwardList()) printf("%s", dumpAllBackForwardLists().c_str()); } if (dumpedAnything && m_params.printSeparators) m_printer->handleTextFooter(); if (m_params.dumpPixels && shouldGeneratePixelResults) { // Image output: we write the image data to the file given on the // command line (for the dump pixels argument), and the MD5 sum to // stdout. dumpedAnything = true; m_webView->layout(); if (m_layoutTestController->testRepaint()) { WebSize viewSize = m_webView->size(); int width = viewSize.width; int height = viewSize.height; if (m_layoutTestController->sweepHorizontally()) { for (WebRect column(0, 0, 1, height); column.x < width; column.x++) m_webViewHost->paintRect(column); } else { for (WebRect line(0, 0, width, 1); line.y < height; line.y++) m_webViewHost->paintRect(line); } } else m_webViewHost->paintInvalidatedRegion(); // See if we need to draw the selection bounds rect. Selection bounds // rect is the rect enclosing the (possibly transformed) selection. // The rect should be drawn after everything is laid out and painted. if (m_layoutTestController->shouldDumpSelectionRect()) { // If there is a selection rect - draw a red 1px border enclosing rect WebRect wr = frame->selectionBoundsRect(); if (!wr.isEmpty()) { // Render a red rectangle bounding selection rect SkPaint paint; paint.setColor(0xFFFF0000); // Fully opaque red paint.setStyle(SkPaint::kStroke_Style); paint.setFlags(SkPaint::kAntiAlias_Flag); paint.setStrokeWidth(1.0f); SkIRect rect; // Bounding rect rect.set(wr.x, wr.y, wr.x + wr.width, wr.y + wr.height); m_webViewHost->canvas()->drawIRect(rect, paint); } } dumpImage(m_webViewHost->canvas()); } m_printer->handleImageFooter(); m_printer->handleTestFooter(dumpedAnything); fflush(stdout); fflush(stderr); } void TestShell::dumpImage(skia::PlatformCanvas* canvas) const { skia::BitmapPlatformDevice& device = static_cast<skia::BitmapPlatformDevice&>(canvas->getTopPlatformDevice()); const SkBitmap& sourceBitmap = device.accessBitmap(false); SkAutoLockPixels sourceBitmapLock(sourceBitmap); // Fix the alpha. The expected PNGs on Mac have an alpha channel, so we want // to keep it. On Windows, the alpha channel is wrong since text/form control // drawing may have erased it in a few places. So on Windows we force it to // opaque and also don't write the alpha channel for the reference. Linux // doesn't have the wrong alpha like Windows, but we ignore it anyway. #if OS(WINDOWS) bool discardTransparency = true; device.makeOpaque(0, 0, sourceBitmap.width(), sourceBitmap.height()); #elif OS(MAC_OS_X) bool discardTransparency = false; #elif OS(UNIX) bool discardTransparency = true; if (areLayoutTestImagesOpaque()) device.makeOpaque(0, 0, sourceBitmap.width(), sourceBitmap.height()); #endif // Compute MD5 sum. We should have done this before calling // device.makeOpaque on Windows. Because we do it after the call, there are // some images that are the pixel identical on windows and other platforms // but have different MD5 sums. At this point, rebaselining all the windows // tests is too much of a pain, so we just check in different baselines. MD5 digester; Vector<uint8_t, 16> digestValue; digester.addBytes(reinterpret_cast<const uint8_t*>(sourceBitmap.getPixels()), sourceBitmap.getSize()); digester.checksum(digestValue); string md5hash; md5hash.reserve(16 * 2); for (unsigned i = 0; i < 16; ++i) { char hex[3]; // Use "x", not "X". The string must be lowercased. sprintf(hex, "%02x", digestValue[i]); md5hash.append(hex); } // Only encode and dump the png if the hashes don't match. Encoding the image // is really expensive. if (md5hash.compare(m_params.pixelHash)) { std::vector<unsigned char> png; webkit_support::EncodeBGRAPNG( reinterpret_cast<const unsigned char*>(sourceBitmap.getPixels()), sourceBitmap.width(), sourceBitmap.height(), static_cast<int>(sourceBitmap.rowBytes()), discardTransparency, &png); m_printer->handleImage(md5hash.c_str(), m_params.pixelHash.c_str(), &png[0], png.size(), m_params.pixelFileName.c_str()); } else m_printer->handleImage(md5hash.c_str(), m_params.pixelHash.c_str(), 0, 0, m_params.pixelFileName.c_str()); } void TestShell::bindJSObjectsToWindow(WebFrame* frame) { m_accessibilityController->bindToJavascript(frame, WebString::fromUTF8("accessibilityController")); m_layoutTestController->bindToJavascript(frame, WebString::fromUTF8("layoutTestController")); m_eventSender->bindToJavascript(frame, WebString::fromUTF8("eventSender")); m_plainTextController->bindToJavascript(frame, WebString::fromUTF8("plainText")); m_textInputController->bindToJavascript(frame, WebString::fromUTF8("textInputController")); } WebViewHost* TestShell::createWebView() { return createNewWindow(WebURL()); } WebViewHost* TestShell::createNewWindow(const WebURL& url) { WebViewHost* host = new WebViewHost(this); WebView* view = WebView::create(host, m_drtDevToolsAgent.get()); host->setWebWidget(view); resetWebSettings(*view); view->initializeMainFrame(host); m_windowList.append(host); host->loadURLForFrame(url, WebString()); return host; } void TestShell::closeWindow(WebViewHost* window) { size_t i = m_windowList.find(window); if (i == notFound) { ASSERT_NOT_REACHED(); return; } m_windowList.remove(i); if (window->webWidget() == m_focusedWidget) m_focusedWidget = 0; window->webWidget()->close(); delete window; } void TestShell::closeRemainingWindows() { // Iterate through the window list and close everything except the main // ihwindow. We don't want to delete elements as we're iterating, so we copy // to a temp vector first. Vector<WebViewHost*> windowsToDelete; for (unsigned i = 0; i < m_windowList.size(); ++i) { if (m_windowList[i] != webViewHost()) windowsToDelete.append(m_windowList[i]); } ASSERT(windowsToDelete.size() + 1 == m_windowList.size()); for (unsigned i = 0; i < windowsToDelete.size(); ++i) closeWindow(windowsToDelete[i]); ASSERT(m_windowList.size() == 1); } int TestShell::windowCount() { return m_windowList.size(); }
[ [ [ 1, 690 ] ] ]
fbf74ab797fb81f2aebf08341bbe9a45c24999d0
45229380094a0c2b603616e7505cbdc4d89dfaee
/ghmm/ghmmc_clr/Stdafx.cpp
e83823ea3f414c051f5d70d26ffdf85b12deb85f
[]
no_license
xcud/msrds
a71000cc096723272e5ada7229426dee5100406c
04764859c88f5c36a757dbffc105309a27cd9c4d
refs/heads/master
2021-01-10T01:19:35.834296
2011-11-04T09:26:01
2011-11-04T09:26:01
45,697,313
1
2
null
null
null
null
UTF-8
C++
false
false
205
cpp
// stdafx.cpp : source file that includes just the standard includes // ghmmc_clr.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671" ]
[ [ [ 1, 5 ] ] ]
261e6e66257e419536b41179c4adf2c42d5f87e9
011359e589f99ae5fe8271962d447165e9ff7768
/src/burner/Xbox360/localise.cpp
3450c6c79aeab85282e677b92301c50bf4184e18
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
982
cpp
// Language module, added by regret /* changelog: update 2: add string cache update 1: create */ #include "burner.h" #define LANG_CACHE 0 bool bLanguageActive = false; TCHAR szLanguage[MAX_PATH] = _T(""); HMODULE hLanguage = NULL; #if LANG_CACHE map<int, tstring> stringMap; #endif int FBALoadString(UINT id, LPTSTR buffer, int maxsize) { int ret = 0; return ret; } TCHAR* FBALoadStringEx(UINT id, bool translate) { static TCHAR loadstr[2048] = _T(""); return loadstr; } // ---------------------------------------------------------------------------- HMODULE FBALocaliseInstance() { return 0; } void FBALocaliseExit() { bLanguageActive = false; } int FBALocaliseInit(TCHAR* lanaugae) { return 0; } // --------------------------------------------------------------------------- // Dialog box to load language static void localiseMakeOfn() { } int FBALocaliseLoad() { return 0; }
[ [ [ 1, 67 ] ] ]
de25ae4e147f206f21a743c533a6c6ff0506ebcf
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/multi_index/test/test_capacity.cpp
808f68020f8e2159e935eb28ff610fbc5db57974
[ "BSL-1.0" ]
permissive
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,453
cpp
/* Boost.MultiIndex test for capacity memfuns. * * Copyright 2003-2004 Joaquín M López Muñoz. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See http://www.boost.org/libs/multi_index for library home page. */ #include "test_capacity.hpp" #include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */ #include "pre_multi_index.hpp" #include "employee.hpp" #include <boost/test/test_tools.hpp> using namespace boost::multi_index; void test_capacity() { employee_set es; es.insert(employee(0,"Joe",31)); es.insert(employee(1,"Robert",27)); es.insert(employee(2,"John",40)); es.insert(employee(3,"Albert",20)); es.insert(employee(4,"John",57)); BOOST_CHECK(!es.empty()); BOOST_CHECK(es.size()==5); BOOST_CHECK(es.size()<=es.max_size()); es.erase(es.begin()); BOOST_CHECK(get<name>(es).size()==4); es.erase(es.begin()); BOOST_CHECK(!get<as_inserted>(es).empty()); BOOST_CHECK(get<as_inserted>(es).size()==3); BOOST_CHECK(get<as_inserted>(es).size()<=get<as_inserted>(es).max_size()); multi_index_container<int,indexed_by<sequenced<> > > ss; ss.resize(10); BOOST_CHECK(ss.size()==10); BOOST_CHECK(ss.size()<=ss.max_size()); ss.resize(20); BOOST_CHECK(ss.size()==20); ss.resize(5); BOOST_CHECK(ss.size()==5); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 53 ] ] ]
cf35abf2e9c0918009d36a68380a3a230c83bfd5
df238aa31eb8c74e2c208188109813272472beec
/Include/CDataElementFactory.h
7442fad8e95f1dff2c9557493ef4f0f524bba59a
[]
no_license
myme5261314/plugin-system
d3166f36972c73f74768faae00ac9b6e0d58d862
be490acba46c7f0d561adc373acd840201c0570c
refs/heads/master
2020-03-29T20:00:01.155206
2011-06-27T15:23:30
2011-06-27T15:23:30
39,724,191
0
0
null
null
null
null
GB18030
C++
false
false
2,879
h
// Copyright (C) 1991 - 1999 Rational Software Corporation #if defined (_MSC_VER) && (_MSC_VER >= 1000) #pragma once #endif #ifndef _INC_CDATAELEMENTFACTORY_4C5E264903E3_INCLUDED #define _INC_CDATAELEMENTFACTORY_4C5E264903E3_INCLUDED #include "CSingletonTml.h" #include "CDataElement.h" #include "CDataContainer.h" class CDataPlugin; const PLUGIN_GUID PLUGIN_ELEMENT_FACTORY_GUID = "{74974477-6A45-4659-9B7B-CAACFBEB8A99}"; const String PLUGIN_ELEMENT_FACTORY_DISPNAME = "工厂基类"; const String PLUGIN_ELEMENT_FACTORY_DESCRIPTION = "描述: 工厂基类"; //##ModelId=4C5E264903E3 class PLUGIN_EXPORT_CLASS CDataElementFactory : public CFactoryObj<CDataElement> { public: //##ModelId=4DE7365A0009 CDataPlugin *m_dataplugin; //##ModelId=4C5E77A7021D CDataElementFactory(); //##ModelId=4C5E77A7023B virtual ~CDataElementFactory(); // 注册对象(派生类必须调用) //##ModelId=4DE7365A000E virtual bool RegisterObject(CDataPlugin *p=NULL); // Returns the factory Guid. //##ModelId=4DE7365A0019 virtual const PLUGIN_GUID& GetGuid() const { return PLUGIN_ELEMENT_FACTORY_GUID; } // 返回工厂的显示名称. //##ModelId=4DE7365A001E virtual const String& GetDispName() const { return PLUGIN_ELEMENT_FACTORY_DISPNAME; } // 返回工厂的描述信息. //##ModelId=4DE7365A0024 virtual const String& GetDescription() const { return PLUGIN_ELEMENT_FACTORY_DESCRIPTION; } // Creates a new object. //##ModelId=4DE7365A002A virtual CDataElement* CreateInstance( const String& InstanceName, bool IsContainer) { // CDataElement *pElement=NULL; // // if(IsContainer) //容器. // { // CDataContainer *pContainer = new CDataContainer(InstanceName); // if(!pContainer) return NULL; // pContainer->SetGuid(PLUGIN_ELEMENT_GUID); // pElement=static_cast<CDataElement*>(pContainer); // } // else //元素. // { // pElement = new CDataElement(InstanceName); // if(!pElement) return NULL; // pElement->SetGuid(PLUGIN_ELEMENT_GUID); // pElement=static_cast<CDataElement*>(pElement); // } // // pElement->m_pFactory=this; // // pElement->SetFactoryGuid(PLUGIN_ELEMENT_FACTORY_GUID); // return pElement; return NULL; } // Destroys an object which was created by this factory. //##ModelId=4DE7365A003A virtual void DestroyInstance( CDataElement* pDataElement) { if(pDataElement->IsContainer()) { CDataContainer *pDataContainer = (CDataContainer *)pDataElement; if(pDataContainer!=NULL) { delete pDataContainer; pDataContainer=NULL; } } else { CDataElement *pMyElement = (CDataElement *)pDataElement; if(pDataElement!=NULL) { delete pDataElement; pDataElement=NULL; } } } }; #endif /* _INC_CDATAELEMENTFACTORY_4C5E264903E3_INCLUDED */
[ "myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5", "[email protected]" ]
[ [ [ 1, 12 ], [ 14, 17 ], [ 19, 21 ], [ 25, 25 ], [ 27, 29 ], [ 32, 33 ], [ 35, 40 ], [ 42, 47 ], [ 49, 54 ], [ 56, 57 ], [ 80, 82 ], [ 84, 106 ] ], [ [ 13, 13 ], [ 18, 18 ], [ 22, 24 ], [ 26, 26 ], [ 30, 31 ], [ 34, 34 ], [ 41, 41 ], [ 48, 48 ], [ 55, 55 ], [ 58, 79 ], [ 83, 83 ] ] ]
3c865333533b74a9ad520351e7e43b526f3f913a
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.7/cbear.berlios.de/vm/test.cpp
0dba3f0bf46687b4f60661a41466ea84f1455517
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
524
cpp
#include <cbear.berlios.de/vm/commands.hpp> #include <cbear.berlios.de/range/end.hpp> namespace Range = cbear_berlios_de::range; namespace Vm = cbear_berlios_de::vm; Vm::process::result Main(Vm::process &P) { std::cout << "Hello world!" << std::endl; P.code++; return Vm::process::continue_; } Vm::process::value_type Code[] = { { Main }, { Main }, { Main }, { Vm::stop }, }; Vm::process::value_type Stack[10]; int main() { Vm::process P(Code, Stack, Range::end(Stack)); P.run(); }
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 28 ] ] ]
3dbe639401bb4bfbc63940bea22b733bb0935eaf
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Include/Nuclex/Video/Blit.h
cd2b82012bd162016b0e75b971da7918ef2928df
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
14,161
h
//  // // # # ### # # -= Nuclex Library =-  // // ## # # # ## ## Blit.h - Software blitting routines  // // ### # # ###  // // # ### # ### Blitting routines for copying or alpha-blending surfaces  // // # ## # # ## ## onto other surface  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #ifndef NUCLEX_VIDEO_BLIT_H #define NUCLEX_VIDEO_BLIT_H #include "Nuclex/Video/PixelFormat.h" #include "Nuclex/Math/Point2.h" namespace Nuclex { namespace Video { //  // //  Nuclex::Video::Blit  // //  // /// Blit memory block /** Performs a blit, optionally including color conversion, alpha blending from alpha value and/or alpha channel. The best blitting solution is statically chosen by a compile-time solvable call graph of template method. */ template< typename DestinationPixelFormatDescription, typename SourcePixelFormatDescription, bool bAlphaBlend > struct Blit { /// Blit source to destination with optional alpha blending /** With alpha blending: Blends source onto dest by source alpha Without alpha blending: Copies source to dest */ inline void operator ()(void *pDestination, long nDestinationPitch, const void *pSource, long nSourcePitch, const Point2<unsigned long> &Size) { blit<bAlphaBlend>( reinterpret_cast<unsigned char *>(pDestination), nDestinationPitch, reinterpret_cast<const unsigned char *>(pSource), nSourcePitch, Size ); } /// Alpha blit source to destination with optional alpha blending /** With alpha blending: Blends source onto dest by (source alpha x cAlpha) Without alpha blending: Copies source to dest, sets dest alpha to cAlpha */ inline void operator ()(void *pDestination, long nDestinationPitch, const void *pSource, long nSourcePitch, const Point2<unsigned long> &Size, unsigned char cAlpha) { blit<bAlphaBlend>( reinterpret_cast<unsigned char *>(pDestination), nDestinationPitch, reinterpret_cast<const unsigned char *>(pSource), nSourcePitch, Size, cAlpha ); } private: static inline typename DestinationPixelFormatDescription::PixelType convertAdjustAlpha( typename SourcePixelFormatDescription::PixelType Pixel ) { return convertAdjustAlpha( Pixel, Bool2Type< (sizeof(SourcePixelFormatDescription::PixelType) > sizeof(DestinationPixelFormatDescription::PixelType)) >() ); } // Required to let the ColorChannelConverter use the larger of two pixel types static inline typename DestinationPixelFormatDescription::PixelType convertAdjustAlpha( typename SourcePixelFormatDescription::PixelType Pixel, Bool2Type<true> ) { return static_cast<PixelType>( ColorChannelConverter<SourcePixelFormatDescription::PixelType, DestinationPixelFormatDescription::Red, SourcePixelFormatDescription::Red>()(Pixel) | ColorChannelConverter<SourcePixelFormatDescription::PixelType, DestinationPixelFormatDescription::Green, SourcePixelFormatDescription::Green>()(Pixel) | ColorChannelConverter<SourcePixelFormatDescription::PixelType, DestinationPixelFormatDescription::Blue, SourcePixelFormatDescription::Blue>()(Pixel) | ColorChannelConverter<SourcePixelFormatDescription::PixelType, DestinationPixelFormatDescription::Alpha, SourcePixelFormatDescription::Alpha>()(Pixel) ); } static inline typename DestinationPixelFormatDescription::PixelType convertAdjustAlpha( typename SourcePixelFormatDescription::PixelType Pixel, Bool2Type<false> ) { return ColorChannelConverter<DestinationPixelFormatDescription::PixelType, DestinationPixelFormatDescription::Red, SourcePixelFormatDescription::Red>()(Pixel) | ColorChannelConverter<DestinationPixelFormatDescription::PixelType, DestinationPixelFormatDescription::Green, SourcePixelFormatDescription::Green>()(Pixel) | ColorChannelConverter<DestinationPixelFormatDescription::PixelType, DestinationPixelFormatDescription::Blue, SourcePixelFormatDescription::Blue>()(Pixel) | ColorChannelConverter<DestinationPixelFormatDescription::PixelType, DestinationPixelFormatDescription::Alpha, SourcePixelFormatDescription::Alpha>()(Pixel); } template<bool bAlphaBlend> inline void blit(unsigned char *pDestination, long nDestinationPitch, const unsigned char *pSource, long nSourcePitch, const Point2<unsigned long> &Size); /// Alpha blended blit with optional pixel format conversion template<> inline void blit<true>(unsigned char *pDestination, long nDestinationPitch, const unsigned char *pSource, long nSourcePitch, const Point2<unsigned long> &Size) { // dest = source + (dest - source) * source.a // Uses non-alpha blit() if no alpha channel in source blend( pDestination, nDestinationPitch, pSource, nSourcePitch, Size, Bool2Type<SourcePixelFormatDescription::HasAlphaChannel>() ); } /// Blit with optional pixel format conversion template<> inline void blit<false>(unsigned char *pDestination, long nDestinationPitch, const unsigned char *pSource, long nSourcePitch, const Point2<unsigned long> &Size) { // dest = source // Uses memcpy() if both pixel formats are identical copy( pDestination, nDestinationPitch, pSource, nSourcePitch, Size, DestinationPixelFormatDescription(), SourcePixelFormatDescription() ); } template<bool bAlphablend> inline void blit(unsigned char *pDestination, long nDestinationPitch, const unsigned char *pSource, long nSourcePitch, const Point2<unsigned long> &Size, unsigned char cAlpha); /// Alpha blended alpha blit with optional pixel format conversion template<> inline void blit<true>(unsigned char *pDestination, long nDestinationPitch, const unsigned char *pSource, long nSourcePitch, const Point2<unsigned long> &Size, unsigned char cAlpha) { // dest = source + (dest - source) * (cAlpha * source.a) long nSourceLineAdd = nSourcePitch - (Size.X * SourcePixelFormatDescription::BytesPerPixel); long nDestinationLineAdd = nDestinationPitch - (Size.X * DestinationPixelFormatDescription::BytesPerPixel); for(unsigned long nY = 0; nY < Size.Y; ++nY) { for(unsigned long nX = 0; nX < Size.X; ++nX) { WritePixel<DestinationPixelFormatDescription>()( pDestination, AlphaBlend< DestinationPixelFormatDescription, SourcePixelFormatDescription, SourcePixelFormatDescription::Alpha::Bits::Count, 8 >(ReadPixel<SourcePixelFormatDescription>()(pSource))( ReadPixel<DestinationPixelFormatDescription>()(pDestination), static_cast<unsigned char>( (ReadPixel<SourcePixelFormatDescription>()(pSource) & SourcePixelFormatDescription::Alpha::Bits::Mask) >> SourcePixelFormatDescription::Alpha::Bits::First ), cAlpha ) ); pSource += SourcePixelFormatDescription::BytesPerPixel; pDestination += DestinationPixelFormatDescription::BytesPerPixel; } pSource += nSourceLineAdd; pDestination += nDestinationLineAdd; } } /// Alpha blit with optional pixel format conversion template<> inline void blit<false>(unsigned char *pDestination, long nDestinationPitch, const unsigned char *pSource, long nSourcePitch, const Point2<unsigned long> &Size, unsigned char cAlpha) { // dest = source; dest.a = source.a * cAlpha long nSourceLineAdd = nSourcePitch - (Size.X * SourcePixelFormatDescription::BytesPerPixel); long nDestinationLineAdd = nDestinationPitch - (Size.X * DestinationPixelFormatDescription::BytesPerPixel); for(unsigned long nY = 0; nY < Size.Y; ++nY) { for(unsigned long nX = 0; nX < Size.X; ++nX) { DestinationPixelFormatDescription::PixelType Pixel = DestinationPixelFormatDescription::convertFrom<SourcePixelFormatDescription>( ReadPixel<SourcePixelFormatDescription>()(pSource) ); NativeType Alpha = (Pixel & DestinationPixelFormatDescription::Alpha::Bits::Mask) >> DestinationPixelFormatDescription::Alpha::Bits::First; Pixel = static_cast<DestinationPixelFormatDescription::PixelType>( (Pixel & ~DestinationPixelFormatDescription::Alpha::Bits::Mask) | (Shift< NativeType, 8 - DestinationPixelFormatDescription::Alpha::Bits::First >()(Alpha * cAlpha) & DestinationPixelFormatDescription::Alpha::Bits::Mask) ); WritePixel<DestinationPixelFormatDescription>()( pDestination, Pixel ); pSource += SourcePixelFormatDescription::BytesPerPixel; pDestination += DestinationPixelFormatDescription::BytesPerPixel; } pSource += nSourceLineAdd; pDestination += nDestinationLineAdd; } } /// Alpha blended blit inline void blend(unsigned char *pDestination, long nDestinationPitch, const unsigned char *pSource, long nSourcePitch, const Point2<unsigned long> &Size, Bool2Type<true>) { long nSourceLineAdd = nSourcePitch - (Size.X * SourcePixelFormatDescription::BytesPerPixel); long nDestinationLineAdd = nDestinationPitch - (Size.X * DestinationPixelFormatDescription::BytesPerPixel); for(unsigned long nY = 0; nY < Size.Y; ++nY) { for(unsigned long nX = 0; nX < Size.X; ++nX) { WritePixel<DestinationPixelFormatDescription>()( pDestination, AlphaBlend< DestinationPixelFormatDescription, SourcePixelFormatDescription, SourcePixelFormatDescription::Alpha::Bits::Count >(ReadPixel<SourcePixelFormatDescription>()(pSource))( ReadPixel<DestinationPixelFormatDescription>()(pDestination), static_cast<unsigned char>( (ReadPixel<SourcePixelFormatDescription>()(pSource) & SourcePixelFormatDescription::Alpha::Bits::Mask) >> SourcePixelFormatDescription::Alpha::Bits::First ) ) ); pSource += SourcePixelFormatDescription::BytesPerPixel; pDestination += DestinationPixelFormatDescription::BytesPerPixel; } pSource += nSourceLineAdd; pDestination += nDestinationLineAdd; } } /// Alpha blended blit inline void blend(unsigned char *pDestination, long nDestinationPitch, const unsigned char *pSource, long nSourcePitch, const Point2<unsigned long> &Size, Bool2Type<false>) { blit<false>( pDestination, nDestinationPitch, pSource, nSourcePitch, Size ); } /// Blit with color conversion template<typename A, typename B> inline void copy(unsigned char *pDestination, long nDestinationPitch, const unsigned char *pSource, long nSourcePitch, const Point2<unsigned long> &Size, A, B) { long nSourceLineAdd = nSourcePitch - (Size.X * SourcePixelFormatDescription::BytesPerPixel); long nDestinationLineAdd = nDestinationPitch - (Size.X * DestinationPixelFormatDescription::BytesPerPixel); for(unsigned long nY = 0; nY < Size.Y; ++nY) { for(unsigned long nX = 0; nX < Size.X; ++nX) { WritePixel<DestinationPixelFormatDescription>()( pDestination, DestinationPixelFormatDescription::convertFrom<SourcePixelFormatDescription>( ReadPixel<SourcePixelFormatDescription>()(pSource) ) ); pSource += SourcePixelFormatDescription::BytesPerPixel; pDestination += DestinationPixelFormatDescription::BytesPerPixel; } pSource += nSourceLineAdd; pDestination += nDestinationLineAdd; } } /// Blit without color conversion template<typename A> inline void copy(unsigned char *pDestination, long nDestinationPitch, const unsigned char *pSource, long nSourcePitch, const Point2<unsigned long> &Size, A, A) { for(unsigned long nY = 0; nY < Size.Y; ++nY) { memcpy(pDestination, pSource, DestinationPixelFormatDescription::BytesPerPixel * Size.X); pSource += nSourcePitch; pDestination += nDestinationPitch; } } }; }} // namespace Nuclex::Video #endif // NUCLEX_VIDEO_BLIT_H
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 294 ] ] ]
4a805ab29f7643b81c2c280dd3e0b2b0d9abba42
0c5fd443401312fafae18ea6a9d17bac9ee61474
/code/engine/View/CameraCreation.h
b7329450c7e0728a20321a3211a6d29d9fe95a90
[]
no_license
nurF/Brute-Force-Game-Engine
fcfebc997d6ab487508a5706b849e9d7bc66792d
b930472429ec6d6f691230e36076cd2c868d853d
refs/heads/master
2021-01-18T09:29:44.038036
2011-12-02T17:31:59
2011-12-02T17:31:59
2,877,061
1
0
null
null
null
null
UTF-8
C++
false
false
1,764
h
/* ___ _________ ____ __ / _ )/ __/ ___/____/ __/___ ___ _/_/___ ___ / _ / _// (_ //___/ _/ / _ | _ `/ // _ | -_) /____/_/ \___/ /___//_//_|_, /_//_//_|__/ /___/ This file is part of the Brute-Force Game Engine, BFG-Engine For the latest info, see http://www.brute-force-games.com Copyright (c) 2011 Brute-Force Games GbR The BFG-Engine 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. The BFG-Engine 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 the BFG-Engine. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BFG_VIEW_CAMERACREATION_H #define BFG_VIEW_CAMERACREATION_H #include <boost/array.hpp> #include <Core/Types.h> #include <View/Enums.hh> namespace BFG { namespace View { struct VIEW_API CameraCreation { CameraCreation(GameHandle handle, GameHandle nodeHandle, bool fullscreen, s32 width, s32 height) : mHandle(handle), mNodeHandle(nodeHandle), mFullscreen(fullscreen), mWidth(width), mHeight(height){} GameHandle mHandle; GameHandle mNodeHandle; bool mFullscreen; s32 mWidth; s32 mHeight; }; } // namespace View } // namespace BFG #endif
[ [ [ 1, 63 ] ] ]
722e4f11a906afe83ef2073fa2b0aafacc125cb4
7209e143b701bf83b10f09f334ea7bf7b08d790b
/src/oflag.cpp
f9981cf959861b565c87889a349d64b6ea5a3eab
[]
no_license
sebhd/zod
755356b11efb2c7cd861b04e09ccf5ba1ec7ac2e
396e2231334af7eada1b41af5aaff065b6235e94
refs/heads/master
2018-12-28T09:04:04.762895
2011-09-30T08:48:16
2011-09-30T08:48:16
2,469,497
5
0
null
null
null
null
UTF-8
C++
false
false
2,823
cpp
#include "oflag.h" ZSDL_Surface OFlag::flag_img[MAX_TEAM_TYPES][4]; OFlag::OFlag(ZTime *ztime_, ZSettings *zsettings_) : ZObject(ztime_, zsettings_) { width = 1; height = 1; width_pix = width * 16; height_pix = height * 16; object_name = "flag"; m_object_type = MAP_ITEM_OBJECT; m_object_id = FLAG_ITEM; can_be_destroyed = false; connected_zone = NULL; flag_i = rand() % 4; } void OFlag::Init() { int i, j; char filename_c[500]; //load colors for (i = 0; i < MAX_TEAM_TYPES; i++) for (j = 0; j < 4; j++) { sprintf(filename_c, "assets/other/flag_%s_%d.png", team_type_string[i].c_str(), j); //flag_img[i][j].LoadBaseImage(filename_c);// = IMG_Load_Error(filename_c); ZTeam::LoadZSurface(i, flag_img[ZTEAM_BASE_TEAM][j], flag_img[i][j], filename_c); } } int OFlag::Process() { double &the_time = ztime->ztime; const double int_time = 0.2; if (the_time - last_process_time >= int_time) { last_process_time = the_time; flag_i++; if (flag_i > 3) flag_i = 0; } return 1; } void OFlag::DoRender(ZMap &the_map, SDL_Surface *dest, int shift_x, int shift_y) { int &x = loc.x; int &y = loc.y; ZSDL_Surface *base_surface; SDL_Rect from_rect, to_rect; int lx, ly; base_surface = &flag_img[owner][flag_i]; if (the_map.GetBlitInfo(base_surface->GetBaseSurface(), x, y, from_rect, to_rect)) { to_rect.x += shift_x; to_rect.y += shift_y; base_surface->BlitSurface(&from_rect, &to_rect); //SDL_BlitSurface( base_surface, &from_rect, dest, &to_rect); } } void OFlag::SetZone(map_zone_info *the_zone, ZMap &zmap, vector<ZObject*> &oobject_list) { connected_zone = the_zone; the_zone->owner = owner; connected_object_list.clear(); //connect to buildings //and set their initial owner for (vector<ZObject*>::iterator i = oobject_list.begin(); i != oobject_list.end(); i++) { unsigned char object_type; unsigned char object_id; int ox, oy; (*i)->GetObjectID(object_type, object_id); (*i)->GetCords(ox, oy); //is this a fort, then just set the zone to the forts owner if (object_type == BUILDING_OBJECT) if (connected_zone == zmap.GetZone(ox, oy)) { connected_object_list.push_back(*i); (*i)->SetOwner(owner); } } } vector<ZObject*> &OFlag::GetLinkedObjects() { return connected_object_list; } map_zone_info *OFlag::GetLinkedZone() { return connected_zone; } bool OFlag::HasRadar() { for (vector<ZObject*>::iterator i = connected_object_list.begin(); i != connected_object_list.end(); i++) { unsigned char ot, oid; (*i)->GetObjectID(ot, oid); if (ot == BUILDING_OBJECT && oid == RADAR) return true; } return false; } // SDL_Surface *OFlag::GetRender() // { // return flag_img[owner][flag_i]; // }
[ "sebastian@T61p" ]
[ [ [ 1, 116 ] ] ]
7a300b1090f282838f9db05a73e0fac7e6341277
46885801c2459416e82517f93b7d452d78b33aff
/source/engine.cpp
188d4b4adb5950e101e4c8835ae843b95b71e7a2
[]
no_license
libercv/smallengine
aabe92d4743789e8eab4a65d86d5a838ddc2aded
c1645fb99db213b419a81d4815a6645e1be89fe9
refs/heads/master
2021-01-10T08:09:05.991405
2009-04-01T14:52:59
2009-04-01T14:52:59
36,439,082
0
0
null
null
null
null
UTF-8
C++
false
false
1,708
cpp
#include "engine.h" #include "script/script.h" namespace Small { void Engine::Run(void) { // PENDIENTE: Implementar métodos init para todos los singleton. // PENDIENTE: Llamar desde aquí a todos los Inits de forma lógica y ordenada. Level = 1; // PENDIENTE: si en fullscreen indicamos una resolución que no se puede activar -> excepcion Window::Instance().Open("Small Project", 0, 0, 1024, 768, 32, true); StateGame::Instance().LoadLevel("level001.xml"); Script::Instance(); // PENDIENTE: ñapa para forzar la inicialización. while( CurrentState != Done ) { Timer::Instance().Update(); Input::Instance().Update(); Window::Instance().Update(); SoundManager::Instance().Update(); // PENDIENTE: UpdateEvents se supone que era el que generaba los eventos en LUA // para que el código no estuviese por ahí disperso. Revisar la idea. //System::Instance().UpdateEvents(); switch( CurrentState ) { case Menu: CurrentState = StateMenu::Instance().Update(Timer::Instance().GetElapsedTime()); StateMenu::Instance().Render(); break; case NextLevel: if( ++Level > 2 ) Level = 1; switch( Level ) { case 2: StateGame::Instance().LoadLevel("level002.xml"); StateGame::Instance().CrearBolitas(); break; default: StateGame::Instance().LoadLevel("level001.xml"); break; } CurrentState = Game; break; case Game: case Pause: CurrentState = StateGame::Instance().Update(Timer::Instance().GetElapsedTime()); StateGame::Instance().Render(); break; } Window::Instance().Refresh(); } } } // namespace Small
[ "daviddq@3342a6a6-5e2d-0410-95e1-bf50fdd259a6" ]
[ [ [ 1, 67 ] ] ]
f2506cba0e404c415ba01f6337ff9f2b42bf2474
b2b5c3694476d1631322a340c6ad9e5a9ec43688
/Baluchon/MarkerFactory.cpp
37c97fd2de29c82db411e0acc72c814936de264d
[]
no_license
jpmn/rough-albatross
3c456ea23158e749b029b2112b2f82a7a5d1fb2b
eb2951062f6c954814f064a28ad7c7a4e7cc35b0
refs/heads/master
2016-09-05T12:18:01.227974
2010-12-19T08:03:25
2010-12-19T08:03:25
32,195,707
1
0
null
null
null
null
UTF-8
C++
false
false
495
cpp
#include "MarkerFactory.h" namespace baluchon { namespace core { namespace services { namespace colordetection { MarkerFactory::MarkerFactory(void) { } MarkerFactory::~MarkerFactory(void) { } ColoredMarker* MarkerFactory::createColoredMarker(CvSeq* contours, CvScalar color, int tolerance) { ColoredMarker* marker = new ColoredMarker(); { marker->setContours(contours); marker->setColor(color); marker->setTolerance(tolerance); } return marker; } }}}};
[ "jpmorin196@bd4f47a5-da4e-a94a-6a47-2669d62bc1a5" ]
[ [ [ 1, 25 ] ] ]
f12d1745558d032550bc02b40ff85ecf1c83f926
ce1b0d027c41f70bc4cfa13cb05f09bd4edaf6a2
/ edge2d --username [email protected]/include/helper/EdgeFadeImage.h
cf4d62ecfebf657a5f4058b9cd4504f41dc4e41e
[]
no_license
ratalaika/edge2d
11189c41b166960d5d7d5dbcf9bfaf833a41c079
79470a0fa6e8f5ea255df1696da655145bbf83ff
refs/heads/master
2021-01-10T04:59:22.495428
2010-02-19T13:45:03
2010-02-19T13:45:03
36,088,756
1
0
null
null
null
null
UTF-8
C++
false
false
1,896
h
/* ----------------------------------------------------------------------------- This source file is part of EDGE (A very object-oriented and plugin-based 2d game engine) For the latest info, see http://edge2d.googlecode.com Copyright (c) 2007-2008 The EDGE Team Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef EDGE_FADE_IMAGE_H_ #define EDGE_FADE_IMAGE_H_ namespace Edge { class Image; /** * FadeImage * * implements an effect that will fade out an image and later fade it out */ class FadeImage { public: enum { FADE_OUT, FADE_IN, STAY, FINISHED }; public: FadeImage( Edge::Image *texture, float x, float y, float speed, float delayTime ); virtual ~FadeImage(); virtual bool update( float dt ); virtual void render(); virtual void reset(); int getState() { return mState; } protected: Edge::Image *mTexture; float mX, mY; float mSpeed; float mAlpha; int mState; float mStayTime; float mDelayTime; }; } #endif //end _FADE_IMAGE_H_
[ "[email protected]@539dfdeb-0f3d-0410-9ace-d34ff1985647" ]
[ [ [ 1, 67 ] ] ]
e5faec67ab6b2163dbbbbd57e590d62e4096998c
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/src/pthread_mutex_unlock.cpp
f53d5747f0aef9aecd65c438b052728fe0f40693
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
2,217
cpp
/* * Copyright (c) 2005-2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: POSIX implementation of mutexes on Symbian * */ #include "mutextypes.h" EXPORT_C int pthread_mutex_unlock (pthread_mutex_t * mutex) { if( !VALID_MUTEX(mutex) ) { return EINVAL; } _pthread_mutex_t* pMutex = mutex->iPtr; pthread_t self; int retval = 0; pMutex->iDataLock.Wait(); if(mutex->iState == _EDestroyed) { return EINVAL; } switch(pMutex->iMutexType) { case PTHREAD_MUTEX_NORMAL: { if(pMutex->iCount == 1) { pMutex->iCount = 0; pMutex->iSignalSemaphore.Signal(); } break; } case PTHREAD_MUTEX_RECURSIVE: { self = pthread_self(); if(pMutex->iLockingThread == self) { pMutex->iCount--; if(pMutex->iCount == 0) { pMutex->iLockingThread = 0; pMutex->iSignalSemaphore.Signal(); } } else { retval = EPERM; } break; } case PTHREAD_MUTEX_ERRORCHECK: { self = pthread_self(); if( (pMutex->iLockingThread != self) || (pMutex->iCount != 1) ) { retval = EPERM; break; } pMutex->iCount = 0; pMutex->iLockingThread = 0; pMutex->iSignalSemaphore.Signal(); break; } default: retval = ENOSYS; break; } //switch pMutex->iDataLock.Signal(); return retval; } // End of File
[ "none@none" ]
[ [ [ 1, 93 ] ] ]
b80cca63805dc4e6659a722fa4ad4fdd80e01c3f
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit2/WebProcess/WebCoreSupport/WebPopupMenu.cpp
9ebc2f6e6916b895e1199b753989dca76a007c33
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,609
cpp
/* * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * Copyright (C) 2010 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "WebPopupMenu.h" #include <WebCore/FrameView.h> #include <WebCore/PopupMenuClient.h> namespace WebKit { PassRefPtr<WebPopupMenu> WebPopupMenu::create(WebCore::PopupMenuClient* client) { return adoptRef(new WebPopupMenu(client)); } WebPopupMenu::WebPopupMenu(WebCore::PopupMenuClient* client) : m_popupClient(client) { } WebPopupMenu::~WebPopupMenu() { } void WebPopupMenu::disconnectClient() { m_popupClient = 0; } void WebPopupMenu::show(const WebCore::IntRect& rect, WebCore::FrameView* view, int index) { } void WebPopupMenu::hide() { } void WebPopupMenu::updateFromElement() { } } // namespace WebKit
[ [ [ 1, 62 ] ] ]
08603b0bc4c081af80ce771626c060f0bb4c03a2
48ab31a0a6a8605d57b5e140309c910f46eb5b35
/Root/Support/DatabaseLocation.h
5f4333cf38e4e63ababa53d477f847af4354257e
[]
no_license
firebreath/indexeddb
4c3106027a70e233eb0f91c6e0b5d60847d75800
50136d2fadced369788a42d249157b8a0d06eb88
refs/heads/master
2023-08-31T11:28:42.664028
2011-01-03T23:29:46
2011-01-03T23:29:46
1,218,008
2
1
null
null
null
null
UTF-8
C++
false
false
1,784
h
/**********************************************************\ Copyright Brandon Haynes http://code.google.com/p/indexeddb GNU Lesser General Public License \**********************************************************/ #ifndef BRANDONHAYNES_INDEXEDDB_SUPPORT_DATABASELOCATION_H #define BRANDONHAYNES_INDEXEDDB_SUPPORT_DATABASELOCATION_H #include <string> #include <boost/filesystem.hpp> namespace BrandonHaynes { namespace IndexedDB { namespace Implementation { ///<summary> /// This utility class is used to retreive operating system-specific paths for implementations. It was /// designed with Berkeley DB in mind, but is probably useful across other environments. ///</summary> class DatabaseLocation { public: // Gets a valid database storage path for this origin, specific to a given user (via an environment variable) static const std::string getDatabasePath(const std::string& origin, const std::string& databaseName); // Gets a valid object storage path for this origin, specific to a given user (and underneath the database path) static const std::string getObjectStorePath(const std::string& origin, const std::string& databaseName, const std::string& objectStoreName); // Given a path, performs some sanity checks on it to ensure that there is no cross-origin or naming issues static void ensurePathValid(const std::string& path); private: DatabaseLocation() { } // Stores a reference to the user-specific home static ::boost::filesystem::path userHome; // Stores a relative reference to the database path static ::boost::filesystem::path databaseHome; // A set of invalid filename characters specific to "this" operating system static const char* illegalFilenameCharacters; }; } } } #endif
[ [ [ 1, 46 ] ] ]
82de5ee29f20162471b1a0b081092561fe248cd1
f13f46fbe8535a7573d0f399449c230a35cd2014
/JelloMan/Effect.h
b6f68bb901417f9f6feddf3f8efa21836b0b14eb
[]
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
1,677
h
#pragma once #include "D3DUtil.h" #include "vertex.h" class Effect { public: //---------Constructor-&-Destructor-------------------------> Effect(ID3D10Device* graphicsDevice, ID3D10Effect* effect); virtual ~Effect(void); //<---------------------------------------------------------- void SetTechnique(int index); void SetTechnique(const string& name); ID3D10EffectTechnique* GetCurrentTechnique() { return m_pCurrentTechnique; } virtual ID3D10InputLayout* GetInputLayout() const = 0; virtual UINT GetVertexStride() const = 0; UINT GetNumPasses() const; ID3D10EffectVariable* GetVariableByName(const string& name) const; ID3D10EffectVariable* GetVariableBySemantic(const string& semantic) const; protected: ID3D10Device* m_pDevice; ID3D10Effect* m_pEffect; ID3D10EffectTechnique* m_pCurrentTechnique; UINT m_NumPasses; private: Effect(const Effect& effect); Effect& operator=(const Effect& effect); }; template <typename T> void CreateInputLayout(ID3D10Device* pDXDevice, Effect* pEffect, ID3D10InputLayout** ppInputLayout, UINT& vertexStride, bool useForInstancing = false) { SafeRelease(*ppInputLayout); // Define the input layout vector<D3D10_INPUT_ELEMENT_DESC> veclayout; UINT numElements; GetInputElementDesc<T>(veclayout, numElements, useForInstancing); D3D10_PASS_DESC passDesc; pEffect->GetCurrentTechnique()->GetPassByIndex(0)->GetDesc(&passDesc); HR(pDXDevice->CreateInputLayout(&veclayout[0], numElements, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, ppInputLayout)); vertexStride = sizeof(T); }
[ "bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6" ]
[ [ [ 1, 52 ] ] ]
3a625c3ad6bbaf43d6995e725a856977f1758f04
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/ModelEditor/AnimSliderCtrl.h
3b2fd600aef320d38834a74c9ca269cf393970d8
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
470
h
#pragma once // CAnimSliderCtrl class CAnimSliderCtrl : public CSliderCtrl { DECLARE_DYNAMIC(CAnimSliderCtrl) public: CAnimSliderCtrl(); virtual ~CAnimSliderCtrl(); protected: DECLARE_MESSAGE_MAP() public: CBrush m_brush; CPen m_pen; protected: virtual void PreSubclassWindow(); public: afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct); afx_msg void OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult); };
[ [ [ 1, 28 ] ] ]
96b4c88dd6dd3005a7e7e1ffb5ec0b7015b99704
507d163c440f53e050b7ce52f3454220af178c65
/data/connecteur.cpp
467cc729154d64eb105c7127dc8df41292d2999c
[]
no_license
BackupTheBerlios/facompt-svn
6d1afce300d28ede03d3780f7a91d333da03db90
a36091aa7800773a2e8d74ee99413bfffe38b635
refs/heads/master
2016-09-06T01:03:18.612873
2004-10-03T03:00:44
2004-10-03T03:00:44
40,601,198
0
0
null
null
null
null
UTF-8
C++
false
false
581
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "connecteur.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TconnecteurDonnees *connecteurDonnees; //--------------------------------------------------------------------------- __fastcall TconnecteurDonnees::TconnecteurDonnees(TComponent* Owner) : TDataModule(Owner) { } //---------------------------------------------------------------------------
[ "perceval33@5653c88f-94df-0310-8653-d071935d23bc" ]
[ [ [ 1, 16 ] ] ]
f528adfa96a6c3eec0deccc8b622f5e7a438918f
a2904986c09bd07e8c89359632e849534970c1be
/topcoder/RugSizes.cpp
85f1dbaf2ef768d90409f879c82ddfb5bf625f47
[]
no_license
naturalself/topcoder_srms
20bf84ac1fd959e9fbbf8b82a93113c858bf6134
7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5
refs/heads/master
2021-01-22T04:36:40.592620
2010-11-29T17:30:40
2010-11-29T17:30:40
444,669
1
0
null
null
null
null
UTF-8
C++
false
false
4,203
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "RugSizes.cpp" #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> using namespace std; #define debug(p) cout << #p << "=" << p << endl; #define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i) #define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i) #define all(a) a.begin(), a.end() #define pb push_back class RugSizes { public: int rugCount(int area) { int ret=0; for(int i=1;i<=area;i++){ if(area%i==0){ int j = area/i; if(i > j) break; if((i != j) && (i%2==0) && (j%2==0)){ }else{ ret++; } } } return ret; } }; // BEGIN CUT HERE namespace moj_harness { int run_test_case(int); void run_test(int casenum = -1, bool quiet = false) { if (casenum != -1) { if (run_test_case(casenum) == -1 && !quiet) { cerr << "Illegal input! Test case " << casenum << " does not exist." << endl; } return; } int correct = 0, total = 0; for (int i=0;; ++i) { int x = run_test_case(i); if (x == -1) { if (i >= 100) break; continue; } correct += x; ++total; } if (total == 0) { cerr << "No test cases run." << endl; } else if (correct < total) { cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl; } else { cerr << "All " << total << " tests passed!" << endl; } } int verify_case(int casenum, const int &expected, const int &received, clock_t elapsed) { cerr << "Example " << casenum << "... "; string verdict; vector<string> info; char buf[100]; if (elapsed > CLOCKS_PER_SEC / 200) { sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC)); info.push_back(buf); } if (expected == received) { verdict = "PASSED"; } else { verdict = "FAILED"; } cerr << verdict; if (!info.empty()) { cerr << " ("; for (int i=0; i<(int)info.size(); ++i) { if (i > 0) cerr << ", "; cerr << info[i]; } cerr << ")"; } cerr << endl; if (verdict == "FAILED") { cerr << " Expected: " << expected << endl; cerr << " Received: " << received << endl; } return verdict == "PASSED"; } int run_test_case(int casenum) { switch (casenum) { case 0: { int area = 4; int expected__ = 2; clock_t start__ = clock(); int received__ = RugSizes().rugCount(area); return verify_case(casenum, expected__, received__, clock()-start__); } case 1: { int area = 8; int expected__ = 1; clock_t start__ = clock(); int received__ = RugSizes().rugCount(area); return verify_case(casenum, expected__, received__, clock()-start__); } // custom cases case 2: { int area = 98415; int expected__ = 10; clock_t start__ = clock(); int received__ = RugSizes().rugCount(area); return verify_case(casenum, expected__, received__, clock()-start__); } case 3: { int area = 99997; int expected__ = 3; clock_t start__ = clock(); int received__ = RugSizes().rugCount(area); return verify_case(casenum, expected__, received__, clock()-start__); } case 4: { int area = 1; int expected__ = 1; clock_t start__ = clock(); int received__ = RugSizes().rugCount(area); return verify_case(casenum, expected__, received__, clock()-start__); } default: return -1; } } } int main(int argc, char *argv[]) { if (argc == 1) { moj_harness::run_test(); } else { for (int i=1; i<argc; ++i) moj_harness::run_test(atoi(argv[i])); } } // END CUT HERE
[ "shin@CF-7AUJ41TT52JO.(none)" ]
[ [ [ 1, 183 ] ] ]
1e86b6b3ce09f24dc3d4b781d7b4e90f359544ec
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/QtGui/qgraphicssceneevent.h
9b2d99e9adcc68ba801bea3ebe37b8024a18ee3a
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,094
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 QGRAPHICSSCENEEVENT_H #define QGRAPHICSSCENEEVENT_H #include <QtCore/qcoreevent.h> #include <QtCore/qpoint.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW class QMimeData; class QPointF; class QSizeF; class QWidget; class QGraphicsSceneEventPrivate; class Q_GUI_EXPORT QGraphicsSceneEvent : public QEvent { public: QGraphicsSceneEvent(Type type); ~QGraphicsSceneEvent(); QWidget *widget() const; void setWidget(QWidget *widget); protected: QGraphicsSceneEvent(QGraphicsSceneEventPrivate &dd, Type type = None); QGraphicsSceneEventPrivate *d_ptr; Q_DECLARE_PRIVATE(QGraphicsSceneEvent) }; class QGraphicsSceneMouseEventPrivate; class Q_GUI_EXPORT QGraphicsSceneMouseEvent : public QGraphicsSceneEvent { public: QGraphicsSceneMouseEvent(Type type = None); ~QGraphicsSceneMouseEvent(); QPointF pos() const; void setPos(const QPointF &pos); QPointF scenePos() const; void setScenePos(const QPointF &pos); QPoint screenPos() const; void setScreenPos(const QPoint &pos); QPointF buttonDownPos(Qt::MouseButton button) const; void setButtonDownPos(Qt::MouseButton button, const QPointF &pos); QPointF buttonDownScenePos(Qt::MouseButton button) const; void setButtonDownScenePos(Qt::MouseButton button, const QPointF &pos); QPoint buttonDownScreenPos(Qt::MouseButton button) const; void setButtonDownScreenPos(Qt::MouseButton button, const QPoint &pos); QPointF lastPos() const; void setLastPos(const QPointF &pos); QPointF lastScenePos() const; void setLastScenePos(const QPointF &pos); QPoint lastScreenPos() const; void setLastScreenPos(const QPoint &pos); Qt::MouseButtons buttons() const; void setButtons(Qt::MouseButtons buttons); Qt::MouseButton button() const; void setButton(Qt::MouseButton button); Qt::KeyboardModifiers modifiers() const; void setModifiers(Qt::KeyboardModifiers modifiers); private: Q_DECLARE_PRIVATE(QGraphicsSceneMouseEvent) }; class QGraphicsSceneWheelEventPrivate; class Q_GUI_EXPORT QGraphicsSceneWheelEvent : public QGraphicsSceneEvent { public: QGraphicsSceneWheelEvent(Type type = None); ~QGraphicsSceneWheelEvent(); QPointF pos() const; void setPos(const QPointF &pos); QPointF scenePos() const; void setScenePos(const QPointF &pos); QPoint screenPos() const; void setScreenPos(const QPoint &pos); Qt::MouseButtons buttons() const; void setButtons(Qt::MouseButtons buttons); Qt::KeyboardModifiers modifiers() const; void setModifiers(Qt::KeyboardModifiers modifiers); int delta() const; void setDelta(int delta); Qt::Orientation orientation() const; void setOrientation(Qt::Orientation orientation); private: Q_DECLARE_PRIVATE(QGraphicsSceneWheelEvent) }; class QGraphicsSceneContextMenuEventPrivate; class Q_GUI_EXPORT QGraphicsSceneContextMenuEvent : public QGraphicsSceneEvent { public: enum Reason { Mouse, Keyboard, Other }; QGraphicsSceneContextMenuEvent(Type type = None); ~QGraphicsSceneContextMenuEvent(); QPointF pos() const; void setPos(const QPointF &pos); QPointF scenePos() const; void setScenePos(const QPointF &pos); QPoint screenPos() const; void setScreenPos(const QPoint &pos); Qt::KeyboardModifiers modifiers() const; void setModifiers(Qt::KeyboardModifiers modifiers); Reason reason() const; void setReason(Reason reason); private: Q_DECLARE_PRIVATE(QGraphicsSceneContextMenuEvent) }; class QGraphicsSceneHoverEventPrivate; class Q_GUI_EXPORT QGraphicsSceneHoverEvent : public QGraphicsSceneEvent { public: QGraphicsSceneHoverEvent(Type type = None); ~QGraphicsSceneHoverEvent(); QPointF pos() const; void setPos(const QPointF &pos); QPointF scenePos() const; void setScenePos(const QPointF &pos); QPoint screenPos() const; void setScreenPos(const QPoint &pos); QPointF lastPos() const; void setLastPos(const QPointF &pos); QPointF lastScenePos() const; void setLastScenePos(const QPointF &pos); QPoint lastScreenPos() const; void setLastScreenPos(const QPoint &pos); Qt::KeyboardModifiers modifiers() const; void setModifiers(Qt::KeyboardModifiers modifiers); private: Q_DECLARE_PRIVATE(QGraphicsSceneHoverEvent) }; class QGraphicsSceneHelpEventPrivate; class Q_GUI_EXPORT QGraphicsSceneHelpEvent : public QGraphicsSceneEvent { public: QGraphicsSceneHelpEvent(Type type = None); ~QGraphicsSceneHelpEvent(); QPointF scenePos() const; void setScenePos(const QPointF &pos); QPoint screenPos() const; void setScreenPos(const QPoint &pos); private: Q_DECLARE_PRIVATE(QGraphicsSceneHelpEvent) }; class QGraphicsSceneDragDropEventPrivate; class Q_GUI_EXPORT QGraphicsSceneDragDropEvent : public QGraphicsSceneEvent { public: QGraphicsSceneDragDropEvent(Type type = None); ~QGraphicsSceneDragDropEvent(); QPointF pos() const; void setPos(const QPointF &pos); QPointF scenePos() const; void setScenePos(const QPointF &pos); QPoint screenPos() const; void setScreenPos(const QPoint &pos); Qt::MouseButtons buttons() const; void setButtons(Qt::MouseButtons buttons); Qt::KeyboardModifiers modifiers() const; void setModifiers(Qt::KeyboardModifiers modifiers); Qt::DropActions possibleActions() const; void setPossibleActions(Qt::DropActions actions); Qt::DropAction proposedAction() const; void setProposedAction(Qt::DropAction action); void acceptProposedAction(); Qt::DropAction dropAction() const; void setDropAction(Qt::DropAction action); QWidget *source() const; void setSource(QWidget *source); const QMimeData *mimeData() const; void setMimeData(const QMimeData *data); private: Q_DECLARE_PRIVATE(QGraphicsSceneDragDropEvent) }; class QGraphicsSceneResizeEventPrivate; class Q_GUI_EXPORT QGraphicsSceneResizeEvent : public QGraphicsSceneEvent { Q_DECLARE_PRIVATE(QGraphicsSceneResizeEvent) public: QGraphicsSceneResizeEvent(); ~QGraphicsSceneResizeEvent(); QSizeF oldSize() const; void setOldSize(const QSizeF &size); QSizeF newSize() const; void setNewSize(const QSizeF &size); }; class QGraphicsSceneMoveEventPrivate; class Q_GUI_EXPORT QGraphicsSceneMoveEvent : public QGraphicsSceneEvent { Q_DECLARE_PRIVATE(QGraphicsSceneMoveEvent) public: QGraphicsSceneMoveEvent(); ~QGraphicsSceneMoveEvent(); QPointF oldPos() const; void setOldPos(const QPointF &pos); QPointF newPos() const; void setNewPos(const QPointF &pos); }; #endif // QT_NO_GRAPHICSVIEW QT_END_NAMESPACE QT_END_HEADER #endif
[ "alon@rogue.(none)" ]
[ [ [ 1, 311 ] ] ]
8abe3b1b1bc276275e7472a06bcdd4c87ab4a442
136e81907731410b95458d5401d4ecf4e092ba39
/src/wrapper/juce_PluginHostType.h
de8ef9ba581d976fee05f93aeab5f6faad692dfc
[]
no_license
ZECTBynmo/MyAwesomeSynth
11c4b317a9cb8f254f3093638f085f2c4dfca241
121abf608f330bc493ed7b3bdce4127e18078491
refs/heads/master
2020-05-29T12:23:04.677418
2010-02-21T02:49:28
2010-02-21T02:49:28
16,752,671
1
0
null
null
null
null
UTF-8
C++
false
false
5,467
h
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-9 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_MAC #include <mach-o/dyld.h> #endif //============================================================================== class PluginHostType { public: //============================================================================== PluginHostType() throw() : type (getHostType()) { } //============================================================================== enum HostType { UnknownHost, AbletonLive6, AbletonLive7, AbletonLive8, AbletonLiveGeneric, AppleLogic, DigidesignProTools, CakewalkSonar8, CakewalkSonarGeneric, Reaper, MackieTracktion3, MackieTracktionGeneric, SteinbergCubase4, SteinbergCubase5, SteinbergCubaseGeneric, }; const HostType type; //============================================================================== bool isAbletonLive() const throw() { return type == AbletonLive6 || type == AbletonLive7 || type == AbletonLive8 || type == AbletonLiveGeneric; } bool isCubase() const throw() { return type == SteinbergCubase4 || type == SteinbergCubase5 || type == SteinbergCubaseGeneric; } bool isTracktion() const throw() { return type == MackieTracktion3 || type == MackieTracktionGeneric; } bool isSonar() const throw() { return type == CakewalkSonar8 || type == CakewalkSonarGeneric; } //============================================================================== private: static HostType getHostType() throw() { const String hostPath (getHostPath()); const String hostFilename (File (hostPath).getFileName()); #if JUCE_MAC if (hostPath.containsIgnoreCase (T("Live 6."))) return AbletonLive6; if (hostPath.containsIgnoreCase (T("Live 7."))) return AbletonLive7; if (hostPath.containsIgnoreCase (T("Live 8."))) return AbletonLive8; if (hostFilename.containsIgnoreCase (T("Live"))) return AbletonLiveGeneric; if (hostFilename.containsIgnoreCase (T("Pro Tools"))) return DigidesignProTools; if (hostFilename.containsIgnoreCase (T("Cubase 4"))) return SteinbergCubase4; if (hostFilename.containsIgnoreCase (T("Cubase 5"))) return SteinbergCubase5; if (hostFilename.contains (T("Logic"))) return AppleLogic; #elif JUCE_WINDOWS if (hostFilename.containsIgnoreCase ("Live 6.")) return AbletonLive6; if (hostFilename.containsIgnoreCase ("Live 7.")) return AbletonLive7; if (hostFilename.containsIgnoreCase ("Live 8.")) return AbletonLive8; if (hostFilename.containsIgnoreCase ("Live ")) return AbletonLiveGeneric; if (hostFilename.containsIgnoreCase ("ProTools")) return DigidesignProTools; if (hostPath.containsIgnoreCase ("SONAR 8")) return CakewalkSonar8; if (hostFilename.containsIgnoreCase ("SONAR")) return CakewalkSonarGeneric; if (hostPath.containsIgnoreCase ("Tracktion 3")) return MackieTracktion3; if (hostFilename.containsIgnoreCase ("Tracktion")) return MackieTracktionGeneric; if (hostFilename.containsIgnoreCase ("Cubase4")) return SteinbergCubase4; if (hostFilename.containsIgnoreCase ("Cubase5")) return SteinbergCubase5; if (hostFilename.containsIgnoreCase ("Cubase")) return SteinbergCubaseGeneric; if (hostFilename.containsIgnoreCase ("reaper")) return Reaper; #elif JUCE_LINUX jassertfalse // not yet done! #else #error #endif return UnknownHost; } static const String getHostPath() throw() { unsigned int size = 8192; MemoryBlock buffer (size + 8); buffer.fillWith (0); #if JUCE_WINDOWS GetModuleFileNameW (0, (WCHAR*) buffer.getData(), size / sizeof (WCHAR)); #elif JUCE_MAC _NSGetExecutablePath ((char*) buffer.getData(), &size); #elif JUCE_LINUX readlink ("/proc/self/exe", (char*) buffer.getData(), size); #else #error #endif return String::fromUTF8 ((const uint8*) buffer.getData(), size); } };
[ [ [ 1, 139 ] ] ]