blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
82209f137b21797fc486dfc8561ead9ab3528f0f
465943c5ffac075cd5a617c47fd25adfe496b8b4
/LNKLST_T.CPP
42884e8993c7419a5c54630f22dec851c1284381
[]
no_license
paulanthonywilson/airtrafficcontrol
7467f9eb577b24b77306709d7b2bad77f1b231b7
6c579362f30ed5f81cabda27033f06e219796427
refs/heads/master
2016-08-08T00:43:32.006519
2009-04-09T21:33:22
2009-04-09T21:33:22
172,292
1
0
null
null
null
null
UTF-8
C++
false
false
141
cpp
# include "eiflist.h" int main () { EifList<int> l (True); l.Add (1); l.Add (2); l.Add (1); l.Remove (2); return 0; }
[ [ [ 1, 14 ] ] ]
e9ad62f63b4b231f035c5e81274cda1750d92883
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/dom/deprecated/DOM.hpp
c63d1b8dcc1e92497b37123d433b614efe9b4303
[]
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
1,558
hpp
#ifndef DOM_DEPRECATED_HEADER_GUARD_ #define DOM_DEPRECATED_HEADER_GUARD_ /* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOM.hpp 176026 2004-09-08 13:57:07Z peiyongz $ */ // // This is the primary header file for inclusion in application // programs using the C++ XML Document Object Model API. // #include "DOM_Attr.hpp" #include "DOM_CDATASection.hpp" #include "DOM_CharacterData.hpp" #include "DOM_Comment.hpp" #include "DOM_Document.hpp" #include "DOM_DocumentFragment.hpp" #include "DOM_DocumentType.hpp" #include "DOM_DOMException.hpp" #include "DOM_DOMImplementation.hpp" #include "DOM_Element.hpp" #include "DOM_Entity.hpp" #include "DOM_EntityReference.hpp" #include "DOM_NamedNodeMap.hpp" #include "DOM_Node.hpp" #include "DOM_NodeList.hpp" #include "DOM_Notation.hpp" #include "DOM_ProcessingInstruction.hpp" #include "DOM_Text.hpp" #include "DOMString.hpp" #include "DOM_XMLDecl.hpp" #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 52 ] ] ]
7c96512a5496e2ac3105d28d64a481284be4c7ce
27bf1951e08b36c01374014a6da855a706680f7b
/USACO-Solution/src/1.5.3.cpp
4005cda01aa8e4900be7a3c330b0a2f566826fcd
[]
no_license
zinking/algorithm-exercise
4c520fd3ff6c14804d32e4ea427e5f7809cc7315
c58902709e9f12146d3d1f66610306e5ff19cfff
refs/heads/master
2016-09-05T22:27:19.791962
2009-07-24T04:45:18
2009-07-24T04:45:18
32,133,027
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,143
cpp
/* ID: zinking1 PROG: pprime LANG: C++ */ /* first thinking within a specific range, I think that the total nubmer of prelindrom must exceeds the total nubmer of primes/not proved,instinctly felt/, so first filter out the prime numbers then test if they are prelindromes is better choice --^~^ this is definitely the wrong idea when the upper bound grow up to 100000000, It won't be possible to allocate enough space for erators prime test */ /* second thinking prelindrome numbers of course is much less than prime nubmers so generate prelindrome numbers and then test whether it si primbe referred to other's hint number with even count of digits is divided by 11 so only need to check the odd count of digits whether they are prime */ #include <iostream> #include <fstream> #include <cstring> #include <cmath> #include <cstdlib> #include <cstdio> using namespace std; //const long int MAX_NUMBER = 100000000; //bool number[MAX_NUMBER]; //void itoa(int i,char* buf) /*¶¨Òåitoaº¯Êý*/ //{ // if (buf) sprintf(buf,"%d",i); //} inline bool isPrime( long int number){ int prime_upper_bound = static_cast<int>( sqrt( (float)number ) ); for( int i=2; i<=prime_upper_bound; i++ ){ if( number % i == 0 ) return false; } return true; } //void EratorsPrimeTest(int start, int end ){ // for( int i=0; i<end; i++ ){ // number[i] = true; // } // // number[0] = false; // number[1] = false; // // int c1, c2, c3; // int prime_upper_bound = static_cast<int>( sqrt( (float)end ) ); // //find primes then eliminate their multiples (0 = prime, 1 = composite) // for(c2 = 2;c2 <= prime_upper_bound+1;c2++){ // if(number[c2]){ // c1=c2; // for(c3 = 2*c1;c3 <= end+1; c3 = c3+c1){ // number[c3] = false; // } // } // } //} ofstream fout ("pprime.out"); ifstream fin ("pprime.in"); void PrimePrelindromeTest( int start, int end ){ if( start < 12 ){ for( int i=5;i<10;i++ ) if( i<end && i>=start && isPrime(i) ) fout << i << endl; fout << 11 << endl; } for( int i=10; i<=9999; i++ ){ char pnumber[20]; sprintf(pnumber,"%d",i); char *p = pnumber + strlen( pnumber ); char *q = p-1; while( --q >= pnumber ) *p++ = *q; *p='\0'; long int number = atol( pnumber ); if( number>=start && number<=end && isPrime(number) )fout << number << endl; } } //void PlindromeTest(int start, int end ){ // char number_character[10]; // for( int i=start; i<end; i++ ){ // if( number[i] ){ // //itoa( i, number_character ); // sprintf(number_character,"%d",i); // bool isPrelindrome = true; // char *p= number_character, *q = p+strlen(number_character)-1; // for( ; p<=q; p++,q-- ){ // if( *p != * q ){ // isPrelindrome = false; // break; // } // } // // if( isPrelindrome ) fout << i << endl; // } // } //} int main() { int start=0, end = 0; fin >> start >> end; //EratorsPrimeTest( start, end ); //PlindromeTest( start, end ); PrimePrelindromeTest(start,end); fin.close(); fout.close(); return 0; } //standard program for etoras prime test //#include <stdio.h> //#include <math.h> //#include <assert.h> //#include <time.h> // //int main(){ // int i; // printf("Find primes up to: "); // scanf("%i",&i); // // clock_t start, stop; // double t = 0.0; // // assert((start = clock())!=-1); // // //create prime list // int prime[i]; // int c1, c2, c3; // // //fill list with 0 - prime // for(c1 = 2; c1 <= i; c1++){ // prime[c1] = 0; // } // // //set 0 and 1 as not prime // prime[0]=1; // prime[1]=1; // // //find primes then eliminate their multiples (0 = prime, 1 = composite) // for(c2 = 2;c2 <= (int)sqrt(i)+1;c2++){ // if(prime[c2] == 0){ // c1=c2; // for(c3 = 2*c1;c3 <= i+1; c3 = c3+c1){ // prime[c3] = 1; // } // } // } // // stop = clock(); // t = (double) (stop-start)/CLOCKS_PER_SEC; // // //print primes // for(c1 = 0; c1 < i+1; c1++){ // if(prime[c1] == 0) printf("%i\n",c1); // } // printf("Run time: %f\n", t); //print time to find primes // // return 0; //}
[ "zinking3@e423e194-685c-11de-ba0c-230037762ff9" ]
[ [ [ 1, 182 ] ] ]
a68447733b07c5a89686cf55bc0fd3124b0f1db5
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/include/logdebug.h
97a9b01e8b08c4ca23b313370af9c7e0a935afa7
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
GB18030
C++
false
false
2,127
h
#ifndef _INCLUDE_LOG_DEBUG_H__ #define _INCLUDE_LOG_DEBUG_H__ #ifdef _DEBUG inline void OutputDebugInfo(const char * str) { OutputDebugString(str); } inline void WriteRawData(const char * filename, const char * str, const int len) { std::fstream file; file.open(filename, std::ios::out | std::ios::app | std::ios::binary); file.write(str, len); file.close(); } inline void WriteLog(const char * filename, const SOCKET s, const char * str) { std::fstream file; file.open(filename, std::ios::out | std::ios::app | std::ios::binary); file.write(str, static_cast<std::streamsize>(strlen(str))); file.close(); } inline void WriteLog(const char *filename, const SOCKET s, const int identity, const char * data, const int len) { char buffer[1024]; std::fstream file; file.open(filename, std::ios::out | std::ios::app | std::ios::binary); // 收到日期 sprintf(buffer, "\r\n===========[%d : %d==========]\r\n", s, identity); file.write(buffer, static_cast<std::streamsize>(strlen(buffer))); file.write(data, len); sprintf(buffer, "\r\nlength : %d\r\n", len); file.write(buffer, static_cast<std::streamsize>(strlen(buffer))); file.close(); } inline void WriteLog(const char *filename, const SOCKET s, const char * data, const int len) { char buffer[1024]; std::fstream file; file.open(filename, std::ios::out | std::ios::app | std::ios::binary); // 收到日期 sprintf(buffer, "\r\n===========[%d : %d==========]\r\n", s, GetTickCount()); file.write(buffer, static_cast<std::streamsize>(strlen(buffer))); file.write(data, len); sprintf(buffer, "\r\nlength : %d\r\n", len); file.write(buffer, static_cast<std::streamsize>(strlen(buffer))); file.close(); } #else inline void OutputDebugInfo(const char * str) { } inline void WriteRawData(const char * filename, const char * str, const int len) {} inline void WriteLog(const char * filename, const SOCKET s, const char * str); inline void WriteLog(const char *filename, const SOCKET s, const char * data, const int len); #endif #endif // _INCLUDE_LOG_DEBUG_H__
[ "ynkhpp@1a8edc88-4151-0410-b40c-1915dda2b29b", "[email protected]" ]
[ [ [ 1, 21 ], [ 23, 33 ], [ 35, 36 ], [ 38, 48 ], [ 50, 51 ], [ 53, 74 ] ], [ [ 22, 22 ], [ 34, 34 ], [ 37, 37 ], [ 49, 49 ], [ 52, 52 ] ] ]
afe90d364816b8dee0e2b7662c480a0ce25ebf9d
fb8ab028c5e7865229f7032052ef6419cce6d843
/patterndemo/src/point_stack.cpp
08334e522a7bb3bee3119cb57055de85d48fdfd3
[]
no_license
alexunder/autumtao
d3fbca5b87fef96606501de8bfd600825b628e42
296db161b50c96efab48b05b5846e6f1ac90c38a
refs/heads/master
2016-09-05T09:43:36.361738
2011-03-25T16:13:51
2011-03-25T16:13:51
33,286,987
0
0
null
null
null
null
UTF-8
C++
false
false
1,463
cpp
// *************************************************************** // point_stack version: 1.0 ? date: 07/23/2008 // ------------------------------------------------------------- // // ------------------------------------------------------------- // Copyright (C) 2008 - All Rights Reserved // *************************************************************** // // *************************************************************** #include "StdAfx.h" #include "point_stack.h" Point_Stack::Point_Stack() { m_curtop = -1; memset( m_stack_point_buffer, 0, STACK_SIZE*sizeof(POINT) ); } Point_Stack::~Point_Stack() { } bool Point_Stack::PushPoint( POINT pt ) { m_curtop++; if ( m_curtop == m_ithreshold ) { return false; } m_stack_point_buffer[m_curtop].x = pt.x; m_stack_point_buffer[m_curtop].y = pt.y; return true; } void Point_Stack::PopPoint( POINT & pt ) { pt.x = m_stack_point_buffer[m_curtop].x; pt.y = m_stack_point_buffer[m_curtop].y; memset( &m_stack_point_buffer[m_curtop], 0, sizeof(POINT) ); if ( m_curtop == 0 ) { m_curtop = -1; return; } m_curtop--; } void Point_Stack::ClearStack() { m_curtop = -1; memset( m_stack_point_buffer, 0, STACK_SIZE*sizeof(POINT) ); } bool Point_Stack::isStackNotClear() { return (m_curtop>=0); } void Point_Stack::SetThreshold( int value ) { m_ithreshold = value; }
[ "Xalexu@59d19903-2beb-cf48-5e42-6f21bef2d45e" ]
[ [ [ 1, 70 ] ] ]
9e0fa7d4ceb64cc57e52f3df3956db5ceaaf1136
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/infostudio/InfoStudio/base/urlcomp.h
ebb56dbc0966599cff1a1393c6eabce8ed1e7122
[]
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
GB18030
C++
false
false
1,767
h
#pragma once #include <wininet.h> // 可能占用内存多了一些,不要保存之, sizeof = 4736 class UrlComponet : public URL_COMPONENTSA { public: UrlComponet() { ZeroMemory(this, sizeof URL_COMPONENTSA); dwStructSize = sizeof URL_COMPONENTSA; dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH; dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH; dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH; dwPasswordLength = INTERNET_MAX_PASSWORD_LENGTH; dwUrlPathLength = INTERNET_MAX_PATH_LENGTH; dwExtraInfoLength = INTERNET_MAX_PATH_LENGTH; // 0 lpszScheme = _szScheme; lpszHostName = _szHostName; lpszUserName = _szUserName; lpszPassword = _szPassword; lpszUrlPath = _szPath; lpszExtraInfo = _szExtraInfo; } BOOL Crack(LPCSTR lpszUrl, DWORD dwUrlLength = 0, DWORD dwFlags = ICU_ESCAPE) { lstrcpynA(_szUrl, lpszUrl, sizeof _szUrl); BOOL f = InternetCrackUrlA(lpszUrl, dwUrlLength, dwFlags, this); return f; } BOOL Create(INTERNET_SCHEME nScheme, LPCSTR lpszHostName, INTERNET_PORT nPort, LPCSTR lpszUserName, LPCSTR lpszPassword, LPCSTR lpszUrlPath, LPCSTR lpszExtraInfo) { // this->lpszHostName = (LPTSTR)lpszHostName; return 0; } LPCSTR GetFileName() const { int n = lstrlenA(_szPath); if (n > 0) { LPCSTR p = _szPath + (n - 1); while ( *p != '\\' && *p != '/' ) p --; return p + 1; } return 0; } private: char _szUrl[INTERNET_MAX_URL_LENGTH]; char _szHostName[INTERNET_MAX_HOST_NAME_LENGTH]; char _szUserName[INTERNET_MAX_USER_NAME_LENGTH]; char _szPassword[INTERNET_MAX_PASSWORD_LENGTH]; char _szPath[INTERNET_MAX_PATH_LENGTH]; char _szScheme[INTERNET_MAX_SCHEME_LENGTH]; char _szExtraInfo[INTERNET_MAX_PATH_LENGTH]; };
[ "ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 60 ] ] ]
a3e07217650ce63c18a5f9fba69d756a6e3dd10a
5da9d428805218901d7c039049d7e13a1a2b1c4c
/Vivian/libFade/MapWnd.h
c6bedab724d31f4273b33eb94852e2e5f125f183
[]
no_license
SakuraSinojun/vivianmage
840be972f14e17bb76241ba833318c13cf2b00a4
7a82ee5c5f37d98b86e8d917d9bb20c96a2d6c7f
refs/heads/master
2021-01-22T20:44:33.191391
2010-12-11T15:26:15
2010-12-11T15:26:15
32,322,907
0
0
null
null
null
null
UTF-8
C++
false
false
1,200
h
////////////////////////////////////////////////////////////////// // // FileName : MapWnd.h // Author : SakuraSinojun // Description : this class is used to draw a joint map spliced by 4 pictures // // Version : 1.0.0.1 // Date : 2009.9.6 // // Copyright(c): 2009-2010 Sakura // ////////////////////////////////////////////////////////////////// #pragma once #include "gamewnd.h" class CMapWnd //: public CGameWnd { public: CMapWnd(void); ~CMapWnd(void); void Create(const char * file1,const char * file2,const char * file3,const char * file4); void ShowWindow(bool show); void SetMap(int index,const char * filename); void SetSplitPoint(CPoint point); CPoint GetSplitPoint(); private: void Create(int width,int height){} void Load(const char *file){} void MoveForward(){} void MoveBehind(){} void SetWindowOn(CGameWnd * _window){} void BringWindowToTop(){} void MoveWindow(int x,int y){} CPoint GetWindowPos(){} void UseBitmapRect(CRect& rect){} void SetColorKey(bool colorkey){} void SetFadeLevel(int level=255){} CSize GetSize(){} private: CGameWnd map[4]; CPoint point; };
[ "SakuraSinojun@c9cc3ed0-94a9-11de-b6d4-8762f465f3f9" ]
[ [ [ 1, 52 ] ] ]
51483c3d09fef3f605adde01946288af2261d2e7
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/topology/polygon/jarvis_march.h
734e28c7200daf0a4caa96b28717a1a0e8b4df8c
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,137
h
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #ifndef JARVIS_MARCH_H_ #define JARVIS_MARCH_H_ #include "_apps_enable_cmake.h" #ifdef ENABLE_TOPOLOGY #include "apps/topology/polygon/polygon.h" #include <vector> #include "sys/vec.h" using namespace std; using std::vector; namespace polygon { class JarvisMarch { public: JarvisMarch(); ~JarvisMarch(); vector<Vec> compute_convex_hull(const vector<Vec>&) throw(); private: vector<Vec> polygon_; int size_of_polygon_; // size of polygon_ int size_of_convex_hull_; // number of nodes of the convex hull of a polygon void jm(void) throw(); int index_of_lowest_point(void) throw(); int index_of_rightmost_point_from(const Vec&) throw(); void swap(int i, int j) throw(); Vec relTo(const Vec&, const Vec&) throw(); // creates a new point relatively to point p as the origin bool isLess(const Vec&, const Vec&) throw(); // checks if the angle between the position vector of the new point and the origin // is smaller than the angle between the position vector of p and the origin double cross(const Vec&, const Vec&) throw(); // cross product bool isFurther(const Vec&, const Vec&) throw(); // checks if the distance between the new point and the origin // is shorter than the distance between p and the origin double mdist(const Vec&) throw(); // Manhattan distance }; } #endif /*ENABLE_TOPOLOGY*/ #endif /*JARVIS_MARCH_H_*/
[ [ [ 1, 11 ], [ 13, 64 ] ], [ [ 12, 12 ] ] ]
c68a29b1515e9f41a645d597191b2002a12eea36
dadf8e6f3c1adef539a5ad409ce09726886182a7
/airplay/src/toeUtils.cpp
7987831eb7a3f38077bbf118af77e7aded1cc398
[]
no_license
sarthakpandit/toe
63f59ea09f2c1454c1270d55b3b4534feedc7ae3
196aa1e71e9f22f2ecfded1c3da141e7a75b5c2b
refs/heads/master
2021-01-10T04:04:45.575806
2011-06-09T12:56:05
2011-06-09T12:56:05
53,861,788
0
0
null
null
null
null
UTF-8
C++
false
false
6,240
cpp
#include <IwResManager.h> #include "toeUtils.h" #include "pugixml.hpp" #include "s3eOSReadString.h" using namespace TinyOpenEngine; namespace TinyOpenEngine { unsigned int UTF8_MALFORMED((unsigned int)0xfffd); bool toeContinuationUtf8(const unsigned char * data, int count) { for (int i = 0; i < count; ++i) { if ((data[i]&0xC0)!= 0x80) return false; } return true; } } //Get scriptable class declaration CtoeScriptableClassDeclaration* CtoeUtils::GetClassDescription() { static TtoeScriptableClassDeclaration<CtoeUtils> d ("CtoeUtils", ScriptTraits::Method("GetResourceByName", &CtoeUtils::GetResourceByName), ScriptTraits::Method("GetDeviceID", &CtoeUtils::GetDeviceID), ScriptTraits::Method("GetDevicePhone", &CtoeUtils::GetDevicePhone), ScriptTraits::Method("GetDeviceOS", &CtoeUtils::GetDeviceOS), ScriptTraits::Method("GetDeviceClass", &CtoeUtils::GetDeviceClass), ScriptTraits::Method("GetDeviceArchitecture", &CtoeUtils::GetDeviceArchitecture), ScriptTraits::Method("GetDeviceS3eVersion", &CtoeUtils::GetDeviceS3eVersion), ScriptTraits::Method("GetDeviceTotalRam", &CtoeUtils::GetDeviceTotalRam), ScriptTraits::Method("GetDeviceFreeRam", &CtoeUtils::GetDeviceFreeRam), ScriptTraits::Method("AssertMsg", &CtoeUtils::AssertMsg), ScriptTraits::Method("ReadString", &CtoeUtils::ReadString), ScriptTraits::Method("UrlEncode", &CtoeUtils::UrlEncode), 0); return &d; } const char* CtoeUtils::GetDeviceID() { return s3eDeviceGetString(S3E_DEVICE_ID); } const char* CtoeUtils::GetDevicePhone() { return s3eDeviceGetString(S3E_DEVICE_PHONE_NUMBER); } const char* CtoeUtils::GetDeviceOS() { return s3eDeviceGetString(S3E_DEVICE_OS); } const char* CtoeUtils::GetDeviceClass() { return s3eDeviceGetString(S3E_DEVICE_CLASS); } const char* CtoeUtils::GetDeviceArchitecture() { return s3eDeviceGetString(S3E_DEVICE_ARCHITECTURE); } const char* CtoeUtils::GetDeviceS3eVersion() { return s3eDeviceGetString(S3E_DEVICE_S3E_VERSION); } int CtoeUtils::GetDeviceTotalRam() { return s3eDeviceGetInt(S3E_DEVICE_TOTAL_RAM); } int CtoeUtils::GetDeviceFreeRam() { return s3eDeviceGetInt(S3E_DEVICE_FREE_RAM); } void CtoeUtils::AssertMsg(const char *m) { IwDebugAssertShow(m,"",0,true); } unsigned int CtoeUtils::DecodeUtf8(const void * p, unsigned int & returnValue) { const unsigned char * data = static_cast<const unsigned char*>(p); int returnLength = 1; if (data[0] < 0x80) { // regular ASCII char // 0x00000000 - 0x0000007F: returnValue = data[0]; return 1; } if (data[0] < 0xC0 || data[0] > 0xfd) { // not a valid start byte. goto malformed; } if ( (data[0] & 0xE0) == 0xC0) { // 0x00000080 - 0x000007FF: if (toeContinuationUtf8(&data[1],1)) { returnValue = ((data[0] & 0x1f)<<6) | (data[1]&0x3f); returnLength = 2; goto checkLength; } else { goto malformed; } } if ( (data[0] & 0xF0) == 0xE0) { // 0x00000800 - 0x0000FFFF: if (toeContinuationUtf8(&data[1],2)) { returnValue = ((data[0] & 0xf)<<(12)) | ((data[1]&0x3f)<<6) | (data[2]&0x3f); returnLength = 3; goto checkLength; } else { goto malformed; } } if ( (data[0] & 0xF8) == 0xF0) { // 0x00010000 - 0x001FFFFF: if (toeContinuationUtf8(&data[1],3)) { returnValue = ((data[0] & 0x7)<<(18)) | ((data[1]&0x3f)<<12) | ((data[2]&0x3f)<<6) | (data[3]&0x3f); returnLength = 4; goto checkLength; } else { goto malformed; } } if ( (data[0] & 0xFC) == 0xF8) { //0x00200000 - 0x03FFFFFF: if (toeContinuationUtf8(&data[1],4)) { returnValue = ((data[0] & 0x3)<<(24)) | ((data[1]&0x3f)<<18) | ((data[2]&0x3f)<<12) | ((data[3]&0x3f)<<6) | (data[4]&0x3f); returnLength = 5; goto checkLength; } else { goto malformed; } } if ( (data[0] & 0xFE) == 0xFC) { // 0x04000000 - 0x7FFFFFFF: if (toeContinuationUtf8(&data[1],5)) { returnValue = ((data[0] & 0x1)<<(30)) | ((data[1]&0x3f)<<24) | ((data[2]&0x3f)<<18) | ((data[3]&0x3f)<<12) | ((data[4]&0x3f)<<6) | (data[5]&0x3f); returnLength = 6; goto checkLength; } else { goto malformed; } } // not implemented returnValue = data[0]; return 1; malformed: returnValue = UTF8_MALFORMED; return 1; checkLength: if ( ( (returnLength > 1) && (returnValue < 0x80)) || ( (returnLength > 2) && (returnValue < 0x800)) || ( (returnLength > 3) && (returnValue < 0x10000)) || ( (returnLength > 4) && (returnValue < 0x200000)) || ( (returnLength > 5) && (returnValue < 0x4000000)) ) { returnValue = UTF8_MALFORMED; } if (returnValue != UTF8_MALFORMED && ( ( returnValue >= 0xd800 && returnValue <= 0xdfff) || returnValue == 0xfffe || returnValue == 0xffff ) ) { returnValue = UTF8_MALFORMED; } return returnLength; } std::string CtoeUtils::UrlEncode(const char* s) { std::string encoded; if (!s || !*s) return encoded; while (*s) { unsigned int ch; int len = DecodeUtf8(s,ch); if (UTF8_MALFORMED == ch) return encoded; s += len; if ((ch >= 0x00 && ch <= 0x26) || ch == 0x2B || ch == 0x2C || ch == 0x2F || (ch >= 0x3A && ch <= 0x40) || (ch >= 0x7B && ch <= 0x7E) || (ch >= 0x5B && ch <= 0x5E) || ch == 0x60 || (ch >= 0x80)) { char buf [32]; if (ch < 128) sprintf(buf,"%%%02X",ch); else sprintf(buf,"%%u%04X",ch); encoded += buf; } else { encoded += (char)ch; } } return encoded; } const char* CtoeUtils::ReadString(const char * t,const char * def) { return s3eOSReadStringUTF8WithDefault(t,def); } CIwManaged* CtoeUtils::GetResourceByName(const char* id,const char* type) { return IwGetResManager()->GetResNamed(id,type,IW_RES_PERMIT_NULL_F); }
[ [ [ 1, 190 ] ] ]
36a599591f071fee5868aaeee06f71c6f556a8f5
fab77712e8dfd19aea9716b74314f998093093e2
/UI/DataView.cpp
818c98944a248862c0e8e129ea1c46cd5559d0f4
[]
no_license
alandigi/tsfriend
95f98b123ae52f1f515ab4a909de9af3724b138d
b8f246a51f01afde40a352248065a6a42f0bcbf8
refs/heads/master
2016-08-12T07:09:23.928793
2011-11-13T15:12:54
2011-11-13T15:12:54
45,849,814
0
2
null
null
null
null
GB18030
C++
false
false
5,069
cpp
// UnitInfoView.cpp : 实现文件 // #include "stdafx.h" #include "DvbTsa.h" #include "DataView.h" #include "ContentTree.h" #include "TSDoc.h" #include "crc.h" #include "builder.h" #include "dataview.h" // CDataView IMPLEMENT_DYNCREATE(CDataView, CEditView) CDataView::CDataView() { Modifyed = false; } CDataView::~CDataView() { } BEGIN_MESSAGE_MAP(CDataView, CEditView) ON_CONTROL_REFLECT(EN_KILLFOCUS, OnEnKillfocus) ON_CONTROL_REFLECT(EN_CHANGE, OnEnChange) END_MESSAGE_MAP() // CDataView 诊断 #ifdef _DEBUG void CDataView::AssertValid() const { CEditView::AssertValid(); } void CDataView::Dump(CDumpContext& dc) const { CEditView::Dump(dc); } #endif //_DEBUG // CDataView 消息处理程序 void CDataView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { if(lHint & CTSDoc::DATA_VIEW) { CEdit & ThisEdit = this->GetEditCtrl(); int FocusIdx = GetDocument()->DocDataFocusStart +GetDocument()->DocDataFocusLen-1 ;/*last first*/ int FocusLen = GetDocument()->DocDataFocusLen; Content.Empty(); if((GetDocument()->DocDataLen)&&(GetDocument()->DocDataFocusLen)) { u8 * pData = (GetDocument()->DocData + (FocusIdx/8)); u8 Data, Bit; u8 CurData = 0; u8 CurDataIdx = 0; CString Cur; FocusIdx = (FocusIdx%8); while(FocusLen) { Data = *pData; for(; (FocusIdx >= 0) && (FocusLen) ;FocusIdx --) { Bit =Data; Bit = (Bit>>(7-FocusIdx)) & 0x1; CurData |= Bit<<CurDataIdx; CurDataIdx ++; if(CurDataIdx >= 8) { Cur.Format("%02x", CurData); Content.Insert(0,Cur); CurData = 0; CurDataIdx = 0; } FocusLen --; } FocusIdx = 7; pData--; } if(CurDataIdx) { Cur.Format("%02x", CurData); Content.Insert(0,Cur); } //Content.Insert(0,"0x"); } ThisEdit.SetWindowText((LPCTSTR)Content); } } CTSDoc * CDataView::GetDocument(void) { return (CTSDoc *)CView::GetDocument();; } void CDataView::TraceOutData(u8 * pData, u32 Lenth) { GetDocument()->DocInfo.AppendFormat("new Field Data:"); u32 Idx =0 ; while(Lenth > Idx) { GetDocument()->DocInfo.AppendFormat(" %2x ",pData[Idx++]); } GetDocument()->DocInfo.AppendFormat("\r\n"); } void CDataView::UpdataData() { CEdit & ThisEdit = this->GetEditCtrl(); //if(Modifyed) { static u8 DataBuff[DATAVIEWBUFFERLENTH]; Content.Empty(); ThisEdit.GetWindowText(Content); Content.MakeUpper(); //int lenth = Content.GetLength(); //u32 DataLen = lenth; u8 * pData = DataBuff; memset(pData ,0 , DATAVIEWBUFFERLENTH); int BitIdx = 0 ; while(Content.GetLength()) { if((Content.Right(1) == "0")) { DataBuff[BitIdx/2] |= 0<<(4- 4*(BitIdx%2)); } else if(Content.Right(1) == "1") { DataBuff[BitIdx/2] |= 1<<(4- 4*(BitIdx%2)); } else if(Content.Right(1) == "2") { DataBuff[BitIdx/2] |= 2<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "3") { DataBuff[BitIdx/2] |= 3<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "4") { DataBuff[BitIdx/2] |= 4<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "5") { DataBuff[BitIdx/2] |= 5<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "6") { DataBuff[BitIdx/2] |= 6<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "7") { DataBuff[BitIdx/2] |= 7<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "8") { DataBuff[BitIdx/2] |= 8<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "9") { DataBuff[BitIdx/2] |= 9<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "A") { DataBuff[BitIdx/2] |= 0xA<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "B") { DataBuff[BitIdx/2] |= 0xB<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "C") { DataBuff[BitIdx/2] |= 0xC<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "D") { DataBuff[BitIdx/2] |= 0xD<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "E") { DataBuff[BitIdx/2] |= 0xE<<(4 - 4*(BitIdx%2)); } else if(Content.Right(1) == "F") { DataBuff[BitIdx/2] |= 0xF<<(4 - 4*(BitIdx%2)); } else { MessageBox("Data input error,you should only input Binary data"); //GetDocument()->UpdateAllViews(NULL,CTSDoc::DATA_VIEW|CTSDoc::TREE_VIEW); return; } Content.Delete(Content.GetLength()-1); BitIdx ++; } { //GetDocument()->DocData[] } //GetDocument()->pSltDataView->PostMessage(MSG_UI_DATA_VIEW_EDIT,(WPARAM)DataBuff); Modifyed = false; } } void CDataView::OnEnKillfocus() { UpdataData(); } void CDataView::OnEnChange() { Modifyed = true; GetEditCtrl().SetModify(FALSE); } void CDataView::OnInitialUpdate() { CEdit & ThisEdit = this->GetEditCtrl(); CEditView::OnInitialUpdate(); GetDocument()->pDataView = this; }
[ [ [ 1, 232 ] ] ]
d4a47696ddcf1228532d342796468f823cf399d9
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/RTTS/TS_ModelLib/RodMill.h
4040361be3a1736bde132049d2fe71c8b70e4507
[]
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,990
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #ifndef __RodMill_H #define __RodMill_H #ifndef __MD_HEADERS_H #include "md_headers.h" #endif #include "TSRodMill.h" #include "Mill.h" //--------------------------------------------------------------------------- class CMill_Rod : public CMill { public: // Constructor CMill_Rod(); // Data Entry Field Method void BuildDataFields(MDataDefn &DB); // Seperator Method Execution void EvalProducts(MBaseMethod &M, MStream &Feed , MStream &Product, bool bInit); protected: // // Parameters // //MILL OPERATING VARIABLES //C ~~~~~~~~~~~~~~~~~~~~~~~~ // //PARAMETER 1 = NUMBER OF PARALLEL MILLS long mi_NParrallelMills; //PARAMETER 2 = DIAMETER (INSIDE LINERS, METRES) OF MILL BEING SIMULATED. double mi_DiameterSim; //PARAMETER 3 = LENGTH (INSIDE LINERS, METRES) OF MILL BEING SIMULATED. double mi_LengthSim; //PARAMETER 4 = FRACTION CRITICAL SPEED OF MILL BEING SIMULATED. double mi_FracCriticalSpeedSim; //PARAMETER 5 = LOAD FRACTION (SEE ABOVE) OF MILL BEING SIMULATED. double mi_FracLoadSim; //PARAMETER 6 = WORK INDEX OF ORE FED TO MILL BEING SIMULATED. double mi_WorkIndexSim; // MODEL PARAMETERS // ~~~~~~~~~~~~~~~~ //PARAMETER 7 = MILL DIAMETER (INSIDE LINERS, METRES) OF MILL FROM // WHICH MODEL PARAMETERS ARE DERIVED. double mi_DiameterDerived; //PARAMETER 8 = LENGTH OF MILL FROM WHICH MODEL PARAMETERS ARE DERIVED. double mi_LengthDerived; //PARAMETER 9 = FRACTION OF CRITICAL SPEED OF MILL FROM WHICH MODEL // PARAMETERS ARE DERIVED. double mi_FracCriticalSpeedDerived; //PARAMETER 10 = LOAD FRACTION (I.E. FRACTION OF MILL OCCUPIED BY // STATIONARY LOAD, INCLUDING VOIDS) OF MILL FROM // WHICH MODEL PARAMETERS ARE DERIVED. double mi_FracLoadDerived; // PARAMETER 11 = ORE WORK INDEX OF MILL FROM WHICH MODEL PARAMETERS ARE // DERIVED. double mi_WorkIndexDerived; // PARAMETER 12 = MILL CONSTANT OF MILL FROM WHICH MODEL PARAMETERS ARE DERIVED double mi_MillConstantDerived; // PARAMETER 13 = PARAMETER XC, THE PARTICLE SIZE BELOW WHICH THE // SELECTION FUNCTION IS CONSTANT. double mi_XC; // PARAMETER 14 = INTERCEPT OF SELECTION FUNCTION AT ZERO SIZE (IN). double mi_IN; // PARAMETER 15 = SLOPE OF SELECTION FUNCTION WITH PARTICLE SIZE (SL). double mi_SL; // PARAMETER 16 = 90% PASSING SIZE OF FEED TO ROD MILL FROM WHICH MILL // PARAMETERS WERE DERIVED. double mi_F90Derived; // PARAMETERS 17-47 = ROD MILL APPEARANCE FUNCTION // How are we going to enter this or will it be calculated based on ore type?? double mi_A[31]; // PARAMETERS 48-78 = ROD MILL CLASSIFICATION FUNCTION // How will we specify this or will it be calculated??? // Doco talks about default classification values being same as sieves?? double mi_C[31]; // MODEL CALCULATED VALUES // ~~~~~~~~~~~~~~~~~~~~~~~ // PARAMETER 79 = MILL CONSTANT OF MILL BEING SIMULATED. double mo_MCSim; // PARAMETER 80 = 90% PASSING SIZE OF FEED TO MILL BEING SIMULATED double mo_F90Sim; // PARAMETER 81 = CHANGE IN NO. OF BREAKAGE STAGES WITH FEED COARSENESS double mo_Out_ChangeNStages; // PARAMETER 82 = NO. OF BREAKAGE STAGES IN MILL BEING SIMULATED double mo_NBreakageStagesSim; // PARAMETERS 83-113 = ROD MILL SELECTION FUNCTION double mo_S[31]; // PARAMETERS 114-144 = Sizes at which above function data occurred // The TS Rod Crusher RioTintoTS::RodMill Mill; // System persistent feed data RioTintoTS::PFlowStream1 FeedStream; RioTintoTS::PStreamInfo1 MatInfo; // Mapping area for SysCAD to TS params double m_Params[78]; }; #endif
[ [ [ 1, 138 ] ] ]
12932978cf367777bce2327f07be3a6778794823
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/XYLib/2D_GTGAU.H
ee3ba6534634671a798e766e8c8f579a3b049b4b
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,074
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== // SysCAD Copyright Kenwalt (Pty) Ltd 1992 #ifndef __2D_GTGAU_H #define __2D_GTGAU_H #ifdef __2D_GTGAU_CPP #define DllImportExport DllExport #elif !defined(XYLIB) #define DllImportExport DllImport #else #define DllImportExport #endif //============================================================================ const long GtGauNoOfParms = 4; DEFINE_TAGOBJ(C2DGtGau); class DllImportExport C2DGtGau : public C2DModel { public: static pchar ParmDescs[GtGauNoOfParms]; public: C2DGtGau(pTagObjClass pClass_, pchar pTag, pTaggedObject pAttach, TagObjAttachment eAttach); virtual ~C2DGtGau(); virtual void Clear(); virtual double Yx(double Xi); virtual pchar GetParmDesc(long i) { return ParmDescs[i]; }; }; // =========================================================================== #undef DllImportExport #endif
[ [ [ 1, 38 ] ] ]
e9a0b072b8e10423f4df252270c29fe72c4d8e24
1c0fa995ba528796c26c3e510118c0e82a1efc8b
/LarGDSPlugin.cpp
3985dede59395e38cd378d8ef24883b45e61596b
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
lg/gd-mirc-indexer
75be8ba507c2325cd93c8b653442670b8cce5b5c
28081ca24e43232a129ce6da1a552c1cfda7b1a9
refs/heads/master
2020-05-27T10:11:24.615860
2009-08-25T00:29:45
2009-08-25T00:29:45
287,104
3
0
null
null
null
null
UTF-8
C++
false
false
8,315
cpp
// LarGDSPlugin 1.01 by Larry Gadea // For the latest version of LarGDSPlugin, please visit: http://www.trivex.net #include "LarGDSPlugin.h" using namespace std; LarGDSPlugin::LarGDSPlugin(CLSID ClassID) { ObjClassID = ClassID; } bool LarGDSPlugin::RegisterPlugin(string Title, string Description, string IconPath) { return RegisterPluginWithExtensions(Title, Description, IconPath, vector <string>()); } bool LarGDSPlugin::RegisterPluginWithExtensions(string Title, string Description, string IconPath, vector<string> Extensions) { // Initialize COM (if required) HRESULT ComInitResult = CoInitialize(NULL); if (FAILED(ComInitResult) && ComInitResult != RPC_E_CHANGED_MODE) { return false; } // Create connection with GDS CComPtr<IGoogleDesktopSearchComponentRegistration> spRegistration; CComPtr<IGoogleDesktopSearchComponentRegister> spRegister; HRESULT hr; hr = spRegister.CoCreateInstance(CLSID_GoogleDesktopSearchRegister); if (SUCCEEDED(hr)) { ATLASSERT(spRegister != NULL); // Component description is 6 strings CComSafeArray<VARIANT> arr_descr(6); arr_descr.SetAt(0, CComVariant(L"Title")); arr_descr.SetAt(1, CComVariant(Title.c_str())); arr_descr.SetAt(2, CComVariant(L"Description")); arr_descr.SetAt(3, CComVariant(Description.c_str())); arr_descr.SetAt(4, CComVariant(L"Icon")); arr_descr.SetAt(5, CComVariant(IconPath.c_str())); // our CLSID in string format CComBSTR clsid(ObjClassID); // Wrap description array in variant CComVariant descr(arr_descr.m_psa); // and register hr = spRegister->RegisterComponent(clsid, descr, &spRegistration); if (FAILED(hr)) { return false; } ATLASSERT(FAILED(hr) || spRegistration); for (int CurExtension = 0; (SUCCEEDED(hr) && (CurExtension <= (int)(Extensions.size() - 1))); CurExtension++) { hr = spRegistration->RegisterExtension(CComBSTR(Extensions[CurExtension].c_str())); } // revoke our registration in case any of our extensions fail to register if (FAILED(hr)) { // ignore the error - we've already failed HRESULT ignore; ignore = spRegister->UnregisterComponent(CComBSTR(clsid)); // Uninitialize COM (if required) if (SUCCEEDED(ComInitResult)) { CoUninitialize(); } return false; } } // Uninitialize COM (if required) if (SUCCEEDED(ComInitResult)) { CoUninitialize(); } return true; } bool LarGDSPlugin::UnregisterPlugin() { // Initialize COM (if required) HRESULT ComInitResult = CoInitialize(NULL); if (FAILED(ComInitResult) && ComInitResult != RPC_E_CHANGED_MODE) { return false; } // Connect to GDS CComPtr<IGoogleDesktopSearchComponentRegister> spRegister; HRESULT hr; hr = spRegister.CoCreateInstance(CLSID_GoogleDesktopSearchRegister); if (SUCCEEDED(hr)) { // our CLSID in string format CComBSTR bstrClsid(ObjClassID); hr = spRegister->UnregisterComponent(bstrClsid); } // Uninitialize COM (if required) if (SUCCEEDED(ComInitResult)) { CoUninitialize(); } return true; } bool LarGDSPlugin::SendIMEvent(string Content, string UserName, string BuddyName, string Title, unsigned long ConversationID) { SYSTEMTIME TimeNow; GetSystemTime(&TimeNow); return SendIMEvent(Content, UserName, BuddyName, Title, ConversationID, TimeNow, ""); } bool LarGDSPlugin::SendIMEvent(string Content, string UserName, string BuddyName, string Title, unsigned long ConversationID, SYSTEMTIME MessageTime, string Format) { // Convert MessageTime double VarMessageTime; SystemTimeToVariantTime(&MessageTime, &VarMessageTime); // If no format was specified, assume it's text/html if (Format == "") { Format = "text/html"; } // Init COM HRESULT hr_coinit = CoInitialize(NULL); if (FAILED(hr_coinit) && hr_coinit != RPC_E_CHANGED_MODE) { return false; } // Assemble event { CComPtr<IGoogleDesktopSearchEventFactory> spFactory; HRESULT hr = spFactory.CoCreateInstance(CLSID_GoogleDesktopSearch, NULL, CLSCTX_INPROC); if (FAILED(hr)) { return false; } CComPtr<IDispatch> spEventDisp; hr = spFactory->CreateEvent(CComBSTR(ObjClassID), CComBSTR(L"Google.Desktop.IM"), &spEventDisp); if (FAILED(hr)) { return false; } CComQIPtr<IGoogleDesktopSearchEvent> spEvent(spEventDisp); ATLASSERT(spEventDisp && spEvent); if (spEvent == NULL) { return false; } if (SUCCEEDED(hr)) { hr = spEvent->AddProperty(CComBSTR(L"message_time"), CComVariant(VarMessageTime, VT_DATE)); } if (SUCCEEDED(hr)) { hr = spEvent->AddProperty(CComBSTR(L"format"), CComVariant(Format.c_str())); } if (SUCCEEDED(hr)) { hr = spEvent->AddProperty(CComBSTR(L"content"), CComVariant(Content.c_str())); } if (SUCCEEDED(hr)) { hr = spEvent->AddProperty(CComBSTR(L"buddy_name"), CComVariant(BuddyName.c_str())); } if (SUCCEEDED(hr)) { hr = spEvent->AddProperty(CComBSTR(L"title"), CComVariant(Title.c_str())); } if (SUCCEEDED(hr)) { hr = spEvent->AddProperty(CComBSTR(L"conversation_id"), CComVariant(ConversationID)); } if (SUCCEEDED(hr)) { hr = spEvent->AddProperty(CComBSTR(L"user_name"), CComVariant(UserName.c_str())); } if (FAILED(hr)) { return false; } hr = spEvent->Send(EventFlagIndexable); if (FAILED(hr)) { return false; } } if (SUCCEEDED(hr_coinit)) { CoUninitialize(); } return true; } bool LarGDSPlugin::SendTextFileEvent(string Content, string Path, SYSTEMTIME LastModified) { // Convert date to proper format double ModifiedTime; SystemTimeToVariantTime(&LastModified, &ModifiedTime); // Init COM HRESULT hr_coinit = CoInitialize(NULL); if (FAILED(hr_coinit) && hr_coinit != RPC_E_CHANGED_MODE) { return false; } // Assemble event { CComPtr<IGoogleDesktopSearchEventFactory> spFactory; HRESULT hr = spFactory.CoCreateInstance(CLSID_GoogleDesktopSearch, NULL, CLSCTX_INPROC); if (FAILED(hr)) { return false; } CComPtr<IDispatch> spEventDisp; hr = spFactory->CreateEvent(CComBSTR(ObjClassID), CComBSTR(L"Google.Desktop.File"), &spEventDisp); if (FAILED(hr)) { return false; } CComQIPtr<IGoogleDesktopSearchEvent> spEvent(spEventDisp); ATLASSERT(spEventDisp && spEvent); if (spEvent == NULL) { return false; } if (SUCCEEDED(hr)) { hr = spEvent->AddProperty(CComBSTR(L"format"), CComVariant("text/plain")); } if (SUCCEEDED(hr)) { hr = spEvent->AddProperty(CComBSTR(L"content"), CComVariant(Content.c_str())); } if (SUCCEEDED(hr)) { hr = spEvent->AddProperty(CComBSTR(L"uri"), CComVariant(Path.c_str())); } if (SUCCEEDED(hr)) { hr = spEvent->AddProperty(CComBSTR(L"last_modified_time"), CComVariant(ModifiedTime, VT_DATE)); } if (FAILED(hr)) { return false; } hr = spEvent->Send(EventFlagIndexable); if (FAILED(hr)) { return false; } } // Uninit COM if (SUCCEEDED(hr_coinit)) { CoUninitialize(); } return true; } unsigned long LarGDSPlugin::GetConversationID(string Identifier) { // Default to a timeout of 15 minutes. return GetConversationID(Identifier, 900); } unsigned long LarGDSPlugin::GetConversationID(string Identifier, int Timeout) { bool CreateNewConversationID = false; // Check if there are any conversations with OtherPartyName in memory if (Conversations.find(Identifier) == Conversations.end()) { // If no, flag for new ConversationID creation CreateNewConversationID = true; } if (CreateNewConversationID == false) { // Check to see if nothing has been said within the last 15 minutes if (difftime(time(0), Conversations[Identifier].LastMessageTime) > Timeout) { // If it has been longer than 15 minutes, flag for new ConversationID creation CreateNewConversationID = true; } } if (CreateNewConversationID == true) { // If flagged to create a new ConversationID, randomize it. srand(static_cast<unsigned>(time(0))); ConversationStruct Conversation; Conversation.ConversationID = (unsigned long) rand(); Conversations[Identifier] = Conversation; } Conversations[Identifier].LastMessageTime = time(0); return Conversations[Identifier].ConversationID; }
[ [ [ 1, 302 ] ] ]
943ccb56569a81e443043016764c25fe59fee924
968aa9bac548662b49af4e2b873b61873ba6f680
/imgtools/romtools/rofsbuild/r_driveutl.cpp
1c9f411c96cc37a75f6d6d0a79ab17d7abc4fbf0
[]
no_license
anagovitsyn/oss.FCL.sftools.dev.build
b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3
f458a4ce83f74d603362fe6b71eaa647ccc62fee
refs/heads/master
2021-12-11T09:37:34.633852
2010-12-01T08:05:36
2010-12-01T08:05:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,279
cpp
/* * Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of 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: * @internalComponent * @released * Driveimage general utilities. * */ #include <string.h> #include <stdlib.h> #include <time.h> #include <e32err.h> #include "h_utl.h" #include "r_driveutl.h" /** Derive log file name from the given driveobey file name(it could be absolute path) and update with .log extn. Checks the validity of driveobey file name before creating the log file name. @param adriveobeyFileName - Drive obey file. @param &apadlogfile - Log file name from command line. @return - returns 'ErrorNone' if log file created, otherwise returns Error. */ string Getlogfile(char *aDriveObeyFileName,const string &CmdLogFile) { string strLogfile(CmdLogFile); if(strLogfile.size() > 0 && strLogfile[strLogfile.size()-1] != '\\' && strLogfile[strLogfile.size()-1] != '/') return strLogfile; if(!(*aDriveObeyFileName)) return string(""); // Validate the user entered driveoby file name. char* logFile = (char*)aDriveObeyFileName; #ifdef __LINUX__ logFile = strrchr(logFile,'/'); #else while(*logFile) { if(*logFile == '/') *logFile = '\\'; logFile++; } logFile = (char*)aDriveObeyFileName; logFile = strrchr(logFile,'\\'); #endif if(logFile) ++logFile; else logFile = (char*)aDriveObeyFileName; TInt len = strlen(logFile); if(!len) return string(""); // Create the log file name. strLogfile += logFile; strLogfile += ".LOG"; return strLogfile; } /** Time Stamp for Log file. */ TAny GetLocalTime(TAny) { struct tm *aNewTime = NULL; time_t aTime = 0; time(&aTime); aNewTime = localtime(&aTime); /* Print the local time as a string */ if(aNewTime) Print(ELog,"%s\n", asctime(aNewTime)); else Print(ELog,"Error : Getting Local Time\n"); }
[ "none@none", "[email protected]" ]
[ [ [ 1, 34 ], [ 36, 38 ], [ 40, 40 ], [ 45, 45 ], [ 47, 50 ], [ 69, 70 ], [ 72, 73 ], [ 76, 76 ], [ 78, 96 ] ], [ [ 35, 35 ], [ 39, 39 ], [ 41, 44 ], [ 46, 46 ], [ 51, 68 ], [ 71, 71 ], [ 74, 75 ], [ 77, 77 ] ] ]
01db906d3e77268949c9d088bf225cce03f1bfc9
a36d7a42310a8351aa0d427fe38b4c6eece305ea
/core_billiard/GeometryFactoryImp.h
4d582861cc3de9883f70b0e36cecc8d0212a72f9
[]
no_license
newpolaris/mybilliard01
ca92888373c97606033c16c84a423de54146386a
dc3b21c63b5bfc762d6b1741b550021b347432e8
refs/heads/master
2020-04-21T06:08:04.412207
2009-09-21T15:18:27
2009-09-21T15:18:27
39,947,400
0
0
null
null
null
null
UTF-8
C++
false
false
1,470
h
#pragma once namespace my_render_imp { class GeometryFactoryImp : IMPLEMENTS_INTERFACE( GeometryFactory ) { public: // from GeometryFactory virtual Geometry * createGeometry( domGeometryRef ) OVERRIDE; virtual Geometry * find( wstring id ) OVERRIDE; virtual bool destroyGeometry( Geometry * ) OVERRIDE; public: GeometryFactoryImp( InstanceResolver * instanceResolver ); private: // create geometry bool readGeometryMesh( GeometryMesh *, domMeshRef ); bool readGeometryConvexMesh( GeometryMesh *, domConvex_meshRef ) { return false; } bool readGeometrySpline( GeometryMesh *, domSplineRef ) { return false; } bool readGeometryMeshPrimitiveVertices( GeometryMeshPrimitiveImp *, const domInputLocalOffset_Array &, const domP_Array & ); private: // create geometry Geometry * createGeometry( wstring id, wstring name, wstring uri ); bool isAlreadyCreated( wstring id ); private: // create geometry mesh primitive GeometryMeshPrimitiveImp * createGeometryMeshPrimitive( wstring name, size_t triangleCount, wstring materialName, int primitiveTypeID ); bool destroyGeometryMeshPrimitive( GeometryMeshPrimitive * prim ); private: typedef list< GeometryPtr > Geometries; Geometries geometries_; typedef list< GeometryMeshPrimitivePtr > Primitives; Primitives primitives_; private: // Pimpl idiom without any member variables. struct Pimpl; }; } // namespace
[ "wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635" ]
[ [ [ 1, 41 ] ] ]
0876c908d5484ec19996ec3cbf9b97dcdc1ac74f
8253a563255bdd5797873c9f80d2a48a690c5bb0
/configlib/dbmsjdbc/src/native/DbmsStatement.h
15410a9852aca1bf1b0337cc0a36918e62303ebb
[]
no_license
SymbianSource/oss.FCL.sftools.depl.swconfigmdw
4e6ab52bf564299f1ed7036755cf16321bd656ee
d2feb88baf0e94da760738fc3b436c3d5d1ff35f
refs/heads/master
2020-03-28T10:16:11.362176
2010-11-06T14:59:14
2010-11-06T14:59:14
73,009,096
0
0
null
null
null
null
UTF-8
C++
false
false
791
h
// Copyright (c) 1998-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // #ifndef __DbmsStatement_h__ #define __DbmsStatement_h__ #include <e32std.h> #include <d32dbms.h> #include "DbmsConnection.h" class DbmsStatement { public: DbmsConnection* iConnection; RDbView iView; public: DbmsStatement(DbmsConnection* aConnection); ~DbmsStatement(); void Close(); }; #endif
[ "none@none" ]
[ [ [ 1, 35 ] ] ]
31f36897b9ba260e714811d043528f306dcf0dce
6629f18d84dc8d5a310b95fedbf5be178b00da92
/SDK-2008-05-27/foobar2000/SDK/ui.h
dbb57cafcc61edfbc19552334fa206f5ecdf11f6
[]
no_license
thenfour/WMircP
317f7b36526ebf8061753469b10f164838a0a045
ad6f4d1599fade2ae4e25656a95211e1ca70db31
refs/heads/master
2021-01-01T17:42:20.670266
2008-07-11T03:10:48
2008-07-11T03:10:48
16,931,152
3
0
null
null
null
null
UTF-8
C++
false
false
8,286
h
#ifndef _WINDOWS #error PORTME #endif //! Entrypoint service for user interface modules. Implement when registering an UI module. Do not call existing implementations; only core enumerates / dispatches calls. To control UI behaviors from other components, use ui_control API. \n //! Use user_interface_factory_t<> to register, e.g static user_interface_factory_t<myclass> g_myclass_factory; class NOVTABLE user_interface : public service_base { public: //!HookProc usage: \n //! in your windowproc, call HookProc first, and if it returns true, return LRESULT value it passed to you typedef BOOL (WINAPI * HookProc_t)(HWND wnd,UINT msg,WPARAM wp,LPARAM lp,LRESULT * ret); //! Retrieves name (UTF-8 null-terminated string) of the UI module. virtual const char * get_name()=0; //! Initializes the UI module - creates the main app window, etc. Failure should be signaled by appropriate exception (std::exception or a derivative). virtual HWND init(HookProc_t hook)=0; //! Deinitializes the UI module - destroys the main app window, etc. virtual void shutdown()=0; //! Activates main app window. virtual void activate()=0; //! Minimizes/hides main app window. virtual void hide()=0; //! Returns whether main window is visible / not minimized. Used for activate/hide command. virtual bool is_visible() = 0; //! Retrieves GUID of your implementation, to be stored in configuration file etc. virtual GUID get_guid() = 0; //! Overrides statusbar text with specified string. The parameter is a null terminated UTF-8 string. The override is valid until another override_statusbar_text() call or revert_statusbar_text() call. virtual void override_statusbar_text(const char * p_text) = 0; //! Disables statusbar text override. virtual void revert_statusbar_text() = 0; //! Shows now-playing item somehow (e.g. system notification area popup). virtual void show_now_playing() = 0; static bool g_find(service_ptr_t<user_interface> & p_out,const GUID & p_guid); FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(user_interface); }; template<typename T> class user_interface_factory : public service_factory_single_t<T> {}; //! Interface class allowing you to override UI statusbar text. There may be multiple callers trying to override statusbar text; backend decides which one succeeds so you will not always get what you want. Statusbar text override is automatically cancelled when the object is released.\n //! Use ui_control::override_status_text_create() to instantiate. //! Implemented by core. Do not reimplement. class NOVTABLE ui_status_text_override : public service_base { public: //! Sets statusbar text to specified UTF-8 null-terminated string. virtual void override_text(const char * p_message) = 0; //! Cancels statusbar text override. virtual void revert_text() = 0; FB2K_MAKE_SERVICE_INTERFACE(ui_status_text_override,service_base); }; //! Serivce providing various UI-related commands. Implemented by core; do not reimplement. //! Instantiation: use static_api_ptr_t<ui_control>. class NOVTABLE ui_control : public service_base { public: //! Returns whether primary UI is visible/unminimized. virtual bool is_visible()=0; //! Activates/unminimizes main UI. virtual void activate()=0; //! Hides/minimizese main UI. virtual void hide()=0; //! Retrieves main GUI icon, to use as window icon etc. Returned handle does not need to be freed. virtual HICON get_main_icon()=0; //! Loads main GUI icon, version with specified width/height. Returned handle needs to be freed with DestroyIcon when you are done using it. virtual HICON load_main_icon(unsigned width,unsigned height) = 0; //! Activates preferences dialog and navigates to specified page. See also: preference_page API. virtual void show_preferences(const GUID & p_page) = 0; //! Instantiates ui_status_text_override service, that can be used to display status messages. //! @param p_out receives new ui_status_text_override instance. //! @returns true on success, false on failure (out of memory / no GUI loaded / etc) virtual bool override_status_text_create(service_ptr_t<ui_status_text_override> & p_out) = 0; FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ui_control); }; //! Service called from the UI when some object is dropped into the UI. Usable for modifying drag&drop behaviors such as adding custom handlers for object types other than supported media files.\n //! Implement where needed; use ui_drop_item_callback_factory_t<> template to register, e.g. static ui_drop_item_callback_factory_t<myclass> g_myclass_factory. class NOVTABLE ui_drop_item_callback : public service_base { public: //! Called when an object was dropped; returns true if the object was processed and false if not. virtual bool on_drop(interface IDataObject * pDataObject) = 0; //! Tests whether specified object type is supported by this ui_drop_item_callback implementation. Returns true and sets p_effect when it's supported; returns false otherwise. \n //! See IDropTarget::DragEnter() documentation for more information about p_effect values. virtual bool is_accepted_type(interface IDataObject * pDataObject, DWORD * p_effect)=0; //! Static helper, calls all existing implementations appropriately. See on_drop(). static bool g_on_drop(interface IDataObject * pDataObject); //! Static helper, calls all existing implementations appropriately. See is_accepted_type(). static bool g_is_accepted_type(interface IDataObject * pDataObject, DWORD * p_effect); FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ui_drop_item_callback); }; template<class T> class ui_drop_item_callback_factory_t : public service_factory_single_t<T> {}; class ui_selection_callback; class NOVTABLE ui_selection_holder : public service_base { public: virtual void set_selection(metadb_handle_list_cref data) = 0; virtual void set_playlist_selection_tracking() = 0; virtual void set_playlist_tracking() = 0; //! Sets selected items and type of selection holder. //! @param type Specifies type of selection. Values same as contextmenu_item caller IDs. virtual void set_selection_ex(metadb_handle_list_cref data, const GUID & type) = 0; FB2K_MAKE_SERVICE_INTERFACE(ui_selection_holder,service_base); }; class NOVTABLE ui_selection_manager : public service_base { public: //! Retrieves current selection. virtual void get_selection(pfc::list_base_t<metadb_handle_ptr> & p_selection) = 0; //! Registers a callback. It is recommended to use ui_selection_callback_impl_base class instead of calling this directly. virtual void register_callback(ui_selection_callback * p_callback) = 0; //! Unregisters a callback. It is recommended to use ui_selection_callback_impl_base class instead of calling this directly. virtual void unregister_callback(ui_selection_callback * p_callback) = 0; virtual ui_selection_holder::ptr acquire() = 0; //! Retrieves type of the active selection holder. Values same as contextmenu_item caller IDs. virtual GUID get_selection_type() = 0; FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ui_selection_manager); }; class ui_selection_callback { public: virtual void on_selection_changed(const pfc::list_base_const_t<metadb_handle_ptr> & p_selection) = 0; protected: ui_selection_callback() {} ~ui_selection_callback() {} }; //! ui_selection_callback implementation helper with autoregistration - do not instantiate statically class ui_selection_callback_impl_base : public ui_selection_callback { protected: ui_selection_callback_impl_base(bool activate = true) : m_active() {ui_selection_callback_activate(activate);} ~ui_selection_callback_impl_base() {ui_selection_callback_activate(false);} void ui_selection_callback_activate(bool state = true) { if (state != m_active) { m_active = state; static_api_ptr_t<ui_selection_manager> api; if (state) api->register_callback(this); else api->unregister_callback(this); } } //avoid pure virtual function calls in rare cases - provide a dummy implementation void on_selection_changed(const pfc::list_base_const_t<metadb_handle_ptr> & p_selection) {} PFC_CLASS_NOT_COPYABLE_EX(ui_selection_callback_impl_base); private: bool m_active; };
[ "carl@72871cd9-16e1-0310-933f-800000000000" ]
[ [ [ 1, 167 ] ] ]
80c11382fd38c36087fc28cdee1391d4e74860f9
021e8c48a44a56571c07dd9830d8bf86d68507cb
/build/vtk/vtkQtTableRepresentation.h
9cb35d151f5896714b04ab98c3c219fbb807075c
[ "BSD-3-Clause" ]
permissive
Electrofire/QdevelopVset
c67ae1b30b0115d5c2045e3ca82199394081b733
f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5
refs/heads/master
2021-01-18T10:44:01.451029
2011-05-01T23:52:15
2011-05-01T23:52:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,423
h
/*========================================================================= Program: Visualization Toolkit Module: vtkQtTableRepresentation.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ // .NAME vtkQtTableRepresentation - set up a vtkTable in a Qt model // // .SECTION Description // // This class is a wrapper around vtkQtTableModelAdapter. It // performs the following functions: // // <ul> // <li>Keep track of the key column, first data column, and last data column. // Populate the appropriate ivars on the Qt adapter. // <li>Assign colors to each of the data series using a vtkLookupTable. // A default lookup table is provided or the user can supply one // using SetColorTable(). // </ul> // // The user must supply the following items: // <ul> // <li>the name of the column that contains the series names, // <li>the names of the first and last data columns // (this range should not contain the key column), and // <li>(optionally) a vtkLookupTable to use when assigning colors. // </ul> // // .SECTION Caveats // // Call SetInputConnection with a table connection // BEFORE the representation is added to a view or strange things // may happen, including segfaults. #ifndef __vtkQtTableRepresentation_h #define __vtkQtTableRepresentation_h #include "QVTKWin32Header.h" #include "vtkDataRepresentation.h" class vtkDoubleArray; class vtkLookupTable; class vtkQtTableModelAdapter; // ---------------------------------------------------------------------- class QVTK_EXPORT vtkQtTableRepresentation : public vtkDataRepresentation { public: vtkTypeMacro(vtkQtTableRepresentation, vtkDataRepresentation); void PrintSelf(ostream &os, vtkIndent indent); // Description: // Set/get the lookup table that will be used to determine colors // for each series. The table's range should be [0, 1). void SetColorTable(vtkLookupTable *t); vtkGetObjectMacro(ColorTable, vtkLookupTable); // Description: // Set/get the name of the column that contains series names. This // must be called BEFORE the representation is added to a view. void SetKeyColumn(const char* col); char* GetKeyColumn(); // Description: // Set/get the name of the first data column. This must be called // BEFORE the representation is added to a view. vtkSetStringMacro(FirstDataColumn); vtkGetStringMacro(FirstDataColumn); // Description: // Set/get the name of the last data column. This must be called // BEFORE the representation is added to a view. vtkSetStringMacro(LastDataColumn); vtkGetStringMacro(LastDataColumn); protected: vtkQtTableRepresentation(); ~vtkQtTableRepresentation(); // Description: // Update the table representation void UpdateTable(); vtkSetStringMacro(KeyColumnInternal); vtkGetStringMacro(KeyColumnInternal); // ---------------------------------------------------------------------- vtkQtTableModelAdapter *ModelAdapter; vtkLookupTable *ColorTable; vtkDoubleArray *SeriesColors; char *KeyColumnInternal; char *FirstDataColumn; char *LastDataColumn; // Description: // Prepare the input connections to this representation. virtual int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); virtual void ResetModel(); virtual void CreateSeriesColors(); // Description: // This should set the model type to DATA, METADATA or FULL // depending on what you want. virtual void SetModelType() { }; private: vtkQtTableRepresentation(const vtkQtTableRepresentation &); void operator=(const vtkQtTableRepresentation &); }; #endif
[ "ganondorf@ganondorf-VirtualBox.(none)" ]
[ [ [ 1, 130 ] ] ]
873231b6a22cb9a6871f8c04bf5f049452d6ca3f
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/UIEventHandler.h
890fa11332a862cace38e09663b94d90b2881e0d
[]
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
554
h
#pragma once #ifndef __HALAK_UIEVENTHANDLER_H__ #define __HALAK_UIEVENTHANDLER_H__ # include <Halak/FWD.h> # include <Halak/UIElement.h> namespace Halak { class UIEventHandler : public UIElement { public: virtual ~UIEventHandler(); virtual bool Invoke(const UIEventArgs& args) = 0; virtual bool IsSequence() const; protected: UIEventHandler(); }; } # include <Halak/UIEventHandler.inl> #endif
[ [ [ 1, 26 ] ] ]
c1cdfc3386c5f188516d8b44762e5ed786dafa18
23017336d25e6ec49c4a51f11c1b3a3aa10acf22
/csc3750/prog4/Face.cpp
bb74473774e43ba809c583eca16c990f629fa76b
[]
no_license
tjshaffer21/School
5e7681c96e0c10966fc7362931412c4244507911
4aa5fc3a8bbbbb8d46d045244e8a7f84e71c768f
refs/heads/master
2020-05-27T19:05:06.422314
2011-05-17T19:55:40
2011-05-17T19:55:40
1,681,224
1
1
null
2017-07-29T13:35:54
2011-04-29T15:36:55
C++
UTF-8
C++
false
false
6,539
cpp
/** * Face * Thomas Shaffer * 16 September 2009 * Face class takes a select number of vertices (three) and connects them * using either DDA algorithm or Bresenham's algorithm. */ #include "Face.h" /** * Face * Constructor that creates an empty face object. * Preconditions: * None. * Postconditions: * Instantiates private variables */ Face::Face() { vertices = new List<Vertex>(); } /** * ~Face * Deconstructor. * Preconditions: * None. * Postconditions: * Destroys the Face object. */ Face::~Face() { vertices->removeAll(); delete vertices; } /** * addVertex * Adds a vertex into the object's list of vertices. * Preconditions: * A pointer to the memory address of the vertex. * Postconditions: * The vertex is added into the list of vertices. */ void Face::addVertex( Vertex* vertex ) { vertices->add( vertex ); } /** * getVertices * Returns a list of vertices. * Preconditions: * None. * Postconditions: * Returns a list of vertices. */ List<Vertex>* Face::getVertices() { return vertices; } /** * render * Renders a face using either DDA or Bresenham's Algorithm. * Preconditions: * A pointer to the face object. * A pointer to the pixel object. */ void Face::render( Matrix* wnd, Pixel* pix ) { // Transform vertices from local to window. Vertex* vrt_wnd = vertices->get(1)->multiply(wnd); Vertex* vrt_wnd2 = vertices->get(2)->multiply(wnd); Vertex* vrt_wnd3 = vertices->get(3)->multiply(wnd); vrt_wnd->homogenize(); vrt_wnd2->homogenize(); vrt_wnd3->homogenize(); // Render //renderDDA( vrt_wnd, vrt_wnd2, pix ); //renderDDA( vrt_wnd2, vrt_wnd3, pix ); //renderDDA( vrt_wnd, vrt_wnd3, pix ); renderBresenham( vrt_wnd, vrt_wnd2, pix ); renderBresenham( vrt_wnd2, vrt_wnd3, pix ); renderBresenham( vrt_wnd, vrt_wnd3, pix ); delete vrt_wnd; delete vrt_wnd2; delete vrt_wnd3; } /** * renderDDA * Renders a line using the DDA algorithm. * Preconditions: * Two vertices. * A pixel object. * Postsconditions: * Connects two dots onto a screen. */ void Face::renderDDA(Vertex* v1, Vertex* v2, Pixel* pix ) { //Color color = Color( 1, 1, 1, 1 ); srand( time(NULL) ); // Obtain x and y for vertices. float y1 = v1->getY(); float y2 = v2->getY(); float x1 = v1->getX(); float x2 = v2->getX(); float dx = x2-x1; float dy = y2-y1; float m = dy/dx; // Obtain slope. float b = y2 - (m*x2); int y_curr = 0; int y_end = 0; int x_curr = 0; int x_end = 0; // Check if absolute value of slope > 1 or if x1 & x2 are equal. if ( fabs(m) > 1 || x1 == x2 ) { m = dx/dy; b = x2 - (m*y2); // If y1 > y2 then y_curr is y2, // else y_curr is y1 if ( y1 > y2 ) { y_curr = (int)(y2+0.5); y_end = (int)(y1+0.5); } else { y_curr = (int)(y1+0.5); y_end = (int)(y2+0.5); } // Loop over y. float x = (y_curr*m)+b; while( y_curr <= y_end ) { Color color = Color( ((float)rand())/RAND_MAX, ((float)rand())/RAND_MAX, ((float)rand())/RAND_MAX, 1 ); int xi = (int)(x+0.5); if (xi < 0) { xi = (int)(x-0.5); } pix->drawPixel( xi, y_curr, color ); y_curr++; x += m; } } else { // If y1 > y2 then y_curr is y2, // else y_curr is y1 if ( x1 > x2 ) { x_curr = (int)(x2+0.5); x_end = (int)(x1+0.5); } else { x_curr = (int)(x1+0.5); x_end = (int)(x2+0.5); } // Loop over x. float y = (m*x_curr)+b; while ( x_curr <= x_end ) { Color color = Color( ((float)rand())/RAND_MAX, ((float)rand())/RAND_MAX, ((float)rand())/RAND_MAX, 1 ); int yi = (int)(y+0.5); if ( yi < 0 ) { yi = (int)(y-0.5); } pix->drawPixel( x_curr, yi, color ); x_curr++; y += m; } } } /** * renderBresenham * Renders a line using the Bresenham algorithm. * Preconditions: * Two vertices. * A pixel object. * Postsconditions: * Connects two dots onto a screen. */ void Face::renderBresenham( Vertex* v1, Vertex* v2, Pixel* pix ) { Color color = Color( 1, 1, 1, 1 ); // Obtain x and y values. double x1 = v1->getX(); double y1 = v1->getY(); double x2 = v2->getX(); double y2 = v2->getY(); int dx = ((int)(x1+0.5)) - ((int)(x2+0.5)); int dy = ((int)(y2+0.5)) - ((int)(y1+0.5)); // Incremental values. int incx = 1; int incy = 1; int inc1, inc2; int fraction; int x, y; if ( dx < 0 ) { dx = -dx; } if ( dy < 0 ) { dy = -dy; } // Negate step size if x2/y2 < x1/y1 if ( x2 < x1 ) { incx = -1; } if ( y2 < y1 ) { incy = -1; } // Round x=((int)(x1+0.5)); y=((int)(y1+0.5)); if ( dx > dy ) { // Loop over x. pix->drawPixel( x, y, color ); fraction = 2*dy-dx; inc1 = 2*(dy-dx); inc2 = 2*dy; for( int i = 0; i < dx; i++ ) { if ( fraction >= 0 ) { y += incy; fraction += inc1; } else { fraction += inc2; } x += incx; pix->drawPixel( x, y, color ); } } else { // Loop over y. pix->drawPixel( x, y, color ); fraction = 2*dx-dy; inc1 = 2*(dx-dy); inc2 = 2*dx; for( int i = 0; i < dy; i++ ) { if ( fraction >= 0 ) { x += incx; fraction += inc1; } else { fraction += inc2; } y += incy; pix->drawPixel( x,y, color ); } } }
[ [ [ 1, 270 ] ] ]
39f089bc5b06fc7cf58e2b529c5ce2cb5054f82a
1193b8d2ab6bb40ce2adbf9ada5b3d1124f1abb3
/trunk/libsonetto/include/SonettoDatabase.h
cc50596b5c7aee2d7d92976cbd158b747194dd76
[]
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
4,951
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_DATABASE_H #define SONETTO_DATABASE_H #include <OgreSingleton.h> #include "SonettoPrerequisites.h" #include "SonettoSavemap.h" #include "SonettoScriptDataHandler.h" #include "SonettoMusic.h" #include "SonettoSoundSource.h" #include "SonettoSoundSet.h" namespace Sonetto { struct GameSystem { float textSize; float textAnimationSpeed; float textFadeInSpeed; float textFadeOutSpeed; float textHorizontalScale; float textVerticalSpacing; //Font * defaultFont; uint8 defaultColor; }; struct GroundType { IDVector defaultFootsteps; }; typedef std::vector<GroundType> GroundTypeVector; typedef std::map<uint32,IDVector> FootwearSounds; typedef std::vector<FootwearSounds> FootwearSoundsVector; class SONETTO_API Database : public Ogre::Singleton<Database> { public: Database() : mInitialized(false) {} ~Database(); void initialize(); /** Overrides standard Singleton retrieval @remarks Warning: These comments below were copied straight from Ogre3D code. Why do we do this? Well, it's because the Singleton implementation is in a .h file, which means it gets compiled into anybody who includes it. This is needed for the Singleton template to work, but we actually only want it compiled into the implementation of the class based on the Singleton, not all of them. If we don't change this, we get link errors when trying to use the Singleton-based class from an outside dll. @param This method just delegates to the template version anyway, but the implementation stays in this single compilation unit, preventing link errors. */ static Database &getSingleton(); /** Overrides standard Singleton retrieval @remarks Warning: These comments below were copied straight from Ogre3D code. Why do we do this? Well, it's because the Singleton implementation is in a .h file, which means it gets compiled into anybody who includes it. This is needed for the Singleton template to work, but we actually only want it compiled into the implementation of the class based on the Singleton, not all of them. If we don't change this, we get link errors when trying to use the Singleton-based class from an outside dll. @param This method just delegates to the template version anyway, but the implementation stays in this single compilation unit, preventing link errors. */ static Database *getSingletonPtr(); GameSystem system; Savemap savemap; MusicVector musics; SoundDefVector sounds; SoundSetVector soundSets; GroundTypeVector groundTypes; FootwearSoundsVector footwears; private: bool mInitialized; ScriptDataHandler mScriptDataHandler; }; } // namespace #endif
[ [ [ 1, 129 ] ] ]
29fd4f1ea6a7cda2f14949fbae9f55a20a2a2f56
8ad5d6836fe4ad3349929802513272db86d15bc3
/tests/lib/Damon/parseURL.cpp
ba3bdcd7e3956796bca9867e0431d9e325d6e748
[]
no_license
blytkerchan/arachnida
90a72c27f0c650a6fbde497896ef32186c0219e5
468f4ef6c35452de3ca026af42b8eedcef6e4756
refs/heads/master
2021-01-10T21:43:51.505486
2010-03-12T04:02:19
2010-03-12T04:02:42
2,203,393
0
1
null
null
null
null
UTF-8
C++
false
false
5,159
cpp
#include "parseURL.h" #include <Damon/Private/parseURL.h> namespace Tests { namespace Damon { CPPUNIT_TEST_SUITE_REGISTRATION(parseURL); void parseURL::setUp() { /* no-op */ } void parseURL::tearDown() { /* no-op */ } void parseURL::tryURL01() { std::string protocol; std::string server; boost::uint16_t port; std::string resource; std::string username; std::string password; boost::tie(protocol, server, port, resource, username, password) = ::Damon::Private::parseURL("http://127.0.0.1/"); CPPUNIT_ASSERT(protocol == "http"); CPPUNIT_ASSERT(server == "127.0.0.1"); CPPUNIT_ASSERT(port == 80); CPPUNIT_ASSERT(resource == "/"); CPPUNIT_ASSERT(username == ""); CPPUNIT_ASSERT(password == ""); } void parseURL::tryURL02() { std::string protocol; std::string server; boost::uint16_t port; std::string resource; std::string username; std::string password; boost::tie(protocol, server, port, resource, username, password) = ::Damon::Private::parseURL("http://127.0.0.1"); CPPUNIT_ASSERT(protocol == "http"); CPPUNIT_ASSERT(server == "127.0.0.1"); CPPUNIT_ASSERT(port == 80); CPPUNIT_ASSERT(resource == "/"); CPPUNIT_ASSERT(username == ""); CPPUNIT_ASSERT(password == ""); } void parseURL::tryURL03() { std::string protocol; std::string server; boost::uint16_t port; std::string resource; std::string username; std::string password; boost::tie(protocol, server, port, resource, username, password) = ::Damon::Private::parseURL("127.0.0.1"); CPPUNIT_ASSERT(protocol == "http"); CPPUNIT_ASSERT(server == "127.0.0.1"); CPPUNIT_ASSERT(port == 80); CPPUNIT_ASSERT(resource == "/"); CPPUNIT_ASSERT(username == ""); CPPUNIT_ASSERT(password == ""); } void parseURL::tryURL04() { std::string protocol; std::string server; boost::uint16_t port; std::string resource; std::string username; std::string password; boost::tie(protocol, server, port, resource, username, password) = ::Damon::Private::parseURL("127.0.0.1:8080"); CPPUNIT_ASSERT(protocol == "http"); CPPUNIT_ASSERT(server == "127.0.0.1"); CPPUNIT_ASSERT(port == 8080); CPPUNIT_ASSERT(resource == "/"); CPPUNIT_ASSERT(username == ""); CPPUNIT_ASSERT(password == ""); } void parseURL::tryURL05() { std::string protocol; std::string server; boost::uint16_t port; std::string resource; std::string username; std::string password; boost::tie(protocol, server, port, resource, username, password) = ::Damon::Private::parseURL("https://127.0.0.1"); CPPUNIT_ASSERT(protocol == "https"); CPPUNIT_ASSERT(server == "127.0.0.1"); CPPUNIT_ASSERT(port == 443); CPPUNIT_ASSERT(resource == "/"); CPPUNIT_ASSERT(username == ""); CPPUNIT_ASSERT(password == ""); } void parseURL::tryURL06() { std::string protocol; std::string server; boost::uint16_t port; std::string resource; std::string username; std::string password; boost::tie(protocol, server, port, resource, username, password) = ::Damon::Private::parseURL("http://127.0.0.1:8080/"); CPPUNIT_ASSERT(protocol == "http"); CPPUNIT_ASSERT(server == "127.0.0.1"); CPPUNIT_ASSERT(port == 8080); CPPUNIT_ASSERT(resource == "/"); CPPUNIT_ASSERT(username == ""); CPPUNIT_ASSERT(password == ""); } void parseURL::tryURL07() { std::string protocol; std::string server; boost::uint16_t port; std::string resource; std::string username; std::string password; boost::tie(protocol, server, port, resource, username, password) = ::Damon::Private::parseURL("http://127.0.0.1:8080"); CPPUNIT_ASSERT(protocol == "http"); CPPUNIT_ASSERT(server == "127.0.0.1"); CPPUNIT_ASSERT(port == 8080); CPPUNIT_ASSERT(resource == "/"); CPPUNIT_ASSERT(username == ""); CPPUNIT_ASSERT(password == ""); } void parseURL::tryURL08() { std::string protocol; std::string server; boost::uint16_t port; std::string resource; std::string username; std::string password; boost::tie(protocol, server, port, resource, username, password) = ::Damon::Private::parseURL("http://[email protected]:8080"); CPPUNIT_ASSERT(protocol == "http"); CPPUNIT_ASSERT(server == "127.0.0.1"); CPPUNIT_ASSERT(port == 8080); CPPUNIT_ASSERT(resource == "/"); CPPUNIT_ASSERT(username == "user"); CPPUNIT_ASSERT(password == ""); } void parseURL::tryURL09() { std::string protocol; std::string server; boost::uint16_t port; std::string resource; std::string username; std::string password; boost::tie(protocol, server, port, resource, username, password) = ::Damon::Private::parseURL("http://user:[email protected]:8080"); CPPUNIT_ASSERT(protocol == "http"); CPPUNIT_ASSERT(server == "127.0.0.1"); CPPUNIT_ASSERT(port == 8080); CPPUNIT_ASSERT(resource == "/"); CPPUNIT_ASSERT(username == "user"); CPPUNIT_ASSERT(password == "password"); } } }
[ [ [ 1, 170 ] ] ]
68dea123f389ec6003df21edeae7b3d698af03d0
28aa891f07cc2240c771b5fb6130b1f4025ddc84
/extern/oolua/unit_tests/cpp_classes/cpp_push.h
8e93f06e14a7456eee47bf2796d6be5603af3523
[ "MIT" ]
permissive
Hincoin/mid-autumn
e7476d8c9826db1cc775028573fc01ab3effa8fe
5271496fb820f8ab1d613a1c2355504251997fef
refs/heads/master
2021-01-10T19:17:01.479703
2011-12-19T14:32:51
2011-12-19T14:32:51
34,730,620
0
0
null
null
null
null
UTF-8
C++
false
false
960
h
#ifndef CPP_PUSH_H_ # define CPP_PUSH_H_ class Push { public: Push():i_(0),pc_int(new int(0)){} ~Push(){delete pc_int;} //Push(Push const & rhs):i_(rhs.i_){} Push& ref(){return *this;} Push const & ref_const(){return *this;} Push* ptr(){return this;} Push const* ptr_const(){return this;} //int const * & ref_ptr_const(){return pc_int;} //int const*const& ref_const_ptr_const(){return pc_int;} Push const* /*const*/ const_ptr_const(){return this;} void const_func()const{} int int_value(){return i_;} int& int_ref(){return i_;} int* int_ptr(){return &i_;} //int*& int_ref_ptr(){return &i_;} int const& int_ref_const(){return i_;} //int *const& int_ref_const_ptr(){return pc_int;} int const *const& int_ref_const_ptr_const(){return pc_int;} int const*& int_ref_ptr_const(){return pc_int;} int i_; Push(Push const & ); Push& operator=(Push const&); private: int const* pc_int; }; #endif//CPP_PUSH_H_
[ "luozhiyuan@ea6f400c-e855-0410-84ee-31f796524d81" ]
[ [ [ 1, 35 ] ] ]
bcc622c82589ec0682f98c3b191ea281b699f1d7
d9a78f212155bb978f5ac27d30eb0489bca87c3f
/PB/src/PbLib/GeneratedFiles/Release/moc_pbvaluetable.cpp
254238576039fa15d2b02e003a6b726664a89504
[]
no_license
marchon/pokerbridge
1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c
97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9
refs/heads/master
2021-01-10T07:15:26.496252
2010-05-17T20:01:29
2010-05-17T20:01:29
36,398,892
0
0
null
null
null
null
UTF-8
C++
false
false
1,917
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'pbvaluetable.h' ** ** Created: Sun 14. Mar 04:04:21 2010 ** by: The Qt Meta Object Compiler version 61 (Qt 4.5.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "stdafx.h" #include "..\..\pbvaluetable.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'pbvaluetable.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 61 #error "This file was generated using the moc from 4.5.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_PBValueTable[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0 // eod }; static const char qt_meta_stringdata_PBValueTable[] = { "PBValueTable\0" }; const QMetaObject PBValueTable::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_PBValueTable, qt_meta_data_PBValueTable, 0 } }; const QMetaObject *PBValueTable::metaObject() const { return &staticMetaObject; } void *PBValueTable::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_PBValueTable)) return static_cast<void*>(const_cast< PBValueTable*>(this)); return QObject::qt_metacast(_clname); } int PBValueTable::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
[ [ [ 1, 64 ] ] ]
d226cc221ab2bd021ee034d6734982556ed75bb0
629e4fdc23cb90c0144457e994d1cbb7c6ab8a93
/lib/threadpool/tque.h
1def5e334de554f9587675321c1f6e57c411a4ee
[]
no_license
akin666/ice
4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2
7cfd26a246f13675e3057ff226c17d95a958d465
refs/heads/master
2022-11-06T23:51:57.273730
2011-12-06T22:32:53
2011-12-06T22:32:53
276,095,011
0
0
null
null
null
null
UTF-8
C++
false
false
1,021
h
/* * tque.h * * Created on: 22.10.2011 * Author: akin */ #ifndef TQUE_H_ #define TQUE_H_ #include <iostream> #include <deque> #include <fixes/thread> namespace ice { template <class tclass> class TQue { protected: std::mutex mutex; std::condition_variable condition; std::deque< tclass > data; unsigned int data_count; public: TQue() : data_count(0) {} virtual ~TQue(){} // blocking, but pushes as fast as possible void push( tclass work ); // blocking. tclass pop(); }; template <class tclass> void TQue<tclass>::push( tclass work ) { std::lock_guard<std::mutex> lock(mutex); data.push_back( work ); ++data_count; condition.notify_one(); } template <class tclass> tclass TQue<tclass>::pop() { std::unique_lock<std::mutex> lock(mutex); while( data.empty() ) { condition.wait(lock); } tclass popped = data.front(); data.pop_front(); --data_count; return popped; } } /* namespace ice */ #endif /* TQUE_H_ */
[ "akin@lich" ]
[ [ [ 1, 66 ] ] ]
ab1f98873a1f467289e710d58df5db6c35ea3d4b
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Framework/IEffectParameter.h
ba64921b32b21dd216c04420a5a9ba90d7355dd4
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,598
h
/*******************************************************************************/ /** * @file IEffectParameter.h.<br> * * @brief エフェクトパラメータインターフェース定義.<br> * * @date 2008/10/27.<br> * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #ifndef _IEFFECTPARAMETER_H_ #define _IEFFECTPARAMETER_H_ #include "Define/Define.h" /** * @brief エフェクトパラメータインターフェース. */ class IEffectParameter { protected: /** * @brief デストラクタ<br> * * @param[in] なし. */ virtual ~IEffectParameter() {} public: /** * @brief 浮動小数点パラメータを設定する<br> * * @param[in] name パラメータ名. * @param[in] f パラメータ. * @return なし. */ virtual void SetParameter( const char* name, float f ) = 0; /** * @brief 浮動小数点パラメータの配列を設定する<br> * * @param[in] name パラメータ名. * @param[in] count 要素数. * @param[in] f パラメータ配列のポインタ. * @return なし. */ virtual void SetParameter( const char* name, int count, float* fv ) = 0; /** * @brief 3次元ベクトル型のパラメータの配列を設定する<br> * * @param[in] name パラメータ名. * @param[in] v パラメータ. * @return なし. */ virtual void SetParameter( const char* name, const Vector3& v ) = 0; /** * @brief カラー型のパラメータの配列を設定する<br> * * @param[in] name パラメータ名. * @param[in] c パラメータ. * @return なし. */ virtual void SetParameter( const char* name, const Color4& c ) = 0; /** * @brief 行列型のパラメータの配列を設定する<br> * * @param[in] name パラメータ名. * @param[in] m パラメータ. * @return なし. */ virtual void SetParameter( const char* name, const Matrix4& m ) = 0; /** * @brief テクスチャのパラメータを設定する<br> * * @param[in] name パラメータ名. * @param[in] id テクスチャID. * @return なし. */ virtual void SetParameter( const char* name, TextureID id ) = 0; /** * @brief 座標変換行列を設定する<br> * * @param[in] model モデリング変換行列. * @return なし. */ virtual void SetModelViewProjMatrix( const Matrix4& model ) = 0; /** * @brief 座標変換行列を設定する<br> * * @param[in] model モデリング変換行列 * @return なし. */ virtual void SetTransform( const Matrix4& model ) = 0; /** * @brief 視野変換行列のライト位置を設定<br> * * @param[in] lightpos ライト位置. * @return なし. */ virtual void SetLightPositionEye( const Vector3& lightpos ) = 0; /** * @brief 環境光カラーを設定<br> * * @param[in] color ライト色. * @return なし. */ virtual void SetAmbientLightColor( const Color4& color ) = 0; /** * @brief 拡散反射光カラーを設定<br> * * @param[in] color ライト色. * @return なし. */ virtual void SetDiffuseLightColor( const Color4& color ) = 0; /** * @brief 鏡面反射光カラーを設定<br> * * @param[in] color ライト色. * @return なし. */ virtual void SetSpecularLightColor( const Color4& color ) = 0; }; #endif /*===== EOF ==================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 142 ] ] ]
d3b189b86a1554be561fc0e1199d700abcfaddab
3472e587cd1dff88c7a75ae2d5e1b1a353962d78
/ytk_bak/sqlitebrowser/debug/moc_edittableform.cpp
82da8e025686302e2746a66b8730f30ae8994b1d
[]
no_license
yewberry/yewtic
9624d05d65e71c78ddfb7bd586845e107b9a1126
2468669485b9f049d7498470c33a096e6accc540
refs/heads/master
2021-01-01T05:40:57.757112
2011-09-14T12:32:15
2011-09-14T12:32:15
32,363,059
0
0
null
null
null
null
UTF-8
C++
false
false
3,116
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'edittableform.h' ** ** Created: Sun Jan 3 14:58:44 2010 ** by: The Qt Meta Object Compiler version 61 (Qt 4.5.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../edittableform.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'edittableform.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 61 #error "This file was generated using the moc from 4.5.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_editTableForm[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 8, 12, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors // slots: signature, parameters, type, tag, flags 31, 15, 14, 14, 0x0a, 68, 14, 14, 14, 0x0a, 85, 14, 14, 14, 0x0a, 99, 14, 14, 14, 0x0a, 111, 14, 14, 14, 0x0a, 122, 14, 14, 14, 0x0a, 136, 14, 14, 14, 0x0a, 160, 14, 14, 14, 0x09, 0 // eod }; static const char qt_meta_stringdata_editTableForm[] = { "editTableForm\0\0thedb,tableName\0" "setActiveTable(DBBrowserDB*,QString)\0" "populateFields()\0renameTable()\0" "editField()\0addField()\0removeField()\0" "fieldSelectionChanged()\0languageChange()\0" }; const QMetaObject editTableForm::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_editTableForm, qt_meta_data_editTableForm, 0 } }; const QMetaObject *editTableForm::metaObject() const { return &staticMetaObject; } void *editTableForm::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_editTableForm)) return static_cast<void*>(const_cast< editTableForm*>(this)); if (!strcmp(_clname, "Ui::editTableForm")) return static_cast< Ui::editTableForm*>(const_cast< editTableForm*>(this)); return QDialog::qt_metacast(_clname); } int editTableForm::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: setActiveTable((*reinterpret_cast< DBBrowserDB*(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 1: populateFields(); break; case 2: renameTable(); break; case 3: editField(); break; case 4: addField(); break; case 5: removeField(); break; case 6: fieldSelectionChanged(); break; case 7: languageChange(); break; default: ; } _id -= 8; } return _id; } QT_END_MOC_NAMESPACE
[ "yew1998@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86" ]
[ [ [ 1, 93 ] ] ]
50ca3a849dc91359c8f9ea89daa5f3ea656b8425
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/ScExec/PGM_I.CPP
528f742643501e0c5a9ff0a7e7b48fdd66c5acd8
[]
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
57,323
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #include "sc_defs.h" #include "gpfuncs.h" #define __PGM_I_CPP #include "pgm_e.h" #include "vectors.h" #include "errorlog.h" #include "optimize.h" #include "executiv.h" #include "ndtree.h" #include "pgm_i.h" #if WITHDEBUGNEW #ifdef new #undef new #endif #endif //#pragma warning (disable : 4756) // Const Arith overflow Warning //=========================================================================== _FWDDEF(GCCommaDef) _FWDDEF(GCCBraceDef) //--------------------------------------------------------------------------- class GCCommaDef : public GCDef { public: GCCommaDef() : GCDef(",") { }; virtual pGCIns Construct(rGCInsMngr IB) { ASSERT(FALSE); return NULL; }; }; GCCommaDef GCComma; //=========================================================================== class GCCBraceDef : public GCDef { public: GCCBraceDef() : GCDef(")") { m_defFlags = DefExp; }; virtual pGCIns Construct(rGCInsMngr IB) { ASSERT(FALSE); return NULL; }; }; GCCBraceDef GCCBrace; //=========================================================================== class GCETagDef : public GCDef { public: GCETagDef() : GCDef("]") { m_defFlags = DefExp; }; virtual pGCIns Construct(rGCInsMngr IB) { ASSERT(FALSE); return NULL; }; }; GCETagDef GCETag; //--------------------------------------------------------------------------- //======================== 'Binary' Operators ============================== //--------------------------------------------------------------------------- START_CODE(Band) MID_CODE(Band,"BAND",DefExp | DefOperator,18) virtual pGCIns Construct(rGCInsMngr IB) { return new(IB) GCBandIns; }; END_CODE(Band) //--------------------------------------------------------------------------- void GCBandIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; IB.m_dCalcStack[IB.m_iCalcPos] = (double)(GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos]) & GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos+1])); Advance(IB); }; //=========================================================================== START_CODE(Bxor) MID_CODE(Bxor,"BXOR",DefExp | DefOperator,16) virtual pGCIns Construct(rGCInsMngr IB) { return new(IB) GCBxorIns; }; END_CODE(Bxor) //--------------------------------------------------------------------------- void GCBxorIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; IB.m_dCalcStack[IB.m_iCalcPos] = (double)(GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos]) ^ GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos+1])); Advance(IB); }; //=========================================================================== START_CODE(Bor) MID_CODE(Bor,"BOR",DefExp | DefOperator,14) virtual pGCIns Construct(rGCInsMngr IB) { return new(IB) GCBorIns; }; END_CODE(Bor) //--------------------------------------------------------------------------- void GCBorIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; IB.m_dCalcStack[IB.m_iCalcPos] = (double)(GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos]) | GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos+1])); Advance(IB); }; //--------------------------------------------------------------------------- //======================== 'Logical' Operators ============================== //--------------------------------------------------------------------------- START_CODE(And) MID_CODE(And,"AND",DefExp | DefOperator,12) virtual pGCIns Construct(rGCInsMngr IB) { return new(IB) GCAndIns; }; END_CODE(And) //--------------------------------------------------------------------------- inline void GCAndIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; IB.m_dCalcStack[IB.m_iCalcPos] = IB.m_dCalcStack[IB.m_iCalcPos] && IB.m_dCalcStack[IB.m_iCalcPos+1]; Advance(IB); }; //=========================================================================== START_CODE(Xor) MID_CODE(Xor,"XOR",DefExp | DefOperator,10) virtual pGCIns Construct(rGCInsMngr IB) { return new(IB) GCXorIns; }; END_CODE(Xor) //--------------------------------------------------------------------------- void GCXorIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; IB.m_dCalcStack[IB.m_iCalcPos] = ( (IB.m_dCalcStack[IB.m_iCalcPos] || IB.m_dCalcStack[IB.m_iCalcPos+1]) && (!(IB.m_dCalcStack[IB.m_iCalcPos] && IB.m_dCalcStack[IB.m_iCalcPos+1]))); Advance(IB); }; //=========================================================================== START_CODE(Or) MID_CODE(Or,"OR",DefExp | DefOperator,8) virtual pGCIns Construct(rGCInsMngr IB) { return new(IB) GCOrIns; }; END_CODE(Or) //--------------------------------------------------------------------------- inline void GCOrIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; IB.m_dCalcStack[IB.m_iCalcPos] = IB.m_dCalcStack[IB.m_iCalcPos] || IB.m_dCalcStack[IB.m_iCalcPos+1]; Advance(IB); }; //=========================================================================== //--------------------------------------------------------------------------- //======================== 'Normal' Operators ============================== //------------------- START_CODE(Add) MID_CODE(Add,"+",DefExp | DefOperator,26) virtual pGCIns Construct(rGCInsMngr IB) { return new(IB) GCAddIns; }; END_CODE(Add) //--------------------------------------------------------------------------- inline void GCAddIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; IB.m_dCalcStack[IB.m_iCalcPos] += IB.m_dCalcStack[IB.m_iCalcPos+1]; Advance(IB); }; //=========================================================================== START_CODE(Sub); MID_CODE(Sub,"-",DefExp | DefOperator,26); virtual pGCIns Construct(rGCInsMngr IB) { return new(IB) GCSubIns; }; END_CODE(Sub); //--------------------------------------------------------------------------- inline void GCSubIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; IB.m_dCalcStack[IB.m_iCalcPos] -= IB.m_dCalcStack[IB.m_iCalcPos + 1]; Advance(IB); }; //=========================================================================== START_CODE(Mult) MID_CODE(Mult,"*",DefExp | DefOperator,28) virtual pGCIns Construct(rGCInsMngr IB) { return new(IB) GCMultIns; }; END_CODE(Mult) //--------------------------------------------------------------------------- inline void GCMultIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; IB.m_dCalcStack[IB.m_iCalcPos] *= IB.m_dCalcStack[IB.m_iCalcPos + 1]; Advance(IB); }; //=========================================================================== START_CODE(Divide) MID_CODE(Divide,"/",DefExp | DefOperator,28) virtual pGCIns Construct(rGCInsMngr IB) { return new(IB) GCDivideIns; }; END_CODE(Divide) //--------------------------------------------------------------------------- inline void GCDivideIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; if (IB.m_dCalcStack[IB.m_iCalcPos + 1] == 0.0) IB.Err(ErrMathRuntime,50); IB.m_dCalcStack[IB.m_iCalcPos] /= NZ(IB.m_dCalcStack[IB.m_iCalcPos + 1]); Advance(IB); }; //=========================================================================== START_CODE(Power) MID_CODE(Power,"^",DefExp | DefOperator,30) virtual pGCIns Construct(rGCInsMngr IB) { return new(IB) GCPowerIns; }; END_CODE(Power) //--------------------------------------------------------------------------- inline void GCPowerIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; if (IB.m_dCalcStack[IB.m_iCalcPos]<0.0 && IB.m_dCalcStack[IB.m_iCalcPos+1]-(double)((long)(IB.m_dCalcStack[IB.m_iCalcPos+1]))!=0.0) IB.Err(ErrMathRuntime,52); if (IB.m_dCalcStack[IB.m_iCalcPos]==0.0 && IB.m_dCalcStack[IB.m_iCalcPos+1]<0.0) IB.Err(ErrMathRuntime,54); IB.m_dCalcStack[IB.m_iCalcPos] = pow(IB.m_dCalcStack[IB.m_iCalcPos], IB.m_dCalcStack[IB.m_iCalcPos+1]); Advance(IB); }; //=========================================================================== START_CODE(Sin) MID_CODE(Sin,"SIN",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCSinIns; }; END_CODE(Sin) //--------------------------------------------------------------------------- void GCSinIns::Exec(rGCInsMngr IB) { IB.m_dCalcStack[IB.m_iCalcPos] = sin(IB.m_dCalcStack[IB.m_iCalcPos]); //todo trap errors, ranges etc Advance(IB); }; //=========================================================================== START_CODE(Cos) MID_CODE(Cos,"COS",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCCosIns; }; END_CODE(Cos) //--------------------------------------------------------------------------- void GCCosIns::Exec(rGCInsMngr IB) { IB.m_dCalcStack[IB.m_iCalcPos] = cos(IB.m_dCalcStack[IB.m_iCalcPos]); //todo trap errors, ranges etc Advance(IB); }; //=========================================================================== START_CODE(Tan) MID_CODE(Tan,"TAN",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCTanIns; }; END_CODE(Tan) //--------------------------------------------------------------------------- void GCTanIns::Exec(rGCInsMngr IB) { IB.m_dCalcStack[IB.m_iCalcPos] = tan(IB.m_dCalcStack[IB.m_iCalcPos]); //todo trap errors, ranges etc Advance(IB); }; //=========================================================================== START_CODE(aTan2) MID_CODE(aTan2,"ATAN2",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(4); return new(IB) GCaTan2Ins; }; END_CODE(aTan2) //--------------------------------------------------------------------------- void GCaTan2Ins::Exec(rGCInsMngr IB) { IB.m_iCalcPos -= 3; IB.m_dCalcStack[IB.m_iCalcPos] = atan2( (IB.m_dCalcStack[IB.m_iCalcPos+1] - IB.m_dCalcStack[IB.m_iCalcPos]), (IB.m_dCalcStack[IB.m_iCalcPos+3] - IB.m_dCalcStack[IB.m_iCalcPos+2]) ); //todo trap errors, ranges etc Advance(IB); }; //=========================================================================== START_CODE(Pow) MID_CODE(Pow,"POW",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2); return new(IB) GCPowIns; }; END_CODE(Pow) //--------------------------------------------------------------------------- void GCPowIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; if (IB.m_dCalcStack[IB.m_iCalcPos]<0.0 && IB.m_dCalcStack[IB.m_iCalcPos+1]-(double)((long)(IB.m_dCalcStack[IB.m_iCalcPos+1]))!=0.0) IB.Err(ErrMathRuntime,52); if (IB.m_dCalcStack[IB.m_iCalcPos]==0.0 && IB.m_dCalcStack[IB.m_iCalcPos+1]<0.0) IB.Err(ErrMathRuntime,54); IB.m_dCalcStack[IB.m_iCalcPos] = pow(IB.m_dCalcStack[IB.m_iCalcPos], IB.m_dCalcStack[IB.m_iCalcPos+1]); Advance(IB); } //=========================================================================== START_CODE(Abs) MID_CODE(Abs,"ABS",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCAbsIns; }; END_CODE(Abs) //--------------------------------------------------------------------------- void GCAbsIns::Exec(rGCInsMngr IB) { IB.m_dCalcStack[IB.m_iCalcPos] = fabs(IB.m_dCalcStack[IB.m_iCalcPos]); Advance(IB); } //=========================================================================== START_CODE(Sqrt) MID_CODE(Sqrt,"SQRT",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCSqrtIns; }; END_CODE(Sqrt) //--------------------------------------------------------------------------- void GCSqrtIns::Exec(rGCInsMngr IB) { if (IB.m_dCalcStack[IB.m_iCalcPos] < 0.0) IB.Err(ErrMathRuntime,51); IB.m_dCalcStack[IB.m_iCalcPos] = sqrt(Max(0.0, IB.m_dCalcStack[IB.m_iCalcPos])); Advance(IB); } //=========================================================================== START_CODE(Exp) MID_CODE(Exp,"EXP",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCExpIns; }; END_CODE(Exp) //--------------------------------------------------------------------------- void GCExpIns::Exec(rGCInsMngr IB) { IB.m_dCalcStack[IB.m_iCalcPos] = exp(IB.m_dCalcStack[IB.m_iCalcPos]); Advance(IB); } //=========================================================================== START_CODE(Ln) MID_CODE(Ln,"LN",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCLnIns; }; END_CODE(Ln) //--------------------------------------------------------------------------- void GCLnIns::Exec(rGCInsMngr IB) { if (IB.m_dCalcStack[IB.m_iCalcPos]<=0.0) IB.Err(ErrMathRuntime,53); IB.m_dCalcStack[IB.m_iCalcPos] = log(GTZ(IB.m_dCalcStack[IB.m_iCalcPos])); Advance(IB); } //=========================================================================== START_CODE(Log) MID_CODE(Log,"LOG",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCLogIns; }; END_CODE(Log) //--------------------------------------------------------------------------- void GCLogIns::Exec(rGCInsMngr IB) { if (IB.m_dCalcStack[IB.m_iCalcPos]<=0.0) IB.Err(ErrMathRuntime,53); IB.m_dCalcStack[IB.m_iCalcPos] = log10(GTZ(IB.m_dCalcStack[IB.m_iCalcPos])); Advance(IB); } //=========================================================================== START_CODE(Mod) MID_CODE(Mod,"MOD",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2); return new(IB) GCModIns; }; END_CODE(Mod) //--------------------------------------------------------------------------- void GCModIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; /*//remainder = a - (floor(a/b)*b) double a = fabs(IB.m_dCalcStack[IB.m_iCalcPos]); double b = fabs(IB.m_dCalcStack[IB.m_iCalcPos+1]); if (b == 0.0) IB.Err(ErrMathRuntime,50); IB.m_dCalcStack[IB.m_iCalcPos] = a - (floor(a/b)*b);*/ if (IB.m_dCalcStack[IB.m_iCalcPos+1] == 0.0) IB.Err(ErrMathRuntime,50); IB.m_dCalcStack[IB.m_iCalcPos] = fmod(IB.m_dCalcStack[IB.m_iCalcPos], NZ(IB.m_dCalcStack[IB.m_iCalcPos+1])); Advance(IB); } //=========================================================================== START_CODE(Div) MID_CODE(Div,"DIV",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2); return new(IB) GCDivIns; }; END_CODE(Div) //--------------------------------------------------------------------------- void GCDivIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; //quot = floor(a/b) double a = fabs(IB.m_dCalcStack[IB.m_iCalcPos]); double b = fabs(IB.m_dCalcStack[IB.m_iCalcPos+1]); if (b == 0.0) IB.Err(ErrMathRuntime,50); IB.m_dCalcStack[IB.m_iCalcPos] = floor(a/NZ(b)); Advance(IB); }; //=========================================================================== START_CODE(Max) MID_CODE(Max,"MAX",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2); return new(IB) GCMaxIns; }; END_CODE(Max) //--------------------------------------------------------------------------- void GCMaxIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; IB.m_dCalcStack[IB.m_iCalcPos] = Max(IB.m_dCalcStack[IB.m_iCalcPos],IB.m_dCalcStack[IB.m_iCalcPos+1]); //todo trap errors, ranges etc Advance(IB); }; //=========================================================================== START_CODE(Min) MID_CODE(Min,"MIN",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2); return new(IB) GCMinIns; }; END_CODE(Min) //--------------------------------------------------------------------------- void GCMinIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; IB.m_dCalcStack[IB.m_iCalcPos] = Min(IB.m_dCalcStack[IB.m_iCalcPos],IB.m_dCalcStack[IB.m_iCalcPos+1]); //todo trap errors, ranges etc Advance(IB); }; //=========================================================================== START_CODE(Range) MID_CODE(Range,"RANGE",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(3); return new(IB) GCRangeIns; }; END_CODE(Range) //--------------------------------------------------------------------------- void GCRangeIns::Exec(rGCInsMngr IB) { IB.m_iCalcPos = IB.m_iCalcPos - 2; IB.m_dCalcStack[IB.m_iCalcPos] = Range(IB.m_dCalcStack[IB.m_iCalcPos],IB.m_dCalcStack[IB.m_iCalcPos+1],IB.m_dCalcStack[IB.m_iCalcPos+2]); //todo trap errors, ranges etc Advance(IB); }; //=========================================================================== START_CODE(Trunc) MID_CODE(Trunc,"TRUNC",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCTruncIns; }; END_CODE(Trunc) //--------------------------------------------------------------------------- void GCTruncIns::Exec(rGCInsMngr IB) { IB.m_dCalcStack[IB.m_iCalcPos] = (long)(IB.m_dCalcStack[IB.m_iCalcPos]); Advance(IB); } //=========================================================================== //note this is "arathmetic round" not "banking round" START_CODE(Round) MID_CODE(Round,"ROUND",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCRoundIns; }; END_CODE(Round) //--------------------------------------------------------------------------- void GCRoundIns::Exec(rGCInsMngr IB) { if (IB.m_dCalcStack[IB.m_iCalcPos]>0) IB.m_dCalcStack[IB.m_iCalcPos] = (long)(IB.m_dCalcStack[IB.m_iCalcPos]+0.5); else IB.m_dCalcStack[IB.m_iCalcPos] = (long)(IB.m_dCalcStack[IB.m_iCalcPos]-0.5); Advance(IB); } //=========================================================================== START_CODE(RoundUp) MID_CODE(RoundUp,"ROUNDUP",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2); return new(IB) GCRoundUpIns; }; END_CODE(RoundUp) //--------------------------------------------------------------------------- void GCRoundUpIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; const long decimals = (long)(IB.m_dCalcStack[IB.m_iCalcPos+1]); //IB.m_dCalcStack[IB.m_iCalcPos] = Math::Round(IB.m_dCalcStack[IB.m_iCalcPos], decimals); //there MUST be a better way of implementing this... if (decimals<16) {//do nothing Advance(IB); return; } double d; switch (decimals) { case -5: d = 0.00001; break; case -4: d = 0.0001; break; case -3: d = 0.001; break; case -2: d = 0.01; break; case -1: d = 0.1; break; case 0: d = 1.0; break; case 1: d = 10.0; break; case 2: d = 100.0; break; case 3: d = 1000.0; break; case 4: d = 10000.0; break; case 5: d = 100000.0; break; case 6: d = 1000000.0; break; case 7: d = 10000000.0; break; case 8: d = 100000000.0; break; default: d = Pow(10, decimals); break; } const double v = IB.m_dCalcStack[IB.m_iCalcPos]*d; if (v<0.0) { const double f = ceil(v); if (v-f<-1.0e-12) IB.m_dCalcStack[IB.m_iCalcPos] = (f-1)/d; else IB.m_dCalcStack[IB.m_iCalcPos] = f/d; } else { const double f = floor(v); if (v>f) IB.m_dCalcStack[IB.m_iCalcPos] = (f+1)/d; else IB.m_dCalcStack[IB.m_iCalcPos] = f/d; } Advance(IB); } //=========================================================================== START_CODE(Random) MID_CODE(Random,"RANDOM",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCRandomIns; }; END_CODE(Random) //--------------------------------------------------------------------------- void GCRandomIns::Exec(rGCInsMngr IB) { IB.m_dCalcStack[IB.m_iCalcPos] = rand()*(IB.m_dCalcStack[IB.m_iCalcPos]/RAND_MAX); Advance(IB); } //=========================================================================== START_CODE(IsNAN) MID_CODE(IsNAN,"ISNAN",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCIsNANIns; }; END_CODE(IsNAN) //--------------------------------------------------------------------------- void GCIsNANIns::Exec(rGCInsMngr IB) { IB.m_dCalcStack[IB.m_iCalcPos] = (_isnan(IB.m_dCalcStack[IB.m_iCalcPos]) ? dGCtrue : dGCfalse); Advance(IB); } //=========================================================================== /* START_CODE(An_Scale) MID_CODE(An_Scale,"AN_SCALE",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCAn_ScaleIns; }; END_CODE(An_Scale) //--------------------------------------------------------------------------- void GCAn_ScaleIns::Exec(rGCInsMngr IB) { --IB.m_iCalcPos; //todo // do nothing , only remove value off stack Advance(IB); }; */ //=========================================================================== START_CODE(Time) MID_CODE(Time,"TIME",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(0); return new(IB) GCTimeIns; }; END_CODE(Time) //--------------------------------------------------------------------------- void GCTimeIns::Exec(rGCInsMngr IB) { IB.m_dCalcStack[++IB.m_iCalcPos] = IB.m_dIC_Time.Seconds; Advance(IB); }; //=========================================================================== START_CODE(Deltatime) MID_CODE(Deltatime,"DELTATIME",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(0); return new(IB) GCDeltatimeIns; }; END_CODE(Deltatime) //--------------------------------------------------------------------------- void GCDeltatimeIns::Exec(rGCInsMngr IB) { IB.m_dCalcStack[++IB.m_iCalcPos] = IB.m_dIC_dTime.Seconds; Advance(IB); }; //=========================================================================== START_CODE(Beep) MID_CODE(Beep,"BEEP",DefLHS,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1); return new(IB) GCBeepIns; }; END_CODE(Beep) //--------------------------------------------------------------------------- void GCBeepIns::Exec(rGCInsMngr IB) { IB.m_iCalcPos -= 1; for (int i = 0; i <= IB.m_dCalcStack[IB.m_iCalcPos+1]; i++) MessageBeep(0xFFFFFFFF); //Beep((DWORD)IB.m_dCalcStack[IB.m_iCalcPos+2], (DWORD)IB.m_dCalcStack[IB.m_iCalcPos+3]); // 16356 Hz , each beep lasts for 10ms Advance(IB); }; //=========================================================================== /*START_CODE(Beep2) MID_CODE(Beep2,"BEEP2",DefLHS,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(3); return new(IB) GCBeep2Ins; }; END_CODE(Beep2) //--------------------------------------------------------------------------- void GCBeep2Ins::Exec(rGCInsMngr IB) { IB.m_iCalcPos -= 3; for (int i = 0; i <= IB.m_dCalcStack[IB.m_iCalcPos+1]; i++) Beep((DWORD)IB.m_dCalcStack[IB.m_iCalcPos+2], (DWORD)IB.m_dCalcStack[IB.m_iCalcPos+3]); // 16356 Hz , each beep lasts for 10ms Advance(IB); };*/ //=========================================================================== // string manipulation functions ... //=========================================================================== START_CODE(StrCat) MID_CODE(StrCat,"STRCAT",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2, 0xff); return new(IB) GCStrCatIns; }; END_CODE(StrCat) //--------------------------------------------------------------------------- void GCStrCatIns::Exec(rGCInsMngr IB) { IB.m_iStrPos--; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+1]; Advance(IB); }; //=========================================================================== START_CODE(StrCat2) MID_CODE(StrCat2,"STRCAT2",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(3, 0xff); return new(IB) GCStrCat2Ins; }; END_CODE(StrCat2) //--------------------------------------------------------------------------- void GCStrCat2Ins::Exec(rGCInsMngr IB) { IB.m_iStrPos -= 2; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+1]; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+2]; Advance(IB); }; //=========================================================================== START_CODE(StrCat3) MID_CODE(StrCat3,"STRCAT3",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(4, 0xff); return new(IB) GCStrCat3Ins; }; END_CODE(StrCat3) //--------------------------------------------------------------------------- void GCStrCat3Ins::Exec(rGCInsMngr IB) { IB.m_iStrPos -= 3; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+1]; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+2]; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+3]; Advance(IB); }; //=========================================================================== START_CODE(StrCat4) MID_CODE(StrCat4,"STRCAT4",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(5, 0xff); return new(IB) GCStrCat4Ins; }; END_CODE(StrCat4) //--------------------------------------------------------------------------- void GCStrCat4Ins::Exec(rGCInsMngr IB) { IB.m_iStrPos -= 4; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+1]; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+2]; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+3]; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+4]; Advance(IB); }; //=========================================================================== START_CODE(StrCat5) MID_CODE(StrCat5,"STRCAT5",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(6, 0xff); return new(IB) GCStrCat5Ins; }; END_CODE(StrCat5) //--------------------------------------------------------------------------- void GCStrCat5Ins::Exec(rGCInsMngr IB) { IB.m_iStrPos -= 5; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+1]; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+2]; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+3]; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+4]; IB.m_StrStack[IB.m_iStrPos] += IB.m_StrStack[IB.m_iStrPos+5]; Advance(IB); }; //=========================================================================== START_CODE(StrStr) MID_CODE(StrStr,"STRSTR",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2, 0xff); return new(IB) GCStrStrIns; }; END_CODE(StrStr) //--------------------------------------------------------------------------- void GCStrStrIns::Exec(rGCInsMngr IB) { IB.m_iStrPos -= 2; IB.m_dCalcStack[++IB.m_iCalcPos] = IB.m_StrStack[IB.m_iStrPos+1].Find(IB.m_StrStack[IB.m_iStrPos+2]); // IB.m_StrStack[IB.m_iStrPos+1].Find(IB.m_StrStack[IB.m_iStrPos]); Advance(IB); }; //=========================================================================== START_CODE(StrCmp) MID_CODE(StrCmp,"STRCMP",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2, 0xff); return new(IB) GCStrCmpIns; }; END_CODE(StrCmp) //--------------------------------------------------------------------------- void GCStrCmpIns::Exec(rGCInsMngr IB) { IB.m_iStrPos -= 2; IB.m_dCalcStack[++IB.m_iCalcPos] = IB.m_StrStack[IB.m_iStrPos+1].XStrCmp(IB.m_StrStack[IB.m_iStrPos+2]); Advance(IB); } //=========================================================================== START_CODE(StriCmp) MID_CODE(StriCmp,"STRICMP",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2, 0xff); return new(IB) GCStriCmpIns; }; END_CODE(StriCmp) //--------------------------------------------------------------------------- void GCStriCmpIns::Exec(rGCInsMngr IB) { IB.m_iStrPos -= 2; IB.m_dCalcStack[++IB.m_iCalcPos] = IB.m_StrStack[IB.m_iStrPos+1].XStrICmp(IB.m_StrStack[IB.m_iStrPos+2]); Advance(IB); } //=========================================================================== START_CODE(Left) MID_CODE(Left,"LEFT",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1, True, False); IB.DoConstructParms(1, 0x0, False, True); return new(IB) GCLeftIns; }; END_CODE(Left) //--------------------------------------------------------------------------- void GCLeftIns::Exec(rGCInsMngr IB) { long i = GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos--]); IB.m_StrStack[IB.m_iStrPos] = IB.m_StrStack[IB.m_iStrPos].Left(i); Advance(IB); } //=========================================================================== START_CODE(Right) MID_CODE(Right,"RIGHT",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1, True, False); IB.DoConstructParms(1, 0x0, False, True); return new(IB) GCRightIns; }; END_CODE(Right) //--------------------------------------------------------------------------- void GCRightIns::Exec(rGCInsMngr IB) { long i = GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos--]); IB.m_StrStack[IB.m_iStrPos] = IB.m_StrStack[IB.m_iStrPos].Right(i); Advance(IB); } //=========================================================================== START_CODE(Mid) MID_CODE(Mid,"MID",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1, True, False); IB.DoConstructParms(2, 0x0, False, True); return new(IB) GCMidIns; }; END_CODE(Mid) //--------------------------------------------------------------------------- void GCMidIns::Exec(rGCInsMngr IB) { long length = GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos--]); long startPosn = GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos--]); IB.m_StrStack[IB.m_iStrPos] = IB.m_StrStack[IB.m_iStrPos].Mid(startPosn,length); Advance(IB); } //=========================================================================== START_CODE(StrLen) MID_CODE(StrLen,"STRLEN",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1); return new(IB) GCStrLenIns; }; END_CODE(StrLen) //--------------------------------------------------------------------------- void GCStrLenIns::Exec(rGCInsMngr IB) { IB.m_dCalcStack[++IB.m_iCalcPos] = IB.m_StrStack[IB.m_iStrPos--].Length(); Advance(IB); } //=========================================================================== START_CODE(StrUpr) MID_CODE(StrUpr,"STRUPR",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1); return new(IB) GCStrUprIns; }; END_CODE(StrUpr) //--------------------------------------------------------------------------- void GCStrUprIns::Exec(rGCInsMngr IB) { // IB.m_StrStack[IB.m_iStrPos] = IB.m_StrStack[IB.m_iStrPos].Upper(); IB.m_StrStack[IB.m_iStrPos].Upper(); Advance(IB); } //=========================================================================== START_CODE(StrLwr) MID_CODE(StrLwr,"STRLWR",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1); return new(IB) GCStrLwrIns; }; END_CODE(StrLwr) //--------------------------------------------------------------------------- void GCStrLwrIns::Exec(rGCInsMngr IB) { //IB.m_StrStack[IB.m_iStrPos] = IB.m_StrStack[IB.m_iStrPos].Lower(); IB.m_StrStack[IB.m_iStrPos].Lower(); Advance(IB); } //=========================================================================== START_CODE(IntStr) MID_CODE(IntStr,"IntStr",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2, 0x0); return new(IB) GCIntStrIns; }; END_CODE(IntStr) //--------------------------------------------------------------------------- void GCIntStrIns::Exec(rGCInsMngr IB) { const long length = GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos--]); const long integer = GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos--]); IB.m_StrStack[++IB.m_iStrPos].Set("%*d",length,integer); Advance(IB); } //=========================================================================== START_CODE(IntToStr) MID_CODE(IntToStr,"IntToStr",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x0); return new(IB) GCIntToStrIns; }; END_CODE(IntToStr) //--------------------------------------------------------------------------- void GCIntToStrIns::Exec(rGCInsMngr IB) { const long integer = GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos--]); IB.m_StrStack[++IB.m_iStrPos].Set("%d",integer); Advance(IB); } //=========================================================================== START_CODE(StrToInt) MID_CODE(StrToInt,"StrToInt",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1); return new(IB) GCStrToIntIns; }; END_CODE(StrToInt) //--------------------------------------------------------------------------- void GCStrToIntIns::Exec(rGCInsMngr IB) { Strng s = (IB.m_StrStack[IB.m_iStrPos--]); s.Trim(" \t\n"); IB.m_dCalcStack[++IB.m_iCalcPos] = s.Len()>0 ? atol(s()) : 0.0; Advance(IB); } //=========================================================================== START_CODE(FltStr) MID_CODE(FltStr,"FltStr",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(3, 0x0); return new(IB) GCFltStrIns; }; END_CODE(FltStr) //--------------------------------------------------------------------------- void GCFltStrIns::Exec(rGCInsMngr IB) { const long length = GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos--]); const long decimal = GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos--]); const double floater = IB.m_dCalcStack[IB.m_iCalcPos--]; IB.m_StrStack[++IB.m_iStrPos].Set("%*.*f",length,decimal,floater); Advance(IB); } //=========================================================================== START_CODE(FltToStr) MID_CODE(FltToStr,"FltToStr",DefExp | DefRetStr,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x0); return new(IB) GCFltToStrIns; }; END_CODE(FltToStr) //--------------------------------------------------------------------------- void GCFltToStrIns::Exec(rGCInsMngr IB) { const double floater = IB.m_dCalcStack[IB.m_iCalcPos--]; IB.m_StrStack[++IB.m_iStrPos].Set("%f",floater); Advance(IB); } //=========================================================================== START_CODE(StrToFlt) MID_CODE(StrToFlt,"StrToFlt",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1); return new(IB) GCStrToFltIns; }; END_CODE(StrToFlt) //--------------------------------------------------------------------------- void GCStrToFltIns::Exec(rGCInsMngr IB) { Strng s = (IB.m_StrStack[IB.m_iStrPos--]); s.Trim(" \t\n"); IB.m_dCalcStack[++IB.m_iCalcPos] = s.Len()>0 ? atof(s()) : 0.0; Advance(IB); } //=========================================================================== START_CODE(AlphaToNum) MID_CODE(AlphaToNum,"AlphaToNum",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1); return new(IB) GCAlphaToNumIns; }; END_CODE(AlphaToNum) //--------------------------------------------------------------------------- void GCAlphaToNumIns::Exec(rGCInsMngr IB) { Strng s = (IB.m_StrStack[IB.m_iStrPos--]); if (s.Len()>0 && isalpha(s[0])) { IB.m_dCalcStack[++IB.m_iCalcPos] = (char)toupper(s[0])-(char)'A'+1; } else IB.m_dCalcStack[++IB.m_iCalcPos] = 0.0; Advance(IB); } //=========================================================================== START_CODE(IsAlpha) MID_CODE(IsAlpha,"IsAlpha",DefExp,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1); return new(IB) GCIsAlphaIns; }; END_CODE(IsAlpha) //--------------------------------------------------------------------------- void GCIsAlphaIns::Exec(rGCInsMngr IB) { Strng s = (IB.m_StrStack[IB.m_iStrPos--]); const int len = s.Len(); for (int i=0; i<len; i++) { if (!isalpha(s[i])) break; } IB.m_dCalcStack[++IB.m_iCalcPos] = (i==len && len>0) ? dGCtrue : dGCfalse; Advance(IB); } //=========================================================================== START_CODE(LogNote) MID_CODE(LogNote,"LogNote",DefLHS,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1); return new(IB) GCLogNoteIns; }; END_CODE(LogNote) //--------------------------------------------------------------------------- void GCLogNoteIns::Exec(rGCInsMngr IB) { char* p = (IB.m_StrStack[IB.m_iStrPos--])(); PgmLogNote(IB.m_pXRM->GetOwnerTag(), 0, p ? p : ""); Advance(IB); } //=========================================================================== START_CODE(LogError) MID_CODE(LogError,"LogError",DefLHS,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1); return new(IB) GCLogErrorIns; }; END_CODE(LogError) //--------------------------------------------------------------------------- void GCLogErrorIns::Exec(rGCInsMngr IB) { char* p = (IB.m_StrStack[IB.m_iStrPos--])(); PgmLogError(IB.m_pXRM->GetOwnerTag(), 0, p ? p : ""); Advance(IB); } //=========================================================================== START_CODE(ConditionNote) MID_CODE(ConditionNote,"ConditionNote",DefLHS,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2, 0x0, True, False); IB.DoConstructParms(1, 0x1, False, True); return new(IB) GCConditionNoteIns; }; END_CODE(ConditionNote) //--------------------------------------------------------------------------- void GCConditionNoteIns::Exec(rGCInsMngr IB) { int CIindex = Range(0L, GetAsLong(IB.m_dCalcStack[--IB.m_iCalcPos]), (long)MaxCondMsgs-1); IB.m_CINOn[CIindex] = (GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos+1])!=0); --IB.m_iCalcPos; IB.m_CINMsgs[CIindex] = (IB.m_StrStack[IB.m_iStrPos--])(); Advance(IB); } //=========================================================================== START_CODE(ConditionError) MID_CODE(ConditionError,"ConditionError",DefLHS,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(2, 0x0, True, False); IB.DoConstructParms(1, 0x1, False, True); return new(IB) GCConditionErrorIns; }; END_CODE(ConditionError) //--------------------------------------------------------------------------- void GCConditionErrorIns::Exec(rGCInsMngr IB) { int CIindex = Range(0L, GetAsLong(IB.m_dCalcStack[--IB.m_iCalcPos]), (long)MaxCondMsgs-1); IB.m_CIEOn[CIindex] = (GetAsLong(IB.m_dCalcStack[IB.m_iCalcPos+1])!=0); --IB.m_iCalcPos; IB.m_CIEMsgs[CIindex] = (IB.m_StrStack[IB.m_iStrPos--])(); Advance(IB); } //=========================================================================== START_CODE(LogEvent) MID_CODE(LogEvent,"LogEvent",DefLHS,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1); return new(IB) GCLogEventIns; }; END_CODE(LogEvent) //--------------------------------------------------------------------------- void GCLogEventIns::Exec(rGCInsMngr IB) { char* p = (IB.m_StrStack[IB.m_iStrPos--])(); CTNode *pNd=dynamic_cast<CTNode*>(IB.m_pXRM); gs_EventLog.LogEvent((pNd ? pNd->FullObjTag():""), (p ? p : "")); Advance(IB); } //=========================================================================== START_CODE(MsgBox) MID_CODE(MsgBox,"MsgBox",DefLHS/* | DefExp*/,0) virtual pGCIns Construct(rGCInsMngr IB) { IB.DoConstructParms(1, 0x1); return new(IB) GCMsgBoxIns; }; END_CODE(MsgBox) //--------------------------------------------------------------------------- void GCMsgBoxIns::Exec(rGCInsMngr IB) { //IB.m_dCalcStack[++IB.m_iCalcPos] = AfxMessageBox((IB.m_StrStack[IB.m_iStrPos--])(), MB_OKCANCEL); //todo: Put message box back. Watch for thread locks, etc!!! PgmLogNote(IB.m_pXRM->GetOwnerTag(), 0, (IB.m_StrStack[IB.m_iStrPos--])()); Advance(IB); } //=========================================================================== // Some PGM classes used by PMC optimization equations... //=========================================================================== #ifdef PMC const short Idf_QuadEqnAddMeas = 1; //--------------------------------------------------------------------------- GCQuadEqn::GCQuadEqn(rGCInsMngr IB) : GCClassVar(IB.m_pVarList, &IB.m_VarMap, "QuadEqn", VarClassDefn) { AddVar(IB, "Output", &GCDouble, VarConst); AddVar(IB, "Scale", &GCDouble); AddVar(IB, "Offset", &GCDouble); AddVar(IB, "Samples", &GCLong); AddVar(IB, "SampleDelay", &GCLong); AddVar(IB, "AdjustSO", &GCLong); AddVar(IB, "UseYMeas", &GCBit); AddVar(IB, "MinYValid", &GCDouble); AddVar(IB, "MaxYValid", &GCDouble); AddVar(IB, "A", &GCDouble); AddVar(IB, "B", &GCDouble); AddFunct(IB, "AddMeas", 2, False, Idf_QuadEqnAddMeas); } //--------------------------------------------------------------------------- void GCQuadEqn::Init(pGCClassVar pClassVar) { pCOptimizer pOpt = new COptimizer(); pClassVar->m_pSubClass = (pvoid)pOpt; pOpt->ChangeModel("Quadratic"); pClassVar->GetVarByName("Output")->set(pOpt->Output); pClassVar->GetVarByName("Scale")->set(pOpt->Scale); pClassVar->GetVarByName("Offset")->set(pOpt->Offset); pClassVar->GetVarByName("Samples")->set(pOpt->NoSamples); pClassVar->GetVarByName("SampleDelay")->set(pOpt->SampleDelay); pClassVar->GetVarByName("AdjustSO")->set(pOpt->AdjSO); pClassVar->GetVarByName("UseYMeas")->set(pOpt->UseYMeas); pClassVar->GetVarByName("MinYValid")->set(pOpt->MinYValid); pClassVar->GetVarByName("MaxYValid")->set(pOpt->MaxYValid); pClassVar->GetVarByName("A")->set(1.0); pClassVar->GetVarByName("B")->set(1.0); } //--------------------------------------------------------------------------- void GCQuadEqn::Done(pGCClassVar pClassVar) { delete (pCOptimizer)(pClassVar->m_pSubClass); } //--------------------------------------------------------------------------- double GCQuadEqn::CallFunct(rGCInsMngr IB, pvoid pSubClass, short FunctId, pGCClassVar pClassVar) { pCOptimizer pOpt = (pCOptimizer)pSubClass; switch (FunctId) { case Idf_QuadEqnAddMeas: { pOpt->Scale = pClassVar->GetVarByName("Scale")->getD(); pOpt->Offset = pClassVar->GetVarByName("Offset")->getD(); pOpt->NoSamples = pClassVar->GetVarByName("Samples")->getL(); pOpt->SampleDelay = pClassVar->GetVarByName("SampleDelay")->getL(); pOpt->AdjSO = pClassVar->GetVarByName("AdjustSO")->getL(); pOpt->UseYMeas = pClassVar->GetVarByName("UseYMeas")->getB(); pOpt->MinYValid = pClassVar->GetVarByName("MinYValid")->getD(); pOpt->MaxYValid = pClassVar->GetVarByName("MaxYValid")->getD(); pOpt->Parm[0] = pClassVar->GetVarByName("A")->getD(); pOpt->Parm[1] = pClassVar->GetVarByName("B")->getD(); pOpt->SetYMeas(IB.GetDParm()); pOpt->SetXMeas(IB.GetDParm(), 0); pOpt->Estimate(); pClassVar->GetVarByName("Output")->set(pOpt->Output); pClassVar->GetVarByName("Offset")->set(pOpt->Offset); pClassVar->GetVarByName("SampleDelay")->set(pOpt->SampleDelay); return pOpt->Output; } break; default: ASSERT(FALSE); //function not defined } return 0.0; } //--------------------------------------------------------------------------- void GCQuadEqn::OnSave(FilingControlBlock &FCB/*FILE* f*/, pvoid pSubClass) { } //--------------------------------------------------------------------------- flag GCQuadEqn::OnLoad(FilingControlBlock &FCB/*rCTokenFile f*/, pvoid pSubClass) { //pCOptimizer pOpt = (pCOptimizer)pSubClass; //pOpt->ChangeModel("Quadratic"); return True; } //========================================================================== const short Idf_CircEqnAddMeas = 1; //--------------------------------------------------------------------------- GCCircEqn::GCCircEqn(rGCInsMngr IB) : GCClassVar(IB.m_pVarList, &IB.m_VarMap, "CircLoadEqn", VarClassDefn) { AddVar(IB, "Output", &GCDouble, VarConst); AddVar(IB, "Scale", &GCDouble); AddVar(IB, "Offset", &GCDouble); AddVar(IB, "Samples", &GCLong); AddVar(IB, "SampleDelay", &GCLong); AddVar(IB, "AdjustSO", &GCLong); AddVar(IB, "UseYMeas", &GCBit); AddVar(IB, "MinYValid", &GCDouble); AddVar(IB, "MaxYValid", &GCDouble); AddVar(IB, "Alpha", &GCDouble); AddVar(IB, "Beta", &GCDouble); AddFunct(IB, "AddMeas", 4, False, Idf_CircEqnAddMeas); } //--------------------------------------------------------------------------- void GCCircEqn::Init(pGCClassVar pClassVar) { pCOptimizer pOpt = new COptimizer(); pClassVar->m_pSubClass = (pvoid)pOpt; pOpt->ChangeModel("CircLoad"); pClassVar->GetVarByName("Output")->set(pOpt->Output); pClassVar->GetVarByName("Scale")->set(pOpt->Scale); pClassVar->GetVarByName("Offset")->set(pOpt->Offset); pClassVar->GetVarByName("Samples")->set(pOpt->NoSamples); pClassVar->GetVarByName("SampleDelay")->set(pOpt->SampleDelay); pClassVar->GetVarByName("AdjustSO")->set(pOpt->AdjSO); pClassVar->GetVarByName("UseYMeas")->set(pOpt->UseYMeas); pClassVar->GetVarByName("MinYValid")->set(pOpt->MinYValid); pClassVar->GetVarByName("MaxYValid")->set(pOpt->MaxYValid); pClassVar->GetVarByName("Alpha")->set(1.0); pClassVar->GetVarByName("Beta")->set(1.0); } //--------------------------------------------------------------------------- void GCCircEqn::Done(pGCClassVar pClassVar) { delete (pCOptimizer)(pClassVar->m_pSubClass); } //--------------------------------------------------------------------------- double GCCircEqn::CallFunct(rGCInsMngr IB, pvoid pSubClass, short FunctId, pGCClassVar pClassVar) { pCOptimizer pOpt = (pCOptimizer)pSubClass; switch (FunctId) { case Idf_CircEqnAddMeas: { pOpt->Scale = pClassVar->GetVarByName("Scale")->getD(); pOpt->Offset = pClassVar->GetVarByName("Offset")->getD(); pOpt->NoSamples = pClassVar->GetVarByName("Samples")->getL(); pOpt->SampleDelay = pClassVar->GetVarByName("SampleDelay")->getL(); pOpt->AdjSO = pClassVar->GetVarByName("AdjustSO")->getL(); pOpt->UseYMeas = pClassVar->GetVarByName("UseYMeas")->getB(); pOpt->MinYValid = pClassVar->GetVarByName("MinYValid")->getD(); pOpt->MaxYValid = pClassVar->GetVarByName("MaxYValid")->getD(); pOpt->Parm[0] = pClassVar->GetVarByName("Alpha")->getD(); pOpt->Parm[1] = pClassVar->GetVarByName("Beta")->getD(); pOpt->SetYMeas(IB.GetDParm()); pOpt->SetXMeas(IB.GetDParm(), 2); pOpt->SetXMeas(IB.GetDParm(), 1); pOpt->SetXMeas(IB.GetDParm(), 0); pOpt->Estimate(); pClassVar->GetVarByName("Output")->set(pOpt->Output); pClassVar->GetVarByName("Offset")->set(pOpt->Offset); pClassVar->GetVarByName("SampleDelay")->set(pOpt->SampleDelay); return pOpt->Output; } break; default: ASSERT(FALSE); //function not defined } return 0.0; } //--------------------------------------------------------------------------- void GCCircEqn::OnSave(FilingControlBlock &FCB/*FILE* f*/, pvoid pSubClass) { } //--------------------------------------------------------------------------- flag GCCircEqn::OnLoad(FilingControlBlock &FCB/*rCTokenFile f*/, pvoid pSubClass) { //pCOptimizer pOpt = (pCOptimizer)pSubClass; //pOpt->ChangeModel("CircLoad"); return True; } //========================================================================== const short Idf_PartEqnAddMeas = 1; //--------------------------------------------------------------------------- GCPartEqn::GCPartEqn(rGCInsMngr IB) : GCClassVar(IB.m_pVarList, &IB.m_VarMap, "PartSizeEqn", VarClassDefn) { AddVar(IB, "Output", &GCDouble, VarConst); AddVar(IB, "Scale", &GCDouble); AddVar(IB, "Offset", &GCDouble); AddVar(IB, "Samples", &GCLong); AddVar(IB, "SampleDelay", &GCLong); AddVar(IB, "AdjustSO", &GCLong); AddVar(IB, "UseYMeas", &GCBit); AddVar(IB, "MinYValid", &GCDouble); AddVar(IB, "MaxYValid", &GCDouble); AddVar(IB, "GnFlw", &GCDouble); AddVar(IB, "PwFlw", &GCDouble); AddVar(IB, "GnPres", &GCDouble); AddVar(IB, "PwPres", &GCDouble); AddVar(IB, "GnRho", &GCDouble); AddVar(IB, "PwRho", &GCDouble); AddVar(IB, "GnTot", &GCDouble); AddFunct(IB, "AddMeas", 4, False, Idf_PartEqnAddMeas); } //--------------------------------------------------------------------------- void GCPartEqn::Init(pGCClassVar pClassVar) { pCOptimizer pOpt = new COptimizer(); pClassVar->m_pSubClass = (pvoid)pOpt; pOpt->ChangeModel("PartSize"); pClassVar->GetVarByName("Output")->set(pOpt->Output); pClassVar->GetVarByName("Scale")->set(pOpt->Scale); pClassVar->GetVarByName("Offset")->set(pOpt->Offset); pClassVar->GetVarByName("Samples")->set(pOpt->NoSamples); pClassVar->GetVarByName("SampleDelay")->set(pOpt->SampleDelay); pClassVar->GetVarByName("AdjustSO")->set(pOpt->AdjSO); pClassVar->GetVarByName("UseYMeas")->set(pOpt->UseYMeas); pClassVar->GetVarByName("MinYValid")->set(pOpt->MinYValid); pClassVar->GetVarByName("MaxYValid")->set(pOpt->MaxYValid); pClassVar->GetVarByName("GnFlw")->set(1.0); pClassVar->GetVarByName("PwFlw")->set(1.0); pClassVar->GetVarByName("GnPres")->set(1.0); pClassVar->GetVarByName("PwPres")->set(1.0); pClassVar->GetVarByName("GnRho")->set(1.0); pClassVar->GetVarByName("PwRho")->set(1.0); pClassVar->GetVarByName("GnTot")->set(1.0); } //--------------------------------------------------------------------------- void GCPartEqn::Done(pGCClassVar pClassVar) { delete (pCOptimizer)(pClassVar->m_pSubClass); } //--------------------------------------------------------------------------- double GCPartEqn::CallFunct(rGCInsMngr IB, pvoid pSubClass, short FunctId, pGCClassVar pClassVar) { pCOptimizer pOpt = (pCOptimizer)pSubClass; switch (FunctId) { case Idf_PartEqnAddMeas: { pOpt->Scale = pClassVar->GetVarByName("Scale")->getD(); pOpt->Offset = pClassVar->GetVarByName("Offset")->getD(); pOpt->NoSamples = pClassVar->GetVarByName("Samples")->getL(); pOpt->SampleDelay = pClassVar->GetVarByName("SampleDelay")->getL(); pOpt->AdjSO = pClassVar->GetVarByName("AdjustSO")->getL(); pOpt->UseYMeas = pClassVar->GetVarByName("UseYMeas")->getB(); pOpt->MinYValid = pClassVar->GetVarByName("MinYValid")->getD(); pOpt->MaxYValid = pClassVar->GetVarByName("MaxYValid")->getD(); pOpt->Parm[0] = pClassVar->GetVarByName("GnFlw")->getD(); pOpt->Parm[1] = pClassVar->GetVarByName("PwFlw")->getD(); pOpt->Parm[2] = pClassVar->GetVarByName("GnPres")->getD(); pOpt->Parm[3] = pClassVar->GetVarByName("PwPres")->getD(); pOpt->Parm[4] = pClassVar->GetVarByName("GnRho")->getD(); if (fabs(pOpt->Parm[4])<1.0e-9) { pOpt->Parm[4] = 1.0; pClassVar->GetVarByName("GnRho")->set(pOpt->Parm[4]); } pOpt->Parm[5] = pClassVar->GetVarByName("PwRho")->getD(); pOpt->Parm[6] = pClassVar->GetVarByName("GnTot")->getD(); pOpt->SetYMeas(IB.GetDParm()); pOpt->SetXMeas(IB.GetDParm(), 2); pOpt->SetXMeas(IB.GetDParm(), 1); pOpt->SetXMeas(IB.GetDParm(), 0); pOpt->Estimate(); pClassVar->GetVarByName("Output")->set(pOpt->Output); pClassVar->GetVarByName("Offset")->set(pOpt->Offset); pClassVar->GetVarByName("SampleDelay")->set(pOpt->SampleDelay); return pOpt->Output; break; } default: ASSERT(FALSE); //function not defined } return 0.0; } //--------------------------------------------------------------------------- void GCPartEqn::OnSave(FilingControlBlock &FCB/*FILE* f*/, pvoid pSubClass) { } //--------------------------------------------------------------------------- flag GCPartEqn::OnLoad(FilingControlBlock &FCB/*rCTokenFile f*/, pvoid pSubClass) { //pCOptimizer pOpt = (pCOptimizer)pSubClass; //pOpt->ChangeModel("PartSize"); return True; } //========================================================================== const short Idf_AveEqnAddMeas = 1; //--------------------------------------------------------------------------- GCAveEqn::GCAveEqn(rGCInsMngr IB) : GCClassVar(IB.m_pVarList, &IB.m_VarMap, "AveSizeEqn", VarClassDefn) { AddVar(IB, "Output", &GCDouble, VarConst); AddVar(IB, "Scale", &GCDouble); AddVar(IB, "Offset", &GCDouble); AddVar(IB, "Samples", &GCLong); AddVar(IB, "SampleDelay", &GCLong); AddVar(IB, "AdjustSO", &GCLong); AddVar(IB, "UseYMeas", &GCBit); AddVar(IB, "MinYValid", &GCDouble); AddVar(IB, "MaxYValid", &GCDouble); AddFunct(IB, "AddMeas", 7, False, Idf_AveEqnAddMeas); } //--------------------------------------------------------------------------- void GCAveEqn::Init(pGCClassVar pClassVar) { pCOptimizer pOpt = new COptimizer(); pClassVar->m_pSubClass = (pvoid)pOpt; pOpt->ChangeModel("AveSize"); pClassVar->GetVarByName("Output")->set(pOpt->Output); pClassVar->GetVarByName("Scale")->set(pOpt->Scale); pClassVar->GetVarByName("Offset")->set(pOpt->Offset); pClassVar->GetVarByName("Samples")->set(pOpt->NoSamples); pClassVar->GetVarByName("SampleDelay")->set(pOpt->SampleDelay); pClassVar->GetVarByName("AdjustSO")->set(pOpt->AdjSO); pClassVar->GetVarByName("UseYMeas")->set(pOpt->UseYMeas); pClassVar->GetVarByName("MinYValid")->set(pOpt->MinYValid); pClassVar->GetVarByName("MaxYValid")->set(pOpt->MaxYValid); } //--------------------------------------------------------------------------- void GCAveEqn::Done(pGCClassVar pClassVar) { delete (pCOptimizer)(pClassVar->m_pSubClass); } //--------------------------------------------------------------------------- double GCAveEqn::CallFunct(rGCInsMngr IB, pvoid pSubClass, short FunctId, pGCClassVar pClassVar) { pCOptimizer pOpt = (pCOptimizer)pSubClass; switch (FunctId) { case Idf_AveEqnAddMeas: { pOpt->Scale = pClassVar->GetVarByName("Scale")->getD(); pOpt->Offset = pClassVar->GetVarByName("Offset")->getD(); pOpt->NoSamples = pClassVar->GetVarByName("Samples")->getL(); pOpt->SampleDelay = pClassVar->GetVarByName("SampleDelay")->getL(); pOpt->AdjSO = pClassVar->GetVarByName("AdjustSO")->getL(); pOpt->UseYMeas = pClassVar->GetVarByName("UseYMeas")->getB(); pOpt->MinYValid = pClassVar->GetVarByName("MinYValid")->getD(); pOpt->MaxYValid = pClassVar->GetVarByName("MaxYValid")->getD(); pOpt->SetYMeas(IB.GetDParm()); pOpt->SetXMeas(IB.GetDParm(), 5); pOpt->SetXMeas(IB.GetDParm(), 4); pOpt->SetXMeas(IB.GetDParm(), 3); pOpt->SetXMeas(IB.GetDParm(), 2); pOpt->SetXMeas(IB.GetDParm(), 1); pOpt->SetXMeas(IB.GetDParm(), 0); pOpt->Estimate(); pClassVar->GetVarByName("Output")->set(pOpt->Output); pClassVar->GetVarByName("Offset")->set(pOpt->Offset); pClassVar->GetVarByName("SampleDelay")->set(pOpt->SampleDelay); return pOpt->Output; break; } default: ASSERT(FALSE); //function not defined } return 0.0; } //--------------------------------------------------------------------------- void GCAveEqn::OnSave(FilingControlBlock &FCB/*FILE* f*/, pvoid pSubClass) { } //--------------------------------------------------------------------------- flag GCAveEqn::OnLoad(FilingControlBlock &FCB/*rCTokenFile f*/, pvoid pSubClass) { //pCOptimizer pOpt = (pCOptimizer)pSubClass; //pOpt->ChangeModel("PartSize"); return True; } #endif //PMC //==========================================================================
[ [ [ 1, 12 ], [ 14, 253 ], [ 275, 372 ], [ 375, 614 ], [ 616, 637 ], [ 702, 773 ], [ 775, 792 ], [ 794, 847 ], [ 849, 867 ], [ 869, 888 ], [ 890, 910 ], [ 912, 933 ], [ 935, 957 ], [ 959, 978 ], [ 980, 998 ], [ 1000, 1018 ], [ 1021, 1039 ], [ 1042, 1060 ], [ 1063, 1082 ], [ 1084, 1101 ], [ 1103, 1121 ], [ 1123, 1141 ], [ 1143, 1162 ], [ 1164, 1182 ], [ 1184, 1203 ], [ 1205, 1225 ], [ 1227, 1245 ], [ 1247, 1262 ], [ 1314, 1317 ], [ 1319, 1337 ], [ 1339, 1357 ], [ 1360, 1380 ], [ 1383, 1403 ], [ 1405, 1413 ], [ 1418, 1426 ], [ 1428, 1450 ], [ 1452, 1548 ], [ 1550, 1648 ], [ 1650, 1768 ], [ 1770, 1861 ] ], [ [ 13, 13 ], [ 774, 774 ], [ 793, 793 ], [ 848, 848 ], [ 868, 868 ], [ 889, 889 ], [ 911, 911 ], [ 934, 934 ], [ 958, 958 ], [ 979, 979 ], [ 999, 999 ], [ 1019, 1020 ], [ 1040, 1041 ], [ 1061, 1062 ], [ 1083, 1083 ], [ 1102, 1102 ], [ 1122, 1122 ], [ 1142, 1142 ], [ 1163, 1163 ], [ 1183, 1183 ], [ 1204, 1204 ], [ 1226, 1226 ], [ 1246, 1246 ], [ 1263, 1313 ], [ 1318, 1318 ], [ 1338, 1338 ], [ 1358, 1359 ], [ 1381, 1382 ], [ 1404, 1404 ], [ 1414, 1417 ], [ 1427, 1427 ], [ 1451, 1451 ], [ 1549, 1549 ], [ 1649, 1649 ], [ 1769, 1769 ] ], [ [ 254, 274 ], [ 373, 374 ], [ 615, 615 ], [ 638, 701 ] ] ]
211b4b8c54809a4b837d84bc0a1c274a357f131c
279b68f31b11224c18bfe7a0c8b8086f84c6afba
/playground/barfan/0.0.1-DEV-01/response.hpp
78d50a5866f6b07cacdd5624c0939073ff800cc5
[]
no_license
bogus/findik
83b7b44b36b42db68c2b536361541ee6175bb791
2258b3b3cc58711375fe05221588d5a068da5ea8
refs/heads/master
2020-12-24T13:36:19.550337
2009-08-16T21:46:57
2009-08-16T21:46:57
32,120,100
0
0
null
null
null
null
UTF-8
C++
false
false
3,109
hpp
#ifndef FINDIK_IO_RESPONSE_HPP #define FINDIK_IO_RESPONSE_HPP #include <string> #include <vector> #include <boost/asio.hpp> #include <boost/logic/tribool.hpp> #include "header.hpp" #include "request.hpp" namespace findik { namespace io { /// A response received from server. class response { public: response(request & request__); enum status_type { // Informational continue_ = 100, switching_protocols = 101, // success ok = 200, created = 201, accepted = 202, no_content = 204, reset_content = 205, partial_content = 206, multiple_choices = 300, moved_permanently = 301, // redirection found = 302, see_other = 303, not_modified = 304, use_proxy = 305, switch_proxy = 306, temporary_redirect = 307, // client error bad_request = 400, unauthorized = 401, payment_required = 402, forbidden = 403, not_found = 404, method_not_allowed = 405, not_acceptable = 406, proxy_authentication_required = 407, request_timeout = 408, conflicy = 409, gone = 410, length_required = 411, precondition_failed = 412, request_entity_too_large = 413, request_uri_too_long = 414, unsupported_media_type = 415, requested_range_not_satifiable = 416, expectation_failed = 417, // server error internal_server_error = 500, not_implemented = 501, bad_gateway = 502, service_unavailable = 503, gateway_timeout = 504, http_version_not_supported = 505, // http extensions processing_webdab = 102, request_uri_too_long_ext = 122, multi_status_webdav = 207, i_am_a_teapot = 418, unprocessable_entity_webdav = 422, locked_webdav = 423, failed_dependency_webdav = 424, unordered_collection = 425, upgrade_required = 426, retry_with = 449, blocked = 450, variant_also_negotiates = 506, insufficient_storage_webdav = 507, bandwidth_limit_exceeded = 509, not_extended = 510 } status_code; enum content_encoding_type { gzip, deflate, none, other, indeterminate }; std::string status_line; unsigned int http_version_major; unsigned int http_version_minor; std::vector<header> headers; unsigned int content_length(); bool is_chunked(); void to_streambuf(boost::asio::streambuf & sbuf_); bool has_content(); const std::string & content_raw(); const std::string & content(); request & get_request(); void push_to_content(char input, bool is_chunked_data = true); const std::string & content_type(); // only applicable for text mimetypes const std::string & content_charset(); content_encoding_type content_encoding(); private: std::string content_uncompressed_; std::string content_chunked_; std::string content_raw_; unsigned int content_length_; std::string content_type_; std::string content_charset_; findik::io::request & request_; boost::tribool is_chunked_; content_encoding_type content_encoding_; const std::string & content_data(); }; } // namespace server3 } // namespace http #endif
[ "barfan@d40773b4-ada0-11de-b0a2-13e92fe56a31" ]
[ [ [ 1, 148 ] ] ]
72de0a78417c3d7ff6982863f75fa7fc9d988616
d609fb08e21c8583e5ad1453df04a70573fdd531
/trunk/OpenXP/数据库组件/src/HAdoConnect.cpp
2387f1cad9a950a421efb3fb38c37b8844bb29e1
[]
no_license
svn2github/openxp
d68b991301eaddb7582b8a5efd30bc40e87f2ac3
56db08136bcf6be6c4f199f4ac2a0850cd9c7327
refs/heads/master
2021-01-19T10:29:42.455818
2011-09-17T10:27:15
2011-09-17T10:27:15
21,675,919
0
1
null
null
null
null
GB18030
C++
false
false
16,854
cpp
#include "stdafx.h" #include "../include/HAdoConnect.h" #include <assert.h> #include <math.h> #pragma warning(disable:4996) //效验结果宏 #define EfficacyResult(hResult) { if (FAILED(hResult)) _com_issue_error(hResult); } ////////////////////////////////////////////////////////////////////////// CADOError::CADOError() { m_enErrorType = ErrorType_Nothing; } void CADOError::SetErrorInfo( enADOErrorType enErrorType, LPCTSTR pszDescribe ) { //设置错误 m_enErrorType = enErrorType; sprintf(m_szErrorDescribe,"%s",pszDescribe); //抛出错误 throw this; } ////////////////////////////////////////////////////////////////////////// //构造函数 HAdoConnect::HAdoConnect() : m_dwResumeConnectCount(30L),m_dwResumeConnectTime(30L) { ::CoInitialize(NULL);//初始化com组件 //引用计数 m_nRef = 0; //状态变量 m_dwConnectCount = 0; m_dwConnectErrorTime = 0L; //创建对象 m_DBCommand.CreateInstance(__uuidof(Command)); m_DBRecordset.CreateInstance(__uuidof(Recordset)); m_DBConnection.CreateInstance(__uuidof(Connection)); //效验数据 assert(m_DBCommand != NULL); assert(m_DBRecordset != NULL); assert(m_DBConnection != NULL); if (m_DBCommand == NULL) throw _T("数据库命令对象创建失败"); if (m_DBRecordset == NULL) throw _T("数据库记录集对象创建失败"); if (m_DBConnection == NULL) throw _T("数据库连接对象创建失败"); //设置变量 m_DBCommand->CommandType = adCmdStoredProc; return; } //析构函数 HAdoConnect::~HAdoConnect() { //关闭连接 CloseConnection(); //释放对象 m_DBCommand.Release(); m_DBRecordset.Release(); m_DBConnection.Release(); // 释放环境 ::CoUninitialize(); return; } //打开连接 bool __cdecl HAdoConnect::OpenConnection() { //连接数据库 try { //关闭连接 CloseConnection(); //连接数据库 EfficacyResult(m_DBConnection->Open(_bstr_t(m_szConnect),L"",L"",adConnectUnspecified)); m_DBConnection->CursorLocation = adUseClient; m_DBCommand->ActiveConnection = m_DBConnection; //设置变量 m_dwConnectCount = 0L; m_dwConnectErrorTime = 0L; return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //关闭记录 bool __cdecl HAdoConnect::CloseRecordset() { try { if (IsRecordsetOpened()) { EfficacyResult(m_DBRecordset->Close()); } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //关闭连接 bool __cdecl HAdoConnect::CloseConnection() { try { CloseRecordset(); if ((m_DBConnection != NULL)&&(m_DBConnection->GetState() != adStateClosed)) { EfficacyResult(m_DBConnection->Close()); } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //重新连接 bool __cdecl HAdoConnect::TryConnectAgain(bool bFocusConnect, CComError * pComError) { try { //判断重连 bool bReConnect = bFocusConnect; if (bReConnect == false) { DWORD dwNowTime = (DWORD)time(NULL); if ((m_dwConnectErrorTime+m_dwResumeConnectTime) > dwNowTime) { bReConnect = true; } } if ((bReConnect == false) && (m_dwConnectCount>m_dwResumeConnectCount)) { bReConnect = true; } //设置变量 m_dwConnectCount++; m_dwConnectErrorTime = (DWORD)time(NULL); if (bReConnect == false) { if (pComError != NULL) { SetErrorInfo(ErrorType_Connect,GetComErrorDescribe(*pComError)); } return false; } //重新连接 OpenConnection(); return true; } catch (CADOError *pADOError) { //重新连接错误 if (pComError != NULL) { SetErrorInfo(ErrorType_Connect,GetComErrorDescribe(*pComError)); } else { throw pADOError; } } return false; } //设置信息 bool __cdecl HAdoConnect::SetConnectionInfo(LPCTSTR szIP, WORD wPort, LPCTSTR szData, LPCTSTR szName, LPCTSTR szPass) { //效验参数 assert(szIP!=NULL); assert(szData!=NULL); assert(szName!=NULL); assert(szPass!=NULL); //构造连接字符串 sprintf(m_szConnect,_T("Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;Initial Catalog=%s;Data Source=%s,%ld;"), szPass,szName,szData,szIP,wPort); return true; } //是否连接错误 bool __cdecl HAdoConnect::IsConnectError() { try { //状态判断 if (m_DBConnection == NULL) { return true; } if (m_DBConnection->GetState() == adStateClosed) { return true; } //参数判断 long lErrorCount = m_DBConnection->Errors->Count; if (lErrorCount > 0L) { ErrorPtr pError = NULL; for(long i = 0; i < lErrorCount; i++) { pError = m_DBConnection->Errors->GetItem(i); if (pError->Number == 0x80004005) { return true; } } } return false; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //是否打开 bool __cdecl HAdoConnect::IsRecordsetOpened() { if (m_DBRecordset == NULL) { return false; } if (m_DBRecordset->GetState() == adStateClosed) { return false; } return true; } //往下移动 void __cdecl HAdoConnect::MoveToNext() { try { m_DBRecordset->MoveNext(); } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return; } //移到开头 void __cdecl HAdoConnect::MoveToFirst() { try { m_DBRecordset->MoveFirst(); } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return; } //是否结束 bool __cdecl HAdoConnect::IsEndRecordset() { try { return (m_DBRecordset->EndOfFile == VARIANT_TRUE); } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return true; } //获取数目 long __cdecl HAdoConnect::GetRecordCount() { try { if (m_DBRecordset == NULL) { return 0; } return m_DBRecordset->GetRecordCount(); } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return 0; } //获取大小 long __cdecl HAdoConnect::GetActualSize(LPCTSTR pszParamName) { assert(pszParamName!=NULL); try { return m_DBRecordset->Fields->Item[pszParamName]->ActualSize; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return -1; } //绑定对象 //bool __cdecl HAdoConnect::BindToRecordset(CADORecordBinding * pBind) //{ /*assert(pBind!=NULL); try { IADORecordBindingPtr pIBind(m_DBRecordset); pIBind->BindToRecordset(pBind); return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); }*/ // return false; //} //获取参数 bool __cdecl HAdoConnect::GetFieldValue(LPCTSTR lpFieldName, BYTE & bValue) { try { bValue = 0; _variant_t vtFld = m_DBRecordset->Fields->GetItem(lpFieldName)->Value; switch(vtFld.vt) { case VT_BOOL: { bValue = (vtFld.boolVal != 0)?1:0; break; } case VT_I2: case VT_UI1: { bValue = (vtFld.iVal > 0)?1:0; break; } case VT_NULL: case VT_EMPTY: { bValue = 0; break; } default: bValue = (BYTE)vtFld.iVal; } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //获取参数 bool __cdecl HAdoConnect::GetFieldValue(LPCTSTR lpFieldName, UINT & ulValue) { try { ulValue = 0L; _variant_t vtFld = m_DBRecordset->Fields->GetItem(lpFieldName)->Value; if ((vtFld.vt != VT_NULL)&&(vtFld.vt != VT_EMPTY)) { ulValue = vtFld.lVal; } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //获取参数 bool __cdecl HAdoConnect::GetFieldValue(LPCTSTR lpFieldName, DOUBLE & dbValue) { try { dbValue = 0.0L; _variant_t vtFld = m_DBRecordset->Fields->GetItem(lpFieldName)->Value; switch(vtFld.vt) { case VT_R4: { dbValue = vtFld.fltVal; break; } case VT_R8: { dbValue = vtFld.dblVal; break; } case VT_DECIMAL: { dbValue = vtFld.decVal.Lo32; dbValue *= (vtFld.decVal.sign == 128)?-1:1; dbValue /= pow((float)10,vtFld.decVal.scale); break; } case VT_UI1: { dbValue = vtFld.iVal; break; } case VT_I2: case VT_I4: { dbValue = vtFld.lVal; break; } case VT_NULL: case VT_EMPTY: { dbValue = 0.0L; break; } default: dbValue = vtFld.dblVal; } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //获取参数 bool __cdecl HAdoConnect::GetFieldValue(LPCTSTR lpFieldName, LONG & lValue) { try { lValue = 0L; _variant_t vtFld = m_DBRecordset->Fields->GetItem(lpFieldName)->Value; if ((vtFld.vt != VT_NULL)&&(vtFld.vt != VT_EMPTY)) { lValue = vtFld.lVal; } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //获取参数 bool __cdecl HAdoConnect::GetFieldValue(LPCTSTR lpFieldName, DWORD & ulValue) { try { ulValue = 0L; _variant_t vtFld = m_DBRecordset->Fields->GetItem(lpFieldName)->Value; if ((vtFld.vt != VT_NULL)&&(vtFld.vt != VT_EMPTY)) { ulValue = vtFld.ulVal; } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //获取参数 bool __cdecl HAdoConnect::GetFieldValue(LPCTSTR lpFieldName, INT & nValue) { try { nValue = 0; _variant_t vtFld = m_DBRecordset->Fields->GetItem(lpFieldName)->Value; switch(vtFld.vt) { case VT_BOOL: { nValue = vtFld.boolVal; break; } case VT_I2: case VT_UI1: { nValue = vtFld.iVal; break; } case VT_NULL: case VT_EMPTY: { nValue = 0; break; } default: nValue = vtFld.iVal; } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //获取参数 bool __cdecl HAdoConnect::GetFieldValue(LPCTSTR lpFieldName, __int64 & llValue) { try { llValue = 0L; _variant_t vtFld = m_DBRecordset->Fields->GetItem(lpFieldName)->Value; if ((vtFld.vt != VT_NULL)&&(vtFld.vt != VT_EMPTY)) { llValue = vtFld.llVal; } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //获取参数 bool __cdecl HAdoConnect::GetFieldValue(LPCTSTR lpFieldName, TCHAR szBuffer[], UINT uSize) { try { _variant_t vtFld = m_DBRecordset->Fields->GetItem(lpFieldName)->Value; if (vtFld.vt == VT_BSTR) { lstrcpy(szBuffer,(char*)_bstr_t(vtFld)); return true; } return false; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //获取参数 bool __cdecl HAdoConnect::GetFieldValue(LPCTSTR lpFieldName, WORD & wValue) { try { wValue = 0L; _variant_t vtFld = m_DBRecordset->Fields->GetItem(lpFieldName)->Value; if ((vtFld.vt != VT_NULL)&&(vtFld.vt != VT_EMPTY)) { wValue = (WORD)vtFld.ulVal; } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //获取参数 bool __cdecl HAdoConnect::GetFieldValue(LPCTSTR lpFieldName, COleDateTime & Time) { try { _variant_t vtFld = m_DBRecordset->Fields->GetItem(lpFieldName)->Value; switch(vtFld.vt) { case VT_DATE: { COleDateTime TempTime(vtFld); Time = TempTime; break; } case VT_EMPTY: case VT_NULL: { Time.SetStatus(COleDateTime::null); break; } default: return false; } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //获取参数 bool __cdecl HAdoConnect::GetFieldValue(LPCTSTR lpFieldName, bool & bValue) { try { _variant_t vtFld = m_DBRecordset->Fields->GetItem(lpFieldName)->Value; switch(vtFld.vt) { case VT_BOOL: { bValue = (vtFld.boolVal == 0)?false:true; break; } case VT_EMPTY: case VT_NULL: { bValue = false; break; } default: return false; } return true; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return false; } //获取返回数值 long __cdecl HAdoConnect::GetReturnValue() { try { _ParameterPtr Parameter; long lParameterCount = m_DBCommand->Parameters->Count; for (long i = 0; i < lParameterCount; i++) { Parameter = m_DBCommand->Parameters->Item[i]; if (Parameter->Direction == adParamReturnValue) { return Parameter->Value.lVal; } } assert(FALSE); } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return 0; } //删除参数 void __cdecl HAdoConnect::ClearAllParameters() { try { long lParameterCount = m_DBCommand->Parameters->Count; if (lParameterCount > 0L) { for (long i = lParameterCount; i > 0; i--) { m_DBCommand->Parameters->Delete(i-1); } } } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return; } //设置存储过程 void __cdecl HAdoConnect::SetSPName(LPCTSTR pszSpName) { assert(pszSpName != NULL); try { m_DBCommand->CommandText = pszSpName; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return; } //获得参数 void __cdecl HAdoConnect::GetParameterValue(LPCTSTR pszParamName, _variant_t & vtValue) { //效验参数 assert(pszParamName != NULL); //获取参数 try { vtValue.Clear(); vtValue = m_DBCommand->Parameters->Item[pszParamName]->Value; } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return; } //插入参数 void __cdecl HAdoConnect::AddParamter(LPCTSTR pszName, ADOCG::ParameterDirectionEnum Direction, ADOCG::DataTypeEnum Type, long lSize, _variant_t & vtValue) { assert(pszName != NULL); try { _ParameterPtr Parameter = m_DBCommand->CreateParameter(pszName,Type,Direction,lSize,vtValue); m_DBCommand->Parameters->Append(Parameter); } catch (CComError & ComError) { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } return; } //执行语句 bool __cdecl HAdoConnect::Execute(LPCTSTR pszCommand) { assert(pszCommand != NULL); try { m_DBConnection->CursorLocation = adUseClient; m_DBConnection->Execute(pszCommand,NULL,adExecuteNoRecords); return true; } catch (CComError & ComError) { if (IsConnectError() == true) { TryConnectAgain(false,&ComError); } else { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } } return false; } //执行命令 bool __cdecl HAdoConnect::ExecuteCommand(bool bRecordset) { try { //关闭记录集 CloseRecordset(); //执行命令 if (bRecordset == true) { m_DBRecordset->PutRefSource(m_DBCommand); m_DBRecordset->CursorLocation = adUseClient; EfficacyResult(m_DBRecordset->Open((IDispatch *)m_DBCommand,vtMissing,adOpenForwardOnly,adLockReadOnly,adOptionUnspecified)); } else { m_DBConnection->CursorLocation=adUseClient; EfficacyResult(m_DBCommand->Execute(NULL,NULL,adExecuteNoRecords)); } return true; } catch (CComError & ComError) { if (IsConnectError() == true) { TryConnectAgain(false,&ComError); } else { SetErrorInfo(ErrorType_Other,GetComErrorDescribe(ComError)); } } return false; } //获取错误 LPCTSTR HAdoConnect::GetComErrorDescribe(CComError & ComError) { _bstr_t bstrDescribe(ComError.Description()); sprintf(m_szErrorDescribe,_T("ADO 错误:0x%8x,%s"),ComError.Error(),(LPCTSTR)bstrDescribe); return m_szErrorDescribe; } //设置错误 void HAdoConnect::SetErrorInfo(enADOErrorType enErrorType, LPCTSTR pszDescribe) { m_ADOError.SetErrorInfo(enErrorType,pszDescribe); return; }
[ "[email protected]@f92b348d-55a1-4afa-8193-148a6675784b" ]
[ [ [ 1, 826 ] ] ]
7f4efd0f1e0482cab00a138ab9bef648658c134f
2acd91cf2dfe87f4c78fba230de2c2ffc90350ea
/ salad-bar-in-space-game/edge/bouncibility/src/SoundManager.cpp
6042ddcec2bb1353c9d01cdfb6b4a85313c8c864
[]
no_license
Joshvanburen/salad-bar-in-space-game
5f410a06be475edee1ab85950c667e6a6f970763
b23a35c832258f4fc1a921a45ab4238c734ef1f0
refs/heads/master
2016-09-01T18:46:29.672326
2008-05-07T18:40:30
2008-05-07T18:40:30
32,195,299
0
0
null
null
null
null
UTF-8
C++
false
false
6,817
cpp
#include "irrXML.h" #include "irrKlang.h" #include "SoundManager.h" using namespace irrklang; using namespace Sound; Sound::Audio::Audio(const std::string& sName, const std::string& sFilename, bool is3D) : m_pSound(NULL), m_Name(sName), m_Filename(sFilename){ this->is3D = is3D; this->position = irrklang::vec3df(0.0,0.0,0.0); this->m_Sources.push_back(SoundManager::engine->addSoundSourceFromFile(m_Filename.c_str(), irrklang::ESM_AUTO_DETECT, true)); } Sound::Audio::~Audio(){ destroy(); } void Sound::Audio::destroy(){ if (m_pSound){ m_pSound->drop(); } m_pSound = NULL; m_Sources.clear(); } void Sound::Audio::appendAudio(irrklang::ISoundSource* soundSource){ this->m_Sources.push_back(soundSource); } void Sound::Audio::setVolume(float newVolume){ SoundSourceList::iterator sourceEnd = m_Sources.end(); for (m_SourcesItr = m_Sources.begin(); m_SourcesItr != sourceEnd; ++m_SourcesItr){ (*m_SourcesItr)->setDefaultVolume(newVolume); } } float Sound::Audio::getVolume(){ if (m_Sources.size() > 0){ return m_Sources[0]->getDefaultVolume(); } else{ return 0.0; } } void Sound::Audio::setPosition(vec3df& newPosition){ this->position = newPosition; if (m_pSound){ m_pSound->setPosition(newPosition); } } void Sound::Audio::setPosition(float x, float y, float z){ this->position = irrklang::vec3df(x, y, z); if (m_pSound){ m_pSound->setPosition(position); } } vec3df Sound::Audio::getPosition(){ return position; } void Sound::Audio::setPaused(bool paused){ if (m_pSound){ m_pSound->setIsPaused(paused); } } void Sound::Audio::setMaxDistance(float distance){ SoundSourceList::iterator sourceEnd = m_Sources.end(); for (m_SourcesItr = m_Sources.begin(); m_SourcesItr != sourceEnd; ++m_SourcesItr){ (*m_SourcesItr)->setDefaultMaxDistance(distance); } } void Sound::Audio::setMinDistance(float distance){ SoundSourceList::iterator sourceEnd = m_Sources.end(); for (m_SourcesItr = m_Sources.begin(); m_SourcesItr != sourceEnd; ++m_SourcesItr){ (*m_SourcesItr)->setDefaultMinDistance(distance); } } const std::string& Sound::Audio::getName(){ return m_Name; } void Sound::Audio::play(bool looped){ int value = rand() % m_Sources.size(); if (is3D){ m_pSound = SoundManager::engine->play3D(m_Sources[value], position, looped, false, true); } else{ m_pSound = SoundManager::engine->play2D(m_Sources[value], looped, false, true); } } bool Sound::Audio::isPlaying(){ return !m_pSound->isFinished(); } void Sound::Audio::stop(){ if (m_pSound){ m_pSound->stop(); } } irrklang::ISoundEngine* SoundManager::engine = NULL; SoundManager::SoundManager() { engine = NULL; } SoundManager::~SoundManager(){ this->shutdown(); } void SoundManager::readInXML(const std::string& XMLFilename){ irr::io::IrrXMLReader* xml = irr::io::createIrrXMLReader(XMLFilename.c_str()); if (!xml){ std::cout << "There was an error loading the xml file " << XMLFilename << ".\n"; throw Sound::SoundManagerInitException(); } std::string name; std::string filename; float volume = 0.0; int is3D = 0; float x = 0.0; float y = 0.0; float z = 0.0; float min_distance = 0.0; float max_distance = 5.0; while(xml && xml->read()){ switch(xml->getNodeType()){ case irr::io::EXN_TEXT: //No text nodes break; case irr::io::EXN_ELEMENT: if (!strcmp("sound", xml->getNodeName())){ name = xml->getAttributeValue("name"); filename = xml->getAttributeValue("filename"); volume = xml->getAttributeValueAsFloat("volume"); is3D = xml->getAttributeValueAsInt("3D"); Sound::Audio* audio = new Sound::Audio(name, filename, (bool)is3D); audio->setVolume(volume); min_distance = xml->getAttributeValueAsFloat("distance_min"); max_distance = xml->getAttributeValueAsFloat("distance_max"); audio->setPosition(irrklang::vec3df(x, y, z)); audio->setMinDistance(min_distance); audio->setMaxDistance(max_distance); m_AudioItr = m_AudioMap.find(name); //If the script is already in the map, print out and continue; if (m_AudioItr != m_AudioMap.end()){ std::cout << "Sound with name: " << name << "already exists. Appending sound to current Audio object.\n"; m_AudioItr->second->appendAudio(audio->m_Sources[0]); delete audio; } else{ m_AudioMap.insert(std::make_pair(name, audio)); } } break; } } delete xml; return; } void SoundManager::init(){ engine = createIrrKlangDevice(); if (!engine){ throw SoundManagerInitException(); } //Load in global sounds readInXML("./res/sounds/global.xml"); } void SoundManager::addNewSounds(const std::string& XMLSoundDefinitions){ readInXML(XMLSoundDefinitions); } void SoundManager::shutdown(){ removeAll(); engine->drop(); } void SoundManager::reset(){ this->shutdown(); this->init(); } void SoundManager::update(){ //need to get properties from the main camera. //Set the current listener position to the camera or the ball or whatever each time update is called. // engine->setListenerPosition(); } void SoundManager::removeAll(){ Sound::StrAudioMap::iterator audioItrEnd = m_AudioMap.end(); for (m_AudioItr = m_AudioMap.begin(); m_AudioItr != audioItrEnd; ++m_AudioItr){ m_AudioItr->second->destroy(); delete m_AudioItr->second; } engine->removeAllSoundSources(); m_AudioMap.clear(); } void SoundManager::removeSound(Sound::Audio* sound){ sound->destroy(); delete sound; m_AudioMap.erase(sound->getName()); } void SoundManager::removeSound(const std::string& soundName){ m_AudioItr = m_AudioMap.find(soundName); if (m_AudioItr == m_AudioMap.end()){ //sound doesn't exist, so don't remove anything return; } m_AudioItr->second->destroy(); delete m_AudioItr->second; m_AudioMap.erase(m_AudioItr); } Sound::Audio* SoundManager::addSound(const std::string& soundName, const std::string& filename, bool is3D){ m_AudioItr = m_AudioMap.find(soundName); Sound::Audio* audio = new Sound::Audio(soundName, filename, is3D); if (m_AudioItr != m_AudioMap.end()){ m_AudioItr->second->appendAudio(audio->m_Sources[0]); delete audio; return m_AudioItr->second; } else{ m_AudioMap.insert(std::make_pair(soundName, audio)); return audio; } } Sound::Audio* SoundManager::getSound(const std::string& soundName){ m_AudioItr = m_AudioMap.find(soundName); //If the sound wasn't found, throw exception if (m_AudioItr == m_AudioMap.end()){ throw Sound::AudioDoestExist(); } return (m_AudioItr->second); }
[ "[email protected]@1a2710a4-8244-0410-8b66-391840787a9e" ]
[ [ [ 1, 297 ] ] ]
3c859625f59065d43f4508d400d8be41bdf27f6d
559770fbf0654bc0aecc0f8eb33843cbfb5834d9
/haina/codes/beluga/client/symbian/BelugaDb/src/contact/CContactDb.cpp
52c20746ed1deb185ceab0b449086adee7f52015
[]
no_license
CMGeorge/haina
21126c70c8c143ca78b576e1ddf352c3d73ad525
c68565d4bf43415c4542963cfcbd58922157c51a
refs/heads/master
2021-01-11T07:07:16.089036
2010-08-18T09:25:07
2010-08-18T09:25:07
49,005,284
1
0
null
null
null
null
UTF-8
C++
false
false
30,828
cpp
/* ============================================================================ Name : CContactDb.cpp Author : shaochuan.yang Copyright : haina Description : Contact Database ============================================================================ */ #include <string.h> #include <stdlib.h> #include <time.h> #include "CContact.h" #include "CGroup.h" #include "CPhoneContact.h" #include "CIMContact.h" #include "CContactDb.h" #include "CContactIterator.h" GLREF_C void freeAddressArray(GPtrArray * pArray); static void insert_contact_ext_row(gpointer key, gpointer value, gpointer user_data) { char sql[128] = {0}; guint32 nContactId = 0; CPhoneContact * contact = (CPhoneContact*)user_data; contact->GetEntityDb()->GetMaxId(&nContactId); sprintf(sql, "insert into contact_ext values(NULL, %d, %d, %s);", nContactId, *((guint32*)key), (char*)value); contact->GetEntityDb()->GetDatabase()->execDML(sql); } static void update_contact_ext_row(gpointer key, gpointer value, gpointer user_data) { char sql[128] = {0}; GString * fieldValue = NULL; CPhoneContact * contact = (CPhoneContact*)user_data; contact->GetFieldValue(ContactField_Id, &fieldValue); sprintf(sql, "insert into contact_ext values(NULL, %d, %d, %s);", atoi(fieldValue->str), *((guint32*)key), (char*)value); g_string_free(fieldValue, TRUE); contact->GetEntityDb()->GetDatabase()->execDML(sql); } CContactDb::CContactDb() { m_nDbErrCode = ECode_No_Error; } CContactDb::~CContactDb() { } EXPORT_C gint32 CContactDb::InitEntityDb() /* fill fields name */ { OpenDatabase(); CppSQLite3Table contactTable = m_dbBeluga.getTable("select * from contact limit 1;"); m_pFieldsName = g_ptr_array_sized_new(contactTable.numFields()); if (!m_pFieldsName) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } for (int i=0; i<contactTable.numFields(); i++) g_ptr_array_add(m_pFieldsName, g_string_new((gchar*)contactTable.fieldName(i))); CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::GetMaxId(guint32 * nMaxId) { OpenDatabase(); *nMaxId = m_dbBeluga.execScalar("select max(cid) from contact;"); CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::GetEntityById(guint32 nId, CDbEntity** ppEntity) { char sql[128] = {0}; *ppEntity = NULL; OpenDatabase(); sprintf(sql, "select * from contact where cid = %d;", nId); CppSQLite3Query query = m_dbBeluga.execQuery(sql); if (query.eof()) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_Not_Exist); } if (ContactType_Phone == query.getIntField(ContactField_Type)) *ppEntity = new CPhoneContact(this); else *ppEntity = new CIMContact(this); if (NULL == *ppEntity) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } for (int i=0; i<query.numFields(); i++) { GString * fieldValue = g_string_new(query.fieldValue(i)); (*ppEntity)->SetFieldValue(i, fieldValue); g_string_free(fieldValue, TRUE); } CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::SaveEntity(CDbEntity * pEntity) { int i; char sql[256] = {0}; OpenDatabase(); try { m_dbBeluga.execDML("begin transaction;"); /* insert contact entity */ strcpy(sql, "insert into contact values(NULL"); for (i=0; i<ContactField_EndFlag - 1; i++) strcat(sql, ", ?"); strcat(sql, ");"); CppSQLite3Statement statement = m_dbBeluga.compileStatement(sql); for (i=1; i<ContactField_EndFlag; i++) { GString * fieldValue = NULL; if (ECode_No_Error == pEntity->GetFieldValue(i, &fieldValue)) { statement.bind(i, fieldValue->str); g_string_free(fieldValue, TRUE); } else statement.bindNull(i); } statement.execDML(); statement.reset(); /* insert contact_ext entity */ CContact * contact = (CContact*)pEntity; GString * fieldValue = NULL; contact->GetFieldValue(ContactField_Type, &fieldValue); if (ContactType_Phone == atoi(fieldValue->str)) { CPhoneContact * phonecontact = (CPhoneContact*)pEntity; /* insert phones */ GHashTable * phones = NULL; phonecontact->GetAllPhones(&phones); g_hash_table_foreach(phones, insert_contact_ext_row, phonecontact); g_hash_table_destroy(phones); /* insert emails */ GHashTable * emails = NULL; phonecontact->GetAllEmails(&emails); g_hash_table_foreach(emails, insert_contact_ext_row, phonecontact); g_hash_table_destroy(emails); /* insert ims */ GHashTable * ims = NULL; phonecontact->GetAllIMs(&ims); g_hash_table_foreach(ims, insert_contact_ext_row, phonecontact); g_hash_table_destroy(ims); /* insert addresses */ GPtrArray * addresses = NULL; phonecontact->GetAllAddresses(&addresses); for (guint32 j=0; j<addresses->len; j++) { guint32 nContactId = 0; memset(sql, 0, sizeof(sql)); GetMaxId(&nContactId); stAddress * addr = (stAddress*)g_ptr_array_index(addresses, j); sprintf(sql, "insert into address values(NULL, %d, %s, %s %s, %s, %s, %s);", addr->atype, addr->block, addr->street, addr->district, addr->city, addr->state, addr->country, addr->postcode); m_dbBeluga.execDML(sql); guint32 nAddrId = m_dbBeluga.execScalar("select max(aid) from address;"); memset(sql, 0, sizeof(sql)); sprintf(sql, "insert into contact_ext values(NULL, %d, %d, %d);", nContactId, addr->atype, nAddrId); m_dbBeluga.execDML(sql); } freeAddressArray(addresses); } g_string_free(fieldValue, TRUE); m_dbBeluga.execDML("commit transaction;"); delete pEntity; pEntity = NULL; CloseDatabase(); return 0; } catch(CppSQLite3Exception& e) { m_dbBeluga.execDML("rollback transaction;"); delete pEntity; pEntity = NULL; CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_Insert_Failed); } return 0; } EXPORT_C gint32 CContactDb::DeleteEntity(guint32 nEntityId) { char sql[128] = {0}; OpenDatabase(); sprintf(sql, "delete from contact where cid = %d;", nEntityId); m_dbBeluga.execDML(sql); CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::UpdateEntity(CDbEntity * pEntity) { int i; char sql[256] = {0}; OpenDatabase(); try { m_dbBeluga.execDML("begin transaction;"); /* update contact entity */ strcpy(sql, "update contact set "); for (i=1; i<ContactField_EndFlag; i++) { GString * fieldName = (GString*)g_ptr_array_index(m_pFieldsName, i); strcat(sql, fieldName->str); strcat(sql, " = ?"); if (i != ContactField_EndFlag - 1) strcat(sql, ", "); } strcat(sql, "where cid = ?;"); CppSQLite3Statement statement = m_dbBeluga.compileStatement(sql); for (i=1; i<ContactField_EndFlag; i++) { GString * fieldValue = NULL; if (ECode_No_Error == pEntity->GetFieldValue(i, &fieldValue)) { statement.bind(i, fieldValue->str); g_string_free(fieldValue, TRUE); } else statement.bindNull(i); } statement.execDML(); statement.reset(); /* update contact_ext entity */ CContact * contact = (CContact*)pEntity; GString * fieldValue = NULL; contact->GetFieldValue(ContactField_Type, &fieldValue); if (ContactType_Phone == atoi(fieldValue->str)) { CPhoneContact * phonecontact = (CPhoneContact*)pEntity; GString * fieldId = NULL; phonecontact->GetFieldValue(ContactField_Id, &fieldId); memset(sql, 0, sizeof(sql)); sprintf(sql, "delete from contact_ext where cid = %d;", atoi(fieldId->str)); m_dbBeluga.execDML(sql); /* insert phones */ GHashTable * phones = NULL; phonecontact->GetAllPhones(&phones); g_hash_table_foreach(phones, update_contact_ext_row, phonecontact); g_hash_table_destroy(phones); /* insert emails */ GHashTable * emails = NULL; phonecontact->GetAllEmails(&emails); g_hash_table_foreach(emails, update_contact_ext_row, phonecontact); g_hash_table_destroy(emails); /* insert ims */ GHashTable * ims = NULL; phonecontact->GetAllIMs(&ims); g_hash_table_foreach(ims, update_contact_ext_row, phonecontact); g_hash_table_destroy(ims); /* insert addresses */ GPtrArray * addresses = NULL; phonecontact->GetAllAddresses(&addresses); for (guint32 j=0; j<addresses->len; j++) { memset(sql, 0, sizeof(sql)); stAddress * addr = (stAddress*)g_ptr_array_index(addresses, j); sprintf(sql, "insert into address values(NULL, %d, %s, %s %s, %s, %s, %s);", addr->atype, addr->block, addr->street, addr->district, addr->city, addr->state, addr->country, addr->postcode); guint32 nAddrId = m_dbBeluga.execScalar("select max(aid) from address;"); memset(sql, 0, sizeof(sql)); sprintf(sql, "insert into contact_ext values(NULL, %d, %d, %d);", atoi(fieldId->str), addr->atype, nAddrId); m_dbBeluga.execDML(sql); } freeAddressArray(addresses); g_string_free(fieldId, TRUE); } g_string_free(fieldValue, TRUE); m_dbBeluga.execDML("commit transaction;"); delete pEntity; pEntity = NULL; CloseDatabase(); return 0; } catch(CppSQLite3Exception& e) { m_dbBeluga.execDML("rollback transaction;"); delete pEntity; pEntity = NULL; CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_Update_Failed); } return 0; } EXPORT_C gint32 CContactDb::DeleteAllContactsByTag(guint32 nTagId) { char sql[256] = {0}; OpenDatabase(); sprintf(sql, "delete from contact where cid in (select cid from r_contact_group where gid in "\ "(select gid from cgroup where tid= %d)); ", nTagId); m_dbBeluga.execDML(sql); CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::ReleaseContactGroupRelation(CContact * pContact, CGroup * pGroup) { GString * ContactId = NULL; GString * GroupId = NULL; pContact->GetFieldValue(ContactField_Id, &ContactId); pGroup->GetFieldValue(GroupField_Id, &GroupId); ReleaseContactGroupRelation(atoi(ContactId->str), atoi(GroupId->str)); g_string_free(ContactId, TRUE); g_string_free(GroupId, TRUE); return 0; } EXPORT_C gint32 CContactDb::ReleaseContactGroupRelation(guint32 nContactId, guint32 nGroupId) { char sql[128] = {0}; OpenDatabase(); sprintf(sql, "delete from r_contact_group where cid = %d and gid = %d;", nContactId, nGroupId); m_dbBeluga.execDML(sql); CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::ReleaseContactAllRelations(guint32 nContactId) { char sql[128] = {0}; OpenDatabase(); sprintf(sql, "delete from r_contact_group where cid = %d;", nContactId); m_dbBeluga.execDML(sql); CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::ReleaseContactAllRelations(CContact * pContact) { GString * ContactId = NULL; pContact->GetFieldValue(ContactField_Id, &ContactId); ReleaseContactAllRelations(atoi(ContactId->str)); g_string_free(ContactId, TRUE); return 0; } EXPORT_C gint32 CContactDb::CreateContactGroupRelation(CContact * pContact, CGroup * pGroup) { GString * ContactId = NULL; GString * GroupId = NULL; pContact->GetFieldValue(ContactField_Id, &ContactId); pGroup->GetFieldValue(GroupField_Id, &GroupId); CreateContactGroupRelation(atoi(ContactId->str), atoi(GroupId->str)); g_string_free(ContactId, TRUE); g_string_free(GroupId, TRUE); return 0; } EXPORT_C gint32 CContactDb::CreateContactGroupRelation(guint32 nContactId, guint32 nGroupId) { char sql[128] = {0}; OpenDatabase(); sprintf(sql, "insert into r_contact_group values(%d, %d);", nContactId, nGroupId); m_dbBeluga.execDML(sql); CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::SearchContactsByTag(guint32 nTagId, GArray * fieldsIndex, GPtrArray * fieldsValue, gboolean onlyPref, CContactIterator ** ppContactIterator) { char sql[512] = {0}; OpenDatabase(); if (onlyPref || nTagId != ContactType_Phone) strcpy(sql, "select * from contact c where "); else strcpy(sql, "select c.*, ext.* from contact c "\ "left join (select ce.cid ,ce.comm_key, ce.comm_value, a.* from contact_ext ce "\ "left join address a on ce.comm_value = a.aid) ext "\ "on c.cid = ext.cid where "); for (guint32 i=0; i<fieldsIndex->len; i++) for (guint32 j=ContactField_UserId; j<ContactField_EndFlag; j++) { if (g_array_index(fieldsIndex, guint32, i) == j) { strcat(sql, ((GString*)g_ptr_array_index(m_pFieldsName, j))->str); strcat(sql, " like '%"); strcat(sql, ((GString*)g_ptr_array_index(fieldsValue, i))->str); strcat(sql, "%' and"); } } strcat(sql, "c.cid >= 0 "); if (-1 != m_nSortFieldIndex) { strcat(sql, "order by c."); strcat(sql, ((GString*)g_ptr_array_index(m_pFieldsName, m_nSortFieldIndex))->str); strcat(sql, " asc;"); } m_dbQuery = m_dbBeluga.execQuery(sql); *ppContactIterator = NULL; *ppContactIterator = new CContactIterator(this); if (NULL == *ppContactIterator) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::SearchPhoneContactsByPhoneOrEmail(gchar * commValue, gboolean onlyPref, CContactIterator ** ppContactIterator) { char sql[512] = {0}; OpenDatabase(); if (onlyPref) strcpy(sql, "select * from contact c where cid in (select cid from contact_ext where comm_value like '%"); else strcpy(sql, "select c.*, ext.* from contact c "\ "left join (select ce.cid ,ce.comm_key, ce.comm_value, a.* from contact_ext ce "\ "left join address a on ce.comm_value = a.aid) ext "\ "on c.cid = ext.cid where c.cid in (select cid from contact_ext where comm_value like '%"); strcat(sql, commValue); strcat(sql, "%') order by c.name_spell asc;"); m_dbQuery = m_dbBeluga.execQuery(sql); *ppContactIterator = NULL; *ppContactIterator = new CContactIterator(this); if (NULL == *ppContactIterator) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::SearchContactsByName(guint32 nTagId, gchar* name, gboolean onlyPref, CContactIterator ** ppContactIterator) { char sql[512] = {0}; OpenDatabase(); if (nTagId != ContactType_Phone) sprintf(sql, "select * from contact where nickname_spell like \'%%s%\' order by nikename_spell asc;", name); else if (onlyPref) sprintf(sql, "select * from contact where name_spell like \'%%s%\' order by name_spell asc;", name); else sprintf(sql, "select c.*, ext.* from contact c "\ "left join (select ce.cid ,ce.comm_key, ce.comm_value, a.* from contact_ext ce "\ "left join address a on ce.comm_value = a.aid) ext "\ "on c.cid = ext.cid where name_spell like \'%%s%\' order by name_spell asc;", name); m_dbQuery = m_dbBeluga.execQuery(sql); *ppContactIterator = NULL; *ppContactIterator = new CContactIterator(this); if (NULL == *ppContactIterator) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } CloseDatabase(); return 0; } /* EXPORT_C gint32 CContactDb::SearchContactsByWordsFirstLetter(guint32 nTagId, gchar* nameLetters, gboolean onlyPref, CContactIterator ** ppContactIterator) { char sql[512] = {0}; OpenDatabase(); if (nTagId != ContactType_Phone) sprintf(sql, "select * from contact where nickname_spell like '\%%s\%' order by nickname_spell asc;", nameLetters); else if (onlyPref) sprintf(sql, "select * from contact where name_spell like '\%%s\%' order by name_spell asc;", nameLetters); else sprintf(sql, "select c.*, ext.* from contact c "\ "left join (select ce.cid ,ce.comm_key, ce.comm_value, a.* from contact_ext ce "\ "left join address a on ce.comm_value = a.aid) ext "\ "on c.cid = ext.cid where name_spell like '\%%s\%' order by name_spell asc;", nameLetters); m_dbQuery = m_dbBeluga.execQuery(sql); *ppContactIterator = NULL; *ppContactIterator = new CContactIterator(this); if (NULL == *ppContactIterator) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::GetMostMatchingContactByTag(guint32 nTagId, GArray * fieldsIndex, GPtrArray * fieldsValue, gboolean onlyPref, CContact ** ppContact) { char sql[512] = {0}; OpenDatabase(); if (onlyPref || nTagId != ContactType_Phone) strcpy(sql, "select * from contact where "); else strcpy(sql, "select c.*, ext.* from contact c "\ "left join (select ce.cid ,ce.comm_key, ce.comm_value, a.* from contact_ext ce "\ "left join address a on ce.comm_value = a.aid) ext "\ "on c.cid = ext.cid where "); for (int i=0; i<fieldsIndex->len; i++) for (int j=ContactField_UserId; j<ContactField_EndFlag; j++) { if (g_array_index(fieldsIndex, guint32, i) == j) { strcat(sql, g_ptr_array_index(m_pFieldsName, j)->str)); strcat(sql, " like '%"); strcat(sql, g_ptr_array_index(fieldsValue, i)->str)); strcat(sql, "%' and"); } } strcat(sql, "c.cid >= 0 "); if (-1 != m_nSortFieldIndex) { strcat(sql, "order by c."); strcat(sql, g_ptr_array_index(m_pFieldsName, m_nSortFieldIndex)->str)); strcat(sql, " asc;"); } m_dbQuery = m_dbBeluga.execQuery(sql); *ppContactIterator = NULL; *ppContactIterator = new CContactIterator(this); if (NULL == *ppContactIterator) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } CloseDatabase(); return 0; } */ EXPORT_C gint32 CContactDb::GetMostMatchingPhoneContactByPhoneOrEmail(gchar * commValue, CContact ** ppContact) { gint32 ret; guint32 nContactId; guint32 nMostMatchingId; guint8 nBaseLen = 7, nLimitLen = 12; guint8 nMatchingBit = CONTACT_PHONE_PREF_LEN; char sql[512] = {0}; *ppContact = NULL; OpenDatabase(); char * email = strrchr(commValue, '@'); /* simply check commValue is email */ if (email != NULL) /* email */ { strcpy(sql, "select c.cid, ext.comm_value from contact c left join contact_ext ext on c.cid = ext.cid "\ "where ext.comm_key & 32 = 32 and ext.comm_value like '"); strcat(sql, commValue); strcat(sql, "' order by c.name_spell asc;"); } else /* phone */ { guint8 nPhoneLen = strlen(commValue); strcpy(sql, "select c.cid, ext.comm_value from contact c left join contact_ext ext on c.cid = ext.cid "\ "where (ext.comm_key & 16 = 16) and (ext.comm_value like '"); if (nPhoneLen < nBaseLen) strcat(sql, commValue); else { guint8 i = 0; strcat(sql, "%"); gchar* tmp = commValue; if (nPhoneLen > nLimitLen) { tmp = commValue + nPhoneLen - nLimitLen; nPhoneLen = nLimitLen; } strcat(sql, tmp + i); i++; while (i < nPhoneLen - nBaseLen) { strcat(sql, "' or ext.comm_value like '%"); strcat(sql, tmp + i); i++; } } strcat(sql, "') order by c.name_spell asc;"); } CppSQLite3Query query = m_dbBeluga.execQuery(sql); while (!query.eof()) { nContactId = query.getIntField(0); const gchar * fieldValue = query.getStringField(1); if (NULL == fieldValue) /* query error */ break; /* get the most matching contact */ char * email = strrchr(commValue, '@'); /* simply check commValue is email */ if (email != NULL) /* email */ { if (0 == strcmp(commValue, fieldValue)) /* email equal */ { nMostMatchingId = nContactId; break; } } else /* phone */ { guint32 i = strlen(commValue); guint32 j = strlen(fieldValue); while (i && j && (commValue[i - 1] == fieldValue[j - 1]) ) { i--; j--; if (0 == j && 0 == i) /* perfect same phone .*/ { nMostMatchingId = nContactId; break; } if (i < nMatchingBit) /* i left less, matching most */ { nMatchingBit = i; nMostMatchingId = nContactId; /* record the most matching contact id */ } } if (0 == j && 0 == i) /* perfect same tel */ break; } query.nextRow(); } CDbEntity * pEntity = NULL; ret = GetEntityById(nMostMatchingId, &pEntity); if (0 == ret) *ppContact = (CContact*)pEntity; CloseDatabase(); return ret; } EXPORT_C gint32 CContactDb::GetAllContactsByTag(guint32 nTagId, gboolean onlyPref, CContactIterator ** ppContactIterator) { char sql[512] = {0}; OpenDatabase(); if (onlyPref || nTagId != ContactType_Phone) sprintf(sql, "select * from contact c where c.type = %d ", nTagId); else sprintf(sql, "select c.*, ext.* from contact c "\ "left join (select ce.cid ,ce.comm_key, ce.comm_value, a.* from contact_ext ce "\ "left join address a on ce.comm_value = a.aid) ext "\ "on c.cid = ext.cid where c.type = %d ", nTagId); if (-1 != m_nSortFieldIndex) { strcat(sql, "order by c."); strcat(sql, ((GString*)g_ptr_array_index(m_pFieldsName, m_nSortFieldIndex))->str); strcat(sql, " asc;"); } m_dbQuery = m_dbBeluga.execQuery(sql); *ppContactIterator = NULL; *ppContactIterator = new CContactIterator(this); if (NULL == *ppContactIterator) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::GetAllContactsNotInGroupByTag(guint32 nTagId, gboolean onlyPref, CContactIterator ** ppContactIterator) { char sql[512] = {0}; OpenDatabase(); if (onlyPref || nTagId != ContactType_Phone) sprintf(sql, "select * from contact c where c.cid not in (select cid from r_contact_group) and c.type = %d ", nTagId); else sprintf(sql, "select c.*, ext.* from contact c "\ "left join (select ce.cid ,ce.comm_key, ce.comm_value, a.* from contact_ext ce "\ "left join address a on ce.comm_value = a.aid) ext "\ "on c.cid = ext.cid where c.cid not in (select cid from r_contact_group) and c.type = %d ", nTagId); if (-1 != m_nSortFieldIndex) { strcat(sql, "order by c."); strcat(sql, ((GString*)g_ptr_array_index(m_pFieldsName, m_nSortFieldIndex))->str); strcat(sql, " asc;"); } m_dbQuery = m_dbBeluga.execQuery(sql); *ppContactIterator = NULL; *ppContactIterator = new CContactIterator(this); if (NULL == *ppContactIterator) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::GetAllContactsByGroup(guint32 nGroupId, gboolean onlyPref, CContactIterator ** ppContactIterator) { char sql[512] = {0}; OpenDatabase(); if (onlyPref || !CheckGroupInTag(nGroupId, ContactType_Phone)) sprintf(sql, "select * from contact c, r_contact_group r where r.gid = %d and ", nGroupId); else sprintf(sql, "select c.*, ext.* from contact c, r_contact_group r "\ "left join (select ce.cid ,ce.comm_key, ce.comm_value, a.* from contact_ext ce "\ "left join address a on ce.comm_value = a.aid) ext "\ "on c.cid = ext.cid where r.gid = %d and ", nGroupId); strcat(sql, "c.cid = r.cid "); if (-1 != m_nSortFieldIndex) { strcat(sql, "order by c."); strcat(sql, ((GString*)g_ptr_array_index(m_pFieldsName, m_nSortFieldIndex))->str); strcat(sql, " asc;"); } m_dbQuery = m_dbBeluga.execQuery(sql); *ppContactIterator = NULL; *ppContactIterator = new CContactIterator(this); if (NULL == *ppContactIterator) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::GetContactsTotalityByTag(guint32 nTagId, guint32 * totality) { char sql[128] = {0}; *totality = 0; OpenDatabase(); sprintf(sql, "select count(*) from contact where type = %d;", nTagId); *totality = m_dbBeluga.execScalar(sql); CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::GetContactsTotalityByGroup(guint32 nGroupId, guint32 * totality) { char sql[128] = {0}; *totality = 0; OpenDatabase(); sprintf(sql, "select count(cid) from r_contact_group where gid = %d;", nGroupId); *totality = m_dbBeluga.execScalar(sql); CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::GetPhoneDistrict(gchar* phoneNumber, gchar ** districtNumber, gchar ** districtName, gchar ** feeType) { char sql[256] = {0}; OpenDatabase(); sprintf(sql, "select * from phone_district where %s >= range_start and %s <= rang_end;", phoneNumber, phoneNumber); CppSQLite3Query query = m_dbBeluga.execQuery(sql); *districtNumber = NULL; *districtNumber = g_strdup(query.getStringField(1)); if (NULL == *districtNumber) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } *districtName = NULL; *districtNumber = g_strdup(query.getStringField(2)); if (NULL == *districtNumber) { CloseDatabase(); g_free(*districtNumber); *districtNumber = NULL; return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } *feeType = NULL; *feeType = (gchar*)query.getStringField(5); CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::GetRecentContacts(GPtrArray ** pContacts) { char sql[64] = {0}; char times[20] = {0}; time_t t; time(&t); *pContacts = NULL; *pContacts = g_ptr_array_new(); if (*pContacts == NULL) { return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } OpenDatabase(); strcpy(sql, "select * from recent_contact;"); CppSQLite3Query query = m_dbBeluga.execQuery(sql); while (!query.eof()) { stRecentContact * recentContact = (stRecentContact*)g_malloc0(sizeof(stRecentContact)); if (recentContact == NULL) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } recentContact->nContactId = query.getIntField(1); recentContact->event = (EContactEvent)query.getIntField(2); strcpy(recentContact->eventCommInfo, query.getStringField(3)); strcpy(times, query.getStringField(4)); /* exp: 2009-6-30 21:51:23 */ recentContact->time = localtime(&t); char * tmp = strrchr(times, '-'); recentContact->time->tm_mon = atoi(tmp+1); tmp = strrchr(tmp, '-'); recentContact->time->tm_mday = atoi(tmp+1); tmp = strrchr(tmp, ' '); recentContact->time->tm_hour = atoi(tmp+1); tmp = strrchr(tmp, ':'); recentContact->time->tm_min = atoi(tmp+1); tmp = strrchr(tmp, ':'); recentContact->time->tm_sec = atoi(tmp+1); g_ptr_array_add(*pContacts, recentContact); query.nextRow(); } CloseDatabase(); return 0; } EXPORT_C gint32 CContactDb::SaveRecentContact(stRecentContact * contact) { char sql[256] = {0}; OpenDatabase(); if (m_dbBeluga.execScalar("select count(*) from recent_contact;") > MAX_RECENT_CONTACT_NUM) { m_dbBeluga.execDML("delete from recent_contact where time = (select max(time) from recent_contact);"); } sprintf(sql, "insert into recent_contact values(null, %d, %d, %s, %d-%d-%d %02d:%02d:%02d);", contact->nContactId, contact->event, contact->eventCommInfo, contact->time->tm_year, contact->time->tm_mon, contact->time->tm_mday, contact->time->tm_hour, contact->time->tm_min, contact->time->tm_sec); m_dbBeluga.execDML(sql); CloseDatabase(); return 0; } gint32 CContactDb::GetContactCommInfo(CPhoneContact * pContact) { char sql[128] = {0}; GHashTable * hashTable = pContact->getCommInfoHashTable(); GPtrArray * ptrArray = pContact->getAddressPtrArray(); GString * CidField = NULL; OpenDatabase(); /* fill pref comm info to hashtable */ GString * fieldValue = NULL; pContact->GetFieldValue(ContactField_PhonePref, &fieldValue); if (fieldValue->len) pContact->SetPhone((ECommType)(CommType_Pref | CommType_Phone), fieldValue->str); g_string_free(fieldValue, TRUE); pContact->GetFieldValue(ContactField_EmailPref, &fieldValue); if (fieldValue->len) pContact->SetEmail((ECommType)(CommType_Pref | CommType_Email), fieldValue->str); g_string_free(fieldValue, TRUE); pContact->GetFieldValue(ContactField_IMPref, &fieldValue); if (fieldValue->len) pContact->SetIM((ECommType)(CommType_Pref | CommType_IM), fieldValue->str); g_string_free(fieldValue, TRUE); pContact->GetFieldValue(ContactField_Id, &CidField); sprintf(sql, "select ce.comm_key, ce.comm_value, a.* from contact_ext ce "\ "left join address a on ce.comm_value = a.aid where ce.cid = %s;", CidField->str); g_string_free(CidField, TRUE); CppSQLite3Query query = m_dbBeluga.execQuery(sql); while (!query.eof()) { ECommType commType = (ECommType)query.getIntField(0); /* comm_key field */ switch(commType & 0xF0) { case CommType_Phone: pContact->SetPhone(commType, (gchar*)query.getStringField(1)); break; case CommType_Email: pContact->SetEmail(commType, (gchar*)query.getStringField(1)); break; case CommType_Address: { stAddress addr; addr.aid = query.getIntField(1); addr.atype = commType; g_stpcpy(addr.block, query.getStringField(3)); g_stpcpy(addr.street, query.getStringField(4)); g_stpcpy(addr.district, query.getStringField(5)); g_stpcpy(addr.city, query.getStringField(6)); g_stpcpy(addr.state, query.getStringField(7)); g_stpcpy(addr.country, query.getStringField(8)); g_stpcpy(addr.postcode, query.getStringField(9)); pContact->SetAddress(commType, &addr); } break; case CommType_IM: pContact->SetIM(commType, (gchar*)query.getStringField(1)); break; default: break; } query.nextRow(); } CloseDatabase(); return 0; } gint32 CContactDb::GetMaxContactCommId(guint32 * pMaxCommId) { *pMaxCommId = 0; OpenDatabase(); *pMaxCommId = m_dbBeluga.execScalar("select max(ce_id) from contact_ext;"); CloseDatabase(); return 0; } gboolean CContactDb::CheckGroupInTag(guint32 nGroupId, guint32 nTagId) { char sql[128] = {0}; guint32 count = 0; OpenDatabase(); sprintf(sql, "select count(*) from cgroup where tid = %d and gid = %d;", nTagId, nGroupId); count = m_dbBeluga.execScalar(sql); CloseDatabase(); return (count ? TRUE : FALSE); }
[ "shaochuan.yang@6c45ac76-16e4-11de-9d52-39b120432c5d" ]
[ [ [ 1, 1020 ] ] ]
1bc8f8da4f06e105314fd42a2d75ca6f35c283b4
12203ea9fe0801d613bbb2159d4f69cab3c84816
/Export/cpp/windows/obj/include/nme/display/Tilesheet.h
24374216ba6ef545c0c88d8cb204575fd0a9eb26
[]
no_license
alecmce/haxe_game_of_life
91b5557132043c6e9526254d17fdd9bcea9c5086
35ceb1565e06d12c89481451a7bedbbce20fa871
refs/heads/master
2016-09-16T00:47:24.032302
2011-10-10T12:38:14
2011-10-10T12:38:14
2,547,793
0
0
null
null
null
null
UTF-8
C++
false
false
1,439
h
#ifndef INCLUDED_nme_display_Tilesheet #define INCLUDED_nme_display_Tilesheet #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS2(nme,display,BitmapData) HX_DECLARE_CLASS2(nme,display,IBitmapDrawable) HX_DECLARE_CLASS2(nme,display,Tilesheet) HX_DECLARE_CLASS2(nme,geom,Rectangle) namespace nme{ namespace display{ class Tilesheet_obj : public hx::Object{ public: typedef hx::Object super; typedef Tilesheet_obj OBJ_; Tilesheet_obj(); Void __construct(::nme::display::BitmapData inImage); public: static hx::ObjectPtr< Tilesheet_obj > __new(::nme::display::BitmapData inImage); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); ~Tilesheet_obj(); HX_DO_RTTI; static void __boot(); static void __register(); void __Mark(HX_MARK_PARAMS); ::String __ToString() const { return HX_CSTRING("Tilesheet"); } Dynamic nmeHandle; /* REM */ ::nme::display::BitmapData nmeBitmap; /* REM */ virtual Void addTileRect( ::nme::geom::Rectangle inRect); Dynamic addTileRect_dyn(); static Dynamic nme_tilesheet_create; /* REM */ Dynamic &nme_tilesheet_create_dyn() { return nme_tilesheet_create;} static Dynamic nme_tilesheet_add_rect; /* REM */ Dynamic &nme_tilesheet_add_rect_dyn() { return nme_tilesheet_add_rect;} }; } // end namespace nme } // end namespace display #endif /* INCLUDED_nme_display_Tilesheet */
[ [ [ 1, 49 ] ] ]
86d9ffec18e051044197846b19e94acfc39898b2
8bbbcc2bd210d5608613c5c591a4c0025ac1f06b
/nes/mapper/094.cpp
449aab05559e4e06a17f2de4d4eedc42d744661e
[]
no_license
PSP-Archive/NesterJ-takka
140786083b1676aaf91d608882e5f3aaa4d2c53d
41c90388a777c63c731beb185e924820ffd05f93
refs/heads/master
2023-04-16T11:36:56.127438
2008-12-07T01:39:17
2008-12-07T01:39:17
357,617,280
1
0
null
null
null
null
UTF-8
C++
false
false
756
cpp
#ifdef _NES_MAPPER_CPP_ ///////////////////////////////////////////////////////////////////// // Mapper 94 void NES_mapper94_Init() { g_NESmapper.Reset = NES_mapper94_Reset; g_NESmapper.MemoryWrite = NES_mapper94_MemoryWrite; } void NES_mapper94_Reset() { // set CPU bank pointers g_NESmapper.set_CPU_banks4(0,1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1); } void NES_mapper94_MemoryWrite(uint32 addr, uint8 data) { if((addr & 0xFFF0) == 0xFF00) { uint8 bank = (data & 0x1C) >> 2; g_NESmapper.set_CPU_bank4(bank*2+0); g_NESmapper.set_CPU_bank5(bank*2+1); } // LOG("W " << HEX(addr,4) << HEX(data,2)<< endl); } ///////////////////////////////////////////////////////////////////// #endif
[ "takka@e750ed6d-7236-0410-a570-cc313d6b6496" ]
[ [ [ 1, 30 ] ] ]
48982f1f9423dfcdeecaf399b63cf61fdad40a5e
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestmisccontrol/src/bctesteikcaptionedcontrolcase.cpp
7cf3a8aff7fc0e713cb6038403f7c654d587e175
[]
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
17,165
cpp
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Implements test bc for eik captioned control. * */ #include <w32std.h> #include <coecntrl.h> #include <bctestmisccontrol.rsg> #include <bctestmisccontrol.mbg> #include <aknscontrolcontext.h> // MAknsControlContext #include <barsread.h> // TResourceReader #include <s32mem.h> // RBufWriteStream #include <eikcapc.h> // CEikCaptionedControl #include <eikcapca.h> // CEikCapCArray #include <fbs.h> // CFbsBitmap #include <akniconutils.h> // AknIconUtils #include <akndef.h> // KEikDynamicLayoutVariantSwitch #include "bctesteikcaptionedcontrolcase.h" #include "bctestsubeikcaptionedcontrol.h" #include "bctestsubaknform.h" #include "bctestmisccontrolcontainer.h" #include "bctestmisccontrol.hrh" #include "autotestcommands.h" //Constant for CEikCaptionedControl _LIT( KForm, "Form created" ); _LIT( KRCapControl, "Eik captioned control created" ); _LIT( KSetDimmed, "Invoke CEikCaptionedControl's SetDimmed()" ); _LIT( KSetDividerAfter, "Invoke CEikCaptionedControl's SetDividerAfter()" ); _LIT( KSetLatent, "Invoke CEikCaptionedControl's SetLatent()" ); _LIT( KSetDrawNoWhiteBackground, "Invoke CEikCaptionedControl's SetDrawNoWhiteBackground()" ); _LIT( KSetOfferHotKeys, "Invoke CEikCaptionedControl's SetOfferHotKeys()" ); _LIT( KSetLatentGroupLineFollows, "Invoke CEikCaptionedControl's SetLatentGroupLineFollows()" ); _LIT( KSetSpaceSharingFlags, "Invoke CEikCaptionedControl's SetSpaceSharingFlags()" ); _LIT( KSetTakesEnterKey, "Invoke CEikCaptionedControl's SetTakesEnterKey()" ); _LIT( KSetUsesEars, "Invoke CEikCaptionedControl's SetUsesEars()" ); _LIT( KOfferKeyEventL, "Invoke CEikCaptionedControl's OfferKeyEventL()" ); _LIT( KOfferHotKeys, "Invoke CEikCaptionedControl's OfferHotKeys()" ); _LIT( KHandlePointerEventL, "Invoke CEikCaptionedControl's HandlePointerEventL()" ); _LIT( KCheckDimmedDisplayState, "Invoke CEikCaptionedControl's CheckDimmedDisplayState()" ); _LIT( KDividerAfter, "Invoke CEikCaptionedControl's DividerAfter()" ); _LIT( KSetIconL, "Invoke CEikCaptionedControl's SetIconL()" ); _LIT( KHandleControlEventL, "Invoke CEikCaptionedControl's HandleControlEventL()" ); _LIT( KSetBitmapFromFileL, "Invoke CEikCaptionedControl's SetBitmapFromFileL()" ); _LIT( KGetColorUseListL, "Invoke CEikCaptionedControl's GetColorUseListL()" ); _LIT( KWriteInternalStateL, "Invoke CEikCaptionedControl's WriteInternalStateL()" ); _LIT( KDraw, "Invoke CEikCaptionedControl's Draw()" ); _LIT( KGetFullCaptionText, "Invoke CEikCaptionedControl's GetFullCaptionText()" ); _LIT( KHandleResourceChange, "Invoke CEikCaptionedControl's HandleResourceChange()" ); _LIT( KInputCapabilities, "Invoke CEikCaptionedControl's InputCapabilities()" ); _LIT( KIsLatent, "Invoke CEikCaptionedControl's IsLatent()" ); _LIT( KLatentGroupLineFollows, "Invoke CEikCaptionedControl's LatentGroupLineFollows()" ); _LIT( KMinimumSize, "Invoke CEikCaptionedControl's MinimumSize()" ); _LIT( KSetCurrent, "Invoke CEikCaptionedControl's SetCurrent()" ); _LIT( KSetExtraAscent, "Invoke CEikCaptionedControl's SetExtraAscent()" ); _LIT( KTakesEnterKey, "Invoke CEikCaptionedControl's TakesEnterKey()" ); _LIT( KToolTipText, "Invoke CEikCaptionedControl's ToolTipText()" ); //Constant for CEikCapCArray _LIT( KCEikCapCArray, "Create CEikCapCArray object" ); _LIT( KSetRect, "Invoke CEikCapCArray's SetRect()" ); _LIT( KAdjustAllIds, "Invoke CEikCapCArray's AdjustAllIds()" ); _LIT( KFindLineIndex, "Invoke CEikCapCArray's FindLineIndex()" ); //MBMFileName constant _LIT( KMBMFileName, "\\resource\\apps\\bctestmisccontrol.mbm" ); const TInt KGranularity = 4; const TInt KZero = 0; const TInt KOne = 1; const TInt KTwo = 2; const TInt KFour = 4; const TInt KTwoHundred = 200; // ======== MEMBER FUNCTIONS ======== // --------------------------------------------------------------------------- // Symbian 2nd static Constructor // --------------------------------------------------------------------------- // CBCTestEikCaptionedControlCase* CBCTestEikCaptionedControlCase::NewL( CBCTestMiscControlContainer* aContainer ) { CBCTestEikCaptionedControlCase* self = new( ELeave ) CBCTestEikCaptionedControlCase( aContainer ); CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop( self ); return self; } // --------------------------------------------------------------------------- // C++ default constructor // --------------------------------------------------------------------------- // CBCTestEikCaptionedControlCase::CBCTestEikCaptionedControlCase( CBCTestMiscControlContainer* aContainer ) : iContainer( aContainer ) { } // --------------------------------------------------------------------------- // Destructor // --------------------------------------------------------------------------- // CBCTestEikCaptionedControlCase::~CBCTestEikCaptionedControlCase() { } // --------------------------------------------------------------------------- // Symbian 2nd Constructor // --------------------------------------------------------------------------- // void CBCTestEikCaptionedControlCase::ConstructL() { BuildScriptL(); } // --------------------------------------------------------------------------- // CBCTestEikCaptionedControlCase::BuildScriptL // --------------------------------------------------------------------------- // void CBCTestEikCaptionedControlCase::BuildScriptL() { const TInt scripts[] = { //outline1 DELAY( KOne ), // delay between commands is 1*0.1 seconds = 0.1 seconds LeftCBA, KeyOK, KeyOK, //outline2 LeftCBA, KeyOK, Down, KeyOK, //outline3 LeftCBA, KeyOK, REP( Down, KTwo ), KeyOK }; AddTestScriptL( scripts, sizeof( scripts ) / sizeof( TInt ) ); } // --------------------------------------------------------------------------- // CBCTestEikCaptionedControlCase::RunL // --------------------------------------------------------------------------- // void CBCTestEikCaptionedControlCase::RunL( TInt aCmd ) { if ( ( aCmd < EBCTestMiscControlCmdOutline01 ) || ( aCmd > EBCTestMiscControlCmdOutline03 ) ) { return; } switch ( aCmd ) { case EBCTestMiscControlCmdOutline01: TestPublicFunctionsL(); break; case EBCTestMiscControlCmdOutline02: TestProtectedFunctionsL(); break; case EBCTestMiscControlCmdOutline03: TestFunctionsOfEikCapCArrayL(); break; default: break; } } // --------------------------------------------------------------------------- // CBCTestEikCaptionedControlCase::TestPublicFunctionsL // --------------------------------------------------------------------------- // void CBCTestEikCaptionedControlCase::TestPublicFunctionsL() { // Construct CBCTestSubAknForm iForm = new( ELeave ) CBCTestSubAknForm(); AssertNotNullL( iForm, KForm ); iForm->PrepareLC( R_BCTESTMISCCONTROL_TEXT_SLIDER_FIELD_DIALOG ); CleanupStack::Pop(); // Construct CEikCaptionedControl iCapControl = iForm->GetFirstLineOnFirstPageOrNull(); AssertNotNullL( iCapControl, KRCapControl ); // Invoke CEikCaptionedControl's CEikCaptionedControl() iCapControl->SetDimmed( EFalse ); AssertTrueL( ETrue, KSetDimmed ); // Invoke CEikCaptionedControl's SetDividerAfter() iCapControl->SetDividerAfter( ETrue ); iCapControl->SetDividerAfter( EFalse ); AssertTrueL( ETrue, KSetDividerAfter ); // Invoke CEikCaptionedControl's SetLatent() iCapControl->SetLatent( EFalse ); iCapControl->SetLatent( ETrue ); AssertTrueL( ETrue, KSetLatent ); // Invoke CEikCaptionedControl's SetDrawNoWhiteBackground() iCapControl->SetDrawNoWhiteBackground( EFalse ); iCapControl->SetDrawNoWhiteBackground( ETrue ); AssertTrueL( ETrue, KSetDrawNoWhiteBackground ); // Invoke CEikCaptionedControl's SetOfferHotKeys() iCapControl->SetOfferHotKeys( ETrue ); iCapControl->SetOfferHotKeys( EFalse ); AssertTrueL( ETrue, KSetOfferHotKeys ); // Invoke CEikCaptionedControl's SetLatentGroupLineFollows() iCapControl->SetLatentGroupLineFollows( ETrue ); iCapControl->SetLatentGroupLineFollows( EFalse ); AssertTrueL( ETrue, KSetLatentGroupLineFollows ); // Invoke CEikCaptionedControl's SetSpaceSharingFlags() iCapControl->SetSpaceSharingFlags( CEikCaptionedControl::EIfTooSmallCtlGetsWidthFirst ); AssertTrueL( ETrue, KSetSpaceSharingFlags ); // Invoke CEikCaptionedControl's SetTakesEnterKey() iCapControl->SetTakesEnterKey( ETrue ); iCapControl->SetTakesEnterKey( EFalse ); AssertTrueL( ETrue, KSetTakesEnterKey ); // Invoke CEikCaptionedControl's SetUsesEars() iCapControl->SetUsesEars(); AssertTrueL( ETrue, KSetUsesEars ); // Invoke CEikCaptionedControl's OfferKeyEventL() TKeyEvent keyEvent; keyEvent.iCode = EKeyCBA1; iCapControl->OfferKeyEventL( keyEvent, EEventKey ); AssertTrueL( ETrue, KOfferKeyEventL ); // Invoke CEikCaptionedControl's OfferHotKeys() iCapControl->OfferHotKeys(); AssertTrueL( ETrue, KOfferHotKeys ); // Invoke CEikCaptionedControl's HandlePointerEventL() TPointerEvent pointEvent; pointEvent.iType = TPointerEvent::EButton1Down; iCapControl->HandlePointerEventL( pointEvent ); pointEvent.iType = TPointerEvent::EButton1Up; iCapControl->HandlePointerEventL( pointEvent ); AssertTrueL( ETrue, KHandlePointerEventL ); // Invoke CEikCaptionedControl's CheckDimmedDisplayState() iCapControl->CheckDimmedDisplayState(); AssertTrueL( ETrue, KCheckDimmedDisplayState ); // Invoke CEikCaptionedControl's DividerAfter() iCapControl->DividerAfter(); AssertTrueL( ETrue, KDividerAfter ); // Invoke CEikCaptionedControl's SetBitmapFromFileL() iCapControl->SetBitmapFromFileL( KMBMFileName, EMbmBctestmisccontrol30x40, EMbmBctestmisccontrol30x40m ); AssertTrueL( ETrue, KSetBitmapFromFileL ); // Invoke CEikCaptionedControl's SetIconL() CFbsBitmap* bitmap = AknIconUtils::CreateIconL( KMBMFileName, EMbmBctestmisccontrol30x40 ); //not own CleanupStack::PushL( bitmap ); CFbsBitmap* bitmapMask = AknIconUtils::CreateIconL( KMBMFileName, EMbmBctestmisccontrol30x40m ); //not own CleanupStack::PushL( bitmapMask ); iCapControl->SetIconL( bitmap, bitmapMask ); AssertTrueL( ETrue, KSetIconL ); CleanupStack::Pop( bitmapMask ); CleanupStack::Pop( bitmap ); // Invoke CEikCaptionedControl's HandleControlEventL() iCapControl->HandleControlEventL( iForm, MCoeControlObserver::EEventRequestExit ); AssertTrueL( ETrue, KHandleControlEventL ); // Invoke CEikCaptionedControl's GetColorUseListL() CArrayFixFlat<TCoeColorUse>* colorUseList = new( ELeave ) CArrayFixFlat<TCoeColorUse>( KGranularity ); CleanupStack::PushL( colorUseList ); iCapControl->GetColorUseListL( *colorUseList ); AssertTrueL( ( colorUseList->Count() > KZero ), KGetColorUseListL ); colorUseList->Reset(); CleanupStack::PopAndDestroy( colorUseList ); // Invoke CEikCaptionedControl's GetFullCaptionText() iCapControl->GetFullCaptionText(); AssertTrueL( ETrue, KGetFullCaptionText ); // Invoke CEikCaptionedControl's HandleResourceChange() iCapControl->HandleResourceChange( KAknsMessageSkinChange ); iCapControl->HandleResourceChange( KEikDynamicLayoutVariantSwitch ); AssertTrueL( ETrue, KHandleResourceChange ); // Invoke CEikCaptionedControl's InputCapabilities() iCapControl->InputCapabilities(); AssertTrueL( ETrue, KInputCapabilities ); // Invoke CEikCaptionedControl's IsLatent() iCapControl->IsLatent(); AssertTrueL( ETrue, KIsLatent ); // Invoke CEikCaptionedControl's LatentGroupLineFollows() iCapControl->LatentGroupLineFollows(); AssertTrueL( ETrue, KLatentGroupLineFollows ); // Invoke CEikCaptionedControl's MinimumSize() iCapControl->MinimumSize(); AssertTrueL( ETrue, KMinimumSize ); // Invoke CEikCaptionedControl's SetCurrent() iCapControl->SetCurrent( ETrue ); iCapControl->SetCurrent( EFalse ); AssertTrueL( ETrue, KSetCurrent ); // Invoke CEikCaptionedControl's SetExtraAscent() iCapControl->SetExtraAscent(); AssertTrueL( ETrue, KSetExtraAscent ); // Invoke CEikCaptionedControl's TakesEnterKey() iCapControl->TakesEnterKey(); AssertTrueL( ETrue, KTakesEnterKey ); // Invoke CEikCaptionedControl's ToolTipText() iCapControl->ToolTipText(); AssertTrueL( ETrue, KToolTipText ); delete iForm; iForm = NULL; } // --------------------------------------------------------------------------- // CBCTestEikCaptionedControlCase::TestProtectedFunctionsL // --------------------------------------------------------------------------- // void CBCTestEikCaptionedControlCase::TestProtectedFunctionsL() { // Construct CBCTestSubAknForm iForm = new( ELeave ) CBCTestSubAknForm(); iForm->PrepareLC( R_BCTESTMISCCONTROL_TEXT_SLIDER_FIELD_DIALOG ); CleanupStack::Pop(); // Construct CSubEikCaptionedControl iSubCapControl = static_cast<CBCTestSubEikCaptionedControl*> ( iForm->GetFirstLineOnFirstPageOrNull() ); // Invoke CEikCaptionedControl's MopSupplyObject() TTypeUid typeId( MAknsControlContext::ETypeId ); iSubCapControl->MopSupplyObject( typeId ); _LIT( KMopSupplyObject, "Invoke CEikCaptionedControl's MopSupplyObject()" ); AssertTrueL( ETrue, KMopSupplyObject ); iSubCapControl->DrawNow(); AssertTrueL( ETrue, KDraw ); // Invoke CEikCaptionedControl's WriteInternalStateL() CBufFlat* buf = CBufFlat::NewL( KTwoHundred ); RBufWriteStream stream; stream.Open( *buf ); iSubCapControl->WriteInternalStateL( stream ); AssertTrueL( ETrue, KWriteInternalStateL ); stream.Close(); delete buf; delete iForm; iForm = NULL; } // --------------------------------------------------------------------------- // CBCTestEikCaptionedControlCase::TestFunctionsOfEikCapCArrayL // --------------------------------------------------------------------------- // void CBCTestEikCaptionedControlCase::TestFunctionsOfEikCapCArrayL() { CEikCapCArray* eikCapCArray = new( ELeave ) CEikCapCArray( KGranularity ); CleanupStack::PushL( eikCapCArray ); AssertNotNullL( eikCapCArray, KCEikCapCArray ); // Invoke CEikCapCArray's SetRect() TRect rect; eikCapCArray->SetRect( rect ); AssertTrueL( ETrue, KSetRect ); // Invoke CEikCapCArray's AdjustAllIds() eikCapCArray->AdjustAllIds( KFour ); AssertTrueL( ETrue, KAdjustAllIds ); // Invoke CEikCapCArray's MinimumSize() eikCapCArray->MinimumSize(); _LIT( KECCMinimumSize, "Invoke CEikCapCArray's MinimumSize()" ); AssertTrueL( ETrue, KECCMinimumSize ); // Invoke CEikCapCArray's ResetMinimumSizes() eikCapCArray->ResetMinimumSizes(); _LIT( KECCResetMinimumSizes, "Invoke CEikCapCArray's ResetMinimumSizes()" ); AssertTrueL( ETrue, KECCResetMinimumSizes ); // Invoke CEikCapCArray's FindLineIndex() CCoeControl* coeControl = new( ELeave ) CCoeControl(); CleanupStack::PushL( coeControl ); eikCapCArray->FindLineIndex( coeControl ); AssertTrueL( ETrue, KFindLineIndex ); CleanupStack::PopAndDestroy( coeControl ); CleanupStack::PopAndDestroy( eikCapCArray ); }
[ "none@none" ]
[ [ [ 1, 464 ] ] ]
57970651caf6e2abafabf0fd622c6eb8c5011bb2
cfcd2a448c91b249ea61d0d0d747129900e9e97f
/thirdparty/OpenCOLLADA/COLLADAFramework/include/COLLADAFWTexture.h
ccb0970b88f8ad383050d54fa06341a02c55863d
[]
no_license
fire-archive/OgreCollada
b1686b1b84b512ffee65baddb290503fb1ebac9c
49114208f176eb695b525dca4f79fc0cfd40e9de
refs/heads/master
2020-04-10T10:04:15.187350
2009-05-31T15:33:15
2009-05-31T15:33:15
268,046
0
0
null
null
null
null
UTF-8
C++
false
false
2,340
h
/* Copyright (c) 2008 NetAllied Systems GmbH This file is part of COLLADAFramework. 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 __COLLADAFW_TEXTURE_H__ #define __COLLADAFW_TEXTURE_H__ #include "COLLADAFWPrerequisites.h" #include "COLLADAFWTypes.h" namespace COLLADAFW { /** A Texture. It only specifies the sampler that should be used for the texture and the texture map. The samplers are contained in an array of the parent EffectCommon.*/ class Texture { private: /** The index of the sampler used by the texture, i.e. the index of the sampler in the array of samplers in the parent EffectCommon. */ SamplerID mSamplerId; /** The id of the texture map, that should be used by this texture. It must be binded to a set of texture coordinates, when the material is binded to the geometry. See also TextureCoordinateBinding in InstanceGeometry*/ TextureMapId mTextureMapId; public: /** Constructor. */ Texture(); /** Destructor. */ virtual ~Texture(); /** * Returns the id of the sampler. * The sampler id is the array index position in the samplers array * (see COLLADAFW::EffectCommon::mSamplers from type COLLADAFW::SamplerPointerArray). */ SamplerID getSamplerId() const { return mSamplerId; } /** Sets the id of the sampler.*/ void setSamplerId(SamplerID samplerId) { mSamplerId = samplerId; } /** Returns the id of the texture map, that should be used by this texture. It must be binded to a set of texture coordinates, when the material is binded to the geometry. See also TextureCoordinateBinding in InstanceGeometry*/ TextureMapId getTextureMapId() const { return mTextureMapId; } /** Returns the id of the texture map, that should be used by this texture. It must be binded to a set of texture coordinates, when the material is binded to the geometry. See also TextureCoordinateBinding in InstanceGeometry*/ void setTextureMapId( TextureMapId textureMapId ) { mTextureMapId = textureMapId; } bool isValid() const { return true; } }; } // namespace COLLADAFW #endif // __COLLADAFW_TEXTURE_H__
[ [ [ 1, 69 ] ] ]
9cafdac1fc48826c7e01b76f59198e75e30ba200
2de257be8dc9ffc70dd28988e7a9f1b64519b360
/tags/rds-0.7/jet/java/FileHeader.inc
f2fae08d5834d134a808ed9eab5b2c65cee821f5
[]
no_license
MichalLeonBorsuk/datascript-svn
f141e5573a1728b006a13a0852a5ebb0495177f8
8a89530c50cdfde43696eb7309767d45979e2f40
refs/heads/master
2020-04-13T03:11:45.133544
2010-04-06T13:04:03
2010-04-06T13:04:03
162,924,533
0
1
null
2018-12-23T21:18:53
2018-12-23T21:18:52
null
UTF-8
C++
false
false
2,130
inc
// Automatically generated // DO NOT EDIT /* BSD License * * Copyright (c) 2006, Harald Wellmann, Harman/Becker Automotive Systems * All rights reserved. * * This software is derived from previous work * Copyright (c) 2003, Godmar Back. * * 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 Harman/Becker Automotive Systems or * Godmar Back nor the names of their 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. */ <% if (pkg != null) {%> package <%=pkg%>; import datascript.runtime.*; import datascript.runtime.array.*; import datascript.runtime.io.*; import java.io.IOException; import java.math.BigInteger; import java.util.Vector; <% } %>
[ "hwellmann@7eccfe4a-4f19-0410-86c7-be9599f3b344" ]
[ [ [ 1, 53 ] ] ]
a6534d9c937e87694faed3167ab3e61438fa592b
02ffe34054155a76c1e4612d4f0772c796bedb77
/TCC_NDS/flib/source/FLib.cpp
bee0104590d31b50bc5855cc2dfb8137b46baeab
[]
no_license
btuduri/programming-nds
5fe58bbb768c517ae2ae2b07e6df9b13376a276e
81e6b9e0d4afaba1178b1fb0d8e4b000c5fdaf22
refs/heads/master
2020-06-09T07:21:31.930053
2009-12-08T17:39:17
2009-12-08T17:39:17
32,271,835
0
0
null
null
null
null
UTF-8
C++
false
false
1,178
cpp
#include "FLib.h" FLib::FLib(bool is3D) { mmInitDefaultMem((mm_addr)soundbank_bin); inputManager = new FInputManager(); videoManager = new FVideoManager(inputManager, is3D); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// FInputManager* FLib::GetInputManager() { return inputManager; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// FVideoManager* FLib::GetVideoManager() { return videoManager; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// void FLib::Update() { swiWaitForVBlank(); inputManager->Update(); videoManager->Update(); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// void FLib::Wait(int time) { while (time-- > 0) swiWaitForVBlank(); }
[ "thiagoauler@f17e7a6a-8b71-11de-b664-3b115b7b7a9b" ]
[ [ [ 1, 48 ] ] ]
5f337e94b40d45b0c56a64b34218306141473d46
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/xpressive/detail/dynamic/parser_enum.hpp
a253f7ddd8cbcf2f6917e9b643f2fe694dd81d5e
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
2,622
hpp
/////////////////////////////////////////////////////////////////////////////// // parser_enum.hpp // // Copyright 2004 Eric Niebler. 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) #ifndef BOOST_XPRESSIVE_DETAIL_DYNAMIC_PARSER_ENUM_HPP_EAN_10_04_2005 #define BOOST_XPRESSIVE_DETAIL_DYNAMIC_PARSER_ENUM_HPP_EAN_10_04_2005 // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif namespace boost { namespace xpressive { namespace regex_constants { /////////////////////////////////////////////////////////////////////////////// // compiler_token_type // enum compiler_token_type { token_literal, token_any, // . token_escape, // token_group_begin, // ( token_group_end, // ) token_alternate, // | token_invalid_quantifier, // { token_charset_begin, // [ token_charset_end, // ] token_charset_invert, // ^ token_charset_hyphen, // - token_charset_backspace, // \b token_posix_charset_begin, // [: token_posix_charset_end, // :] token_quote_meta_begin, // \Q token_quote_meta_end, // \E token_no_mark, // ?: token_positive_lookahead, // ?= token_negative_lookahead, // ?! token_positive_lookbehind, // ?<= token_negative_lookbehind, // ?<! token_independent_sub_expression, // ?> token_comment, // ?# token_assert_begin_sequence, // \A token_assert_end_sequence, // \Z token_assert_begin_line, // ^ token_assert_end_line, // $ token_assert_word_begin, // \< token_assert_word_end, // \> token_assert_word_boundary, // \b token_assert_not_word_boundary, // \B token_escape_newline, // \n token_escape_escape, // \e token_escape_formfeed, // \f token_escape_horizontal_tab, // \t token_escape_vertical_tab, // \v token_escape_bell, // \a token_escape_control, // \c token_end_of_pattern }; }}} // namespace boost::xpressive::regex_constants #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 72 ] ] ]
d328b51655986b7564b39e3b64d7250672773862
b22c254d7670522ec2caa61c998f8741b1da9388
/FinalClient/ConfigurationManager.cpp
09a68150511b547cfbe2e90c1008a40dfb519d51
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
9,711
cpp
/* ------------------------[ Lbanet Source ]------------------------- Copyright (C) 2009 Author: Vivien Delage [Rincevent_123] Email : [email protected] -------------------------------[ GNU License ]------------------------------- This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------- */ #include "ConfigurationManager.h" #include "LogHandler.h" #include <libconfig.h++> ConfigurationManager* ConfigurationManager::_singletonInstance = NULL; /*********************************************************** constructor ***********************************************************/ ConfigurationManager::ConfigurationManager() : _opened(false) { _configH = new libconfig::Config(); try { _configH->readFile("Data/Preferences.cfg"); _opened = true; } catch(libconfig::FileIOException) { LogHandler::getInstance()->LogToFile("Can not open file Preferences.cfg"); } catch(libconfig::ParseException & ex) { LogHandler::getInstance()->LogToFile(std::string("Can not correctly parse Preferences.cfg: ") + ex.what()); } } /*********************************************************** destructor ***********************************************************/ ConfigurationManager::~ConfigurationManager() { delete _configH; } /*********************************************************** get singleton instance ***********************************************************/ ConfigurationManager * ConfigurationManager::GetInstance() { if(!_singletonInstance) _singletonInstance = new ConfigurationManager(); return _singletonInstance; } /*********************************************************** get functions ***********************************************************/ bool ConfigurationManager::GetBool(const std::string & path, bool &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; return _configH->lookupValue(path, res); } /*********************************************************** get functions ***********************************************************/ bool ConfigurationManager::GetInt(const std::string & path, int &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; return _configH->lookupValue(path, res); } /*********************************************************** get functions ***********************************************************/ bool ConfigurationManager::GetLong(const std::string & path, long &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; return _configH->lookupValue(path, res); } /*********************************************************** get functions ***********************************************************/ bool ConfigurationManager::GetFloat(const std::string & path, float &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; return _configH->lookupValue(path, res); } /*********************************************************** get functions ***********************************************************/ bool ConfigurationManager::GetDouble(const std::string & path, double &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; return _configH->lookupValue(path, res); } /*********************************************************** get functions ***********************************************************/ bool ConfigurationManager::GetString(const std::string & path, std::string &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; return _configH->lookupValue(path, res); } /*********************************************************** set functions ***********************************************************/ bool ConfigurationManager::SetBool(const std::string & path, const bool &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; bool ret = false; try { _configH->lookup(path) = res; _configH->writeFile("Data/Preferences.cfg"); ret = true; } catch(libconfig::SettingNotFoundException) { LogHandler::getInstance()->LogToFile(std::string("Can not find preferences setting: ") + path); } catch(libconfig::SettingTypeException) { LogHandler::getInstance()->LogToFile(std::string("Can not set the preferences setting: ") + path); } catch(libconfig::FileIOException) { LogHandler::getInstance()->LogToFile(std::string("Can not write the preferences into file")); } return ret; } /*********************************************************** set functions ***********************************************************/ bool ConfigurationManager::SetInt(const std::string & path, const int &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; bool ret = false; try { _configH->lookup(path) = res; _configH->writeFile("Data/Preferences.cfg"); ret = true; } catch(libconfig::SettingNotFoundException) { LogHandler::getInstance()->LogToFile(std::string("Can not find preferences setting: ") + path); } catch(libconfig::SettingTypeException) { LogHandler::getInstance()->LogToFile(std::string("Can not set the preferences setting: ") + path); } catch(libconfig::FileIOException) { LogHandler::getInstance()->LogToFile(std::string("Can not write the preferences into file")); } return ret; } /*********************************************************** set functions ***********************************************************/ bool ConfigurationManager::SetLong(const std::string & path, const long &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; bool ret = false; try { _configH->lookup(path) = res; _configH->writeFile("Data/Preferences.cfg"); ret = true; } catch(libconfig::SettingNotFoundException) { LogHandler::getInstance()->LogToFile(std::string("Can not find preferences setting: ") + path); } catch(libconfig::SettingTypeException) { LogHandler::getInstance()->LogToFile(std::string("Can not set the preferences setting: ") + path); } catch(libconfig::FileIOException) { LogHandler::getInstance()->LogToFile(std::string("Can not write the preferences into file")); } return ret; } /*********************************************************** set functions ***********************************************************/ bool ConfigurationManager::SetFloat(const std::string & path, const float &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; bool ret = false; try { _configH->lookup(path) = res; _configH->writeFile("Data/Preferences.cfg"); ret = true; } catch(libconfig::SettingNotFoundException) { LogHandler::getInstance()->LogToFile(std::string("Can not find preferences setting: ") + path); } catch(libconfig::SettingTypeException) { LogHandler::getInstance()->LogToFile(std::string("Can not set the preferences setting: ") + path); } catch(libconfig::FileIOException) { LogHandler::getInstance()->LogToFile(std::string("Can not write the preferences into file")); } return ret; } /*********************************************************** set functions ***********************************************************/ bool ConfigurationManager::SetDouble(const std::string & path, const double &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; bool ret = false; try { _configH->lookup(path) = res; _configH->writeFile("Data/Preferences.cfg"); ret = true; } catch(libconfig::SettingNotFoundException) { LogHandler::getInstance()->LogToFile(std::string("Can not find preferences setting: ") + path); } catch(libconfig::SettingTypeException) { LogHandler::getInstance()->LogToFile(std::string("Can not set the preferences setting: ") + path); } catch(libconfig::FileIOException) { LogHandler::getInstance()->LogToFile(std::string("Can not write the preferences into file")); } return ret; } /*********************************************************** set functions ***********************************************************/ bool ConfigurationManager::SetString(const std::string & path, const std::string &res) { boost::mutex::scoped_lock lock(m_mutex); if(!_opened) return false; bool ret = false; try { _configH->lookup(path) = res; _configH->writeFile("Data/Preferences.cfg"); ret = true; } catch(libconfig::SettingNotFoundException) { LogHandler::getInstance()->LogToFile(std::string("Can not find preferences setting: ") + path); } catch(libconfig::SettingTypeException) { LogHandler::getInstance()->LogToFile(std::string("Can not set the preferences setting: ") + path); } catch(libconfig::FileIOException) { LogHandler::getInstance()->LogToFile(std::string("Can not write the preferences into file")); } return ret; }
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 350 ] ] ]
4c24895d0ce07948a2516f92d967784299c33164
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/_统计专用/C++Primer中文版(第4版)/第一次-代码集合-20090414/第十六章 模板与泛型编程/20090328_测试_关于调用.cpp
ca0c81bb8e6f1474dd85b4cb8a7f557a083dde45
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
288
cpp
#include <iostream> using namespace std; template <typename T> T calc(T, T) { cout << "It is me." << endl; return 0; } int main() { int ival; double dval; float fval; calc(dval, dval); calc(ival, dval); //error calc(fval, ival); //error return 0; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 25 ] ] ]
fe78ea1fffab302dc80c4597f83b92ea0c04f52c
9277f8b966db2bc75acaf12a75f620853be4ffa4
/utils/task/apex_tensor_update_task.h
11387cda0220f71117f590f179d0b426fa57964d
[]
no_license
guochao1/apex-dbn
3e6ad9de12564fc206ed08e563ecea1976edfff5
d95a606a55ba80687e730b78bd4579f20d616eec
refs/heads/master
2021-01-22T13:42:09.752260
2010-09-29T09:13:39
2010-09-29T09:13:39
40,700,204
1
0
null
null
null
null
UTF-8
C++
false
false
11,679
h
#ifndef _APEX_TENSOR_UPDATE_TASK_H_ #define _APEX_TENSOR_UPDATE_TASK_H_ // task that use tensor input to update the inner state of model #include <ctime> #include <cstring> #include "../apex_task.h" #include "../apex_config.h" #include "../apex_tensor_iterator.h" #include "../../tensor/apex_tensor.h" namespace apex_utils{ namespace deprecated{ // model updater that updates the model template<typename T> class ITensorUpdater{ public: // set parameter necessary virtual void set_param( const char *name, const char *val )=0; // initalize the updater virtual void init( void ) = 0; // update the model using a trunk of tensor virtual void train_update_trunk( const T &data )=0; // validate the model using a trunk of tensor virtual void validate_trunk ( const T &data )=0; // end of a round virtual void round_end() = 0; // end of all training rounds virtual void all_end() =0; public: virtual ~ITensorUpdater(){} }; template<typename T> class TensorUpdateTask : public ITask{ private: ITensorUpdater<T> *updater; ITensorIterator<T> *iter; private: int task; int silent, do_validation; int trunk_size; int num_round, print_step; char name_config[ 256 ]; inline void set_param_inner( const char *name, const char *val ){ if( !strcmp( name, "silent") ) silent = atoi( val ); if( !strcmp( name, "do_validation") ) do_validation = atoi( val ); if( !strcmp( name, "num_round") ) num_round = atoi( val ); if( !strcmp( name, "print_step") ) print_step = atoi( val ); if( !strcmp( name, "trunk_size") ) trunk_size = atoi( val ); iter->set_param( name, val ); updater->set_param( name, val ); } inline void configure(){ apex_utils::ConfigIterator cfg( name_config ); while( cfg.next() ){ set_param_inner( cfg.name(), cfg.val() ); } } inline void reset_default_param(){ silent = 0; do_validation = 0; task = 0; num_round = 1; print_step = 30; strcpy( name_config, "config.conf" ); } private: inline void task_update(){ iter->init(); updater->init(); if( !silent ){ printf("initializing end, start updating\n"); } clock_t start = clock(); double elapsed = 0, valid_elapsed = 0; // do validation for the initial model if( do_validation ){ clock_t valid_start = clock(); updater->validate_trunk( iter->validation_trunk() ); valid_elapsed += (double)(clock() - valid_start)/CLOCKS_PER_SEC; } for( int i = 0 ; i < num_round ; i ++ ){ int sample_counter = 0; iter->before_first(); while( iter->next_trunk() ){ updater->train_update_trunk( iter->trunk() ); if( ++ sample_counter % print_step == 0 ){ if( !silent ){ printf("\r \r"); printf("round %8d:[%8d] %.3lf sec elapsed, %.3lf sec for validation", i , sample_counter*trunk_size, elapsed, valid_elapsed ); fflush( stdout ); } } } updater->round_end(); if( do_validation ){ clock_t valid_start = clock(); updater->validate_trunk( iter->validation_trunk() ); valid_elapsed += (double)(clock() - valid_start)/CLOCKS_PER_SEC; } elapsed = (double)(clock() - start)/CLOCKS_PER_SEC; } updater->all_end(); if( !silent ){ printf("\nupdating end, %lf sec in all, %lf for validation\n", elapsed , valid_elapsed ); } } public: TensorUpdateTask( ITensorUpdater<T> *updater, ITensorIterator<T> *iter ){ this->updater = updater; this->iter = iter; this->reset_default_param(); } virtual void set_param( const char *name , const char *val ) { set_param_inner( name, val ); } virtual void set_task ( const char *task ){ strcpy( name_config , task ); } virtual void print_task_help( FILE *fo ) const { fprintf( fo , "Usage: <config file> [param1=xxx] ...\n" ); } virtual void run_task( void ){ configure(); switch( task ){ case 0: task_update(); break; default: apex_utils::error("unkown task"); } } virtual ~TensorUpdateTask(){} }; // gavinhu: model updater using labeled data template<typename T> class ITensorLabeledUpdater: public ITensorUpdater<T> { public: // update the model using a trunk of label and a trunk of data virtual void train_update_trunk(const T &label, const T &data) = 0; // validate the model using a trunk of label and a trunk of data virtual void validate_trunk(const T &label, const T &data) = 0; }; // gavinhu: update task for labeled data template<typename T> class TensorLabeledUpdateTask : public ITask { private: ITensorLabeledUpdater<T> *updater; ITensorIterator<T> *data_iter; ITensorIterator<T> *label_iter; private: int task; int silent, do_validation; int trunk_size; int num_round, print_step; char name_config[ 256 ]; inline void set_param_inner( const char *name, const char *val ){ if( !strcmp( name, "silent") ) silent = atoi( val ); if( !strcmp( name, "do_validation") ) do_validation = atoi( val ); if( !strcmp( name, "num_round") ) num_round = atoi( val ); if( !strcmp( name, "print_step") ) print_step = atoi( val ); if( !strcmp( name, "trunk_size") ) trunk_size = atoi( val ); label_iter->set_param( name, val ); data_iter->set_param( name, val ); updater->set_param( name, val ); } inline void configure(){ apex_utils::ConfigIterator cfg( name_config ); while( cfg.next() ){ set_param_inner( cfg.name(), cfg.val() ); } } inline void reset_default_param(){ silent = 0; do_validation = 0; task = 0; num_round = 100; print_step = 30; strcpy( name_config, "config.conf" ); } private: inline void task_update(){ label_iter->init(); data_iter->init(); updater->init(); if( !silent ){ printf("initializing end, start updating\n"); } clock_t start = clock(); double elapsed = 0, valid_elapsed = 0; // do validation for the initial model if( do_validation ){ clock_t valid_start = clock(); updater->validate_trunk( label_iter->validation_trunk(), data_iter->validation_trunk() ); valid_elapsed += (double)(clock() - valid_start)/CLOCKS_PER_SEC; } for( int i = 0 ; i < num_round ; i ++ ){ int sample_counter = 0; label_iter->before_first(); data_iter->before_first(); while( label_iter->next_trunk() && data_iter->next_trunk() ){ updater->train_update_trunk( label_iter->trunk(), data_iter->trunk() ); if( ++ sample_counter % print_step == 0 ){ if( !silent ){ printf("\r \r"); printf("round %8d:[%8d] %.3lf sec elapsed, %.3lf sec for validation", i , sample_counter*trunk_size, elapsed, valid_elapsed ); fflush( stdout ); } } } updater->round_end(); if( do_validation ){ clock_t valid_start = clock(); updater->validate_trunk( label_iter->validation_trunk(), data_iter->validation_trunk() ); valid_elapsed += (double)(clock() - valid_start)/CLOCKS_PER_SEC; } elapsed = (double)(clock() - start)/CLOCKS_PER_SEC; } updater->all_end(); if( !silent ){ printf("\nupdating end, %lf sec in all, %lf for validation\n", elapsed , valid_elapsed ); } } public: TensorLabeledUpdateTask( ITensorLabeledUpdater<T> *updater, ITensorIterator<T> *label_iter, ITensorIterator<T> *data_iter ){ this->updater = updater; this->label_iter = label_iter; this->data_iter = data_iter; this->reset_default_param(); } virtual void set_param( const char *name , const char *val ) { set_param_inner( name, val ); } virtual void set_task ( const char *task ){ strcpy( name_config , task ); } virtual void print_task_help( FILE *fo ) const { fprintf( fo , "Usage: <config file> [param1=xxx] ...\n" ); } virtual void run_task( void ){ configure(); switch( task ){ case 0: task_update(); break; default: apex_utils::error("unkown task"); } } virtual ~TensorLabeledUpdateTask(){} }; }; }; #endif
[ "workcrow@b861ab8a-2dba-11df-8e64-fd3be38ee323", "GavinHu119@b861ab8a-2dba-11df-8e64-fd3be38ee323" ]
[ [ [ 1, 143 ], [ 145, 153 ], [ 155, 167 ], [ 169, 177 ], [ 179, 184 ], [ 187, 202 ], [ 204, 206 ], [ 209, 209 ], [ 212, 239 ], [ 241, 247 ], [ 249, 250 ], [ 253, 254 ], [ 256, 273 ] ], [ [ 144, 144 ], [ 154, 154 ], [ 168, 168 ], [ 178, 178 ], [ 185, 186 ], [ 203, 203 ], [ 207, 208 ], [ 210, 211 ], [ 240, 240 ], [ 248, 248 ], [ 251, 252 ], [ 255, 255 ] ] ]
b3a766def73a1bb06a66ba7dd74d252eee3e4900
221e3e713891c951e674605eddd656f3a4ce34df
/core/OUE/Impl/DXLib/DXInput.cpp
deaa46e809aa687961b0f08f1c5d022c3cb3d972
[ "MIT" ]
permissive
zacx-z/oneu-engine
da083f817e625c9e84691df38349eab41d356b76
d47a5522c55089a1e6d7109cebf1c9dbb6860b7d
refs/heads/master
2021-05-28T12:39:03.782147
2011-10-18T12:33:45
2011-10-18T12:33:45
null
0
0
null
null
null
null
GB18030
C++
false
false
4,995
cpp
/* This source file is part of OneU Engine. Copyright (c) 2011 Ladace Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma comment( lib, "dinput8.lib" ) #include "DXInput.h" namespace OneU { namespace DX { IDirectInput8 *_pDInput = 0; static HWND s_hWnd = NULL; Input_cls* const GetInput() { static Input_cls instance; return &instance; } Input_cls& Input = *GetInput(); void Input_cls::Init(HINSTANCE hInstance, HWND hWnd) { DXCHECK_RAISE( DirectInput8Create( hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, reinterpret_cast< void ** >( &_pDInput ), NULL ), L"初始化输入失败!" ); s_hWnd = hWnd; } void InputDevice::Create(uint32 BufferSize) { ONEU_ASSERT(m_pDIDevice == NULL); Init(BufferSize); DXCHECK_RAISE(m_pDIDevice->SetCooperativeLevel( s_hWnd, DISCL_BACKGROUND|DISCL_NONEXCLUSIVE ), L"设置输入设备协作级别失败!"); if(BufferSize) { //设置缓冲区大小 使设备能够用缓冲模式工作 DIPROPDWORD dp; dp.diph.dwSize = sizeof(DIPROPDWORD); dp.diph.dwHeaderSize = sizeof(DIPROPHEADER); dp.diph.dwObj = 0; dp.diph.dwHow = DIPH_DEVICE; dp.dwData = BufferSize; DXCHECK(m_pDIDevice->SetProperty(DIPROP_BUFFERSIZE, &dp.diph), L"设置输入设备缓冲区大小失败!"); } } void InputDevice::Read( void *DataBuffer, uint32 BufferSize ) { while( TRUE ) { HRESULT hr; if( SUCCEEDED( hr = m_pDIDevice->GetDeviceState( BufferSize, DataBuffer ) ) ) break; if( hr != DIERR_INPUTLOST && hr != DIERR_NOTACQUIRED ) RAISE_HRESULT(hr); if( FAILED( m_pDIDevice->Acquire() ) ) RAISE_HRESULT(hr); } } bool InputDevice::GetData( DataType *Buffer, uint32& dwElements ) { while( TRUE ) { HRESULT hr; if( SUCCEEDED( hr= m_pDIDevice->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), Buffer, &dwElements, 0 ) ) ) { if( hr == DI_BUFFEROVERFLOW ) return TRUE; else return FALSE; } // 发生了一个错误 保留 // 这个错误有可能是 DI_BUFFEROVERFLOW 缓冲区溢出错误 // 但不管是哪种错误,都意味着同输入设备的联系被丢失了 // 这种错误引起的最严重的后果就是如果你按下一个键后还未松开时 // 发生了错误,就会丢失后面松开该键的消息。这样一来,你的程序 // 就可能以为该键尚未被松开,从而发生一些意想不到的情况 // 现在这段代码并未处理该错误 // 解决该问题的一个办法是,在出现这种错误时,就去调用一次 // GetDeviceState(),然后把结果同程序最后所记录的状态进行 // 比较,从而修正可能发生的错误 if( hr != DIERR_INPUTLOST && hr != DIERR_NOTACQUIRED ) RAISE_HRESULT(hr); if( FAILED( m_pDIDevice->Acquire() ) ) RAISE_HRESULT(hr); } } void InputDevice::HandleData( DataHandler Fn ) { uint32 dwElements = DATA_BUFFER_SIZE; static DataType Buffer[ DATA_BUFFER_SIZE ]; bool bOverFlow; do { bOverFlow = GetData( Buffer, dwElements ); for( unsigned long i = 0; i < dwElements; i++ ) { ( *Fn )( Buffer[i].dwOfs, Buffer[i].dwData, Buffer[i].dwTimeStamp, Buffer[i].dwSequence ); } }while( bOverFlow ); } void KeyBoard::Init( uint32 BufferSize ) { DXCHECK_RAISE( _pDInput->CreateDevice( GUID_SysKeyboard, &m_pDIDevice, NULL ), L"创建键盘输入设备失败!" ); DXCHECK_RAISE( m_pDIDevice->SetDataFormat( &c_dfDIKeyboard ), L"设置键盘输入设备数据格式失败!" ); } void Mouse::Init( uint32 BufferSize ) { DXCHECK_RAISE( _pDInput->CreateDevice( GUID_SysMouse, &m_pDIDevice, NULL ), L"创建鼠标输入设备失败!" ); DXCHECK_RAISE( m_pDIDevice->SetDataFormat( &c_dfDIMouse ), L"设置鼠标输入设备数据格式失败!" ); } } }
[ "[email protected]@d30a3831-f586-b1a3-add9-2db6dc386f9c" ]
[ [ [ 1, 149 ] ] ]
6dee8ad4e4ac05ae10e9a651f3a993e1586e79d4
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_audio_basics/midi/juce_MidiBuffer.cpp
b46d2179d94302e90c7906756dfb258a5ca4ec9b
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
8,479
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ BEGIN_JUCE_NAMESPACE namespace MidiBufferHelpers { inline int getEventTime (const void* const d) noexcept { return *static_cast <const int*> (d); } inline uint16 getEventDataSize (const void* const d) noexcept { return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int)); } inline uint16 getEventTotalSize (const void* const d) noexcept { return getEventDataSize (d) + sizeof (int) + sizeof (uint16); } } //============================================================================== MidiBuffer::MidiBuffer() noexcept : bytesUsed (0) { } MidiBuffer::MidiBuffer (const MidiMessage& message) noexcept : bytesUsed (0) { addEvent (message, 0); } MidiBuffer::MidiBuffer (const MidiBuffer& other) noexcept : data (other.data), bytesUsed (other.bytesUsed) { } MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) noexcept { bytesUsed = other.bytesUsed; data = other.data; return *this; } void MidiBuffer::swapWith (MidiBuffer& other) noexcept { data.swapWith (other.data); std::swap (bytesUsed, other.bytesUsed); } MidiBuffer::~MidiBuffer() { } inline uint8* MidiBuffer::getData() const noexcept { return static_cast <uint8*> (data.getData()); } void MidiBuffer::clear() noexcept { bytesUsed = 0; } void MidiBuffer::clear (const int startSample, const int numSamples) { uint8* const start = findEventAfter (getData(), startSample - 1); uint8* const end = findEventAfter (start, startSample + numSamples - 1); if (end > start) { const int bytesToMove = bytesUsed - (int) (end - getData()); if (bytesToMove > 0) memmove (start, end, bytesToMove); bytesUsed -= (int) (end - start); } } void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber) { addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber); } namespace MidiBufferHelpers { int findActualEventLength (const uint8* const data, const int maxBytes) noexcept { unsigned int byte = (unsigned int) *data; int size = 0; if (byte == 0xf0 || byte == 0xf7) { const uint8* d = data + 1; while (d < data + maxBytes) if (*d++ == 0xf7) break; size = (int) (d - data); } else if (byte == 0xff) { int n; const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n); size = jmin (maxBytes, n + 2 + bytesLeft); } else if (byte >= 0x80) { size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte)); } return size; } } void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber) { const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes); if (numBytes > 0) { int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16); data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7); uint8* d = findEventAfter (getData(), sampleNumber); const int bytesToMove = bytesUsed - (int) (d - getData()); if (bytesToMove > 0) memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove); *reinterpret_cast <int*> (d) = sampleNumber; d += sizeof (int); *reinterpret_cast <uint16*> (d) = (uint16) numBytes; d += sizeof (uint16); memcpy (d, newData, numBytes); bytesUsed += numBytes + sizeof (int) + sizeof (uint16); } } void MidiBuffer::addEvents (const MidiBuffer& otherBuffer, const int startSample, const int numSamples, const int sampleDeltaToAdd) { Iterator i (otherBuffer); i.setNextSamplePosition (startSample); const uint8* eventData; int eventSize, position; while (i.getNextEvent (eventData, eventSize, position) && (position < startSample + numSamples || numSamples < 0)) { addEvent (eventData, eventSize, position + sampleDeltaToAdd); } } void MidiBuffer::ensureSize (size_t minimumNumBytes) { data.ensureSize (minimumNumBytes); } bool MidiBuffer::isEmpty() const noexcept { return bytesUsed == 0; } int MidiBuffer::getNumEvents() const noexcept { int n = 0; const uint8* d = getData(); const uint8* const end = d + bytesUsed; while (d < end) { d += MidiBufferHelpers::getEventTotalSize (d); ++n; } return n; } int MidiBuffer::getFirstEventTime() const noexcept { return bytesUsed > 0 ? MidiBufferHelpers::getEventTime (data.getData()) : 0; } int MidiBuffer::getLastEventTime() const noexcept { if (bytesUsed == 0) return 0; const uint8* d = getData(); const uint8* const endData = d + bytesUsed; for (;;) { const uint8* const nextOne = d + MidiBufferHelpers::getEventTotalSize (d); if (nextOne >= endData) return MidiBufferHelpers::getEventTime (d); d = nextOne; } } uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const noexcept { const uint8* const endData = getData() + bytesUsed; while (d < endData && MidiBufferHelpers::getEventTime (d) <= samplePosition) d += MidiBufferHelpers::getEventTotalSize (d); return d; } //============================================================================== MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) noexcept : buffer (buffer_), data (buffer_.getData()) { } MidiBuffer::Iterator::~Iterator() noexcept { } //============================================================================== void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) noexcept { data = buffer.getData(); const uint8* dataEnd = data + buffer.bytesUsed; while (data < dataEnd && MidiBufferHelpers::getEventTime (data) < samplePosition) data += MidiBufferHelpers::getEventTotalSize (data); } bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) noexcept { if (data >= buffer.getData() + buffer.bytesUsed) return false; samplePosition = MidiBufferHelpers::getEventTime (data); numBytes = MidiBufferHelpers::getEventDataSize (data); data += sizeof (int) + sizeof (uint16); midiData = data; data += numBytes; return true; } bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) noexcept { if (data >= buffer.getData() + buffer.bytesUsed) return false; samplePosition = MidiBufferHelpers::getEventTime (data); const int numBytes = MidiBufferHelpers::getEventDataSize (data); data += sizeof (int) + sizeof (uint16); result = MidiMessage (data, numBytes, samplePosition); data += numBytes; return true; } END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 298 ] ] ]
fcb9171fa3761a0c2aad543abae00a6c8925145e
1dba10648f60dea02c9be242c668f3488ae8dec4
/program/src/mp_logger.cpp
41be1e262a0b78be2e87cd9a53da6b6b1adceda2
[]
no_license
hateom/si-air
f02ffc8ba9fac9777d12a40627f06044c92865f0
2094c98a04a6785078b4c8bcded8f8b4450c8b92
refs/heads/master
2021-01-15T17:42:12.887029
2007-01-21T17:48:48
2007-01-21T17:48:48
32,139,237
0
0
null
null
null
null
UTF-8
C++
false
false
1,279
cpp
#include "mp_logger.h" #include <cstdarg> #include <qtextedit.h> #include <qstring.h> ////////////////////////////////////////////////////////////////////////// int mpLogger::output_type = OT_NONE; QTextEdit * mpLogger::te = NULL; mpLogger::mpLogger() { } ////////////////////////////////////////////////////////////////////////// mpLogger::~mpLogger() { } ////////////////////////////////////////////////////////////////////////// void mpLogger::set_output( int ot, QTextEdit * t_e ) { output_type = ot; if( ot == OT_WINDOW ) { te = t_e; } } ////////////////////////////////////////////////////////////////////////// void mpLogger::log( std::string text ) { log( text.c_str() ); } ////////////////////////////////////////////////////////////////////////// void mpLogger::log( const char * text, ... ) { va_list al; static char buffer[256] = ""; va_start( al, text ); vsprintf( buffer, text, al ); va_end( al ); switch( output_type ) { case OT_CONSOLE: printf( buffer ); break; case OT_WINDOW: if( te != NULL ) { te->insert( QString(buffer) ); } break; default: /// none break; } } //////////////////////////////////////////////////////////////////////////
[ "tomasz.huczek@9b5b1781-be22-0410-ac8e-a76ce1d23082" ]
[ [ [ 1, 69 ] ] ]
2290969462f3987c6d3f6a56267fd47f281ce3ed
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/test/metaprogramming.cpp
987d51ac69e1a488eb89124dc96b7ffeca76902e
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
3,437
cpp
// Copyright (C) 2008 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #include <sstream> #include <string> #include <cstdlib> #include <ctime> #include <dlib/algs.h> #include "tester.h" namespace { using namespace test; using namespace dlib; using namespace std; logger dlog("test.metaprogramming"); void metaprogramming_test ( ) /*! ensures - runs tests on template metaprogramming objects and functions for compliance with the specs !*/ { print_spinner(); DLIB_CASSERT(is_signed_type<signed char>::value == true,""); DLIB_CASSERT(is_signed_type<signed short>::value == true,""); DLIB_CASSERT(is_signed_type<signed int>::value == true,""); DLIB_CASSERT(is_signed_type<signed long>::value == true,""); DLIB_CASSERT(is_unsigned_type<signed char>::value == false,""); DLIB_CASSERT(is_unsigned_type<signed short>::value == false,""); DLIB_CASSERT(is_unsigned_type<signed int>::value == false,""); DLIB_CASSERT(is_unsigned_type<signed long>::value == false,""); DLIB_CASSERT(is_unsigned_type<unsigned char>::value == true,""); DLIB_CASSERT(is_unsigned_type<unsigned short>::value == true,""); DLIB_CASSERT(is_unsigned_type<unsigned int>::value == true,""); DLIB_CASSERT(is_unsigned_type<unsigned long>::value == true,""); DLIB_CASSERT(is_signed_type<unsigned char>::value == false,""); DLIB_CASSERT(is_signed_type<unsigned short>::value == false,""); DLIB_CASSERT(is_signed_type<unsigned int>::value == false,""); DLIB_CASSERT(is_signed_type<unsigned long>::value == false,""); COMPILE_TIME_ASSERT(is_signed_type<signed char>::value == true); COMPILE_TIME_ASSERT(is_signed_type<signed short>::value == true); COMPILE_TIME_ASSERT(is_signed_type<signed int>::value == true); COMPILE_TIME_ASSERT(is_signed_type<signed long>::value == true); COMPILE_TIME_ASSERT(is_unsigned_type<signed char>::value == false); COMPILE_TIME_ASSERT(is_unsigned_type<signed short>::value == false); COMPILE_TIME_ASSERT(is_unsigned_type<signed int>::value == false); COMPILE_TIME_ASSERT(is_unsigned_type<signed long>::value == false); COMPILE_TIME_ASSERT(is_unsigned_type<unsigned char>::value == true); COMPILE_TIME_ASSERT(is_unsigned_type<unsigned short>::value == true); COMPILE_TIME_ASSERT(is_unsigned_type<unsigned int>::value == true); COMPILE_TIME_ASSERT(is_unsigned_type<unsigned long>::value == true); COMPILE_TIME_ASSERT(is_signed_type<unsigned char>::value == false); COMPILE_TIME_ASSERT(is_signed_type<unsigned short>::value == false); COMPILE_TIME_ASSERT(is_signed_type<unsigned int>::value == false); COMPILE_TIME_ASSERT(is_signed_type<unsigned long>::value == false); } class metaprogramming_tester : public tester { public: metaprogramming_tester ( ) : tester ("test_metaprogramming", "Runs tests on the metaprogramming objects and functions.") {} void perform_test ( ) { metaprogramming_test(); } } a; }
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 94 ] ] ]
934b355e7ee1f64a8d8f5950594e9253a605dd71
f94f9d54bf316a15d9e1962b1514bba80ad226c9
/Session.cpp
82eaf8682c9090890b6136d163cb6676fa78f111
[ "Apache-2.0" ]
permissive
bbyk/devsmtp
2b015a31a41657f8677bfdb4326e3dac2bf53bcd
b98b4267cc4bc7808180367e92d5efe299297767
refs/heads/master
2021-01-19T10:11:05.366080
2010-08-18T10:07:51
2010-08-18T10:08:51
845,840
3
0
null
null
null
null
UTF-8
C++
false
false
10,906
cpp
/* * Copyright 2010 Boris Byk. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #include "StdAfx.h" #include "Session.h" #pragma warning(disable:4482) namespace DevSmtp { Session::Session( Server* r_pServer ) : m_pServer(r_pServer), m_eState(WAIT_ACCEPT), m_eOpState(NONE), m_hFile(0), m_pFo(this) { ZeroMemory( m_charBuf, DEFAULT_READ_BUFFER_SIZE ); m_line.reserve( DEFAULT_READ_BUFFER_SIZE ); IssueAccept(); } Session::~Session(void) { } void Session::IssueAccept(void) { Internal = 0; InternalHigh = 0; Offset = 0; OffsetHigh = 0; hEvent = 0; m_eState = WAIT_ACCEPT; ZeroMemory( m_addrBlock, ACCEPT_ADDRESS_LENGTH * 2 ); m_hSocket = WSASocket( PF_INET, SOCK_STREAM, IPPROTO_TCP, 0, 0, WSA_FLAG_OVERLAPPED ); assert(m_hSocket != INVALID_SOCKET); // Associate the client socket with the I/O Completion Port. CreateIoCompletionPort( (HANDLE)m_hSocket, m_pServer->m_hIoPort, COMPLETION_KEY_IO, 0 ); BOOL res = AcceptEx( m_pServer->m_hListener, m_hSocket, m_addrBlock, 0, ACCEPT_ADDRESS_LENGTH, ACCEPT_ADDRESS_LENGTH, NULL, this ); int err; if (!(res == FALSE && (err = WSAGetLastError()) == ERROR_IO_PENDING)) { LOG1(_T("Fail AcceptEx (%d)"), err); exit(2); } } void Session::OnIoComplete(DWORD rNumTransferred) { switch (m_eState) { case WAIT_ACCEPT: CompleteAccept(); break; case WAIT_REQUEST: CompleteReadLine( rNumTransferred ); break; case WAIT_SEND: CompleteWrite( rNumTransferred ); break; case WAIT_REQUEST_DATA: CompleteReadData( rNumTransferred ); break; case WAIT_WRITE: CompleteWriteFile( rNumTransferred ); break; } } void Session::CompleteReadLine(DWORD rNumTransferred) { bool shdIssue = true; if (rNumTransferred > 0) { DWORD l_charPos = 0; int span; DWORD char_pos = l_charPos; do { char ch = m_charBuf[char_pos]; if (ch == '\r' || ch == '\n') { span = char_pos - l_charPos; m_line.append( &(m_charBuf[l_charPos]), span ); l_charPos = char_pos + 1; if ((ch == '\r' && l_charPos < rNumTransferred) && (m_charBuf[l_charPos] == '\n')) { l_charPos++; } OnReadLine(); m_line.clear(); return; } else { char_pos++; } } while (char_pos < rNumTransferred); span = rNumTransferred - l_charPos; m_line.append( &(m_charBuf[l_charPos]), span ); } if (shdIssue) IssueRead(); } void Session::CompleteReadData( DWORD rNumTransferred ) { DWORD l_char_pos = 0; int span; DWORD char_pos = l_char_pos; bool shdIssue = true; char sep[] = "\r\n.\r\n"; int si = 0; do { char ch = m_charBuf[char_pos]; if (ch == sep[si]) { si++; } else if (si > 0) { si = 0; if (ch == sep[si]) { si++; } } if (si == 5) //separator length) { span = char_pos - l_char_pos; m_line.append( &(m_charBuf[l_char_pos]), span - 3 ); l_char_pos = char_pos + 1; OnReadLine(); m_line.clear(); return; } char_pos++; } while (char_pos < rNumTransferred); span = rNumTransferred - l_char_pos; m_line.append( &(m_charBuf[l_char_pos]), span ); if (shdIssue) IssueRead(STATE::WAIT_REQUEST_DATA); } void Session::CompleteAccept() { setsockopt( m_hSocket, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (char*)&m_pServer->m_hListener, sizeof(SOCKET) ); // fetch connection context and log it SOCKADDR_IN sin; int nameLen = sizeof(sin); getpeername( m_hSocket, (PSOCKADDR)&sin, &nameLen); char* remote_ip = inet_ntoa(sin.sin_addr); char buffer[26]; sprintf_s(buffer, sizeof(buffer), "Connected %s", remote_ip); Log(TOLPTCHAR(buffer)); CompleteOperation(); } void Session::OnReadLine() { _TCHAR buf[65]; _itot_s(m_hSocket, buf, 10); LOG2(_T("C: %s"), buf, TOLPTCHAR(&m_line[0])); CompleteOperation(); } void Session::IssueRead() { IssueRead(STATE::WAIT_REQUEST); } void Session::IssueRead(STATE rState) { m_eState = rState; BOOL res = ReadFile( (HANDLE)m_hSocket, m_charBuf, DEFAULT_READ_BUFFER_SIZE, NULL, (LPOVERLAPPED)this ); if (!res) { int err = GetLastError(); if (err == ERROR_IO_PENDING) { return; } else if (err == ERROR_NETNAME_DELETED) { IssueReset(); return; } assert(false); } } void Session::IssueWrite(size_t pos) { m_eState = WAIT_SEND; BOOL res = WriteFile( (HANDLE)m_hSocket, &(m_outline[pos]), m_outline.size() - pos, NULL, (LPOVERLAPPED)this ); int err; if (!(res == TRUE || (err = WSAGetLastError()) == ERROR_IO_PENDING)) { LOG1(_T("Fail WriteFile (%d)"), err); } } void Session::CompleteWrite( DWORD rNumTransferred ) { if (rNumTransferred < m_outline.size()) { IssueWrite( rNumTransferred ); return; } _TCHAR buf[65]; _itot_s(m_hSocket, buf, 10); LOG2(_T("S: %s"), buf, TOLPTCHAR(&(m_outline.substr(0, m_outline.size() - 2)[0]))); CompleteOperation(); } void Session::CompleteOperation() { if (m_eState == STATE::WAIT_REQUEST && strncmp(m_line.c_str(), "QUIT", 4) == 0) { m_eOpState = OPSTATE::RE_QUIT; m_outline = "221 Bye\r\n"; IssueWrite(0); return; } if (m_eState == STATE::WAIT_REQUEST && strncmp(m_line.c_str(), "RSET", 4) == 0) { m_eOpState = OPSTATE::RE_DOT; m_outline = "250 Ok\r\n"; IssueWrite(0); return; } if (m_eState == STATE::WAIT_REQUEST && strncmp(m_line.c_str(), "NOOP", 4) == 0) { // does not change state m_outline = "250 Ok\r\n"; IssueWrite(0); return; } switch (m_eOpState) { case OPSTATE::NONE: m_eOpState = OPSTATE::SEND_WELCOME; m_outline = "220 DevSmtp\r\n"; IssueWrite(0); break; case OPSTATE::SEND_WELCOME: m_eOpState = OPSTATE::RCV_HELLO; IssueRead(); break; case OPSTATE::RCV_HELLO: if (strncmp(m_line.c_str(), "HELO", 4) != 0) { m_eOpState = OPSTATE::SEND_WELCOME; m_outline = "500 Command not recognized: EHLO\r\n"; IssueWrite(0); return; } m_eOpState = OPSTATE::RE_RCV_HELLO; m_outline = "250 Ok\r\n"; IssueWrite(0); break; case OPSTATE::RE_RCV_HELLO: m_eOpState = OPSTATE::MAIL; IssueRead(); break; case OPSTATE::MAIL: if (strncmp(m_line.c_str(), "MAIL", 4) != 0) { m_eOpState = OPSTATE::RE_RCV_HELLO; m_outline = "500 Command not recognized: EHLO\r\n"; IssueWrite(0); return; } m_eOpState = OPSTATE::RE_MAIL; m_outline = "250 Ok\r\n"; IssueWrite(0); break; case OPSTATE::RE_MAIL: m_eOpState = OPSTATE::RCPT; IssueRead(); break; case OPSTATE::RCPT: m_eOpState = OPSTATE::RE_RCPT; m_outline = "250 Ok\r\n"; IssueWrite(0); break; case OPSTATE::RE_RCPT: m_eOpState = OPSTATE::RCPT_OR_DATA; IssueRead(); break; case OPSTATE::RCPT_OR_DATA: if (strncmp(m_line.c_str(), "DATA", 4) == 0) { m_eOpState = OPSTATE::RE_DATA; m_outline = "354 End data with <CR><LF>.<CR><LF>\r\n"; } else { m_eOpState = OPSTATE::RE_RCPT; m_outline = "250 Ok\r\n"; } IssueWrite(0); break; case OPSTATE::RE_DATA: m_eOpState = OPSTATE::DOT; IssueRead(STATE::WAIT_REQUEST_DATA); break; case OPSTATE::DOT: m_eOpState = OPSTATE::WRITE_FILE; IssueWriteFile(0); break; case OPSTATE::WRITE_FILE: m_eOpState = OPSTATE::RE_DOT; m_outline = "250 Ok\r\n"; IssueWrite(0); break; case OPSTATE::RE_DOT: m_eOpState = OPSTATE::QUIT_OR_MAIL; IssueRead(); break; case OPSTATE::QUIT_OR_MAIL: if (strncmp(m_line.c_str(), "MAIL", 4) == 0) { m_eOpState = OPSTATE::RE_MAIL; m_outline = "250 Ok\r\n"; IssueWrite(0); } break; case OPSTATE::RE_QUIT: IssueReset(); break; } } void Session::IssueReset() { Log(_T("Closed socket.")); closesocket(m_hSocket); m_eOpState = OPSTATE::NONE; IssueAccept(); } bool Session::CanProcessZero() { return m_eState == STATE::WAIT_ACCEPT; } void Session::IssueWriteFile(size_t pos) { if (m_hFile == 0) { byte attempts = 5; _TCHAR file_name[_MAX_PATH]; tstring full_path; full_path.reserve(_MAX_PATH); full_path.append(m_pServer->m_pPath); full_path.append("email-"); time_t tt = time( NULL ); srand((unsigned)tt); _TCHAR tmpbuf[16]; struct tm today; localtime_s( &today, &tt ); _tcsftime(tmpbuf, sizeof(tmpbuf) / sizeof(_TCHAR), _T("%Y%m%d-%H%M%S"), &today); full_path.append(tmpbuf); while (TRUE) { _stprintf_s(file_name, sizeof(file_name) / sizeof(_TCHAR), _T("%s-(%d).eml"), full_path.c_str(), rand()); LOG1(_T("Saving email to '%s'"), file_name); m_hFile = CreateFile(file_name, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_FLAG_OVERLAPPED | FILE_FLAG_WRITE_THROUGH, NULL); if (m_hFile == INVALID_HANDLE_VALUE) { LOG1(_T("Can't open file to write (%d)."), GetLastError()); if (--attempts > 0) continue; else { IssueReset(); return; } } break; } HANDLE hcport = CreateIoCompletionPort( m_hFile, m_pServer->m_hIoPort, COMPLETION_FILE_KEY_IO, 0 ); assert(hcport != NULL); m_eState = WAIT_WRITE; m_pFo.Internal = 0; m_pFo.InternalHigh = 0; m_pFo.Offset = 0; m_pFo.OffsetHigh = 0; m_pFo.hEvent = 0; } else { LOG1(_T("Used existing file handler %d"), m_hFile); } BOOL res = WriteFile( m_hFile, &(m_line[pos]), m_line.size() - pos, NULL, &m_pFo ); int err; if (!(res == TRUE || (err = GetLastError()) == ERROR_IO_PENDING)) { LOG1(_T("Fail WriteFile (%d)"), err); CloseHandle(m_hFile); m_hFile = 0; IssueReset(); } } void Session::CompleteWriteFile( DWORD rNumTransferred ) { if (rNumTransferred < m_line.size()) { IssueWriteFile( rNumTransferred ); return; } CloseHandle(m_hFile); m_hFile = 0; CompleteOperation(); } }
[ [ [ 1, 498 ] ] ]
c82c7cf9e51ddabdea7150556e09d83eab1001fa
61fb1bf48c8eeeda8ecb2c40fcec1d3277ba6935
/patoBase/patolog.cpp
e22a01f6b620ab97f6f5580c688ce620ae28b27a
[]
no_license
matherthal/pato-scm
172497f3e5c6d71a2cbbd2db132282fb36ba4871
ba573dad95afa0c0440f1ae7d5b52a2736459b10
refs/heads/master
2020-05-20T08:48:12.286498
2011-11-25T11:05:23
2011-11-25T11:05:23
33,139,075
0
0
null
null
null
null
UTF-8
C++
false
false
875
cpp
#include "patolog.h" PatoLog::PatoLog() { } void PatoLog::setId(int id) { m_idLog = id; } int PatoLog::getId() { return m_idLog; } void PatoLog::setData(std::string& data) { m_data = data; } std::string PatoLog::getData() { return m_data; } void PatoLog::setMessage(std::string& msg) { m_message = msg; } std::string PatoLog::getMessage() { return m_message; } void PatoLog::setUser(PatoUser& user) { m_user = user; } PatoUser PatoLog::getUser() { return m_user; } std::string PatoLog::getNameUser() { return m_user.getName(); } void PatoLog::setVecFile(std::vector<PatoFile>& vecFile) { m_vecFile = vecFile; } std::vector<PatoFile> PatoLog::getVecFile() { return m_vecFile; } void PatoLog::insertFile(PatoFile& file) { m_vecFile.push_back(file); }
[ "rafael@Micro-Mariana" ]
[ [ [ 1, 65 ] ] ]
20962d8cbcf3a25edbf5080c97bcbdfe2cc0576a
57574cc7192ea8564bd630dbc2a1f1c4806e4e69
/Poker/Servidor/main.cpp
cd301a88ab9db8dacad8a17084244ae969d9ab48
[]
no_license
natlehmann/taller-2010-2c-poker
3c6821faacccd5afa526b36026b2b153a2e471f9
d07384873b3705d1cd37448a65b04b4105060f19
refs/heads/master
2016-09-05T23:43:54.272182
2010-11-17T11:48:00
2010-11-17T11:48:00
32,321,142
0
0
null
null
null
null
UTF-8
C++
false
false
349
cpp
#include <vld.h> #include "UIServidor.h" #include "ContextoJuego.h" #include "SincronizadorThreads.h" int main (int argc, char** argv) { UIServidor ui; ui.iniciarAplicacion(); ContextoJuego::getInstancia()->finalizar(); delete(ContextoJuego::getInstancia()); //delete(SincronizadorThreads::getInstancia()); return 0; }
[ "natlehmann@a9434d28-8610-e991-b0d0-89a272e3a296", "flrago78538@a9434d28-8610-e991-b0d0-89a272e3a296", "[email protected]@a9434d28-8610-e991-b0d0-89a272e3a296", "marianofl85@a9434d28-8610-e991-b0d0-89a272e3a296" ]
[ [ [ 1, 1 ] ], [ [ 2, 2 ], [ 5, 12 ], [ 16, 17 ] ], [ [ 3, 4 ], [ 13, 15 ] ], [ [ 18, 18 ] ] ]
16911b1dcdc77710777f2b8c17ffde0a7b604fe4
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/UIRenderer.Windows.inl
56ad35c6f71f2545bbffba087595343f97abeebf
[]
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
823
inl
namespace Halak { GraphicsDevice* UIRenderer::GetGraphicsDevice() const { return graphicsDevice; } float UIRenderer::GetFieldOfView() const { return fieldOfView; } const Matrix4& UIRenderer::GetViewTransform() { UpdateViewProjectionTransform(); return viewTransform; } const Matrix4& UIRenderer::GetProjectionTransform() { UpdateViewProjectionTransform(); return projectionTransform; } const Matrix4& UIRenderer::GetInversedViewTransform() { UpdateViewProjectionTransform(); return viewTransformInv; } const Matrix4& UIRenderer::GetInversedProjectionTransform() { UpdateViewProjectionTransform(); return projectionTransformInv; } }
[ [ [ 1, 36 ] ] ]
aa122c5c17b468dabb6a8e067c9d4e7bd5f5ca9c
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Common/CooltimeMgr.cpp
b191f1f76390873ba2c0fc1d9b1a87cb36fada3d
[]
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
1,501
cpp
#include "stdafx.h" #include "misc.h" #include "CooltimeMgr.h" #include "ProjectCmn.h" CCooltimeMgr::CCooltimeMgr() { ZeroMemory( m_times, sizeof(m_times) ); ZeroMemory( m_bases, sizeof(m_bases) ); } CCooltimeMgr::~CCooltimeMgr() { } // 쿨타임 아이템의 쿨타임 그룹번호를 얻는다. // 같은 그룹의 아이템은 한번 사용하면 모두 같이 쿨타임을 적용받는다. // 주의: 수정하려면 헤더파일에 MAX_COOLTIME_TYPE를 잘 조절할 것 DWORD CCooltimeMgr::GetGroup( ItemProp* pItemProp ) { DWORD dwCooltimeItemGroup = 0; if( pItemProp->dwSkillReady > 0 ) { switch ( pItemProp->dwItemKind2 ) { case IK2_FOOD: dwCooltimeItemGroup = 1; if( pItemProp->dwItemKind3 == IK3_PILL ) dwCooltimeItemGroup = 2; break; case IK2_SKILL: dwCooltimeItemGroup = 3; break; // case IK2_POTION: // dwCooltimeItemGroup = 3; // break; } } return dwCooltimeItemGroup; } // dwGroup을 사용할 수 있는가? BOOL CCooltimeMgr::CanUse( DWORD dwGroup ) { ASSERT( dwGroup > 0 ); return g_tmCurrent > GetTime( dwGroup ); // 재사용 시각을 넘으면 사용가능 } // 사용한 시각을 기록해서, CanUse에서 판단 근거로 사용한다. void CCooltimeMgr::SetTime( DWORD dwGroup, DWORD dwCoolTime ) { ASSERT( dwGroup > 0 && dwCoolTime > 0 ); DWORD dwTick = g_tmCurrent; m_times[dwGroup - 1] = dwTick + dwCoolTime; m_bases[dwGroup - 1] = dwTick; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 63 ] ] ]
2cbb06c8b7ef1098c04be18026bea0ebd098eaf8
6327ac79f3294817895d5ef859509145bc0c28a9
/win/w32dir.cpp
fbd0e2588ebdb4c416bb53f39c1baf91ec42b358
[]
no_license
corpsofengineers/ffed3d
c8da1cb6e58f8b37b138d6f7d7ac0faa585e961b
8b6df7c081fd9ec4cf86220e8561439a8340d59b
refs/heads/master
2021-01-10T13:17:57.882726
2011-12-05T22:24:07
2011-12-05T22:24:07
49,797,267
2
1
null
null
null
null
UTF-8
C++
false
false
5,550
cpp
#include <windows.h> // messagebox #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../ffecfg.h" #include "../ffeapi.h" #include <direct.h> #include <io.h> static char pDirAVIPathDef[] = "DATA\\"; static char pDirCmmdrPathDef[] = "COMMANDR\\"; static char pDirSamplePathDef[] = "FX\\"; static char pDirSongPathDef[] = "MUSIC\\"; static char pDirAVIPath[256]; static char pDirCmmdrPathSys[256]; static char pDirCmmdrPath[256]; static char pDirSamplePath[256]; static char pDirSongPath[256]; static struct _finddata_t DirFFBlk; static long dirFFHandle; static FileInfo pDirFFDrives[26]; static int dirFFNumDrives = 0; static int dirFFCurDrive = 0; static int dirFirstFlag = 1; static int dirDirsFlag = 1; static FILE *pLog = NULL; void WinDirAddDrive (char *pName, int type) { FileInfo *pCur = pDirFFDrives+dirFFNumDrives; strcpy (pCur->pName, pName); pCur->type = type; pCur->size = 0; dirFFNumDrives++; } void WinDirFixPath (char *pInPath, char *pOutPath) { char pBuf[256], *pTok; if (pInPath[1] != ':') { _getcwd (pBuf, 255); strcat (pBuf, "\\"); strcat (pBuf, pInPath); } else strcpy (pBuf, pInPath); strcpy (pOutPath, strtok (pBuf, "\\/")); strcat (pOutPath, "\\"); while ((pTok = strtok (NULL, "\\/")) != NULL) { strcat (pOutPath, pTok); strcat (pOutPath, "\\"); } } extern "C" void DirInit (void) { CfgStruct cfg; int rv; char *pTok; char pBuf[256]; char pBuf2[256]; // Working directory hack for shareware version if (_access ("mission.dat", 4) != 0) { //MessageBox (NULL, "Warning - JJFFE not installed correctly", // "WinFFE startup error", MB_OK | MB_ICONWARNING); _chdir ("game"); } CfgOpen (&cfg, __CONFIGFILE__); CfgFindSection (&cfg, "DIR"); rv = CfgGetKeyStr (&cfg, "AVIPath", pBuf, 255); if (rv != 0) { pTok = strtok (pBuf, " \n\t"); strcpy (pBuf, pTok); WinDirFixPath (pBuf, pDirAVIPath); } else WinDirFixPath (pDirAVIPathDef, pDirAVIPath); rv = CfgGetKeyStr (&cfg, "CmmdrPath", pBuf, 255); if (rv != 0) { pTok = strtok (pBuf, " \n\t"); strcpy (pBuf, pTok); WinDirFixPath (pBuf, pDirCmmdrPath); } else WinDirFixPath (pDirCmmdrPathDef, pDirCmmdrPath); rv = CfgGetKeyStr (&cfg, "SamplePath", pBuf, 255); if (rv != 0) { pTok = strtok (pBuf, " \n\t"); strcpy (pBuf, pTok); WinDirFixPath (pBuf, pDirSamplePath); } else WinDirFixPath (pDirSamplePathDef, pDirSamplePath); rv = CfgGetKeyStr (&cfg, "SongPath", pBuf, 255); if (rv != 0) { pTok = strtok (pBuf, " \n\t"); strcpy (pBuf, pTok); WinDirFixPath (pBuf, pDirSongPath); } else WinDirFixPath (pDirSongPathDef, pDirSongPath); CfgClose (&cfg); // Test for directory presence _getcwd (pBuf, 255); if (_chdir (pDirCmmdrPath) != 0) { WinDirFixPath (pBuf, pDirCmmdrPath); } strcpy (pDirCmmdrPathSys, pDirCmmdrPath); // Read drive letters WinDirAddDrive ("A:\\", 6); strcpy (pBuf2, "C:\\"); while (_chdir (pBuf2) == 0) { WinDirAddDrive (pBuf2, 6); pBuf2[0]++; } _chdir (pBuf); } extern "C" void DirCleanup (void) { } extern "C" { char *DirMakeAVIName (char *pBuf, char *pStub) { strcpy (pBuf, pDirAVIPath); strcat (pBuf, pStub); strcat (pBuf, ".avi"); return pBuf; } char *DirMakeSampleName (char *pBuf, char *pFilename) { strcpy (pBuf, pDirSamplePath); strcat (pBuf, pFilename); return pBuf; } char *DirMakeSongName (char *pBuf, char *pFilename) { strcpy (pBuf, pDirSongPath); strcat (pBuf, pFilename); return pBuf; } char *DirMakeCmmdrName (char *pBuf, char *pFilename) { strcpy (pBuf, pDirCmmdrPath); strcat (pBuf, pFilename); return pBuf; } char *DirGetCmmdrPath (void) { return pDirCmmdrPath; } void DirResetCmmdrPath (void) { strcpy (pDirCmmdrPath, pDirCmmdrPathSys); } int DirFindFirst (FileInfo *pFile) { *pFile = pDirFFDrives[0]; dirFFCurDrive = 1; dirFirstFlag = 1; dirDirsFlag = 1; return 1; } int DirFindNext (FileInfo *pFile) { int rv; if (dirFFCurDrive < dirFFNumDrives) { *pFile = pDirFFDrives[dirFFCurDrive++]; return 1; } while (1) { if (dirFirstFlag == 1) { char pTemp[256]; strcpy (pTemp, pDirCmmdrPath); strcat (pTemp, "*.*"); rv = _findfirst (pTemp, &DirFFBlk); dirFFHandle = rv; dirFirstFlag = 0; } else { rv = _findnext (dirFFHandle, &DirFFBlk); } if (rv == -1) { if (dirFFHandle!=-1) _findclose (dirFFHandle); if (dirDirsFlag==0) return 0; else { dirDirsFlag = 0; dirFirstFlag = 1; continue; } continue; } if (dirDirsFlag && !(DirFFBlk.attrib & _A_SUBDIR)) continue; if (!dirDirsFlag && (DirFFBlk.attrib & _A_SUBDIR)) continue; if (!strcmp (DirFFBlk.name, ".")) continue; break; } strncpy (pFile->pName, DirFFBlk.name, 16); pFile->size = DirFFBlk.size; if (DirFFBlk.attrib & _A_SUBDIR) { pFile->type = 2; strcat (pFile->pName, "\\"); } else pFile->type = 0; if (!strcmp (pFile->pName, "..\\")) { strcpy (pFile->pName, "(Parent Dir)\\"); pFile->type = 4; } return 1; } void DirNavigateTree (FileInfo *pFile) { if (pFile->type == 2) { strcat (pDirCmmdrPath, pFile->pName); } if (pFile->type == 4) { char *pTemp; int i = strlen (pDirCmmdrPath); pDirCmmdrPath[i-1] = 0; pTemp = strrchr (pDirCmmdrPath, '\\'); if (pTemp != 0) pTemp[1] = 0; else pDirCmmdrPath[i-1] = '\\'; } if (pFile->type == 6) { strcpy (pDirCmmdrPath, pFile->pName); } } }
[ "dreamonzzz@a43015ce-51b6-2c96-052f-f15b0ecaca65" ]
[ [ [ 1, 256 ] ] ]
20d32e584b917358ab8d1480cda957dca36875cf
9b402d093b852a574dccb869fbe4bada1ef069c6
/libs/mygui/inc/MyGUI_OverlayItem.h
c1f1442bfdfde6148dcc50186929e12dab7d3dc1
[]
no_license
wangscript007/foundation-engine
adb24d4ccc932d7a8f8238170029de6d2db0cbfb
2982b06d8f6b69c0654e0c90671aaef9cfc6cc40
refs/heads/master
2021-05-27T17:26:15.178095
2010-06-30T22:06:45
2010-06-30T22:06:45
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,017
h
/*! @file @author Albert Semenov @date 02/2008 @module */ #ifndef __MYGUI_OVERLAY_ITEM_H__ #define __MYGUI_OVERLAY_ITEM_H__ #include "MyGUI_Prerequest.h" #include "MyGUI_DrawItem.h" #include <OgreRenderSystem.h> namespace MyGUI { typedef std::pair<DrawItem *, size_t> DrawItemInfo; typedef std::vector<DrawItemInfo> VectorDrawItem; class _MyGUIExport OverlayItem { public: OverlayItem(const Ogre::String& _material); void updatePositionGeometry(); void updateView(); void addDrawItem(DrawItem * _item, size_t _count); void removeDrawItem(DrawItem * _item, size_t _count); // обновить буфер inline void outOfDate() { mOutOfDate = true; } private: void memoryAllocation(); private: Ogre::RenderOperation mRenderOp; bool mOutOfDate; VectorDrawItem mVectorDrawItem; size_t mNeedVertex; size_t mCountVertex; float mPixelScaleX, mPixelScaleY; }; } // namespace MyGUI #endif // __MYGUI_OVERLAY_ITEM_H__
[ "drivehappy@a5d1a9aa-f497-11dd-9d1a-b59b2e1864b6" ]
[ [ [ 1, 50 ] ] ]
dac87711cbeee8eba509d68daef1ee92d49033e0
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/slon/Scene/Visitor.h
07953a313c945efd530e8b6972406b1d4b86cd7d
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
930
h
#ifndef __SLON_ENGINE_SCENE_VISITOR_H__ #define __SLON_ENGINE_SCENE_VISITOR_H__ #include "Forward.h" #include <boost/type_traits/integral_constant.hpp> namespace slon { namespace scene { /** Base class for visitors, traversing scene graphs. */ class SLON_PUBLIC Visitor { public: typedef Node node_type; // tags typedef boost::false_type accept_tag; public: /** Perform traverse. */ virtual void traverse(node_type& node) = 0; virtual ~Visitor() {} }; /** Base class for constant visitors, traversing scene graphs. */ class SLON_PUBLIC ConstVisitor { public: typedef const Node node_type; // tags typedef boost::false_type accept_tag; public: /** Perform traverse. */ virtual void traverse(node_type& node) = 0; virtual ~ConstVisitor() {} }; } // namepsace scene } // namespace slon #endif // __SLON_ENGINE_SCENE_VISITOR_H__
[ "devnull@localhost" ]
[ [ [ 1, 45 ] ] ]
8a7a01a24ca75304a0ec7794656f839b63e9e35d
2d212a074917aad8c57ed585e6ce8e2073aa06c6
/cgworkshop/src-0.1/GUI/GUI.h
130592ba10d7592e1bef4f8a791d9eb32899987e
[]
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
1,327
h
#ifndef _H_GUI_H_ #define _H_GUI_H_ #include <cv.h> #include <GL/glut.h> #include "TypeDefs.h" #include "Loader.h" class CGUI { public: //TODO: move to cpp. you are lazy! CGUI() { m_fScribbling = false; } virtual ~CGUI() {} int Setup(char * pszImagePath, char * pScribbleFile = NULL); static CGUI * GetInstance() { static CGUI inst; return &inst; } void LoadTextures(); public: int GetWidth() const { return m_nWindowWidth; } int GetHeight() const { return m_nWindowHeight; } void SetWindowSize(int x, int y) { m_nWindowWidth = x; m_nWindowHeight = y; } const IplImage * const GetImage() { return m_pImg; } public: void MouseMove(int x, int y); void MouseAction(int button, int state, int x, int y); void KeysAction(unsigned char key, int x, int y ); void Reshape(int x , int y); void Render(); protected: void AddScribblePoints(int x, int y); protected: IplImage * m_pImg; int m_nWindowWidth; int m_nWindowHeight; // the bounding box for the opengl orthogonal projection float m_orthoBBox[4]; unsigned int m_textures[1]; // The vectors in object space coordinates (for rendering) ScribbleVector m_scribbles; bool m_fScribbling; CLoader m_loader; }; #endif //_H_GUI_H_
[ "ikirsh@60b542fb-872c-0410-bfbb-43802cb78f6e" ]
[ [ [ 1, 73 ] ] ]
bd2859c127c731f9584ca5d5a983c62d378b3835
58865be8e22939fd980af6c9697add3571868b17
/source/HotkeyRegistration.hxx
47850c67d462747dfe3f9ca00f6ac1120027826b
[ "BSD-2-Clause" ]
permissive
dilyanrusev/foo-mm-keys
73fb63a10730fac1a4b5e52ee901a2b0e854195c
ab326f7243e997550186a99cdc73a4f147bc3d2c
refs/heads/master
2020-04-05T23:27:47.251505
2011-12-01T07:52:27
2011-12-01T07:52:27
32,144,913
0
0
null
null
null
null
UTF-8
C++
false
false
1,831
hxx
/* Copyright (c) 2011, Dilyan Rusev All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <Windows.h> #include <vector> enum Hotkeys { Hotkey_ToggleVolume, Hotkey_VolumeUp, Hotkey_VolumeDown, Hotkey_Quit }; const char * hotkey_to_str(Hotkeys hk); class HotkeyRegistration { Hotkeys _hk; HWND _hwnd; UINT _mods; UINT _vk; BOOL _registered; public: HotkeyRegistration(HWND hwnd, Hotkeys hk, UINT mods, UINT vk); HotkeyRegistration(Hotkeys hk, UINT mods, UINT vk); virtual ~HotkeyRegistration(); const char * hotkey_str(); };
[ [ [ 1, 54 ] ] ]
95ea4906ffd2f721b73648e10c364f5c35d6859b
4b116281b895732989336f45dc65e95deb69917b
/Code Base/GSP410-Project2/DirectXFramework.h
fbf29e344182a88753ee9e557b276b0c6dd3fe43
[]
no_license
Pavani565/gsp410-spaceshooter
1f192ca16b41e8afdcc25645f950508a6f9a92c6
c299b03d285e676874f72aa062d76b186918b146
refs/heads/master
2021-01-10T00:59:18.499288
2011-12-12T16:59:51
2011-12-12T16:59:51
33,170,205
0
0
null
null
null
null
UTF-8
C++
false
false
2,361
h
#pragma once #include "Definitions.h" #include "DirectXIncludes.h" #include "Unit.h" #include "FriendlyUnit.h" #include "EnemyUnit.h" #include<sstream> class CDirectXFramework { private: // Application Variables // HWND m_hWnd; // Window Handle // RECT m_Window; // Window Size // RECT m_Source; // Source Window Size // bool m_bVsync; // Vertical Sync Boolean // HRESULT m_HResult; // Error Checking // // Direct3D Variables // IDirect3D9* m_pD3DObject; // Direct3D 9 Object Pointer // IDirect3DDevice9* m_pD3DDevice; // Direct3D 9 Device Pointer // D3DCAPS9 m_D3DCaps; // Device Capabilites // // Matrices // D3DXMATRIX m_MatTrans; // Translation Matrix // D3DXMATRIX m_MatRot; // Rotation Matrix // D3DXMATRIX m_MatScale; // Scale Matrix // D3DXMATRIX m_MatWorld; // World Matrix // D3DXMATRIX m_MatView; // View Transform Matrix // D3DXMATRIX m_MatProj; // Projection Transform Matrix // // Sprite Variables // ID3DXSprite* m_pD3DSprite; // Sprite Object Pointer // IDirect3DTexture9* m_Paneling; // Pointer To The Texture // D3DXIMAGE_INFO m_PanelingInfo; // Info Related To Texture // IDirect3DTexture9* m_FireButton; // Pointer To The Texture // D3DXIMAGE_INFO m_FireButtonInfo; // Info Related To Texture // // Font Variables // ID3DXFont* m_pD3DFont; // Font Object Pointer // // Direct Input Variables // IDirectInput8* m_pDIObject; // DirectInput Object // IDirectInputDevice8* m_pDIKeyboard; // Keyboard Device // bool m_bKeyDown[256]; // Used To Get Keyboard Input // IDirectInputDevice8* m_pDIMouse; // Mouse Device // DIMOUSESTATE2 m_MouseState; // Mouse's State // POINT m_MousePosition; // Mouse's Position // // Game Variables // CFriendlyUnit m_Player; // m_Player 1 // TCHAR m_Text[32]; // Text to Display // TCHAR m_Text2[3]; // Text to Display // public: // Constructor And Destructor // CDirectXFramework(void); ~CDirectXFramework(void); // Initialize DirectX // void InitDX(HWND& hWnd, HINSTANCE& hInst, bool bWindowed); void LoadTextures(void); // Update // void Update(float DeltaTime); // Render // void Render(void); // Shutdown // void Shutdown(void); };
[ "[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7" ]
[ [ [ 1, 75 ] ] ]
9b877563d8fddabd59039e99f185f92778749e24
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/libs/STLPort-4.0/test/regression/vec1.cpp
d3e3dcbff0400023c4d2a05cc1345531297738cc
[ "LicenseRef-scancode-stlport-4.5" ]
permissive
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
918
cpp
// STLport regression testsuite component. // To compile as a separate example, please #define MAIN. #include <iostream> #include <algorithm> #include <vector> #ifdef MAIN #define vec1_test main #endif #if !defined (STLPORT) || defined(__STL_USE_NAMESPACES) using namespace std; #endif int vec1_test(int, char**) { // cout<<"Sizeof(vector) is "<<sizeof(vector<int>)<<endl; // cout<<"Sizeof(fw) is "<<sizeof(forward_iterator_tag)<<endl; // cout<<"Sizeof(ra) is "<<sizeof(random_access_iterator_tag)<<endl; cout<<"Results of vec1_test:"<<endl; vector<int> v1; // Empty vector of integers. cout << "empty = " << v1.empty() << endl; cout << "size = " << v1.size() << endl; cout << "max_size = " << v1.max_size() << endl; v1.push_back(42); // Add an integer to the vector. cout << "size = " << v1.size() << endl; cout << "v1[0] = " << v1[0] << endl; return 0; }
[ [ [ 1, 29 ] ] ]
12c44abf56ee2e1f3b2aad192946fb4f1c8288a9
76ea17bc9bc52ae653bd203dd6716fd1e965a8c9
/libcoolaudio/demo_with_pspsdk/test.cpp
8a7a29e26b11f346c1cb88c95bef45668bb83df9
[]
no_license
eickegao/avgscript
1e78cc09b8c52e5ee9b3be48b81ef5b128fef269
75e75b8c5597b673855b91e6e1bd87c5c60b8c04
refs/heads/master
2016-09-08T00:32:29.508547
2009-01-12T08:40:08
2009-01-12T08:40:08
33,953,223
0
0
null
null
null
null
UTF-8
C++
false
false
2,477
cpp
#include "interface.h" #include <pspsdk.h> #include <pspkernel.h> #include <pspctrl.h> #include <stdio.h> #include <stdlib.h> #include <pspaudiocodec.h> #include <pspmpeg.h> #include <pspdisplay.h> int SetupCallbacks(); PSP_MODULE_INFO("MP3 TEST", 0x1000, 1, 1); PSP_MAIN_THREAD_ATTR(0); __attribute__ ((constructor)) void loaderInit(){ pspKernelSetKernelPC(); pspSdkInstallNoDeviceCheckPatch(); pspSdkInstallNoPlainModuleCheckPatch(); pspSdkInstallKernelLoadModulePatch(); } play_ops ops; SceCtrlData input; int main(int argc, char *argv[]){ SetupCallbacks(); pspDebugScreenInit(); pspDebugScreenSetXY(0, 2); int result = pspSdkLoadStartModule("flash0:/kd/me_for_vsh.prx", PSP_MEMORY_PARTITION_KERNEL); result = pspSdkLoadStartModule("flash0:/kd/videocodec.prx", PSP_MEMORY_PARTITION_KERNEL); result = pspSdkLoadStartModule("flash0:/kd/audiocodec.prx", PSP_MEMORY_PARTITION_KERNEL); result = pspSdkLoadStartModule("flash0:/kd/mpegbase.prx", PSP_MEMORY_PARTITION_KERNEL); result = pspSdkLoadStartModule("flash0:/kd/mpeg_vsh.prx", PSP_MEMORY_PARTITION_USER); pspSdkFixupImports(result); sceMpegInit(); //init MP3PlayInit(&ops); //load and play int res = ops.load("ms0:/Test.mp3"); pspDebugScreenPrintf("%d\n", res); if (res == 1) { ops.play(); pspDebugScreenPrintf("playing....\n"); do{ sceKernelDelayThread(100); }while( ops.eos()!=1); } pspDebugScreenPrintf("stop....\n"); sceCtrlReadBufferPositive(&input, 1); while(!(input.Buttons & PSP_CTRL_TRIANGLE)) { sceKernelDelayThread(10000); // wait 10 milliseconds sceCtrlReadBufferPositive(&input, 1); } MP3PlayFini(); sceKernelExitGame(); return 0; } /* Exit callback */ int exit_callback(int arg1, int arg2, void *common) { sceKernelExitGame(); return 0; } /* Callback thread */ int CallbackThread(SceSize args, void *argp) { int cbid; cbid = sceKernelCreateCallback("Exit Callback", exit_callback, NULL); sceKernelRegisterExitCallback(cbid); sceKernelSleepThreadCB(); return 0; } /* Sets up the callback thread and returns its thread id */ int SetupCallbacks(void) { int thid = 0; thid = sceKernelCreateThread("update_thread", CallbackThread, 0x11, 0xFA0, 0, 0); if(thid >= 0) { sceKernelStartThread(thid, 0, 0); } return thid; }
[ "pspbter@7305fedb-903f-0410-a37f-9f94d3351015" ]
[ [ [ 1, 105 ] ] ]
7bbd6d458d7ce88fbb9ff0a4f1b850ca26e0190e
ce8a2b1cb1d4baaefc643f8116999ce8aeff2e2c
/VbGame/TestClient/Client.h
9cbceb479fbff13d02dac517802f301b0595d567
[]
no_license
qingxiaoxuxu/virtual-bicycle
077929f925c01d54c9ef6d6e627437451ecf758c
4a5e7aa8b8c8616567ccb170c2aa0c17b520aed1
refs/heads/master
2021-01-10T04:47:37.424169
2011-06-02T13:15:56
2011-06-02T13:15:56
55,270,741
0
0
null
null
null
null
UTF-8
C++
false
false
682
h
#pragma once #pragma unmanaged #include "Common.h" namespace TestClient { class Client { private: static bool m_aborting; static char s_serverAdd[]; static SOCKET m_socket; Client(void) {} ~Client(void) {} static SOCKET CreateConnection(); static void CloseConnection(SOCKET sck); public: static void SetServerAddress(const String &str) { BOOL flag; WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, str.c_str(), (int)str.length(), s_serverAdd, 20, NULL, &flag); } static void Initialize(); static void Finalize(); static bool Send(const String& str); static String ReceiveLine(); }; }
[ "canbitwell@15f0cb43-c384-8cde-1ce0-2bb2f560ea80" ]
[ [ [ 1, 42 ] ] ]
d36a27f9ade493351bb1c75557151569527178ce
a46400e00852a50d520994e2784834ca1662ca41
/CPPNinjaMonkey/src/lib/game/GameLoop.h
1abdadd0fe15c81c07133478f026e518f622645e
[]
no_license
j0rg3n/shadow-ninja-monkey
ccddd252da672d13c9a251c687d83be98c4c59c8
aac16245be849e109f5e584bf97a4e6443860aba
refs/heads/master
2021-01-10T10:28:39.371674
2011-02-06T21:12:56
2011-02-06T21:12:56
45,484,036
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
h
#pragma once #ifndef GAMELOOP_H_INCLUDED #define GAMELOOP_H_INCLUDED #include <vector> #include "boost/cstdint.hpp" #include "boost/signals2/signal.hpp" #include "net/PeerServer.h" // ----------------------------------------------------------------------------- class Entity; // ----------------------------------------------------------------------------- struct GameLoop { typedef boost::signals2::signal<void (boost::int32_t x, boost::int32_t y)> PlayerPositionUpdatedSignal; virtual ~GameLoop() {}; virtual void Run() = 0; virtual std::vector<Entity*>& GetEntities() = 0; virtual void OnPeerJoined(SessionID nSessionID) = 0; virtual void OnPeerLeft(SessionID nSessionID) = 0; virtual void OnPeerUpdatePosition(SessionID nSessionID, boost::int32_t x, boost::int32_t y) = 0; virtual void OnButtonUpdate(const std::string& sButtonName, bool bPressed) = 0; virtual void OnAxisUpdate(const std::string& sAxisName, float nValue) = 0; virtual boost::signals2::connection ConnectPlayerPositionUpdatedSlot(const PlayerPositionUpdatedSignal::slot_type& slot) = 0; static GameLoop* CreateInstance(); }; #endif // GAMELOOP_H_INCLUDED
[ [ [ 1, 44 ] ] ]
4c7b2124afde0ed9aa0e03f89568a40650ff173e
96f796a966025265020459ca2a38346c3c292b1e
/Ansoply/D3DHelpers/d3dutil.cpp
a6495ef97c12fecdf7b2f464b157dd35ac34db89
[]
no_license
shanewfx/ansoply
222979843662ddb98fb444ce735d607e3033dd5e
99e91008048d0c1afbf80152d0dc173a15e068ee
refs/heads/master
2020-05-18T15:53:46.618329
2009-06-17T01:04:47
2009-06-17T01:04:47
32,243,359
1
0
null
null
null
null
UTF-8
C++
false
false
11,071
cpp
//----------------------------------------------------------------------------- // File: D3DUtil.cpp // // Desc: Shortcut macros and functions for using DirectX objects // // Copyright (c) Microsoft Corporation. All rights reserved //----------------------------------------------------------------------------- #include "stdafx.h" #include "../project.h" #define D3D_OVERLOADS #include <math.h> #include "D3DUtil.h" #ifndef _T #define _T TEXT #endif //----------------------------------------------------------------------------- // Name: D3DUtil_GetDXSDKMediaPath() // Desc: Returns the DirectX SDK media path, as stored in the system registry // during the SDK install. //----------------------------------------------------------------------------- const TCHAR* D3DUtil_GetDXSDKMediaPath() { static TCHAR strNull[2] = _T(""); static TCHAR strPath[MAX_PATH + 20]; HKEY hKey; DWORD type, size=MAX_PATH; // Open the appropriate registry key LONG result = RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\DirectX SDK"), 0, KEY_READ, &hKey ); if( ERROR_SUCCESS != result ) return strNull; result = RegQueryValueEx( hKey, _T("DX9J3SDK Samples Path"), NULL, &type, (BYTE*)strPath, &size ); if( ERROR_SUCCESS != result ) { result = RegQueryValueEx( hKey, _T("DX81SDK Samples Path"), NULL, &type, (BYTE*)strPath, &size ); if( ERROR_SUCCESS != result ) { result = RegQueryValueEx( hKey, _T("DX8SDK Samples Path"), NULL, &type, (BYTE*)strPath, &size ); if( ERROR_SUCCESS != result ) { RegCloseKey( hKey ); return strNull; } } } RegCloseKey( hKey ); lstrcat( strPath, _T("\\D3DIM\\Media\\") ); return strPath; } //----------------------------------------------------------------------------- // Name: D3DUtil_InitSurfaceDesc() // Desc: Helper function called to build a DDSURFACEDESC2 structure, // typically before calling CreateSurface() or GetSurfaceDesc() //----------------------------------------------------------------------------- VOID D3DUtil_InitSurfaceDesc( DDSURFACEDESC2& ddsd, DWORD dwFlags, DWORD dwCaps ) { ZeroMemory( &ddsd, sizeof(ddsd) ); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = dwFlags; ddsd.ddsCaps.dwCaps = dwCaps; ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT); } //----------------------------------------------------------------------------- // Name: D3DUtil_InitMaterial() // Desc: Helper function called to build a D3DMATERIAL7 structure //----------------------------------------------------------------------------- VOID D3DUtil_InitMaterial( D3DMATERIAL7& mtrl, FLOAT r, FLOAT g, FLOAT b, FLOAT a ) { ZeroMemory( &mtrl, sizeof(D3DMATERIAL7) ); mtrl.dcvDiffuse.r = mtrl.dcvAmbient.r = r; mtrl.dcvDiffuse.g = mtrl.dcvAmbient.g = g; mtrl.dcvDiffuse.b = mtrl.dcvAmbient.b = b; mtrl.dcvDiffuse.a = mtrl.dcvAmbient.a = a; } //----------------------------------------------------------------------------- // Name: D3DUtil_InitLight() // Desc: Initializes a D3DLIGHT7 structure //----------------------------------------------------------------------------- VOID D3DUtil_InitLight( D3DLIGHT7& light, D3DLIGHTTYPE ltType, FLOAT x, FLOAT y, FLOAT z ) { ZeroMemory( &light, sizeof(D3DLIGHT7) ); light.dltType = ltType; light.dcvDiffuse.r = 1.0f; light.dcvDiffuse.g = 1.0f; light.dcvDiffuse.b = 1.0f; light.dcvSpecular = light.dcvDiffuse; light.dvPosition.x = light.dvDirection.x = x; light.dvPosition.y = light.dvDirection.y = y; light.dvPosition.z = light.dvDirection.z = z; light.dvAttenuation0 = 1.0f; light.dvRange = D3DLIGHT_RANGE_MAX; } //----------------------------------------------------------------------------- // Name: D3DUtil_SetViewMatrix() // Desc: Given an eye point, a lookat point, and an up vector, this // function builds a 4x4 view matrix. //----------------------------------------------------------------------------- HRESULT D3DUtil_SetViewMatrix( D3DMATRIX& mat, D3DVECTOR& vFrom, D3DVECTOR& vAt, D3DVECTOR& vWorldUp ) { // Get the z basis vector, which points straight ahead. This is the // difference from the eyepoint to the lookat point. D3DVECTOR vView = vAt - vFrom; FLOAT fLength = Magnitude( vView ); if( fLength < 1e-6f ) return E_INVALIDARG; // Normalize the z basis vector vView /= fLength; // Get the dot product, and calculate the projection of the z basis // vector onto the up vector. The projection is the y basis vector. FLOAT fDotProduct = DotProduct( vWorldUp, vView ); D3DVECTOR vUp = vWorldUp - fDotProduct * vView; // If this vector has near-zero length because the input specified a // bogus up vector, let's try a default up vector if( 1e-6f > ( fLength = Magnitude( vUp ) ) ) { vUp = D3DVECTOR( 0.0f, 1.0f, 0.0f ) - vView.y * vView; // If we still have near-zero length, resort to a different axis. if( 1e-6f > ( fLength = Magnitude( vUp ) ) ) { vUp = D3DVECTOR( 0.0f, 0.0f, 1.0f ) - vView.z * vView; if( 1e-6f > ( fLength = Magnitude( vUp ) ) ) return E_INVALIDARG; } } // Normalize the y basis vector vUp /= fLength; // The x basis vector is found simply with the cross product of the y // and z basis vectors D3DVECTOR vRight = CrossProduct( vUp, vView ); // Start building the matrix. The first three rows contains the basis // vectors used to rotate the view to point at the lookat point D3DUtil_SetIdentityMatrix( mat ); mat._11 = vRight.x; mat._12 = vUp.x; mat._13 = vView.x; mat._21 = vRight.y; mat._22 = vUp.y; mat._23 = vView.y; mat._31 = vRight.z; mat._32 = vUp.z; mat._33 = vView.z; // Do the translation values (rotations are still about the eyepoint) mat._41 = - DotProduct( vFrom, vRight ); mat._42 = - DotProduct( vFrom, vUp ); mat._43 = - DotProduct( vFrom, vView ); return S_OK; } //----------------------------------------------------------------------------- // Name: D3DUtil_SetProjectionMatrix() // Desc: Sets the passed in 4x4 matrix to a perpsective projection matrix built // from the field-of-view (fov, in y), aspect ratio, near plane (D), // and far plane (F). Note that the projection matrix is normalized for // element [3][4] to be 1.0. This is performed so that W-based range fog // will work correctly. //----------------------------------------------------------------------------- HRESULT D3DUtil_SetProjectionMatrix( D3DMATRIX& mat, FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane, FLOAT fFarPlane ) { if( fabs(fFarPlane-fNearPlane) < 0.01f ) return E_INVALIDARG; if( fabs(sin(fFOV/2)) < 0.01f ) return E_INVALIDARG; FLOAT w = fAspect * ( cosf(fFOV/2)/sinf(fFOV/2) ); FLOAT h = 1.0f * ( cosf(fFOV/2)/sinf(fFOV/2) ); FLOAT Q = fFarPlane / ( fFarPlane - fNearPlane ); ZeroMemory( &mat, sizeof(D3DMATRIX) ); mat._11 = w; mat._22 = h; mat._33 = Q; mat._34 = 1.0f; mat._43 = -Q*fNearPlane; return S_OK; } //----------------------------------------------------------------------------- // Name: D3DUtil_SetRotateXMatrix() // Desc: Create Rotation matrix about X axis //----------------------------------------------------------------------------- VOID D3DUtil_SetRotateXMatrix( D3DMATRIX& mat, FLOAT fRads ) { D3DUtil_SetIdentityMatrix( mat ); mat._22 = cosf( fRads ); mat._23 = sinf( fRads ); mat._32 = -sinf( fRads ); mat._33 = cosf( fRads ); } //----------------------------------------------------------------------------- // Name: D3DUtil_SetRotateYMatrix() // Desc: Create Rotation matrix about Y axis //----------------------------------------------------------------------------- VOID D3DUtil_SetRotateYMatrix( D3DMATRIX& mat, FLOAT fRads ) { D3DUtil_SetIdentityMatrix( mat ); mat._11 = cosf( fRads ); mat._13 = -sinf( fRads ); mat._31 = sinf( fRads ); mat._33 = cosf( fRads ); } //----------------------------------------------------------------------------- // Name: D3DUtil_SetRotateZMatrix() // Desc: Create Rotation matrix about Z axis //----------------------------------------------------------------------------- VOID D3DUtil_SetRotateZMatrix( D3DMATRIX& mat, FLOAT fRads ) { D3DUtil_SetIdentityMatrix( mat ); mat._11 = cosf( fRads ); mat._12 = sinf( fRads ); mat._21 = -sinf( fRads ); mat._22 = cosf( fRads ); } //----------------------------------------------------------------------------- // Name: D3DUtil_SetRotationMatrix // Desc: Create a Rotation matrix about vector direction //----------------------------------------------------------------------------- VOID D3DUtil_SetRotationMatrix( D3DMATRIX& mat, D3DVECTOR& vDir, FLOAT fRads ) { FLOAT fCos = cosf( fRads ); FLOAT fSin = sinf( fRads ); D3DVECTOR v = Normalize( vDir ); mat._11 = ( v.x * v.x ) * ( 1.0f - fCos ) + fCos; mat._12 = ( v.x * v.y ) * ( 1.0f - fCos ) - (v.z * fSin); mat._13 = ( v.x * v.z ) * ( 1.0f - fCos ) + (v.y * fSin); mat._21 = ( v.y * v.x ) * ( 1.0f - fCos ) + (v.z * fSin); mat._22 = ( v.y * v.y ) * ( 1.0f - fCos ) + fCos ; mat._23 = ( v.y * v.z ) * ( 1.0f - fCos ) - (v.x * fSin); mat._31 = ( v.z * v.x ) * ( 1.0f - fCos ) - (v.y * fSin); mat._32 = ( v.z * v.y ) * ( 1.0f - fCos ) + (v.x * fSin); mat._33 = ( v.z * v.z ) * ( 1.0f - fCos ) + fCos; mat._14 = mat._24 = mat._34 = 0.0f; mat._41 = mat._42 = mat._43 = 0.0f; mat._44 = 1.0f; } //----------------------------------------------------------------------------- // Name: _DbgOut() // Desc: Outputs a message to the debug stream //----------------------------------------------------------------------------- HRESULT _DbgOut( CHAR* strFile, DWORD dwLine, HRESULT hr, TCHAR* strMsg ) { TCHAR buffer[256]; wsprintf( buffer, _T("%hs(%ld): "), strFile, dwLine ); OutputDebugString( buffer ); OutputDebugString( strMsg ); if( hr != (HRESULT) S_OK ) { wsprintf( buffer, _T("(hr=%08lx)\n"), hr ); OutputDebugString( buffer ); } OutputDebugString( _T("\n") ); return hr; }
[ "Gmagic10@26f92a05-6149-0410-981d-7deb1f891687" ]
[ [ [ 1, 305 ] ] ]
44666fe60152a1ed47c1e3db1c768fd6388db8ba
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Common/utility/RelativePoseResolver.cpp
6c2509af0957873da60827bf792a475eba671221
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,627
cpp
#include "RelativePoseResolver.h" #include <stdio.h> #include "../Math/Mat4x4d.h" RelativePoseResolver::RelativePoseResolver(int queueSize) : queue(queueSize,RelativePoseState()){ InitializeCriticalSection(&cs); } RelativePoseResolver::~RelativePoseResolver(){ DeleteCriticalSection(&cs); } void RelativePoseResolver::PushRelPose(const pose_rel_msg& msg){ int r,c; RelativePoseState rps; rps.vts = (double)msg.car_ts_secs + (double)msg.car_ts_ticks/10000.0; memcpy(rps.Rinit2veh,msg.Rinit2veh,sizeof(double)*16); // figure out the inverse for (r = 0; r < 3; r++){ for (c = 0; c < 3; c++){ //upper left 3x3 block is just transposed rps.Rveh2init[c*4+r] = msg.Rinit2veh[r][c]; } } //last row is [0, 0, 0, 1] rps.Rveh2init[12] = rps.Rveh2init[13] = rps.Rveh2init[14] = 0.0; rps.Rveh2init[15] = 1.0; //last col is -R'*d for (r = 0; r < 3; r++) { rps.Rveh2init[r*4+3] = 0.0; // init last column to 0 for (c = 0; c < 3; c++) rps.Rveh2init[r*4+3] -= msg.Rinit2veh[c][r] * msg.Rinit2veh[c][3]; } EnterCriticalSection(&cs); if(queue.n_meas()>0 && queue.newest().vts >= rps.vts){ printf("RelativePoseResolver WARNING: new relative pose is older than the previous newest state... flushing resolver (new: %lf, already have: %lf)\n",rps.vts,queue.newest().vts); queue.reset(); } queue.push(rps); LeaveCriticalSection(&cs); double test[16]; matmul4x4(rps.Rinit2veh,rps.Rveh2init,test); } bool RelativePoseResolver::GetTransform(double to, double from, double* xform){ EnterCriticalSection(&cs); if(to < queue.oldest().vts || to > queue.newest().vts){ printf("RelativePoseResolver WARNING: 'to' time (%lf) is outside of known xform bounds (%lf to %lf)\n",to,queue.oldest().vts,queue.newest().vts); LeaveCriticalSection(&cs); return false; } if(from < queue.oldest().vts || from > queue.newest().vts){ printf("RelativePoseResolver WARNING: 'from' time (%lf) is outside of known xform bounds (%lf to %lf)\n",from,queue.oldest().vts,queue.newest().vts); LeaveCriticalSection(&cs); return false; } // we've verified that both 'to' and 'from' timestamps are inside the known relative pose xform timespan // find the rp states right before "to" and "from" int toIndex=0, fromIndex=0; for(unsigned int i=0;i<queue.n_meas();i++){ if(queue[i].vts < to) toIndex = i; if(queue[i].vts < from) fromIndex = i; if(queue[i].vts > to && queue[i].vts > from) break; } // for now, directly use the closest known relative pose // in the future, might want to interpolate if(toIndex==fromIndex) eye4x4(xform); else matmul4x4(queue[toIndex].Rinit2veh,queue[fromIndex].Rveh2init,xform); LeaveCriticalSection(&cs); return true; } Transform3d RelativePoseResolver::GetTransform(double to, double from){ Transform3d ret; EnterCriticalSection(&cs); if(to < queue.oldest().vts || to > queue.newest().vts){ printf("RelativePoseResolver WARNING: 'to' time (%lf) is outside of known xform bounds (%lf to %lf)\n",to,queue.oldest().vts,queue.newest().vts); LeaveCriticalSection(&cs); return ret; } if(from < queue.oldest().vts || from > queue.newest().vts){ printf("RelativePoseResolver WARNING: 'from' time (%lf) is outside of known xform bounds (%lf to %lf)\n",from,queue.oldest().vts,queue.newest().vts); LeaveCriticalSection(&cs); return ret; } // we've verified that both 'to' and 'from' timestamps are inside the known relative pose xform timespan // find the rp states right before "to" and "from" int toIndex=0, fromIndex=0; for(unsigned int i=0;i<queue.n_meas();i++){ if(queue[i].vts < to) toIndex = i; if(queue[i].vts < from) fromIndex = i; if(queue[i].vts > to && queue[i].vts > from) break; } // interpolate to find the "to" Rinit2veh matrix double to_Rinit2veh[16]; double q = (to - queue[toIndex].vts)/(queue[toIndex+1].vts-queue[toIndex].vts); for(unsigned int i=0;i<16;i++){ to_Rinit2veh[i] = queue[toIndex].Rinit2veh[i] * (1.0-q) + queue[toIndex+1].Rinit2veh[i] * q; } // interpolate to find the "from" Rinit2veh matrix double from_Rveh2init[16]; q = (from - queue[fromIndex].vts)/(queue[fromIndex+1].vts-queue[fromIndex].vts); for(unsigned int i=0;i<16;i++){ from_Rveh2init[i] = queue[fromIndex].Rveh2init[i] * (1.0-q) + queue[fromIndex+1].Rveh2init[i] * q; } ret = to_Rinit2veh; ret = ret * from_Rveh2init; LeaveCriticalSection(&cs); return ret; } Transform3d RelativePoseResolver::GetInitToVeh(double vts,bool suppressWarning){ Transform3d ret; ret.valid = false; EnterCriticalSection(&cs); if(vts < queue.oldest().vts || vts > queue.newest().vts){ if(!suppressWarning) printf("RelativePoseResolver::GetInitToVeh WARNING: 'vts' time (%lf) is outside of known xform bounds (%lf to %lf)\n",vts,queue.oldest().vts,queue.newest().vts); LeaveCriticalSection(&cs); return ret; } // find the rp states right before "to" and "from" int vtsIndex=0; for(unsigned int i=0;i<queue.n_meas();i++){ if(queue[i].vts < vts) vtsIndex = i; else break; } // interpolate to find the "to" Rinit2veh matrix double q = (vts - queue[vtsIndex].vts)/(queue[vtsIndex+1].vts-queue[vtsIndex].vts); for(unsigned int i=0;i<16;i++){ ret.xform[i] = queue[vtsIndex].Rinit2veh[i] * (1.0-q) + queue[vtsIndex+1].Rinit2veh[i] * q; } LeaveCriticalSection(&cs); ret.valid = true; return ret; } Transform3d RelativePoseResolver::GetVehToInit(double vts,bool suppressWarning){ Transform3d ret; ret.valid = false; EnterCriticalSection(&cs); if(vts < queue.oldest().vts || vts > queue.newest().vts){ if(!suppressWarning) printf("RelativePoseResolver::GetVehToInit WARNING: 'vts' time (%lf) is outside of known xform bounds (%lf to %lf)\n",vts,queue.oldest().vts,queue.newest().vts); LeaveCriticalSection(&cs); return ret; } // find the rp states right before "to" and "from" int vtsIndex=0; for(unsigned int i=0;i<queue.n_meas();i++){ if(queue[i].vts < vts) vtsIndex = i; else break; } // interpolate to find the "to" Rinit2veh matrix double q = (vts - queue[vtsIndex].vts)/(queue[vtsIndex+1].vts-queue[vtsIndex].vts); for(unsigned int i=0;i<16;i++){ ret.xform[i] = queue[vtsIndex].Rveh2init[i] * (1.0-q) + queue[vtsIndex+1].Rveh2init[i] * q; } LeaveCriticalSection(&cs); ret.valid = true; return ret; }
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 196 ] ] ]
9dfb7171560820b1e7692a3582d9c173cc92ece3
6caf1a340711c6c818efc7075cc953b2f1387c04
/client/Options.cpp
f72469d3deac2e85671285fce079d23b1ddae699
[]
no_license
lbrucher/timelis
35c68061bea68cc31ce1c68e3adbc23cb7f930b1
0fa9f8f5ef28fe02ca620c441783a1ff3fc17bde
refs/heads/master
2021-01-01T18:18:37.988944
2011-08-18T19:39:19
2011-08-18T19:39:19
2,229,915
2
1
null
null
null
null
UTF-8
C++
false
false
1,346
cpp
// $Id: Options.cpp,v 1.1 2005/01/13 12:23:20 lbrucher Exp $ // #include "stdafx.h" #include "Options.h" #include "Timelis.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern CTimelisApp theApp; // //////////////////////////////////////////////////////////////////////////// // CString COptions::getReportTemplateDir() { return theApp.GetProfileString("Report", "TemplateDir", ""); } CString COptions::getReportDir() { return theApp.GetProfileString("Report", "ReportDir", ""); } CString COptions::getSyncWsdlUrl() { return theApp.GetProfileString("Synchronize", "WSDLURL", ""); } CString COptions::getSyncUsername() { return theApp.GetProfileString("Synchronize", "Username", ""); } // //////////////////////////////////////////////////////////////////////////// // void COptions::setReportTemplateDir( const CString& s ) { theApp.WriteProfileString("Report", "TemplateDir", s); } void COptions::setReportDir( const CString& s ) { theApp.WriteProfileString("Report", "ReportDir", s); } void COptions::setSyncWsdlUrl( const CString& s ) { theApp.WriteProfileString("Synchronize", "WSDLURL", s); } void COptions::setSyncUsername( const CString& s ) { theApp.WriteProfileString("Synchronize", "Username", s); }
[ [ [ 1, 61 ] ] ]
821b55925ff81ade167f802d756a6207c35e3a97
989aa92c9dab9a90373c8f28aa996c7714a758eb
/HydraIRC/include/dockingwindows/DWAutoHide.h
dcb4e787f2370808f07d9d5e52e3ed6eaf5f71b0
[]
no_license
john-peterson/hydrairc
5139ce002e2537d4bd8fbdcebfec6853168f23bc
f04b7f4abf0de0d2536aef93bd32bea5c4764445
refs/heads/master
2021-01-16T20:14:03.793977
2010-04-03T02:10:39
2010-04-03T02:10:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
45,741
h
// Copyright (c) 2002 // Sergey Klimov ([email protected]) // WTL Docking windows // // This code is provided "as is", with absolutely no warranty expressed // or implied. Any use is at your own risk. // // This code may be used in compiled form in any way you desire. This // file may be redistributed unmodified by any means PROVIDING it is // not sold for profit without the authors written consent, and // providing that this notice and the authors name is included. If // the source code in this file is used in any commercial application // then a simple email woulod be nice. #ifndef __WTL_DW__DWAUTOHIDE_H__ #define __WTL_DW__DWAUTOHIDE_H__ #pragma once #define DF_AUTO_HIDE_FEATURES #include <queue> #include <deque> #include "ssec.h" #include "DockMisc.h" #include "ExtDockingWindow.h" namespace dockwins{ typedef CDockingWindowTraits<COutlookLikeCaption, WS_CAPTION | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,WS_EX_TOOLWINDOW> COutlookLikeAutoHidePaneTraits; template <class TAutoHidePaneTraits,class TSplitterBar,/* DWORD TDockFrameStyle=0,*/ DWORD t_dwStyle = 0, DWORD t_dwExStyle = 0> struct CDockingFrameTraitsT : CWinTraits <t_dwStyle,t_dwExStyle> { typedef TSplitterBar CSplitterBar; typedef TAutoHidePaneTraits CAutoHidePaneTraits; }; typedef CDockingFrameTraitsT< COutlookLikeAutoHidePaneTraits,CSimpleSplitterBar<5>, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, WS_EX_APPWINDOW | WS_EX_WINDOWEDGE> CDockingFrameTraits; typedef CDockingFrameTraitsT<COutlookLikeAutoHidePaneTraits, CSimpleSplitterBarEx<6>, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,0> CDockingSiteTraits; struct IPinnedLabel { typedef CDockingSide CSide; enum { leftBorder=3, rightBorder=3, labelEdge=2, labelPadding=5, // padding between the labels captionPadding=3 // padding between border of the label and the lable caption }; class CPinnedWindow { public: CPinnedWindow() :m_hWnd(NULL),m_icon(0),m_txt(0),m_width(0) { } CPinnedWindow(const CPinnedWindow& ref) { this->operator=(ref); } ~CPinnedWindow() { delete [] m_txt; } CPinnedWindow& operator = (const CPinnedWindow& ref) { m_hWnd=ref.m_hWnd; m_icon=ref.m_icon; m_width=ref.m_width; m_txt=ref.m_txt; ref.m_txt=0; return *this; } int Assign(HWND hWnd,unsigned long width) { assert(::IsWindow(hWnd)); m_hWnd=hWnd; m_width=width; m_icon=reinterpret_cast<HICON>(::SendMessage(hWnd, WM_GETICON, FALSE, 0)); if(m_icon == NULL) m_icon = reinterpret_cast<HICON>(::GetClassLong(hWnd, GCL_HICONSM)); delete [] m_txt; int len=0; try { len=::GetWindowTextLength(hWnd)+1; m_txt=new TCHAR[len]; ::GetWindowText(hWnd,m_txt,len); } catch(std::bad_alloc& /*e*/) { m_txt=0; } return len; } HWND Wnd() const { return m_hWnd; } HICON Icon() const { return m_icon; } LPCTSTR Text() const { return m_txt; } unsigned long Width() const { return m_width; } void Width(unsigned long width) { m_width=width; } void PrepareForDock(HDOCKBAR hBar,bool bHorizontal) { ::ShowWindow(m_hWnd,SW_HIDE); DWORD style = ::GetWindowLong(m_hWnd,GWL_STYLE); DWORD newStyle = style&(~(WS_POPUP | WS_CAPTION))|WS_CHILD; ::SetWindowLong(m_hWnd, GWL_STYLE, newStyle); ::SetParent(m_hWnd,hBar); ::SendMessage(m_hWnd,WM_NCACTIVATE,TRUE,NULL); ::SendMessage(m_hWnd,WMDF_NDOCKSTATECHANGED, MAKEWPARAM(TRUE,bHorizontal), reinterpret_cast<LPARAM>(hBar)); } void PrepareForUndock(HDOCKBAR hBar) { ::ShowWindow(m_hWnd,SW_HIDE); DWORD style = ::GetWindowLong(m_hWnd,GWL_STYLE); DWORD newStyle = style&(~WS_CHILD) | WS_POPUP | WS_CAPTION; ::SetWindowLong(m_hWnd, GWL_STYLE, newStyle); ::SetParent(m_hWnd,NULL); ::SendMessage(m_hWnd,WMDF_NDOCKSTATECHANGED, FALSE, reinterpret_cast<LPARAM>(hBar)); } void DrawLabel(CDC& dc,const CRect& rc,const CSide& side) const { CRect rcOutput(rc); rcOutput.DeflateRect(captionPadding,captionPadding); if(m_icon!=NULL) { CDWSettings settings; CSize szIcon(settings.CXMinIcon(),settings.CYMinIcon()); if(side.IsHorizontal()) { if(rc.Width()>szIcon.cx+2*captionPadding) { POINT pt={rcOutput.left,rc.top+(rc.Height()-szIcon.cx)/2}; rcOutput.left+=szIcon.cx+captionPadding; dc.DrawIconEx(pt,m_icon,szIcon); } } else { if(rc.Height()>szIcon.cy+2*captionPadding) { POINT pt={rc.left+(rc.Width()-szIcon.cy)/2,rcOutput.top}; rcOutput.top+=szIcon.cy+captionPadding; dc.DrawIconEx(pt,m_icon,szIcon); } } } DrawEllipsisText(dc,m_txt,_tcslen(m_txt),&rcOutput,side.IsHorizontal()); } protected: unsigned long m_width; HWND m_hWnd; HICON m_icon; mutable LPTSTR m_txt; }; class CCmp { public: CCmp(HWND hWnd):m_hWnd(hWnd) { } bool operator() (const IPinnedLabel* ptr) const { return ptr->IsOwner(m_hWnd); } protected: HWND m_hWnd; }; virtual ~IPinnedLabel(){} virtual IPinnedLabel* Remove(HWND hWnd,HDOCKBAR hBar)=0; virtual bool UnPin(HWND hWnd,HDOCKBAR hBar,DFDOCKPOS* pHdr)=0; virtual long Width() const=0; virtual void Width(long width)=0; virtual long DesiredWidth(CDC& dc) const=0; virtual bool GetDockingPosition(DFDOCKPOS* pHdr) const=0; virtual CPinnedWindow* ActivePinnedWindow()=0; virtual CPinnedWindow* FromPoint(long x,bool bActivate)=0; virtual bool IsOwner(HWND hWnd) const=0; virtual void Draw(CDC& dc,const CRect& rc,const CSide& side) const=0; }; class CSinglePinnedLabel : public IPinnedLabel { public: CSinglePinnedLabel(DFPINUP* pHdr,bool bHorizontal) :m_width(0) { assert( (pHdr->n==0) || (pHdr->n==1) ); m_wnd.Assign(pHdr->hdr.hWnd,pHdr->nWidth); m_wnd.PrepareForDock(pHdr->hdr.hBar,bHorizontal); } CSinglePinnedLabel(const CPinnedWindow& wnd) :m_wnd(wnd),m_width(0) { } virtual IPinnedLabel* Remove(HWND hWnd,HDOCKBAR hBar) { assert(IsOwner(hWnd)); m_wnd.PrepareForUndock(hBar); return 0; } virtual bool UnPin(HWND hWnd,HDOCKBAR hBar,DFDOCKPOS* pHdr) { GetDockingPosition(pHdr); bool bRes=(Remove(hWnd,hBar)==0); if(bRes) { pHdr->hdr.code=DC_SETDOCKPOSITION; ::SendMessage(pHdr->hdr.hBar,WMDF_DOCK,NULL,reinterpret_cast<LPARAM>(pHdr)); } return bRes; } virtual long Width() const { return m_width; } virtual void Width(long width) { m_width=width; } virtual long DesiredWidth(CDC& dc) const { SIZE sz; LPCTSTR text=m_wnd.Text(); bool bRes=(GetTextExtentPoint32(dc, text,_tcslen(text),&sz)!=FALSE); assert(bRes); unsigned long width=sz.cx+2*captionPadding; if(m_wnd.Icon()!=NULL) { CDWSettings settings; width+=settings.CXMinIcon()+captionPadding; } bRes; return width; } virtual CPinnedWindow* ActivePinnedWindow() { return &m_wnd; } virtual CPinnedWindow* FromPoint(long x,bool /*bActivate*/) { assert(x>=0 && x<Width() ); return ActivePinnedWindow(); } virtual void Draw(CDC& dc,const CRect& rc,const CSide& side) const { dc.Rectangle(&rc); m_wnd.DrawLabel(dc,rc,side); } virtual bool IsOwner(HWND hWnd) const { return m_wnd.Wnd()==hWnd; } virtual bool GetDockingPosition(DFDOCKPOS* pHdr) const { assert(pHdr->hdr.hWnd==m_wnd.Wnd()); pHdr->nBar=0; pHdr->nWidth=m_wnd.Width(); pHdr->nHeight=1; pHdr->nIndex=0; pHdr->fPctPos=0; return true; } protected: CPinnedWindow m_wnd; long m_width; }; class CMultyPinnedLabel : public IPinnedLabel { enum {npos=ULONG_MAX/*std::numeric_limits<unsigned long>::max()*/}; public: CMultyPinnedLabel(DFPINUP* pHdr,bool bHorizontal) :m_width(0) { assert(pHdr->n>1); m_n=pHdr->n; m_tabs=new CPinnedWindow[m_n]; int maxLen=0; for(unsigned long i=0;i<m_n;i++) { int len=m_tabs[i].Assign(pHdr->phWnds[i],pHdr->nWidth); m_tabs[i].PrepareForDock(pHdr->hdr.hBar,bHorizontal); if(len>maxLen) { maxLen=len; m_longestTextTab=i; } if(pHdr->phWnds[i]==pHdr->hdr.hWnd) m_activeTab=i; } } ~CMultyPinnedLabel() { delete [] m_tabs; } virtual bool UnPin(HWND hWnd,HDOCKBAR hBar,DFDOCKPOS* pHdr) { assert(pHdr->hdr.hWnd==hWnd); GetDockingPosition(pHdr); pHdr->hdr.hWnd=m_tabs[0].Wnd(); pHdr->hdr.code=DC_SETDOCKPOSITION; m_tabs[0].PrepareForUndock(hBar); ::SendMessage(pHdr->hdr.hBar,WMDF_DOCK,NULL,reinterpret_cast<LPARAM>(pHdr)); pHdr->hdr.hBar=pHdr->hdr.hWnd; for(unsigned long i=1;i<m_n;i++) { pHdr->nIndex=i; pHdr->hdr.hWnd=m_tabs[i].Wnd(); m_tabs[i].PrepareForUndock(hBar); ::SendMessage(pHdr->hdr.hBar,WMDF_DOCK,NULL,reinterpret_cast<LPARAM>(pHdr)); } pHdr->hdr.code=DC_ACTIVATE; pHdr->hdr.hWnd=m_tabs[m_activeTab].Wnd(); ::SendMessage(pHdr->hdr.hBar,WMDF_DOCK,NULL,reinterpret_cast<LPARAM>(&(pHdr->hdr))); return true; } virtual IPinnedLabel* Remove(HWND hWnd,HDOCKBAR hBar) { assert(IsOwner(hWnd)); IPinnedLabel* ptr=this; try { if(m_n==2) { unsigned long i=(m_tabs[0].Wnd()!=hWnd); ptr=new CSinglePinnedLabel(m_tabs[i]); m_tabs[!i].PrepareForUndock(hBar); } else { CPinnedWindow* ptr=m_tabs; m_tabs=new CPinnedWindow[m_n-1]; unsigned long j=0; unsigned int maxLen=0; for(unsigned long i=0;i<m_n;i++) { if(ptr[i].Wnd()!=hWnd) { if(maxLen<_tcslen(ptr[i].Text())) m_longestTextTab=j; m_tabs[j++]=ptr[i]; } else ptr[i].PrepareForUndock(hBar); } if(m_activeTab==--m_n) --m_activeTab; delete [] ptr; } } catch(std::bad_alloc& /*e*/) { } return ptr; } unsigned long Locate(HWND hWnd) const { for(unsigned long i=0;i<m_n;i++) if(m_tabs[i].Wnd()==hWnd) return i; return (unsigned long)npos; } virtual bool IsOwner(HWND hWnd) const { return (Locate(hWnd)!=npos); } virtual long Width() const { return m_width; } virtual void Width(long width) { m_width=width; if(m_width<m_passiveTabWidth*long(m_n)) { if(m_width<long(m_n)) m_passiveTabWidth=0; else m_passiveTabWidth=m_width/m_n; } } virtual long DesiredWidth(CDC& dc) const { SIZE sz; LPCTSTR text=m_tabs[m_longestTextTab].Text(); bool bRes=(GetTextExtentPoint32(dc, text,_tcslen(text),&sz)!=FALSE); assert(bRes); bRes; long width=sz.cx+2*captionPadding; CDWSettings settings; width+=settings.CXMinIcon()+captionPadding; m_passiveTabWidth=settings.CXMinIcon()+2*captionPadding; width+=m_passiveTabWidth*(m_n-1); return width; } virtual CPinnedWindow* ActivePinnedWindow() { return m_tabs+m_activeTab; } virtual CPinnedWindow* FromPoint(long x,bool bActivate) { assert(x>=0 && x<Width() ); unsigned long i=m_activeTab; if(x<long(m_activeTab)*m_passiveTabWidth) i=x/m_passiveTabWidth; else { long width=Width()-(m_n-m_activeTab-1)*m_passiveTabWidth; if( width<x ) i+=(x-width)/m_passiveTabWidth+1; } assert(m_activeTab<m_n); if(bActivate) m_activeTab=i; return m_tabs+i; } void DrawPassiveTab(unsigned long i,CDC& dc,const CRect& rc,const CSide& side) const { CRect rcOutput(rc); rcOutput.DeflateRect(captionPadding,captionPadding); HICON icon=m_tabs[i].Icon(); CDWSettings settings; CSize sz(settings.CXMinIcon(),settings.CYMinIcon()); if( icon!=0 && (sz.cx<=(rc.Width()-2*captionPadding)) && (sz.cy<=(rc.Height()-2*captionPadding)) ) { POINT pt={rcOutput.left,rcOutput.top}; dc.DrawIconEx(pt,icon,sz); } else { LPCTSTR text=m_tabs[i].Text(); DrawEllipsisText(dc,text,_tcslen(text),&rcOutput,side.IsHorizontal()); } } void DrawActiveTab(unsigned long i,CDC& dc,const CRect& rc,const CSide& side) const { m_tabs[i].DrawLabel(dc,rc,side.IsHorizontal()); } virtual void Draw(CDC& dc,const CRect& rc,const CSide& side) const { CRect rcOutput(rc); dc.Rectangle(&rcOutput); long* pLeft; long* pRight; long* px; long* py; if(side.IsHorizontal()) { pLeft=&rcOutput.left; pRight=&rcOutput.right; px=&rcOutput.left; py=&rcOutput.bottom; } else { pLeft=&rcOutput.top; pRight=&rcOutput.bottom; px=&rcOutput.right; py=&rcOutput.top; } for(unsigned long i=0;i<m_n;i++) { if(i==m_activeTab) { *pRight=*pLeft+m_width-m_passiveTabWidth*(m_n-1); assert(*pRight<=(side.IsHorizontal() ? rcOutput.right : rcOutput.bottom)); DrawActiveTab(i,dc,rcOutput,side.IsHorizontal()); } else { *pRight=*pLeft+m_passiveTabWidth; assert(*pRight<=(side.IsHorizontal() ? rcOutput.right : rcOutput.bottom)); DrawPassiveTab(i,dc,rcOutput,side); } dc.MoveTo(rcOutput.left, rcOutput.top); dc.LineTo(*px,*py); *pLeft=*pRight; } } virtual bool GetDockingPosition(DFDOCKPOS* pHdr) const { unsigned long i=Locate(pHdr->hdr.hWnd); bool bRes=(i!=npos); if(bRes) { if(m_activeTab==i) pHdr->dwDockSide|=CDockingSide::sActive; pHdr->nBar=0; pHdr->nWidth=m_tabs[i].Width(); pHdr->nHeight=1; pHdr->nIndex=i; pHdr->fPctPos=0; } return bRes; } protected: unsigned long m_n; CPinnedWindow* m_tabs; long m_width; mutable long m_passiveTabWidth; unsigned long m_activeTab; unsigned long m_longestTextTab; }; class CAutoHideBar: protected CRect { typedef CRect baseClass; protected: typedef IPinnedLabel* CPinnedLabelPtr; typedef std::deque<CPinnedLabelPtr> CBunch; typedef CBunch::const_iterator const_iterator; public: typedef IPinnedLabel::CSide CSide; CAutoHideBar() { SetRectEmpty(); } ~CAutoHideBar() { /* For some reason this didn't correctly delete and destroy the CPinnedWindow objects (especially the m_txt member variable). So let's do it the old fashioned way.. void (*pDelete)(void *)=&(operator delete); std::for_each(m_bunch.begin(), m_bunch.end(), pDelete);*/ for (CBunch::iterator i=m_bunch.begin(); i != m_bunch.end(); ++i) delete (*i); } operator const CRect& () const { return *this; } bool IsPtIn(const CPoint& pt) const { return (PtInRect(pt)!=FALSE); } const CSide& Orientation() const { return m_side; } bool IsVisible() const { return !m_bunch.empty(); } bool IsHorizontal() const { return Orientation().IsHorizontal(); } bool IsTop() const { return Orientation().IsTop(); } void Initialize(CSide side) { m_side=side; } bool CalculateRect(CDC& dc,CRect& rc,long width,long leftPadding,long rightPadding) { if(IsVisible()) { CopyRect(rc); if(IsHorizontal()) { if(IsTop()) rc.top=bottom=top+width; else rc.bottom=top=bottom-width; left+=leftPadding; right-=rightPadding; } else { if(IsTop()) rc.left=right=left+width; else rc.right=left=right-width; top+=leftPadding; bottom-=rightPadding; } UpdateLayout(dc); } return true; } void UpdateLayout(CDC& dc) const { bool bHorizontal=IsHorizontal(); HFONT hPrevFont; long availableWidth; // long availableWidth=bHorizontal ? Width() : Height(); CDWSettings settings; if(bHorizontal) { availableWidth=Width(); hPrevFont=dc.SelectFont(settings.HSysFont()); } else { availableWidth=Height(); hPrevFont=dc.SelectFont(settings.VSysFont()); } availableWidth+=IPinnedLabel::labelPadding-IPinnedLabel::leftBorder-IPinnedLabel::rightBorder; typedef std::priority_queue<long,std::deque<long>,std::greater<long> > CQWidth; CQWidth widths; long width = 0; for(const_iterator i=m_bunch.begin();i!=m_bunch.end();++i) { int labelWidth=(*i)->DesiredWidth(dc); (*i)->Width(labelWidth); labelWidth+=IPinnedLabel::labelPadding; widths.push(labelWidth); width+=labelWidth; } long averageLableWidth=width; long n=m_bunch.size(); if(n>0 && (width>availableWidth) ) { width=availableWidth; long itemsLeft=n; averageLableWidth=width/itemsLeft; long diffrence=width%itemsLeft; while(!widths.empty()) { long itemWidth=widths.top(); long diff=averageLableWidth-itemWidth; if(diff>0) { diffrence+=diff; --itemsLeft; widths.pop(); } else { if(diffrence<itemsLeft) break; averageLableWidth+=diffrence/itemsLeft; diffrence=diffrence%itemsLeft; } } averageLableWidth-=IPinnedLabel::labelPadding; if(averageLableWidth<IPinnedLabel::labelPadding) averageLableWidth=0; for(const_iterator i=m_bunch.begin();i!=m_bunch.end();++i) { long labelWidth=(*i)->Width(); if( labelWidth>averageLableWidth ) labelWidth=averageLableWidth; (*i)->Width(labelWidth); } } dc.SelectFont(hPrevFont); } void Draw(CDC& dc,bool bEraseBackground=true) { if(IsVisible()) { if(bEraseBackground) { CDWSettings settings; CBrush bgrBrush; bgrBrush.CreateSolidBrush(settings.CoolCtrlBackgroundColor()); HBRUSH hOldBrush=dc.SelectBrush(bgrBrush); dc.PatBlt(left, top, Width(), Height(), PATCOPY); dc.SelectBrush(hOldBrush); } CDWSettings settings; CPen pen; pen.CreatePen(PS_SOLID,1,::GetSysColor(COLOR_BTNSHADOW)); HPEN hOldPen=dc.SelectPen(pen); CPen penEraser; penEraser.CreatePen(PS_SOLID,1,::GetSysColor(COLOR_BTNFACE)); COLORREF oldColor=dc.SetTextColor(settings.AutoHideBarTextColor()); CBrush brush; brush.CreateSolidBrush(::GetSysColor(COLOR_BTNFACE)); HBRUSH hOldBrush=dc.SelectBrush(brush); int oldBkMode=dc.SetBkMode(TRANSPARENT); HFONT hOldFont; long* pLeft; long* pRight; CRect rcLabel(this); long *xELine,*yELine; long tmp; if(IsHorizontal()) { xELine=&rcLabel.right; if(IsTop()) { rcLabel.bottom-=IPinnedLabel::labelEdge; yELine=&rcLabel.top; } else { rcLabel.top+=IPinnedLabel::labelEdge; tmp=rcLabel.bottom-1; yELine=&tmp; } hOldFont=dc.SelectFont(settings.HSysFont()); pLeft=&rcLabel.left; pRight=&rcLabel.right; } else { yELine=&rcLabel.bottom; if(IsTop()) { rcLabel.right-=IPinnedLabel::labelEdge; xELine=&rcLabel.left; } else { rcLabel.left+=IPinnedLabel::labelEdge; tmp=rcLabel.right-1; xELine=&tmp; } hOldFont=dc.SelectFont(settings.VSysFont()); pLeft=&rcLabel.top; pRight=&rcLabel.bottom; } *pLeft+=IPinnedLabel::leftBorder; *pRight-=IPinnedLabel::rightBorder; long minSize=m_bunch.size()*IPinnedLabel::labelPadding-IPinnedLabel::labelPadding; if(minSize<(*pRight-*pLeft)) { *pRight=*pLeft+1; CPoint ptELine; for(const_iterator i=m_bunch.begin();i!=m_bunch.end();++i) { ptELine.x=*xELine; ptELine.y=*yELine; *pRight=*pLeft+(*i)->Width(); assert( m_side.IsHorizontal() ? *pRight<=right : *pRight<=bottom); (*i)->Draw(dc,rcLabel,m_side); *pLeft=*pRight+IPinnedLabel::labelPadding; --*pRight; HPEN hPrevPen=dc.SelectPen(penEraser); dc.MoveTo(ptELine); dc.LineTo(*xELine,*yELine); dc.SelectPen(hPrevPen); *pRight=*pLeft+1; assert( m_side.IsHorizontal() ? (*pLeft>=left && (*pLeft<=right+IPinnedLabel::labelPadding) ) : (*pLeft>=top && (*pLeft<=bottom+IPinnedLabel::labelPadding) ) ); } } dc.SelectFont(hOldFont); dc.SelectPen(hOldPen); dc.SetTextColor(oldColor); dc.SelectBrush(hOldBrush); dc.SetBkMode(oldBkMode); } } IPinnedLabel::CPinnedWindow* MouseEnter(const CPoint& pt,bool bActivate=false) const { IPinnedLabel::CPinnedWindow* ptr=0; if(IsVisible() && IsPtIn(pt)) { int x; int vRight; if(IsHorizontal()) { x=pt.x; vRight=left; } else { x=pt.y; vRight=top; } for(const_iterator i=m_bunch.begin();i!=m_bunch.end();++i) { unsigned long vLeft=vRight; vRight+=(*i)->Width(); if(vRight>x) { ptr=(*i)->FromPoint(x-vLeft,bActivate); break; } vRight+=IPinnedLabel::labelPadding; if(vRight>x) break; } } return ptr; } CPinnedLabelPtr Insert(DFPINUP* pHdr) { assert(m_side.Side()==CSide(pHdr->dwDockSide).Side()); CPinnedLabelPtr ptr=0; try{ if(pHdr->n>1) ptr=new CMultyPinnedLabel(pHdr,IsHorizontal()); else ptr=new CSinglePinnedLabel(pHdr,IsHorizontal()); m_bunch.push_back(ptr); } catch(std::bad_alloc& /*e*/) { } return ptr; } bool Remove(HWND hWnd,HDOCKBAR hBar,DFDOCKPOS* pHdr) { CBunch::iterator i=std::find_if(m_bunch.begin(),m_bunch.end(), IPinnedLabel::CCmp(hWnd)); bool bRes=(i!=m_bunch.end()); if(bRes) { CPinnedLabelPtr ptr=*i; if(pHdr==0) (*i)=ptr->Remove(hWnd,hBar); else { pHdr->dwDockSide=m_side.Side() | CDockingSide::sSingle | CSide::sPinned; ptr->UnPin(hWnd,hBar,pHdr); (*i)=0; } if((*i)!=ptr) delete ptr; if((*i)==0) m_bunch.erase(i); if(!IsVisible()) SetRectEmpty(); } return bRes; } bool GetDockingPosition(DFDOCKPOS* pHdr) const { CBunch::const_iterator i=std::find_if(m_bunch.begin(),m_bunch.end(), IPinnedLabel::CCmp(pHdr->hdr.hWnd)); bool bRes=(i!=m_bunch.end()); if(bRes) { pHdr->dwDockSide=m_side.Side() | CDockingSide::sSingle | CSide::sPinned; (*i)->GetDockingPosition(pHdr); pHdr->nBar=std::distance(m_bunch.begin(),i); } return bRes; } protected: CSide m_side; CBunch m_bunch; }; #define HTSPLITTERH HTLEFT #define HTSPLITTERV HTTOP template <class T, class TBase = CWindow, class TAutoHidePaneTraits = COutlookLikeAutoHidePaneTraits> class ATL_NO_VTABLE CAutoHidePaneImpl : public CWindowImpl< T, TBase, TAutoHidePaneTraits > { typedef CWindowImpl< T, TBase, TAutoHidePaneTraits > baseClass; typedef CAutoHidePaneImpl< T, TBase, TAutoHidePaneTraits > thisClass; protected: typedef typename TAutoHidePaneTraits::CCaption CCaption; typedef typename CAutoHideBar::CSide CSide; struct CSplitterBar : CSimpleSplitterBarEx<> { CSplitterBar(bool bHorizontal=true):CSimpleSplitterBarEx<>(bHorizontal) { } void CalculateRect(CRect& rc,DWORD side) { CopyRect(rc); switch(side) { case CSide::sTop: rc.bottom=top=bottom-GetThickness(); break; case CSide::sBottom: rc.top=bottom=top+GetThickness(); break; case CSide::sRight: rc.left=right=left+GetThickness(); break; case CSide::sLeft: rc.right=left=right-GetThickness(); break; }; } }; public: CAutoHidePaneImpl() { m_caption.SetPinButtonState(CPinIcons::sUnPinned/*CCaption::PinButtonStates::sPinned*/); } protected: CSide Orientation() const { return m_side; } void Orientation(const CSide& side) { m_side=side; m_splitter.SetOrientation(IsHorizontal()); m_caption.SetOrientation(IsHorizontal()); } bool IsHorizontal() const { return m_side.IsHorizontal(); } bool IsTop() const { return m_side.IsTop(); } public: void GetMinMaxInfo(LPMINMAXINFO pMinMaxInfo) const { pMinMaxInfo->ptMinTrackSize.x=0; pMinMaxInfo->ptMinTrackSize.y=0; } LRESULT NcHitTest(const CPoint& pt) { LRESULT lRes=HTNOWHERE; if(m_splitter.PtInRect(pt)) lRes=(IsHorizontal()) ? HTSPLITTERV : HTSPLITTERH; else { lRes=m_caption.HitTest(pt); if(lRes==HTNOWHERE) lRes=HTCLIENT; else { if(GetCapture()==NULL) m_caption.HotTrack(m_hWnd,lRes); } } return lRes; } void NcCalcSize(CRect* pRc) { m_splitter.CalculateRect(*pRc,m_side.Side()); DWORD style = GetWindowLong(GWL_STYLE); if((style&WS_CAPTION)==0) m_caption.SetRectEmpty(); else m_caption.CalculateRect(*pRc,true); } void NcDraw(CDC& dc) { DWORD style = GetWindowLong(GWL_STYLE); if((style&WS_CAPTION)!=0) m_caption.Draw(m_hWnd,dc); m_splitter.Draw(dc); } bool CloseBtnPress() { PostMessage(WM_CLOSE); return false; } bool PinBtnPress(bool bVisualize=true) { return true; } void StartResizing(const CPoint& pt) { assert(false); } bool OnClosing() { return false; } bool AnimateWindow(long time,bool bShow) { const int n=10; CRect rc; GetWindowRect(&rc); CWindow parent(GetParent()); if(parent.m_hWnd!=NULL) parent.ScreenToClient(&rc); long* ppoint; long step; CRect rcInvalidate(rc); long* pipoint; if(m_side.IsHorizontal()) { step=rc.Height()/n; if(m_side.IsTop()) { ppoint=&rc.bottom; pipoint=&rc.bottom; rcInvalidate.bottom=rcInvalidate.top; } else { ppoint=&rc.top; pipoint=&rc.top; rcInvalidate.top=rcInvalidate.bottom; step=-step; } } else { step=rc.Width()/n; if(m_side.IsTop()) { ppoint=&rc.right; pipoint=&rc.right; rcInvalidate.left=rcInvalidate.right; } else { ppoint=&rc.left; pipoint=&rc.left; rcInvalidate.right=rcInvalidate.left; step=-step; } } if(!bShow) step=-step; else { parent.RedrawWindow(&rc,NULL,RDW_INVALIDATE | RDW_UPDATENOW); *ppoint-=step*n; SetWindowPos(HWND_TOP,&rc,SWP_FRAMECHANGED|SWP_SHOWWINDOW); } bool bRes=true; for(int i=0;i<n;i++) { *ppoint+=step; bRes=(SetWindowPos(HWND_TOP,&rc,NULL)!=FALSE); if(!bShow) { *pipoint+=step; parent.RedrawWindow(&rcInvalidate,NULL,RDW_INVALIDATE | RDW_UPDATENOW); } else { CRect rcInvalidateClient(rc); parent.MapWindowPoints(m_hWnd,&rcInvalidateClient); RedrawWindow(&rcInvalidateClient,NULL,RDW_INVALIDATE | RDW_UPDATENOW); } Sleep(time/n); } return bRes; } protected: BEGIN_MSG_MAP(thisClass) MESSAGE_HANDLER(WM_GETMINMAXINFO,OnGetMinMaxInfo) MESSAGE_HANDLER(WM_NCCALCSIZE, OnNcCalcSize) MESSAGE_HANDLER(WM_NCACTIVATE, OnNcActivate) MESSAGE_HANDLER(WM_NCHITTEST,OnNcHitTest) MESSAGE_HANDLER(WM_NCPAINT,OnNcPaint) MESSAGE_HANDLER(WM_SETTEXT,OnCaptionChange) MESSAGE_HANDLER(WM_SETICON,OnCaptionChange) MESSAGE_HANDLER(WM_NCLBUTTONDOWN, OnNcLButtonDown) MESSAGE_HANDLER(WM_NCLBUTTONUP,OnNcLButtonUp) MESSAGE_HANDLER(WM_NCLBUTTONDBLCLK,OnNcLButtonDblClk) MESSAGE_HANDLER(WM_CLOSE, OnClose) MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange) MESSAGE_HANDLER(WM_SYSCOLORCHANGE, OnSysColorChange) END_MSG_MAP() LRESULT OnGetMinMaxInfo(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/) { T* pThis=static_cast<T*>(this); LRESULT lRes=pThis->DefWindowProc(uMsg,wParam,lParam); pThis->GetMinMaxInfo(reinterpret_cast<LPMINMAXINFO>(lParam)); return lRes; } LRESULT OnNcActivate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { bHandled=IsWindowEnabled(); return TRUE; } LRESULT OnNcCalcSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/) { T* pThis=static_cast<T*>(this); CRect* pRc=reinterpret_cast<CRect*>(lParam); CPoint ptTop(pRc->TopLeft()); (*pRc)-=ptTop; pThis->NcCalcSize(pRc); (*pRc)+=ptTop; return NULL; } LRESULT OnNcHitTest(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/) { CPoint pt(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); T* pThis=static_cast<T*>(this); CRect rcWnd; GetWindowRect(&rcWnd); pt.x-=rcWnd.TopLeft().x; pt.y-=rcWnd.TopLeft().y; return pThis->NcHitTest(pt); } //OnSetIcon //OnSetText LRESULT OnCaptionChange(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/) { // LockWindowUpdate(); DWORD style = ::GetWindowLong(m_hWnd,GWL_STYLE); ::SetWindowLong(m_hWnd, GWL_STYLE, style&(~WS_CAPTION)); LRESULT lRes=DefWindowProc(uMsg,wParam,lParam); ::SetWindowLong(m_hWnd, GWL_STYLE, style); T* pThis=static_cast<T*>(this); pThis->SetWindowPos(NULL,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); // CWindowDC dc(m_hWnd); // pThis->NcDraw(dc); // LockWindowUpdate(FALSE); return lRes; } LRESULT OnNcPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { CWindowDC dc(m_hWnd); T* pThis=static_cast<T*>(this); pThis->NcDraw(dc); return NULL; } LRESULT OnNcLButtonDown(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/) { if( (wParam==HTSPLITTERH) || (wParam==HTSPLITTERV) ) static_cast<T*>(this)->StartResizing(CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); else m_caption.OnAction(m_hWnd,wParam); return 0; } LRESULT OnNcLButtonUp(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled) { T* pThis=static_cast<T*>(this); HWND hWndFocus = ::GetFocus(); switch(wParam) { case HTCLOSE: bHandled=pThis->CloseBtnPress(); break; case HTPIN: bHandled=pThis->PinBtnPress(); break; default: bHandled=FALSE; } if(hWndFocus != ::GetFocus()) { if(::IsWindow(hWndFocus) && ::IsWindowVisible(hWndFocus)) { ::SetFocus(hWndFocus); } else { ::SetFocus(this->GetTopLevelParent()); } } return 0; } LRESULT OnNcLButtonDblClk(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { return 0; } LRESULT OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM/* lParam*/, BOOL& bHandled) { T* pThis=reinterpret_cast<T*>(this); bHandled=pThis->OnClosing(); return 0; } LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { // Note: We can depend on CDWSettings already being updated // since we will always be a descendant of the main frame m_caption.UpdateMetrics(); T* pThis=static_cast<T*>(this); pThis->SetWindowPos(NULL,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); bHandled = FALSE; return 1; } LRESULT OnSysColorChange(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { // Note: We can depend on CDWSettings already being updated // since we will always be a descendant of the main frame m_caption.UpdateMetrics(); T* pThis=static_cast<T*>(this); pThis->SetWindowPos(NULL,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); bHandled = FALSE; return 1; } protected: CCaption m_caption; CSplitterBar m_splitter; CSide m_side; }; template <class TAutoHidePaneTraits = COutlookLikeAutoHidePaneTraits> class CAutoHideManager : public CAutoHidePaneImpl<CAutoHideManager<TAutoHidePaneTraits>,CWindow,TAutoHidePaneTraits> { typedef CAutoHidePaneImpl<CAutoHideManager<TAutoHidePaneTraits>,CWindow,TAutoHidePaneTraits> baseClass; typedef CAutoHideManager<TAutoHidePaneTraits> thisClass; protected: typedef CAutoHideBar::CSide CSide; enum{ tmID=1,tmTimeout=1300}; enum{ animateTimeout=100}; enum{ hoverTimeout=50/*HOVER_DEFAULT*/}; enum{ barsCount=4 }; class CSizeTrackerFull : public IDDTracker { protected: typedef ssec::bounds_type<long> CBounds; public: bool IsHorizontal() const { return m_side.IsHorizontal(); } bool IsTop() const { return m_side.IsTop(); } CSizeTrackerFull(HWND hWnd,CPoint pt,const CSide& side,long minSize,const CRect& rcBound) : m_wnd(hWnd),m_side(side) { m_rc.SetRectEmpty(); m_wnd.GetWindowRect(&m_rc); CWindow wndParent=m_wnd.GetParent(); wndParent.ScreenToClient(&m_rc); wndParent.ScreenToClient(&pt); if(IsHorizontal()) { if(IsTop()) m_ppos=&m_rc.bottom; else m_ppos=&m_rc.top; m_bounds.low=rcBound.top; m_bounds.hi=rcBound.bottom; m_offset=pt.y-*m_ppos; } else { if(IsTop()) m_ppos=&m_rc.right; else m_ppos=&m_rc.left; m_bounds.low=rcBound.left; m_bounds.hi=rcBound.right; m_offset=pt.x-*m_ppos; } m_bounds.low+=minSize; m_bounds.hi-=minSize; } void OnMove(long x, long y) { long pos = IsHorizontal() ? y : x; pos-=m_offset; pos=m_bounds.bind(pos); if(*m_ppos!=pos) { *m_ppos=pos; Move(); } } void SetPosition() { m_wnd.SetWindowPos(NULL,&m_rc,SWP_NOZORDER | SWP_NOACTIVATE); } virtual void Move() { SetPosition(); } bool ProcessWindowMessage(MSG* pMsg) { return (pMsg->message==WM_TIMER); } protected: CWindow m_wnd; CBounds m_bounds; CRect m_rc; const CSide m_side; long* m_ppos; long m_offset; }; class CSizeTrackerGhost : public CSizeTrackerFull { typedef CSimpleSplitterBarSlider<CSplitterBar> CSlider; public: CSizeTrackerGhost(HWND hWnd,CPoint pt,const CSide& side,CSplitterBar& splitter,const CRect& rcBound) : CSizeTrackerFull(hWnd,pt,side,splitter.GetThickness(),rcBound),m_dc(::GetWindowDC(NULL)) ,m_splitter(splitter),m_slider(splitter) { m_spOffset=m_slider-*m_ppos; } void BeginDrag() { m_splitter.DrawGhostBar(m_dc); } void EndDrag(bool bCanceled) { m_splitter.CleanGhostBar(m_dc); if(!bCanceled) SetPosition(); } virtual void Move() { m_splitter.CleanGhostBar(m_dc); m_slider=*m_ppos+m_spOffset; m_splitter.DrawGhostBar(m_dc); } protected: CDC m_dc; CSplitterBar& m_splitter; CSlider m_slider; long m_spOffset; }; public: CAutoHideManager() : m_barThickness(0),m_pActive(0),m_pTracked(0) { m_rcBound.SetRectEmpty(); m_side=0; } bool Initialize(HWND hWnd) { ApplySystemSettings(hWnd); m_bars[CSide::sTop].Initialize(CSide(CSide::sTop)); m_bars[CSide::sBottom].Initialize(CSide(CSide::sBottom)); m_bars[CSide::sLeft].Initialize(CSide(CSide::sLeft)); m_bars[CSide::sRight].Initialize(CSide(CSide::sRight)); RECT rc={0,0,0,0}; return (Create(hWnd,rc)!=NULL); } void ApplySystemSettings(HWND hWnd) { CClientDC dc(hWnd); CDWSettings settings; HFONT hOldFont=dc.SelectFont(settings.VSysFont()); TEXTMETRIC tm; dc.GetTextMetrics(&tm); m_barThickness=tm.tmHeight; dc.SelectFont(settings.HSysFont()); dc.GetTextMetrics(&tm); if(m_barThickness<tm.tmHeight) m_barThickness=tm.tmHeight; dc.SelectFont(hOldFont); int widthIcon=settings.CXMinIcon(); assert(widthIcon==settings.CYMinIcon()); //if it throw let me know ;) if(widthIcon>m_barThickness) m_barThickness=widthIcon; m_barThickness+=2*IPinnedLabel::captionPadding+IPinnedLabel::labelEdge; } void UpdateLayout(CDC& dc,CRect& rc) { long leftPadding= ( m_bars[CSide::sLeft].IsVisible() ) ? m_barThickness : 0; long rightPadding=( m_bars[CSide::sRight].IsVisible() ) ? m_barThickness : 0; m_bars[CSide::sTop].CalculateRect( dc,rc,m_barThickness,leftPadding,rightPadding); m_bars[CSide::sBottom].CalculateRect( dc,rc,m_barThickness,leftPadding,rightPadding); leftPadding=0; rightPadding=0; m_bars[CSide::sLeft].CalculateRect( dc,rc,m_barThickness,leftPadding,rightPadding); m_bars[CSide::sRight].CalculateRect( dc,rc,m_barThickness,leftPadding,rightPadding); m_rcBound.CopyRect(&rc); if(m_pActive) FitPane(); } long Width() const { long width=0; if(m_bars[CSide::sLeft].IsVisible()) width+=m_barThickness; if(m_bars[CSide::sRight].IsVisible()) width+=m_barThickness; return width; } long Height() const { long height=0; if(m_bars[CSide::sTop].IsVisible()) height+=m_barThickness; if(m_bars[CSide::sBottom].IsVisible()) height+=m_barThickness; return height; } bool FitPane() { CRect rc(m_rcBound); long spliterWidth=m_splitter.GetThickness(); long width=m_pActive->Width()+spliterWidth; if(IsHorizontal()) { long maxWidth=rc.Height(); maxWidth=(maxWidth<spliterWidth) ? spliterWidth : maxWidth-spliterWidth; if(IsTop()) rc.bottom=rc.top+( (maxWidth>width) ? width : maxWidth ); else rc.top=rc.bottom-( (maxWidth>width) ? width : maxWidth ); } else { long maxWidth=rc.Width(); maxWidth=(maxWidth<spliterWidth) ? spliterWidth : maxWidth-spliterWidth; if(IsTop()) rc.right=rc.left+( (maxWidth>width) ? width : maxWidth ); else rc.left=rc.right-( (maxWidth>width) ? width : maxWidth ); } return (SetWindowPos(HWND_TOP,rc,SWP_NOACTIVATE)!=FALSE); } IPinnedLabel::CPinnedWindow* LocatePinnedWindow(const CPoint& pt) const { IPinnedLabel::CPinnedWindow* ptr=0; for(int i=0;i<barsCount;i++) { ptr=m_bars[i].MouseEnter(pt); if(ptr!=0) break; } return ptr; } bool IsPtIn(const CPoint& pt) const { bool bRes; for(int i=0;i<barsCount;i++) { bRes=m_bars[i].IsPtIn(pt); if(bRes) break; } return bRes; } bool MouseEnter(HWND hWnd,const CPoint& pt) { IPinnedLabel::CPinnedWindow* ptr=0; for(int i=0;i<barsCount;i++) { CAutoHideBar* pbar=m_bars+i; ptr=pbar->MouseEnter(pt); if((ptr!=0) && IsVisualizationNeeded(ptr)) { m_pTracked=ptr; TRACKMOUSEEVENT tme = { 0 }; tme.cbSize = sizeof(tme); tme.hwndTrack = hWnd; tme.dwFlags = TME_HOVER; tme.dwHoverTime = hoverTimeout; ::_TrackMouseEvent(&tme); break; } } return (ptr!=0); } bool MouseHover(HWND hWnd,const CPoint& pt) { IPinnedLabel::CPinnedWindow* ptr=0; for(int i=0;i<barsCount;i++) { CAutoHideBar* pbar=m_bars+i; ptr=pbar->MouseEnter(pt,true); if((ptr!=0) && (ptr==m_pTracked) &&IsVisualizationNeeded(ptr)) { CClientDC dc(hWnd); pbar->Draw(dc); Visualize(ptr,i,true); break; } } return (ptr!=0); } void Draw(CDC& dc) { EraseBackground(dc); for(int i=0;i<barsCount;i++) m_bars[i].Draw(dc,false); } void EraseBackground(CDC& dc) { CDWSettings settings; CBrush bgrBrush; bgrBrush.CreateSolidBrush(settings.CoolCtrlBackgroundColor()); HBRUSH hOldBrush=dc.SelectBrush(bgrBrush); CRect rcTop(m_bars[CSide::sTop].operator const CRect&()); CRect rcBottom(m_bars[CSide::sBottom].operator const CRect&()); if(m_bars[CSide::sLeft].IsVisible()) { const CRect& rc=m_bars[CSide::sLeft].operator const CRect&(); rcTop.left-=rc.Height(); rcBottom.left-=rc.Height(); dc.PatBlt(rc.left, rc.top, rc.Width(), rc.Height(), PATCOPY); } if(m_bars[CSide::sRight].IsVisible()) { const CRect& rc=m_bars[CSide::sRight].operator const CRect&(); rcTop.right+=rc.Height(); rcBottom.right+=rc.Height(); dc.PatBlt(rc.left, rc.top, rc.Width(), rc.Height(), PATCOPY); } if(m_bars[CSide::sTop].IsVisible()) dc.PatBlt(rcTop.left, rcTop.top, rcTop.Width(), rcTop.Height(), PATCOPY); if(m_bars[CSide::sBottom].IsVisible()) dc.PatBlt(rcBottom.left, rcBottom.top, rcBottom.Width(), rcBottom.Height(), PATCOPY); dc.SelectBrush(hOldBrush); } bool PinUp(HWND hWnd,DFPINUP* pHdr,bool& bUpdate) { pHdr->hdr.hBar=m_hWnd; CSide side(pHdr->dwDockSide); assert(side.IsValid()); CAutoHideBar* pbar=m_bars+side.Side(); bUpdate=!pbar->IsVisible(); IPinnedLabel* pLabel=pbar->Insert(pHdr); bool bRes=(pLabel!=0); if(bRes&& ((pHdr->dwFlags&DFPU_VISUALIZE)!=0)) Visualize(pLabel->ActivePinnedWindow(),side); if(!bUpdate) { CClientDC dc(hWnd); pbar->UpdateLayout(dc); pbar->Draw(dc); } return bRes; } bool Remove(HWND hWnd,bool bUnpin=false) { if(m_pActive!=0 && (m_pActive->Wnd()==hWnd ) ) Vanish(); HDOCKBAR hBar=GetParent(); assert(::IsWindow(hBar)); DFDOCKPOS* pHdr=0; DFDOCKPOS dockHdr={0}; if(bUnpin) { // dockHdr.hdr.code=DC_SETDOCKPOSITION; dockHdr.hdr.hWnd=hWnd; dockHdr.hdr.hBar=hBar; pHdr=&dockHdr; } bool bRes=false; for(int i=0;i<barsCount;i++) { CAutoHideBar* pbar=m_bars+i; bRes=pbar->Remove(hWnd,m_hWnd,pHdr); if(bRes) { if(pbar->IsVisible()) { CClientDC dc(hBar); pbar->UpdateLayout(dc); pbar->Draw(dc); } else { ::SendMessage(hBar, WM_SIZE, 0, 0); ::RedrawWindow(hBar,NULL,NULL, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE); } break; } } return bRes; } bool GetDockingPosition(DFDOCKPOS* pHdr) const { bool bRes=false; for(int i=0;i<barsCount;i++) { bRes=m_bars[i].GetDockingPosition(pHdr); if(bRes) break; } return bRes; } /////////////////////////////////////////////////////////// bool IsVisualizationNeeded(const IPinnedLabel::CPinnedWindow* ptr) const { return (ptr!=m_pActive); } bool Visualize(IPinnedLabel::CPinnedWindow* ptr,const CSide& side,bool bAnimate=false) { assert(ptr); assert(IsVisualizationNeeded(ptr)); Vanish(); Orientation(side); assert(m_pActive==0); m_pActive=ptr; bool bRes=(::SetWindowPos(m_pActive->Wnd(),HWND_TOP,0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW)!=FALSE); if(bRes) { bRes=FitPane(); if(bRes) { SetWindowText(m_pActive->Text()); CDWSettings setting; if(bAnimate && setting.IsAnimationEnabled()) AnimateWindow(animateTimeout,true); else bRes=(SetWindowPos(HWND_TOP,0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_FRAMECHANGED )!=FALSE); if(bRes) { BOOL dummy; OnSize(0,0,0,dummy); bRes=(SetTimer(tmID,tmTimeout)==tmID); } } } assert(bRes); return bRes; } bool Vanish(bool bAnimate=false) { bool bRes=(m_pActive==0); if(!bRes) { KillTimer(tmID); ::ShowWindow(m_pActive->Wnd(),SW_HIDE); m_pActive=0; CDWSettings setting; if(bAnimate && setting.IsAnimationEnabled()) AnimateWindow(animateTimeout,false); bRes=ShowWindow(SW_HIDE)!=FALSE; } return bRes; } /////////////////////////////////////////////////////////// void StartResizing(const CPoint& pt) { std::auto_ptr<CSizeTrackerFull> pTracker; CDWSettings settings; if(settings.GhostDrag()) { CRect rc; GetWindowRect(&rc); CSplitterBar splitter(IsHorizontal()); splitter.CalculateRect(rc,m_side.Side()); pTracker=std::auto_ptr<CSizeTrackerFull>( new CSizeTrackerGhost(m_hWnd,pt,Orientation(),splitter,m_rcBound)); } else pTracker=std::auto_ptr<CSizeTrackerFull>( new CSizeTrackerFull(m_hWnd,pt,Orientation(),m_splitter.GetThickness(),m_rcBound)); HWND hWndParent=GetParent(); assert(hWndParent); TrackDragAndDrop(*pTracker,hWndParent); } bool PinBtnPress() { assert(m_pActive); return Remove(m_pActive->Wnd(),true); } bool OnClosing() { assert(m_pActive); ::PostMessage(m_pActive->Wnd(),WM_CLOSE,NULL,NULL); return true; } DECLARE_WND_CLASS(_T("CAutoHideManager")) protected: BEGIN_MSG_MAP(thisClass) MESSAGE_HANDLER(WM_DESTROY, OnDestroy) MESSAGE_HANDLER(WM_TIMER,OnTimer) MESSAGE_HANDLER(WM_SIZE, OnSize) ///////////////// MESSAGE_HANDLER(WMDF_DOCK,OnDock) CHAIN_MSG_MAP(baseClass) END_MSG_MAP() LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { bHandled = false; Vanish(false); return 0; } LRESULT OnTimer(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { POINT pt; CRect rc; GetCursorPos(&pt); GetWindowRect(&rc); if(!rc.PtInRect(pt)) { CWindow wndParent (GetParent()); wndParent.ScreenToClient(&pt); IPinnedLabel::CPinnedWindow* ptr=LocatePinnedWindow(pt); if(ptr==0 || IsVisualizationNeeded(ptr)) { HWND hWnd=GetFocus(); while( hWnd!=m_hWnd ) { if(hWnd==NULL) { Vanish(true); break; } hWnd=::GetParent(hWnd); } } } return 0; } LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled) { if(wParam != SIZE_MINIMIZED && (m_pActive!=0)) { CRect rc; GetClientRect(&rc); ::SetWindowPos(m_pActive->Wnd(),NULL, rc.left,rc.top, rc.Width(),rc.Height(), SWP_NOZORDER | SWP_NOACTIVATE); GetWindowRect(&rc); long width = (IsHorizontal()) ? rc.Height() : rc.Width(); width -= m_splitter.GetThickness(); if(width>m_caption.GetThickness()/*0*/) m_pActive->Width(width); } bHandled = FALSE; return 1; } LRESULT OnDock(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/) { LRESULT lRes=FALSE; DFMHDR* pHdr=reinterpret_cast<DFMHDR*>(lParam); switch(pHdr->code) { case DC_UNDOCK: assert(::IsWindow(pHdr->hWnd)); lRes=Remove(pHdr->hWnd); break; } return lRes; } protected: long m_barThickness; IPinnedLabel::CPinnedWindow* m_pActive; IPinnedLabel::CPinnedWindow* m_pTracked; CRect m_rcBound; CAutoHideBar m_bars[barsCount]; }; }//namespace dockwins #endif // __WTL_DW__DWAUTOHIDE_H__
[ "hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0" ]
[ [ [ 1, 1842 ] ] ]
8d54ce8c86c84e674a4f14d72a8a819a706ff333
9dd0a777fc67c4b6c7bce8c4838a3013f1b65c04
/ mepakaneta --username jeffom/MEPA.h
b2788d92191004155757faa00848adeb49640b2f
[]
no_license
lucasjcastro/mepakaneta
b99957df02d000e3a08b1f5a8e53e81f31383fe1
deadb5f1164317323accdefd56aa24dfe4def71a
refs/heads/master
2021-01-10T08:17:33.427687
2008-09-25T10:18:59
2008-09-25T10:18:59
46,521,179
0
0
null
null
null
null
ISO-8859-1
C++
false
false
5,570
h
#ifndef MEPA_H_ #define MEPA_H_ #include <string> #include <iostream> #include <vector> #include <fstream> #define EMPTY -1 using namespace std; /* Declaração dos tipos de comando */ enum { crct, soma, subt, mult, divi, invr, conj, disj, nega, cmme, cmma, cmig, cmdg, cmeg, cmag, dsvs, dsvf, nada, leit, impr, impl, impc, inpp, amem, para, crvl, armz, chpr, enpr, dmem, rtpr, crvi, armi, cren}; class pilha_P { public: int comando; string label; vector<int> args; }; class label { public: int endereco; string label; }; class MEPA { private: /* Pilha de intrução */ vector<pilha_P> P; /* Pilha de dados */ vector<int> M; /* Pilha de registradores */ vector<int> D; /* Marcador da pilha de instrução */ int i; /* Marcador da pilha de dados*/ int s; /** * Carrega constante no topo da pilha * @param valor a ser inserido no topo */ void CRCT( int ); /** * carrega valor de M[D[m]+n] para o topo da pilha * @param m é o nível léxico, e n o número da variável em VAR */ void CRVL( int , int ); /** * */ void CRVL( int); /** * Soma o valor do topo com o valor armazenado * uma posição abaixo e então guarda o valor * no novo topo */ void SOMA(); /** * Subtrai o valor do topo com o valor armazenado * uma posição abaixo e então guarda o valor * no novo topo */ void SUBT(); /** * Multiplica o valor do topo com o valor armazenado * uma posição abaixo e então guarda o valor * no novo topo */ void MULT(); /** * Divide o valor do topo com o valor armazenado * uma posição abaixo e então guarda o valor * no novo topo */ void DIVI(); /** * Compara o valor do topo com o valor uma posição * abaixo e verifica se é igual */ void CMIG(); /** * Compara o valor do topo com o valor uma posição * abaixo e verifica se é maior */ void CMMA(); /** * Compara o valor do topo com o valor uma posição * abaixo e verifica se é menor */ void CMME(); /** * Compara o valor do topo com o valor uma posição * abaixo e verifica se é maior ou igual */ void CMAG(); /** * Compara o valor do topo com o valor uma posição * abaixo e verifica se é menor ou igual */ void CMEG(); /** * Compara o valor do topo com o valor uma posição * abaixo e verifica se é diferente */ void CMDG(); /** * Faz a operação lógica "AND" entre o topo da pilha * e o valor uma posição abaixo */ void CONJ(); /** * Faz a operação lógica "OR" entre o topo da pilha * e o valor uma posição abaixo */ void DISJ(); /** * Faz a operação lógica "NOT" com o valor do topo */ void NEGA(); /** * Complementa o sinal do valor do topo da pilha */ void INVR(); /** * Lê um valor no dispositivo de entrada (teclado) * e armazena-o no topo da pilha */ void LEIT(); /** * imprime no dispositivo de saída (monitor) * o conteúdo do topo da pilha */ void IMPR(); /** * equivalente a NOP, * será utilizada na geração de endereços de destino de desvios */ void NADA(); /** * desvia sempre, i.e., desvio incondicional * @param endereco do LABEL L */ void DSVS( int ); /** * Desvio Condicional, desvia para o LABEL L se o topo da pilha for FALSE (zero) * @param endereco do LABEL L */ void DSVF( int ); /** * inicia programa principal */ void INPP(); /** * aloca memória para N variáveis * @param numero de variaveis a serem alocadas */ void AMEM( int ); /** * desaloca memória para N variáveis * @param numero de variaveis a serem desalocadas */ void DMEM( int ); /** * encerra a execução da MEPA */ void PARA(); /** * armazena o valor do topo da pilha em M[D[m]+n] * @param m é o nível léxico, e n o número da variável em VAR */ void ARMZ( int, int ); void ARMZ (int ); /** * chama o procedimento cuja primeira instrução se encontra no LABEL L * @param endereco do LABEL L */ void CHPR( int ); /** * salva no topo da pilha o endereço do registro de ativação * do procedimento de nível léxico K que estava ativado * @param nivel lexico do procedimento */ void ENPR( int ); /** * retorna do procedimento de nível léxico k com n parâmetros * @param nivel lexico do procedimento e numero de parametros */ void RTPR( int, int ); /** * carrega valor indireto * @param nivel lexico e deslocamento da variavel */ void CRVI( int, int ); /** * armazena valor indiretamente * @param nivel lexico e deslocamento da variavel */ void ARMI( int, int ); /** * carrega endereço indireto * @param nivel lexico e deslocamento da variavel */ void CREN( int, int ); void ClearArray ( char[] , int ); public: MEPA(); ~MEPA(); void Teste(); /** * Executa as instruções da pilha P * */ void Executar(); /** * Executa as instruções da pilha P * mostrando passo a passo * */ void ExecutarPasso(); /** * Carrega as instruçõe na pilha P * @param string * */ void CarregaInstrucao(string); /** * Imprime situação atual das pilhas * */ void Imprime(); //Teste para trace de erro void conteudo_P(); }; #endif /*MEPA_H_*/
[ "jeffom@485f0772-852a-11dd-99d6-6900107db72b" ]
[ [ [ 1, 280 ] ] ]
b61a1a4a67bec80195ab5643079a85c94cc426bf
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib/src/common/MyuLoaderBase.cpp
02dfb3e39dfec574e948c3b4e105f5de552a39b5
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,697
cpp
////////////////////////////////////////////////////////// // // MyuLoaderBase // - 名前がstring確定なクラス(エラー処理付き) // ////////////////////////////////////////////////////////// #include "stdafx.h" #include "MyuLoaderBase.h" // マクロ化 #define TEMPLATE_T template <typename T> // コンストラクタ TEMPLATE_T CMyuLoaderBase<T>::CMyuLoaderBase() { } // デストラクタ TEMPLATE_T CMyuLoaderBase<T>::~CMyuLoaderBase() { } // 全てをクリア TEMPLATE_T void CMyuLoaderBase<T>::DeleteAll() { m_map.clear(); } // 追加 TEMPLATE_T bool CMyuLoaderBase<T>::Add( const char* szFilename ) { // 既に無いかチェック if ( IsExist( szFilename ) == true ) return false; // 追加 //(*p_map)[szFilename] = T(); m_map[szFilename] = T(); return TLoad( m_map[szFilename], szFilename ); } // 取得 TEMPLATE_T typename T* CMyuLoaderBase<T>::Get( const char* szFilename ) { // 本当にあるかチェック if ( IsExist( szFilename ) == false ) return false; //return &(*p_map)[szFilename]; return &m_map[szFilename]; } // 削除 TEMPLATE_T typename bool CMyuLoaderBase<T>::Delete( const char* szFilename ) { // 本当にあるかチェック if ( IsExist( szFilename ) == false ) return false; m_map.erase( szFilename ); } // 存在するかチェック TEMPLATE_T bool CMyuLoaderBase<T>::IsExist( const char* szFilename ) { MAP_ITR itr = m_map.find( szFilename ); if ( itr == m_map.end() ) return false; else return true; } // サイズ取得 TEMPLATE_T size_t CMyuLoaderBase<T>::Size() { //return p_map->size(); return m_map.size(); }
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 81 ] ] ]
109c23b8b4f237a8efe3d4cc2dae25c857887d1e
394a3cb743fa873132d44a5800440e5bf7bcfad8
/src/ADstar.cpp
8b0964e2fa617914ae9b7e6aa630fa73bf788239
[]
no_license
lfsmoura/dalgo
19487487271b5410b3facfc0b0647c8736074fa8
47cfb3be3126955e822ca08179f82aa3eba1de6f
refs/heads/master
2020-06-03T11:02:49.541436
2010-06-30T01:35:30
2010-06-30T01:35:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
735
cpp
#include <iostream> #include <fstream> #include <limits> #include <queue> #include <list> #include <algorithm> #include <boost/graph/random.hpp> #include <boost/random.hpp> //#include <boost/foreach.hpp> #include "Timer.h" #include "ADstar.h" #define test(nome,var) cout << nome << " = " << var << endl const double INFINITO = std::numeric_limits<double>::max(); ADstar::ADstar(G* graph){ numNodes_ = num_vertices(*graph); //x = new double[numNodes_](); //y = new double[numNodes_](); f_ = new double[numNodes_](); g_ = new double[numNodes_](); v_ = new double[numNodes_](); backPointer_ = new int[numNodes_](); set_ = new Sets[numNodes_](); open_ = new PriorityQueue(numNodes_, f_); }
[ [ [ 1, 33 ] ] ]
60db008de7d20d8418ed334542bcec4377ad53cd
78fb44a7f01825c19d61e9eaaa3e558ce80dcdf5
/guceGUI/src/CGUCEGUIModule.cpp
43ae509ef272d67ee66b7a31e88ab7084889fcd7
[]
no_license
LiberatorUSA/GUCE
a2d193e78d91657ccc4eab50fab06de31bc38021
a4d6aa5421f8799cedc7c9f7dc496df4327ac37f
refs/heads/master
2021-01-02T08:14:08.541536
2011-09-08T03:00:46
2011-09-08T03:00:46
41,840,441
0
0
null
null
null
null
UTF-8
C++
false
false
3,153
cpp
/* * guceGUI: GUCE module providing GUI functionality * Copyright (C) 2002 - 2007. Dinand Vanvelzen * * 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 */ /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #ifndef GUCE_GUI_CGUIMANAGER_H #include "CGUIManager.h" #define GUCE_GUI_CGUIMANAGER_H #endif /* GUCE_GUI_CGUIMANAGER_H ? */ #include "CGUCEGUIModule.h" /* definition of the class implemented here */ /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCE { namespace GUI { /*-------------------------------------------------------------------------// // // // CLASSES // // // //-------------------------------------------------------------------------*/ bool CGUCEGUIModule::Load( void ) {GUCE_TRACE; CGUIManager::Instance(); return true; } /*-------------------------------------------------------------------------*/ bool CGUCEGUIModule::Unload( void ) {GUCE_TRACE; CGUIManager::Deinstance(); return true; } /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ } // namespace GUI } // namespace GUCE /*-------------------------------------------------------------------------*/
[ [ [ 1, 75 ] ] ]
ce763c68a2aeb2a670ad03cf781af9ffc16b4be0
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/util/regx/XMLUniCharacter.hpp
8bce5c8d821345c6eecaa307ac29b6a7ed233362
[]
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
2,935
hpp
/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: XMLUniCharacter.hpp 176026 2004-09-08 13:57:07Z peiyongz $ */ #if !defined(XMLUNICHARACTER_HPP) #define XMLUNICHARACTER_HPP #include <xercesc/util/XercesDefs.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * Class for representing unicode characters */ class XMLUTIL_EXPORT XMLUniCharacter { public: // ----------------------------------------------------------------------- // Public Constants // ----------------------------------------------------------------------- // Unicode chara types enum { UNASSIGNED = 0, UPPERCASE_LETTER = 1, LOWERCASE_LETTER = 2, TITLECASE_LETTER = 3, MODIFIER_LETTER = 4, OTHER_LETTER = 5, NON_SPACING_MARK = 6, ENCLOSING_MARK = 7, COMBINING_SPACING_MARK = 8, DECIMAL_DIGIT_NUMBER = 9, LETTER_NUMBER = 10, OTHER_NUMBER = 11, SPACE_SEPARATOR = 12, LINE_SEPARATOR = 13, PARAGRAPH_SEPARATOR = 14, CONTROL = 15, FORMAT = 16, PRIVATE_USE = 17, SURROGATE = 18, DASH_PUNCTUATION = 19, START_PUNCTUATION = 20, END_PUNCTUATION = 21, CONNECTOR_PUNCTUATION = 22, OTHER_PUNCTUATION = 23, MATH_SYMBOL = 24, CURRENCY_SYMBOL = 25, MODIFIER_SYMBOL = 26, OTHER_SYMBOL = 27, INITIAL_PUNCTUATION = 28, FINAL_PUNCTUATION = 29 }; /** destructor */ ~XMLUniCharacter() {} /* Static methods for getting unicode character type */ /** @name Getter functions */ //@{ /** Gets the unicode type of a given character * * @param ch The character we want to get its unicode type */ static unsigned short getType(const XMLCh ch); //@} private : /** @name Constructors and Destructor */ //@{ /** Unimplemented default constructor */ XMLUniCharacter(); //@} }; XERCES_CPP_NAMESPACE_END #endif /** * End of file XMLUniCharacter.hpp */
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 100 ] ] ]
2c21448465126b14efcaa4784e014a654545353d
54dfb0046228832dcdec6dc5a18c5c23ada6f9ee
/MainProgram/Track.cpp
ce555fb56fc73d0a12e19859e62747082a6f2e78
[]
no_license
github188/piglets-monitoring
3f6ec92e576d334762cc805727d358d9799ca053
620b6304384534eb71113c26a054c36ce3800ed8
refs/heads/master
2021-01-22T12:45:45.159790
2011-11-08T15:37:18
2011-11-08T15:37:18
null
0
0
null
null
null
null
GB18030
C++
false
false
8,384
cpp
#include "Track.h" const int stateNum=8; const int measureNum=stateNum/2; const float T=0.5; #if stateNum==10 float transitionMat[stateNum][stateNum] ={//transition matrix(x,y,width,height,angle,dx,dy,dw,dh,da) 1,0,0,0,0,T,0,0,0,0, 0,1,0,0,0,0,T,0,0,0, 0,0,1,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,T, 0,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,1,0,0,0, 0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,1,0, 0,0,0,0,0,0,0,0,0,1, }; #else if stateNum==8 float transitionMat[stateNum][stateNum] ={//transition matrix(x,y,width,height,dx,dy,dw,dh) 1,0,0,0,T,0,0,0, 0,1,0,0,0,T,0,0, 0,0,1,0,0,0,T,0, 0,0,0,1,0,0,0,T, 0,0,0,0,1,0,0,0, 0,0,0,0,0,1,0,0, 0,0,0,0,0,0,1,0, 0,0,0,0,0,0,0,1, }; #endif //公共面积计算,面积重合率计算 //参数:相比较的两个矩形 //返回:返回最大重合率 double CommonArea(CvRect rectT1,CvRect rectT2) { if (rectT1.x>rectT2.x+rectT2.width||rectT2.x>rectT1.x+rectT1.width){ return 0.; } if (rectT1.y>rectT2.y+rectT2.height||rectT2.y>rectT1.y+rectT1.height){ return 0.; } int maxLeftTopX,maxLeftTopY,minRightButtonX,minRightButtonY; float commonArea,rectT1Area,rectT2Area; float rate1,rate2; if (rectT1.x-rectT2.x>0){ maxLeftTopX=rectT1.x; }else{ maxLeftTopX=rectT2.x; } if (rectT1.y-rectT2.y>0){ maxLeftTopY=rectT1.y; }else{ maxLeftTopY=rectT2.y; } if (rectT1.x+rectT1.width>rectT2.x+rectT2.width){ minRightButtonX=rectT2.x+rectT2.width; }else{ minRightButtonX=rectT1.x+rectT1.width; } if (rectT1.y+rectT1.height>rectT2.y+rectT2.height){ minRightButtonY=rectT2.y+rectT2.height; }else{ minRightButtonY=rectT1.y+rectT1.height; } commonArea=(float)(minRightButtonX-maxLeftTopX)*(minRightButtonY-maxLeftTopY); rectT1Area=(float)rectT1.height*rectT1.width; rectT2Area=(float)rectT2.height*rectT2.width; rate1=commonArea/rectT1Area; rate2=commonArea/rectT2Area; return rate1 >rate2 ? rate1 : rate2; } double DistanceBetweenTrackAndBlob( CBlob& blob, CTrack& track ) { CvRect blobrc=blob.GetBoundingBox(); CvRect trackrc=track.m_rcBoundingBox; double dcommArea=CommonArea(blobrc,trackrc); double dhis[3]; for (int i=0; i<3; ++i){ blob.GetHistogram(i)->CompareHist(track.GetHistogram(i),CV_COMP_BHATTACHARYYA,dhis[i]); dcommArea+=1-dhis[i]; } dcommArea/=4; return dcommArea; } CTrack::CTrack() :CBlob() ,m_kalmanblob(new KalmanBlob(stateNum,measureNum,0)) ,m_lifetime(0) ,m_active(0) ,m_inactive(0) { memcpy( m_kalmanblob->transitionMatrix->data.fl,transitionMat, sizeof(transitionMat)); } CTrack::CTrack(CBlob &blob,int id,TRACKSTATE state) :CBlob(blob) ,m_trackid(id) ,m_trackState(state) ,m_kalmanblob(new KalmanBlob(stateNum,measureNum,0)) ,m_lifetime(0) ,m_active(0) ,m_inactive(0) { memcpy( m_kalmanblob->transitionMatrix->data.fl,transitionMat, sizeof(transitionMat)); m_rcBoundingBox=blob.GetBoundingBox(); m_box=blob.GetEllipse(); if (stateNum==10) { m_kalmanblob->statePost->data.fl[0]=m_box.center.x; m_kalmanblob->statePost->data.fl[1]=m_box.center.y; m_kalmanblob->statePost->data.fl[2]=m_box.size.width; m_kalmanblob->statePost->data.fl[3]=m_box.size.height; m_kalmanblob->statePost->data.fl[4]=m_box.angle; }else if (stateNum==8) { m_kalmanblob->statePost->data.fl[0]=m_rcBoundingBox.x; m_kalmanblob->statePost->data.fl[1]=m_rcBoundingBox.y; m_kalmanblob->statePost->data.fl[2]=m_rcBoundingBox.width; m_kalmanblob->statePost->data.fl[3]=m_rcBoundingBox.height; } } CTrack::CTrack( CTrack &srcTrack ) :m_kalmanblob(new KalmanBlob(stateNum,measureNum,0)) ,m_lifetime(0) ,m_active(0) ,m_inactive(0) { memcpy( m_kalmanblob->transitionMatrix->data.fl,transitionMat, sizeof(transitionMat)); *this=srcTrack; } CTrack::CTrack( CTrack *srcTrack ) :m_kalmanblob(new KalmanBlob(stateNum,measureNum,0)) ,m_lifetime(0) ,m_active(0) ,m_inactive(0) { memcpy( m_kalmanblob->transitionMatrix->data.fl,transitionMat, sizeof(transitionMat)); if (srcTrack!=NULL) { *this=*srcTrack; } } CTrack::CTrack( CBlob &srcBlob ) :m_kalmanblob(new KalmanBlob(stateNum,measureNum,0)) ,m_lifetime(0) ,m_active(0) ,m_inactive(0) { *this=srcBlob; } CTrack::CTrack( CBlob *srcBlob ) :m_kalmanblob(new KalmanBlob(stateNum,measureNum,0)) ,m_lifetime(0) ,m_active(0) ,m_inactive(0) { if (srcBlob!=NULL) { *this=*srcBlob; } } CTrack::~CTrack(void) { } CTrack& CTrack::operator=( const CTrack &srcTrack ) { if(this != &srcTrack){ this->CBlob::operator=(srcTrack); this->m_lifetime=srcTrack.m_lifetime; this->m_active=srcTrack.m_active; this->m_inactive=srcTrack.m_inactive; this->m_rcBoundingBox=srcTrack.m_rcBoundingBox; this->m_box=srcTrack.m_box; this->m_kalmanblob=srcTrack.m_kalmanblob; this->SetState(srcTrack.GetState()); this->SetID(srcTrack.GetID()); } return *this; } CTrack& CTrack::operator=( const CBlob &srcBlob ) { if(this != &srcBlob){ CBlob tmpBlob(srcBlob); this->CBlob::operator=(tmpBlob); m_rcBoundingBox=tmpBlob.GetBoundingBox(); m_box=tmpBlob.GetEllipse(); if (stateNum==10) { m_kalmanblob->statePost->data.fl[0]=m_box.center.x; m_kalmanblob->statePost->data.fl[1]=m_box.center.y; m_kalmanblob->statePost->data.fl[2]=m_box.size.width; m_kalmanblob->statePost->data.fl[3]=m_box.size.height; m_kalmanblob->statePost->data.fl[4]=m_box.angle; }else if (stateNum==8) { m_kalmanblob->statePost->data.fl[0]=m_rcBoundingBox.x; m_kalmanblob->statePost->data.fl[1]=m_rcBoundingBox.y; m_kalmanblob->statePost->data.fl[2]=m_rcBoundingBox.width; m_kalmanblob->statePost->data.fl[3]=m_rcBoundingBox.height; } } return *this; } void CTrack::SetState( TRACKSTATE trackState ) { m_trackState=trackState; switch(trackState){ case TRACKSTATE_ACTIVE: this->m_lifetime++; this->m_active++; this->m_inactive=0; break; case TRACKSTATE_MISS: //this->m_lifetime++; this->m_active=0; this->m_inactive++; break; case TRACKSTATE_MERGE: //this->m_lifetime++; this->m_active=0; this->m_inactive++; break; case TRACKSTATE_SEPARATE: //this->m_lifetime++; this->m_active=0; this->m_inactive++; break; default: break; } } void CTrack::UpdateBlob( CBlob &blob,bool isUseKalman/*=false*/) { this->CBlob::operator=(blob); if(isUseKalman){ const CvMat*predict=m_kalmanblob->predict();//预测结果 m_box=blob.GetEllipse(); m_rcBoundingBox=blob.GetBoundingBox(); float fmeasure[measureNum]; CvMat blobMat=cvMat(measureNum,1,CV_32FC1,fmeasure); if (measureNum==5) { fmeasure[0]=m_box.center.x; fmeasure[1]=m_box.center.y; fmeasure[2]=m_box.size.width; fmeasure[3]=m_box.size.height; fmeasure[4]=m_box.angle; m_kalmanblob->correct(&blobMat);//加上测量结果得到最优估算 m_box.center.x=predict->data.fl[0]; m_box.center.y=predict->data.fl[1]; m_box.size.width=predict->data.fl[2]; m_box.size.height=predict->data.fl[3]; m_box.angle=predict->data.fl[4]; m_rcBoundingBox=box2D2rect(m_box); }else if(measureNum==4) { fmeasure[0]=m_rcBoundingBox.x; fmeasure[1]=m_rcBoundingBox.y; fmeasure[2]=m_rcBoundingBox.width; fmeasure[3]=m_rcBoundingBox.height; predict=m_kalmanblob->correct(&blobMat);//加上测量结果得到最优估算 m_rcBoundingBox.x=predict->data.fl[0]; m_rcBoundingBox.y=predict->data.fl[1]; m_rcBoundingBox.width=predict->data.fl[2]; m_rcBoundingBox.height=predict->data.fl[3]; } }else{ m_rcBoundingBox=blob.GetBoundingBox(); m_box=blob.GetEllipse(); const CvMat*predict=m_kalmanblob->predict();//预测结果 float fmeasure[measureNum]; CvMat blobMat=cvMat(measureNum,1,CV_32FC1,fmeasure); if (measureNum==5) { fmeasure[0]=m_box.center.x; fmeasure[1]=m_box.center.y; fmeasure[2]=m_box.size.width; fmeasure[3]=m_box.size.height; fmeasure[4]=m_box.angle; m_kalmanblob->correct(&blobMat);//加上测量结果得到最优估算 }else if(measureNum==4) { fmeasure[0]=m_rcBoundingBox.x; fmeasure[1]=m_rcBoundingBox.y; fmeasure[2]=m_rcBoundingBox.width; fmeasure[3]=m_rcBoundingBox.height; m_kalmanblob->correct(&blobMat);//加上测量结果得到最优估算 } } }
[ [ [ 1, 298 ] ] ]
d55bd3c2f8c629bfed0fe98934bd40d133c6a5ef
296387b2289a05b29cf72e276e0fc9c9db82e42f
/qt/chap02/find/debug/moc_finddialog.cpp
ec9cf66db0fdfbc29bc3fba4f1f7e35b772b50e7
[]
no_license
jaykrell/jsvn
c469435ece6e8b11a4a9e6dd5bb4e500574b17ac
474b5afe0a515fe384de4bfb16f7483a25ead6ca
refs/heads/master
2020-04-01T19:27:12.846133
2011-10-16T22:16:03
2011-10-16T22:16:03
60,684,877
1
0
null
null
null
null
UTF-8
C++
false
false
3,265
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'finddialog.h' ** ** Created: Sat Nov 25 18:44:18 2006 ** by: The Qt Meta Object Compiler version 59 (Qt 4.2.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../finddialog.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'finddialog.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 59 #error "This file was generated using the moc from 4.2.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif static const uint qt_meta_data_FindDialog[] = { // content: 1, // revision 0, // classname 0, 0, // classinfo 4, 10, // methods 0, 0, // properties 0, 0, // enums/sets // signals: signature, parameters, type, tag, flags 14, 12, 11, 11, 0x05, 52, 12, 11, 11, 0x05, // slots: signature, parameters, type, tag, flags 94, 11, 11, 11, 0x08, 108, 11, 11, 11, 0x08, 0 // eod }; static const char qt_meta_stringdata_FindDialog[] = { "FindDialog\0\0,\0findNext(QString,Qt::CaseSensitivity)\0" "findPrevious(QString,Qt::CaseSensitivity)\0findClicked()\0" "enableFindButton(QString)\0" }; const QMetaObject FindDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_FindDialog, qt_meta_data_FindDialog, 0 } }; const QMetaObject *FindDialog::metaObject() const { return &staticMetaObject; } void *FindDialog::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_FindDialog)) return static_cast<void*>(const_cast<FindDialog*>(this)); return QDialog::qt_metacast(_clname); } int FindDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: findNext((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< Qt::CaseSensitivity(*)>(_a[2]))); break; case 1: findPrevious((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< Qt::CaseSensitivity(*)>(_a[2]))); break; case 2: findClicked(); break; case 3: enableFindButton((*reinterpret_cast< const QString(*)>(_a[1]))); break; } _id -= 4; } return _id; } // SIGNAL 0 void FindDialog::findNext(const QString & _t1, Qt::CaseSensitivity _t2) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void FindDialog::findPrevious(const QString & _t1, Qt::CaseSensitivity _t2) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); }
[ [ [ 1, 93 ] ] ]
92826e8596bd5503ec403b591ddc04bd7d2e15b0
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/dependencies/include/ParticleUniverse/ParticleUniverseObserverFactory.h
c43e794a54b5aa54eff0c60f7a865ce591e6f7d0
[]
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
1,940
h
/* ----------------------------------------------------------------------------------------------- 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. ----------------------------------------------------------------------------------------------- */ #ifndef __PU_OBSERVER_FACTORY_H__ #define __PU_OBSERVER_FACTORY_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseObserver.h" #include "ParticleUniverseObserverTokens.h" #include "ParticleUniverseScriptDeserializer.h" #include "ParticleUniverseScriptReader.h" namespace ParticleUniverse { /** This is the base factory of all ParticleObserver implementations. */ class _ParticleUniverseExport ParticleObserverFactory : public ScriptReader, public ScriptWriter, public Ogre::FactoryAlloc { protected: /** */ template <class T> ParticleObserver* _createObserver(void) { ParticleObserver* particleObserver = OGRE_NEW_T(T, Ogre::MEMCATEGORY_SCENE_OBJECTS)(); particleObserver->setObserverType(getObserverType()); return particleObserver; }; public: ParticleObserverFactory(void) {}; virtual ~ParticleObserverFactory(void) {}; /** Returns the type of the factory, which identifies the particle observer type this factory creates. */ virtual Ogre::String getObserverType(void) const = 0; /** Creates a new observer instance. @remarks */ virtual ParticleObserver* createObserver(void) = 0; /** Delete an observer */ void destroyObserver (ParticleObserver* observer) { OGRE_DELETE_T(observer, ParticleObserver, Ogre::MEMCATEGORY_SCENE_OBJECTS); }; }; } #endif
[ [ [ 1, 60 ] ] ]
3c47e196272f99b95068286a9258517ef1a32f92
5a48b6a95f18598181ef75dba2930a9d1720deae
/LuaEngine/LuaPlus/LuaPlus/LuaFunction.h
14dc97a1ba78509f1f8e8aec81d6a33871d8563e
[]
no_license
CBE7F1F65/f980f016e8cbe587c9148f07b799438c
078950c80e3680880bc6b3751fcc345ebc8fe8e5
1aaed5baef10a5b9144f20603d672ea5ac76b3cc
refs/heads/master
2021-01-15T10:42:46.944415
2010-08-28T19:25:48
2010-08-28T19:25:48
32,192,651
0
0
null
null
null
null
UTF-8
C++
false
false
6,212
h
/////////////////////////////////////////////////////////////////////////////// // This source file is part of the LuaPlus source distribution and is Copyright // 2001-2004 by Joshua C. Jensen ([email protected]). // // The latest version may be obtained from http://wwhiz.com/LuaPlus/. // // The code presented in this file may be used in any environment it is // acceptable to use Lua. /////////////////////////////////////////////////////////////////////////////// #ifdef _MSC_VER #pragma once #endif // _MSC_VER #ifndef LUAFUNCTION_H #define LUAFUNCTION_H #include "LuaPlusInternal.h" #include "LuaAutoBlock.h" #include <Windows.h> namespace LuaPlus { #define LUAFUNCTION_PRECALL() \ lua_State* L = m_functionObj.GetCState(); \ LuaAutoBlock autoBlock(L); \ m_functionObj.Push(); #define LUAFUNCTION_POSTCALL(numArgs) \ if (lua_pcall(L, numArgs, 1, 0)) \ { \ const char* errorString = lua_tostring(L, -1); (void)errorString; \ LuaState * ls = m_functionObj.GetState(); \ ls->SetError(errorString); \ } \ return LPCD::Get(LPCD::TypeWrapper<RT>(), L, -1); /** **/ template <typename RT> class LuaFunction { public: LuaFunction(LuaObject& functionObj) : m_functionObj(functionObj) { luaplus_assert(m_functionObj.IsFunction()); } LuaFunction(LuaState* state, const char* functionName) { m_functionObj = state->GetGlobals()[functionName]; luaplus_assert(m_functionObj.IsFunction()); } RT operator()() { LUAFUNCTION_PRECALL(); LUAFUNCTION_POSTCALL(0); } template <typename P1> RT operator()(P1 p1) { LUAFUNCTION_PRECALL(); LPCD::Push(L, p1); LUAFUNCTION_POSTCALL(1); } template <typename P1, typename P2> RT operator()(P1 p1, P2 p2) { LUAFUNCTION_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LUAFUNCTION_POSTCALL(2); } template <typename P1, typename P2, typename P3> RT operator()(P1 p1, P2 p2, P3 p3) { LUAFUNCTION_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LPCD::Push(L, p3); LUAFUNCTION_POSTCALL(3); } template <typename P1, typename P2, typename P3, typename P4> RT operator()(P1 p1, P2 p2, P3 p3, P4 p4) { LUAFUNCTION_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LPCD::Push(L, p3); LPCD::Push(L, p4); LUAFUNCTION_POSTCALL(4); } template <typename P1, typename P2, typename P3, typename P4, typename P5> RT operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { LUAFUNCTION_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LPCD::Push(L, p3); LPCD::Push(L, p4); LPCD::Push(L, p5); LUAFUNCTION_POSTCALL(5); } template <typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> RT operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) { LUAFUNCTION_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LPCD::Push(L, p3); LPCD::Push(L, p4); LPCD::Push(L, p5); LPCD::Push(L, p6); LUAFUNCTION_POSTCALL(6); } template <typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> RT operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) { LUAFUNCTION_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LPCD::Push(L, p3); LPCD::Push(L, p4); LPCD::Push(L, p5); LPCD::Push(L, p6); LPCD::Push(L, p7); LUAFUNCTION_POSTCALL(7); } protected: LuaObject m_functionObj; }; #define LUAFUNCTIONVOID_PRECALL() \ lua_State* L = m_functionObj.GetCState(); \ LuaAutoBlock autoBlock(L); \ m_functionObj.Push(); #define LUAFUNCTIONVOID_POSTCALL(numArgs) \ if (lua_pcall(L, numArgs, 1, 0)) \ { \ const char* errorString = lua_tostring(L, -1); (void)errorString;\ luaplus_assert(0); \ } /** **/ class LuaFunctionVoid { public: LuaFunctionVoid(const LuaObject& functionObj) : m_functionObj(functionObj) { luaplus_assert(m_functionObj.IsFunction()); } LuaFunctionVoid(LuaState* state, const char* functionName) { m_functionObj = state->GetGlobals()[functionName]; luaplus_assert(m_functionObj.IsFunction()); } void operator()() { LUAFUNCTIONVOID_PRECALL(); LUAFUNCTIONVOID_POSTCALL(0); } template <typename P1> void operator()(P1 p1) { LUAFUNCTIONVOID_PRECALL(); LPCD::Push(L, p1); LUAFUNCTIONVOID_POSTCALL(1); } template <typename P1, typename P2> void operator()(P1 p1, P2 p2) { LUAFUNCTIONVOID_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LUAFUNCTIONVOID_POSTCALL(2); } template <typename P1, typename P2, typename P3> void operator()(P1 p1, P2 p2, P3 p3) { LUAFUNCTIONVOID_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LPCD::Push(L, p3); LUAFUNCTIONVOID_POSTCALL(3); } template <typename P1, typename P2, typename P3, typename P4> void operator()(P1 p1, P2 p2, P3 p3, P4 p4) { LUAFUNCTIONVOID_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LPCD::Push(L, p3); LPCD::Push(L, p4); LUAFUNCTIONVOID_POSTCALL(4); } template <typename P1, typename P2, typename P3, typename P4, typename P5> void operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { LUAFUNCTIONVOID_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LPCD::Push(L, p3); LPCD::Push(L, p4); LPCD::Push(L, p5); LUAFUNCTIONVOID_POSTCALL(5); } template <typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> void operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) { LUAFUNCTIONVOID_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LPCD::Push(L, p3); LPCD::Push(L, p4); LPCD::Push(L, p5); LPCD::Push(L, p6); LUAFUNCTIONVOID_POSTCALL(6); } template <typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> void operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) { LUAFUNCTIONVOID_PRECALL(); LPCD::Push(L, p1); LPCD::Push(L, p2); LPCD::Push(L, p3); LPCD::Push(L, p4); LPCD::Push(L, p5); LPCD::Push(L, p6); LPCD::Push(L, p7); LUAFUNCTIONVOID_POSTCALL(7); } protected: LuaObject m_functionObj; }; } // namespace LuaPlus #endif // LUAFUNCTION_H
[ "CBE7F1F65@120521f8-859b-11de-8382-973a19579e60" ]
[ [ [ 1, 263 ] ] ]
69dcd07d5236025f828209d28511e8e215062978
563e71cceb33a518f53326838a595c0f23d9b8f3
/v3/ProcCity/ProcCity/Util/Segment.h
9506f3b8f414f143e52a37f81d7492c6e821fa58
[]
no_license
fabio-miranda/procedural
3d937037d63dd16cd6d9e68fe17efde0688b5a0a
e2f4b9d34baa1315e258613fb0ea66d1235a63f0
refs/heads/master
2021-05-28T18:13:57.833985
2009-10-07T21:09:13
2009-10-07T21:09:13
39,636,279
1
1
null
null
null
null
UTF-8
C++
false
false
344
h
#ifndef SEGMENT_H #define SEGMENT_H #include "GL/glew.h" #include "Vector3.h" template <typename T> class Segment{ private: Vector3<T> point1; Vector3<T> point2; public: Segment(T x1, T y1, T z1, T x2, T y2, T z2){ point1 = new Vector3<T>(x1, y1, z1); point2 = new Vector3<T>(x2, y2, z2); } }; #endif
[ "fabiom@01b71de8-32d4-11de-96ab-f16d9912eac9" ]
[ [ [ 1, 26 ] ] ]
703cc420f258739dbb46ae0ba7c7508cce874602
3699ee70db05a390ce86e64e09e779263510df6f
/branches/Common/SocketServer.cpp
b66ef977b0beddf261a06beec77a2c5c7a3eb913
[]
no_license
trebor57/osprosedev
4fbe6616382ccd98e45c8c24034832850054a4fc
71852cac55df1dbe6e5d6f4264a2a2e6fd3bb506
refs/heads/master
2021-01-13T01:50:47.003277
2008-05-14T17:48:29
2008-05-14T17:48:29
32,129,756
0
0
null
null
null
null
UTF-8
C++
false
false
16,132
cpp
/* Rose Online Server Emulator Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. developed with Main erose/hrose source server + some change from the original eich source */ #include "sockets.h" // Constructor CServerSocket::CServerSocket( ) { ConnectedClients = 0; } // Destructor CServerSocket::~CServerSocket( ) { } // Start up our server bool CServerSocket::StartServer( ) { //struct sockaddr_in ain; sock = socket( AF_INET, SOCK_STREAM, 0 ); if (sock == INVALID_SOCKET) { Log( MSG_FATALERROR, "Could not create a socket" ); return false; } int optval = 1; if(setsockopt(sock, SOL_SOCKET,SO_KEEPALIVE,(const char*)&optval,sizeof(optval))==-1) { Log(MSG_ERROR, "setsockopt:SO_KEEPALIVE" ); } setsockopt(sock, IPPROTO_TCP,TCP_NODELAY,(const char*)&optval,sizeof(optval)); ain.sin_family = AF_INET; ain.sin_addr.s_addr = INADDR_ANY; ain.sin_port = htons( port ); memset(&(ain.sin_zero), '\0', 8); if ( bind( sock, (const sockaddr*)&ain, sizeof( struct sockaddr ) ) ) { Log( MSG_FATALERROR, "Could not bind socket" ); closesocket( sock ); sock = INVALID_SOCKET; return false; } if ( listen( sock, SOMAXCONN ) == -1 ) { Log( MSG_FATALERROR, "Could not listen on socket" ); closesocket( sock ); sock = INVALID_SOCKET; return false; } if (LOG_THISSERVER == LOG_CHARACTER_SERVER) { //struct sockaddr_in ain; sckISC = socket( AF_INET, SOCK_STREAM, 0 ); if (sckISC == INVALID_SOCKET) { Log( MSG_ERROR, "Could not create valid ISC socket (WSK2 ERROR: %i)", WSAGetLastError( ) ); return false; } int optval = 1; if(setsockopt(sckISC, SOL_SOCKET,SO_KEEPALIVE,(const char*)&optval,sizeof(optval))==-1) { Log(MSG_ERROR, "setsockopt:SO_KEEPALIVE" ); } setsockopt(sckISC, IPPROTO_TCP,TCP_NODELAY,(const char*)&optval,sizeof(optval)); sain.sin_family = AF_INET; sain.sin_addr.s_addr = INADDR_ANY; sain.sin_port = htons( Config.CharsPort);//29110 ); memset(&(sain.sin_zero), '\0', 8); if ( bind( sckISC, (const sockaddr*)&sain, sizeof( struct sockaddr ) ) ) { Log( MSG_FATALERROR, "Could not bind socket" ); closesocket( sckISC ); sckISC = INVALID_SOCKET; return false; } if ( listen( sckISC, SOMAXCONN ) == -1 ) { Log( MSG_FATALERROR, "Could not listen on socket" ); closesocket( sckISC ); sckISC = INVALID_SOCKET; return false; } Log( MSG_INFO, "opened ISC poort %i",29110 ); } if (LOG_THISSERVER == LOG_WORLD_SERVER) { struct sockaddr_in ain; sckISC = socket( AF_INET, SOCK_STREAM, 0 ); if (sckISC == INVALID_SOCKET) { Log( MSG_ERROR, "Could not create valid ISC socket (WSK2 ERROR: %i)", WSAGetLastError( ) ); return false; } ain.sin_family = AF_INET; ain.sin_addr.s_addr = inet_addr(Config.CharIP);//( "127.0.0.1" ); ain.sin_port = htons( Config.CharPort);//29110 ); if ( connect( sckISC, (const sockaddr*)&ain, sizeof( ain ) ) == SOCKET_ERROR ) { Log( MSG_ERROR, "Could not connect to ISC (WSK2 ERROR: %i)", WSAGetLastError( ) ); closesocket( sckISC ); sckISC = INVALID_SOCKET; return false; } sckISCII = socket( AF_INET, SOCK_STREAM, 0 ); if (sckISCII == INVALID_SOCKET) { Log( MSG_ERROR, "Could not create valid ISC socket (WSK2 ERROR: %i)", WSAGetLastError( ) ); return false; } int optval = 1; if(setsockopt(sckISCII, SOL_SOCKET,SO_KEEPALIVE,(const char*)&optval,sizeof(optval))==-1) { Log(MSG_ERROR, "setsockopt:SO_KEEPALIVE" ); } setsockopt(sckISCII, IPPROTO_TCP,TCP_NODELAY,(const char*)&optval,sizeof(optval)); sain.sin_family = AF_INET; sain.sin_addr.s_addr = INADDR_ANY; sain.sin_port = htons( Config.WorldsPort );//29210 ); memset(&(sain.sin_zero), '\0', 8); if ( bind( sckISCII, (const sockaddr*)&sain, sizeof( struct sockaddr ) ) ) { Log( MSG_FATALERROR, "Could not bind socket" ); closesocket( sckISCII ); sckISCII = INVALID_SOCKET; return false; } if ( listen( sckISCII, SOMAXCONN ) == -1 ) { Log( MSG_FATALERROR, "Could not listen on socket" ); closesocket( sckISCII ); sckISCII = INVALID_SOCKET; return false; } Log( MSG_INFO, "opened ISC poort %i",Config.WorldsPort );//29210 ); } if (LOG_THISSERVER == LOG_LOGIN_SERVER) { struct sockaddr_in ain; sckISC = socket( AF_INET, SOCK_STREAM, 0 ); if (sckISC == INVALID_SOCKET) { Log( MSG_ERROR, "Could not create valid ISC socket (WSK2 ERROR: %i)", WSAGetLastError( ) ); return false; } } isActive = true; if ( !this->OnServerReady( ) ) { Log( MSG_FATALERROR, "Server could not start" ); closesocket( sock ); sock = INVALID_SOCKET; isActive = false; return false; } Log( MSG_INFO, "Server started on port %i and is listening.", port ); //ISCThread( ); ServerLoop( ); // Nothing past here is ever really called OnServerDie( ); closesocket( sock ); return true; } // Raven0123 void CServerSocket::CryptISCPak( char* pak ) { return; unsigned paksize = *((unsigned short*)&pak[0]); for( unsigned short i = 2; i < paksize; i ++ ) pak[i] ^= 0x81 * i * paksize; } // Raven0123 //void CServerSocket::ISCThread() bool CClientSocket::ISCThread() { unsigned char buffer[0x400]; unsigned recvd = 0; unsigned bufsize = 0; unsigned readlen = 6; bool go = true; //Log( MSG_INFO, "ISC Communication Active" ); do { //Sleep( 1 ); recvd = recv( sock, (char*)&buffer[bufsize], readlen-bufsize, 0 ); if( recvd == 0){ //Log( MSG_ERROR, "Server Disconected!" ); return false; } if( recvd == SOCKET_ERROR ) { //Log( MSG_INFO, "Server Disconected!" ); return false; } bufsize += recvd; if( bufsize != readlen ) continue;//return;//continue; if( bufsize == 6 ) { readlen = *((unsigned short*)&buffer[0]); if( readlen < 6 ) Log( MSG_ERROR, "Invalid server Packet Header" ); if( readlen > 6 ) continue;//return;//continue; } //CryptISCPak( &buffer[0] ); //GS->ReceivedISCPacket( (CPacket*)&buffer[0] ); GS->OnReceivePacket( this, (CPacket*)&buffer[0] ); go = false; //Log( MSG_INFO, "ISC Communication finished" ); bufsize = 0; readlen = 6; } while ( go==true ); return true; } // Server is started, lets run our loop :D void CServerSocket::ServerLoop( ) { fd_set fds; int activity; maxfd = 0; sockaddr_in ClientInfo; SOCKET NewSocket; timeval timeout; maxfd = sock; OnServerStep(); do { timeout.tv_sec = 0; timeout.tv_usec = 1000; NewSocket = INVALID_SOCKET; FD_ZERO( &fds ); if(!Config.usethreads) FillFDS( &fds ); FD_SET( sock, &fds ); activity = select( maxfd+1, &fds, NULL, NULL, &timeout ); if ( activity == 0 ) { // continue; FD_ZERO( &fds ); if(!Config.usethreads) FillFDS( &fds ); FD_SET( sckISC, &fds ); activity = select( maxfd+1, &fds, NULL, NULL, &timeout ); if ( activity == 0 )continue; if ( activity < 0 && errno != EINTR ) { #ifdef _WIN32 Log( MSG_ERROR, "Select command failed. Error #%i", WSAGetLastError() ); #else Log( MSG_ERROR, "Select command failed. Error #%i", errno ); #endif isActive = false; } if ( FD_ISSET( sckISC, &fds ) ) { int clientinfolen = sizeof( sockaddr_in ); #ifdef _WIN32 NewSocket = accept( sckISC, (sockaddr*)&ClientInfo, (int*)&clientinfolen ); #else NewSocket = accept( sckISC, (sockaddr*)&ClientInfo, (socklen_t*)&clientinfolen ); #endif // TODO: check if server is full if (NewSocket != INVALID_SOCKET) { AddUser( NewSocket, &ClientInfo, true ); } else { #ifdef _WIN32 Log( MSG_ERROR, "Error accepting socket: %i", WSAGetLastError() ); #else Log( MSG_ERROR, "Error accepting socket: %i", errno ); #endif } } } if ( activity < 0 && errno != EINTR ) { #ifdef _WIN32 Log( MSG_ERROR, "Select command failed. Error #%i", WSAGetLastError() ); #else Log( MSG_ERROR, "Select command failed. Error #%i", errno ); #endif isActive = false; } if ( FD_ISSET( sock, &fds ) ) { int clientinfolen = sizeof( sockaddr_in ); #ifdef _WIN32 NewSocket = accept( sock, (sockaddr*)&ClientInfo, (int*)&clientinfolen ); #else NewSocket = accept( sock, (sockaddr*)&ClientInfo, (socklen_t*)&clientinfolen ); #endif // TODO: check if server is full if (NewSocket != INVALID_SOCKET) AddUser( NewSocket, &ClientInfo, false ); else { #ifdef _WIN32 Log( MSG_ERROR, "Error accepting socket: %i", WSAGetLastError() ); #else Log( MSG_ERROR, "Error accepting socket: %i", errno ); #endif } } if(!Config.usethreads) HandleClients( &fds ); } while( isActive ); } // Fills out an FDS for the server void CServerSocket::FillFDS( fd_set* fds ) { for(UINT i=0;i<ClientList.size( );i++) { CClientSocket* client = ClientList.at( i ); if(client->isActive) { FD_SET( (unsigned)client->sock, fds ); if(client->sock>maxfd) maxfd=client->sock; } else { DisconnectClient( client ); } } } // Handle all our clients void CServerSocket::HandleClients( fd_set* fds ) { for(UINT i=0;i<ClientList.size( );i++) { CClientSocket* client = ClientList.at( i ); if(!client->isActive) continue; if(FD_ISSET( client->sock, fds )) {//Log( MSG_INFO,"port %s",inet_ntoa( client->clientinfo.sin_addr )); //Log( MSG_INFO,"Info %d", ntohs(client->clientinfo.sin_port)); //Log( MSG_INFO,"Info %d", ntohs(ain.sin_port)); if (client->isserver == true) { //Log( MSG_INFO,"ISC PACKET"); if(!client->ISCThread()){ client->isActive = false; DisconnectClient( client );} } else if(!client->ReceiveData( ) ) { client->isActive = false; DisconnectClient( client ); } } } } // Add a new user to our server void CServerSocket::AddUser( SOCKET sock, sockaddr_in* ClientInfo, bool server ) { ConnectedClients++; CClientSocket* thisclient = this->CreateClientSocket( ); if (thisclient==NULL) { closesocket( thisclient->sock ); if (thisclient!=0) delete thisclient; thisclient=0; return; } thisclient->CryptTable = CryptTable; thisclient->CryptStatus.CurAddValue = 0; thisclient->CryptStatus.CurEncryptionValue = CryptTable->EncryptionStartValue; thisclient->GS = this; thisclient->sock = sock; thisclient->isActive = true; if (!OnClientConnect( thisclient )) { closesocket( thisclient->sock ); if (thisclient!=0) delete thisclient; thisclient=0; return; } thisclient->ClientIP = ""; thisclient->ClientIP = inet_ntoa( ClientInfo->sin_addr ); char *tmp; memset(&thisclient->ClientSubNet, '\0', 12 ); sprintf(thisclient->ClientSubNet, "%i.%i.%i", (ClientInfo->sin_addr.s_addr )&0xFF, (ClientInfo->sin_addr.s_addr>>8 )&0xFF, (ClientInfo->sin_addr.s_addr>>16)&0xFF); ClientList.push_back( thisclient ); if(Config.usethreads) { pthread_create( &threads[sock], NULL, ClientMainThread, (PVOID)thisclient); } memcpy( &thisclient->clientinfo, ClientInfo, sizeof(struct sockaddr_in)); if(server==true) { thisclient->isserver=true; Log( MSG_INFO, "Server connected from %s", inet_ntoa( ClientInfo->sin_addr ) ); } else { thisclient->isserver=false; Log( MSG_INFO, "User connected from %s", inet_ntoa( ClientInfo->sin_addr ) ); } } // Disconnect our user void CServerSocket::DisconnectClient( CClientSocket* thisclient ) { ConnectedClients--; OnClientDisconnect( thisclient ); closesocket( thisclient->sock ); thisclient->isActive = false; thisclient->sock = INVALID_SOCKET; for(UINT i=0;i<ClientList.size( );i++) { CClientSocket* client = ClientList.at( i ); if( client == thisclient ) { ClientList.erase( ClientList.begin( ) + i ); break; } } DeleteClientSocket( thisclient ); } // This function creates an appropriate client socket CClientSocket* CServerSocket::CreateClientSocket ( ) { CClientSocket* thisclient; thisclient = new (nothrow) CClientSocket( ); return thisclient; } // This function deletes an old client socket void CServerSocket::DeleteClientSocket( CClientSocket* thisclient ) { if (thisclient->isserver) Log( MSG_INFO, "Server disconnected" ); else Log( MSG_INFO, "User disconnected" ); delete thisclient; } //This function loads the encryption void CServerSocket::LoadEncryption( ) { GenerateCryptTables( CryptTable, 0x87654321 ); //port = ConfigGetInt("server.conf", "loginport", 29000); } // This function is called just before proccessing clients void CServerSocket::OnServerStep( ) { } // This function is called just before the server starts bool CServerSocket::OnServerReady( ) { return true; } // This function is called just before the server dies void CServerSocket::OnServerDie( ) { // DOESNT WORK - DAMN CONSOLE APPS } // This function is called, if a client receives data bool CServerSocket::OnReceivePacket( CClientSocket* thisclient, CPacket *P ) { return true; } // This function is called, if a client connects bool CServerSocket::OnClientConnect( CClientSocket* thisclient ) { return true; } // This function is called, if a client disconnects void CServerSocket::OnClientDisconnect( CClientSocket* thisclient ) { } // Raven0123 void CServerSocket::SendISCPacket( CPacket* pak ) { //CryptISCPak( (char*)pak ); send( sckISC, (char*)pak, pak->Size, 0 ); } void CServerSocket::ReceivedISCPacket( CPacket* pak ) { Log( MSG_DEBUG, "GOT ISC PACKET (BASESERVER) - 0x%04x %04x", pak->Command, pak->Size ); } bool CServerSocket::DoSQL(char *Format, ...) { int retval; char Buffer[0x1500]; va_list ap; va_start( ap, Format ); vsprintf( Buffer, Format, ap ); va_end ( ap ); retval = mysql_query( mysql, Buffer ); if( retval != 0 ) Log( MSG_ERROR, "MySQL Query Error '%s'", mysql_error( mysql ) ); return (retval==0); }
[ "remichael@004419b5-314d-0410-88ab-2927961a341b" ]
[ [ [ 1, 537 ] ] ]
245aa6206a9e1dfbf2dd9f960449f94364f37400
465943c5ffac075cd5a617c47fd25adfe496b8b4
/AIRPORT.CPP
bfc47390e73cad6b08e22b07ec491cbf21de6fb4
[]
no_license
paulanthonywilson/airtrafficcontrol
7467f9eb577b24b77306709d7b2bad77f1b231b7
6c579362f30ed5f81cabda27033f06e219796427
refs/heads/master
2016-08-08T00:43:32.006519
2009-04-09T21:33:22
2009-04-09T21:33:22
172,292
1
0
null
null
null
null
UTF-8
C++
false
false
1,207
cpp
# include "airport.h" /**************************************************************************/ Airport::Airport ( Position GrndPos_i, int ID_i, const Heading &Dir_i ) : Destination (GrndPos_i, ID_i, Dir_i), AtLandmark (GrndPos_i, ID_i), Landmark (GrndPos_i, ID_i) { assert (GrndPos_i.inField()); } /**************************************************************************/ Boolean Airport::IsSafeCoords(Vector3D Coords_i) { // Note ver 0.4 safe landing direction reversed from previous versions return ( Coords_i.GrndPos == GrndPos_c && Coords_i.Head == Dir_c && Coords_i.Altitude == LANDING_ALTITUDE ); } /**************************************************************************/ Vector3D Airport::NewPlaneCoords () { return Vector3D ( GrndPos_c, Dir_c, TAKEOFF_ALTITUDE ); } /**************************************************************************/ PlaneState Airport::NewPlaneState () { return PlaneHolding; } /**************************************************************************/ LandmarkTypeId Airport::LandmarkType () { return TypeAirport; }
[ [ [ 1, 55 ] ] ]
ef9ba62f82e347041463c8eead7281e4bd9e8fe0
bdb1e38df8bf74ac0df4209a77ddea841045349e
/CapsuleSortor/Version 1.0 -2.0/CapsuleSortor-10-11-12/CapsuleSortor-10-11-12/ImageCard/Genie/include/SapManager.h
53eded57460d3972b5be6f536965da351c5114cd
[]
no_license
Strongc/my001project
e0754f23c7818df964289dc07890e29144393432
07d6e31b9d4708d2ef691d9bedccbb818ea6b121
refs/heads/master
2021-01-19T07:02:29.673281
2010-12-17T03:10:52
2010-12-17T03:10:52
49,062,858
0
1
null
2016-01-05T11:53:07
2016-01-05T11:53:07
null
UTF-8
C++
false
false
23,746
h
#ifndef _SAPMANAGER_H_ #define _SAPMANAGER_H_ // SapManager.h : header file // #include "SapClassBasicDef.h" // // SapLocation class declaration // class SAPCLASSBASIC_CLASS SapLocation { public: // Common server indices enum ServerIndex { ServerUnknown = -1, ServerSystem = 0 }; // Common resource indices enum ResourceIndex { ResourceUnknown = -1 }; public: // Constructor/Destructor SapLocation() { m_ServerIndex = ServerSystem; CorStrncpy(m_ServerName, "", CORSERVER_MAX_STRLEN); m_ResourceIndex = 0; } SapLocation(int serverIndex, int resourceIndex = 0) { m_ServerIndex = serverIndex; CorStrncpy(m_ServerName, "", CORSERVER_MAX_STRLEN); m_ResourceIndex = resourceIndex; } SapLocation(const char *serverName, int resourceIndex = 0) { m_ServerIndex = ServerUnknown; CorStrncpy(m_ServerName, serverName, CORSERVER_MAX_STRLEN); m_ServerName[CORSERVER_MAX_STRLEN - 1] = '\0'; m_ResourceIndex = resourceIndex; } SapLocation(const SapLocation &loc) { m_ServerIndex = loc.m_ServerIndex; CorStrncpy(m_ServerName, loc.m_ServerName, CORSERVER_MAX_STRLEN); m_ResourceIndex = loc.m_ResourceIndex; } SapLocation(const SapLocation &loc, int resourceIndex) { m_ServerIndex = loc.m_ServerIndex; CorStrncpy(m_ServerName, loc.m_ServerName, CORSERVER_MAX_STRLEN); m_ResourceIndex = resourceIndex; } virtual ~SapLocation() {} int GetServerIndex() const { return m_ServerIndex; } const char *GetServerName() const { return m_ServerName; } int GetResourceIndex() const { return m_ResourceIndex; } BOOL IsUnknown() const { return m_ServerIndex < 0 && !strlen(m_ServerName); } // Obsolete method BOOL IsNull() const { return IsUnknown(); } protected: int m_ServerIndex; char m_ServerName[CORSERVER_MAX_STRLEN]; int m_ResourceIndex; }; // These macros that may only be called from SapManager derived classes // Set current function name for error messages #define SAP_FUNCNAME(funcName) \ static char *sapFuncName = funcName; // Check for an error condition with possible arguments for formatting the error message #define SAP_CHECK(errorCondition, errorMsg, statement) \ if ((errorCondition)) \ { \ if (strlen(errorMsg) != 0) \ DisplayMessageAndSave(sapFuncName, errorMsg, __FILE__, __LINE__); \ statement; \ } // Signal an error condition #define SAP_ERROR(errorMsg, statement) \ { \ if (strlen(errorMsg) != 0) \ DisplayMessageAndSave(sapFuncName, errorMsg, __FILE__, __LINE__); \ statement; \ } // Valid only for classes that implement the Destroy() method #define SAP_DESTROY(errorMsg, statement) \ { \ if (strlen(errorMsg) != 0) \ DisplayMessageAndSave(sapFuncName, errorMsg, __FILE__, __LINE__); \ Destroy(); \ statement; \ } // Show a message for the current function with one possible arguments for formatting #define SAP_MESSAGE(message) \ { \ if (strlen(message) != 0) \ DisplayMessage(sapFuncName, message, __FILE__, __LINE__); \ } // Forward declarations class SAPCLASSBASIC_CLASS SapManCallbackInfo; class SAPCLASSBASIC_CLASS SapInterface; class SAPCLASSBASIC_CLASS SapResourceInfo; typedef void (*SapManCallback)(SapManCallbackInfo *); // // SapManager class declaration // class SAPCLASSBASIC_CLASS SapManager { public: // Server types typedef int ServerType; // For compatibility with old Sapera++ application code enum _ServerType { ServerNone = 0, ServerSystem = CORPORT_SYSTEM, ServerCobra = CORPORT_COBRA, // No longer officially supported ServerViperRgb = CORPORT_VIPERRGB, ServerViperDigital = CORPORT_VIPERDIG, ServerViperQuad = CORPORT_VIPERQUAD, ServerViperCamLink = CORPORT_VIPERCAMLINK, ServerBanditII = CORPORT_BANDITII, ServerX64CL = CORPORT_X64, ServerX64LVDS = CORPORT_X64LVDS, ServerX64NS = CORPORT_X64NS, ServerX64Analog = CORPORT_X64AN, // Obsolete, use ServerX64ANQuad instead ServerX64ANQuad = CORPORT_X64AN, ServerX64CLiPRO = CORPORT_X64IPRO, ServerX64CLiPROe = CORPORT_X64IPROE, ServerPC2Vision = CORPORT_PC2V, ServerPC2CamLink = CORPORT_PC2C, ServerMamba = CORPORT_MAMBA, // No longer officially supported ServerAnaconda = CORPORT_ANACONDA, // Obsolete, use ServerAnacondaCL instead ServerAnacondaCL = CORPORT_ANACONDA, ServerAnacondaLVDS = CORPORT_ANACONDALVDS, ServerXriCL = CORPORT_XRICL, }; // Resource types typedef int ResType; // For compatibility with old Sapera++ application code enum _ResType { ResourceAcq = 0, ResourceDisplay, ResourceCab, ResourcePixPro, ResourceRtPro = ResourcePixPro, ResourceDsp, ResourceGraphic, ResourceGio, ResourceCounter, ResourceAcqDevice, ResourceLast = ResourceAcqDevice }; // Sapera error return codes // To be completed later if necessary enum StatusCode { StatusOk = CORSTATUS_OK, StatusInvalidHandle = CORSTATUS_INVALID_HANDLE, StatusIncompatibleAcq = CORSTATUS_INCOMPATIBLE_ACQ , StatusIncompatibleBuffer = CORSTATUS_INCOMPATIBLE_BUFFER, StatusIncompatibleCab = CORSTATUS_INCOMPATIBLE_CAB , StatusIncompatibleCam = CORSTATUS_INCOMPATIBLE_CAM, StatusIncompatibleDisplay = CORSTATUS_INCOMPATIBLE_DISPLAY, StatusIncompatibleGraphic = CORSTATUS_INCOMPATIBLE_GRAPHIC, StatusIncompatibleKernel = CORSTATUS_INCOMPATIBLE_KERNEL , StatusIncompatibleLut = CORSTATUS_INCOMPATIBLE_LUT , StatusIncompatibleManager = CORSTATUS_INCOMPATIBLE_MANAGER , StatusIncompatiblePro = CORSTATUS_INCOMPATIBLE_PRO , StatusIncompatibleVic = CORSTATUS_INCOMPATIBLE_VIC , StatusIncompatibleView = CORSTATUS_INCOMPATIBLE_VIEW, StatusIncompatibleXfer = CORSTATUS_INCOMPATIBLE_XFER, StatusIncompatibleString = CORSTATUS_INCOMPATIBLE_STRING , StatusIncompatibleObject = CORSTATUS_INCOMPATIBLE_OBJECT , StatusIncompatibleArray = CORSTATUS_INCOMPATIBLE_ARRAY , StatusIncompatibleStream = CORSTATUS_INCOMPATIBLE_STREAM , StatusIncompatibleFile = CORSTATUS_INCOMPATIBLE_FILE , StatusCapInvalid = CORSTATUS_CAP_INVALID , StatusCapNotAvailable = CORSTATUS_CAP_NOT_AVAILABLE, StatusPrmInvalid = CORSTATUS_PRM_INVALID , StatusPrmNotAvailable = CORSTATUS_PRM_NOT_AVAILABLE, StatusPrmOutOfRange = CORSTATUS_PRM_OUT_OF_RANGE , StatusPrmInvalidValue = CORSTATUS_PRM_INVALID_VALUE, StatusPrmReadOnly = CORSTATUS_PRM_READ_ONLY , StatusPrmMutuallyExclusive = CORSTATUS_PRM_MUTUALLY_EXCLUSIVE , StatusArgInvalid = CORSTATUS_ARG_INVALID , StatusArgOutOfRange = CORSTATUS_ARG_OUT_OF_RANGE , StatusArgIncompatible = CORSTATUS_ARG_INCOMPATIBLE , StatusArgInvalidValue = CORSTATUS_ARG_INVALID_VALUE, StatusArgNull = CORSTATUS_ARG_NULL , StatusFileOptionsError = CORSTATUS_FILE_OPTIONS_ERROR, StatusFileOpenModeInvalid = CORSTATUS_FILE_OPEN_MODE_INVALID , StatusFileSeekError = CORSTATUS_FILE_SEEK_ERROR , StatusFileCreateError = CORSTATUS_FILE_CREATE_ERROR , StatusFileOpenError = CORSTATUS_FILE_OPEN_ERROR , StatusFileReadError = CORSTATUS_FILE_READ_ERROR , StatusFileWriteError = CORSTATUS_FILE_WRITE_ERROR , StatusFileCloseError = CORSTATUS_FILE_CLOSE_ERROR , StatusFileFormatUnkown = CORSTATUS_FILE_FORMAT_UNKNOWN , StatusFileFieldValueNotSupported = CORSTATUS_FILE_FIELD_VALUE_NOT_SUPPORTED , StatusFileGetFieldError = CORSTATUS_FILE_GET_FIELD_ERROR , StatusFileReadOnly = CORSTATUS_FILE_READ_ONLY , StatusFileWriteOnly = CORSTATUS_FILE_WRITE_ONLY , StatusNotImplemented = CORSTATUS_NOT_IMPLEMENTED , StatusNoMemory = CORSTATUS_NO_MEMORY , StatusClippingOccurred = CORSTATUS_CLIPPING_OCCURED, StatusHardwareError = CORSTATUS_HARDWARE_ERROR , StatusServiceNotAvailable = CORSTATUS_SERVICE_NOT_AVAILABLE , StatusNotAccessible = CORSTATUS_NOT_ACCESSIBLE , StatusNotAvailable = CORSTATUS_NOT_AVAILABLE , StatusRoutingNotImplemented = CORSTATUS_ROUTING_NOT_IMPLEMENTED, StatusRoutingNotAvailable = CORSTATUS_ROUTING_NOT_AVAILABLE , StatusRoutingInUse = CORSTATUS_ROUTING_IN_USE , StatusIncompatibleSize = CORSTATUS_INCOMPATIBLE_SIZE , StatusIncompatibleFormat = CORSTATUS_INCOMPATIBLE_FORMAT , StatusIncompatibleLocation = CORSTATUS_INCOMPATIBLE_LOCATION, StatusResourceInUse = CORSTATUS_RESOURCE_IN_USE , StatusResourceLinked = CORSTATUS_RESOURCE_LINKED , StatusSoftwareError = CORSTATUS_SOFTWARE_ERROR , StatusParametersLocked = CORSTATUS_PARAMETERS_LOCKED , StatusXferNotConnected = CORSTATUS_XFER_NOT_CONNECTED , StatusXferEmptyList = CORSTATUS_XFER_EMPTY_LIST , StatusXferCantCycle = CORSTATUS_XFER_CANT_CYCLE , StatusRoutingNotSpecified = CORSTATUS_ROUTING_NOT_SPECIFIED , StatusTransferInProgress = CORSTATUS_TRANSFER_IN_PROGRESS , StatusApiNotLocked = CORSTATUS_API_NOT_LOCKED , StatusServerNotFound = CORSTATUS_SERVER_NOT_FOUND , StatusCannotSignalEvent = CORSTATUS_CANNOT_SIGNAL_EVENT, StatusNoMessage = CORSTATUS_NO_MESSAGE , StatusTimeOut = CORSTATUS_TIMEOUT , StatusInvalidAlignment = CORSTATUS_INVALID_ALIGNMENT, StatusDdraw256Colors = CORSTATUS_DDRAW_256_COLORS , StatusPciIoError = CORSTATUS_PCI_IO_ERROR , StatusPciCannotAccessDevice = CORSTATUS_PCI_CANNOT_ACCESS_DEVICE, StatusEventCreateError = CORSTATUS_EVENT_CREATE_ERROR , StatusBoardNotReady = CORSTATUS_BOARD_NOT_READY , StatusXferMaxSize = CORSTATUS_XFER_MAX_SIZE , StatusProcessingError = CORSTATUS_PROCESSING_ERROR , StatusResourceLocked = CORSTATUS_RESOURCE_LOCKED , StatusNoMessagingMemory = CORSTATUS_NO_MESSAGING_MEMORY , StatusDdrawNotAvailable = CORSTATUS_DDRAW_NOT_AVAILABLE , StatusDdrawError = CORSTATUS_DDRAW_ERROR , StatusResourceNotLocked = CORSTATUS_RESOURCE_NOT_LOCKED, StatusDiskOnChipError = CORSTATUS_DISK_ON_CHIP_ERROR , StatusNotCompleted = CORSTATUS_NOT_COMPLETED , StatusAuthentificationFailed = CORSTATUS_AUTHENTIFICATION_FAILED , StatusInsufficientBandwidth = CORSTATUS_INSUFFICIENT_BANDWIDTH , StatusFileTellError = CORSTATUS_FILE_TELL_ERROR , StatusMaxProcessExceeded = CORSTATUS_MAX_PROCESS_EXCEEDED , StatusXferCountMultSrcFrameCount = CORSTATUS_XFER_COUNT_MULT_SRC_FRAME_COUNT , StatusAcqConnectedToXfer = CORSTATUS_ACQ_CONNECTED_TO_XFER , StatusInsufficientBoardMemory = CORSTATUS_INSUFFICIENT_BOARD_MEMORY , StatusInsufficientResources = CORSTATUS_INSUFFICIENT_RESOURCES, StatusMissingResource = CORSTATUS_MISSING_RESOURCE, StatusNoDeviceFound = CORSTATUS_NO_DEVICE_FOUND, StatusResourceNotConnected = CORSTATUS_RESOURCE_NOT_CONNECTED, StatusServerDatabaseFull = CORSTATUS_SERVER_DATABASE_FULL }; // Status reporting modes typedef int StatusMode; // For compatibility with old Sapera++ application code enum _StatusMode { StatusNotify = 0, StatusLog, StatusDebug, StatusCustom, StatusCallback }; // Manager event types typedef int EventType; enum _EventType { EventNone = 0, EventServerNew = CORMAN_VAL_EVENT_TYPE_SERVER_NEW, EventServerNotAccessible = CORMAN_VAL_EVENT_TYPE_SERVER_NOT_ACCESSIBLE, EventServerAccessible = CORMAN_VAL_EVENT_TYPE_SERVER_ACCESSIBLE, EventServerDatabaseFull = CORMAN_VAL_EVENT_TYPE_SERVER_DATABASE_FULL, EventResourceInfoChanged = CORMAN_VAL_EVENT_TYPE_RESOURCE_INFO_CHANGED }; // Various maximum values enum MiscValues { MaxServers = 40, MaxResourceTypes = ResourceLast + 1, MaxResources = 8, MaxLabelSize = 128, LockTimeout = 5000, }; public: // Constructor/Destructor SapManager(); virtual ~SapManager(); // Server-access methods static int GetServerCount(); static int GetServerCount(ResType resourceType); static int GetServerIndex(const char *serverName); static int GetServerIndex(SapLocation loc); // Note: nameSize argument (formerly bufSize) is now obsolete static BOOL GetServerName(int serverIndex, char *serverName, int nameSize = CORSERVER_MAX_STRLEN); static BOOL GetServerName(SapLocation loc, char *serverName, int nameSize = CORSERVER_MAX_STRLEN); static BOOL GetServerName(int serverIndex, ResType resourceType, char *serverName); static BOOL GetServerHandle(int serverIndex, PCORSERVER pServer); static BOOL GetServerHandle(const char *serverName, PCORSERVER pServer); static BOOL GetServerHandle(SapLocation loc, PCORSERVER pServer); static ServerType GetServerType(int serverIndex); static ServerType GetServerType(const char *serverName); static ServerType GetServerType(SapLocation loc); static BOOL IsServerAccessible(int serverIndex); static BOOL IsServerAccessible(const char *serverName); static BOOL IsServerAccessible(SapLocation loc); static BOOL GetServerSerialNumber(int serverIndex, char *serialNumber); static BOOL GetServerSerialNumber(const char *serverName, char *serialNumber); static BOOL GetServerSerialNumber(SapLocation loc, char *serialNumber); static BOOL ResetServer(int serverIndex, BOOL wait = TRUE, SapManCallback pCallback = NULL, void *pContext = NULL); static BOOL ResetServer(const char *serverName, BOOL wait = TRUE, SapManCallback pCallback = NULL, void *pContext = NULL); static BOOL ResetServer(SapLocation loc, BOOL wait = TRUE, SapManCallback pCallback = NULL, void *pContext = NULL); // Resource-access methods static int GetResourceCount(int serverIndex, ResType resourceType); static int GetResourceCount(const char *serverName, ResType resourceType); static int GetResourceCount(SapLocation loc, ResType resourceType); // Note: nameSize argument (formerly bufSize) is now obsolete static BOOL GetResourceName(int serverIndex, ResType resourceType, int resourceIndex, char *resourceName, int nameSize = MaxLabelSize); static BOOL GetResourceName(const char *serverName, ResType resourceType, int resourceIndex, char *resourceName, int nameSize = MaxLabelSize); static BOOL GetResourceName(SapLocation loc, ResType resourceType, char *resourceName, int nameSize = MaxLabelSize); static int GetResourceIndex(int serverIndex, ResType resourceType, const char *resourceName); static int GetResourceIndex(const char *serverName, ResType resourceType, const char *resourceName); static BOOL IsResourceAvailable(int serverIndex, ResType resourceType, int resourceIndex); static BOOL IsResourceAvailable(const char *serverName, ResType resourceType, int resourceIndex); static BOOL IsResourceAvailable(SapLocation loc, ResType resourceType); static BOOL GetInstallDirectory(int serverIndex, char *installDir); static BOOL GetInstallDirectory(const char *serverName, char *installDir); static BOOL GetInstallDirectory(SapLocation loc, char *installDir); // Server callback functionality static BOOL RegisterServerCallback(EventType eventType, SapManCallback callback, void *context = NULL); static BOOL UnregisterServerCallback(void); // Utility methods #if COR_LINUX static BOOL IsSystemLocation() { return TRUE; } #else static BOOL IsSystemLocation() { return CorManIsSystemHandle(CorManGetLocalServer()); } #endif static BOOL IsSystemLocation(SapLocation loc); static BOOL IsSameServer(SapLocation loc1, SapLocation loc2); static BOOL IsSameLocation(SapLocation loc1, SapLocation loc2); static int GetPixelDepthMin(SapFormat format); static int GetPixelDepthMax(SapFormat format); static SapFormatType GetFormatType(SapFormat format); static BOOL GetStringFromFormat( SapFormat format, char* txtFormat); static int GetResetTimeout() { return m_ResetTimeout; } static void SetResetTimeout(int resetTimeout) { m_ResetTimeout = resetTimeout; } // Status reporting methods static StatusMode GetDisplayStatusMode() { return m_DisplayStatusMode; } static BOOL SetDisplayStatusMode(StatusMode mode, SapManCallback pCallback = NULL, void *pContext = NULL); static SAPSTATUS DisplayStatus(const char *functionName, SAPSTATUS status); static void DisplayMessage(const char *message, const char *fileName = NULL, int lineNumber = 0, ...); static void GetLastStatus(SAPSTATUS *pLastStatus); static const char *GetLastStatus(); static BOOL IsStatusOk(const char *funcName, SAPSTATUS status) { return DisplayStatus(funcName, status) == StatusOk; } // Check if all handles were created successfully (derived classes only) operator BOOL() const {return m_bInitOK;} // Internal usage only BOOL InternalCommand(int serverIndex, int command, void *inData, int inDataSize, void *outData, int outDataSize); protected: BOOL m_bInitOK; // TRUE if all handles were created successfully (derived classes only) protected: static BOOL Open(BOOL isUserCall); static BOOL Close(BOOL isUserCall); static ServerType GetServerType(CORSERVER hServer); static BOOL GetServerSerialNumber(CORSERVER hServer, char *serialNumber); static BOOL SetResourceCount(int serverIndex, ResType resourceType); static BOOL SetResourceName(int serverIndex, ResType resourceType, int resourceIndex); static BOOL SetResourceName(SapLocation loc, ResType resourceType, CORHANDLE handle); static void DisplayMessage(const char *funcName, const char *message, const char *fileName, int lineNumber); static void DisplayMessageAndSave(const char *funcName, char *message, const char *fileName, int lineNumber); static void DisplayMessageAndSave(char *message, const char *fileName, int lineNumber); static char *FormatMessage(char *formatStr, ...); static UINT WINAPI ResetThreadProc(LPVOID lpParameter); static BOOL GetInstallDirectory(CORSERVER hServer, char *installDir); static SAPSTATUS CCONV OnServerCallback(void *context, COREVENTINFO eventInfo); protected: static SapInterface m_Interface; static SapResourceInfo m_ResourceInfo[MaxResourceTypes]; static StatusMode m_DisplayStatusMode; static int m_ResetIndex; static int m_ResetTimeout; static SapManCallback m_ResetCallback; static void *m_ResetContext; static SapManCallback m_ErrorCallback; static void *m_ErrorContext; static EventType m_ServerEventType; static SapManCallback m_ServerCallback; static void *m_ServerContext; // Tracks usage of Open and Close methods from application code static BOOL m_UserOpenDone; // Tracks automatic usage of Open and Close through the SapManager constructor static int m_InternalOpenCount; }; // // SapManCallbackInfo class declaration // class SAPCLASSBASIC_CLASS SapManCallbackInfo { public: enum MaxValues { MaxMessageSize = 255 }; public: SapManCallbackInfo(int serverIndex, void *context) { Construct(SapManager::EventNone, serverIndex, 0, context, SapManager::StatusOk, NULL); } SapManCallbackInfo(SapManager::EventType eventType, int serverIndex, void *context) { Construct(eventType, serverIndex, 0, context, SapManager::StatusOk, NULL); } SapManCallbackInfo(SapManager::EventType eventType, int serverIndex, int resourceIndex, void *context) { Construct(eventType, serverIndex, resourceIndex, context, SapManager::StatusOk, NULL); } SapManCallbackInfo(SAPSTATUS errorValue, const char *errorMessage, void *context) { Construct(SapManager::EventNone, 0, 0, context, errorValue, errorMessage); } ~SapManCallbackInfo() {} SapManager::EventType GetEventType() const { return m_EventType; } int GetServerIndex() const { return m_ServerIndex; } int GetResourceIndex() const { return m_ResourceIndex; } void *GetContext() const { return m_Context; } SAPSTATUS GetErrorValue() const { return m_ErrorValue; } const char *GetErrorMessage() const { return m_ErrorMessage; } protected: void Construct(SapManager::EventType eventType, int serverIndex, int resourceIndex, void *context, SAPSTATUS errorValue, const char *errorMessage) { m_EventType = eventType; m_ServerIndex = serverIndex; m_ResourceIndex = resourceIndex; m_Context = context; m_ErrorValue = errorValue; if (errorMessage) { // Make sure that the resulting string is null terminated, no matter how CorStrncpy is defined CorStrncpy(m_ErrorMessage, errorMessage, MaxMessageSize); m_ErrorMessage[sizeof(m_ErrorMessage) - 1] = '\0'; } } protected: SapManager::EventType m_EventType; int m_ServerIndex; int m_ResourceIndex; void *m_Context; SAPSTATUS m_ErrorValue; char m_ErrorMessage[MaxMessageSize + 1]; }; // // SapInterface class declaration // typedef SAPSTATUS (__stdcall *PGETCOUNT)( CORSERVER server, PUINT32 count); typedef SAPSTATUS (__stdcall *PGETHANDLE)( CORSERVER server, UINT32 instance, CORHANDLE *pHandle); typedef SAPSTATUS (__stdcall *PGETHANDLEREADONLY)( CORSERVER server, UINT32 instance, CORHANDLE *pHandle); typedef SAPSTATUS (__stdcall *PRELEASE)( CORHANDLE handle); typedef SAPSTATUS (__stdcall *PGETPRM)( CORHANDLE handle, UINT32 param, void *value); class SAPCLASSBASIC_CLASS SapInterface { public: static PGETCOUNT m_GetCount[SapManager::MaxResourceTypes]; static PGETHANDLE m_GetHandle[SapManager::MaxResourceTypes]; static PGETHANDLEREADONLY m_GetHandleReadOnly[SapManager::MaxResourceTypes]; static PRELEASE m_Release[SapManager::MaxResourceTypes]; static PGETPRM m_GetPrm[SapManager::MaxResourceTypes]; static int m_LabelPrm[SapManager::MaxResourceTypes]; }; // // SapResourceInfo class declaration // class SAPCLASSBASIC_CLASS SapResourceInfo { public: SapResourceInfo(); int m_Counts[SapManager::MaxServers]; char m_Labels[SapManager::MaxServers][SapManager::MaxResources][SapManager::MaxLabelSize]; BOOL m_IsLabelInitOk[SapManager::MaxServers][SapManager::MaxResources]; }; #endif // _SAPMANAGER_H_
[ "vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e" ]
[ [ [ 1, 535 ] ] ]
0062017e00149f05708b32600f547cfbf6593ecc
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/program_options/value_semantic.hpp
19971738240f91bc9dbdb6820f99b4df9418d053
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
12,148
hpp
// Copyright Vladimir Prus 2004. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_VALUE_SEMANTIC_HPP_VP_2004_02_24 #define BOOST_VALUE_SEMANTIC_HPP_VP_2004_02_24 #include <boost/program_options/config.hpp> #include <boost/program_options/errors.hpp> #include <boost/any.hpp> #include <boost/function/function1.hpp> #include <boost/lexical_cast.hpp> #include <string> #include <vector> #include <typeinfo> namespace boost { namespace program_options { /** Class which specifies how the option's value is to be parsed and converted into C++ types. */ class BOOST_PROGRAM_OPTIONS_DECL value_semantic { public: /** Returns the name of the option. The name is only meaningful for automatic help message. */ virtual std::string name() const = 0; /** The minimum number of tokens for this option that should be present on the command line. */ virtual unsigned min_tokens() const = 0; /** The maximum number of tokens for this option that should be present on the command line. */ virtual unsigned max_tokens() const = 0; /** Returns true if values from different sources should be composed. Otherwise, value from the first source is used and values from other sources are discarded. */ virtual bool is_composing() const = 0; /** Parses a group of tokens that specify a value of option. Stores the result in 'value_store', using whatever representation is desired. May be be called several times if value of the same option is specified more than once. */ virtual void parse(boost::any& value_store, const std::vector<std::string>& new_tokens, bool utf8) const = 0; /** Called to assign default value to 'value_store'. Returns true if default value is assigned, and false if no default value exists. */ virtual bool apply_default(boost::any& value_store) const = 0; /** Called when final value of an option is determined. */ virtual void notify(const boost::any& value_store) const = 0; virtual ~value_semantic() {} }; /** Helper class which perform necessary character conversions in the 'parse' method and forwards the data further. */ template<class charT> class value_semantic_codecvt_helper { // Nothing here. Specializations to follow. }; /** Helper conversion class for values that accept ascii strings as input. Overrides the 'parse' method and defines new 'xparse' method taking std::string. Depending on whether input to parse is ascii or UTF8, will pass it to xparse unmodified, or with UTF8->ascii conversion. */ template<> class BOOST_PROGRAM_OPTIONS_DECL value_semantic_codecvt_helper<char> : public value_semantic { private: // base overrides void parse(boost::any& value_store, const std::vector<std::string>& new_tokens, bool utf8) const; protected: // interface for derived classes. virtual void xparse(boost::any& value_store, const std::vector<std::string>& new_tokens) const = 0; }; /** Helper conversion class for values that accept ascii strings as input. Overrides the 'parse' method and defines new 'xparse' method taking std::wstring. Depending on whether input to parse is ascii or UTF8, will recode input to Unicode, or pass it unmodified. */ template<> class BOOST_PROGRAM_OPTIONS_DECL value_semantic_codecvt_helper<wchar_t> : public value_semantic { private: // base overrides void parse(boost::any& value_store, const std::vector<std::string>& new_tokens, bool utf8) const; protected: // interface for derived classes. #if !defined(BOOST_NO_STD_WSTRING) virtual void xparse(boost::any& value_store, const std::vector<std::wstring>& new_tokens) const = 0; #endif }; /** Class which specifies a simple handling of a value: the value will have string type and only one token is allowed. */ class BOOST_PROGRAM_OPTIONS_DECL untyped_value : public value_semantic_codecvt_helper<char> { public: untyped_value(bool zero_tokens = false) : m_zero_tokens(zero_tokens) {} std::string name() const; unsigned min_tokens() const; unsigned max_tokens() const; bool is_composing() const { return false; } /** If 'value_store' is already initialized, or new_tokens has more than one elements, throws. Otherwise, assigns the first string from 'new_tokens' to 'value_store', without any modifications. */ void xparse(boost::any& value_store, const std::vector<std::string>& new_tokens) const; /** Does nothing. */ bool apply_default(boost::any&) const { return false; } /** Does nothing. */ void notify(const boost::any&) const {} private: bool m_zero_tokens; }; /** Base class for all option that have a fixed type, and are willing to announce this type to the outside world. Any 'value_semantics' for which you want to find out the type can be dynamic_cast-ed to typed_value_base. If conversion succeeds, the 'type' method can be called. */ class typed_value_base { public: // Returns the type of the value described by this // object. virtual const std::type_info& value_type() const = 0; // Not really needed, since deletion from this // class is silly, but just in case. virtual ~typed_value_base() {} }; /** Class which handles value of a specific type. */ template<class T, class charT = char> class typed_value : public value_semantic_codecvt_helper<charT>, public typed_value_base { public: /** Ctor. The 'store_to' parameter tells where to store the value when it's known. The parameter can be NULL. */ typed_value(T* store_to) : m_store_to(store_to), m_composing(false), m_multitoken(false), m_zero_tokens(false) {} /** Specifies default value, which will be used if none is explicitly specified. The type 'T' should provide operator<< for ostream. */ typed_value* default_value(const T& v) { m_default_value = boost::any(v); m_default_value_as_text = boost::lexical_cast<std::string>(v); return this; } /** Specifies default value, which will be used if none is explicitly specified. Unlike the above overload, the type 'T' need not provide operator<< for ostream, but textual representation of default value must be provided by the user. */ typed_value* default_value(const T& v, const std::string& textual) { m_default_value = boost::any(v); m_default_value_as_text = textual; return this; } /** Specifies a function to be called when the final value is determined. */ typed_value* notifier(function1<void, const T&> f) { m_notifier = f; return this; } /** Specifies that the value is composing. See the 'is_composing' method for explanation. */ typed_value* composing() { m_composing = true; return this; } /** Specifies that the value can span multiple tokens. */ typed_value* multitoken() { m_multitoken = true; return this; } typed_value* zero_tokens() { m_zero_tokens = true; return this; } public: // value semantic overrides std::string name() const; bool is_composing() const { return m_composing; } unsigned min_tokens() const { if (m_zero_tokens) { return 0; } else { return 1; } } unsigned max_tokens() const { if (m_multitoken) { return 32000; } else if (m_zero_tokens) { return 0; } else { return 1; } } /** Creates an instance of the 'validator' class and calls its operator() to perform the actual conversion. */ void xparse(boost::any& value_store, const std::vector< std::basic_string<charT> >& new_tokens) const; /** If default value was specified via previous call to 'default_value', stores that value into 'value_store'. Returns true if default value was stored. */ virtual bool apply_default(boost::any& value_store) const { if (m_default_value.empty()) { return false; } else { value_store = m_default_value; return true; } } /** If an address of variable to store value was specified when creating *this, stores the value there. Otherwise, does nothing. */ void notify(const boost::any& value_store) const; public: // typed_value_base overrides const std::type_info& value_type() const { return typeid(T); } private: T* m_store_to; // Default value is stored as boost::any and not // as boost::optional to avoid unnecessary instantiations. boost::any m_default_value; std::string m_default_value_as_text; bool m_composing, m_implicit, m_multitoken, m_zero_tokens; boost::function1<void, const T&> m_notifier; }; /** Creates a typed_value<T> instance. This function is the primary method to create value_semantic instance for a specific type, which can later be passed to 'option_description' constructor. The second overload is used when it's additionally desired to store the value of option into program variable. */ template<class T> typed_value<T>* value(); /** @overload */ template<class T> typed_value<T>* value(T* v); /** Creates a typed_value<T> instance. This function is the primary method to create value_semantic instance for a specific type, which can later be passed to 'option_description' constructor. */ template<class T> typed_value<T, wchar_t>* wvalue(); /** @overload */ template<class T> typed_value<T, wchar_t>* wvalue(T* v); /** Works the same way as the 'value<bool>' function, but the created value_semantic won't accept any explicit value. So, if the option is present on the command line, the value will be 'true'. */ BOOST_PROGRAM_OPTIONS_DECL typed_value<bool>* bool_switch(); /** @overload */ BOOST_PROGRAM_OPTIONS_DECL typed_value<bool>* bool_switch(bool* v); }} #include "boost/program_options/detail/value_semantic.hpp" #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 356 ] ] ]
d60b538cc1086d8c89536049ff7337fd1df01790
54745d6fa529d0adcd19a41e115bbccfb804b575
/HandIndexingV1/getindex2N.h
4efadba8843222d75aaf24de93aabc130a567fc0
[]
no_license
jackylee1/regretitron
e7a5f1a8794f0150b57f3ca679438d0f38984bca
bb241e6dea4d345e48d633da48ed2cfd410a5fdf
refs/heads/master
2020-03-26T17:53:07.040365
2011-11-14T03:38:53
2011-11-14T03:38:53
145,185,451
0
1
null
2018-08-18T03:04:05
2018-08-18T03:04:04
null
UTF-8
C++
false
false
1,702
h
#ifndef __get_index2N__ #define __get_index2N__ #include "../utility.h" //for int64 #include "../PokerLibrary/constants.h" #include <vector> using std::vector; //getindex2N // mine are the PokerEval CardMask containing my hole cards. Must be 2 cards. // board are the PokerEval CardMask containing the board cards. Must contain 3, 4, or 5 cards. // boardcards is just the total number of cards in the board. Must be 3, 4, or 5. //This function will return an integer in the range 0..INDEX2N_MAX //Two hands with the same integer should have the same strength/EV/etc against an opponent. extern int getindex2N(const vector<CardMask> &cards, int maxround = RIVER); extern int getindex2N(const CardMask& mine, const CardMask& board, const int boardcards, int * suits = NULL); extern int getindexN(const CardMask& board, const int boardcards, int * suits = NULL); extern int getindex2(const CardMask& mine); inline int getindex23(CardMask pflop, CardMask flop) { return getindex2N(pflop, flop, 3); } extern int getindex231(CardMask pflop, CardMask flop, CardMask turn); extern int64 getindex2311(CardMask pflop, CardMask flop, CardMask turn, CardMask river); inline int getindex25(CardMask pflop, CardMask flop, CardMask turn, CardMask river) { CardMask board; CardMask_OR( board, flop, turn ); CardMask_OR( board, board, river ); return getindex2N( pflop, board, 5 ); } inline int getindex3(CardMask flop) { return getindexN(flop, 3); } extern int getindex31(CardMask flop, CardMask turn); extern int getindex311(CardMask flop, CardMask turn, CardMask river); #ifdef COMPILE_TESTCODE extern void testindex2N(); extern void testindex231(); #endif #endif
[ [ [ 1, 41 ] ] ]
3d94bf78a89e1c2e5eca4781926206007e5631e9
fbd2deaa66c52fc8c38baa90dd8f662aabf1f0dd
/totalFirePower/ta demo/code/glFont.cpp
df8c5856723eb62c41f7bb13a314e9bc244aec2f
[]
no_license
arlukin/dev
ea4f62f3a2f95e1bd451fb446409ab33e5c0d6e1
b71fa9e9d8953e33f25c2ae7e5b3c8e0defd18e0
refs/heads/master
2021-01-15T11:29:03.247836
2011-02-24T23:27:03
2011-02-24T23:27:03
1,408,455
2
1
null
null
null
null
UTF-8
C++
false
false
6,112
cpp
// glFont.cpp: implementation of the CglFont class. // ////////////////////////////////////////////////////////////////////// #include "glFont.h" #include <stdio.h> #include "globalstuff.h" #include "camera.h" #include <fstream> //#include <ostream.h> //#include <istream.h> using namespace std; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CglFont* font; CglFont::CglFont(HDC hDC, int start, int num) { numchars=num; startchar=start; HFONT font; // Windows Font ID base = glGenLists(num); unsigned char tex[1024][4]; char ch; int a; for(a=0;a<1024;a++){ tex[a][0]=255; tex[a][1]=255; tex[a][2]=255; tex[a][3]=0; } ifstream ifs("bagge.fnt",ios::in|ios::binary); ofstream* ofs=0; if(!ifs.is_open()) ofs=new ofstream("bagge.fnt",ios::out|ios::binary); int size=64; for(int sizenum=0;size!=32;sizenum++){ size/=2; font = CreateFont( -size, // Height Of Font 0, // Width Of Font 0, // Angle Of Escapement 0, // Orientation Angle FW_BOLD, // Font Weight FALSE, // Italic FALSE, // Underline FALSE, // Strikeout ANSI_CHARSET, // Character Set Identifier OUT_TT_PRECIS, // Output Precision CLIP_DEFAULT_PRECIS, // Clipping Precision ANTIALIASED_QUALITY, // Output Quality FF_DONTCARE|DEFAULT_PITCH, // Family And Pitch "Courier New"); // Font Name SelectObject(hDC, font); // Selects The Font We Want if(sizenum==0){ glGenTextures(num, ttextures); if(GetCharWidth(hDC,start,start+num,charWidths)==0){ char t[500]; sprintf(t,"Couldnt get text width %d",GetLastError()); MessageBox(0,t,"Error generating font",0); } } RECT r; r.bottom=size; r.left=0; r.top=0; r.right=size; for(a=0;a<num;a++){ if(ofs){ ch=a+start; DrawText(hDC,&ch,1,&r,DT_LEFT | DT_TOP); COLORREF cr; for(int y=0;y<size;y++){ for(int x=0;x<charWidths[a];x++){ cr=GetPixel(hDC,x,y); int a=255-cr&0xff; tex[y*size+x][0]=255; tex[y*size+x][1]=255; tex[y*size+x][2]=255; tex[y*size+x][3]=a; } } ofs->write((char*)tex[0],size*size*4); } else ifs.read((char*)tex[0],size*size*4); if(sizenum==0){ glBindTexture(GL_TEXTURE_2D, ttextures[a]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR/*_MIPMAP_NEAREST*/); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP); } glBindTexture(GL_TEXTURE_2D, ttextures[a]); glTexImage2D(GL_TEXTURE_2D, sizenum, 4, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex[0]); // gluBuild2DMipmaps(GL_TEXTURE_2D,4 ,size, size, GL_RGBA, GL_UNSIGNED_BYTE, tex[0]); } } for(a=0;a<num;a++){ int ch=a+start; #define DRAW_SIZE 1 float charpart=(charWidths[a])/32.0f; glNewList(base+a,GL_COMPILE); glBindTexture(GL_TEXTURE_2D, ttextures[a]); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0,1-1.0/64); glVertex3f(0,0,0); glTexCoord2f(0,0); glVertex3f(0,DRAW_SIZE,0); glTexCoord2f(charpart,1-1.0/64); glVertex3f(DRAW_SIZE*charpart,0,0); glTexCoord2f(charpart,0); glVertex3f(DRAW_SIZE*charpart,DRAW_SIZE,0); glEnd(); glTranslatef(DRAW_SIZE*(charpart+0.02f),0,0); glEndList(); } if(ofs) delete ofs; } CglFont::~CglFont() { glDeleteLists(base, numchars); // Delete All 96 Characters glDeleteTextures (numchars, ttextures); } void CglFont::glPrint(const char *fmt, ...) { char text[256]; // Holds Our String va_list ap; // Pointer To List Of Arguments if (fmt == NULL) // If There's No Text return; // Do Nothing va_start(ap, fmt); // Parses The String For Variables vsprintf(text, fmt, ap); // And Converts Symbols To Actual Numbers va_end(ap); // Results Are Stored In Text glPushAttrib(GL_LIST_BIT); // Pushes The Display List Bits glPushMatrix(); glListBase(base - startchar); glCallLists(strlen(text), GL_UNSIGNED_BYTE, text); // Draws The Display List Text glPopMatrix(); glPopAttrib(); // Pops The Display List Bits } void CglFont::glWorldPrint(const char *fmt, ...) { char text[256]; // Holds Our String va_list ap; // Pointer To List Of Arguments if (fmt == NULL) // If There's No Text return; // Do Nothing va_start(ap, fmt); // Parses The String For Variables vsprintf(text, fmt, ap); // And Converts Symbols To Actual Numbers va_end(ap); // Results Are Stored In Text glPushMatrix(); int b=strlen(text); float charpart=(charWidths[text[0]-startchar])/32.0f; glTranslatef(-b*0.5f*DRAW_SIZE*(charpart+0.03f)*camera.right.x,-b*0.5f*DRAW_SIZE*(charpart+0.03f)*camera.right.y,-b*0.5f*DRAW_SIZE*(charpart+0.03f)*camera.right.z); for(int a=0;a<b;a++) WorldChar(text[a]); glPopMatrix(); } CglFont::WorldChar(char c) { float charpart=(charWidths[c-startchar])/32.0f; glBindTexture(GL_TEXTURE_2D, ttextures[c-startchar]); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0,1); glVertex3f(0,0,0); glTexCoord2f(0,0); glVertex3f(DRAW_SIZE*camera.up.x,DRAW_SIZE*camera.up.y,DRAW_SIZE*camera.up.z); glTexCoord2f(charpart,1); glVertex3f(DRAW_SIZE*charpart*camera.right.x,DRAW_SIZE*charpart*camera.right.y,DRAW_SIZE*charpart*camera.right.z); glTexCoord2f(charpart,0); glVertex3f(DRAW_SIZE*(camera.up.x+camera.right.x*charpart),DRAW_SIZE*(camera.up.y+camera.right.y*charpart),DRAW_SIZE*(camera.up.z+camera.right.z*charpart)); glEnd(); glTranslatef(DRAW_SIZE*(charpart+0.03f)*camera.right.x,DRAW_SIZE*(charpart+0.03f)*camera.right.y,DRAW_SIZE*(charpart+0.03f)*camera.right.z); }
[ [ [ 1, 187 ] ] ]
9ae0f9bf40068e9b8c271de3434edfc1568fba6d
eddd3b38e897eb6dcf311a3de1f33aa3f0d26b5c
/FileInfo.h
f5c30b8cc5f33e73ea449784624df06a2e8efb20
[]
no_license
reyoung/tjufsmon
41eb34979d885f479b7cc47d913df7c281090ce7
6a2f2000d41e59a00050b490ca1834da72183527
refs/heads/master
2020-11-26T21:14:04.139320
2010-11-24T14:18:31
2010-11-24T14:18:31
33,868,135
0
0
null
null
null
null
UTF-8
C++
false
false
1,181
h
/* * File: FileInfo.h * Author: reyoung * * Created on 2010年11月21日, 下午3:34 */ #ifndef _FILEINFO_H #define _FILEINFO_H #include <string> class FileInfo { public: /** \brief * File Info Default Constructor . * \param fn const std::string& * The File Name. */ FileInfo(const std::string& fn); /** \brief * Copy Constructor. * \param orig const FileInfo& * */ FileInfo(const FileInfo& orig); /** \brief * Get Base Name Of FileInfo * For Example: * the base name of 'a.txt' is 'txt'. * \return const std::string * base Name string. */ const std::string getBaseName()const; /** \brief * Is Base Name Matched. * input the base name, return the base name is match to * File Info or not. * \param fn const std::string& * \return bool * Is Matched Return true. */ bool isBaseNameMatch(const std::string& fn)const; /** \brief * Deconstructor. * \return virtual * */ virtual ~FileInfo(); private: std::string m_filename; }; #endif /* _FILEINFO_H */
[ "[email protected]@d1ef24bf-30e3-250a-0152-633f91453181" ]
[ [ [ 1, 57 ] ] ]
b40cdf4209889e5fc2e6a27ee132f9b8460fe352
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/opcode/OPC_AABB.cc
0b8b4d0b83c3cd567a3e0914856523bfdf8ce79a
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,657
cc
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Contains AABB-related code. * \file IceAABB.cpp * \author Pierre Terdiman * \date January, 29, 2000 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * AABB class. * \class AABB * \author Pierre Terdiman * \version 1.0 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Precompiled Header #include "opcode/opcodedef.h" using namespace IceMaths; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the sum of two AABBs. * \param aabb [in] the other AABB * \return Self-Reference */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AABB& AABB::Add(const AABB& aabb) { // Compute new min & max values Point Min; GetMin(Min); Point Tmp; aabb.GetMin(Tmp); Min.Min(Tmp); Point Max; GetMax(Max); aabb.GetMax(Tmp); Max.Max(Tmp); // Update this SetMinMax(Min, Max); return *this; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Makes a cube from the AABB. * \param cube [out] the cube AABB * \return cube edge length */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float AABB::MakeCube(AABB& cube) const { Point Ext; GetExtents(Ext); float Max = Ext.Max(); Point Cnt; GetCenter(Cnt); cube.SetCenterExtents(Cnt, Point(Max, Max, Max)); return Max; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Makes a sphere from the AABB. * \param sphere [out] sphere containing the AABB */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABB::MakeSphere(Sphere& sphere) const { GetExtents(sphere.mCenter); sphere.mRadius = sphere.mCenter.Magnitude() * 1.00001f; // To make sure sphere::Contains(*this) succeeds GetCenter(sphere.mCenter); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Checks a box is inside another box. * \param box [in] the other AABB * \return true if current box is inside input box */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AABB::IsInside(const AABB& box) const { if(box.GetMin(0)>GetMin(0)) return false; if(box.GetMin(1)>GetMin(1)) return false; if(box.GetMin(2)>GetMin(2)) return false; if(box.GetMax(0)<GetMax(0)) return false; if(box.GetMax(1)<GetMax(1)) return false; if(box.GetMax(2)<GetMax(2)) return false; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the AABB planes. * \param planes [out] 6 planes surrounding the box * \return true if success */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AABB::ComputePlanes(Plane* planes) const { // Checkings if(!planes) return false; Point Center, Extents; GetCenter(Center); GetExtents(Extents); // Writes normals planes[0].n = Point(1.0f, 0.0f, 0.0f); planes[1].n = Point(-1.0f, 0.0f, 0.0f); planes[2].n = Point(0.0f, 1.0f, 0.0f); planes[3].n = Point(0.0f, -1.0f, 0.0f); planes[4].n = Point(0.0f, 0.0f, 1.0f); planes[5].n = Point(0.0f, 0.0f, -1.0f); // Compute a point on each plane Point p0 = Point(Center.x+Extents.x, Center.y, Center.z); Point p1 = Point(Center.x-Extents.x, Center.y, Center.z); Point p2 = Point(Center.x, Center.y+Extents.y, Center.z); Point p3 = Point(Center.x, Center.y-Extents.y, Center.z); Point p4 = Point(Center.x, Center.y, Center.z+Extents.z); Point p5 = Point(Center.x, Center.y, Center.z-Extents.z); // Compute d planes[0].d = -(planes[0].n|p0); planes[1].d = -(planes[1].n|p1); planes[2].d = -(planes[2].n|p2); planes[3].d = -(planes[3].n|p3); planes[4].d = -(planes[4].n|p4); planes[5].d = -(planes[5].n|p5); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the aabb points. * \param pts [out] 8 box points * \return true if success */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AABB::ComputePoints(Point* pts) const { // Checkings if(!pts) return false; // Get box corners Point min; GetMin(min); Point max; GetMax(max); // 7+------+6 0 = --- // /| /| 1 = +-- // / | / | 2 = ++- // / 4+---/--+5 3 = -+- // 3+------+2 / y z 4 = --+ // | / | / | / 5 = +-+ // |/ |/ |/ 6 = +++ // 0+------+1 *---x 7 = -++ // Generate 8 corners of the bbox pts[0] = Point(min.x, min.y, min.z); pts[1] = Point(max.x, min.y, min.z); pts[2] = Point(max.x, max.y, min.z); pts[3] = Point(min.x, max.y, min.z); pts[4] = Point(min.x, min.y, max.z); pts[5] = Point(max.x, min.y, max.z); pts[6] = Point(max.x, max.y, max.z); pts[7] = Point(min.x, max.y, max.z); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Gets vertex normals. * \param pts [out] 8 box points * \return true if success */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const Point* AABB::GetVertexNormals() const { static float VertexNormals[] = { -INVSQRT3, -INVSQRT3, -INVSQRT3, INVSQRT3, -INVSQRT3, -INVSQRT3, INVSQRT3, INVSQRT3, -INVSQRT3, -INVSQRT3, INVSQRT3, -INVSQRT3, -INVSQRT3, -INVSQRT3, INVSQRT3, INVSQRT3, -INVSQRT3, INVSQRT3, INVSQRT3, INVSQRT3, INVSQRT3, -INVSQRT3, INVSQRT3, INVSQRT3 }; return (const Point*)VertexNormals; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns edges. * \return 24 indices (12 edges) indexing the list returned by ComputePoints() */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const udword* AABB::GetEdges() const { static udword Indices[] = { 0, 1, 1, 2, 2, 3, 3, 0, 7, 6, 6, 5, 5, 4, 4, 7, 1, 5, 6, 2, 3, 7, 4, 0 }; return Indices; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns edge normals. * \return edge normals in local space */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const Point* AABB::GetEdgeNormals() const { static float EdgeNormals[] = { 0, -INVSQRT2, -INVSQRT2, // 0-1 INVSQRT2, 0, -INVSQRT2, // 1-2 0, INVSQRT2, -INVSQRT2, // 2-3 -INVSQRT2, 0, -INVSQRT2, // 3-0 0, INVSQRT2, INVSQRT2, // 7-6 INVSQRT2, 0, INVSQRT2, // 6-5 0, -INVSQRT2, INVSQRT2, // 5-4 -INVSQRT2, 0, INVSQRT2, // 4-7 INVSQRT2, -INVSQRT2, 0, // 1-5 INVSQRT2, INVSQRT2, 0, // 6-2 -INVSQRT2, INVSQRT2, 0, // 3-7 -INVSQRT2, -INVSQRT2, 0 // 4-0 }; return (const Point*)EdgeNormals; } // =========================================================================== // (C) 1996-98 Vienna University of Technology // =========================================================================== // NAME: bboxarea // TYPE: c++ code // PROJECT: Bounding Box Area // CONTENT: Computes area of 2D projection of 3D oriented bounding box // VERSION: 1.0 // =========================================================================== // AUTHORS: ds Dieter Schmalstieg // ep Erik Pojar // =========================================================================== // HISTORY: // // 19-sep-99 15:23:03 ds last modification // 01-dec-98 15:23:03 ep created // =========================================================================== //---------------------------------------------------------------------------- // SAMPLE CODE STARTS HERE //---------------------------------------------------------------------------- // NOTE: This sample program requires OPEN INVENTOR! //indexlist: this table stores the 64 possible cases of classification of //the eyepoint with respect to the 6 defining planes of the bbox (2^6=64) //only 26 (3^3-1, where 1 is "inside" cube) of these cases are valid. //the first 6 numbers in each row are the indices of the bbox vertices that //form the outline of which we want to compute the area (counterclockwise //ordering), the 7th entry means the number of vertices in the outline. //there are 6 cases with a single face and and a 4-vertex outline, and //20 cases with 2 or 3 faces and a 6-vertex outline. a value of 0 indicates //an invalid case. // Original list was made of 7 items, I added an 8th element: // - to padd on a cache line // - to repeat the first entry to avoid modulos // // I also replaced original ints with sbytes. static const sbyte gIndexList[64][8] = { {-1,-1,-1,-1,-1,-1,-1, 0}, // 0 inside { 0, 4, 7, 3, 0,-1,-1, 4}, // 1 left { 1, 2, 6, 5, 1,-1,-1, 4}, // 2 right {-1,-1,-1,-1,-1,-1,-1, 0}, // 3 - { 0, 1, 5, 4, 0,-1,-1, 4}, // 4 bottom { 0, 1, 5, 4, 7, 3, 0, 6}, // 5 bottom, left { 0, 1, 2, 6, 5, 4, 0, 6}, // 6 bottom, right {-1,-1,-1,-1,-1,-1,-1, 0}, // 7 - { 2, 3, 7, 6, 2,-1,-1, 4}, // 8 top { 0, 4, 7, 6, 2, 3, 0, 6}, // 9 top, left { 1, 2, 3, 7, 6, 5, 1, 6}, //10 top, right {-1,-1,-1,-1,-1,-1,-1, 0}, //11 - {-1,-1,-1,-1,-1,-1,-1, 0}, //12 - {-1,-1,-1,-1,-1,-1,-1, 0}, //13 - {-1,-1,-1,-1,-1,-1,-1, 0}, //14 - {-1,-1,-1,-1,-1,-1,-1, 0}, //15 - { 0, 3, 2, 1, 0,-1,-1, 4}, //16 front { 0, 4, 7, 3, 2, 1, 0, 6}, //17 front, left { 0, 3, 2, 6, 5, 1, 0, 6}, //18 front, right {-1,-1,-1,-1,-1,-1,-1, 0}, //19 - { 0, 3, 2, 1, 5, 4, 0, 6}, //20 front, bottom { 1, 5, 4, 7, 3, 2, 1, 6}, //21 front, bottom, left { 0, 3, 2, 6, 5, 4, 0, 6}, //22 front, bottom, right {-1,-1,-1,-1,-1,-1,-1, 0}, //23 - { 0, 3, 7, 6, 2, 1, 0, 6}, //24 front, top { 0, 4, 7, 6, 2, 1, 0, 6}, //25 front, top, left { 0, 3, 7, 6, 5, 1, 0, 6}, //26 front, top, right {-1,-1,-1,-1,-1,-1,-1, 0}, //27 - {-1,-1,-1,-1,-1,-1,-1, 0}, //28 - {-1,-1,-1,-1,-1,-1,-1, 0}, //29 - {-1,-1,-1,-1,-1,-1,-1, 0}, //30 - {-1,-1,-1,-1,-1,-1,-1, 0}, //31 - { 4, 5, 6, 7, 4,-1,-1, 4}, //32 back { 0, 4, 5, 6, 7, 3, 0, 6}, //33 back, left { 1, 2, 6, 7, 4, 5, 1, 6}, //34 back, right {-1,-1,-1,-1,-1,-1,-1, 0}, //35 - { 0, 1, 5, 6, 7, 4, 0, 6}, //36 back, bottom { 0, 1, 5, 6, 7, 3, 0, 6}, //37 back, bottom, left { 0, 1, 2, 6, 7, 4, 0, 6}, //38 back, bottom, right {-1,-1,-1,-1,-1,-1,-1, 0}, //39 - { 2, 3, 7, 4, 5, 6, 2, 6}, //40 back, top { 0, 4, 5, 6, 2, 3, 0, 6}, //41 back, top, left { 1, 2, 3, 7, 4, 5, 1, 6}, //42 back, top, right {-1,-1,-1,-1,-1,-1,-1, 0}, //43 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //44 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //45 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //46 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //47 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //48 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //49 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //50 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //51 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //52 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //53 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //54 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //55 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //56 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //57 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //58 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //59 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //60 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //61 invalid {-1,-1,-1,-1,-1,-1,-1, 0}, //62 invalid {-1,-1,-1,-1,-1,-1,-1, 0} //63 invalid }; const sbyte* AABB::ComputeOutline(const Point& local_eye, sdword& num) const { // Get box corners Point min; GetMin(min); Point max; GetMax(max); // Compute 6-bit code to classify eye with respect to the 6 defining planes of the bbox int pos = ((local_eye.x < min.x) ? 1 : 0) // 1 = left + ((local_eye.x > max.x) ? 2 : 0) // 2 = right + ((local_eye.y < min.y) ? 4 : 0) // 4 = bottom + ((local_eye.y > max.y) ? 8 : 0) // 8 = top + ((local_eye.z < min.z) ? 16 : 0) // 16 = front + ((local_eye.z > max.z) ? 32 : 0); // 32 = back // Look up number of vertices in outline num = (sdword)gIndexList[pos][7]; // Zero indicates invalid case if(!num) return null; return &gIndexList[pos][0]; } // calculateBoxArea: computes the screen-projected 2D area of an oriented 3D bounding box //const Point& eye, //eye point (in bbox object coordinates) //const AABB& box, //3d bbox //const Matrix4x4& mat, //free transformation for bbox //float width, float height, int& num) float AABB::ComputeBoxArea(const Point& eye, const Matrix4x4& mat, float width, float height, sdword& num) const { const sbyte* Outline = ComputeOutline(eye, num); if(!Outline) return -1.0f; // Compute box vertices Point vertexBox[8], dst[8]; ComputePoints(vertexBox); // Transform all outline corners into 2D screen space for(sdword i=0;i<num;i++) { HPoint Projected; vertexBox[Outline[i]].ProjectToScreen(width, height, mat, Projected); dst[i] = Projected; } float Sum = (dst[num-1][0] - dst[0][0]) * (dst[num-1][1] + dst[0][1]); for(int i=0; i<num-1; i++) Sum += (dst[i][0] - dst[i+1][0]) * (dst[i][1] + dst[i+1][1]); return Sum * 0.5f; //return computed value corrected by 0.5 }
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 405 ] ] ]
8dcdcecb3c79822452633e06451ad750dab86163
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Common/math/matrix.h
e9ea181a6528200927d6ad6622061029031ad73f
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,086
h
#ifndef _MATRIX_H #define _MATRIX_H #include <cassert> #include <memory> #include <limits> #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #include <math.h> using namespace std; #ifdef __cplusplus_cli #pragma managed(push,off) #endif #include "acml.h" #include "../coords/dpvector3.h" #include "../coords/dpvector4.h" #define MAT_IND(i, j, m, n) ((j) * (m) + (i)) inline int mat_ind(int i, int j, int m, int n) { return j * m + i; } class matrix_exception { private: int len; char* msg; public: matrix_exception(); matrix_exception(const char* msg); matrix_exception(const matrix_exception&); virtual matrix_exception& operator = (const matrix_exception&); virtual ~matrix_exception(); // returns a human readable message for the exception virtual const char* what() const; }; // random utility function, not sure where to put it inline double round(double l) { double fl = floor(l); if (l - fl < 0.5) return fl; else return fl + 1.0; } inline double round(double l, int prec) { double s = _Pow_int(10, prec); double si = 1 / s; l *= s; double fl = floor(l); if (l - fl < 0.5) return fl * si; else return fl * si + si; } // rounds denormalized numbers inline double denorm_round(const double l) { int fpc = _fpclass(l); if (fpc == _FPCLASS_ND || fpc == _FPCLASS_PD) return 0; else return l; } inline double double_round_up(const double l) { int fpc = _fpclass(l); if (fpc == _FPCLASS_ND) return -DBL_MIN; else if (fpc == _FPCLASS_PD) return DBL_MIN; else return fpc; } // N.B. -- there is a little weirdness with how the copy constructor and assignment operator work: // copy constructor will not copy the data, but will copy the pointer, so it will use the original data // assignment operator will copy the data and dimensions of the two matrices must match // // Here are some cases where each are used // matrix source(...); // matrix crap = source; // copy constructor // matrix crap2(...); // use same dimensions as source, supply valid data buffer // crap2 = source; // assignment operator, so data will be copied into crap2 buffer // // There is no way right now to change the buffer once the class is constructed. // // The reason for designing the class as a BYOBB (bring your own buffer beotch) is so that the program // can control allocations more effectively. Basically, it revolves around efficient multi-threading: // want to avoid heap allocations if possible since a program-wide lock is taken to allocate memory. // This is particularly so that data can be stack allocated but the utility class can still be used. // Also, memory can be allocated from a specific heap and supplied. The syntax will likely be more // awkward as a result, but hopefully the extra control will make up for it. // // As a result of this design, memory cannot be allocated for operations, so there is no convenient // multiplication, addition or subtraction operators that return a new matrix. Everything must be // done with an explicit target/in place. // // Operations that can fails (inversion, cholesky decomposition, etc) will throw a matrix_exception if // there is a problem. This will have a human readable description, but not much else. class submatrix; class matrix { friend class submatrix; protected: double* d; int cm, cn; bool trans; public: matrix() : cm(0), cn(0), d(NULL), trans(false) {} matrix(const int m, const int n, double* data, bool transpose = false) : cm(m), cn(n), d(data), trans(transpose) {} matrix(const matrix& c) : cm(c.cm), cn(c.cn), d(c.d), trans(c.trans) {} // Assignment operator, copies data into local buffer // See notes above matrix& operator = (const matrix& c) { assert(d != NULL && c.d != NULL); int tm = m(), tn = n(); int om = c.m(), on = c.n(); assert(m() == c.m() && n() == c.n()); // copy data in int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) operator() (i, j) = c(i, j); return *this; } matrix& operator = (const dpvector3& c) { return copy(c); } matrix& operator = (const dpvector4& c) { return copy(c); } matrix& operator = (const dpmatrix3& c) { return copy(c); } matrix& copy(const dpvector3& c) { assert((m() == 3 && n() == 1) || (m() == 1 && n() == 3)); assert(d != NULL); // copy data in int dm = m(), dn = n(); if (dm > dn) { for (int i = 0; i < 3; i++) { operator() (i, 0) = c[i]; } } else { for (int j = 0; j < 3; j++) { operator() (0, j) = c[j]; } } return *this; } matrix& copy(const dpvector4& c) { assert((m() == 4 && n() == 1) || (m() == 1 && n() == 4)); assert(d != NULL); // copy data in int dm = m(), dn = n(); if (dm > dn) { for (int i = 0; i < 4; i++) operator()(i, 0) = c[i]; } else { for (int j = 0; j < 4; j++) operator()(0, j) = c[j]; } return *this; } matrix& copy(const dpmatrix3& c) { assert(m() == 3 && n() == 3); assert(d != NULL); // copy data in for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) operator()(i,j) = c(i,j); return *this; } matrix& copy(const matrix& A, const double c) { assert(d != NULL && A.d != NULL); assert(m() == A.m() && n() == A.n()); int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) operator() (i, j) = A(i, j) * c; return *this; } matrix& copy(const matrix& A, const double c, const matrix& B, const double k) { assert(d != NULL && A.d != NULL && B.d != NULL); assert(m() == A.m() && m() == B.m() && n() == A.n() && n() == B.n()); int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) operator() (i, j) = A(i, j) * c + B(i, j) * k; return *this; } matrix& copy(const matrix& A, const double a, const matrix& B, const double b, const matrix& C, const double c, const matrix& D, const double ds, const matrix& E, const double e) { // skip asserts for now int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) { operator () (i, j) = A(i, j) * a + B(i, j) * b + C(i, j) * c + D(i, j) * ds + E(i, j) * e; } return *this; } void resize(int m, int n) { cm = m; cn = n; } void get(double* c) { // store in column major order int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) { c[j*dm+i] = operator() (i, j); } } // Number of rows virtual int m() const { return trans ? cn : cm; } // Number of columns virtual int n() const { return trans ? cm : cn; } // Leading dimension of the matrix. Used in BLAS operations, not really useful elsewhere int ld() const { return (int)cm; } // not sure what to do with this and transpose // Retrievies the data pointer of the (0, 0) element of the matrix // For sub-matrices, this is the pointer to the (0, 0) element of the submatrix, not // the original matrix virtual operator const double* () const { return d; } virtual operator double* () { return d; } operator void* () { return (void*)(operator double *()); } operator dpvector3 () const { assert((m() == 3 && n() == 1) || (m() == 1 && n() == 3)); if (m() == 3) return dpvector3(operator()(0, 0), operator()(1, 0), operator()(2, 0)); else if (n() == 3) return dpvector3(operator()(0, 0), operator()(0, 1), operator()(0, 2)); else return dpvector3(); } operator dpmatrix3 () const { assert(m() == 3 && n() == 3); return dpmatrix3(d); } // Accessor for the elements of the matrix virtual double operator () (const int i, const int j) const { assert(i >= 0 && i < m() && j >= 0 && j < n()); if (trans) return d[i * cm + j]; else return d[j * cm + i]; } virtual double& operator() (const int i, const int j) { assert(i >= 0 && i < m() && j >= 0 && j < n()); if (trans) return d[i * cm + j]; else return d[j * cm + i]; } bool is_valid() const { return d != NULL; } // Returns a sub-matrix with the same data pointer as this matrix. This can be used for // assigning sub-blocks of the matrix: // matrix big(10, 10, ...); // matrix small(4, 4, ...); // big(2, 5, 3, 6) = small; // // si = start row, ei = end col (and similarly for sj, ej) // This is designed to be as similar as possible to matlab syntax // // Also, the resulting submatrix can be used with the other operators (+=, -=, *=, etc) // and in multiplication, cholesky decomposition, etc, although that is somewhat sketch. // The result should be valid (as if the submatrix was the only matrix under consideration) // // The following code SHOULD NOT be used // matrix big(10, 10, ...); // matrix small = big(2, 5, 3, 6); // This would cause small to reference the upper-left 4x4 block of big, which is clearly // not intended. If the intent is to copy into small, the following code would work // matrix big(10, 10, ...); // matrix small(4, 4, ...); // small = big(2, 5, 3, 6); // Also, submatrices can be assigned to other submatrices: // matrix big1(10, 10, ...); // matrix big2(10, 10, ...); // big1(2, 5, 3, 6) = big2(4, 7, 0, 3); const submatrix operator () (int si, int ei, int sj, int ej) const; submatrix operator () (int si, int ei, int sj, int ej); // Add this and C element-wise matrix& operator += (const matrix& c) { assert(m() == c.m() && n() == c.n()); int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) operator()(i, j) += c(i, j); return *this; } // Subtracts this and C element-wise matrix& operator -= (const matrix& c) { assert(m() == c.m() && n() == c.n()); int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) operator()(i, j) -= c(i, j); return *this; } // Multiplies all elements by c matrix& operator *= (const double c) { int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) operator()(i, j) *= c; return *this; } // Divides all elements by c matrix& operator /= (const double c) { double r = 1.0/c; int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) operator()(i, j) *= r; return *this; } // Multiplies A * B and stores the result into this matrix, where A -> (m x k), B -> (k x n) and this matrix is (m x n). // Respects the transpose property of A and B // General formula is // ab_coeff * A * B + c_coeff * this // For standard multiplication, ab_coeff = 1.0, c_coeff = 0.0 matrix& mult(const matrix &A, const matrix &B, const double ab_coeff = 1.0, const double c_coeff = 0.0) { assert(m() == A.m() && n() == B.n() && A.n() == B.m()); dgemm(A.trans ? 'T' : 'N', B.trans ? 'T' : 'N', (int)m(), (int)n(), (int)A.n(), ab_coeff, (matrix&)A, (int)A.ld(), (matrix&)B, (int)B.ld(), c_coeff, this->operator double *(), (int)ld()); return *this; } matrix& mult(const dpmatrix3 &A, const matrix &B, const double ab_coeff = 1.0, const double c_coeff = 0.0) { assert(m() == 3 && n() == B.n() && B.m() == 3); dgemm('N', B.trans ? 'T' : 'N', 3, (int)n(), 3, ab_coeff, (double*)A.m, 4, (matrix&)B, (int)B.ld(), c_coeff, (double*)(*this), (int)ld()); return *this; } matrix& mult(const matrix &B, const dpmatrix3 &A, const double ab_coeff = 1.0, const double c_coeff = 0.0) { assert(m() == B.m() && n() == 3 && B.n() == 3); dgemm(B.trans ? 'T' : 'N', 'N', (int)m(), 3, 3, ab_coeff, (matrix&)B, (int)B.ld(), (double*)A.m, 4, c_coeff, (double*)(*this), (int)ld()); return *this; } matrix& mult(const matrix &A, const dpvector3 &b, const double ab_coeff = 1.0, const double c_coeff = 0.0) { assert(m() == A.m() && n() == 1 && A.n() == 3); dgemm(A.trans ? 'T' : 'N', 'N', (int)m(), 1, 3, ab_coeff, (matrix&)A, (int)A.ld(), (double*)b.v, 4, c_coeff, (double*)(this), (int)ld()); return *this; } // Performs the transpose in place. At the moment, only works with square matrices virtual matrix& T() { //trans = !trans; // do the actual transpose // swap (i, j) with (j, i) // this is surprisingly hard when the matrix is not square if (cm == cn) { for (int i = 0; i < cm; i++) for (int j = i+1; j < cn; j++) { double t = d[i * cm + j]; // source spot d[i * cm + j] = d[j * cm + i]; d[j * cm + i] = t; } } else { // very tricky...use algorithm 467 // for now, just fail assert(false); } return *this; } // Fills the matrix with zeros matrix& zeros() { int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) operator() (i, j) = 0.0; return *this; } // Set the matrix to the identity matrix of the appropriate dimension // Must be a square matrix for this to work matrix& eye() { assert(m() == n()); int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) { if (i == j) operator() (i, j) = 1.0; else operator() (i, j) = 0.0; } return *this; } // Fills the matrix with ones matrix& ones() { int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) operator() (i, j) = 1.0; return *this; } // Performs cholesky decomposition on a matrix in place. The matrix must be positive definite. // upper specifies the form of the cholesky decomposition: // upper = true => chol(A)'*chol(A) = A // lower = true => chol(A)*chol(A)' = A // // The opposite triangular portion of the matrix will contain zeros // The transpose property of the matrix will be set to false after exit--if we can perform // cholesky decomposition, then the matrix was symmetric in the first place, so it doesn't matter // Throws matrix_exception if decomposition fails matrix& chol(bool upper = true) throw(...) { assert(m() == n()); // square matrices only int info; // see http://www.netlib.org/lapack/double/dpotrf.f dpotrf(upper ? 'U' : 'L', (int)m(), (double*)(*this), (int)ld(), &info); if (info != 0) throw matrix_exception("Error computing cholesky factorization"); // set transpose to false--if we can perform cholesky decomposition, the // matrix was symmetric, so trans didn't matter // want to respect upper or lower as appropriate trans = false; // zero out other portion if (upper) { int dm = m(), dn = n(); for (int j = 0; j < dn - 1; j++) { for (int i = j + 1; i < dm; i++) { operator()(i, j) = 0.0; } } } else { int dm = m(), dn = n(); for (int j = 1; j < dn; j++) { for (int i = 0; i < j; i++) { operator()(i, j) = 0.0; } } } return *this; } // inverts a general matrix using LU factorization // throws matrix_exception if inversion fails matrix& inv_lu() throw(...) { assert(m() == n()); // square matrices only // to do this, need to compute LU factorization int* ipiv = (int*)_alloca(m()*sizeof(int)); int info; // see http://www.netlib.org/lapack/double/dgetrf.f for more information dgetrf((int)m(), (int)n(), (*this), (int)ld(), ipiv, &info); // check for success if (info != 0) throw matrix_exception("Error computing LU factorization in inv_lu"); // now compute the inverse // see http://www.netlib.org/lapack/double/dgetri.f for more information dgetri((int)m(), (*this), (int)ld(), ipiv, &info); if (info != 0) throw matrix_exception("Error computing inverse in inv_lu"); // note that this works appropriately even matrix is transposed: // inv(A') = inv(A)'; return *this; } // inverts a triangular matrix stored the upper or lower triangle. // throws matrix_exception if inversion fails (matrix is not full rank) matrix& inv_tri(bool upper = true) throw(...) { upper ^= trans; // swap if transposed int info; // see http://www.netlib.org/lapack/double/dtrtri.f dtrtri(upper ? 'U' : 'L', 'N', (int)m(), (double*)(*this), (int)ld(), &info); if (info != 0) throw matrix_exception("Error computing inverse in inv_tri"); // note that transpose is still respected return *this; } // rounds all elements of the matrix matrix& round() { assert(d != NULL); int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) operator () (i, j) = ::round(operator()(i, j)); return *this; } bool is_empty() const { return this->operator const double *() == NULL; } }; class submatrix : public matrix { friend class matrix; private: int si, sj, sm, sn; submatrix(const matrix& par, int si, int sj, int sm, int sn) { this->cn = par.cn; this->cm = par.cm; this->trans = par.trans; this->d = par.d; this->si = si; this->sj = sj; this->sm = sm; this->sn = sn; } public: submatrix(const submatrix& m) { this->cn = m.cn; this->cm = m.cm; this->trans = m.trans; this->d = m.d; this->si = m.si; this->sj = m.sj; this->sm = m.sm; this->sn = m.sn; } matrix& operator = (const matrix& c) { assert(d != NULL && c.d != NULL); assert(m() == c.m() && n() == c.n()); // copy data in int dm = m(), dn = n(); for (int j = 0; j < dn; j++) for (int i = 0; i < dm; i++) operator() (i, j) = c(i, j); return *this; } matrix& operator = (const submatrix& c) { return operator = ((matrix&)c); } matrix& operator = (const dpvector3& c) { return matrix::copy(c); } matrix& operator = (const dpvector4& c) { return matrix::copy(c); } matrix& operator = (const dpmatrix3& c) { return matrix::copy(c); } virtual int m() const { return /*trans ? sn :*/ sm; } virtual int n() const { return /*trans ? sm :*/ sn; } virtual operator const double* () const { if (trans) return d + si * cm + sj; else return d + sj * cm + si; } virtual operator double* () { if (trans) return d + si * cm + sj; else return d + sj * cm + si; } virtual double operator () (const int i, const int j) const { assert(i >= 0 && i < m() && j >= 0 && j < n()); if (trans) return d[(i + si) * cm + (j + sj)]; else return d[(j + sj) * cm + (i + si)]; } virtual double& operator() (const int i, const int j) { assert(i >= 0 && i < m() && j >= 0 && j < n()); if (trans) return d[(i + si) * cm + (j + sj)]; else return d[(j + sj) * cm + (i + si)]; } }; inline const submatrix matrix::operator () (int si, int ei, int sj, int ej) const { assert(si >= 0 && si <= ei && ei < m() && sj >= 0 && sj <= ej && ej < n()); // if this is a transpose, swap the stuffters /*if (trans) { int temp = si; si = sj; sj = temp; temp = ei; ei = ej; ej = temp; }*/ return submatrix(*this, si, sj, ei-si+1, ej-sj+1); } inline submatrix matrix::operator () (int si, int ei, int sj, int ej) { assert(si >= 0 && si <= ei && ei < m() && sj >= 0 && sj <= ej && ej < n()); /*if (trans) { int temp = si; si = sj; sj = temp; temp = ei; ei = ej; ej = temp; }*/ // the submatrix will be un-transposed (if that makes sense) // it will handle the transpose stuff itself return submatrix(*this, si, sj, ei-si+1, ej-sj+1); } inline double unwrap(double d) { double w = fmod(d,2*M_PI); if (w > M_PI) w -= 2*M_PI; return w; } inline void unwrap(matrix& m) { for (int i = 0; i < m.m(); i++) { for (int j = 0; j < m.n(); j++) { double w = fmod(m(i,j),2*M_PI); if (w > M_PI) w -= 2*M_PI; m(i,j) = w; } } } /*template <class Ty, class Ax> class _submatrix; template <class Ty = double, class Ax = allocator<Ty>> class matrix { template <typename Ty2, typename Ax2> friend class matrix; public: typedef typename Ax::template rebind<Ty>::other Alt; protected: typedef typename Ax::template rebind<int>::other Intalt; typedef matrix<Ty, Ax> Myt; typename Alt::pointer d; typename Alt::size_type cm, cn; Alt alloc; Intalt intalloc; int* submat_count; virtual void free_data() { if (submat_count != NULL) (*submat_count)--; if (d != NULL && (submat_count == NULL || *submat_count == 0)) { //for (int i = 0; i < cm * cn; i++) alloc.destroy(d + i); alloc.deallocate(d, cm * cn); } if (submat_count != NULL && *submat_count == 0) intalloc.deallocate(submat_count, 1); d = NULL; } void check_alloc() { if (d == NULL) d = alloc.allocate(cm * cn); } public: matrix() : cm(0), cn(0), d(NULL), submat_count(NULL) {} matrix(const typename Alt::size_type m, const typename Alt::size_type n, typename Alt::const_pointer d = NULL) { this->cm = m; this->cn = n; this->d = NULL; if (d != NULL) { // allocate space this->d = alloc.allocate(m * n); // copy data for (typename Alt::size_type j = 0; j < n; j++) for (typename Alt::size_type i = 0; i < m; i++) this->d[j * m + i] = d[j * m + i]; } submat_count = NULL; } //template <typename Ax2> matrix(const Myt& m) { this->cm = m.m(); this->cn = m.n(); this->d = NULL; // copy data if (m.d != NULL) { this->d = alloc.allocate(cm * cn); for (typename Alt::size_type j = 0; j < cn; j++) for (typename Alt::size_type i = 0; i < cm; i++) this->operator()(i, j) = m(i, j); } submat_count = NULL; } virtual ~matrix() { free_data(); } Myt& operator = (const Myt& m) { free_data(); this->cm = m.cm; this->cn = m.cn; this->d = NULL; if (m.d != NULL) { this->d = alloc.allocate(cm * cn); // copy data for (int j = 0; j < cn; j++) for (int i = 0; i < cm; i++) operator()(i, j) = m(i, j); } submat_count = NULL; return *this; } //template <typename Ax2> //matrix<Ty, Ax>& operator = (const matrix<Ty, Ax2>& m) { // free_data(); // this->cm = m.cm; // this->cn = m.cn; // this->d = NULL; // if (m.d != NULL) { // this->d = alloc.allocate(cm * cn); // // copy data // for (int j = 0; j < cm; j++) for (int i = 0; i < cm; i++) // operator()(i, j) = m(i, j); // } // submat_count = NULL; // return *this; //} virtual typename Alt::size_type m() const { return cm; } virtual typename Alt::size_type n() const { return cn; } #ifdef min #pragma push_macro("min") #undef min #define _min_removed #endif virtual typename Alt::value_type operator () (const typename Alt::size_type i, const typename Alt::size_type j) const { assert(i >= 0 && i < cm && j >= 0 && j < cn); if (d == NULL) return numeric_limits<Alt::value_type>::min(); return d[j * cm + i]; } #ifdef _min_removed #pragma pop_macro("min") #endif virtual typename Alt::reference operator() (const typename Alt::size_type i, const typename Alt::size_type j) { assert(i >= 0 && i < cm && j >= 0 && j < cn); check_alloc(); return d[j * cm + i]; } virtual _submatrix<Ty, Ax> operator () (const typename Alt::size_type si, const typename Alt::size_type ei, const typename Alt::size_type sj, const typename Alt::size_type ej) { assert(si >= 0 && ei >= si && ei < cm && sj >= 0 && ej >= sj && ej < cn); check_alloc(); if (submat_count == NULL) { submat_count = intalloc.allocate(1); *submat_count = 1; } return _submatrix<Ty, Ax>(*this, submat_count, si, sj, ei - si + 1, ej - sj + 1); } //matrix<Ty, Ax> get_submatrix(const typename Alt::size_type i_start, const typename Alt::size_type j_start, const typename Alt::size_type m, const typename Alt::size_type n) const { // assert(i_start >= 0 && i_start + m <= cm && j_start >= 0 && j_start + n <= cn); // matrix<Ty, Ax> r(m, n); // for (int j = 0; j < n; j++) for (int i = 0; i < m; i++) // r(i, j) = operator()(i + i_start, j + i_start); // return r; //} // //void set_submatrix(const typename Alt::size_type i_start, const typename Alt::size_type j_start, const matrix<Ty, Ax>& d) { // assert(i_start >= 0 && i_start + m <= cm && j_start >= 0 && j_start + n <= cn); //} virtual operator typename Alt::const_pointer () const { const_cast<matrix<Ty, Ax>*>(this)->check_alloc(); return d; } virtual operator typename Alt::pointer () { check_alloc(); return d; } virtual int ld() const { return (int)cm; } }; template <typename Ty, typename Ax> class _submatrix : public matrix<Ty, Ax> { friend class matrix<Ty, Ax>; private: typename Alt::size_type si, sj, sm, sn; _submatrix(matrix<Ty, Ax>& par, int* submat_count, typename Alt::size_type si, typename Alt::size_type sj, typename Alt::size_type cm, typename Alt::size_type cn) { this->si = si; this->sj = sj; this->sm = cm; this->sn = cn; this->cm = par.m(); this->cn = par.n(); this->d = (double*)par; this->submat_count = submat_count; (*submat_count)++; } public: _submatrix(const _submatrix<Ty, Ax>& c) { this->d = c.d; this->cm = c.cm; this->cn = c.cn; this->submat_count = c.submat_count; this->si = c.si; this->sj = c.sj; this->sm = c.sm; this->sn = c.sn; (*submat_count)++; } virtual ~_submatrix() { free_data(); } template <typename Ax2> matrix<Ty, Ax>& operator = (const matrix<Ty, Ax2>& r) { // copy data in assert(sm == r.m() && sn == r.n()); for (typename Alt::size_type j = 0; j < sn; j++) for (typename Alt::size_type i = 0; i < sm; i++) this->operator () (i, j) = r(i, j); return *this; } virtual typename Alt::size_type m() const { return sm; } virtual typename Alt::size_type n() const { return sn; } virtual typename Alt::value_type operator () (const typename Alt::size_type i, const typename Alt::size_type j) const { assert(i >= 0 && i < sm && j >= 0 && j < cn); return d[(j + sj) * cm + (i + si)]; } virtual typename Alt::reference operator() (const typename Alt::size_type i, const typename Alt::size_type j) { assert(i >= 0 && i < sm && j >= 0 && j < sn); return d[(j + sj) * cm + (i + si)]; } // offset pointer by si, so that incrementing by ld will result in repositioning at the next full column virtual operator typename Alt::const_pointer () const { return d + si; } virtual operator typename Alt::pointer () { return d + si; } }; template <typename Ty, typename Ax, typename Ax2> matrix<Ty, Ax> operator + (const matrix<Ty, Ax>& A, const matrix<Ty, Ax2>& B) { assert(A.m() == B.m() && A.n() == B.n()); matrix<Ty, Ax> r(A.m(), A.n()); for (int j = 0; j < A.n(); j++) for (int i = 0; i < A.m(); i++) r(i, j) = A(i, j) + B(i, j); return r; } template <typename Ty, typename Ax, typename Ax2> matrix<Ty, Ax> operator - (const matrix<Ty, Ax>& A, const matrix<Ty, Ax2>& B) { assert(A.m() == B.m() && A.n() == B.n()); matrix<Ty, Ax> r(A.m(), A.n()); for (int j = 0; j < A.n(); j++) for (int i = 0; i < A.m(); i++) r(i, j) = A(i, j) - B(i, j); return r; } template <typename Ty, typename Ax, typename Ax2> matrix<Ty, Ax>& operator += (matrix<Ty, Ax>& A, const matrix<Ty, Ax2>& B) { assert(A.m() == B.m() && A.n() == B.n()); for (int j = 0; j < A.n(); j++) for (int i = 0; i < A.m(); i++) A(i, j) += B(i, j); return A; } template <typename Ty, typename Ax, typename Ax2> matrix<Ty, Ax>& operator -= (matrix<Ty, Ax>& A, const matrix<Ty, Ax2>& B) { assert(A.m() == B.m() && A.n() == B.n()); for (int j = 0; j < A.n(); j++) for (int i = 0; i < A.m(); i++) A(i, j) -= B(i, j); return A; } template <typename Ty, typename Ax, typename Ax2> matrix<Ty, Ax> operator * (const matrix<Ty, Ax>& A, const matrix<Ty, Ax2>& B) { assert(A.n() == B.m()); matrix<Ty, Ax> r(A.m(), B.n()); dgemm('N', 'N', (int)A.m(), (int)B.n(), (int)A.n(), 1.0, (matrix<Ty, Ax>&)A, A.ld(), (matrix<Ty, Ax>&)B, B.ld(), 0.0, r, r.ld()); return r; } template <typename Ty, typename Ax> matrix<Ty, Ax> operator * (const matrix<Ty, Ax>& A, const double c) { matrix<Ty, Ax> r(A.m(), A.n()); for (int j = 0; j < A.n(); j++) for (int i = 0; i < A.m(); i++) r(i, j) = A(i, j) * c; return r; } template <typename Ty, typename Ax> matrix<Ty, Ax> operator * (const double c, const matrix<Ty, Ax>& A) { return A * c; } template <typename Ty, typename Ax> matrix<Ty, Ax>& operator *= (matrix<Ty, Ax>& A, const double c) { for (int j = 0; j < A.n(); j++) for (int i = 0; i < A.m(); i++) A(i, j) *= c; return A; } template <typename Ty, typename Ax> matrix<Ty, Ax> operator / (const matrix<Ty, Ax>& A, const double c) { matrix<Ty, Ax> r(A.m(), A.n()); double recip = 1.0/c; for (int j = 0; j < A.n(); j++) for (int i = 0; i < A.m(); i++) r(i, j) = A(i, j) * recip; return r; } template <typename Ty, typename Ax> matrix<Ty, Ax>& operator /= (matrix<Ty, Ax>& A, const double c) { double recip = 1.0 / c; for (int j = 0; j < A.n(); j++) for (int i = 0; i < A.m(); i++) A(i, j) *= recip; return A; } */ #ifdef __cplusplus_cli #pragma managed(pop) #endif #endif
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 937 ] ] ]
b3617c7da9836806851dfdc244bbb387de806757
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.2/bctestuniteditor/inc/bctestuniteditorcontainer.h
db64edaa58fec96d01f5adc4a27917a48a01e244
[]
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,020
h
/* * Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: container * */ #ifndef BCTEST_UNITEDITORCONTAINER_H #define BCTEST_UNITEDITORCONTAINER_H #include <coecntrl.h> /** * container class */ class CBCTestUnitEditorContainer: public CCoeControl { public: // constructor and destructor /** * C++ default constructor */ CBCTestUnitEditorContainer(); /** * Destructor */ virtual ~CBCTestUnitEditorContainer(); /** * Symbian 2nd constructor */ void ConstructL( const TRect& aRect ); public: // new functions /** * Set component control, and container will own the control * @param aControl pointer to a control. */ void SetControl( CCoeControl* aControl ); /** * Delete control */ void ResetControl(); public: // from CCoeControl /** * Return count of component controls */ TInt CountComponentControls() const; /** * Return pointer to component control specified by index * @param aIndex, a index to specify a component control */ CCoeControl* ComponentControl( TInt aIndex ) const; private: // from CCoeControl /** * From CCoeControl, Draw. * Fills the window's rectangle. * @param aRect Region of the control to be (re)drawn. */ void Draw( const TRect& aRect ) const; private: // data /** * Pointer to component control. * own */ CCoeControl* iControl; }; #endif // BCTEST_UNITEDITORCONTAINER_H
[ "none@none" ]
[ [ [ 1, 90 ] ] ]
ff855599ca26c783d57916656ed42c562c3a3aa5
291355fd4592e4060bca01383e2c3a2eff55bd58
/src/trees.h
16186bb6c0bd01651a31f82204b5b40c31b42d45
[]
no_license
rrader/cprompt
6d7c9aac25d134971bbf99d4e84848252a626bf3
dfb7d55111b6e8d3c3a0a0a1c703c04a58d5e808
refs/heads/master
2020-05-16T22:06:16.127336
2010-01-23T21:33:04
2010-01-23T21:33:04
1,659,726
1
1
null
null
null
null
UTF-8
C++
false
false
2,634
h
#ifndef TREES_H_INCLUDED #define TREES_H_INCLUDED #include <iostream> #include <fstream> extern bool debugmode; #include "lists.h" #include "main.h" namespace ag { template<typename T> class tree { public: T data; ag::list<tree*> childs; tree* parent; int iCount; tree(T d); tree(tree* p,T d); ~tree(); tree* addchild(T d); void addchild_ptr(tree* ptr); void delchild(tree* c); void delallchilds(); void delchild_r(tree* c);//recursively void drawtree_con(std::ostream* o,int depth=0); }; template<typename T> tree<T>::tree(T d) { data=d; parent=NULL; } template<typename T> tree<T>::tree(tree* p,T d) { if (debugmode) std::cout<<"tree::tree()\n"; p->addchild_ptr(this); parent=p; data=d; } template<typename T> tree<T>::~tree() { } template<typename T> tree<T>* tree<T>::addchild(T d) { tree<T>* c=new tree(this,d); return c; } template<typename T> void tree<T>::addchild_ptr(tree<T>* ptr) { childs.add_tail(ptr); } template<typename T> void tree<T>::delchild(tree* c) { for(listmember< tree<T>* >* k=childs.head;k!=NULL;k=k->next) { if (c==k->data) { childs.del(k); break; } } } template<typename T> void tree<T>::delallchilds() { listmember< tree<T>* >* p=childs.head; listmember< tree<T>* >* k; while (p!=childs.tail) { k=p->next; childs.del(p); p=k; } } template<typename T> void tree<T>::delchild_r(tree* c)//recursively { for(listmember< tree<T>* >* k=childs.head;k!=NULL;k=k->next) { if (c==k->data) { k->data->delallchilds(); childs.del(k); break; } } }; template<typename T> void tree<T>::drawtree_con(std::ostream* o,int depth) { for(int i=0;i<depth;i++) *o<<"| "; // char* s =this->data; char ss[255]; sprintf(ss,"t%d;%s;%s;%s;%s",this->data->tntType,(this->data->text==NULL)?"":this->data->text, (this->data->text2==NULL)?"":this->data->text2,(this->data->text3==NULL)?"":this->data->text3, (this->data->text4==NULL)?"":this->data->text4); (*o) << ss << "\n"; for(listmember< tree<T>* >* k=childs.head;k!=NULL;k=k->next) { k->data->drawtree_con(o,depth+1); } }; }; #endif // TREES_H_INCLUDED
[ [ [ 1, 128 ] ] ]
c9adab4ffea6e8716c88c037538c6c4ec383461c
905a210043c8a48d128822ddb6ab141a0d583d27
/renderer/renderer2d/sgr_nodes.cpp
e48b715bac84855a94d6a33ede54db3093683ba1
[]
no_license
mweiguo/sgt
50036153c81f35356e2bfbba7019a8307556abe4
7770cdc030f5e69fef0b2150b92b87b7c8b56ba5
refs/heads/master
2020-04-01T16:32:21.566890
2011-10-31T04:35:02
2011-10-31T04:35:02
1,139,668
0
0
null
null
null
null
UTF-8
C++
false
false
13,373
cpp
#include "sgr_nodes.h" #include <cstdlib> #include <cstring> #include <map> #include <list> #include <iostream> #include <sstream> #include <mat4f.h> #include <bbox2d.h> using namespace std; typedef struct { float mat[16]; } MyMat; list<MyMat> _current_matrix_stack; float _current_matrix[16]; void calcCurrentMatrix () { mat_loadidentity ( _current_matrix ); for ( list<MyMat>::iterator pp=_current_matrix_stack.begin(); pp!=_current_matrix_stack.end(); ++pp ) { mat_multmatrix ( _current_matrix, pp->mat ); } } // -------------------------------------------------------------------------------- int SLCNode::getDepth() { SLCNode* p = parent; int depth = 0; while ( p != 0 ) { if ( p->getType() != SLC_TRANSFORM ) depth++; p = p->parent; } return depth; } void SLCNode::addChild ( SLCNode* node ) { children.push_back ( node ); node->parent = this; } void SLCNode::push_front_child ( SLCNode* node ) { children.push_front ( node ); node->parent = this; } // -------------------------------------------------------------------------------- SLCSceneNode::SLCSceneNode ( const char* gname ) : SLCNode(), name(gname) { } string SLCSceneNode::toXML () const { stringstream ss; ss << "<scene name=\"" << name << "\">" << endl; for ( list<SLCNode*>::const_iterator pp=children.begin(); pp!=children.end(); ++pp ) ss << (*pp)->toXML(); ss << "</scene>" << endl; return ss.str(); } // -------------------------------------------------------------------------------- SLCMaterial::SLCMaterial ( const char* nm ) : SLCNode() { name = nm; foreground_color = vec4i ( 0, 0, 0, 1 ); background_color = vec4i ( 0, 0, 0, 1 ); linetype = 0xFFFF;//LINETYPE_SOLID; linewidth = 1; fontfilename = ""; texturefilename = ""; } string SLCMaterial::toXML () const { stringstream ss; ss << "<material id=\"" << name << "\">" << endl; ss << "<color foregroud_color=\"" << foreground_color.x() << ' ' << foreground_color.y() << ' ' << foreground_color.z() << ' ' << foreground_color.w() << "\" background_color=\"" << background_color.x() << ' ' << background_color.y() << ' ' << background_color.z()<< ' ' << background_color.w() << "\"/>" << endl; ss << "<line pattern=\"" << linetype << "\" factor=\"" << linetypefactor << "\" width=\"" << linewidth << "\"/>" << endl; if ( fontfilename != "" ) ss << "<font path=\"" << fontfilename << "\"/>" << endl; if ( texturefilename != "" ) ss << "<texture path=\"" << texturefilename << "\"/>" << endl; ss << "</material>" << endl; return ss.str(); } // -------------------------------------------------------------------------------- SLCLayerNode::SLCLayerNode ( const char* lname, SLCMaterial* bindmaterial ) : SLCNode(), name(lname), bindmat(bindmaterial) { visible = true; } string SLCLayerNode::toXML () const { stringstream ss; ss << "<layer name=\"" << name << "\">" << endl; for ( list<SLCNode*>::const_iterator pp=children.begin(); pp!=children.end(); ++pp ) ss << (*pp)->toXML(); ss << "</layer>" << endl; return ss.str(); } // -------------------------------------------------------------------------------- SLCLODNode::SLCLODNode () : SLCNode() { } string SLCLODNode::toXML () const { stringstream ss; ss << "<lod "; if ( false == scales.empty() ) { ss << "\""; for ( list<float>::const_iterator pp=scales.begin(); pp!=scales.end(); ++pp ) ss << *pp << ' '; ss << "\""; } ss << ">" << endl; for ( list<SLCNode*>::const_iterator pp=children.begin(); pp!=children.end(); ++pp ) ss << (*pp)->toXML(); ss << "</lod>" << endl; return ss.str(); } // -------------------------------------------------------------------------------- SLCLODPageNode::SLCLODPageNode () : SLCNode() { delayloading = false; imposter = false; kdtree = ""; } string SLCLODPageNode::toXML () const { stringstream ss; ss << "<lodpage delayloading=\"" << delayloading << "\" imposter=\"" << imposter << "\""; if ( kdtree != "" ) ss << " kdtree=\"" << kdtree << "\""; if ( children.empty() ) { ss << "/>" << endl; return ss.str(); } ss << ">" << endl; for ( list<SLCNode*>::const_iterator pp=children.begin(); pp!=children.end(); ++pp ) ss << (*pp)->toXML(); ss << "</lodpage>" << endl; return ss.str(); } // -------------------------------------------------------------------------------- SLCPrimitiveNode::SLCPrimitiveNode ( SLCMaterial* mat ) : SLCNode() { bindmat = mat; } SLCPrimitiveNode::SLCPrimitiveNode ( const SLCPrimitiveNode& rhs ) { bindmat = rhs.bindmat; } // -------------------------------------------------------------------------------- string SLCLineNode::toXML () const { stringstream ss; ss << "<line>" << pnts[0].x() << ' ' << pnts[0].y() << ' ' << pnts[0].z() << ' ' << pnts[1].x() << ' ' << pnts[1].y() << ' ' << pnts[1].z() << "</line>" << endl; return ss.str(); } // -------------------------------------------------------------------------------- SLCFillablePrimitiveNode::SLCFillablePrimitiveNode ( const SLCFillablePrimitiveNode& rhs ) : SLCPrimitiveNode(rhs) { textureScale = rhs.textureScale; textureAngle = rhs.textureAngle; filltexture = rhs.filltexture; } string SLCFillablePrimitiveNode::toXML () const { stringstream ss; if ( filltexture ) ss << "filltexture=\"true\" textureScale=\"" << textureScale << "\" textureAngle=\"" << textureAngle << "\""; return ss.str(); } // -------------------------------------------------------------------------------- string SLCTriNode::toXML () const { stringstream ss; ss << "<triangle>" << pnts[0].x() << ' ' << pnts[0].y() << ' ' << pnts[0].z() << ' ' << pnts[1].x() << ' ' << pnts[1].y() << ' ' << pnts[1].z() << ' ' << pnts[2].x() << ' ' << pnts[2].y() << ' ' << pnts[2].z() << ' ' << "</triangle>" << endl; return ss.str(); } // -------------------------------------------------------------------------------- SLCRectNode::SLCRectNode ( SLCMaterial* mat ) : SLCFillablePrimitiveNode ( mat ) { z = 0.0f; } SLCRectNode::SLCRectNode ( const SLCRectNode& rhs ) : SLCFillablePrimitiveNode ( rhs ) { pnts[0] = rhs.pnts[0]; pnts[1] = rhs.pnts[1]; pnts[2] = rhs.pnts[2]; pnts[3] = rhs.pnts[3]; z = rhs.z; } string SLCRectNode::toXML () const { stringstream ss; float p0[] = { pnts[0].x(), pnts[0].y(), z, 1 }; mat_multvector ( _current_matrix, p0 ); float p1[] = { pnts[2].x(), pnts[2].y(), z, 1 }; mat_multvector ( _current_matrix, p1 ); ss << "<primitive type=\"rect\" bindmaterial=\"" << bindmat->name << "\">" << p0[0] << ' ' << p0[1] << ' ' << p1[0]-p0[0] << ' ' << p1[1]-p0[1] << ' ' << 0 << "</primitive>" << endl; return ss.str(); } SLCPrimitiveNode* SLCRectNode::copy() { return new SLCRectNode (*this); } void SLCRectNode::getMinMax ( float* minmax ) { BBox2d box; box.init ( pnts[0] ); box.expandby ( pnts[1] ); box.expandby ( pnts[2] ); box.expandby ( pnts[3] ); minmax[0] = box.minvec().x(); minmax[1] = box.minvec().y(); minmax[2] = z; minmax[3] = box.maxvec().x(); minmax[4] = box.maxvec().y(); minmax[5] = z; } void SLCRectNode::setRect ( float x, float y, float zz, float w, float h ) { pnts[0] = vec3f(x,y,zz); pnts[1] = vec3f(x+w,y,zz); pnts[2] = vec3f(x+w,y+h,zz); pnts[3] = vec3f(x,y+h,zz); } void SLCRectNode::setSize ( float w, float h ) { float x = pnts[0].x(); float y = pnts[0].y(); float zz = z; pnts[1] = vec3f(x+w,y,zz); pnts[2] = vec3f(x+w,y+h,zz); pnts[3] = vec3f(x,y+h,zz); } // -------------------------------------------------------------------------------- SLCImageNode::SLCImageNode () : SLCRectNode(NULL) { texturefilename = ""; } SLCImageNode::SLCImageNode ( const SLCImageNode& rhs ) : SLCRectNode(rhs) { texturefilename = rhs.texturefilename; } string SLCImageNode::toXML () const { stringstream ss; float p0[] = { pnts[0].x(), pnts[0].y(), z, 1 }; mat_multvector ( _current_matrix, p0 ); float p1[] = { pnts[2].x(), pnts[2].y(), z, 1 }; mat_multvector ( _current_matrix, p1 ); ss << "<primitive type=\"image\" filename=\"" << texturefilename << "\">" << p0[0] << ' ' << p0[1] << ' ' << p1[0]-p0[0] << ' ' << p1[1]-p0[1] << ' ' << 0 << "</primitive>" << endl; return ss.str(); } // -------------------------------------------------------------------------------- SLCTextNode::SLCTextNode ( SLCMaterial* mat ) : SLCPrimitiveNode (mat) { pos.xyz(0, 0, 0); scale = 1; rotz = 0; text = ""; } SLCTextNode::SLCTextNode ( const SLCTextNode& rhs ) : SLCPrimitiveNode(rhs) { pos = rhs.pos; scale = rhs.scale; rotz = rhs.rotz; text = rhs.text; } string SLCTextNode::toXML () const { stringstream ss; float v[] = { pos.x(), pos.y(), pos.z(), 1 }; mat_multvector ( _current_matrix, v ); ss << "<primitive type=\"text\" bindmaterial=\"" << bindmat->name << "\" pos=\"" << v[0] << ' ' << v[1] << ' ' << v[2] << "\" scale=\"" << scale << "\" rotz=\"" << rotz << "\">" << text << "</primitive>" << endl; return ss.str(); } SLCPrimitiveNode* SLCTextNode::copy() { return new SLCTextNode(*this); } void SLCTextNode::getMinMax ( float* minmaxabc ) { } // -------------------------------------------------------------------------------- SLCPLineNode::SLCPLineNode ( SLCMaterial* mat ) : SLCPrimitiveNode (mat) { z = 0.0f; } SLCPLineNode::SLCPLineNode ( const SLCPLineNode& rhs ) : SLCPrimitiveNode(rhs) { pnts.assign ( rhs.pnts.begin(), rhs.pnts.end() ); z = rhs.z; } string SLCPLineNode::toXML () const { stringstream ss; ss << "<primitive type=\"pline\" bindmaterial=\"" << bindmat->name << "\">"; for ( vector<vec2f>::const_iterator pp=pnts.begin(); pp!=pnts.end(); ++pp ) { float v[] = { pp->x(), pp->y(), z, 1 }; mat_multvector ( _current_matrix, v ); ss << v[0] << ' ' << v[1] << ' ' << v[2] << ' '; } ss <<"</primitive>" << endl; return ss.str(); } SLCPrimitiveNode* SLCPLineNode::copy() { return new SLCPLineNode(*this); } void SLCPLineNode::getMinMax ( float* minmax ) { BBox2d box; vector<vec2f>::iterator pp=pnts.begin(); box.init ( *pp ); for ( ++pp; pp!=pnts.end(); ++pp ) box.expandby ( *pp ); minmax[0] = box.minvec().x(); minmax[1] = box.minvec().y(); minmax[2] = z; minmax[3] = box.maxvec().x(); minmax[4] = box.maxvec().y(); minmax[5] = z; } // -------------------------------------------------------------------------------- SLCPolyNode::SLCPolyNode ( SLCMaterial* mat ) : SLCFillablePrimitiveNode (mat) { z = 0.0f; } SLCPolyNode::SLCPolyNode ( const SLCPolyNode& rhs ) : SLCFillablePrimitiveNode(rhs) { pnts.assign(rhs.pnts.begin(), rhs.pnts.end()); z = rhs.z; } string SLCPolyNode::toXML () const { stringstream ss; ss << "<primitive type=\"poly\" bindmaterial=\"" << bindmat->name << "\" " << SLCFillablePrimitiveNode::toXML () << ">"; for ( vector<vec2f>::const_iterator pp=pnts.begin(); pp!=pnts.end(); ++pp ) { float v[] = { pp->x(), pp->y(), z, 1 }; mat_multvector ( _current_matrix, v ); ss << v[0] << ' ' << v[1] << ' ' << v[2] << ' '; } // ss << pp->x() << ' ' << pp->y() << ' ' << z << ' '; ss <<"</primitive>" << endl; return ss.str(); } SLCPrimitiveNode* SLCPolyNode::copy() { return new SLCPolyNode(*this); } void SLCPolyNode::getMinMax ( float* minmax ) { BBox2d box; vector<vec2f>::iterator pp=pnts.begin(); box.init ( *pp ); for ( ++pp; pp!=pnts.end(); ++pp ) box.expandby ( *pp ); minmax[0] = box.minvec().x(); minmax[1] = box.minvec().y(); minmax[2] = z; minmax[3] = box.maxvec().x(); minmax[4] = box.maxvec().y(); minmax[5] = z; } // -------------------------------------------------------------------------------- SLCTransformNode::SLCTransformNode () : SLCNode() { mat_loadidentity ( mat ); } string SLCTransformNode::toXML () const { MyMat m; memcpy ( m.mat, mat, sizeof(float)*16 ); _current_matrix_stack.push_back ( m ); calcCurrentMatrix (); stringstream ss; // ss << "<transform mat=\"" << // mat[0] << ' ' << mat[1] << ' ' << mat[2] << ' ' << mat[3] << ' ' << // mat[4] << ' ' << mat[5] << ' ' << mat[6] << ' ' << mat[7] << ' ' << // mat[8] << ' ' << mat[9] << ' ' << mat[10] << ' ' << mat[11] << ' ' << // mat[12] << ' ' << mat[13] << ' ' << mat[14] << ' ' << mat[15] << ' ' << "\">" << endl; for ( list<SLCNode*>::const_iterator pp=children.begin(); pp!=children.end(); ++pp ) ss << (*pp)->toXML(); // ss <<"</transform>" << endl; return ss.str(); } // --------------------------------------------------------------------------------
[ [ [ 1, 486 ] ] ]
ac9b0df9b657e03a3594231321f45533314b0f0c
7c51155f60ff037d1b8d6eea1797c7d17e1d95c2
/Demo/ClassData.cpp
46a3f8fa0c2a421d29dcd756500881fd6e08ded9
[]
no_license
BackupTheBerlios/ejvm
7258cd180256970d57399d0c153d00257dbb127c
626602de9ed55a825efeefd70970c36bcef0588d
refs/heads/master
2020-06-11T19:47:07.882834
2006-07-10T16:39:59
2006-07-10T16:39:59
39,960,044
0
0
null
null
null
null
UTF-8
C++
false
false
14,814
cpp
#include "ClassData.h" #include "Heap.h" #include <stdio.h> #include "ExecutionEng.h" /* the constructor takes a stream of bytes as a parameter */ ClassData::ClassData(const char *name, const byte inputFile []) { int inputPtr; // pointer to be advanced in the input stream u2 i; u2 CPCount; // ////f//printf(stdout,"Let the file parsing BEGIN\n"); /* here, there exist magic number, minor and major numbers */ inputPtr=8; // initialize inputPtr at the beginning of CPCount /* extract constant pool count and advance the input pointer */ CPCount =( ( (u2)inputFile[inputPtr] )<<8) + inputFile[inputPtr+1]; inputPtr+=2; // ////f//printf(stdout,"getting the constant pool count => %d entries\n",CPCount-1); ////printf("Ask the heap to create the constant pool\n"); /* ask the heap to create the constant pool */ constantPool = Heap::createCP(inputFile,CPCount, &inputPtr,this); ////printf("Getting the acess flags of the class\n"); /* extract accessFlags, thisClass, superClass and advance the input pointer */ accessFlags = ( ((u2)inputFile[inputPtr])<<8 ) + inputFile[inputPtr+1]; inputPtr+=2; ////f//printf(stdout,"getting the access flags of the class\n"); thisClass = ( ((u2)inputFile[inputPtr])<<8 ) + inputFile[inputPtr+1]; inputPtr+=2; ////f//printf(stdout,"getting the current class index in the constant pool => %d \n",thisClass); ////printf("getting the current class index in the constant pool => %d \n",thisClass); superClass = ( ((u2)inputFile[inputPtr])<<8) + inputFile[inputPtr+1]; inputPtr+=2; //f//printf(stdout,"getting the super class index in the constant pool => %d \n",superClass); ////printf("getting the super class index in the constant pool => %d \n",superClass); /* extract interfacesCount and advance the input pointer */ interfacesCount =( ((u2)inputFile[inputPtr])<<8 ) + inputFile[inputPtr+1]; inputPtr+=2; //f//printf(stdout,"getting the interfaces count => %d \n",interfacesCount); ////printf("getting the interfaces count => %d \n",interfacesCount); /* create the interfaces array and fill it */ ////printf("create the interfaces array and fill it\n"); interfaces = Heap::createInterfaces(interfacesCount); for( i=0 ; i < interfacesCount ; i++) { interfaces[i] = ( ((u2)inputFile[inputPtr])<<8 ) + inputFile[inputPtr+1]; inputPtr+=2; } /* extract fieldsCount and advance the input pointer */ fieldsCount = ( ((u2)inputFile[inputPtr])<<8 ) + inputFile[inputPtr+1]; inputPtr+=2; ////printf("getting the fields count in this class=> %d \n",fieldsCount); //f//printf(stdout,"getting the fields count in this class=> %d \n",fieldsCount); ////printf("create the fields table and fill it\n"); /* create the fields table and fill it */ fields = Heap::createFileds(fieldsCount); for( i=0 ; i < fieldsCount ; i++) fields[i] = Heap::createFieldData(inputFile, &inputPtr,constantPool); /* extract methodsCount and advance the input pointer */ methodsCount =( ((u2)inputFile[inputPtr])<<8 )+ inputFile[inputPtr+1]; inputPtr+=2; //f//printf(stdout,"getting the methods count in this class=> %d \n",methodsCount); ////printf("getting the methods count in this class=> %d \n",methodsCount); /* create the methods table and fill it */ ////printf("create the methods table and fill it\n"); methods = Heap::createMethods(methodsCount); for(i=0 ; i < methodsCount ; i++) methods[i] = Heap::createMethodData(inputFile, &inputPtr,constantPool); /* here, there exist the attributes count and attributes table */ /* to load and resolve the super class */ ////printf("load and resolve the super class NOW COMMENTED IN CODE\n"); //if(strcmp(constantPool->getClassName(superClass),"java/lang/Object")!=0)//it is not the java/lang/Object.class Class if(superClass!=0)//dont load superclass if it is java/lang/Object { constantPool-> getClassData(superClass); // } /* to load and resolve the superInterfaces */ ////printf("load and resolve the super interfaces NOW COMMENTED IN CODE\n"); for( i=0 ; i < interfacesCount ; i++) constantPool-> getClassData(interfaces[i]); } //call prepare this->prepare(); } /*****************ARRAY USAGE**********************/ /*****************ARRAY USAGE**********************/ //new constructor specific for arrays ClassData::ClassData(const char* arrayName) { /*****************ARRAY USAGE**********************/ /*****************ARRAY USAGE**********************/ ////printf("Creating the class Data of an array\n"); ////printf("Creating the constant pool of an array\n"); constantPool = Heap::createArrayCP(arrayName,this ); accessFlags = 35;//public thisClass = 1; superClass = 2; interfacesCount =0; interfaces = NULL; fieldsCount = 0; fields = NULL; methodsCount =0; methods = NULL; // constantPool-> getClassData(superClass); } ClassData::~ClassData() { } void ClassData:: prepare(void) { ////printf("the preparation phase of the class\n"); /* get the size of an object of the parent class */ // if(strcmp(constantPool->getClassName(superClass),"java/lang/Object")==0) if(superClass==0)//the object size of the Class java/lang/Object = 0 objectSize=0; else { ClassData * parentClass=constantPool->getClassData(superClass); objectSize = parentClass-> getObjectSize(); } //objectSize=0; for(u2 i=0; i < fieldsCount; i++) { /* if the field is static, then set it to the default value */ if(fields[i]-> isStatic()) { fields[i]-> setDefaultValue(); ////printf("setting the default value for a static feild\n"); } else /* this part is for nonstatic fields only */ { ////printf("Non static feild--->set the offset of the field in the cbject image\n"); /* set the offset of the field in the cbject image */ fields[i]->setInstanceVariableSize(); fields[i]-> setOffset(objectSize); /* update the value of the object size */ objectSize += fields[i]-> getSize(); } } /* now create the method table */ ///////////////////////createMethodTable(); } bool ClassData:: isInitialized(void) { return initialized; } void ClassData:: initialize(void) { ////printf("initializing the class--> commented now \n"); ////printf("\tso it does only a loop to get the method clinit from the methods array\n"); ClassData * myParent; Method * clInit=NULL; u2 i; // if(strcmp(constantPool->getClassName(superClass),"java/lang/Object")!=0) if(superClass!=0) { myParent = constantPool->getClassData(superClass); if( !(myParent->isInitialized()) ) myParent->initialize(); } /* search in this class */ for(i=0; i<methodsCount ; i++) { if(strcmp(methods[i]-> getName() ,"<clinit>")==0 ) /* another method */ { clInit = methods[i]; break; } } initialized = true; if(clInit) { ExecutionEng * exec=ExecutionEng::getInstance(); exec->executeMethod(NULL,clInit); //;//execEng->exec(clInit); } //initialized = true; } Field * ClassData:: lookupField(const char *name,const char*desc) { ////printf("return the Field block using its name and descriptor\n"); u2 i; /* search in this class */ for(i=0; i<fieldsCount ; i++) { if( (strcmp(name , fields[i]-> getName())==0 ) && (strcmp(desc , fields[i]->getDesc() )==0) ) /* another method */ return fields[i]; } ////printf("searching the super interfaces for this field\n"); /* search the super interfaces */ /* what is meant by interface extended by this class */ ClassData * interface; Field * field; for(i=0; i<interfacesCount ; i++) { interface = constantPool-> getClassData(interfaces[i]); if( (field = interface->lookupField(name,desc)) != NULL) return field; } /* search in the super class */ ////printf("searching the super class for this field\n"); ClassData * myParent=constantPool->getClassData(superClass); return myParent->lookupField(name,desc); } Method * ClassData:: lookupMethod(const char *name, const char*desc) { ////printf("return the Method block using its name and descriptor\n"); if(this->isInterface()) ;/////////exception(); u2 i; /* search in this class */ for(i=0; i<methodsCount ; i++) { if( (strcmp(name , methods[i]-> getName() )==0) && (strcmp(desc , methods[i]->getDesc() )==0) ) /* another method */ return methods[i]; } ////printf("searching the super class for this Method\n"); /* search in the super class */ Method * method; ClassData * myParent=constantPool->getClassData(superClass); if( (method=myParent->lookupMethod(name,desc)) != NULL) return method; /* search the super interfaces */ /* what is meant by sueprinterface of interfaces * directly implemented by this class */ ////printf("searching the super interfaces for this Method\n"); ClassData * interface; for(i=0; i<interfacesCount ; i++) { interface = constantPool-> getClassData(interfaces[i]); if( (method = interface->lookupMethod(name,desc)) != NULL) return method; } return NULL; } Method* ClassData:: lookupInterfaceMethod(const char *name,const char *desc) { ////printf("look up interface method\n"); if(! (this->isInterface()) ) ;//////////////////////// u2 i; /* search in this interface */ ////printf("search in this interface\n"); for(i=0; i<methodsCount ; i++) { if( (strcmp(name ,methods[i]-> getName())==0) && (strcmp(desc , methods[i]->getDesc() )==0) ) /* another method */ return methods[i]; } ////printf("search in this super interfaces\n"); /* search the super interfaces */ /* what is meant by sueprinterface of interfaces * directly implemented by this class */ ClassData * interface; Method * method; for(i=0; i<interfacesCount ; i++) { interface = constantPool-> getClassData(interfaces[i]); if( (method = interface->lookupInterfaceMethod(name,desc)) != NULL) return method; } /* search in class Object */ return NULL; } u2 ClassData:: getObjectSize(void) { return objectSize; } /* till now assume that there is no method * overriding for simpilicity */ void ClassData::createMethodTable(void) { ////printf("Create the method table\n"); u2 count,i; ClassData * parentClass=constantPool->getClassData(superClass); Method ** tempTable = parentClass->getMethodTable(); count = parentClass->methodTableEntriesCount; methodTableEntriesCount = count + methodsCount; methodTable = new Method * [methodTableEntriesCount]; for(i=0 ;i<count ;i++) methodTable[i] = tempTable[i]; for(i=0 ;i<methodsCount ;i++) methodTable[i+count] = methods[i]; } Method ** ClassData::getMethodTable(void) { return methodTable; } bool ClassData:: canCastedTo(ClassData *classData) { ////printf("check the validation of casting this class to another given class\n"); /* if this class is a class */ if( ! isInterface() ) { ////printf("This class is of type class not interface\n"); /* the other class is a class */ if( !(classData->isInterface()) ) { ////printf("the class to be casted to is of type class\n"); ////printf("check if this class is a descendent of the given class\n"); if(isDescendentOf(classData)||this==classData) return true; } else /* the other class is an interface */ { ////printf("the class to be casted to is of type interface\n"); ////printf("check if this class implements the given interface\n"); if(isImplement(classData)) return true; } } /* this class is an interface */ else { ////printf("This class is of type class not interface\n"); /* the other class is a class */ if( !(classData->isInterface()) ) { ////printf("the class to be casted to is of type class\n"); ////printf("check if the class to be casted to is the Object class\n"); if(classData->getFQName()=="Object")//another function return true; } else /* the other class is an interface */ { ////printf("the class to be casted to is of type interface\n"); ////printf("check if this class is a descendent of the given interface\n"); ///////what is meant by superinterfaces if(this==classData||isDescendentOf(classData)) return true; } } return false; } bool ClassData:: isImplement(ClassData * theInterface) { ////printf("searches the interfaces array for the given interface"); ////printf(" to check if this class implements this given interface\n"); for(u2 i=0; i<interfacesCount; i++) { if(theInterface==constantPool->getClassData(i)) return true; } return false; } char * ClassData :: getFQName(void) { return constantPool->getClassName(thisClass); } bool ClassData:: isPublic(void) { ////printf("Check the access flags of the class to check if it is public\n"); if( ( accessFlags & ( ( (u2)1 ) ) ) ==0 ) return false; return true; } bool ClassData:: isFinal(void) { ////printf("Check the access flags of the class to check if it is final\n"); if( ( accessFlags & ( ( (u2)1 )<<1 ) ) ==0 ) return false; return true; } bool ClassData:: treatSuperMethodsSpecially() { ////printf("Check the access flags of the class to check if it treats the super class methods specially\n"); if( ( accessFlags & ( ( (u2)1 )<< 5 ) ) ==0 ) return false; return true; } bool ClassData:: isInterface(void) { ////printf("Check the access flags of the class to check if it is an interface\n"); if( ( accessFlags & ( ( (u2)1 )<< 9 ) ) ==0 ) return false; return true; } bool ClassData:: isAbstract(void) { ////printf("Check the access flags of the class to check if it is abstract class\n"); if( ( accessFlags & ( ( (u2)1 )<< 10 ) ) ==0 ) return false; return true; } Method * ClassData:: getActualMethod(Method* nonActualMethod) { ////printf("Get actual method--> it returns NULL so far\n"); ////printf("--------------->if U reached here the error is a call to getActualMethod\n"); return NULL; } bool ClassData:: isDescendentOf(ClassData* classData) { ////printf("Check if this class is a descendent of the given class\n"); ClassData * myParent=constantPool->getClassData(superClass); if( classData == myParent ) return true; return myParent->isDescendentOf(classData); } ClassData* ClassData::getSuperClassData() { ////printf("Get super class data --> it returns NULL so far\n"); ////printf("--------------->if U reached here the error is a call to getSuperClassData\n"); //if(strcmp(constantPool->getClassName(superClass),"java/lang/Object") ==0) if(superClass!=0) return NULL; else { ClassData * myParent = constantPool->getClassData(superClass); return myParent;} //return NULL; }
[ "almahallawy" ]
[ [ [ 1, 440 ] ] ]
af7de1d0ffc50aee54482a5fdc4a58aaa452407e
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak.Samples/SwapChain.cpp
dc2223498d02ca51fe1d7ed22a68541b4bc190ad
[]
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
3,732
cpp
#include <Halak.Samples/Samples.h> #include <Halak/Colors.h> #include <Halak/DisplaySwapChain.h> #include <Halak/Font.h> #include <Halak/FontLibrary.h> #include <Halak/GameFramework.h> #include <Halak/GameNode.h> #include <Halak/GameStructure.h> #include <Halak/GameWindow.h> #include <Halak/GraphicsDevice.h> #include <Halak/Math.h> #include <Halak/SpriteRenderer.h> using namespace Halak; class SwapChainSampleApp : public GameFramework { GameWindow* otherWindow; DisplaySwapChain* otherSwapChain; FontLibrary* fontLibrary; SpriteRenderer* spriteRenderer; FontPtr font; float textRotation; Vector2 textSize; virtual void Initialize() { GetWindow()->SetSize(Point(800, 600)); GetWindow()->SetTitle("Mainwindow"); GetWindow()->MoveToScreenCenter(); GameFramework::Initialize(); otherWindow = new GameWindow(); otherWindow->SetSize(Point(200, 100)); otherWindow->SetTitle("SubWindow"); otherWindow->SetVisible(true); otherWindow->SetPosition(Point::Zero); GetStructure()->GetRoot()->AttachChild(otherWindow); otherSwapChain = new DisplaySwapChain(GetGraphicsDevice(), otherWindow); GetStructure()->GetRoot()->AttachChild(otherSwapChain); fontLibrary = new FontLibrary(GetGraphicsDevice()); spriteRenderer = new SpriteRenderer(GetGraphicsDevice()); GetStructure()->GetRoot()->AttachChild(fontLibrary); GetStructure()->GetRoot()->AttachChild(spriteRenderer); font = new Font(fontLibrary); font->SetFace("malgun.ttf"); font->SetSize(20.0f); font->SetColor(Colors::Blue); textRotation = 0.0f; textSize = font->Measure("Hello"); } virtual void Finalize() { font.Reset(); GameFramework::Finalize(); } virtual void Update(float dt, uint timestamp) { GameFramework::Update(dt, timestamp); textRotation += dt * Math::TwoPi; } virtual void Draw() { GetGraphicsDevice()->Clear(); spriteRenderer->Begin(); spriteRenderer->Push(Matrix4::Translation(Vector3(-textSize.X * 0.5f - 100.0f, -textSize.Y * 0.5f - 100.0f, 0.0f)) * Matrix4::RotationZ(textRotation) * Matrix4::Translation(Vector3(+textSize.X * 0.5f + 100.0f, +textSize.Y * 0.5f + 100.0f, 0.0f))); spriteRenderer->DrawString(Vector2(100.0f, 100.0f), font, "Hello"); spriteRenderer->Pop(); char fpsString[32] = { '\0', }; _snprintf(fpsString, sizeof(fpsString), "%.4f", GetFPS()); spriteRenderer->DrawString(Vector2(10.0f, 10.0f), font, fpsString); spriteRenderer->End(); GameFramework::Draw(); } virtual void EndDraw() { GameFramework::EndDraw(); otherSwapChain->BeginDraw(); GetGraphicsDevice()->Clear(Colors::YellowGreen); spriteRenderer->Begin(); spriteRenderer->Push(Matrix4::Translation(Vector3(-textSize.X * 0.5f - 10.0f, -textSize.Y * 0.5f - 10.0f, 0.0f)) * Matrix4::RotationZ(-textRotation) * Matrix4::Translation(Vector3(+textSize.X * 0.5f + 10.0f, +textSize.Y * 0.5f + 10.0f, 0.0f))); spriteRenderer->DrawString(Vector2(10.0f, 10.0f), font, "Hello"); spriteRenderer->Pop(); spriteRenderer->End(); otherSwapChain->EndDraw(); otherSwapChain->Present(); } }; void Halak::Samples::SwapChainSample(const std::vector<const char*>& /*args*/) { SwapChainSampleApp app; app.Run(); }
[ [ [ 1, 110 ] ] ]
11ce4443270dd0a5d036b09b590e195f8a4b3ec7
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/GUIRadioButton.h
536a4d74093ef1895ada6bc3fa2c44ac6d81c8af
[]
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
1,460
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: GUIRadioButton.h Version: 0.02 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_GUIRADIOBUTTON_H_ #define __INC_GUIRADIOBUTTON_H_ #include "GUIControl.h" #include "Prerequisities.h" namespace nGENE { /** Radio button control. */ class nGENEDLL GUIRadioButton: public GUIControl { private: GUIGroupBox* m_pGroup; ///< A group this radio button belongs to bool m_bValue; ///< Value of the check box public: GUIRadioButton(); ~GUIRadioButton(); void render(ScreenOverlay* _overlay, Vector2& _position); void setValue(bool _value); bool getValue() const; void mouseClick(uint _x, uint _y); void setGroup(GUIGroupBox* _group); }; inline void GUIRadioButton::setValue(bool _value) { m_bValue = _value; } //---------------------------------------------------------------------- inline bool GUIRadioButton::getValue() const { return m_bValue; } //---------------------------------------------------------------------- inline void GUIRadioButton::setGroup(GUIGroupBox* _group) { m_pGroup = _group; } //---------------------------------------------------------------------- } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 68 ] ] ]
a829fae74e526d21a824a4319f9aed4bb4f0b365
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/test/testSetting/testSetting.cpp
ad78f741512ba9975fa3009aedec69bd974da687
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
GB18030
C++
false
false
4,049
cpp
// testSetting.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include ".\dnssettingtest.h" #include ".\authorizetest.h" #include ".\eyecaretest.h" #include ".\calculargraphtest.h" #include ".\contentsettingtest.h" #include ".\configreadertest.h" #include ".\searchruletest.h" #include ".\onlinehoursettingtest.h" #include ".\webhistoryrecordtest.h" #include ".\autocleantest.h" #include ".\hotkeysettingtest.h" #include ".\appcontroltest.h" #include <boost\test\included\unit_test.hpp> using namespace boost::unit_test; boost::unit_test::test_suite* init_unit_test_suite( int argc, char* argv[] ) { // AppControlTest framework::master_test_suite().add( BOOST_TEST_CASE(&testAppConrol) ); // AuthorizeTest framework::master_test_suite().add( BOOST_TEST_CASE(&TestCheckPassword) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestChangePassword) ); // AutocleanTest framework::master_test_suite().add( BOOST_TEST_CASE(&testAutoclean) ); // CalculargraphTest framework::master_test_suite().add( BOOST_TEST_CASE(&TestForceswitch) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestSetASmallerTime) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestCulargraph) ); framework::master_test_suite().add( BOOST_TEST_CASE(&testCalarStopTimer) ); framework::master_test_suite().add( BOOST_TEST_CASE(&testMulitSetTimeLeft) ); framework::master_test_suite().add( BOOST_TEST_CASE(&testMultiStopTimer) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestMultiCalculargraph) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestSetTimeEscape) ); // ConfigReaderTest framework::master_test_suite().add( BOOST_TEST_CASE(&TestReadFromFile) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestSaveFile) ); // ContentSettingTest framework::master_test_suite().add( BOOST_TEST_CASE(&TestEnableCheck) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestNeedCheck) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestTwoModel) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestTwoWrong) ); // DNSSettingTest framework::master_test_suite().add( BOOST_TEST_CASE(&testCheck) ); framework::master_test_suite().add( BOOST_TEST_CASE(&testFuzzeCheck) ); framework::master_test_suite().add( BOOST_TEST_CASE(&testTwoModels) ); framework::master_test_suite().add( BOOST_TEST_CASE(&testJustPassedWhiteDNS) ); // EyecareTest framework::master_test_suite().add( BOOST_TEST_CASE(&TestPassword) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestSwitchState) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestTimeSetting) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestSetLeft) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestMultiModelSwitch) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestAfterModelSwitch) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestModelsInParentAndChild) ); // HotkeySettingTest framework::master_test_suite().add( BOOST_TEST_CASE(&testHotkey) ); // OnlineHourSettingTest framework::master_test_suite().add( BOOST_TEST_CASE(&TestOnlineHour) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestTowModeSwitched) ); // SearchRuleTest framework::master_test_suite().add( BOOST_TEST_CASE(&TestSeachRuleSetting) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestSeachEnabled) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestParentChildMode) ); // WebHistoryRecordTest framework::master_test_suite().add( BOOST_TEST_CASE(&TestDefault) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestRegular) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestEnable) ); framework::master_test_suite().add( BOOST_TEST_CASE(&TestParentMode) ); return 0; }
[ "ynkhpp@1a8edc88-4151-0410-b40c-1915dda2b29b", "[email protected]" ]
[ [ [ 1, 4 ], [ 6, 8 ], [ 18, 18 ] ], [ [ 5, 5 ], [ 9, 17 ], [ 19, 86 ] ] ]
99f1fee56cf36a61bfdc1f5a6599a94f09cc4837
906e87b1936397339734770be45317f06fe66e6e
/src/TGModColour.cpp
535f92ff06a9a2252b8beae94c9bc206d871bec4
[]
no_license
kcmohanprasad/tgui
03c1ab47e9058bc763b7e6ffc21a37b4358369bf
9f9cf391fa86b99c7d606c4d196e512a7b06be95
refs/heads/master
2021-01-10T08:52:18.629088
2007-05-17T04:42:58
2007-05-17T04:42:58
52,069,498
0
0
null
null
null
null
UTF-8
C++
false
false
1,850
cpp
//----------------------------------------------------------------------------- // This source file is part of TGUI (Tiny GUI) // // Copyright (c) 2006-2007 Tubras Software, Ltd // Also see acknowledgements in Readme.html // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to // do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //----------------------------------------------------------------------------- #include <tgui.h> namespace TGUI { //----------------------------------------------------------------------- // T G M o d C o l o u r //----------------------------------------------------------------------- TGModColour::TGModColour(TGControl* target,float duration, TGColour from, TGColour to) : TGModLerp(target,duration), m_from(from), m_to(to) { } }
[ "pc0der@a5263bde-0223-0410-8bbb-1954fdd97a2f" ]
[ [ [ 1, 41 ] ] ]
adb3fd4a3114f4657c156bad078a178c64db3bf9
bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2
/Open GL Basic Engine/source/glutFramework/glutFramework/oglGameVars.cpp
ccd6d37a4d933df3a1147163f42fad50060d29fc
[]
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
9,100
cpp
#include "oglGameVars.h" #include<fstream> #include<iostream> #include <string> #include <sstream> #include <cmath> #include <ctime> using namespace std; oglGameVars* oglGameVars::pinstance = 0;// initialize pointer oglGameVars* oglGameVars::Instance () { if (pinstance == 0) // is it the first call? { pinstance = new oglGameVars; // create sole instance } return pinstance; // address of sole instance } oglGameVars::oglGameVars() { init(); } //======================================== // Non singleton functions here wee. void oglGameVars::init() { srand ( time(NULL) ); // always had it, always will bacardi = new oglTexture2D(); bacardi->loadImage("buttons/bacardi.png", imageSize, imageSize); //======================= // Marble Game marbleImage = new oglTexture2D(); emptyImage = new oglTexture2D(); selectedImage = new oglTexture2D(); possibilityImage = new oglTexture2D(); boardImage = new oglTexture2D(); hintButton = new oglTexture2D(); resetButton = new oglTexture2D(); undoButton = new oglTexture2D(); marbleImage->loadImage("marbleNormal.png", imageSize, imageSize); emptyImage->loadImage("emptyPeg.png", imageSize, imageSize); selectedImage->loadImage("marbleBlue.png", imageSize, imageSize); possibilityImage->loadImage("possibleMove.png", imageSize, imageSize); boardImage->loadImage("pyramid.png", 768, 768); undoButton->loadImage("undoButton.png", 128, 64); resetButton->loadImage("resetButton.png", 128, 64); hintButton->loadImage("hintButton.png", 128, 64); //======================= // RockPaperScissors Game RPSBG = new oglTexture2D(); RPSRock = new oglTexture2D(); RPSPaper = new oglTexture2D(); RPSScissors = new oglTexture2D(); playerWins = new oglTexture2D(); cpuWins = new oglTexture2D(); tieHand = new oglTexture2D(); RPSBG->loadImage("rpsBackground.png", 1024, 768); RPSRock->loadImage("rock.png", 128, 128); RPSPaper->loadImage("paper.png", 128, 128); RPSScissors->loadImage("scissors.png", 128, 128); playerWins->loadImage("playerWins.png", 128, 128); cpuWins->loadImage("cpuWins.png", 128, 128); tieHand->loadImage("tieHand.png", 128, 128); //======================= // RedvBlue Game rvbTile = new oglTexture2D(); rvbObstacle = new oglTexture2D(); rvbNullTile = new oglTexture2D(); rvbBlackTile = new oglTexture2D(); rvbEntityArrow = new oglTexture2D(); rvbEntityBlue = new oglTexture2D(); rvbEntityBlueN = new oglTexture2D(); rvbEntityRed = new oglTexture2D(); rvbEntityRedN = new oglTexture2D(); rvbEntitySelected = new oglTexture2D(); rvbEntityTarget = new oglTexture2D(); rvbSelectionPix = new oglTexture2D(); redPathImg = new oglTexture2D(); bluePathImg = new oglTexture2D(); rvbHeyYouWithTheFace = new oglTexture2D(); redActive = new oglTexture2D(); blueActive = new oglTexture2D(); godActive = new oglTexture2D(); fog = new oglTexture2D(); redPixel = new oglTexture2D(); greenPixel = new oglTexture2D(); yellowPixel = new oglTexture2D(); deadIcon = new oglTexture2D(); healthBorder = new oglTexture2D(); pistolShotImg = new oglTexture2D(); riffleShotImg = new oglTexture2D(); shottyShotImg = new oglTexture2D(); helpScreen = new oglTexture2D(); helpButton = new oglTexture2D(); rvbTile->loadImage("baseTile.png", 128, 128); rvbObstacle->loadImage("obstacle.png", 128, 128); rvbNullTile->loadImage("nullTile.png", 128, 128); rvbBlackTile->loadImage("blackTile.png", 128, 128); rvbEntityArrow->loadImage("entityArrow.png", 128, 128); rvbEntityBlue->loadImage("entityBlue.png", 128, 128); rvbEntityBlueN->loadImage("entityBlueN.png", 128, 128); rvbEntityRed->loadImage("entityRed.png", 128, 128); rvbEntityRedN->loadImage("entityRedN.png", 128, 128); rvbEntitySelected->loadImage("entitySelected.png", 128, 128); rvbEntityTarget->loadImage("entityTarget.png", 128, 128); rvbSelectionPix->loadImage("greenPixel.png", 1, 1); redPathImg->loadImage("rvbRedPath.png", 128, 128); bluePathImg->loadImage("rvbBluePath.png", 128, 128); rvbHeyYouWithTheFace->loadImage("entityTargetEntity.png", 128, 128); redActive->loadImage("rvbRedActive.png", 1024, 64); blueActive->loadImage("rvbBlueActive.png", 1024, 64); godActive->loadImage("rvbGodActive.png", 1024, 64); fog->loadImage("rvbFog.png", 128, 128); redPixel->loadImage("redPixel.png", 1, 1); greenPixel->loadImage("greenPixel.png", 1, 1); yellowPixel->loadImage("yellowPixel.png", 1, 1); deadIcon->loadImage("rvbEntityDead.png", 128, 128); healthBorder->loadImage("rvbHealthBorder.png", 128, 128); pistolShotImg->loadImage("rvbBulletOrange.png", 16, 16); riffleShotImg->loadImage("rvbBulletYellow.png", 16, 16); shottyShotImg->loadImage("rvbBulletShotgun.png", 8, 8); helpScreen->loadImage("rvbHelpScreen.png", 800, 446); helpButton->loadImage("helpButton.png", 150, 100); loadFonts(); } void oglGameVars::loadFonts() { fontArial32.open ("fonts\\arialSpriteFontBlack.png", 32); fontArial24.open ("fonts\\arialSpriteFontBlack.png", 24); fontArial18.open ("fonts\\arialSpriteFontBlack.png", 18); fontArial16.open ("fonts\\arialSpriteFontBlack.png", 16); fontArial12.open ("fonts\\arialSpriteFontBlack.png", 14); fontDigital32.open ("fonts\\digitalSpriteFontBlack.png", 32); fontDigital16.open ("fonts\\digitalSpriteFontBlack.png", 16); fontDigital12.open ("fonts\\digitalSpriteFontBlack.png", 12); fontOurs.open ("fonts\\schwabenSpriteFontWhite.png", 64); fontArialRed12.open ("fonts\\arialSpriteFontRed.png", 12); fontArialRed14.open ("fonts\\arialSpriteFontRed.png", 14); } void oglGameVars::parseMeIntoRows(vector<std::string*> *storageContainer, std::string stringToParse, int numCharsPerRow, bool autoFeed) { storageContainer->clear(); string* tempString = new string; //*tempString = stringToParse; int row = 0; if(!autoFeed) { for(int x = 0; x < (int)(stringToParse.length() / numCharsPerRow); x++) { *tempString = stringToParse.substr(numCharsPerRow*row, numCharsPerRow); storageContainer->push_back(tempString); tempString = new string; row++; } *tempString = stringToParse.substr(numCharsPerRow*row, stringToParse.length()%numCharsPerRow); storageContainer->push_back(tempString); } else { // auto separation int curStart = 0; int curEnd = numCharsPerRow-1; bool done = false; while(!done) { // if we're not on row zero, check the first character of the line // if its a space, increment until its not a space if(curStart >= numCharsPerRow) { while(stringToParse.substr(curStart, 1) == " ") { curStart++; } } curEnd = curStart + numCharsPerRow-1; if(curEnd > (int)stringToParse.length()) { curEnd = stringToParse.length(); } // check the last character of the line // if its a space, leave it alone if(stringToParse.substr(curEnd, 1) == " ") { // leave curEnd alone } else { // if its a character, we have three possibilities // #1 it is a character with a space after it in which we're ok to cut and move on // #2 its a character with another character after it, in which case we have to go backward // and figure out where the cut spot is // #3 its a word that's so long it goes on for multiple lines in which case we have to backtrack and just cut anyways // #1 if(curEnd < (int)stringToParse.length()) { if(stringToParse.substr(curEnd+1, 1) == " ") { // do nothing } else { // find a new ending while((stringToParse.substr(curEnd, 1) != " ") && (curEnd < (int)stringToParse.length())) { curEnd++; } // #2 if((curEnd - curStart) < numCharsPerRow*2) { curEnd = curStart + numCharsPerRow; // backtrack until we find a space while(stringToParse.substr(curEnd,1) != " ") { curEnd--; } } // #3 else { // reset it and just cut curEnd = curStart + numCharsPerRow; } } } } // with the newly calculated curEnd lets chop it and move on if(curEnd > (int)stringToParse.length()) { curEnd = stringToParse.length(); } *tempString = stringToParse.substr(curStart, curEnd-curStart+1); storageContainer->push_back(tempString); tempString = new string; curStart = curEnd + 1; if(curStart > (int)stringToParse.length()) { done = true; } } } } double oglGameVars::getDistanceToTarget(double xPos, double yPos, double targetXPos, double targetYPos) { double length = GameVars->dAbs(xPos - targetXPos); double height = GameVars->dAbs(yPos - targetYPos); double hypotenuse = sqrt((length * length) + (height * height)); return hypotenuse; } double oglGameVars::dAbs(double something) { if(something > 0) { return something; } else { return (something * -1); } }
[ "corwin.j@5457d560-9b84-11de-b17c-2fd642447241", "DavidBMoss@5457d560-9b84-11de-b17c-2fd642447241", "davidbmoss@5457d560-9b84-11de-b17c-2fd642447241" ]
[ [ [ 1, 5 ], [ 8, 30 ], [ 33, 92 ], [ 103, 104 ], [ 109, 123 ], [ 136, 136 ], [ 139, 266 ], [ 290, 290 ] ], [ [ 6, 6 ], [ 93, 102 ], [ 105, 108 ], [ 124, 135 ], [ 137, 138 ], [ 267, 271 ], [ 274, 277 ] ], [ [ 7, 7 ], [ 31, 32 ], [ 272, 273 ], [ 278, 289 ] ] ]
72c7ea027026831339a6ea508660a9a281031420
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/Algorithm/AprioriOpt.h
a9c3a30d7bc4d00f5b554ed96ac466aa64d8bd1f
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
7,943
h
#pragma once #include "EncodedAttributeInfo.h" #include <vector> #include "aprioriitemset.h" #include "WrapDataSource.h" #include "algoutils.h" #include "BitStreamInfo.h" #include "associaterule.h" #include <string> #include <algorithm> #include "smalgorithmexceptions.h" /************************************************************************ * Class :AprioriOpt * Author :Amila De Silva * Subj : * Class implementing an Apriori-type algorithm. * Iteratively reduces the minimum support until it finds the * required number of rules with the given minimum confidence * The algorithm has an option to mine class association rules. * * Version: 1 ************************************************************************/ class AprioriOpt { public: /*** * Constructor */ _declspec(dllexport) AprioriOpt(void); /*** * Destructor */ _declspec(dllexport) ~AprioriOpt(void); /*** * Iterator for iterating through attributes */ typedef vector<EncodedAttributeInfo *>::iterator attribute_iterator; /*** * Returns the set of distinct values for all the attributes in the data source. */ _declspec(dllexport) vector<AprioriItemset *> UniqueItems() const { return m_uniqueItems; } /*** * Sets the unique items for the data source. */ _declspec(dllexport) void UniqueItems(vector<AprioriItemset *> val) { m_uniqueItems = val; } /*** * Finds the distinct value for each attribute in the data source and store them in a vector. */ _declspec(dllexport) void FindUniqueItemSets(WrapDataSource * _instances) throw (algorithm_exception); /*** * Top level function to find itemsets larger than a given minimum support and a confidence. */ _declspec(dllexport) void FindLargeItemSets(); /*** * Delete itemsets that are lower than the _nec_support value. * If the itemset is the initial itemset it is not deleted. */ _declspec(dllexport) vector<AprioriItemset *> DeleteItemSets(vector<AprioriItemset *> & _itemsets,int _nec_support, int _max_support,bool _not_initial_set); /*** * Procedure to merge all k-1-itemsets to create k itemsets */ _declspec(dllexport) vector<AprioriItemset *> MergeAllItemSets(vector<AprioriItemset *> & _itemSets, int size); /*** * Itemsets whose subsets are not large, are deleted by this method. * _ksets indicates the collection of itemsets to be tested * _kMinusOne contains the support values of k-1 itemsets */ _declspec(dllexport) vector<AprioriItemset *> PruneItemSets(vector<AprioriItemset *> & _ksets,hash_map<int,int> & _kMinusOne); /*** * Create the Associate rules using the large itemsets. * _instances provide the header information required for decoding data. */ _declspec(dllexport) void BuildAssociations(WrapDataSource * _instances); /*** * Implementation of the comparison function to compare two associate rules */ _declspec(dllexport) int Compare(const void * _arg1, const void * _arg2); /*** * Method used for sorting the rules according to theri support values. */ _declspec(dllexport) void SortRules(); /*** * Updates the support values for newly created k-itemsets, by merging. */ _declspec(dllexport) void UpdateCounters(vector<AprioriItemset *> & _ksets,int _kminusize); /*** * Updates the support values for newly created k-itemsets, by merging. */ _declspec(dllexport) static void UpDateCounters(vector<AprioriItemset *> & _ksets, vector<AprioriItemset *> & _kMinusSets); /*** * Gives the string representation of all the rules. */ _declspec(dllexport) string ToString(); /*** * Prints the current collection of large itemsets. */ _declspec(dllexport) void PrintItemsets(); /*** * Returns the large itemsets. */ _declspec(dllexport) vector<vector<AprioriItemset *>> LargeItemSets() const { return m_largeItemSets; } /*** * Sets the large itemsets. */ _declspec(dllexport) void LargeItemSets(vector<vector<AprioriItemset *>> val) { m_largeItemSets = val; } /*** * Returns the number of cycles performed in the algorithm. */ _declspec(dllexport) int Cycles() const { return m_cycles; } /*** * Sets the number of cycles performed. */ _declspec(dllexport) void Cycles(int val) { m_cycles = val; } /*** * Returns the minimum support. */ _declspec(dllexport) double MinSupport() const { return m_minSupport; } /*** * Sets the minimum support. */ _declspec(dllexport) void MinSupport(double val) { m_minSupport = val; } /*** * Generate Associate Rules from the itemset. */ _declspec(dllexport) vector<AssociateRule *> GenerateRules( int numItemsInSet, AprioriItemset * _itemset ); /*** * Returns the confidence. */ _declspec(dllexport) double Confidence() const { return m_confidence; } /*** * Sets the confidence. */ _declspec(dllexport) void Confidence(double val) { m_confidence = val; } /*** * Delete rules which are lower than a particular confidence level */ _declspec(dllexport) vector<AssociateRule *> PruneRules( vector<AssociateRule *> & _rules); /*** * Releases all the member variables used for computation. */ _declspec(dllexport) void Clear(); /*** * Method used to find simple associate rules. * These rules will only contain one side of the the relations. */ _declspec(dllexport) void FindRulesQuickly(vector<AssociateRule *> & _rules); /*** * Returns the created set of associate rules. */ _declspec(dllexport) vector<AssociateRule *> Rules() const { return m_rules; } /*** * Sets the set of Association Rules. */ _declspec(dllexport) void Rules(vector<AssociateRule *> val) { m_rules = val; } /*** * Generate the string representation of the association rule. */ _declspec(dllexport) void BuildStrings(); /*** * Returns the number of rules. */ _declspec(dllexport) int NumRules() const { return m_numRules; } /*** * Sets the number of rules. */ _declspec(dllexport) void NumRules(int val) { m_numRules = val; } /*** * Gets the string representation of an Itemset. */ _declspec(dllexport) string GetItemSetString(AprioriItemset * _itemset); /*** * Clears the bitstreams for k-2itemsets. * Initial itemsets are preserved. */ _declspec(dllexport) void ClearPreviousBitStreams(vector<AprioriItemset *> & _prev_set); private: /*** * Deletes large itemset vector (m_largeItemSets) */ void ClearlargeItemSets(); /*** * Deletes unique itemset vector (m_uniqueItems) */ void ClearUniqueItems(); /*** * Deletes hash table vector (m_hashTables) */ void ClearHashTable(); /*** * Deletes the set of rules created (m_rules) */ void ClearRules(); /*** * Calls all the clear functions. */ void ClearAll(); /* Vector to store distinct itemsets*/ vector<AprioriItemset *> m_uniqueItems; /** Hashtable to store count of each itemset*/ vector<hash_map<int,int>> m_hashTables; /** Hashtable to store count of each itemset*/ vector<hash_map<int,AprioriItemset *>> m_hashItemSets; /** Structure to hold each large k-itemsets */ vector<vector<AprioriItemset *>> m_largeItemSets; /** Vector holding Association Rules*/ vector<AssociateRule *> m_rules; /** Stores the maximum value the support can have*/ double m_upperBoundMinSupport; /** Unit to increment support at each iteration*/ double m_delta; /** Stores the minimum value the support can have*/ double m_lowerBoundMinSupport; /** Number of rules to be derived*/ int m_numRules; /** Counts the number of iterations performed*/ int m_cycles; /** Minimum support for rules*/ double m_minSupport; /** Confidence for rules.*/ double m_confidence; /** Number of attributes in the data source*/ int m_numberOfAttributes; /** Data source to be used*/ WrapDataSource * m_instances; };
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 284 ] ] ]
783fc8324ce098c789fae8d518a45732cecaa1dc
d9bb737ffc2d5b0c4564b63b280eb24ae55e119a
/sketch.cpp
06178ea7e07c695eb27945f107e9c152912a2421
[]
no_license
piyushsoni/voxelcompression
3c0600970341cb03754974d59a60908eccb9e665
fb564e0827aefa5ddca1f1e78c10117cc41b0503
refs/heads/master
2020-06-12T16:51:38.535725
2008-04-02T17:43:03
2008-04-02T17:43:03
32,435,915
0
0
null
null
null
null
UTF-8
C++
false
false
2,735
cpp
/******************************************************************* Example Main Program for CS480 Programming Assignment 1 ******************************************************************** Author: Stan Sclaroff Boston University Computer Science Dept. September 9, 2004 ******************************************************************** Description: This is a template program for the polygon tool. It supports drawing a polygon vertices, moving vertices, reporting whether the polygon is concave or convex, and testing points are inside/outside the current polygon. LEFTMOUSE: add polygon vertex RIGHTMOUSE: move closest vertex MIDDLEMOUSE: click to see if point is inside or outside poly The following keys control the program: Q,q: quit T,t: cycle through test cases S,s: toggle inside/outside pattern P,p: print polygon vertex coordinates (for debugging) F,f: toggle polygon fill off/on C,c: clear polygon (set vertex count=0) ******************************************************************** Comments: This program uses the GLUT library. This library has it's own event loop handler which passes control back to your program's callback routines. Links to WWW pages for GLUT and OpenGL are provided on the course web page. ********************************************************************/ /* #include <stdlib.h> //#include <GL/gl.h> //#include <GL/glut.h> //#include <GL/glext.h> #include <GL/glaux.h> #include "const.h" #include "types.h" #include "funcs.h" #include <GL/gl.h> #include <GL/glext.h> #include <GL/glut.h> #include <GL/glaux.h> #include <stdio.h> #include <assert.h> int main(int argc, char **argv) { GLint windW=DEFAULT_WINDOW_WIDTH, windH=DEFAULT_WINDOW_HEIGHT; glutInit(&argc, argv); initPoly(); // display modes: 24 BIT, double buffer mode glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(windW,windH); glutCreateWindow("CS480/CS680 Skeleton Polygon Tool"); // clear the display glClear(GL_COLOR_BUFFER_BIT); //set default attributes glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); glLineWidth(DEFAULT_LINE_WIDTH); // register callbacks for window redisplay // and reshape event callbacks glutDisplayFunc(display); glutReshapeFunc(reshape); // setup mouse handler callbacks glutMotionFunc(mouseMotion); glutMouseFunc(mouseButton); // setup keyboard handler callback glutKeyboardFunc(keyboard); // turn over control to GLUT glutMainLoop(); //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); return 0; } */
[ "piyushsoni@a21f6fc8-a949-0410-a047-d72f5bcd5aec" ]
[ [ [ 1, 86 ] ] ]
6ada48ee63ebde78521f332888da400472f3ff35
1bc72c361ded5d439bcf3cb3bebf143e7bf75257
/funciones.cpp
8fa3b19274490262e82ea4d440ca53a953f7bc00
[]
no_license
escaleno/g11-algoii
d4831539fa353e77b0b0d13ac89e8fbb7c23416a
521d1cc1aa49d6e46cf8dd58d8c6b35b7c9e6df7
refs/heads/master
2021-01-10T12:06:53.886726
2011-11-24T11:46:47
2011-11-24T11:46:47
36,740,239
0
0
null
null
null
null
UTF-8
C++
false
false
2,826
cpp
#include "funciones.h" #include <iostream> #include <stdlib.h> using namespace std; /**************************************************************************************/ unsigned opcionesMenu(){ unsigned opcion; system("CLS"); cout<<"d888888P 888888ba dP dP 8888ba.88ba dP "<<endl; cout<<" 88 88 `8b Y8. .8P 88 `8b `8b 88 "<<endl; cout<<" 88 a88aaaa8P' Y8aa8P 88 88 88 88 "<<endl; cout<<" 88 88 d8' `8b 88 88 88 88 "<<endl; cout<<" 88 88 88 88 88 88 88 88 "<<endl; cout<<" dP dP dP dP dP dP dP 88888888P "<<endl; cout<<"ooooooooooooooooooooooooooooooooooooooooooooooooooooooo "<<endl; cout <<endl; cout<<"OPCIONES: "<<endl; cout<<endl; cout<<"1) Imprimir XML completo"<<endl; cout<<"2) Imprimir un tag cualquiera (con hijos y contenido)"<<endl; cout<<"3) Listar los hijos (solamente los nombre) de un tag dado"<<endl; cout<<"0) SALIR"<<endl; cout<<""<<endl; cout<<""<<endl; cout<<"Ingrese una opcion: "; cin>>opcion; if ((opcion <0) || (opcion > 3)){ cout<<"Opcion invalida!"<<endl; mjePresioneCualquierTecla(); system("CLS"); return 100; }else { return opcion; } } /**************************************************************************************/ void menuPrincipal(ArbolNario* aXML){ unsigned opcion; bool sale = false; string tag; do{ do{ opcion = opcionesMenu(); }while(opcion == 100); switch (opcion){ case 1: cout << endl; aXML->imprimirXML(aXML->getRaiz(), 0); mjePresioneCualquierTecla(); break; case 2: tag = pideTag(); cout << endl; aXML->imprimir(tag); mjePresioneCualquierTecla(); break; case 3: tag = pideTag(); cout << endl; aXML->imprimirSoloTag(tag); mjePresioneCualquierTecla(); break; case 0: sale = true; break; }; }while(opcion != 0); } /**************************************************************************************/ string pideTag(){ string tag; cout<<"Ingrese el tag a buscar y presione ENTER: "; cin >>tag; return tag; } /**************************************************************************************/ void mjePresioneCualquierTecla(){ cout <<endl; cout<<"Presione cualquier tecla para volver al menu principal..."; cin.get(); cin.get(); } /**************************************************************************************/
[ [ [ 1, 57 ], [ 60, 62 ], [ 64, 67 ], [ 69, 96 ] ], [ [ 58, 59 ], [ 63, 63 ], [ 68, 68 ] ] ]
5939c721621abc4fc5a0d841a629c4ea14fe5a8c
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/iostreams/example/iterator_range_example.cpp
9e30fddecc4b15cc37d289be22602f522a965c3d
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
691
cpp
// (C) Copyright Jonathan Turkanis 2005. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.) // See http://www.boost.org/libs/iostreams for documentation. #include <cassert> #include <string> #include <boost/iostreams/filtering_stream.hpp> #include <boost/range/iterator_range.hpp> namespace io = boost::iostreams; int main() { using namespace std; string input = "Hello World!"; string output; io::filtering_istream in(boost::make_iterator_range(input)); getline(in, output); assert(input == output); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 23 ] ] ]
43e3cbd8b25cce427aece8b3c6839a7dc8609de5
0c5fd443401312fafae18ea6a9d17bac9ee61474
/code/engine/Model/Loader/SectorFactory.cpp
dea0c63b0b81656fb89e0e80df3558243770869e
[]
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
17,108
cpp
/* ___ _________ ____ __ / _ )/ __/ ___/____/ __/___ ___ _/_/___ ___ / _ / _// (_ //___/ _/ / _ | _ `/ // _ | -_) /____/_/ \___/ /___//_//_|_, /_//_//_|__/ /___/ 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/>. */ #include <Model/Loader/SectorFactory.h> #include <boost/foreach.hpp> #include <Core/Utils.h> // generateHandle() #include <Model/Loader/FileLoader.h> #include <Model/Loader/GameObjectFactory.h> #include <Model/Loader/Interpreter.h> #include <Model/GameObject.h> #include <Model/Sector.h> #include <Model/Property/Concepts/Camera.h> // struct CameraParameter #include <View/Event.h> namespace BFG { namespace Loader { SectorFactory::SectorFactory(EventLoop* loop, boost::shared_ptr<Interpreter> interpreter, boost::shared_ptr<GameObjectFactory> gof, boost::shared_ptr<Environment> environment, GameHandle viewState) : Emitter(loop), mInterpreter(interpreter), mGameObjectFactory(gof), mEnvironment(environment), mViewState(viewState) { assert(gof && "Interpreter must be initialized"); assert(gof && "GameObjectFactory must be initialized"); assert(environment && "Environment must be initialized"); } boost::shared_ptr<Sector> SectorFactory::createSector(const std::string& fileSectorConfig, GameHandle& outCameraHandle) { FileLoader fileLoader; SectorDraft sectorDraft; sectorDraft.mObjects.reset(new ManyTagsT); sectorDraft.mPaths.reset(new ManyManyTagsT); sectorDraft.mSectorProperties.reset(new TagWithAttributesT); sectorDraft.mConditions.reset(new TagWithAttributesT); sectorDraft.mCameras.reset(new ManyTagsT); sectorDraft.mSkybox.reset(new TagWithAttributesT); sectorDraft.mLights.reset(new ManyTagsT); sectorDraft.mPlaylist.reset(new ManyTagsT); // Build Sector std::string sectorName; fileLoader.loadSectorDraft(fileSectorConfig, sectorDraft, sectorName); boost::shared_ptr<Sector> sector(new Sector ( loop(), generateHandle(), sectorName, mGameObjectFactory )); // Build Objects std::vector<ObjectParameter> objVector; mInterpreter->interpretObjectConfig(*sectorDraft.mObjects, objVector); BOOST_FOREACH(ObjectParameter& op, objVector) { sector->addObject(mGameObjectFactory->createGameObject(op)); } BOOST_FOREACH(ObjectParameter& op, objVector) { mGameObjectFactory->applyConnection(op); } // Setup View emit<View::Event>(ID::VE_SET_AMBIENT, cv4(0.1f, 0.1f, 0.1f)); TagWithAttributesT::iterator skyIt = sectorDraft.mSkybox->begin(); if (skyIt == sectorDraft.mSkybox->end()) { throw std::runtime_error("CreateSector: no skybox material defined!"); } View::SkyCreation sc(skyIt->second); emit<View::Event>(ID::VE_SET_SKY, sc, mViewState); // Create all lights BOOST_FOREACH(ManyTagsT::value_type em, *sectorDraft.mLights) { LightParameters lightParameters; mInterpreter->interpretLightDefinition(*em, lightParameters); View::DirectionalLightCreation dlc(generateHandle(), lightParameters.mOrientation); emit<View::Event>(ID::VE_CREATE_DIRECTIONALLIGHT, dlc); } // Create all cameras BOOST_FOREACH(ManyTagsT::value_type em, *sectorDraft.mCameras) { CameraParameter cameraParameter; std::string parentObject; mInterpreter->interpretCameraDefinition(*em, cameraParameter, parentObject); boost::shared_ptr<GameObject> cam = mGameObjectFactory->createCamera(cameraParameter, parentObject); sector->addObject(cam); } #if 0 // Create all paths typedef boost::unordered_map<std::string, std::vector<GameHandle> > PathListT; PathListT pathList; BOOST_FOREACH(ManyManyTagsT::value_type paths, *sectorDraft.mPaths) { std::vector<GameHandle> aPath; createPath(*paths.second, aPath); pathList.insert(std::make_pair(paths.first, aPath)); } // Create RaceControl RaceCondition raceCondition; std::vector<GameHandle> path; std::string pathId; mInterpreter->interpretRaceCondition(*sectorDraft.mConditions, raceCondition, pathId); if (! pathId.empty()) { PathListT::iterator pathIt = pathList.find(pathId); // Check: If it has a name, it should be there. if (pathIt == pathList.end()) throw LoaderException("SectorFactory: Path \"" + pathId + "\"not found in path list."); // This is a copy, but that's okay. If the pathId is empty, we'll pass // an empty vector to the race control ctor to ensure proper // initialization. path = pathIt->second; outRaceControl.reset(new RaceControl ( generateHandle(), path, raceCondition, *mEnvironment )); } // Create the playlist for music outPlaylistControl.reset(new PlaylistControl ( GameStateManager::getSingleton().getEventLoop() )); BOOST_FOREACH(ManyTagsT::value_type song, *sectorDraft.mPlaylist) { std::string publicName, fileName; mInterpreter->interpretPlaylistDefinition(*song, publicName, fileName); outPlaylistControl->addSong(publicName, fileName); } #endif return sector; #if 0 // create raceControl RaceCondition raceCondition; std::string path; mInterpreter->interpretRaceCondition(draft.mConditions, raceCondition, path); PathListT::iterator pathIt = pathList.find(path); if (pathIt == pathList.end()) throw LoaderException("Path not found in path list."); std::vector<GameHandle> waypoints; // waypoint list for racetrack. BOOST_FOREACH(GameHandle gh, pathIt->second) { WaypointMapT::iterator waypointIt = mWaypointMap.find(gh); waypoints.push_back(waypointIt->second->getHandle()); } mRaceControl.reset(new RaceControl(generateHandle(), pathIt->second, raceCondition, *mEnvironment)); View::Gui* gui = new View::Gui(GameStateManager::getSingleton().getEventLoop(), player); outPlaylistControl.reset(new PlaylistControl(GameStateManager::getSingleton().getEventLoop())); // create the playlist for music. BOOST_FOREACH(ListOfEntitiesT::value_type song, draft.mPlaylist) { std::string publicName, fileName; mInterpreter->interpretPlaylistDefinition(*song, publicName, fileName); outPlaylistControl->addSong(publicName, fileName); } //! \TODO This doesn't belong to this place. Put it into view. // ###################### // # Pre-load Explosion # // ###################### mRenderInt->loadMaterial("explosion", "General"); mRenderInt->loadMaterial("explosion2", "General"); mRenderInt->loadMaterial("flash", "General"); mRenderInt->loadMaterial("spark", "General"); mRenderInt->loadMaterial("smoketrail", "General"); mRenderInt->loadMaterial("shockwave", "General"); // ################## // # Pre-load Laser # // ################## mRenderInt->loadMaterial("laser_front", "General"); mRenderInt->loadMaterial("laser_side", "General"); #endif } #if 0 // This function affect to create a Waypoint-Object, but it only returns the waypoint of // an existing object. This is needed to create paths by objects. GameHandle SectorFactory::createWaypoint(const std::string& objectName) { GameObjectFactory::GoMapT::const_iterator it; it = mGameObjectFactory->names().find(objectName); if (it == mGameObjectFactory->names().end()) { std::stringstream ss; ss << "createWaypoint: " << objectName << " not found."; throw LoaderException(ss.str()); } boost::shared_ptr<GameObject> go = it->second.lock(); if (! go) { std::stringstream ss; ss << "createWaypoint: " << objectName << " does not exist anymore."; throw LoaderException(ss.str()); } return go->getHandle(); } // This function creates a lonely waypoint just by a position vector. // This waypoint is not related to any object. GameHandle SectorFactory::createWaypoint(const v3& position) { ObjectParameter parameters; parameters.mLocation.position = position; return createGameObject(parameters); } void SectorFactory::createPath(const ManyTagsT& pathDefinition, std::vector<GameHandle>& path) { BOOST_FOREACH(ManyTagsT::value_type em, pathDefinition) { path.push_back(mInterpreter->interpretPathDefinition(em->begin()->second, *this)); } } #endif #if 0 void SectorFactory::createLaserP(const Location& loc, const v3& startVelocity) { View::RenderInterface* renderInt = View::RenderInterface::Instance(); View::ObjectInterface* viewObjInt = View::ObjectInterface::Instance(); Physics::PhysicsManager* physicsMngr = Physics::PhysicsManager::getSingletonPtr(); GameHandle handle = generateHandle(); boost::shared_ptr<Waypoint> wpLaser(new Waypoint(generateHandle(), loc, handle)); // This has to be done in advance of the GameObject creation due to call of setPosition and setOrientation physicsMngr->createPhysicalObject( handle, ID::CG_Sphere, 0.5f, //radius of sphere ID::CT_Bullet, // This has nothing to say. It's not even used. true, true ); boost::shared_ptr<ViewUpdateBase> view_updater(new ViewObjectUpdater); viewObjInt->createObject(handle, NULL_HANDLE, true); boost::shared_ptr<GameObject> laser( new GameObject( handle, "Laser", mEnvironment, wpLaser, view_updater ) ); mEnvironment->addGameObject(laser); boost::shared_ptr<Physical> h; h.reset(new Physical(*laser, 100.0f, 23.75f)); boost::shared_static_cast<PropertyConcept>(h)->activate(); laser->addPropertyConcept(h); NoRespawn respawn(*mSector); boost::shared_ptr<Destroyable<NoRespawn> > d; d.reset(new Destroyable<NoRespawn>(*laser, 5, respawn)); boost::shared_static_cast<PropertyConcept>(d)->activate(); laser->addPropertyConcept(d); boost::shared_ptr<SelfDestruction> s; s.reset(new SelfDestruction(*laser, 2.0f)); boost::shared_static_cast<PropertyConcept>(s)->activate(); laser->addPropertyConcept(s); boost::shared_ptr<Engine> e; e.reset(new Engine(*laser, startVelocity.squaredLength(), v3(0, 0, 0), 0.0f, 0.0f, 0.01f, 0.01f, 200.f, 10.f, startVelocity)); boost::shared_static_cast<PropertyConcept>(e)->activate(); laser->addPropertyConcept(e); #ifdef DISCO // DISCO! YEAH BABY! static int disco = 0; if (disco == 0) viewObjInt->createLaserP(handle, loc, startVelocity, cv4::Black); else if (disco == 1) viewObjInt->createLaserP(handle, loc, startVelocity, cv4::Blue); else if (disco == 2) viewObjInt->createLaserP(handle, loc, startVelocity, cv4::Green); else if (disco == 3) viewObjInt->createLaserP(handle, loc, startVelocity, cv4::Red); else if (disco == 4) viewObjInt->createLaserP(handle, loc, startVelocity, cv4::White); else if (disco == 5) viewObjInt->createLaserP(handle, loc, startVelocity, Ogre::ColourValue(0.0f, 1.0f, 1.0f)); else if (disco == 6) viewObjInt->createLaserP(handle, loc, startVelocity, Ogre::ColourValue(1.0f, 1.0f, 0.0f)); if (++disco == 7) disco = 0; #else viewObjInt->createLaserP(handle, loc, startVelocity, cv4::Green); #endif mSector->addObject(laser); } void SectorFactory::createRocket(const Location& loc, const v3& startVelocity, GameHandle target) { View::RenderInterface* renderInt = View::RenderInterface::Instance(); View::ObjectInterface* viewObjInt = View::ObjectInterface::Instance(); Physics::PhysicsManager* physicsMngr = Physics::PhysicsManager::getSingletonPtr(); GameHandle handle = generateHandle(); boost::shared_ptr<Waypoint> wpRocket(new Waypoint(generateHandle(), loc, handle)); // This has to be done in advance of the GameObject creation due to call of setPosition and setOrientation physicsMngr->createPhysicalObject( handle, ID::CG_TriMesh, "Rocket.mesh", ID::CT_Bullet, // This has nothing to say. It's not even used. true, true ); boost::shared_ptr<ViewUpdateBase> view_updater(new ViewObjectUpdater); viewObjInt->createObject( handle, NULL_HANDLE, true, loc.position, loc.orientation ); boost::shared_ptr<GameObject> rocket1( new GameObject( handle, "Rocket", mEnvironment, wpRocket, view_updater ) ); mEnvironment->addGameObject(rocket1); const float max_speed = 1e5; const v3 maxAngularVelocity = v3(M_PI, M_PI, M_PI); boost::shared_ptr<EnergyCell> Ec; Ec.reset(new EnergyCell(*rocket1, 200.f, 2000.f)); boost::shared_static_cast<PropertyConcept>(Ec)->activate(); rocket1->addPropertyConcept(Ec); boost::shared_ptr<EnergyAllocator> Ea; Ea.reset(new EnergyAllocator(*rocket1)); boost::shared_static_cast<PropertyConcept>(Ea)->activate(); rocket1->addPropertyConcept(Ea); boost::shared_ptr<Physical> h; h.reset(new Physical(*rocket1, 100.0f, 23.75f)); boost::shared_static_cast<PropertyConcept>(h)->activate(); rocket1->addPropertyConcept(h); boost::shared_ptr<Engine> e; e.reset(new Engine(*rocket1, max_speed, maxAngularVelocity, 10417.0f, 300.0f, 1.00f, 0.01f, 200.f, 10.f, startVelocity)); boost::shared_static_cast<PropertyConcept>(e)->activate(); rocket1->addPropertyConcept(e); boost::shared_ptr<AutoNavigator> n; n.reset(new AutoNavigator(*rocket1, 0.01745f, max_speed, maxAngularVelocity, 1.0f)); boost::shared_static_cast<PropertyConcept>(n)->activate(); rocket1->addPropertyConcept(n); NoRespawn respawn(*mSector); boost::shared_ptr<Destroyable<NoRespawn> > d; d.reset(new Destroyable<NoRespawn>(*rocket1, 5, respawn)); boost::shared_static_cast<PropertyConcept>(d)->activate(); rocket1->addPropertyConcept(d); boost::shared_ptr<SelfDestruction> s; s.reset(new SelfDestruction(*rocket1, 20.0f)); boost::shared_static_cast<PropertyConcept>(s)->activate(); rocket1->addPropertyConcept(s); viewObjInt->createOgreEntity(handle, "Rocket.mesh"); viewObjInt->attachEntityToObject(handle, handle); #ifdef DISCO // DISCO! YEAH BABY! static int disco = 0; if (disco == 0) renderInt->attachSmokeTrail(handle, v3(0,0,-1), Ogre::ColourValue(1.0f, 0.0f, 1.0f)); else if (disco == 1) renderInt->attachSmokeTrail(handle, v3(0,0,-1), cv4::Blue); else if (disco == 2) renderInt->attachSmokeTrail(handle, v3(0,0,-1), cv4::Green); else if (disco == 3) renderInt->attachSmokeTrail(handle, v3(0,0,-1), cv4::Red); else if (disco == 4) renderInt->attachSmokeTrail(handle, v3(0,0,-1), cv4::White); else if (disco == 5) renderInt->attachSmokeTrail(handle, v3(0,0,-1), Ogre::ColourValue(0.0f, 1.0f, 1.0f)); else if (disco == 6) renderInt->attachSmokeTrail(handle, v3(0,0,-1), Ogre::ColourValue(1.0f, 1.0f, 0.0f)); if (++disco == 7) disco = 0; #else renderInt->attachSmokeTrail(handle, v3(0,0,-1), cv4::White); #endif // Body Module boost::shared_ptr<Module> Body = new Module; Body->mHandle = generateHandle(); Body->mValues[ID::PV_Weight] = 1000.0f; Body->mValues[ID::PV_MaxSpeed] = 750.0f; // Body Adapters Adapter Active; Adapter Inactive; Active.mParentPosition = v3(1.0f, 0, 0); Active.mParentOrientation = qv4(1,2,3,4); Active.mIdentifier = 3; Inactive.mParentPosition = v3(0, -1.0f, 0); Inactive.mParentOrientation = qv4(4,3,2,1); Inactive.mIdentifier = 4; std::vector<Adapter> Adapters; Adapters.push_back(Active); Adapters.push_back(Inactive); // Attach Body rocket1->attachModule(Body, Adapters, 0, NULL_HANDLE, 0); // Wing Module boost::shared_ptr<Module> Wing = new Module; Wing->mHandle = generateHandle(); Wing->mValues[ID::PV_Weight] = 200.0f; // Wing Adapters Adapter Active2; Active2.mParentPosition = v3(-1.0f, 0, 0); Active2.mParentOrientation = qv4(5,6,7,8); Active2.mIdentifier = 1; Adapters.clear(); Adapters.push_back(Active2); // Attach Wing to Body rocket1->attachModule(Wing, Adapters, 1, Body->mHandle, 3); rocket1->detachModule(Wing->mHandle); mSector->addObject(rocket1); // // //! \todo put this into weapon rack. // GameObjectEventEmitter::emit // ( // ID::GOE_AUTONAVIGATE, // target, // handle // ); } #endif } // namespace Loader } // namespace BFG
[ [ [ 1, 560 ] ] ]
d083db9cae076c47a9e6a5a796f9e769a0607d3c
dadf8e6f3c1adef539a5ad409ce09726886182a7
/airplay/h/toe2DScene.h
749550434f2012f141ab6a20d0c9a64960b9e92c
[]
no_license
sarthakpandit/toe
63f59ea09f2c1454c1270d55b3b4534feedc7ae3
196aa1e71e9f22f2ecfded1c3da141e7a75b5c2b
refs/heads/master
2021-01-10T04:04:45.575806
2011-06-09T12:56:05
2011-06-09T12:56:05
53,861,788
0
0
null
null
null
null
UTF-8
C++
false
false
405
h
#pragma once #include <toeSubsystemItems.h> #include <toeComponent.h> #include <toeSelfRenderedComponent.h> namespace TinyOpenEngine { class Ctoe2DScene : public TtoeSubsystem<CtoeSelfRenderedComponent> { public: //Declare managed class IW_MANAGED_DECLARE(Ctoe2DScene); //Constructor Ctoe2DScene(); //Desctructor virtual ~Ctoe2DScene(); virtual void Render(); }; }
[ [ [ 1, 21 ] ] ]
45d508c551c9919a93ebc518e119aee8f2a7fa89
3276915b349aec4d26b466d48d9c8022a909ec16
/c++/stl/向量/普通向量.cpp
1bfeb93492791ae6f78292da9e660699cf3e81d3
[]
no_license
flyskyosg/3dvc
c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82
0279b1a7ae097b9028cc7e4aa2dcb67025f096b9
refs/heads/master
2021-01-10T11:39:45.352471
2009-07-31T13:13:50
2009-07-31T13:13:50
48,670,844
0
0
null
null
null
null
GB18030
C++
false
false
547
cpp
#include<iostream> //vector的使用 #include<string> //#include<iomanip> #include<sstream> #include<fstream> #include<vector> using namespace std; void main() { vector<char> s(10,97); vector<char> s1(s); vector<char> s2(s.begin(),s.end()); vector<char> s3(10); cout<<s.capacity()<<endl; vector<char>::iterator it; //一代起 it=s1.begin(); for(int i=0;i<s1.capacity();i++) cout<<s1[i]<<*it++<<endl; s1.push_back('n'); it=s1.end()-1; cout<<*it; }
[ [ [ 1, 39 ] ] ]