blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
ecb2d694fe0896503192ffd8cef6574f31941dc1
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/12_21114_30.cpp
cc093b6656190654746fada02bb937fab5bfe32a
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,491
cpp
#include<algorithm> #include<cassert> #include<complex> #include<cstdio> #include<cstring> #include<iostream> #include<map> #include<queue> #include<set> #include<sstream> #include<stack> #include<string> #include<vector> #define FOR(i,a,b) for(int i=(a);i<=(b);++i) #define FORD(i,a,b) for(int i=(a);i>=(b);--i) #define REP(i,n) for(int i=0;i<(n);++i) #define fup FOR #define fdo FORD #define VAR(v,i) __typeof(i) v=(i) #define FORE(i,c) for(VAR(i,(c).begin());i!=(c).end();++i) #define ALL(x) (x).begin(),(x).end() #define SIZE(x) ((int)(x).size()) #define SZ SIZE #define CLR memset((x),0,sizeof (x)) #define PB push_back #define MP make_pair #define FI first #define SE second #define SQR(a) ((a)*(a)) #define DEBUG 1 #define debug(x) {if(DEBUG) cerr << #x << " = " << x << endl;} #define debugv(x) {if(DEBUG) {cerr << #x << " = "; FORE(it,(x)) cerr << *it << " . "; cerr <<endl;}} using namespace std; typedef long long LL; typedef long double LD; typedef pair<int,int> PII; typedef vector<int> VI; typedef VI vi; typedef LL lli; const int inf = 1000000000; int dx[6] = {1, 0, -1, -1, 0, 1}, dy[6] = {1, 1, 0, -1, -1, 0}; int ng(PII p, PII q) { int ddx = p.FI - q.FI; int ddy = p.SE - q.SE; REP(i, 6) if(ddx == dx[i] && ddy == dy[i]) return i; return -1; } int s; int corner(int i, int j) { if (i == 2*s-1) { if (j == 2*s-1) return 0; else if (j == s) return 5; } else if (i == s) { if (j == 2*s-1) return 1; else if (j == 1) return 4; } else if (i == 1) { if (j == s) return 2; else if (j == 1) return 3; } return -1; } int edge(int i, int j) { if (i == 2*s-1) return 5; else if (j == 2*s-1) return 0; else if (j-i == s-1) return 1; else if (i == 1) return 2; else if (j == 1) return 3; else if (i-j == s-1) return 4; return -1; } const int MN = 101; int cmp[MN][MN]; const int MAXN = MN * MN; vector<PII> C[MAXN]; int crn[MAXN]; int edg[MAXN][6]; int c; int comp(int x, int y) { cmp[x][y] = c; REP(i, 6) edg[c][i] = 0; crn[c] = 0; C[c]= vector<PII>(); C[c].PB(MP(x,y)); int cr = corner(x,y); if (cr != -1) crn[c] = 1; else { int e = edge(x, y); if (e != -1) edg[c][e] = 1; } return c++; } bool bridge, ffork, ring; int merge(int c1, int c2) { if (c1 == c2) return c1; if (SZ(C[c1]) < SZ(C[c2])) swap(c1, c2); FORE(it, C[c2]) { cmp[it->FI][it->SE] = c1; C[c1].PB(*it); } crn[c1] += crn[c2]; int e = 0; REP(i, 6) { edg[c1][i] |= edg[c2][i]; e += edg[c1][i]; assert(edg[c1][i] == 0 || edg[c1][i] == 1); } if (e >= 3) ffork = true; if (crn[c1]>=2) bridge = true; return c1; } void solve(int tcase) { int m; scanf("%d%d", &s, &m); //printf("%d %d\n", s,m); c = 0; REP(i, 2*s+1) REP(j, 2*s+1) { cmp[i][j] = -1; } REP(i, MAXN) { crn[i] = 0; REP(t, 6) edg[i][t] = 0; C[i].clear(); } printf("Case #%d: ", tcase); bool d = false; bridge = ffork = ring = false; REP(i, m) { int x, y; scanf("%d%d", &x, &y); if (!d) { int n[12]; int cm = comp(x, y); REP(t, 6) { n[t] = cmp[x+dx[t]][y+dy[t]]; n[t+6] = n[t]; } REP(t, 6) { if (n[t] != -1) { cm = merge(cm, cmp[x+dx[t]][y+dy[t]]); } } REP(t, 6) { FOR(j,1, 5) { if (n[t] != -1 && n[t+1] == -1 && n[t] == n[t+j] && n[t+j+1] == -1) ring = true; } } if (bridge) { printf("bridge"); if (ffork || ring) printf("-"); } if (ffork) { printf("fork"); if (ring) printf("-"); } if (ring) printf("ring"); if (bridge || ffork || ring) { printf(" in move %d\n", i+1); d = true; } } } if (!d) printf("none\n"); } int main() { int t; scanf("%d", &t); s = 3; /* FOR(i,1, 5) FOR(j,1, 5) { int cr = corner(i,j); int e = edge(i,j); if (i-j >= 3 || j-i >= 3) continue; if (cr != -1) printf("%d %d: C %d\n", i,j,cr); else if (e != -1) printf("%d %d E %d\n", i,j,e); }*/ REP(i, t) solve(i+1); return 0; }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
4ed64e6e8b6339b9da996cee07124c3b75e8fc8c
a5239258d872ce52cd24a52d7b1ef19ce9eec537
/GameCode/GameEntity.hpp
4af488e26cab103ce92aec3566d6207d7b6f97a6
[]
no_license
derofim/simple_miner
e3aaafb1eab1369f3d61c15bd978fe26a696e939
0c4419eba585343ca581f60579175cc0a6caf92c
refs/heads/master
2020-07-03T03:23:05.349392
2016-11-03T15:27:20
2016-11-03T15:27:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,608
hpp
//================================================================================= // GameEntity.hpp // Author: Tyler George // Date : April 23, 2015 //================================================================================= #pragma once #ifndef __included_GameEntity__ #define __included_GameEntity__ #include <vector> #include "Engine/Math/PhysicsMotion3D.hpp" #include "Engine/Math/AABB3D.hpp" #include "Engine/Renderer/OpenGLRenderer.hpp" ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- class GameEntity { public: ///--------------------------------------------------------------------------------- /// Constructors ///--------------------------------------------------------------------------------- GameEntity() {}; explicit GameEntity( const Vector3& position, const EulerAngles& orientation, const Vector3& boundingBoxOffsets ); ~GameEntity() {}; ///--------------------------------------------------------------------------------- /// Accessors/Queries ///--------------------------------------------------------------------------------- const Vector3 GetPosition() const; const Vector3 GetVelocity() const; const EulerAngles GetOrientation() const; const EulerAngles GetAngularVelocity() const; const Vector3s GetBoundingBoxVertices() const; const Vector3s GetBottomVertices() const; const Vector3 GetBottomPosition() const; ///--------------------------------------------------------------------------------- /// Mutators ///--------------------------------------------------------------------------------- void SetPosition( const Vector3& position ); void SetVelocity( const Vector3& velocity ); void SetOrientation( const EulerAngles& orientation ); void SetAngularVelocity( const EulerAngles& angularVelocity ); void ApplyAcceleration( const Vector3& acceleration ); ///--------------------------------------------------------------------------------- /// Upadate ///--------------------------------------------------------------------------------- virtual void Update( double deltaSeconds ); ///--------------------------------------------------------------------------------- /// Render ///--------------------------------------------------------------------------------- virtual void Render( OpenGLRenderer* renderer, bool debugModeEnabled ) const; private: ///--------------------------------------------------------------------------------- /// Private member variables ///--------------------------------------------------------------------------------- PhysicsMotion3D m_physics; AABB3D m_boundingBox; Vector3 m_boundingBoxOffsets; Vector3 m_bottomPosition; }; typedef std::vector< GameEntity* > GameEntities; ///--------------------------------------------------------------------------------- /// Inline function implementations ///--------------------------------------------------------------------------------- ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline GameEntity::GameEntity( const Vector3& position, const EulerAngles& orientation, const Vector3& boundingBoxOffsets ) { m_physics.m_position = position; m_physics.m_orientationDegrees = orientation; m_boundingBoxOffsets = boundingBoxOffsets; m_boundingBox.m_mins.x = -m_boundingBoxOffsets.x; m_boundingBox.m_mins.y = -m_boundingBoxOffsets.y; m_boundingBox.m_mins.z = -m_boundingBoxOffsets.z; m_boundingBox.m_maxs.x = m_boundingBoxOffsets.x; m_boundingBox.m_maxs.y = m_boundingBoxOffsets.y; m_boundingBox.m_maxs.z = m_boundingBoxOffsets.z; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline const Vector3 GameEntity::GetPosition() const { return m_physics.m_position; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline const Vector3 GameEntity::GetVelocity() const { return m_physics.m_velocity; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline const EulerAngles GameEntity::GetOrientation() const { return m_physics.m_orientationDegrees; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline const EulerAngles GameEntity::GetAngularVelocity() const { return m_physics.m_orientationVelocityDegreesPerSecond; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline const Vector3 GameEntity::GetBottomPosition() const { return m_bottomPosition; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline void GameEntity::SetPosition( const Vector3& position ) { m_physics.m_position = position; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline void GameEntity::SetVelocity( const Vector3& velocity ) { m_physics.m_velocity = velocity; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline void GameEntity::SetOrientation( const EulerAngles& orientation ) { m_physics.m_orientationDegrees = orientation; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline void GameEntity::SetAngularVelocity( const EulerAngles& angularVelocity ) { m_physics.m_orientationVelocityDegreesPerSecond = angularVelocity; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline void GameEntity::ApplyAcceleration( const Vector3& acceleration ) { m_physics.ApplyAcceleration( acceleration ); } #endif
[ "tyler.george@live.com" ]
tyler.george@live.com
d042fbfab4dc7a584f2c90f59e09a3f37e07c958
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/ds/security/services/scerpc/sceutil.cpp
7bf2780f465026a28af03bdc36d35dd72c22b75c
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
65,144
cpp
/*++ Copyright (c) 1996 Microsoft Corporation Module Name: sceutil.cpp Abstract: Shared APIs Author: Jin Huang Revision History: jinhuang 23-Jan-1998 merged from multiple modules --*/ #include "headers.h" #include "sceutil.h" #include "infp.h" #include <sddl.h> #include "commonrc.h" #include "client\CGenericLogger.h" extern HINSTANCE MyModuleHandle; BOOL ScepInitNameTable() { LoadString(MyModuleHandle, IDS_EVERYONE, NameTable[0].Name, 36); LoadString(MyModuleHandle, IDS_CREATOR_OWNER, NameTable[1].Name, 36); LoadString(MyModuleHandle, IDS_CREATOR_GROUP, NameTable[2].Name, 36); LoadString(MyModuleHandle, IDS_CREATOR_OWNER_SERVER, NameTable[3].Name, 36); LoadString(MyModuleHandle, IDS_CREATOR_GROUP_SERVER, NameTable[4].Name, 36); LoadString(MyModuleHandle, IDS_DIALUP, NameTable[5].Name, 36); LoadString(MyModuleHandle, IDS_NETWORK, NameTable[6].Name, 36); LoadString(MyModuleHandle, IDS_BATCH, NameTable[7].Name, 36); LoadString(MyModuleHandle, IDS_INTERACTIVE, NameTable[8].Name, 36); LoadString(MyModuleHandle, IDS_SERVICE, NameTable[9].Name, 36); LoadString(MyModuleHandle, IDS_ANONYMOUS_LOGON, NameTable[10].Name, 36); LoadString(MyModuleHandle, IDS_PROXY, NameTable[11].Name, 36); LoadString(MyModuleHandle, IDS_ENTERPRISE_DOMAIN, NameTable[12].Name, 36); LoadString(MyModuleHandle, IDS_NAME_SELF, NameTable[13].Name, 36); LoadString(MyModuleHandle, IDS_AUTHENTICATED_USERS, NameTable[14].Name, 36); LoadString(MyModuleHandle, IDS_RESTRICTED, NameTable[15].Name, 36); LoadString(MyModuleHandle, IDS_TERMINAL_SERVER_USER, NameTable[16].Name, 36); LoadString(MyModuleHandle, IDS_LOCAL_SYSTEM, NameTable[17].Name, 36); LoadString(MyModuleHandle, IDS_LOCALSERVICE, NameTable[18].Name, 36); LoadString(MyModuleHandle, IDS_NETWORKSERVICE, NameTable[19].Name, 36); LoadString(MyModuleHandle, IDS_ADMINISTRATORS, NameTable[20].Name, 36); LoadString(MyModuleHandle, IDS_NAME_USERS, NameTable[21].Name, 36); LoadString(MyModuleHandle, IDS_NAME_GUESTS, NameTable[22].Name, 36); LoadString(MyModuleHandle, IDS_POWER_USERS, NameTable[23].Name, 36); LoadString(MyModuleHandle, IDS_ACCOUNT_OPERATORS, NameTable[24].Name, 36); LoadString(MyModuleHandle, IDS_SERVER_OPERATORS, NameTable[25].Name, 36); LoadString(MyModuleHandle, IDS_PRINT_OPERATORS, NameTable[26].Name, 36); LoadString(MyModuleHandle, IDS_BACKUP_OPERATORS, NameTable[27].Name, 36); LoadString(MyModuleHandle, IDS_REPLICATOR, NameTable[28].Name, 36); LoadString(MyModuleHandle, IDS_RAS_SERVERS, NameTable[29].Name, 36); LoadString(MyModuleHandle, IDS_PREW2KCOMPACCESS, NameTable[30 ].Name, 36); LoadString(MyModuleHandle, IDS_REMOTE_DESKTOP_USERS, NameTable[31].Name, 36); LoadString(MyModuleHandle, IDS_NETWORK_CONFIGURATION_OPERATORS, NameTable[32].Name, 36); return TRUE; } BOOL ScepLookupNameTable( IN PWSTR Name, OUT PWSTR *StrSid ) { if ( Name == NULL || Name[0] == L'\0' ) { return FALSE; } for (int i = 0; i < TABLE_SIZE; i++) { if ( _wcsicmp(NameTable[i].Name, Name) == 0 ) { //found match *StrSid = (PWSTR)ScepAlloc((UINT)0, (2+wcslen(NameTable[i].StrSid))*sizeof(WCHAR)); if ( *StrSid == NULL ) { return FALSE; } else { (*StrSid)[0] = L'*'; wcscpy((*StrSid)+1, NameTable[i].StrSid); return TRUE; } } } return FALSE; } INT ScepLookupPrivByName( IN PCWSTR Right ) /* ++ Routine Description: This routine looksup a user right in SCE_Rights table and returns the index component in SCE_Rights. The index component indicates the bit number for the user right. Arguments: Right - The user right to look up Return value: The index component in SCE_Rights table if a match is found, -1 for no match -- */ { DWORD i; for (i=0; i<cPrivCnt; i++) { if ( _wcsicmp(Right, SCE_Privileges[i].Name) == 0 ) return (i); } return(-1); } SCESTATUS WINAPI SceLookupPrivRightName( IN INT Priv, OUT PWSTR Name, OUT PINT NameLen ) { INT Len; if ( Name != NULL && NameLen == NULL ) return(SCESTATUS_INVALID_PARAMETER); if ( Priv >= 0 && Priv < cPrivCnt ) { Len = wcslen(SCE_Privileges[Priv].Name); if ( Name != NULL ) { if ( *NameLen >= Len ) wcscpy(Name, SCE_Privileges[Priv].Name); else { *NameLen = Len; return(SCESTATUS_BUFFER_TOO_SMALL); } } if ( NameLen != NULL) *NameLen = Len; return(SCESTATUS_SUCCESS); } else return SCESTATUS_RECORD_NOT_FOUND; } SCESTATUS SceInfpOpenProfile( IN PCWSTR ProfileName, IN HINF *hInf ) /* Routine Description: This routine opens a profile and returns a handle. This handle may be used when read information out of the profile using Setup APIs. The handle must be closed by calling SCECloseInfProfile. Arguments: ProfileName - The profile to open hInf - the address for inf handle Return value: SCESTATUS */ { if ( ProfileName == NULL || hInf == NULL ) { return(SCESTATUS_INVALID_PARAMETER); } // // Check to see if the INF file is opened OK. // SetupOpenInfFile is defined in setupapi.h // *hInf = SetupOpenInfFile(ProfileName, NULL, INF_STYLE_WIN4, NULL ); if (*hInf == INVALID_HANDLE_VALUE) return( ScepDosErrorToSceStatus( GetLastError() ) ); else return( SCESTATUS_SUCCESS); } SCESTATUS SceInfpCloseProfile( IN HINF hInf ) { if ( hInf != INVALID_HANDLE_VALUE ) SetupCloseInfFile( hInf ); return(SCESTATUS_SUCCESS); } SCESTATUS ScepConvertMultiSzToDelim( IN PWSTR pValue, IN DWORD Len, IN WCHAR DelimFrom, IN WCHAR Delim ) /* Convert the multi-sz delimiter \0 to space */ { DWORD i; for ( i=0; i<Len && pValue; i++) { // if ( *(pValue+i) == L'\0' && *(pValue+i+1) != L'\0') { if ( *(pValue+i) == DelimFrom && i+1 < Len && *(pValue+i+1) != L'\0' ) { // // a NULL delimiter is encounted and it's not the end (double NULL) // *(pValue+i) = Delim; } } return(SCESTATUS_SUCCESS); } /* SCESTATUS SceInfpInfErrorToSceStatus( IN SCEINF_STATUS InfErr ) /* ++ Routine Description: This routine converts error codes from Inf routines into SCESTATUS code. Arguments: InfErr - The error code from Inf routines Return Value: SCESTATUS code -- *//* { SCESTATUS rc; switch ( InfErr ) { case SCEINF_SUCCESS: rc = SCESTATUS_SUCCESS; break; case SCEINF_PROFILE_NOT_FOUND: rc = SCESTATUS_PROFILE_NOT_FOUND; break; case SCEINF_NOT_ENOUGH_MEMORY: rc = SCESTATUS_NOT_ENOUGH_RESOURCE; break; case SCEINF_INVALID_PARAMETER: rc = SCESTATUS_INVALID_PARAMETER; break; case SCEINF_CORRUPT_PROFILE: rc = SCESTATUS_BAD_FORMAT; break; case SCEINF_INVALID_DATA: rc = SCESTATUS_INVALID_DATA; break; case SCEINF_ACCESS_DENIED: rc = SCESTATUS_ACCESS_DENIED; break; default: rc = SCESTATUS_OTHER_ERROR; break; } return(rc); } */ // // below are exported APIs in secedit.h // SCESTATUS WINAPI SceCreateDirectory( IN PCWSTR ProfileLocation, IN BOOL FileOrDir, PSECURITY_DESCRIPTOR pSecurityDescriptor ) { return ( ScepCreateDirectory(ProfileLocation, FileOrDir, pSecurityDescriptor )); } SCESTATUS WINAPI SceCompareSecurityDescriptors( IN AREA_INFORMATION Area, IN PSECURITY_DESCRIPTOR pSD1, IN PSECURITY_DESCRIPTOR pSD2, IN SECURITY_INFORMATION SeInfo, OUT PBOOL IsDifferent ) { SE_OBJECT_TYPE ObjectType; BYTE resultSD=0; SCESTATUS rc; BOOL bContainer = FALSE; switch ( Area) { case AREA_REGISTRY_SECURITY: ObjectType = SE_REGISTRY_KEY; bContainer = TRUE; break; case AREA_FILE_SECURITY: ObjectType = SE_FILE_OBJECT; break; case AREA_DS_OBJECTS: ObjectType = SE_DS_OBJECT; bContainer = TRUE; break; case AREA_SYSTEM_SERVICE: ObjectType = SE_SERVICE; break; default: ObjectType = SE_FILE_OBJECT; break; } rc = ScepCompareObjectSecurity( ObjectType, bContainer, pSD1, pSD2, SeInfo, &resultSD); if ( resultSD ) *IsDifferent = TRUE; else *IsDifferent = FALSE; return(rc); } SCESTATUS WINAPI SceAddToNameStatusList( IN OUT PSCE_NAME_STATUS_LIST *pNameStatusList, IN PWSTR Name, IN ULONG Len, IN DWORD Status ) { return(ScepAddToNameStatusList( pNameStatusList, Name, Len, Status) ); } SCESTATUS WINAPI SceAddToNameList( IN OUT PSCE_NAME_LIST *pNameList, IN PWSTR Name, IN ULONG Len ) { return( ScepDosErrorToSceStatus( ScepAddToNameList( pNameList, Name, Len ) ) ); } SCESTATUS WINAPI SceAddToObjectList( IN OUT PSCE_OBJECT_LIST *pObjectList, IN PWSTR Name, IN ULONG Len, IN BOOL IsContainer, // TRUE if the object is a container type IN BYTE Status, // SCE_STATUS_IGNORE, SCE_STATUS_CHECK, SCE_STATUS_OVERWRITE IN BYTE byFlags // SCE_CHECK_DUP if duplicate Name entry should not be added, SCE_INCREASE_COUNT ) { return(ScepDosErrorToSceStatus( ScepAddToObjectList( pObjectList, Name, Len, IsContainer, Status, 0, byFlags ) ) ); } BOOL SceCompareNameList( IN PSCE_NAME_LIST pList1, IN PSCE_NAME_LIST pList2 ) /* Routine Description: This routine compares two name lists for exact match. Sequence is not important in comparsion. */ { PSCE_NAME_LIST pName1, pName2; DWORD Count1=0, Count2=0; if ( (pList2 == NULL && pList1 != NULL) || (pList2 != NULL && pList1 == NULL) ) { // return(TRUE); // should be not equal return(FALSE); } for ( pName2=pList2; pName2 != NULL; pName2 = pName2->Next ) { if ( pName2->Name == NULL ) { continue; } Count2++; } for ( pName1=pList1; pName1 != NULL; pName1 = pName1->Next ) { if ( pName1->Name == NULL ) { continue; } Count1++; for ( pName2=pList2; pName2 != NULL; pName2 = pName2->Next ) { if ( pName2->Name == NULL ) { continue; } if ( _wcsicmp(pName1->Name, pName2->Name) == 0 ) { // // find a match // break; // the second for loop } } if ( pName2 == NULL ) { // // does not find a match // return(FALSE); } } if ( Count1 != Count2 ) return(FALSE); return(TRUE); } DWORD WINAPI SceEnumerateServices( OUT PSCE_SERVICES *pServiceList, IN BOOL bServiceNameOnly ) /* Routine Description: Enumerate all services installed on the local system. The information returned include startup status and security descriptor on each service object. Arguments: pServiceList - the list of services returned. Must be freed by LocalFree return value: ERROR_SUCCESS Win32 error codes */ { SC_HANDLE hScManager=NULL; LPENUM_SERVICE_STATUS pEnumBuffer=NULL, pTempEnum; DWORD ResumeHandle=0, BytesNeeded, ServicesCount=0; DWORD BufSize=1024; // // check arguments // if ( NULL == pServiceList ) return(ERROR_INVALID_PARAMETER); // // open service control manager // hScManager = OpenSCManager( NULL, NULL, MAXIMUM_ALLOWED //SC_MANAGER_ALL_ACCESS // SC_MANAGER_CONNECT | // SC_MANAGER_ENUMERATE_SERVICE | // SC_MANAGER_QUERY_LOCK_STATUS ); if ( NULL == hScManager ) { return( GetLastError() ); } DWORD rc=NO_ERROR; DWORD i; DWORD status; if ( !bServiceNameOnly ) { // // Adjust privilege for setting SACL // status = SceAdjustPrivilege( SE_SECURITY_PRIVILEGE, TRUE, NULL ); // // if can't adjust privilege, ignore (will error out later if SACL is requested) // } do { // // enumerate all services // pEnumBuffer = (LPENUM_SERVICE_STATUS)LocalAlloc(LMEM_FIXED,(UINT)BufSize); if ( NULL == pEnumBuffer ) { rc = ERROR_NOT_ENOUGH_MEMORY; break; } if ( !EnumServicesStatus( hScManager, SERVICE_WIN32, // do not expose driver | SERVICE_DRIVER, SERVICE_STATE_ALL, pEnumBuffer, BufSize, &BytesNeeded, &ServicesCount, &ResumeHandle) ) { rc = GetLastError(); } else rc = ERROR_SUCCESS; pTempEnum = pEnumBuffer; // // Process each service // if ( rc == ERROR_SUCCESS || rc == ERROR_MORE_DATA || rc == ERROR_INSUFFICIENT_BUFFER ) { rc = ERROR_SUCCESS; for ( i=0; pEnumBuffer && i<ServicesCount; i++ ) { // // add the service to our list // if ( bServiceNameOnly ) { // // only ask for service name, do not need to query // status = ScepAddOneServiceToList( pEnumBuffer->lpServiceName, pEnumBuffer->lpDisplayName, 0, NULL, 0, TRUE, pServiceList ); } else { // // query startup and security descriptor // status = ScepQueryAndAddService( hScManager, pEnumBuffer->lpServiceName, pEnumBuffer->lpDisplayName, pServiceList ); } if ( status != ERROR_SUCCESS ) { rc = status; break; } pEnumBuffer++; } } // // Free buffer for next enumeration // if ( pTempEnum ) { LocalFree(pTempEnum); pTempEnum = NULL; } pEnumBuffer = NULL; BufSize = BytesNeeded + 2; ServicesCount = 0; } while ( rc == ERROR_SUCCESS && BytesNeeded > 0 ); // // clear memory and close handle // CloseServiceHandle (hScManager); if ( rc != ERROR_SUCCESS ) { // // free memory in pServiceList // SceFreePSCE_SERVICES(*pServiceList); *pServiceList = NULL; } if ( !bServiceNameOnly ) { // // Adjust privilege for SACL // SceAdjustPrivilege( SE_SECURITY_PRIVILEGE, FALSE, NULL ); } return(rc); } DWORD ScepQueryAndAddService( IN SC_HANDLE hScManager, IN LPWSTR lpServiceName, IN LPWSTR lpDisplayName, OUT PSCE_SERVICES *pServiceList ) /* Routine Description: Queries the security descriptor of the service and add all information to PSCE_SERVICE list Arguments: hScManager - service control manager handle lpServiceName - The service name ServiceStatus - The service status pServiceList - The service list to output Return Value: ERROR_SUCCESS Win32 errors */ { SC_HANDLE hService; DWORD rc=ERROR_SUCCESS; if ( hScManager == NULL || lpServiceName == NULL || pServiceList == NULL ) { return(ERROR_INVALID_PARAMETER); } // // Open the service // SERVICE_ALL_ACCESS | // READ_CONTROL | // ACCESS_SYSTEM_SECURITY // hService = OpenService( hScManager, lpServiceName, MAXIMUM_ALLOWED | ACCESS_SYSTEM_SECURITY ); if ( hService != NULL ) { // // Query the startup type // DWORD BytesNeeded=0; DWORD BufSize; // // Query configuration (Startup type) // get size first // if ( !QueryServiceConfig( hService, NULL, 0, &BytesNeeded ) ) { rc = GetLastError(); if ( rc == ERROR_INSUFFICIENT_BUFFER ) { // // should always gets here // LPQUERY_SERVICE_CONFIG pConfig=NULL; pConfig = (LPQUERY_SERVICE_CONFIG)LocalAlloc(0, BytesNeeded+1); if ( pConfig != NULL ) { rc = ERROR_SUCCESS; BufSize=BytesNeeded; // // the real query for Startup type (pConfig->dwStartType) // if ( QueryServiceConfig( hService, pConfig, BufSize, &BytesNeeded ) ) { // // Query the security descriptor length // the following function does not take NULL for the // address of security descriptor so use a temp buffer first // to get the real length // BYTE BufTmp[128]; SECURITY_INFORMATION SeInfo; // // only query DACL and SACL information // /* SeInfo = DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION; */ SeInfo = DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION; if ( !QueryServiceObjectSecurity( hService, SeInfo, (PSECURITY_DESCRIPTOR)BufTmp, 128, &BytesNeeded ) ) { rc = GetLastError(); if ( rc == ERROR_INSUFFICIENT_BUFFER || rc == ERROR_MORE_DATA ) { // // if buffer is not enough, it is ok // because BytesNeeded is the real length // rc = ERROR_SUCCESS; } } else rc = ERROR_SUCCESS; if ( rc == ERROR_SUCCESS ) { // // allocate buffer for security descriptor // PSECURITY_DESCRIPTOR pSecurityDescriptor=NULL; pSecurityDescriptor = (PSECURITY_DESCRIPTOR)LocalAlloc(LMEM_FIXED, BytesNeeded+2); if ( NULL != pSecurityDescriptor ) { // // query the security descriptor // BufSize = BytesNeeded; if ( QueryServiceObjectSecurity( hService, SeInfo, pSecurityDescriptor, BufSize, &BytesNeeded ) ) { // // create a service node and add it to the list // rc = ScepAddOneServiceToList( lpServiceName, lpDisplayName, pConfig->dwStartType, pSecurityDescriptor, SeInfo, TRUE, pServiceList ); } else { // // error query the security descriptor // rc = GetLastError(); } if ( rc != ERROR_SUCCESS ) { LocalFree(pSecurityDescriptor); } } else { // // cannot allocate memory for security descriptor // rc = ERROR_NOT_ENOUGH_MEMORY; } } } else { // // cannot query config // rc = GetLastError(); } LocalFree(pConfig); } else rc = ERROR_NOT_ENOUGH_MEMORY; } } else { // // should not fall in here, if it does, just return success // } CloseServiceHandle(hService); } else { // // cannot open service // rc = GetLastError(); } return(rc); } INT ScepLookupPrivByValue( IN DWORD Priv ) /* ++ Routine Description: This routine looksup a privilege in SCE_Privileges table and returns the index for the priv. Arguments: Priv - The privilege to look up Return value: The index in SCE_Privileges table if a match is found, or -1 for no match -- */ { DWORD i; if ( Priv == 0 ) return (-1); for ( i=0; i<cPrivCnt; i++) { if ( SCE_Privileges[i].Value == Priv ) return i; } return (-1); } SCESTATUS ScepGetProductType( OUT PSCE_SERVER_TYPE srvProduct ) { NT_PRODUCT_TYPE theType; if ( RtlGetNtProductType(&theType) ) { #if _WIN32_WINNT>=0x0500 // // NT5+ // switch (theType) { case NtProductLanManNt: *srvProduct = SCESVR_DC_WITH_DS; break; case NtProductServer: *srvProduct = SCESVR_NT5_SERVER; break; case NtProductWinNt: *srvProduct = SCESVR_NT5_WKS; break; default: *srvProduct = SCESVR_UNKNOWN; } #else // // NT4 // switch (theType) { case NtProductLanManNt: *srvProduct = SCESVR_DC; break; case NtProductServer: *srvProduct = SCESVR_NT4_SERVER; break; case NtProductWinNt: *srvProduct = SCESVR_NT4_WKS; break; default: *srvProduct = SCESVR_UNKNOWN; } #endif } else { *srvProduct = SCESVR_UNKNOWN; } return(SCESTATUS_SUCCESS); } DWORD ScepAddTwoNamesToNameList( OUT PSCE_NAME_LIST *pNameList, IN BOOL bAddSeparator, IN PWSTR Name1, IN ULONG Length1, IN PWSTR Name2, IN ULONG Length2 ) /* ++ Routine Description: This routine adds two names (wchar) to the name list in the format of Name1\Name2, or Name1Name2, depends if bSeparator is TRUE. This routine is used for Domain\Account tracking list Arguments: pNameList - The name list to add to. Name1 - The name 1 to add Length1 - the length of name1 (number of wchars) Name2 - the name 2 to add Length2 - the length of name2 (number of wchars) Return value: Win32 error code -- */ { PSCE_NAME_LIST pList=NULL; ULONG Length; if ( pNameList == NULL ) return(ERROR_INVALID_PARAMETER); if ( Name1 == NULL && Name2 == NULL ) return(NO_ERROR); Length = Length1 + Length2; if ( Length <= 0 ) return(NO_ERROR); pList = (PSCE_NAME_LIST)ScepAlloc( (UINT)0, sizeof(SCE_NAME_LIST)); if ( pList == NULL ) return(ERROR_NOT_ENOUGH_MEMORY); if ( bAddSeparator ) { Length++; } pList->Name = (PWSTR)ScepAlloc( LMEM_ZEROINIT, (Length+1)*sizeof(TCHAR)); if ( pList->Name == NULL ) { ScepFree(pList); return(ERROR_NOT_ENOUGH_MEMORY); } if ( Name1 != NULL && Length1 > 0 ) wcsncpy(pList->Name, Name1, Length1); if ( bAddSeparator ) { wcsncat(pList->Name, L"\\", 1); } if ( Name2 != NULL && Length2 > 0 ) wcsncat(pList->Name, Name2, Length2); pList->Next = *pNameList; *pNameList = pList; return(NO_ERROR); } NTSTATUS ScepDomainIdToSid( IN PSID DomainId, IN ULONG RelativeId, OUT PSID *Sid ) /*++ Routine Description: Given a domain Id and a relative ID create a SID Arguments: DomainId - The template SID to use. RelativeId - The relative Id to append to the DomainId. Sid - Returns a pointer to an allocated buffer containing the resultant Sid. Free this buffer using NetpMemoryFree. Return Value: NTSTATUS --*/ { UCHAR DomainIdSubAuthorityCount; // Number of sub authorities in domain ID ULONG SidLength; // Length of newly allocated SID // // Allocate a Sid which has one more sub-authority than the domain ID. // DomainIdSubAuthorityCount = *(RtlSubAuthorityCountSid( DomainId )); SidLength = RtlLengthRequiredSid(DomainIdSubAuthorityCount+1); if ((*Sid = (PSID) ScepAlloc( (UINT)0, SidLength )) == NULL ) { return STATUS_NO_MEMORY; } // // Initialize the new SID to have the same inital value as the // domain ID. // if ( !NT_SUCCESS( RtlCopySid( SidLength, *Sid, DomainId ) ) ) { ScepFree( *Sid ); *Sid = NULL; return STATUS_INTERNAL_ERROR; } // // Adjust the sub-authority count and // add the relative Id unique to the newly allocated SID // (*(RtlSubAuthorityCountSid( *Sid ))) ++; *RtlSubAuthoritySid( *Sid, DomainIdSubAuthorityCount ) = RelativeId; return ERROR_SUCCESS; } DWORD ScepConvertSidToPrefixStringSid( IN PSID pSid, OUT PWSTR *StringSid ) /* The pair routine to convert stringsid to a Sid is ConvertStringSidToSid defined in sddl.h */ { if ( pSid == NULL || StringSid == NULL ) { return(ERROR_INVALID_PARAMETER); } UNICODE_STRING UnicodeStringSid; DWORD rc = RtlNtStatusToDosError( RtlConvertSidToUnicodeString(&UnicodeStringSid, pSid, TRUE )); if ( ERROR_SUCCESS == rc ) { *StringSid = (PWSTR)ScepAlloc(LPTR, UnicodeStringSid.Length+2*sizeof(WCHAR)); if ( *StringSid ) { (*StringSid)[0] = L'*'; wcsncpy( (*StringSid)+1, UnicodeStringSid.Buffer, UnicodeStringSid.Length/2); } else { rc = ERROR_NOT_ENOUGH_MEMORY; } RtlFreeUnicodeString( &UnicodeStringSid ); } return(rc); } NTSTATUS ScepConvertSidToName( IN LSA_HANDLE LsaPolicy, IN PSID AccountSid, IN BOOL bFromDomain, OUT PWSTR *AccountName, OUT DWORD *Length OPTIONAL ) { if ( LsaPolicy == NULL || AccountSid == NULL || AccountName == NULL ) { return(STATUS_INVALID_PARAMETER); } PSID pTmpSid=AccountSid; PLSA_TRANSLATED_NAME Names=NULL; PLSA_REFERENCED_DOMAIN_LIST ReferencedDomains=NULL; NTSTATUS NtStatus = LsaLookupSids( LsaPolicy, 1, (PSID *)&pTmpSid, &ReferencedDomains, &Names ); DWORD Len=0; if ( NT_SUCCESS(NtStatus) ) { if ( ( Names[0].Use != SidTypeInvalid && Names[0].Use != SidTypeUnknown ) ) { // // build the account name without domain name // if ( bFromDomain && Names[0].Use != SidTypeWellKnownGroup && ReferencedDomains->Entries > 0 && ReferencedDomains->Domains != NULL && Names[0].DomainIndex != -1 && (ULONG)(Names[0].DomainIndex) < ReferencedDomains->Entries && ReferencedDomains->Domains[Names[0].DomainIndex].Name.Length > 0 && ScepIsSidFromAccountDomain( ReferencedDomains->Domains[Names[0].DomainIndex].Sid ) ) { // // build domain name\account name // Len = Names[0].Name.Length + ReferencedDomains->Domains[Names[0].DomainIndex].Name.Length + 2; *AccountName = (PWSTR)LocalAlloc(LPTR, Len+sizeof(TCHAR)); if ( *AccountName ) { wcsncpy(*AccountName, ReferencedDomains->Domains[Names[0].DomainIndex].Name.Buffer, ReferencedDomains->Domains[Names[0].DomainIndex].Name.Length/2); (*AccountName)[ReferencedDomains->Domains[Names[0].DomainIndex].Name.Length/2] = L'\\'; wcsncpy((*AccountName)+ReferencedDomains->Domains[Names[0].DomainIndex].Name.Length/2+1, Names[0].Name.Buffer, Names[0].Name.Length/2); } else { NtStatus = STATUS_NO_MEMORY; } Len /= 2; } else { Len = Names[0].Name.Length/2; *AccountName = (PWSTR)LocalAlloc(LPTR, Names[0].Name.Length+2); if ( *AccountName ) { wcsncpy(*AccountName, Names[0].Name.Buffer, Len); } else { NtStatus = STATUS_NO_MEMORY; } } } else { NtStatus = STATUS_NONE_MAPPED; } } if ( ReferencedDomains ) { LsaFreeMemory(ReferencedDomains); ReferencedDomains = NULL; } if ( Names ) { LsaFreeMemory(Names); Names = NULL; } if ( NT_SUCCESS(NtStatus) && Length ) { *Length = Len; } return(NtStatus); } NTSTATUS ScepConvertNameToSid( IN LSA_HANDLE LsaPolicy, IN PWSTR AccountName, OUT PSID *AccountSid ) { if ( LsaPolicy == NULL || AccountName == NULL || AccountSid == NULL ) { return(STATUS_INVALID_PARAMETER); } PLSA_REFERENCED_DOMAIN_LIST RefDomains=NULL; PLSA_TRANSLATED_SID2 Sids=NULL; NTSTATUS NtStatus = ScepLsaLookupNames2( LsaPolicy, LSA_LOOKUP_ISOLATED_AS_LOCAL, AccountName, &RefDomains, &Sids ); if ( NT_SUCCESS(NtStatus) && Sids ) { // // build the account sid // if ( Sids[0].Use != SidTypeInvalid && Sids[0].Use != SidTypeUnknown && Sids[0].Sid != NULL ) { // // this name is mapped, the SID is in Sids[0].Sid // DWORD SidLength = RtlLengthSid(Sids[0].Sid); if ( (*AccountSid = (PSID) ScepAlloc( (UINT)0, SidLength)) == NULL ) { NtStatus = STATUS_NO_MEMORY; } else { // // copy the SID // NtStatus = RtlCopySid( SidLength, *AccountSid, Sids[0].Sid ); if ( !NT_SUCCESS(NtStatus) ) { ScepFree( *AccountSid ); *AccountSid = NULL; } } } else { NtStatus = STATUS_NONE_MAPPED; } } if ( Sids ) { LsaFreeMemory(Sids); } if ( RefDomains ) { LsaFreeMemory(RefDomains); } return(NtStatus); } NTSTATUS ScepLsaLookupNames2( IN LSA_HANDLE PolicyHandle, IN ULONG Flags, IN PWSTR pszAccountName, OUT PLSA_REFERENCED_DOMAIN_LIST *ReferencedDomains, OUT PLSA_TRANSLATED_SID2 *Sids ) /*++ Routine Description: Similar to LsaLookupNames2 except that on local lookup failures, it resolves free text accounts to the domain this machine is joined to Arguments: PolicyHandle - handle to LSA Flags - usually LSA_LOOKUP_ISOLATED_AS_LOCAL pszAccountName - name of account to lookup ReferencedDomains - returns the reference domain id (to be freed by caller) Sids - returns the SID looked up (to be freed by caller) Return Value: NTSTATUS --*/ { PWSTR pszScopedName = NULL; UNICODE_STRING UnicodeName; PPOLICY_ACCOUNT_DOMAIN_INFO pDomainInfo = NULL; RtlInitUnicodeString(&UnicodeName, pszAccountName); NTSTATUS NtStatus = LsaLookupNames2( PolicyHandle, Flags, 1, &UnicodeName, ReferencedDomains, Sids ); if ((NtStatus == STATUS_SOME_NOT_MAPPED || NtStatus == STATUS_NONE_MAPPED) && NULL == wcschr(pszAccountName, L'\\') ) { NtStatus = LsaQueryInformationPolicy(PolicyHandle, PolicyDnsDomainInformation, ( PVOID * )&pDomainInfo ); if (!NT_SUCCESS(NtStatus) || pDomainInfo == NULL || pDomainInfo->DomainName.Buffer == NULL || pDomainInfo->DomainName.Length <= 0) { NtStatus = STATUS_SOME_NOT_MAPPED; goto ExitHandler; } pszScopedName = (PWSTR) LocalAlloc(LMEM_ZEROINIT, (pDomainInfo->DomainName.Length/2 + wcslen(pszAccountName) + 2) * sizeof(WCHAR)); if (pszScopedName == NULL) { NtStatus = STATUS_NO_MEMORY; goto ExitHandler; } wcsncpy(pszScopedName, pDomainInfo->DomainName.Buffer, pDomainInfo->DomainName.Length/2); wcscat(pszScopedName, L"\\"); wcscat(pszScopedName, pszAccountName); RtlInitUnicodeString(&UnicodeName, pszScopedName); NtStatus = LsaLookupNames2( PolicyHandle, Flags, 1, &UnicodeName, ReferencedDomains, Sids ); } ExitHandler: if (pszScopedName) { LocalFree(pszScopedName); } if (pDomainInfo) { LsaFreeMemory( pDomainInfo ); } if ( STATUS_SUCCESS != NtStatus ) return STATUS_NONE_MAPPED; else return STATUS_SUCCESS; } SCESTATUS ScepConvertNameToSidString( IN LSA_HANDLE LsaHandle, IN PWSTR Name, IN BOOL bAccountDomainOnly, OUT PWSTR *SidString, OUT DWORD *SidStrLen ) { if ( LsaHandle == NULL || Name == NULL ) { return(SCESTATUS_INVALID_PARAMETER); } if ( Name[0] == L'\0' ) { return(SCESTATUS_INVALID_PARAMETER); } if ( SidString == NULL || SidStrLen == NULL ) { return(SCESTATUS_INVALID_PARAMETER); } // // convert the sid string to a real sid // PSID pSid=NULL; NTSTATUS NtStatus; DWORD rc; PLSA_REFERENCED_DOMAIN_LIST RefDomains=NULL; PLSA_TRANSLATED_SID2 Sids=NULL; NtStatus = ScepLsaLookupNames2( LsaHandle, LSA_LOOKUP_ISOLATED_AS_LOCAL, Name, &RefDomains, &Sids ); rc = RtlNtStatusToDosError(NtStatus); if ( ERROR_SUCCESS == rc && Sids ) { // // name is found, make domain\account format // if ( Sids[0].Use != SidTypeInvalid && Sids[0].Use != SidTypeUnknown && Sids[0].Sid != NULL ) { // // this name is mapped // if ( !bAccountDomainOnly || ScepIsSidFromAccountDomain( Sids[0].Sid ) ) { // // convert to a sid string, note: a prefix "*" should be added // UNICODE_STRING UnicodeStringSid; rc = RtlNtStatusToDosError( RtlConvertSidToUnicodeString(&UnicodeStringSid, Sids[0].Sid, TRUE )); if ( ERROR_SUCCESS == rc ) { *SidStrLen = UnicodeStringSid.Length/2 + 1; *SidString = (PWSTR)ScepAlloc(LPTR, UnicodeStringSid.Length + 2*sizeof(WCHAR)); if ( *SidString ) { (*SidString)[0] = L'*'; wcsncpy((*SidString)+1, UnicodeStringSid.Buffer, (*SidStrLen)-1); } else { *SidStrLen = 0; rc = ERROR_NOT_ENOUGH_MEMORY; } RtlFreeUnicodeString( &UnicodeStringSid ); } } else { // // add only the account name // rc = ERROR_NONE_MAPPED; } } else { rc = ERROR_NONE_MAPPED; } } if ( Sids ) { LsaFreeMemory(Sids); } if ( RefDomains ) { LsaFreeMemory(RefDomains); } return(ScepDosErrorToSceStatus(rc)); } SCESTATUS ScepLookupSidStringAndAddToNameList( IN LSA_HANDLE LsaHandle, IN OUT PSCE_NAME_LIST *pNameList, IN PWSTR LookupString, IN ULONG Len ) { if ( LsaHandle == NULL || LookupString == NULL ) { return(SCESTATUS_INVALID_PARAMETER); } if ( LookupString[0] == L'\0' ) { return(SCESTATUS_INVALID_PARAMETER); } if ( Len <= 3 || (LookupString[1] != L'S' && LookupString[1] != L's') || LookupString[2] != L'-' ) { return(SCESTATUS_INVALID_PARAMETER); } // // convert the sid string to a real sid // PSID pSid=NULL; NTSTATUS NtStatus; DWORD rc; PLSA_REFERENCED_DOMAIN_LIST RefDomains=NULL; PLSA_TRANSLATED_NAME Names=NULL; if ( ConvertStringSidToSid(LookupString+1, &pSid) ) { NtStatus = LsaLookupSids( LsaHandle, 1, &pSid, &RefDomains, &Names ); rc = RtlNtStatusToDosError(NtStatus); LocalFree(pSid); pSid = NULL; } else { rc = GetLastError(); } if ( ERROR_SUCCESS == rc && Names && RefDomains ) { // // name is found, make domain\account format // if ( ( Names[0].Use != SidTypeInvalid && Names[0].Use != SidTypeUnknown ) ) { // // this name is mapped // if ( RefDomains->Entries > 0 && Names[0].Use != SidTypeWellKnownGroup && RefDomains->Domains != NULL && Names[0].DomainIndex != -1 && (ULONG)(Names[0].DomainIndex) < RefDomains->Entries && RefDomains->Domains[Names[0].DomainIndex].Name.Length > 0 && ScepIsSidFromAccountDomain( RefDomains->Domains[Names[0].DomainIndex].Sid ) ) { // // add both domain name and account name // rc = ScepAddTwoNamesToNameList( pNameList, TRUE, RefDomains->Domains[Names[0].DomainIndex].Name.Buffer, RefDomains->Domains[Names[0].DomainIndex].Name.Length/2, Names[0].Name.Buffer, Names[0].Name.Length/2); } else { // // add only the account name // rc = ScepAddToNameList( pNameList, Names[0].Name.Buffer, Names[0].Name.Length/2); } } else { rc = ERROR_NONE_MAPPED; } } else { // // lookup in the constant table for builtin accounts // note. This will resolve the builtin SIDs to the language of the binary // which may not be the locale the process is running (UI) // for (int i = 0; i < TABLE_SIZE; i++) { if ( _wcsicmp(NameTable[i].StrSid, LookupString+1) == 0 ) { // //found match // rc = ScepAddToNameList( pNameList, NameTable[i].Name, 0); break; } } } if ( ERROR_SUCCESS != rc ) { // // either invalid sid string, or not found a name map, or // failed to add to the name list, just simply add the sid string to the name list // rc = ScepAddToNameList( pNameList, LookupString, Len); } if ( Names ) { LsaFreeMemory(Names); } if ( RefDomains ) { LsaFreeMemory(RefDomains); } return(ScepDosErrorToSceStatus(rc)); } SCESTATUS ScepLookupNameAndAddToSidStringList( IN LSA_HANDLE LsaHandle, IN OUT PSCE_NAME_LIST *pNameList, IN PWSTR LookupString, IN ULONG Len ) { if ( LsaHandle == NULL || LookupString == NULL || Len == 0 ) { return(SCESTATUS_INVALID_PARAMETER); } if ( LookupString[0] == L'\0' ) { return(SCESTATUS_INVALID_PARAMETER); } // // convert the sid string to a real sid // PSID pSid=NULL; NTSTATUS NtStatus; DWORD rc; PLSA_REFERENCED_DOMAIN_LIST RefDomains=NULL; PLSA_TRANSLATED_SID2 Sids=NULL; UNICODE_STRING UnicodeName; NtStatus = ScepLsaLookupNames2( LsaHandle, LSA_LOOKUP_ISOLATED_AS_LOCAL, LookupString, &RefDomains, &Sids ); rc = RtlNtStatusToDosError(NtStatus); if ( ERROR_SUCCESS == rc && Sids ) { // // name is found, make domain\account format // if ( Sids[0].Use != SidTypeInvalid && Sids[0].Use != SidTypeUnknown && Sids[0].Sid ) { // // this name is mapped // convert to a sid string, note: a prefix "*" should be added // UNICODE_STRING UnicodeStringSid; rc = RtlNtStatusToDosError( RtlConvertSidToUnicodeString(&UnicodeStringSid, Sids[0].Sid, TRUE )); if ( ERROR_SUCCESS == rc ) { rc = ScepAddTwoNamesToNameList( pNameList, FALSE, TEXT("*"), 1, UnicodeStringSid.Buffer, UnicodeStringSid.Length/2); RtlFreeUnicodeString( &UnicodeStringSid ); } } else { rc = ERROR_NONE_MAPPED; } } if ( ERROR_SUCCESS != rc ) { // // either invalid sid string, or not found a name map, or // failed to add to the name list, just simply add the sid string to the name list // rc = ScepAddToNameList( pNameList, LookupString, Len); } if ( Sids ) { LsaFreeMemory(Sids); } if ( RefDomains ) { LsaFreeMemory(RefDomains); } return(ScepDosErrorToSceStatus(rc)); } NTSTATUS ScepOpenLsaPolicy( IN ACCESS_MASK access, OUT PLSA_HANDLE pPolicyHandle, IN BOOL bDoNotNotify ) /* ++ Routine Description: This routine opens the LSA policy with the desired access. Arguments: access - the desired access to the policy pPolicyHandle - returned address of the Policy Handle Return value: NTSTATUS -- */ { NTSTATUS NtStatus; LSA_OBJECT_ATTRIBUTES attributes; SECURITY_QUALITY_OF_SERVICE service; memset( &attributes, 0, sizeof(attributes) ); attributes.Length = sizeof(attributes); attributes.SecurityQualityOfService = &service; service.Length = sizeof(service); service.ImpersonationLevel= SecurityImpersonation; service.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING; service.EffectiveOnly = TRUE; // // open the lsa policy first // NtStatus = LsaOpenPolicy( NULL, &attributes, access, pPolicyHandle ); /* if ( NT_SUCCESS(NtStatus) && bDoNotNotify && *pPolicyHandle ) { NtStatus = LsaSetPolicyReplicationHandle(pPolicyHandle); if ( !NT_SUCCESS(NtStatus) ) { LsaClose( *pPolicyHandle ); *pPolicyHandle = NULL; } } */ return(NtStatus); } BOOL ScepIsSidFromAccountDomain( IN PSID pSid ) { if ( pSid == NULL ) { return(FALSE); } if ( !RtlValidSid(pSid) ) { return(FALSE); } PSID_IDENTIFIER_AUTHORITY pia = RtlIdentifierAuthoritySid ( pSid ); if ( pia ) { if ( pia->Value[5] != 5 || pia->Value[0] != 0 || pia->Value[1] != 0 || pia->Value[2] != 0 || pia->Value[3] != 0 || pia->Value[4] != 0 ) { // // this is not a account from account domain // return(FALSE); } if ( RtlSubAuthorityCountSid( pSid ) == 0 || *RtlSubAuthoritySid ( pSid, 0 ) != SECURITY_NT_NON_UNIQUE ) { return(FALSE); } return(TRUE); } return(FALSE); } //+-------------------------------------------------------------------------- // // Function: SetupINFAsUCS2 // // Synopsis: Dumps some UCS-2 to the specified INF file if it // doesn't already exist; this makes the .inf/.ini manipulation code // use UCS-2. // // Arguments: The file to create and dump to // // Returns: 0 == failure, non-zero == success; use GetLastError() // to retrieve the error code (same as WriteFile). // //+-------------------------------------------------------------------------- BOOL SetupINFAsUCS2(LPCTSTR szName) { HANDLE file; BOOL status; file = CreateFile(szName, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (file == INVALID_HANDLE_VALUE) { if (GetLastError() != ERROR_ALREADY_EXISTS) // Well, this isn't good -- we lose. status = FALSE; else // Otherwise, the file already existed, which is just fine. // We'll just let the .inf/.ini manipulation code keep using // the same charset&encoding... status = TRUE; } else { // We created the file -- it didn't exist. // So we need to spew a little UCS-2 into it. static WCHAR str[] = L"0[Unicode]\r\nUnicode=yes\r\n"; DWORD n_written; BYTE *pbStr = (BYTE *)str; pbStr[0] = 0xFF; pbStr[1] = 0xFE; status = WriteFile(file, (LPCVOID)str, sizeof(str) - sizeof(UNICODE_NULL), &n_written, NULL); CloseHandle(file); } return status; } //+-------------------------------------------------------------------------- // // Function: ScepStripPrefix // // Arguments: pwszPath to look in // // Returns: Returns ptr to stripped path (same if no stripping) // //+-------------------------------------------------------------------------- WCHAR * ScepStripPrefix( IN LPTSTR pwszPath ) { WCHAR wszMachPrefix[] = TEXT("LDAP://CN=Machine,"); INT iMachPrefixLen = lstrlen( wszMachPrefix ); WCHAR wszUserPrefix[] = TEXT("LDAP://CN=User,"); INT iUserPrefixLen = lstrlen( wszUserPrefix ); WCHAR *pwszPathSuffix; // // Strip out prefix to get the canonical path to Gpo // if ( CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE, pwszPath, iUserPrefixLen, wszUserPrefix, iUserPrefixLen ) == CSTR_EQUAL ) { pwszPathSuffix = pwszPath + iUserPrefixLen; } else if ( CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE, pwszPath, iMachPrefixLen, wszMachPrefix, iMachPrefixLen ) == CSTR_EQUAL ) { pwszPathSuffix = pwszPath + iMachPrefixLen; } else pwszPathSuffix = pwszPath; return pwszPathSuffix; } //+-------------------------------------------------------------------------- // // Function: ScepGenerateGuid // // Arguments: out: the guid string // // Returns: Returns guid string (has to be freed outside // //+-------------------------------------------------------------------------- /* DWORD ScepGenerateGuid( OUT PWSTR *ppwszGuid ) { GUID guid; DWORD rc = ERROR_SUCCESS; if (ppwszGuid == NULL) return ERROR_INVALID_PARAMETER; *ppwszGuid = (PWSTR) ScepAlloc(LMEM_ZEROINIT, (MAX_GUID_STRING_LEN + 1) * sizeof(WCHAR)); if (*ppwszGuid) { if (ERROR_SUCCESS == (rc = ScepWbemErrorToDosError(CoCreateGuid( &guid )))) { if (!SCEP_NULL_GUID(guid)) SCEP_GUID_TO_STRING(guid, *ppwszGuid); else { rc = ERROR_INVALID_PARAMETER; } } } else rc = ERROR_NOT_ENOUGH_MEMORY; return rc; } */ SCESTATUS SceInfpGetPrivileges( IN HINF hInf, IN BOOL bLookupAccount, OUT PSCE_PRIVILEGE_ASSIGNMENT *pPrivileges, OUT PSCE_ERROR_LOG_INFO *Errlog OPTIONAL ) /* ++ Description: Get user right assignments from a INF template. If bLookupAccount is set to TRUE, the accounts in user right assignments will be translated to account names (from SID format); else the information is returned in the same way as defined in the template. Arguments: Return Value: -- */ { INFCONTEXT InfLine; SCESTATUS rc=SCESTATUS_SUCCESS; PSCE_PRIVILEGE_ASSIGNMENT pCurRight=NULL; WCHAR Keyname[SCE_KEY_MAX_LENGTH]; PWSTR StrValue=NULL; DWORD DataSize; DWORD PrivValue; DWORD i, cFields; LSA_HANDLE LsaHandle=NULL; // // [Privilege Rights] section // if(SetupFindFirstLine(hInf,szPrivilegeRights,NULL,&InfLine)) { // // open lsa policy handle for sid/name lookup // rc = RtlNtStatusToDosError( ScepOpenLsaPolicy( POLICY_LOOKUP_NAMES | POLICY_VIEW_LOCAL_INFORMATION, &LsaHandle, TRUE )); if ( ERROR_SUCCESS != rc ) { ScepBuildErrorLogInfo( rc, Errlog, SCEERR_ADD, TEXT("LSA") ); return(ScepDosErrorToSceStatus(rc)); } do { memset(Keyname, '\0', SCE_KEY_MAX_LENGTH*sizeof(WCHAR)); rc = SCESTATUS_SUCCESS; if ( SetupGetStringField(&InfLine, 0, Keyname, SCE_KEY_MAX_LENGTH, NULL) ) { // // find a key name (which is a privilege name here ). // lookup privilege's value // if ( ( PrivValue = ScepLookupPrivByName(Keyname) ) == -1 ) { ScepBuildErrorLogInfo( ERROR_INVALID_DATA, Errlog, SCEERR_INVALID_PRIVILEGE, Keyname ); // goto NextLine; } // // a sm_privilege_assignment structure. allocate buffer // pCurRight = (PSCE_PRIVILEGE_ASSIGNMENT)ScepAlloc( LMEM_ZEROINIT, sizeof(SCE_PRIVILEGE_ASSIGNMENT) ); if ( pCurRight == NULL ) { rc = SCESTATUS_NOT_ENOUGH_RESOURCE; goto Done; } pCurRight->Name = (PWSTR)ScepAlloc( (UINT)0, (wcslen(Keyname)+1)*sizeof(WCHAR)); if ( pCurRight->Name == NULL ) { ScepFree(pCurRight); rc = SCESTATUS_NOT_ENOUGH_RESOURCE; goto Done; } wcscpy(pCurRight->Name, Keyname); pCurRight->Value = PrivValue; cFields = SetupGetFieldCount( &InfLine ); for ( i=0; i<cFields && rc==SCESTATUS_SUCCESS; i++) { // // read each user/group name // if ( SetupGetStringField( &InfLine, i+1, NULL, 0, &DataSize ) ) { if (DataSize > 1) { StrValue = (PWSTR)ScepAlloc( 0, (DataSize+1)*sizeof(WCHAR) ); if ( StrValue == NULL ) rc = SCESTATUS_NOT_ENOUGH_RESOURCE; else { StrValue[DataSize] = L'\0'; if ( SetupGetStringField( &InfLine, i+1, StrValue, DataSize, NULL) ) { if ( bLookupAccount && StrValue[0] == L'*' && DataSize > 0 ) { // // this is a SID format, should look it up // rc = ScepLookupSidStringAndAddToNameList( LsaHandle, &(pCurRight->AssignedTo), StrValue, // +1, DataSize // -1 ); } else { rc = ScepAddToNameList(&(pCurRight->AssignedTo), StrValue, DataSize ); } } else rc = SCESTATUS_INVALID_DATA; } ScepFree( StrValue ); StrValue = NULL; } } else { ScepBuildErrorLogInfo( ERROR_INVALID_DATA, Errlog, SCEERR_QUERY_INFO, Keyname ); rc = SCESTATUS_INVALID_DATA; } } if ( rc == SCESTATUS_SUCCESS ) { // // add this node to the list // pCurRight->Next = *pPrivileges; *pPrivileges = pCurRight; pCurRight = NULL; } else ScepFreePrivilege(pCurRight); } else rc = SCESTATUS_BAD_FORMAT; //NextLine: if (rc != SCESTATUS_SUCCESS ) { ScepBuildErrorLogInfo( ScepSceStatusToDosError(rc), Errlog, SCEERR_QUERY_INFO, szPrivilegeRights ); goto Done; } } while(SetupFindNextLine(&InfLine,&InfLine)); } Done: if ( StrValue != NULL ) ScepFree(StrValue); if ( LsaHandle ) { LsaClose(LsaHandle); } return(rc); } NTSTATUS ScepIsSystemContext( IN HANDLE hUserToken, OUT BOOL *pbSystem ) { NTSTATUS NtStatus; DWORD nRequired; // // variables to determine calling context // PTOKEN_USER pUser=NULL; SID_IDENTIFIER_AUTHORITY ia=SECURITY_NT_AUTHORITY; PSID SystemSid=NULL; BOOL b; // // get current user SID in the token // NtStatus = NtQueryInformationToken (hUserToken, TokenUser, NULL, 0, &nRequired ); if ( STATUS_BUFFER_TOO_SMALL == NtStatus ) { pUser = (PTOKEN_USER)LocalAlloc(0,nRequired+1); if ( pUser ) { NtStatus = NtQueryInformationToken (hUserToken, TokenUser, (PVOID)pUser, nRequired, &nRequired ); } else { NtStatus = STATUS_NO_MEMORY; } } b = FALSE; if ( NT_SUCCESS(NtStatus) && pUser && pUser->User.Sid ) { // // build system sid and compare with the current user SID // NtStatus = RtlAllocateAndInitializeSid (&ia,1,SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &SystemSid); if ( NT_SUCCESS(NtStatus) && SystemSid ) { // // check to see if it is system sid // if ( RtlEqualSid(pUser->User.Sid, SystemSid) ) { b=TRUE; } } } // // free memory allocated // if ( SystemSid ) { FreeSid(SystemSid); } if ( pUser ) { LocalFree(pUser); } *pbSystem = b; return NtStatus; } BOOL IsNT5() { WCHAR szInfName[MAX_PATH*2+1]; szInfName[0] = L'\0'; DWORD cNumCharsReturned = GetSystemWindowsDirectory(szInfName, MAX_PATH); if (cNumCharsReturned) { wcscat(szInfName, L"\\system32\\$winnt$.inf"); } else { return TRUE; } UINT nRet = GetPrivateProfileInt( L"Networking", L"BuildNumber", 0, szInfName ); if (nRet == 0) { return TRUE; } else if (nRet > 1381) { return TRUE; } return FALSE; } DWORD ScepVerifyTemplateName( IN PWSTR InfTemplateName, OUT PSCE_ERROR_LOG_INFO *pErrlog OPTIONAL ) /* Routine Description: This routine verifies the template name for read protection and invalid path Arguments: InfTemplateName - the full path name of the inf template pErrlog - the error log buffer Return Value: WIN32 error code */ { if ( !InfTemplateName ) { return(ERROR_INVALID_PARAMETER); } PWSTR DefProfile; DWORD rc; // // verify the InfTemplateName to generate // if read only, or access denied, return ERROR_ACCESS_DENIED // if invalid path, return ERROR_PATH_NOT_FOUND // DefProfile = InfTemplateName + wcslen(InfTemplateName)-1; while ( DefProfile > InfTemplateName+1 ) { if ( *DefProfile != L'\\') { DefProfile--; } else { break; } } rc = NO_ERROR; if ( DefProfile > InfTemplateName+2 ) { // at least allow a drive letter, a colon, and a \ // // find the directory path // DWORD Len=(DWORD)(DefProfile-InfTemplateName); PWSTR TmpBuf=(PWSTR)LocalAlloc(0, (Len+1)*sizeof(WCHAR)); if ( TmpBuf ) { wcsncpy(TmpBuf, InfTemplateName, Len); TmpBuf[Len] = L'\0'; if ( 0xFFFFFFFF == GetFileAttributes(TmpBuf) ) rc = ERROR_PATH_NOT_FOUND; LocalFree(TmpBuf); } else { rc = ERROR_NOT_ENOUGH_MEMORY; } } else if ( DefProfile == InfTemplateName+2 && InfTemplateName[1] == L':' ) { // // this is a template path off the root // } else { // // invalid directory path // rc = ERROR_PATH_NOT_FOUND; } if ( rc != NO_ERROR ) { // // error occurs // if ( ERROR_PATH_NOT_FOUND == rc ) { ScepBuildErrorLogInfo( rc, pErrlog, SCEERR_INVALID_PATH, InfTemplateName ); } return(rc); } // // make it unicode aware // do not worry about failure // SetupINFAsUCS2(InfTemplateName); // // validate if the template is write protected // FILE *hTempFile; hTempFile = _wfopen(InfTemplateName, L"a+"); if ( !hTempFile ) { // // can't overwrite/create the file, must be access denied // rc = ERROR_ACCESS_DENIED; ScepBuildErrorLogInfo( rc, pErrlog, SCEERR_ERROR_CREATE, InfTemplateName ); return(rc); } else { fclose( hTempFile ); } return(rc); }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
44948cf2e10d13c406ed4c0ddc26e4fcedbdc12d
acc2f5336d768a7d86dbd2eec441283cfd11d52d
/src/server/gameserver/EffectSafeForceScroll.cpp
fb76ef16c4ac0b6f52c5952cec9dc4c572515887
[]
no_license
stevexk/server
86df9e8c2448ad97db9c3ab86820beec507ef092
4ddb6e7cfa510bb13ccd87f56db008aa1be1baad
refs/heads/master
2020-01-23T22:00:57.359964
2015-09-18T14:58:27
2015-09-18T14:58:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,809
cpp
////////////////////////////////////////////////////////////////////////////// // Filename : EffectSafeForceScroll.cpp // Written by : bezz // Description : ////////////////////////////////////////////////////////////////////////////// #include "EffectSafeForceScroll.h" #include "PlayerCreature.h" #include "Zone.h" #include "GCRemoveEffect.h" #include "Timeval.h" #include "DB.h" ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// EffectSafeForceScroll::EffectSafeForceScroll(Creature* pCreature) throw(Error) { __BEGIN_TRY setTarget(pCreature); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::affect() throw(Error) { __BEGIN_TRY Creature* pCreature = dynamic_cast<Creature *>(m_pTarget); affect(pCreature); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::affect(Creature* pCreature) throw(Error) { __BEGIN_TRY PlayerCreature* pPC = dynamic_cast<PlayerCreature*>(pCreature); Assert(pPC != NULL); pPC->initAllStatAndSend(); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::unaffect() throw(Error) { __BEGIN_TRY Creature* pCreature = dynamic_cast<Creature *>(m_pTarget); unaffect(pCreature); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::unaffect(Creature* pCreature) throw(Error) { __BEGIN_TRY PlayerCreature* pPC = dynamic_cast<PlayerCreature*>(pCreature); Assert(pPC != NULL); Zone* pZone = pPC->getZone(); Assert(pZone != NULL); pPC->removeFlag(getEffectClass()); pPC->initAllStatAndSend(); GCRemoveEffect gcRemoveEffect; gcRemoveEffect.setObjectID(pCreature->getObjectID()); gcRemoveEffect.addEffectList(getEffectClass()); pZone->broadcastPacket(pPC->getX(), pPC->getY(), &gcRemoveEffect); destroy(pPC->getName()); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::create(const string& ownerID ) throw(Error) { __BEGIN_TRY Statement* pStmt = NULL; BEGIN_DB { pStmt = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement(); Timeval currentTime; getCurrentTime(currentTime); Timeval remainTime = timediff(m_Deadline, currentTime); Turn_t remainTurn = remainTime.tv_sec * 10 + remainTime.tv_usec / 100000; pStmt->executeQuery("INSERT INTO EffectSafeForceScroll (OwnerID, RemainTime ) VALUES('%s',%lu)", ownerID.c_str(), remainTurn); SAFE_DELETE(pStmt); } END_DB(pStmt) __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::destroy(const string& ownerID ) throw(Error) { __BEGIN_TRY Statement* pStmt = NULL; BEGIN_DB { pStmt = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement(); pStmt->executeQuery("DELETE FROM EffectSafeForceScroll WHERE OwnerID = '%s'", ownerID.c_str()); SAFE_DELETE(pStmt); } END_DB(pStmt) __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::save(const string& ownerID ) throw(Error) { __BEGIN_TRY Statement* pStmt = NULL; BEGIN_DB { pStmt = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement(); Timeval currentTime; getCurrentTime(currentTime); Timeval remainTime = timediff(m_Deadline, currentTime); Turn_t remainTurn = remainTime.tv_sec * 10 + remainTime.tv_usec / 100000; pStmt->executeQuery("UPDATE EffectSafeForceScroll SET RemainTime = %lu WHERE OwnerID = '%s'", remainTurn, ownerID.c_str()); SAFE_DELETE(pStmt); } END_DB(pStmt) __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// string EffectSafeForceScroll::toString() const throw() { __BEGIN_TRY StringStream msg; msg << "EffectSafeForceScroll(" << "ObjectID:" << getObjectID() << ")"; return msg.toString(); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScrollLoader::load(Creature* pCreature ) throw(Error) { __BEGIN_TRY Assert(pCreature != NULL); Statement* pStmt = NULL; BEGIN_DB { pStmt = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement(); Result* pResult = pStmt->executeQuery("SELECt RemainTime FROM EffectSafeForceScroll WHERE OwnerID = '%s'", pCreature->getName().c_str()); if (pResult->next() ) { Turn_t remainTurn = pResult->getDWORD(1); Timeval currentTime; getCurrentTime(currentTime); EffectSafeForceScroll* pEffect = new EffectSafeForceScroll(pCreature); pEffect->setDeadline(remainTurn); pCreature->addEffect(pEffect); pCreature->setFlag(pEffect->getEffectClass()); } SAFE_DELETE(pStmt); } END_DB(pStmt) __END_CATCH } EffectSafeForceScrollLoader* g_pEffectSafeForceScrollLoader = NULL;
[ "tiancaiamao@gmail.com" ]
tiancaiamao@gmail.com
dfbc5722dabaf6fa7f5b8ecd59e2158c99fe1ec8
addbaa42a916bac9510d8f44f4ced3a6d324a4a3
/CODE_BASE/src/scene/character.h
3222a758ef348b5d7b78f7a153152b8dd2319d68
[]
no_license
iCodeIN/Game-Engine-Project
424725053c8002ada75bd018888359247d3f22a8
513773d8f5f52e36542021c5c5f52eaa365412b0
refs/heads/master
2023-03-20T11:31:14.438239
2019-06-29T21:22:22
2019-06-29T21:22:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
h
#pragma once #include "globals.h" #include "scene_object.h" #include "rig_solver.h" #include "bone.h" class Character : public SceneObject { RigSolver rig_solver_; std::vector<Bone*> bones_; std::shared_ptr<SceneObject> bone_obj_vis_; public: Character(); Character( const char* file_path, Filetype file_type, std::shared_ptr<ShaderProgram> using_program, const char* name, const glm::vec3& pos); Character( std::vector<shared_ptr<Drawable>>* body, std::shared_ptr<ShaderProgram> using_program, const char* name, const glm::vec3& pos); Character(const char* name, const glm::vec3& pos); ~Character(); void Jump(std::shared_ptr<Camera>& c); void Crouch(std::shared_ptr<Camera>& c); // temp void SetBones(std::vector<Bone*> bones); void SetBoneObjectVisual(std::shared_ptr<SceneObject> bone_obj_vis) { bone_obj_vis_ = bone_obj_vis; } void DrawBones(const glm::mat4& view_proj); virtual void Draw(const glm::mat4 view_proj); void HoldStaff(const glm::vec3& loc); };
[ "hanbollar@gmail.com" ]
hanbollar@gmail.com
9a43fb21618de67c2756653de7e5e3e4d00923a3
e99c20155e9b08c7e7598a3f85ccaedbd127f632
/ sjtu-project-pipe/thirdparties/VTK.Net/src/Filtering/vtkVertex.cxx
d7db4aac28986a09ce782f496a93a97724c1bdbb
[ "BSD-3-Clause" ]
permissive
unidevop/sjtu-project-pipe
38f00462d501d9b1134ce736bdfbfe4f9d075e4a
5a09f098db834d5276a2921d861ef549961decbe
refs/heads/master
2020-05-16T21:32:47.772410
2012-03-19T01:24:14
2012-03-19T01:24:14
38,281,086
1
1
null
null
null
null
UTF-8
C++
false
false
8,081
cxx
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkVertex.cxx,v $ 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. =========================================================================*/ #include "vtkVertex.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPointLocator.h" #include "vtkPoints.h" vtkCxxRevisionMacro(vtkVertex, "$Revision: 1.1 $"); vtkStandardNewMacro(vtkVertex); //---------------------------------------------------------------------------- // Construct the vertex with a single point. vtkVertex::vtkVertex() { this->Points->SetNumberOfPoints(1); this->PointIds->SetNumberOfIds(1); for (int i = 0; i < 1; i++) { this->Points->SetPoint(i, 0.0, 0.0, 0.0); this->PointIds->SetId(i,0); } } //---------------------------------------------------------------------------- // Make a new vtkVertex object with the same information as this object. int vtkVertex::EvaluatePosition(double x[3], double* closestPoint, int& subId, double pcoords[3], double& dist2, double *weights) { double X[3]; subId = 0; pcoords[1] = pcoords[2] = 0.0; this->Points->GetPoint(0, X); if (closestPoint) { closestPoint[0] = X[0]; closestPoint[1] = X[1]; closestPoint[2] = X[2]; } dist2 = vtkMath::Distance2BetweenPoints(X,x); weights[0] = 1.0; if (dist2 == 0.0) { pcoords[0] = 0.0; return 1; } else { pcoords[0] = -10.0; return 0; } } //---------------------------------------------------------------------------- void vtkVertex::EvaluateLocation(int& vtkNotUsed(subId), double vtkNotUsed(pcoords)[3], double x[3], double *weights) { this->Points->GetPoint(0, x); weights[0] = 1.0; } //---------------------------------------------------------------------------- // Given parametric coordinates of a point, return the closest cell boundary, // and whether the point is inside or outside of the cell. The cell boundary // is defined by a list of points (pts) that specify a vertex (1D cell). // If the return value of the method is != 0, then the point is inside the cell. int vtkVertex::CellBoundary(int vtkNotUsed(subId), double pcoords[3], vtkIdList *pts) { pts->SetNumberOfIds(1); pts->SetId(0,this->PointIds->GetId(0)); if ( pcoords[0] != 0.0 ) { return 0; } else { return 1; } } //---------------------------------------------------------------------------- // Generate contouring primitives. The scalar list cellScalars are // scalar values at each cell point. The point locator is essentially a // points list that merges points as they are inserted (i.e., prevents // duplicates). void vtkVertex::Contour(double value, vtkDataArray *cellScalars, vtkPointLocator *locator, vtkCellArray *verts, vtkCellArray *vtkNotUsed(lines), vtkCellArray *vtkNotUsed(polys), vtkPointData *inPd, vtkPointData *outPd, vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd) { if ( value == cellScalars->GetComponent(0,0) ) { int newCellId; vtkIdType pts[1]; pts[0] = locator->InsertNextPoint(this->Points->GetPoint(0)); if ( outPd ) { outPd->CopyData(inPd,this->PointIds->GetId(0),pts[0]); } newCellId = verts->InsertNextCell(1,pts); outCd->CopyData(inCd,cellId,newCellId); } } //---------------------------------------------------------------------------- // Intersect with a ray. Return parametric coordinates (both line and cell) // and global intersection coordinates, given ray definition and tolerance. // The method returns non-zero value if intersection occurs. int vtkVertex::IntersectWithLine(double p1[3], double p2[3], double tol, double& t, double x[3], double pcoords[3], int& subId) { int i; double X[3], ray[3], rayFactor, projXYZ[3]; subId = 0; pcoords[1] = pcoords[2] = 0.0; this->Points->GetPoint(0, X); for (i=0; i<3; i++) { ray[i] = p2[i] - p1[i]; } if (( rayFactor = vtkMath::Dot(ray,ray)) == 0.0 ) { return 0; } // // Project each point onto ray. Determine whether point is within tolerance. // t = (ray[0]*(X[0]-p1[0]) + ray[1]*(X[1]-p1[1]) + ray[2]*(X[2]-p1[2])) / rayFactor; if ( t >= 0.0 && t <= 1.0 ) { for (i=0; i<3; i++) { projXYZ[i] = p1[i] + t*ray[i]; if ( fabs(X[i]-projXYZ[i]) > tol ) { break; } } if ( i > 2 ) // within tolerance { pcoords[0] = 0.0; x[0] = X[0]; x[1] = X[1]; x[2] = X[2]; return 1; } } pcoords[0] = -10.0; return 0; } //---------------------------------------------------------------------------- // Triangulate the vertex. This method fills pts and ptIds with information // from the only point in the vertex. int vtkVertex::Triangulate(int vtkNotUsed(index),vtkIdList *ptIds, vtkPoints *pts) { pts->Reset(); ptIds->Reset(); pts->InsertPoint(0,this->Points->GetPoint(0)); ptIds->InsertId(0,this->PointIds->GetId(0)); return 1; } //---------------------------------------------------------------------------- // Get the derivative of the vertex. Returns (0.0, 0.0, 0.0) for all // dimensions. void vtkVertex::Derivatives(int vtkNotUsed(subId), double vtkNotUsed(pcoords)[3], double *vtkNotUsed(values), int dim, double *derivs) { int i, idx; for (i=0; i<dim; i++) { idx = i*dim; derivs[idx] = 0.0; derivs[idx+1] = 0.0; derivs[idx+2] = 0.0; } } //---------------------------------------------------------------------------- void vtkVertex::Clip(double value, vtkDataArray *cellScalars, vtkPointLocator *locator, vtkCellArray *verts, vtkPointData *inPd, vtkPointData *outPd, vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd, int insideOut) { double s, x[3]; int newCellId; vtkIdType pts[1]; s = cellScalars->GetComponent(0,0); if ( ( !insideOut && s > value) || (insideOut && s <= value) ) { this->Points->GetPoint(0, x); if ( locator->InsertUniquePoint(x, pts[0]) ) { outPd->CopyData(inPd,this->PointIds->GetId(0),pts[0]); } newCellId = verts->InsertNextCell(1,pts); outCd->CopyData(inCd,cellId,newCellId); } } //---------------------------------------------------------------------------- // Compute interpolation functions // void vtkVertex::InterpolationFunctions(double vtkNotUsed(pcoords)[3], double weights[1]) { weights[0] = 1.0; } //---------------------------------------------------------------------------- static double vtkVertexCellPCoords[3] = {0.0,0.0,0.0}; double *vtkVertex::GetParametricCoords() { return vtkVertexCellPCoords; } //---------------------------------------------------------------------------- void vtkVertex::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
[ "useminmin@gmail.com" ]
useminmin@gmail.com
632808b5e6ab290f0c5bcb8079bb4d9ee5b5b920
841776845974ba2645eff58ff8fabedd873093f0
/LeetCode/1013将数组分成和相等的三个部分.cpp
76a7c174c30076dcece23eed9d20b7026294c525
[]
no_license
hello-sources/Coding-Training
f2652c9b8e58d244a172922e56897fa2a3ad52fb
d885ca23676cb712243640169cf2e5bef2d8c70e
refs/heads/master
2023-01-19T11:17:36.097846
2023-01-01T00:49:09
2023-01-01T00:49:09
246,630,755
4
0
null
null
null
null
UTF-8
C++
false
false
496
cpp
bool canThreePartsEqualSum(int* arr, int arrSize){ int sum = 0, num = 0; for (int i = 0; i < arrSize; i++) sum += arr[i]; if (sum % 3 != 0) return false; num = sum / 3; int temp = 0, temp2 = 0; for (int i = 0; i < arrSize - 2; i++) { temp += arr[i]; if (temp == num) { for (int j = i + 1; j < arrSize - 1; j++) { temp2 += arr[j]; if (temp2 == temp) return true; } } } return false; }
[ "3245849061@qq.com" ]
3245849061@qq.com
ee7e8bdd3deeada4ec2bfbff8b62d93713e3b169
cb417c58658ac99e26fda8c79d2737de4b8688f9
/tagkeyedit.cpp
8d6c81f3309b602bc424f8ade6be35b338846d39
[]
no_license
SinixCosix/Mosaic
b2760da7ac161f91b4d61482b4560abc53273a78
262d3fc4390a6b60084af577085acb32dbf589c3
refs/heads/master
2022-09-16T19:15:19.203715
2020-05-28T12:46:32
2020-05-28T12:46:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,332
cpp
#include "tagkeyeditlist.h" TagKeyEdit::TagKeyEdit(QWidget *parent) : TagBaseWidget(parent) { this->exif_name = new QComboBox(); setExifName(); connect(exif_name, &QComboBox::currentTextChanged, this, &TagKeyEdit::checkValid); layout->addWidget(short_name_lineEdit); layout->addWidget(exif_name); layout->addWidget(remove_btn); setLayout(layout); setData(); } void TagKeyEdit::setExifName() { exif_name->addItems(extra.getExtra()); exif_name->setEditable(true); QCompleter *c = new QCompleter(extra.getExtra(), exif_name); c->setCaseSensitivity(Qt::CaseInsensitive); exif_name->setCompleter(c); } void TagKeyEdit::setExifName(const QString &cur_text) { setExifName(); exif_name->setCurrentIndex(exif_name->findText(cur_text)); } void TagKeyEdit::setData() { setShortName(); setExifName(); } void TagKeyEdit::setData(QPair<QString, QString> data) { setShortName(data.first); setExifName(data.second); } QPair<QString, QString> TagKeyEdit::getData() { QPair<QString, QString> pair(short_name_lineEdit->text(), exif_name->currentText()); return pair; } bool TagKeyEdit::isValid() { return !(short_name_lineEdit->text().isEmpty() or exif_name->currentText().isEmpty() or exif_name->findText(exif_name->currentText()) == -1); }
[ "rainbowshardofdeath@gmail.com" ]
rainbowshardofdeath@gmail.com
af31f561da07cd75baf90f7c1b00cb3d414704e3
27c75711bbe10b3120c158971bb4e830af0c33e8
/AsZ/2015.09.13/9.cpp
d6c902df0aa6d311d29b73f478ef55a2a5f2d12b
[]
no_license
yl3i/ACM
9d2f7a6f3faff905eb2ed6854c2dbf040a002372
29bb023cb13489bda7626f8105756ef64f89674f
refs/heads/master
2021-05-22T02:00:56.486698
2020-04-04T05:45:10
2020-04-04T05:45:10
252,918,033
0
0
null
2020-04-04T05:36:11
2020-04-04T05:36:11
null
UTF-8
C++
false
false
2,243
cpp
#include <bits/stdc++.h> #define N 50500 #define INF 0x3f3f3f3f using namespace std; int dp[N], p; void calc(int v, int c, int s) { int upper = min(p + 100 - v, s); for (int i = upper; i >= 0; i--) dp[i + v] = min(dp[i + v], dp[i] + c); } void calc1(int v, int c, int s) { int upper = min(p - v, s); // cout << v << " " << c << " " << s << endl; // cout << upper << endl; for (int i = upper; i >= 0; i--) { if (dp[i] == -1) continue; dp[i + v] = max(dp[i + v], dp[i] + c); } } int main() { //freopen("9.in", "r", stdin); int ttt; scanf("%d", &ttt); while (ttt--) { int n, m; scanf("%d %d %d", &n, &m, &p); for (int i = 0; i <= p + 200; i++) dp[i] = INF; dp[0] = 0; int sum = 0; for (int i = 0; i < n; i++) { int x, y, z; scanf("%d %d %d", &x, &y, &z); for (int k = 1; k <= z; k <<= 1) { calc(x * k, y * k, sum); z -= k, sum += k * x; } if (z) { calc(x * z, y * z, sum); sum += z * x; } } // cout << endl; int minspace = INF; for (int i = p; i <= p + 100; i++) minspace = min(minspace, dp[i]); p = 50000, sum = 0; for (int i = 0; i <= p; i++) dp[i] = -1; dp[0] = 0; for (int i = 0; i < m; i++) { int x, y, z; scanf("%d %d %d", &x, &y, &z); for (int k = 1; k <= z; k <<= 1) { calc1(y * k, x * k, sum); z -= k, sum += k * y; } if (z) { calc1(y * z, x * z, sum); sum += z * y; } } // for (int i = 0; i <= 20; i++) // printf("%d%c", dp[i], " \n"[i == 20]); bool flag = false; for (int i = 0; i <= p; i++) if (dp[i] >= minspace) { printf("%d\n", i); flag = true; break; } if (!flag) printf("TAT\n"); } return 0; }
[ "yuzhou627@gmail.com" ]
yuzhou627@gmail.com
05579139d95851e549675beacd8901baae6df3a1
f6439b5ed1614fd8db05fa963b47765eae225eb5
/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc
ffbad82ed9b9291cc6c91839f17155209f792126
[ "BSD-3-Clause" ]
permissive
aranajhonny/chromium
b8a3c975211e1ea2f15b83647b4d8eb45252f1be
caf5bcb822f79b8997720e589334266551a50a13
refs/heads/master
2021-05-11T00:20:34.020261
2018-01-21T03:31:45
2018-01-21T03:31:45
118,301,142
2
0
null
null
null
null
UTF-8
C++
false
false
22,211
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <list> #include <set> #include "base/files/scoped_temp_dir.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_browser_main.h" #include "chrome/browser/chrome_browser_main_extra_parts.h" #include "chrome/browser/chrome_content_browser_client.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/download/download_browsertest.h" #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/extensions/api/web_navigation/web_navigation_api.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/resource_controller.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/resource_throttle.h" #include "content/public/browser/web_contents.h" #include "content/public/common/context_menu_params.h" #include "content/public/common/resource_type.h" #include "content/public/common/url_constants.h" #include "content/public/test/browser_test_utils.h" #include "extensions/browser/extension_system.h" #include "extensions/common/switches.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "third_party/WebKit/public/web/WebContextMenuData.h" #include "third_party/WebKit/public/web/WebInputEvent.h" using content::ResourceType; using content::WebContents; namespace extensions { namespace { // This class can defer requests for arbitrary URLs. class TestNavigationListener : public base::RefCountedThreadSafe<TestNavigationListener> { public: TestNavigationListener() {} // Add |url| to the set of URLs we should delay. void DelayRequestsForURL(const GURL& url) { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)) { content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind(&TestNavigationListener::DelayRequestsForURL, this, url)); return; } urls_to_delay_.insert(url); } // Resume all deferred requests. void ResumeAll() { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)) { content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind(&TestNavigationListener::ResumeAll, this)); return; } WeakThrottleList::const_iterator it; for (it = throttles_.begin(); it != throttles_.end(); ++it) { if (it->get()) (*it)->Resume(); } throttles_.clear(); } // Constructs a ResourceThrottle if the request for |url| should be held. // // Needs to be invoked on the IO thread. content::ResourceThrottle* CreateResourceThrottle( const GURL& url, ResourceType::Type resource_type) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (urls_to_delay_.find(url) == urls_to_delay_.end()) return NULL; Throttle* throttle = new Throttle(); throttles_.push_back(throttle->AsWeakPtr()); return throttle; } private: friend class base::RefCountedThreadSafe<TestNavigationListener>; virtual ~TestNavigationListener() {} // Stores a throttle per URL request that we have delayed. class Throttle : public content::ResourceThrottle, public base::SupportsWeakPtr<Throttle> { public: void Resume() { controller()->Resume(); } // content::ResourceThrottle implementation. virtual void WillStartRequest(bool* defer) OVERRIDE { *defer = true; } virtual const char* GetNameForLogging() const OVERRIDE { return "TestNavigationListener::Throttle"; } }; typedef base::WeakPtr<Throttle> WeakThrottle; typedef std::list<WeakThrottle> WeakThrottleList; WeakThrottleList throttles_; // The set of URLs to be delayed. std::set<GURL> urls_to_delay_; DISALLOW_COPY_AND_ASSIGN(TestNavigationListener); }; // Waits for a WC to be created. Once it starts loading |delay_url| (after at // least the first navigation has committed), it delays the load, executes // |script| in the last committed RVH and resumes the load when a URL ending in // |until_url_suffix| commits. This class expects |script| to trigger the load // of an URL ending in |until_url_suffix|. class DelayLoadStartAndExecuteJavascript : public content::NotificationObserver, public content::WebContentsObserver { public: DelayLoadStartAndExecuteJavascript( TestNavigationListener* test_navigation_listener, const GURL& delay_url, const std::string& script, const std::string& until_url_suffix) : content::WebContentsObserver(), test_navigation_listener_(test_navigation_listener), delay_url_(delay_url), until_url_suffix_(until_url_suffix), script_(script), script_was_executed_(false), rvh_(NULL) { registrar_.Add(this, chrome::NOTIFICATION_TAB_ADDED, content::NotificationService::AllSources()); test_navigation_listener_->DelayRequestsForURL(delay_url_); } virtual ~DelayLoadStartAndExecuteJavascript() {} virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE { if (type != chrome::NOTIFICATION_TAB_ADDED) { NOTREACHED(); return; } content::WebContentsObserver::Observe( content::Details<content::WebContents>(details).ptr()); registrar_.RemoveAll(); } virtual void DidStartProvisionalLoadForFrame( content::RenderFrameHost* render_frame_host, const GURL& validated_url, bool is_error_page, bool is_iframe_srcdoc) OVERRIDE { if (validated_url != delay_url_ || !rvh_) return; rvh_->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16(script_)); script_was_executed_ = true; } virtual void DidCommitProvisionalLoadForFrame( content::RenderFrameHost* render_frame_host, const GURL& url, content::PageTransition transition_type) OVERRIDE { if (script_was_executed_ && EndsWith(url.spec(), until_url_suffix_, true)) { content::WebContentsObserver::Observe(NULL); test_navigation_listener_->ResumeAll(); } rvh_ = render_frame_host->GetRenderViewHost(); } private: content::NotificationRegistrar registrar_; scoped_refptr<TestNavigationListener> test_navigation_listener_; GURL delay_url_; std::string until_url_suffix_; std::string script_; bool script_was_executed_; content::RenderViewHost* rvh_; DISALLOW_COPY_AND_ASSIGN(DelayLoadStartAndExecuteJavascript); }; // A ResourceDispatcherHostDelegate that adds a TestNavigationObserver. class TestResourceDispatcherHostDelegate : public ChromeResourceDispatcherHostDelegate { public: TestResourceDispatcherHostDelegate( prerender::PrerenderTracker* prerender_tracker, TestNavigationListener* test_navigation_listener) : ChromeResourceDispatcherHostDelegate(prerender_tracker), test_navigation_listener_(test_navigation_listener) { } virtual ~TestResourceDispatcherHostDelegate() {} virtual void RequestBeginning( net::URLRequest* request, content::ResourceContext* resource_context, content::AppCacheService* appcache_service, ResourceType::Type resource_type, int child_id, int route_id, ScopedVector<content::ResourceThrottle>* throttles) OVERRIDE { ChromeResourceDispatcherHostDelegate::RequestBeginning( request, resource_context, appcache_service, resource_type, child_id, route_id, throttles); content::ResourceThrottle* throttle = test_navigation_listener_->CreateResourceThrottle(request->url(), resource_type); if (throttle) throttles->push_back(throttle); } private: scoped_refptr<TestNavigationListener> test_navigation_listener_; DISALLOW_COPY_AND_ASSIGN(TestResourceDispatcherHostDelegate); }; } // namespace class WebNavigationApiTest : public ExtensionApiTest { public: WebNavigationApiTest() {} virtual ~WebNavigationApiTest() {} virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); FrameNavigationState::set_allow_extension_scheme(true); CommandLine::ForCurrentProcess()->AppendSwitch( switches::kAllowLegacyExtensionManifests); host_resolver()->AddRule("*", "127.0.0.1"); } virtual void SetUpOnMainThread() OVERRIDE { ExtensionApiTest::SetUpOnMainThread(); test_navigation_listener_ = new TestNavigationListener(); resource_dispatcher_host_delegate_.reset( new TestResourceDispatcherHostDelegate( g_browser_process->prerender_tracker(), test_navigation_listener_.get())); content::ResourceDispatcherHost::Get()->SetDelegate( resource_dispatcher_host_delegate_.get()); } TestNavigationListener* test_navigation_listener() { return test_navigation_listener_.get(); } private: scoped_refptr<TestNavigationListener> test_navigation_listener_; scoped_ptr<TestResourceDispatcherHostDelegate> resource_dispatcher_host_delegate_; DISALLOW_COPY_AND_ASSIGN(WebNavigationApiTest); }; IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, Api) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, GetFrame) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/getFrame")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ClientRedirect) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/clientRedirect")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ServerRedirect) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/serverRedirect")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, Download) { base::ScopedTempDir download_directory; ASSERT_TRUE(download_directory.CreateUniqueTempDir()); DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(browser()->profile()); download_prefs->SetDownloadPath(download_directory.path()); DownloadTestObserverNotInProgress download_observer( content::BrowserContext::GetDownloadManager(profile()), 1); download_observer.StartObserving(); ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/download")) << message_; download_observer.WaitForFinished(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ServerRedirectSingleProcess) { ASSERT_TRUE(StartEmbeddedTestServer()); // Set max renderers to 1 to force running out of processes. content::RenderProcessHost::SetMaxRendererProcessCount(1); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE( RunExtensionTest("webnavigation/serverRedirectSingleProcess")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::WaitForLoadStop(tab); ResultCatcher catcher; GURL url(base::StringPrintf( "http://www.a.com:%d/" "extensions/api_test/webnavigation/serverRedirectSingleProcess/a.html", embedded_test_server()->port())); ui_test_utils::NavigateToURL(browser(), url); url = GURL(base::StringPrintf( "http://www.b.com:%d/server-redirect?http://www.b.com:%d/", embedded_test_server()->port(), embedded_test_server()->port())); ui_test_utils::NavigateToURL(browser(), url); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ForwardBack) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/forwardBack")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, IFrame) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/iframe")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, SrcDoc) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/srcdoc")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, OpenTab) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/openTab")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ReferenceFragment) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/referenceFragment")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, SimpleLoad) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/simpleLoad")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, Failures) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/failures")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, FilteredTest) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/filtered")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, UserAction) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionTest("webnavigation/userAction")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::WaitForLoadStop(tab); ResultCatcher catcher; ExtensionService* service = extensions::ExtensionSystem::Get( browser()->profile())->extension_service(); const extensions::Extension* extension = service->GetExtensionById(last_loaded_extension_id(), false); GURL url = extension->GetResourceURL("a.html"); ui_test_utils::NavigateToURL(browser(), url); // This corresponds to "Open link in new tab". content::ContextMenuParams params; params.is_editable = false; params.media_type = blink::WebContextMenuData::MediaTypeNone; params.page_url = url; params.link_url = extension->GetResourceURL("b.html"); TestRenderViewContextMenu menu(tab->GetMainFrame(), params); menu.Init(); menu.ExecuteCommand(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB, 0); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, RequestOpenTab) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionTest("webnavigation/requestOpenTab")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::WaitForLoadStop(tab); ResultCatcher catcher; ExtensionService* service = extensions::ExtensionSystem::Get( browser()->profile())->extension_service(); const extensions::Extension* extension = service->GetExtensionById(last_loaded_extension_id(), false); GURL url = extension->GetResourceURL("a.html"); ui_test_utils::NavigateToURL(browser(), url); // There's a link on a.html. Middle-click on it to open it in a new tab. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; mouse_event.button = blink::WebMouseEvent::ButtonMiddle; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); mouse_event.type = blink::WebInputEvent::MouseUp; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, TargetBlank) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionTest("webnavigation/targetBlank")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::WaitForLoadStop(tab); ResultCatcher catcher; GURL url = embedded_test_server()->GetURL( "/extensions/api_test/webnavigation/targetBlank/a.html"); chrome::NavigateParams params(browser(), url, content::PAGE_TRANSITION_LINK); ui_test_utils::NavigateToURL(&params); // There's a link with target=_blank on a.html. Click on it to open it in a // new tab. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; mouse_event.button = blink::WebMouseEvent::ButtonLeft; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); mouse_event.type = blink::WebInputEvent::MouseUp; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, TargetBlankIncognito) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionTestIncognito("webnavigation/targetBlank")) << message_; ResultCatcher catcher; GURL url = embedded_test_server()->GetURL( "/extensions/api_test/webnavigation/targetBlank/a.html"); Browser* otr_browser = ui_test_utils::OpenURLOffTheRecord( browser()->profile(), url); WebContents* tab = otr_browser->tab_strip_model()->GetActiveWebContents(); // There's a link with target=_blank on a.html. Click on it to open it in a // new tab. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; mouse_event.button = blink::WebMouseEvent::ButtonLeft; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); mouse_event.type = blink::WebInputEvent::MouseUp; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, History) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/history")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcess) { ASSERT_TRUE(StartEmbeddedTestServer()); LoadExtension(test_data_dir_.AppendASCII("webnavigation").AppendASCII("app")); // See crossProcess/d.html. DelayLoadStartAndExecuteJavascript call_script( test_navigation_listener(), embedded_test_server()->GetURL("/test1"), "navigate2()", "empty.html"); ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcess")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcessFragment) { ASSERT_TRUE(StartEmbeddedTestServer()); // See crossProcessFragment/f.html. DelayLoadStartAndExecuteJavascript call_script3( test_navigation_listener(), embedded_test_server()->GetURL("/test3"), "updateFragment()", base::StringPrintf("f.html?%d#foo", embedded_test_server()->port())); // See crossProcessFragment/g.html. DelayLoadStartAndExecuteJavascript call_script4( test_navigation_listener(), embedded_test_server()->GetURL("/test4"), "updateFragment()", base::StringPrintf("g.html?%d#foo", embedded_test_server()->port())); ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcessFragment")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcessHistory) { ASSERT_TRUE(StartEmbeddedTestServer()); // See crossProcessHistory/e.html. DelayLoadStartAndExecuteJavascript call_script2( test_navigation_listener(), embedded_test_server()->GetURL("/test2"), "updateHistory()", "empty.html"); // See crossProcessHistory/h.html. DelayLoadStartAndExecuteJavascript call_script5( test_navigation_listener(), embedded_test_server()->GetURL("/test5"), "updateHistory()", "empty.html"); // See crossProcessHistory/i.html. DelayLoadStartAndExecuteJavascript call_script6( test_navigation_listener(), embedded_test_server()->GetURL("/test6"), "updateHistory()", "empty.html"); ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcessHistory")) << message_; } // TODO(jam): http://crbug.com/350550 #if !(defined(OS_CHROMEOS) && defined(ADDRESS_SANITIZER)) IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, Crash) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionTest("webnavigation/crash")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::WaitForLoadStop(tab); ResultCatcher catcher; GURL url(base::StringPrintf( "http://www.a.com:%d/" "extensions/api_test/webnavigation/crash/a.html", embedded_test_server()->port())); ui_test_utils::NavigateToURL(browser(), url); ui_test_utils::NavigateToURL(browser(), GURL(content::kChromeUICrashURL)); url = GURL(base::StringPrintf( "http://www.a.com:%d/" "extensions/api_test/webnavigation/crash/b.html", embedded_test_server()->port())); ui_test_utils::NavigateToURL(browser(), url); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } #endif } // namespace extensions
[ "jhonnyjosearana@gmail.com" ]
jhonnyjosearana@gmail.com
ed42ea7e82dfcce3c03f16adfc8be0e68f21e8b0
f2a10941c41312b228b74a935013a27ef13c2838
/z3D/Core/SMem.cpp
99a393872e4b1afe2904e93c7338f1e7356b5d62
[]
no_license
vinceplusplus/z3D
375df45283c9ed64f5d2e991e2361352151ca030
7b52534db183298b7c92ff8cf6493fce0ac6e0d9
refs/heads/master
2020-12-24T19:13:21.574789
2016-05-05T17:04:17
2016-05-05T17:04:17
58,145,312
6
0
null
null
null
null
UTF-8
C++
false
false
1,418
cpp
#include "SMem.h" #include "interlocked.h" namespace z3D { namespace Core { void SMem::___ctor() { _block = 0; _size = 0; } void SMem::___ctor(const SMem& rhs) { if(!rhs._block) { ___ctor(); return; } _block = rhs._block; _size = rhs._size; _dealloc_func = rhs._dealloc_func; interlocked::increment(&_block->ref_count); } void SMem::___dtor() { if(!_block) return; if(interlocked::decrement(&_block->ref_count) != 0) return; if(_dealloc_func.valid()) _dealloc_func(_block); } SMem::SMem() { ___ctor(); } SMem::SMem(const SMem& rhs) { ___ctor(rhs); } SMem::~SMem() { ___dtor(); } SMem& SMem::operator=(const SMem& rhs) { if(this == &rhs) return *this; ___dtor(); ___ctor(rhs); return *this; } size_t SMem::getRequiredSize(size_t data_size) { return sizeof(BLOCK) - 1 + data_size; } SMem SMem::create(void* required_mem, size_t data_size, const functor1<void, void*>& dealloc_func) { SMem sm; sm._block = (BLOCK*)required_mem; sm._size = data_size; sm._dealloc_func = dealloc_func; interlocked::exchange(&sm._block->ref_count, 1); return sm; } void* SMem::get() const { return _block->data; } size_t SMem::size() const { return _size; } void SMem::reset() { ___dtor(); ___ctor(); } }; };
[ "vinceplusplus@gmail.com" ]
vinceplusplus@gmail.com
bcd183501c27515766d16f978f48dc5ec272b1f2
de5bbebd0b6c83f76bd65fc8984c5bb2154d8446
/2020-2021/previous/simplemetaheuristics/simannealing.cpp
479fa3b6d51b87b741c9a5d8f54922cab79fae0b
[ "MIT" ]
permissive
pantadeusz/examples-ai
5760f812de6112c2d66924160b35eef89b823300
7529242eb47123dd948d13eb44c5a28d225d11b9
refs/heads/master
2023-01-24T03:02:28.022307
2023-01-18T11:36:34
2023-01-18T11:36:34
90,629,458
3
2
null
null
null
null
UTF-8
C++
false
false
5,857
cpp
/* * Copyright 2017 Tadeusz Puźniakowski * * 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. * * */ // g++ -std=c++11 simannealing.cpp -o simannealing #include <tuple> #include <iostream> #include <cstdlib> #include <cmath> #include <functional> #include <vector> #include <list> #include <random> #include <chrono> using namespace std; /* The simulated annealing algorithm */ vector < double > simulatedAnnealing(const vector< double > solution0, function < bool (const vector<double>&) > inDomain, function < double (const vector<double>&) > goalF, function < bool (const vector<double>&) > termCondition, function < double ( int ) > T = [](const double k){return pow(0.99999,(double)k);}, bool maximize = false, unsigned generatorSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count() ); //////////////////////////////////////////////////////////////////////// // // The main function testing the execution of optimization // //////////////////////////////////////////////////////////////////////// int main () { // random start point default_random_engine generator(chrono::high_resolution_clock::now().time_since_epoch().count()); uniform_real_distribution<double> rdist(-5, 5); vector< double > solution = {rdist(generator), rdist(generator)}; // start point // check if value is in function domain vector< double > minV = {-5,-5}, maxV = {5,5}; auto functionDomain = [&](const vector < double > & v){ for (int i = 0; i < v.size(); i++) { if((v[i] <= minV[i]) || (v[i] >= maxV[i])) {return false;} } return true; }; // function -- Ackley - minimization auto f = [](const vector<double > &solution) -> double { double x,y; tie(x,y) = pair<double, double>(solution[0], solution[1]); return (-20*exp(-0.2*sqrt(0.5*(x*x+y*y)))- exp(0.5*(cos(2.0*M_PI*x)+cos(2*M_PI*y))) + M_E + 20); }; int i = 0; solution = simulatedAnnealing(solution, functionDomain, f, [&](const vector < double > &){i++;if (i > 100000) return true; return false;}, [](const double k){return pow(0.99999,(double)k);} ); cout << "Solution ( " << f(solution) << " ): " << solution[0] << " , " << solution[1] << endl; return 0; } /* The simulated annealing */ vector < double > simulatedAnnealing( const vector< double > solution0, // initial solution function < bool (const vector<double>&) > inDomain, // solution domain check function < double (const vector<double>&) > goalF, // goal function (for minimization) function < bool (const vector<double>&) > termCondition, // termination condition function < double ( int ) > T, // temperature function bool maximize, // maximize or minimize unsigned generatorSeed // random number generator seed ) { std::default_random_engine generator(generatorSeed); std::normal_distribution<double> rdist(0.0,0.01); // distribution for neighbour finding // std::uniform_real_distribution<double> rdist(-0.01, 0.01); list < vector< double > > solution = { solution0 }; // classic approach - store every result in container std::uniform_real_distribution<double> zerooneprob(0, 1); int i = 0; while (!termCondition(solution.back())) { auto solutionCandidate = solution.back(); for (auto &e: solutionCandidate) { e = e+rdist(generator); // new solution based on the previous solution } if(inDomain(solutionCandidate)) { auto y = goalF(solution.back()); // current solution quality (previous) auto yp = goalF(solutionCandidate); // new solution quality if (((y > yp) && !maximize) || (((y < yp) && maximize))) { // better solution solution.push_back(solutionCandidate); } else { auto e = exp(-(fabs(yp-y)/T(i))); if ( zerooneprob(generator) < e ) { // not that good, but temperature allows us to accept solution.push_back(solutionCandidate); } } } i++; } auto best = solution.back(); for (auto e : solution) { auto y = goalF(best); // current solution quality (previous) auto yp = goalF(e); // new solution quality if (((y > yp) && !maximize) || (((y < yp) && maximize))) best = e; } return best; }
[ "pantadeusz@pjwstk.edu.pl" ]
pantadeusz@pjwstk.edu.pl
aef02a58526ea95bd463729fb57b43bb6fa07392
988e7ad6574222ca77e8620b9fbe15e1b0cc9a1a
/rain_water_harvesting.cpp
330ff7235fbd962be309b7a35ce7361d649d41f6
[]
no_license
vaarigupta/C-_programs
361df5af8ebb9eb36f79a24189e4ff0be3934bd6
ae5d5c6f3b147b16c5dbdbc449de2c6fbb8a5dac
refs/heads/master
2020-03-12T20:36:20.483047
2018-04-26T08:36:29
2018-04-26T08:36:29
130,809,479
0
0
null
null
null
null
UTF-8
C++
false
false
967
cpp
#include<iostream> using namespace std; int main() { int n, height[20]={0}, k=1,j=n-1,left_ht[20]={0},right_ht[20] ={0}, current_height, sum=0; cin>>n; for(int i=0;i<n;i++) { cin>>height[i]; } current_height = height[0]; for(int i=0;i<n;i++) { left_ht[0]=height[0]; if(height[i]>current_height&&i!=0) { current_height =height[i]; } left_ht[k]=current_height; k++; } for(int i=0;i<n;i++) { cout<<left_ht[i]<<endl;; } current_height =height[n-1]; for(int i=n-1;i>=0;i--) { right_ht[n-1]=height[n-1]; if(height[i]>current_height&&i!=(n-1)) { current_height =height[i]; } right_ht[j]= current_height; j--; } cout<<endl; for(int i=0;i<n;i++) { cout<<right_ht[i]<<endl;; } for(int i=0;i<n;i++) { sum += min(left_ht[i],right_ht[i]) - height[i]; } cout<<sum; return 0; }
[ "cutievaarigupta@gmail.com" ]
cutievaarigupta@gmail.com
403ba5c0f91869137a88307dae5ed91ddeffb04b
1321b27ee8b6f757d23c0d538257ce648c1d7c03
/src/bitcoinrpc.cpp
4be193d98b9916bb7e7e25c4e5d2036f7aed0de0
[ "MIT" ]
permissive
peter600/ParkByte
1a9348f1cc15b445c66af11ea26bedf0dda4187c
b7fcc7e7d92d6bf8638e98b48182240704077490
refs/heads/master
2020-05-29T11:07:11.986054
2015-05-06T23:46:00
2015-05-06T23:46:00
35,618,241
1
0
null
2015-05-14T15:12:55
2015-05-14T15:12:55
null
UTF-8
C++
false
false
48,057
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "util.h" #include "sync.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #include "db.h" #undef printf #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> #define printf OutputDebugStringF using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; void ThreadRPCServer2(void* parg); static std::string strRPCUserColonPass; const Object emptyobj; void ThreadRPCServer3(void* parg); static inline unsigned short GetDefaultRPCPort() { return GetBoolArg("-testnet", false) ? 59061 : 59060; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str())); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } int64_t AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > MAX_MONEY) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); int64_t nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64_t amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } // // Utilities: convert hex-encoded Values // (throws error if not hex). // uint256 ParseHashV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) // Note: IsHex("") is false throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); uint256 result; result.SetHex(strHex); return result; } uint256 ParseHashO(const Object& o, string strKey) { return ParseHashV(find_value(o, strKey), strKey); } vector<unsigned char> ParseHexV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); return ParseHex(strHex); } vector<unsigned char> ParseHexO(const Object& o, string strKey) { return ParseHexV(find_value(o, strKey), strKey); } /// /// Note: This interface may still be subject to change. /// string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "stop <detach>\n" "<detach> is true or false to detach the database or not for this stop only\n" "Stop ParkByte server (and possibly override the detachdb config value)."); // Shutdown will take long enough that the response should get back if (params.size() > 0) bitdb.SetDetach(params[0].get_bool()); StartShutdown(); return "ParkByte server stopping"; } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name function safemd unlocked // ------------------------ ----------------------- ------ -------- { "help", &help, true, true }, { "stop", &stop, true, true }, { "getbestblockhash", &getbestblockhash, true, false }, { "getblockcount", &getblockcount, true, false }, { "getconnectioncount", &getconnectioncount, true, false }, { "getpeerinfo", &getpeerinfo, true, false }, { "getdifficulty", &getdifficulty, true, false }, { "getinfo", &getinfo, true, false }, { "getsubsidy", &getsubsidy, true, false }, { "getmininginfo", &getmininginfo, true, false }, { "getstakinginfo", &getstakinginfo, true, false }, { "getnewaddress", &getnewaddress, true, false }, { "getnewpubkey", &getnewpubkey, true, false }, { "getaccountaddress", &getaccountaddress, true, false }, { "setaccount", &setaccount, true, false }, { "getaccount", &getaccount, false, false }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false }, { "sendtoaddress", &sendtoaddress, false, false }, { "getreceivedbyaddress", &getreceivedbyaddress, false, false }, { "getreceivedbyaccount", &getreceivedbyaccount, false, false }, { "listreceivedbyaddress", &listreceivedbyaddress, false, false }, { "listreceivedbyaccount", &listreceivedbyaccount, false, false }, { "backupwallet", &backupwallet, true, false }, { "keypoolrefill", &keypoolrefill, true, false }, { "walletpassphrase", &walletpassphrase, true, false }, { "walletpassphrasechange", &walletpassphrasechange, false, false }, { "walletlock", &walletlock, true, false }, { "encryptwallet", &encryptwallet, false, false }, { "validateaddress", &validateaddress, true, false }, { "validatepubkey", &validatepubkey, true, false }, { "getbalance", &getbalance, false, false }, { "move", &movecmd, false, false }, { "sendfrom", &sendfrom, false, false }, { "sendmany", &sendmany, false, false }, { "addmultisigaddress", &addmultisigaddress, false, false }, { "addredeemscript", &addredeemscript, false, false }, { "getrawmempool", &getrawmempool, true, false }, { "getblock", &getblock, false, false }, { "getblockbynumber", &getblockbynumber, false, false }, { "getblockhash", &getblockhash, false, false }, { "gettransaction", &gettransaction, false, false }, { "listtransactions", &listtransactions, false, false }, { "listaddressgroupings", &listaddressgroupings, false, false }, { "signmessage", &signmessage, false, false }, { "verifymessage", &verifymessage, false, false }, { "getwork", &getwork, true, false }, { "getworkex", &getworkex, true, false }, { "listaccounts", &listaccounts, false, false }, { "settxfee", &settxfee, false, false }, { "getblocktemplate", &getblocktemplate, true, false }, { "submitblock", &submitblock, false, false }, { "listsinceblock", &listsinceblock, false, false }, { "dumpprivkey", &dumpprivkey, false, false }, { "dumpwallet", &dumpwallet, true, false }, { "importwallet", &importwallet, false, false }, { "importprivkey", &importprivkey, false, false }, { "listunspent", &listunspent, false, false }, { "getrawtransaction", &getrawtransaction, false, false }, { "createrawtransaction", &createrawtransaction, false, false }, { "decoderawtransaction", &decoderawtransaction, false, false }, { "decodescript", &decodescript, false, false }, { "signrawtransaction", &signrawtransaction, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false }, { "getcheckpoint", &getcheckpoint, true, false }, { "reservebalance", &reservebalance, false, true}, { "checkwallet", &checkwallet, false, true}, { "repairwallet", &repairwallet, false, true}, { "resendtx", &resendtx, false, true}, { "makekeypair", &makekeypair, false, true}, { "sendalert", &sendalert, false, false}, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: ParkByte-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: ParkByte-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == HTTP_OK) cStatus = "OK"; else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request"; else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden"; else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found"; else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %"PRIszu"\r\n" "Content-Type: application/json\r\n" "Server: ParkByte-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; while (true) { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet) { mapHeadersRet.clear(); strMessageRet = ""; // Read status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Read header int nLen = ReadHTTPHeader(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return nStatus; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } // // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ThreadRPCServer(void* parg) { // Make this thread recognisable as the RPC listener RenameThread("ParkByte-rpclist"); try { vnThreadsRunning[THREAD_RPCLISTENER]++; ThreadRPCServer2(parg); vnThreadsRunning[THREAD_RPCLISTENER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(&e, "ThreadRPCServer()"); } catch (...) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(NULL, "ThreadRPCServer()"); } printf("ThreadRPCServer exited\n"); } // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { vnThreadsRunning[THREAD_RPCLISTENER]++; // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush; delete conn; } // start HTTP client thread else if (!NewThread(ThreadRPCServer3, conn)) { printf("Failed to create RPC server client thread\n"); delete conn; } vnThreadsRunning[THREAD_RPCLISTENER]--; } void ThreadRPCServer2(void* parg) { printf("ThreadRPCServer started\n"); strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if ((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use parkbyted"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n %s\n" "It is recommended you use the following random password:\n" "rpcuser=pkbrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"ParkByte Alert\" admin@foo.com\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } const bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); if (fUseSSL) { context.set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort())); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service)); boost::signals2::signal<void ()> StopRequests; bool fListening = false; std::string strerr; try { acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } vnThreadsRunning[THREAD_RPCLISTENER]--; while (!fShutdown) io_service.run_one(); vnThreadsRunning[THREAD_RPCLISTENER]++; StopRequests(); } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } static CCriticalSection cs_THREAD_RPCHANDLER; void ThreadRPCServer3(void* parg) { // Make this thread recognisable as the RPC handler RenameThread("ParkByte-rpchand"); { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]++; } AcceptedConnection *conn = (AcceptedConnection *) parg; bool fRun = true; while (true) { if (fShutdown || !fRun) { conn->close(); delete conn; { LOCK(cs_THREAD_RPCHANDLER); --vnThreadsRunning[THREAD_RPCHANDLER]; } return; } map<string, string> mapHeaders; string strRequest; ReadHTTP(conn->stream(), mapHeaders, strRequest); // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DOS the user really shouldn't have their RPC port exposed.*/ if (mapArgs["-rpcpassword"].size() < 20) MilliSleep(250); conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); break; } } delete conn; { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]--; } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->unlocked) result = pcmd->actor(params, false); else { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort())))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive reply map<string, string> mapHeaders; string strReply; int nStatus = ReadHTTP(stream, mapHeaders, strReply); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value, bool fAllowNull=false) { if (fAllowNull && value.type() == null_type) return; if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); ConvertTo<T>(value2, fAllowNull); value = value2; } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getblockbynumber" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "sendalert" && n > 2) ConvertTo<int64_t>(params[2]); if (strMethod == "sendalert" && n > 3) ConvertTo<int64_t>(params[3]); if (strMethod == "sendalert" && n > 4) ConvertTo<int64_t>(params[4]); if (strMethod == "sendalert" && n > 5) ConvertTo<int64_t>(params[5]); if (strMethod == "sendalert" && n > 6) ConvertTo<int64_t>(params[6]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<int64_t>(params[2]); if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true); if (strMethod == "keypoolrefill" && n > 0) ConvertTo<int64_t>(params[0]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
[ "rzimail@aol.com" ]
rzimail@aol.com
f9ac533538f56fdea0e286b02dd2df6d57e0e179
8635e9e8cde70ce1f55aac7b50d8090add38a163
/Problems/bzoj/1565.cpp
c67233d72852caac21b98eeea17d0c03930399d4
[]
no_license
99hgz/Algorithms
f0b696f60331ece11e99c93e75eb8a38326ddd96
a24c22bdee5432925f615aef58949402814473cd
refs/heads/master
2023-04-14T15:21:58.434225
2023-04-03T13:01:04
2023-04-03T13:01:04
88,978,471
3
1
null
null
null
null
UTF-8
C++
false
false
3,687
cpp
#include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> #include <queue> #include <vector> using namespace std; typedef long long ll; int Q[1100], dep[1100], score[1000]; int tot, Head[1100], cur[1100], Next[21000]; ll Val[21000], To[21000]; int n, m, S, T, u, v; int calc(int x, int y) { return (x - 1) * m + y; } bool bfs() { memset(dep, -1, sizeof dep); int t = 0, w = 1; Q[w] = S; dep[S] = 0; while (t != w) { t++; int u = Q[t]; //printf("bfs:%d\n", u); for (int it = Head[u]; it; it = Next[it]) { int v = To[it]; if (Val[it] > 0 && dep[v] == -1) { dep[v] = dep[u] + 1; w++; Q[w] = v; } } } return dep[T] != -1; } ll dfs(int x, ll flow) { //printf("%lld\n", flow); if (x == T) return flow; ll used = 0; for (int it = cur[x]; it; it = Next[it]) { int v = To[it]; if (dep[v] == dep[x] + 1) { ll tmp = dfs(v, min(Val[it], flow - used)); used += tmp; Val[it] -= tmp; Val[it ^ 1] += tmp; cur[x] = it; if (used == flow) return flow; } } if (used == 0) dep[x] = -1; return used; } ll dinic() { ll ans = 0; while (bfs()) { for (int i = 1; i <= T; i++) cur[i] = Head[i]; ans += dfs(S, 1LL << 60); //printf("%lld\n", ans); } return ans; } void addedge(int u, int v, ll flow) { //printf("%d->%d\n", u, v); tot++; Next[tot] = Head[u]; Head[u] = tot; Val[tot] = flow; To[tot] = v; tot++; Next[tot] = Head[v]; Head[v] = tot; Val[tot] = 0; To[tot] = u; } vector<int> vec[1000]; vector<int> revec[1000]; int indegree[1000]; bool chose[1000]; void addedge1(int u, int v) { vec[u].push_back(v); revec[v].push_back(u); indegree[u]++; } void topsort() { queue<int> Q; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (indegree[calc(i, j)] == 0) Q.push(calc(i, j)); while (!Q.empty()) { int u = Q.front(); Q.pop(); chose[u] = true; for (int i = 0; i < revec[u].size(); i++) { int v = revec[u][i]; indegree[v]--; if (indegree[v] == 0) Q.push(v); } } } int SUM; void build() { for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int id = calc(i, j); if (!chose[id]) continue; if (score[id] >= 0) { SUM += score[id]; addedge(S, id, score[id]); } else addedge(id, T, -score[id]); for (int it = 0; it < vec[id].size(); it++) addedge(id, vec[id][it], 0x3f3f3f3f); } } int main() { tot = 1; scanf("%d%d", &n, &m); S = n * m + 1; T = n * m + 2; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (j != m) addedge1(calc(i, j), calc(i, j + 1)); scanf("%d", &score[calc(i, j)]); int nnum; scanf("%d", &nnum); for (int k = 1; k <= nnum; k++) { int x, y; scanf("%d%d", &x, &y); x++, y++; addedge1(calc(x, y), calc(i, j)); } } } topsort(); build(); printf("%lld", SUM - dinic()); system("pause"); return 0; }
[ "2252870379@qq.com" ]
2252870379@qq.com
8a97bc9927be19784dc1459086dd3c89cee46335
9240ceb15f7b5abb1e4e4644f59d209b83d70066
/sp/src/game/server/sdk/sdk_player.h
efac7ec14105184433f8e0e2dd4e2cb656620036
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Margen67/blamod
13e5cd9f7f94d1612eb3f44a2803bf2f02a3dcbe
d59b5f968264121d013a81ae1ba1f51432030170
refs/heads/master
2023-04-16T12:05:12.130933
2019-02-20T10:23:04
2019-02-20T10:23:04
264,556,156
2
0
NOASSERTION
2020-05-17T00:47:56
2020-05-17T00:47:55
null
UTF-8
C++
false
false
2,757
h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Player for SDK Game // // $NoKeywords: $ //=============================================================================// #ifndef SDK_PLAYER_H #define SDK_PLAYER_H #pragma once #include "player.h" #include "server_class.h" #include "sdk_playeranimstate.h" #include "sdk_shareddefs.h" //============================================================================= // >> SDK Game player //============================================================================= class CSDKPlayer : public CBasePlayer, public ISDKPlayerAnimStateHelpers { public: DECLARE_CLASS( CSDKPlayer, CBasePlayer ); DECLARE_SERVERCLASS(); DECLARE_PREDICTABLE(); DECLARE_DATADESC(); CSDKPlayer(); ~CSDKPlayer(); static CSDKPlayer *CreatePlayer( const char *className, edict_t *ed ); static CSDKPlayer* Instance( int iEnt ); // This passes the event to the client's and server's CPlayerAnimState. void DoAnimationEvent( PlayerAnimEvent_t event, int nData = 0 ); virtual void FlashlightTurnOn( void ); virtual void FlashlightTurnOff( void ); virtual int FlashlightIsOn( void ); virtual void PreThink(); virtual void PostThink(); virtual void Spawn(); virtual void InitialSpawn(); virtual void Precache(); virtual void Event_Killed( const CTakeDamageInfo &info ); virtual void LeaveVehicle( const Vector &vecExitPoint, const QAngle &vecExitAngles ); CWeaponSDKBase* GetActiveSDKWeapon() const; virtual void CreateViewModel( int viewmodelindex = 0 ); virtual void CheatImpulseCommands( int iImpulse ); CNetworkVar( int, m_iThrowGrenadeCounter ); // used to trigger grenade throw animations. CNetworkQAngle( m_angEyeAngles ); // Copied from EyeAngles() so we can send it to the client. CNetworkVar( int, m_iShotsFired ); // number of shots fired recently // Tracks our ragdoll entity. CNetworkHandle( CBaseEntity, m_hRagdoll ); // networked entity handle // In shared code. public: // ISDKPlayerAnimState overrides. virtual CWeaponSDKBase* SDKAnim_GetActiveWeapon(); virtual bool SDKAnim_CanMove(); void FireBullet( Vector vecSrc, const QAngle &shootAngles, float vecSpread, int iDamage, int iBulletType, CBaseEntity *pevAttacker, bool bDoEffects, float x, float y ); private: void CreateRagdollEntity(); ISDKPlayerAnimState *m_PlayerAnimState; }; inline CSDKPlayer *ToSDKPlayer( CBaseEntity *pEntity ) { if ( !pEntity || !pEntity->IsPlayer() ) return NULL; #ifdef _DEBUG Assert( dynamic_cast<CSDKPlayer*>( pEntity ) != 0 ); #endif return static_cast< CSDKPlayer* >( pEntity ); } #endif // SDK_PLAYER_H
[ "joe@valvesoftware.com" ]
joe@valvesoftware.com
d989762f67fa5df6af4abbe39a3b1b2501f53dde
3764f1bcd1b95ea9c26b713e525130edac47bc73
/mach/mach/machine/machine_runtime.cpp
5cd52e91d810a20c5682200242cbe4bc42aadffb
[ "MIT" ]
permissive
benbraide/mach
bc5d46185ff8e17afa0e26dbecbdb035e8e3c9c6
a723b6392778ab8391723a78ac52f53c455da6f5
refs/heads/master
2020-04-15T01:55:24.866280
2019-02-04T23:41:47
2019-02-04T23:41:47
164,296,462
0
0
null
null
null
null
UTF-8
C++
false
false
2,120
cpp
#include "machine_runtime.h" mach::machine::runtime::runtime(io::reader &reader){ init_(reader); } mach::machine::runtime::runtime(qword entry) : entry_(entry){} mach::machine::runtime::runtime(byte *data, std::size_t size){ init_(data, size); } void mach::machine::runtime::run(){ if (stack_ != nullptr) return;//Already running memory_block *module_block = nullptr; if (module_size_ != 0u){//Load module module_block = ((reader_ == nullptr) ? memory_.allocate_block(data_, module_size_) : memory_.allocate_block(module_size_)); if (reader_ != nullptr)//Write module to memory memory_.copy(*reader_, module_block->get_address(), module_block->get_size()); entry_ += module_block->get_address(); } auto stack_block = memory_.allocate_block(stack_size_); stack_ = std::make_shared<stack>(stack_block->get_data(), stack_block->get_real_size()); reg_table_.get_instruction_pointer()->write_scalar(entry_); while (stack_ != nullptr){ switch (memory_.read_scalar<op_code>(reg_table_.get_instruction_pointer()->read_scalar<qword>())){ case op_code::nop://No operation break; case op_code::mov: byte_code::mov_instruction::execute(memory_, reg_table_, *stack_); break; default: throw byte_code::instruction_error_code::unrecognized_instruction; break; } } memory_.deallocate_block(stack_block->get_address()); if (module_block != nullptr)//Unload module memory_.deallocate_block(module_block->get_address()); } void mach::machine::runtime::init_(io::reader &reader){ prepare_(reader); reader_ = &reader; } void mach::machine::runtime::init_(byte *data, std::size_t size){ io::binary_buffer_reader reader(data, size); prepare_(reader); data_ = (data + reader.get_offset()); } void mach::machine::runtime::prepare_(io::reader &reader){ if ((stack_size_ = reader.read_scalar<std::size_t>()) == 0u) stack_size_ = (1024u * 1024u);//Use default size -- 1MB module_size_ = reader.read_scalar<std::size_t>(); entry_ = reader.read_scalar<qword>(); } mach::machine::memory mach::machine::runtime::memory_; std::size_t mach::machine::runtime::stack_size_ = 0u;
[ "benbraide@yahoo.com" ]
benbraide@yahoo.com
41b8edae2958da41e17ee97a8144b9a5e72fd4f6
e176ee182c7737e98434cf6702a6ed0fff6431fb
/include/UdmBase.h
e7ef51d12f61535328be989b3f3b483c84f0c3ab
[ "BSD-2-Clause" ]
permissive
syoyo/UDMlib
4d1d1a61170b543f6199f62133b02081dbcce035
f7796265d9381a7f0e878112842b7ce4bfe9af15
refs/heads/master
2023-09-04T12:37:22.953014
2015-04-20T03:25:52
2015-04-20T03:25:52
34,649,537
0
0
null
2015-04-27T06:22:51
2015-04-27T06:22:50
null
UTF-8
C++
false
false
2,026
h
/* * UDMlib - Unstructured Data Management Library * * Copyright (C) 2012-2015 Institute of Industrial Science, The University of Tokyo. * All rights reserved. * */ #ifndef _UDMBASE_H_ #define _UDMBASE_H_ /** * @file UdmBase.h * UDMlibライブラリのすべてのクラスの基底クラスのヘッダーファイル */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <vector> #include <map> #include <set> #include <iostream> #include <cstdio> #include <limits> #include <sstream> #include <math.h> #include <limits> #include "UdmErrorHandler.h" #include "utils/UdmStopWatch.h" #include "udmlib.h" #include "udm_memutils.h" #include "udm_define.h" /** * @file UdmGeneral.h * モデル構成の基底クラスのヘッダーファイル */ /** * UDMlibライブラリのネームスペース */ namespace udm { /** * 大文字・小文字を無視して比較する. */ struct insensitive_compare { std::string _compare; insensitive_compare( const std::string &src ) : _compare(src) {} bool operator() ( const std::string &dest ) const { if (_compare.size() != dest.size()) { return false; } for (std::string::const_iterator c1 = _compare.begin(), c2 = dest.begin(); c1 != _compare.end(); ++c1, ++c2) { if (tolower(*c1) != tolower(*c2)) { return false; } } return true; } }; struct map_case_compare { bool operator() (const std::string& lhs, const std::string& rhs) const { return strcasecmp(lhs.c_str(), rhs.c_str()) < 0; } }; /** * UDMlibライブラリのすべてのクラスの基底クラス */ class UdmBase { public: UdmBase(); virtual ~UdmBase(); protected: int split(const std::string &str, char delim, std::vector<std::string>& results) const; void trim(char *buf); bool compareCaseInsensitive(const std::string& str1, const std::string& str2); }; } /* namespace udm */ #endif /* _UDMBASE_H_ */
[ "keno@riken.jp" ]
keno@riken.jp
b3bd6dd44be2d655306a106ce69bafae36280f5a
0208776bfede55763e03a08c80b79c28564cfb04
/src/cpu.cpp
bc67327cb5a04fafae5736446ab78696258682cd
[ "MIT" ]
permissive
mikefeneley/mechanicus-emulator
cda239387bdbf291487d796338186bd34515a13b
949946de02b8346c4654baaf6946b3a15da51d5b
refs/heads/master
2021-06-09T19:36:51.329209
2016-12-23T13:43:14
2016-12-23T13:43:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
448
cpp
/* * CPU Simulator */ class CPU { public: CPU(void); void reset(void); void set_program(void *program); void fetch(void); void decode(void); void execute(void); private: void *program; int zero_flag; int sign_flag; int overflow_flag; int break_flag; int decimal_flag; int interrupt_flag; int carry_flag; };
[ "michael.j.feneley@gmail.com" ]
michael.j.feneley@gmail.com
d981dc1bb0cc27d14d2f321be6cbf914f21d21b7
66deb611781cae17567efc4fd3717426d7df5e85
/pcmanager/src/src_kclear/trackcleaner/src/regopt.cpp
4a1578dc0595bfb175eceb65e2ea0e21bcc452df
[ "Apache-2.0" ]
permissive
heguoxing98/knoss-pcmanager
4671548e14b8b080f2d3a9f678327b06bf9660c9
283ca2e3b671caa85590b0f80da2440a3fab7205
refs/heads/master
2023-03-19T02:11:01.833194
2020-01-03T01:45:24
2020-01-03T01:45:24
504,422,245
1
0
null
2022-06-17T06:40:03
2022-06-17T06:40:02
null
GB18030
C++
false
false
17,003
cpp
#include "stdafx.h" #include "regopt.h" /************************************************************************/ //枚举当前所有值可递归 /************************************************************************/ void CRegOpt::DoRegEnumeration(HKEY rootKey,LPCTSTR lpItemPath,EnumerateRegFun fnRegFun,void* pUserData/* =NULL */) { if(s_bUserBreak) return; HKEY hKey = NULL; LONG lResult; LPTSTR lpName = new TCHAR[MAX_PATH]; LPBYTE lpValue = new BYTE[MAX_PATH * 20]; if (lpValue == NULL) { goto clean0; } if (lpName == NULL) { goto clean0; } lResult = RegOpenKeyEx(rootKey, lpItemPath, NULL, KEY_READ, &hKey ); if(lResult != ERROR_SUCCESS) { m_iErrCode = ::GetLastError(); goto clean0; } /************************************************************************/ /*枚举值 /************************************************************************/ BEGIN DWORD dwIndex=0; do { if (lpName == NULL||lpValue ==NULL) { m_iErrCode = ::GetLastError(); goto clean0; } memset(lpName,0,sizeof(lpName)); memset(lpValue,0,sizeof(lpValue)); DWORD dwName = MAX_PATH; DWORD dwValue = MAX_PATH * 20; DWORD dwType; lResult = RegEnumValue( hKey, dwIndex, lpName, &dwName, NULL, &dwType, lpValue, &dwValue ); if (lResult == ERROR_MORE_DATA) { //delete[] lpName; delete[] lpValue; //lpName = NULL; lpValue = NULL; //lpName = new TCHAR[dwName+2]; lpValue = new BYTE [dwValue+10]; //memset(lpName,0,sizeof(lpName)); memset(lpValue,0,sizeof(lpValue) + 10); if (lpName == NULL||lpValue ==NULL) { m_iErrCode = ::GetLastError(); goto clean0; } lResult = RegEnumValue( hKey, dwIndex, lpName, &dwName, NULL, &dwType, lpValue, &dwValue ); } if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { break; } else { m_iErrCode = GetLastError(); goto clean0; } } if(0==wcscmp(lpName,_T(""))) { wcscpy(lpName,_T("默认值")); } BOOL bRet= fnRegFun(rootKey, lpItemPath, lpName, dwName ,lpValue,dwValue, dwType, pUserData); //是否继续枚举 if (bRet == FALSE) { s_bUserBreak = TRUE; goto clean0; } dwIndex++; } while (1); END /************************************************************************/ /*枚举键 /************************************************************************/ BEGIN DWORD dwIndex=0; do { TCHAR szKey[MAX_PATH]={0}; DWORD dwKey = sizeof(szKey); lResult =RegEnumKey(hKey,dwIndex,szKey,dwKey); dwIndex++; if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { // RegCloseKey(hKey); // return ; goto clean0; } else { m_iErrCode = GetLastError(); // RegCloseKey(hKey); // return ; goto clean0; } } //!!由于递归过深有可能溢出 //#define MAX_REGPATH 2048 //TCHAR szRoot[MAX_REGPATH]={0}; CString strRoot; if (wcscmp(lpItemPath,_T("")) == 0 ) { strRoot.Format(_T("%s"),szKey); //wsprintf(szRoot,_T("%s"),szKey); } else { strRoot.Format(_T("%s\\%s"),lpItemPath,szKey); //wsprintf(szRoot,_T("%s\\%s"),lpItemPath,szKey); } if (fnRegFun(rootKey, strRoot.GetBuffer(), NULL,NULL,NULL,NULL, -1, pUserData)) { DoRegEnumeration(rootKey, strRoot.GetBuffer(), fnRegFun, pUserData); } } while (1); END clean0: if (hKey) { RegCloseKey(hKey); hKey = NULL; } if (lpName) { delete[] lpName; lpName = NULL; } if (lpValue) { delete[] lpValue; lpValue = NULL; } return ; } /************************************************************************/ /* 递归枚举所有子键 /************************************************************************/ BOOL CRegOpt::DoEnumCurrnetSubKeyEx(HKEY hRootKey,LPCTSTR lpcKey,CSimpleArray<CString>& vec_Key,BOOL bRes,BOOL bFullPath) { HKEY hKey; LONG lResult; //打开键 lResult = RegOpenKeyEx(hRootKey, lpcKey, NULL, KEY_READ, &hKey ); if(lResult != ERROR_SUCCESS) { m_iErrCode = lResult; return FALSE; } //枚举键名 BOOL bRet = TRUE; DWORD dwIndex=0; do { TCHAR szKey[MAX_PATH]={0}; DWORD dwKey = sizeof(szKey); lResult =RegEnumKey(hKey,dwIndex,szKey,dwKey); dwIndex++; if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { bRet = TRUE; break; } else { bRet = FALSE; m_iErrCode = lResult; break; } } if(bFullPath == TRUE) { CString strRegFullPath; strRegFullPath = lpcKey; strRegFullPath.Append(_T("\\")); strRegFullPath.Append(szKey); vec_Key.Add(strRegFullPath); } else vec_Key.Add(szKey); if (TRUE == bRes) { CString strSub=lpcKey; strSub.Append(_T("\\")); strSub.Append(szKey); DoEnumCurrnetSubKeyEx(hRootKey,strSub,vec_Key,bRes,bFullPath); } } while (1); RegCloseKey(hKey); return bRet; } /************************************************************************/ //获得当前键下的所有子键 /************************************************************************/ BOOL CRegOpt::DoEnumCurrnetSubKey(HKEY hRootKey,LPCTSTR lpcKey,CSimpleArray<CString>& vec_Key) { HKEY hKey; LONG lResult; //打开键 lResult = RegOpenKeyEx(hRootKey, lpcKey, NULL, KEY_READ, &hKey ); if(lResult != ERROR_SUCCESS) { m_iErrCode = lResult; return FALSE; } //枚举键名 BOOL bRet = TRUE; DWORD dwIndex=0; do { TCHAR szKey[MAX_PATH]={0}; DWORD dwKey = sizeof(szKey); lResult =RegEnumKey(hKey,dwIndex,szKey,dwKey); dwIndex++; if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { bRet = TRUE; break; } else { bRet = FALSE; m_iErrCode = lResult; break; } } vec_Key.Add(szKey); } while (1); RegCloseKey(hKey); return bRet; } BOOL CRegOpt::DoEnumCurrnetSubKey(HKEY hRootKey,LPCTSTR lpcKey,CAtlMap<CString,char>& vec_Key) { HKEY hKey; LONG lResult; //打开键 lResult = RegOpenKeyEx(hRootKey, lpcKey, NULL, KEY_READ, &hKey ); if(lResult != ERROR_SUCCESS) { m_iErrCode = lResult; return FALSE; } //枚举键名 BOOL bRet = TRUE; DWORD dwIndex=0; do { TCHAR szKey[MAX_PATH]={0}; DWORD dwKey = sizeof(szKey); lResult =RegEnumKey(hKey,dwIndex,szKey,dwKey); if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { bRet = TRUE; break; } else { bRet = FALSE; m_iErrCode = lResult; break; } } vec_Key.SetAt(szKey,'1'); dwIndex++; } while (1); RegCloseKey(hKey); return bRet; } /************************************************************************/ //获得当前键下的所有值名 /************************************************************************/ BOOL CRegOpt::DoEnumCurrnetValue(HKEY hRootKey,LPCTSTR lpcKey,CSimpleArray<REGVALUE>& vec_Value,BOOL bRes) { HKEY hKey; LONG lResult; //打开键 lResult = RegOpenKeyEx(hRootKey, lpcKey, NULL, KEY_READ, &hKey ); if(lResult != ERROR_SUCCESS) { m_iErrCode = ::GetLastError(); return FALSE; } BOOL bRet = TRUE; DWORD dwIndex=0; do { LPTSTR lpName = new TCHAR[MAX_PATH]; LPBYTE lpValue = new BYTE[MAX_PATH]; if (lpName == NULL||lpValue ==NULL) { m_iErrCode = ERROR_NOMEMOEY bRet = FALSE; break; } memset(lpName,0,sizeof(lpName)); memset(lpValue,0,sizeof(lpValue)); DWORD dwName = MAX_PATH; DWORD dwValue = MAX_PATH; DWORD dwType; lResult = RegEnumValue( hKey, dwIndex, lpName, &dwName, NULL, &dwType, lpValue, &dwValue ); if (lResult == ERROR_MORE_DATA) { delete[] lpName; delete[] lpValue; lpName = NULL; lpValue = NULL; lpName = new TCHAR[dwName+1]; lpValue = new BYTE [dwValue+1]; memset(lpName,0,sizeof(lpName)); memset(lpValue,0,sizeof(lpValue)); if (lpName == NULL||lpValue ==NULL) { m_iErrCode = ERROR_NOMEMOEY bRet = FALSE; break; } lResult = RegEnumValue( hKey, dwIndex, lpName, &dwName, NULL, &dwType, lpValue, &dwValue ); } if (lResult == ERROR_NO_MORE_ITEMS) { bRet = TRUE; break; } if (dwName == 0) { wcscpy(lpName,_T("默认值")); } REGVALUE regValue; regValue.strValueName = lpName; regValue.dwType = dwType; switch (dwType) { case REG_SZ: case REG_EXPAND_SZ: { regValue.strValue = (wchar_t*) lpValue; } break; case REG_BINARY: case REG_DWORD_LITTLE_ENDIAN: case REG_DWORD_BIG_ENDIAN: case REG_LINK: case REG_MULTI_SZ: case REG_NONE: case REG_QWORD_LITTLE_ENDIAN: regValue.strValue = _T(""); break; } vec_Value.Add(regValue); //释放相应空间 delete[] lpName; delete[] lpValue; lpName = NULL; lpValue = NULL; dwIndex++; } while (1); if (bRes == FALSE) { RegCloseKey(hKey); return TRUE; } //向下层枚举 BEGIN DWORD dwIndex=0; do { TCHAR szKey[MAX_PATH]={0}; DWORD dwKey = sizeof(szKey); lResult =RegEnumKey(hKey,dwIndex,szKey,dwKey); dwIndex++; if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { RegCloseKey(hKey); return TRUE; } else { m_iErrCode = GetLastError(); RegCloseKey(hKey); return TRUE; } } // //!!由于递归过深有可能溢出 //#define MAX_REGPATH 2048 // // TCHAR szRoot[MAX_REGPATH]={0}; // // // if (wcscmp(lpcKey,_T("")) == 0 ) // wsprintf(szRoot,_T("%s"),szKey); // else // wsprintf(szRoot,_T("%s\\%s"),lpcKey,szKey); CString strRoot; if (wcscmp(lpcKey,_T("")) == 0 ) { strRoot.Format(_T("%s"),szKey); //wsprintf(szRoot,_T("%s"),szKey); } else { strRoot.Format(_T("%s\\%s"),lpcKey,szKey); //wsprintf(szRoot,_T("%s\\%s"),lpItemPath,szKey); } DoEnumCurrnetValue(hRootKey, strRoot.GetBuffer(), vec_Value, bRes); } while (1); END RegCloseKey(hKey); return TRUE; } /************************************************************************/ //删除子键 /************************************************************************/ BOOL CRegOpt::RegDelnode(HKEY hKeyRoot, LPCTSTR lpSubKey) { TCHAR szDelKey[2 * MAX_PATH]; lstrcpy (szDelKey, lpSubKey); return RegDelnodeRecurse(hKeyRoot, szDelKey); } BOOL CRegOpt::RegDelnodeRecurse(HKEY hKeyRoot, LPTSTR lpSubKey) { LPTSTR lpEnd; LONG lResult; DWORD dwSize; TCHAR szName[MAX_PATH]; HKEY hKey; FILETIME ftWrite; lResult = RegDeleteKey(hKeyRoot, lpSubKey); if (lResult == ERROR_SUCCESS) { m_iErrCode = GetLastError(); return TRUE; } lResult = RegOpenKeyEx (hKeyRoot, lpSubKey, 0, KEY_READ, &hKey); if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_FILE_NOT_FOUND) { return TRUE; } else { m_iErrCode = GetLastError(); return FALSE; } } lpEnd = lpSubKey + lstrlen(lpSubKey); if (*(lpEnd - 1) != '\\') { *lpEnd = '\\'; lpEnd++; *lpEnd = '\0'; } dwSize = MAX_PATH; lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL, NULL, NULL, &ftWrite); if (lResult == ERROR_SUCCESS) { do { lstrcpy (lpEnd, szName); if (!RegDelnodeRecurse(hKeyRoot, lpSubKey)) { break; } dwSize = MAX_PATH; lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,NULL, NULL, &ftWrite); } while (lResult == ERROR_SUCCESS); } lpEnd--; *lpEnd = TEXT('\0'); RegCloseKey (hKey); lResult = RegDeleteKey(hKeyRoot, lpSubKey); if (lResult == ERROR_SUCCESS) return TRUE; return FALSE; } BOOL CRegOpt::RegDelValue (HKEY hKeyRoot,LPCTSTR lpSubKey,LPCTSTR lpValue) { HKEY hKey = NULL; DWORD dwRet; BOOL bRet = FALSE; if ((dwRet=RegOpenKeyEx(hKeyRoot,lpSubKey,0,KEY_ALL_ACCESS,&hKey))==ERROR_SUCCESS) { DWORD cbdata; if ((dwRet=RegQueryValueEx(hKey,lpValue,NULL,NULL,NULL,&cbdata))==ERROR_SUCCESS) { if (RegDeleteValue(hKey,lpValue)==ERROR_SUCCESS) { bRet = TRUE; goto clean0; } } else { m_iErrCode = dwRet; bRet = FALSE; goto clean0; } } else { m_iErrCode = dwRet; bRet = FALSE; } clean0: if (hKey) { RegCloseKey(hKey); hKey = NULL; } return TRUE; } /************************************************************************/ //是否存键 /************************************************************************/ BOOL CRegOpt::FindKey(HKEY hKeyRoot,LPCTSTR lpSubKey) { HKEY hKey = NULL; DWORD dwRet; BOOL bRet = FALSE; if ((dwRet=RegOpenKeyEx(hKeyRoot,lpSubKey,0,KEY_ALL_ACCESS,&hKey))==ERROR_SUCCESS) { bRet = TRUE; goto clean0; } if (dwRet == ERROR_FILE_NOT_FOUND ) //找不到指定文件 { bRet = FALSE; dwRet = GetLastError(); goto clean0; } clean0: m_iErrCode = dwRet; return TRUE; } /************************************************************************/ //获得错误代码 /************************************************************************/ DWORD CRegOpt::GetErrorCode() { return m_iErrCode; } BOOL CRegOpt::CrackRegKey(wchar_t* regstring,HKEY& root, wchar_t*& subkey,wchar_t*& value) { if (!(subkey = wcsstr(regstring,L"\\"))) { return FALSE; //No valid root key } *subkey = 0; ++subkey; if (!lstrcmpi(regstring,L"HKEY_CURRENT_USER"))root = HKEY_CURRENT_USER; else if (!lstrcmpi(regstring,L"HKEY_LOCAL_MACHINE"))root = HKEY_LOCAL_MACHINE; else if (!lstrcmpi(regstring,L"HKEY_USERS")) root = HKEY_USERS; else if (!lstrcmpi(regstring,L"HKEY_CLASSES_ROOT")) root = HKEY_CLASSES_ROOT; else //No valid root key { m_iErrCode = ERROR_NOFAILKEY; return FALSE; } //value = wcsstr(subkey,L"\\"); //if (value) //{ // //value can point to real value or to '\0', meaning empty std::wstring // *value = 0; // ++value; //} ////value points to NULL return TRUE; } BOOL CRegOpt::CrackRegKey(CString& strRegPath,HKEY& root,CString& strSubKey) { int nInx = strRegPath.Find(_T("\\")); if (nInx == -1) return FALSE; strSubKey = strRegPath.Mid(nInx+1); CString strRootKey = strRegPath.Mid(0,nInx); if (-1!=strRootKey.Find(L"HKEY_CURRENT_USER")) root = HKEY_CURRENT_USER; else if(-1!=strRootKey.Find(L"HKEY_LOCAL_MACHINE")) root = HKEY_LOCAL_MACHINE; else if(-1!=strRootKey.Find(L"HKEY_USERS")) root = HKEY_USERS; else if(-1!=strRootKey.Find(L"HKEY_CLASSES_ROOT")) root = HKEY_CLASSES_ROOT; else { m_iErrCode = ERROR_NOFAILKEY; return FALSE; } return TRUE; } //获得指定键的默认值 BOOL CRegOpt::GetDefValue(HKEY hKeyRoot,LPCTSTR lpSubKey,CString& strValueName,CString& strValue) { HKEY hKey; DWORD dwRet; BOOL bRet = FALSE; if ((dwRet=RegOpenKeyEx(hKeyRoot,lpSubKey,0,KEY_ALL_ACCESS,&hKey))!=ERROR_SUCCESS) { m_iErrCode = dwRet; bRet = FALSE; goto clean0; } DWORD cbData =MAX_PATH; LPBYTE lpValue = new BYTE[MAX_PATH]; memset(lpValue,0,MAX_PATH); DWORD dwType; dwRet = RegQueryValueEx(hKey, strValueName.GetBuffer(), NULL, &dwType, (LPBYTE) lpValue, &cbData ); if ( dwRet== ERROR_MORE_DATA ) { lpValue = new BYTE[cbData+2]; if (lpValue ==NULL) { m_iErrCode = ERROR_NOMEMOEY; bRet = FALSE; goto clean0; } dwRet = RegQueryValueEx(hKey, strValueName.GetBuffer(), NULL, NULL, (LPBYTE) lpValue, &cbData ); } if (dwRet != ERROR_SUCCESS) { m_iErrCode = ERROR_NODEF; bRet = FALSE; goto clean0; } if (REG_SZ == dwType|| REG_EXPAND_SZ== dwType) { strValue = (TCHAR*)lpValue; } else strValue = _T(""); bRet = TRUE; clean0: RegCloseKey(hKey); return bRet; } BOOL CRegOpt::GetHKEYToString(HKEY hRootKey,LPCTSTR lpszSubKey,CString& strRegFullPath) { strRegFullPath = _T(""); if (hRootKey == HKEY_CURRENT_USER) { strRegFullPath.Append(L"HKEY_CURRENT_USER\\"); } else if (hRootKey == HKEY_LOCAL_MACHINE) { strRegFullPath.Append(L"HKEY_LOCAL_MACHINE\\"); } else if (hRootKey == HKEY_USERS) { strRegFullPath.Append(L"HKEY_USERS\\"); } else if (hRootKey == HKEY_CLASSES_ROOT) { strRegFullPath.Append(L"HKEY_CLASSES_ROOT\\"); } else { return FALSE; } strRegFullPath.Append(lpszSubKey); return TRUE; }
[ "dreamsxin@qq.com" ]
dreamsxin@qq.com
1fffd194233ffa0c366a83229c6af41508f892e3
3047545349bf224a182b2c33bf1f110aef1ce9b6
/Transims60/Converge_Service/Fuel_Check.cpp
b71ed57d3cbe2229458fb73523b7e32a26a88d95
[]
no_license
qingswu/Transim
585afe71d9666557cff53f6683cf54348294954c
f182d1639a4db612dd7b43a379a3fa344c2de9ea
refs/heads/master
2021-01-10T21:04:50.576267
2015-04-08T19:07:28
2015-04-08T19:07:28
35,232,171
1
1
null
null
null
null
UTF-8
C++
false
false
6,866
cpp
//********************************************************* // Fuel_Check.cpp - check the fuel supply and build path //********************************************************* #include "Converge_Service.hpp" //--------------------------------------------------------- // Fuel_Check //--------------------------------------------------------- void Converge_Service::Fuel_Check (Plan_Data &plan) { if (plan.size () == 0) return; double supply = initial_fuel [plan.Index ()]; if (supply <= 0) return; Veh_Type_Data *veh_type_ptr = &veh_type_array [plan.Veh_Type ()]; int seek_level = DTOI (veh_type_ptr->Fuel_Cap () * seek_fuel / 100.0); if (seek_level < 1) seek_level = 1; int function = veh_type_ptr->Fuel_Func (); if (function < 0) function = 0; Dtime tod; int leg, fuel_leg, fuel_id; double speed, factor, ttime; Loc_Fuel_Data *fuel_ptr; Plan_Leg_Itr itr, itr2; Integers stop_list; Int_Itr stop_itr; factor = (Metric_Flag ()) ? 1000.0 : 5280.0; //---- find the last fuel location ---- fuel_leg = fuel_id = -1; for (leg=0, itr = plan.begin (); itr != plan.end (); itr++, leg++) { if (itr->Type () == LOCATION_ID && itr->Mode () == WAIT_MODE) { fuel_ptr = &loc_fuel_array [itr->ID ()]; if (fuel_ptr->supply > 0) { fuel_leg = leg; fuel_id = itr->ID (); stop_list.push_back (itr->ID ()); } } } bool look_ahead = true; bool reserve = (info_flag && info_range.In_Range (plan.Type ())); //---- monitor the fuel supply ---- tod = plan.Depart (); for (leg=0, itr = plan.begin (); itr != plan.end (); itr++, leg++) { tod += itr->Time (); if (itr->Type () == LOCATION_ID && itr->Mode () == WAIT_MODE) { fuel_ptr = &loc_fuel_array [itr->ID ()]; if (fuel_ptr->supply <= 0) continue; if (leg < fuel_leg) { MAIN_LOCK fuel_ptr->failed++; END_LOCK continue; } //---- try to fill the tank ---- MAIN_LOCK if (reserve) { if (plan.Method () != BUILD_PATH) { fuel_ptr->consumed += veh_type_ptr->Fuel_Cap (); } supply = veh_type_ptr->Fuel_Cap (); } else if ((fuel_ptr->consumed + veh_type_ptr->Fuel_Cap ()) <= fuel_ptr->supply) { fuel_ptr->consumed += veh_type_ptr->Fuel_Cap (); supply = veh_type_ptr->Fuel_Cap (); } else { fuel_ptr->failed++; Set_Problem (FUEL_PROBLEM); } END_LOCK continue; } //---- consume fuel ---- if (itr->Mode () != DRIVE_MODE) continue; ttime = itr->Time () / 3600.0; if (ttime > 0) { speed = itr->Length () / (factor * ttime); } else { speed = 1; } supply -= ttime * functions.Apply_Function (function, speed); if (supply > seek_level) continue; if (supply < 0) { plan.Problem (FUEL_PROBLEM); if (fuel_id >= 0) { fuel_ptr = &loc_fuel_array [fuel_id]; MAIN_LOCK fuel_ptr->ran_out++; END_LOCK } if (reserve) { initial_fuel [plan.Index ()] = veh_type_ptr->Fuel_Cap (); plan.Stop_Location (-2); Time_Index new_index = plan.Get_Time_Index (); MAIN_LOCK Time_Index index = time_itr->first; new_index.Start (index.Start () + 10); if (!plan_time_map.insert (Time_Map_Data (new_index, plan.Index ())).second) { Warning (String ("Fuel Time Index Problem Plan %d-%d-%d-%d") % plan.Household () % plan.Person () % plan.Tour () % plan.Trip ()); } time_itr = plan_time_map.find (index); END_LOCK } else { plan.Stop_Location (-1); } return; } if (leg < fuel_leg) continue; //---- look for fuel ---- if (itr->Type () != DIR_ID || plan.Priority () == SKIP || plan.Method () != BUILD_PATH || !look_ahead) continue; int i, node, best; double x1, y1, x2, y2, x3, y3, x, y, dx, dy, diff1, diff2, diff, best_diff, best_diff2; bool flag; Dir_Data *dir_ptr; Link_Data *link_ptr; Node_Data *node_ptr; Location_Itr loc_itr; Location_Data *loc_ptr; dir_ptr = &dir_array [itr->ID ()]; link_ptr = &link_array [dir_ptr->Link ()]; if (dir_ptr->Dir () == 0) { node = link_ptr->Bnode (); } else { node = link_ptr->Anode (); } node_ptr = &node_array [node]; x1 = node_ptr->X (); y1 = node_ptr->Y (); loc_ptr = &location_array [plan.Destination ()]; x2 = loc_ptr->X (); y2 = loc_ptr->Y (); dx = x2 - x1; dy = y2 - y1; diff1 = dx * dx + dy * dy; best = -1; best_diff = 0; for (i=0, loc_itr = location_array.begin (); loc_itr != location_array.end (); loc_itr++, i++) { fuel_ptr = &loc_fuel_array [i]; if (fuel_ptr->supply <= 0) continue; if (reserve) { if ((fuel_ptr->consumed + veh_type_ptr->Fuel_Cap ()) > fuel_ptr->supply) continue; } for (flag=false, stop_itr = stop_list.begin (); stop_itr != stop_list.end (); stop_itr++) { if (*stop_itr == i) { flag = true; break; } } if (flag) continue; x = loc_itr->X (); y = loc_itr->Y (); dx = x - x2; dy = y - y2; diff = dx * dx + dy * dy; if (diff > diff1) { continue; } dx = x - x1; dy = y - y1; diff += diff2 = (dx * dx + dy * dy) * 2.0; best_diff2 = diff + diff2; for (itr2 = itr + 1; itr2 != plan.end (); itr2++) { if (itr2->Mode () != DRIVE_MODE || itr2->Type () != DIR_ID) continue; dir_ptr = &dir_array [itr2->ID ()]; link_ptr = &link_array [dir_ptr->Link ()]; if (dir_ptr->Dir () == 0) { node = link_ptr->Bnode (); } else { node = link_ptr->Anode (); } node_ptr = &node_array [node]; x3 = node_ptr->X (); y3 = node_ptr->Y (); dx = x - x3; dy = y - y3; diff2 = diff + (dx * dx + dy * dy) * 2.0; if (diff2 < best_diff2) { best_diff2 = diff2; } } if (best < 0 || best_diff2 < best_diff) { best = i; best_diff = best_diff2; } } if (best < 0) { look_ahead = false; continue; } //---- stop at the gas station ---- Time_Index new_index = plan.Get_Time_Index (); plan.Reroute_Time (tod); plan.Stop_Location (best); plan.Activity (fuel_duration); plan.Constraint (START_TIME); plan.Priority (CRITICAL); //---- save and update iterator ----- MAIN_LOCK if (reserve) { fuel_ptr = &loc_fuel_array [best]; fuel_ptr->consumed += veh_type_ptr->Fuel_Cap (); } Time_Index index = time_itr->first; if (tod <= index.Start ()) { new_index.Start (index.Start () + 10); } else { new_index.Start (tod); } if (!plan_time_map.insert (Time_Map_Data (new_index, plan.Index ())).second) { Warning (String ("Fuel Time Index Problem Plan %d-%d-%d-%d") % plan.Household () % plan.Person () % plan.Tour () % plan.Trip ()); } time_itr = plan_time_map.find (index); END_LOCK plan.Problem (FUEL_PROBLEM); break; } }
[ "davidroden@7728d46c-9721-0410-b1ea-f014b4b56054" ]
davidroden@7728d46c-9721-0410-b1ea-f014b4b56054
39ef0be40668f9ae72bda45c43d33a60f1508b3e
0f252a72f9c464bc4e38d8b18c4d03717d84acf2
/laptop/SPOJ/LARMY.cpp
31254d9d45c9b893c2ae619c0cdadea0d2dce3b1
[]
no_license
ZikXewen/Submissions
e5286f1a94f1108eaa43c30fe6d12cec8537f066
ec6efc8f92440e43850b8d094927958c5533eb05
refs/heads/master
2023-07-24T11:59:16.460972
2021-05-24T13:02:43
2021-05-24T13:02:43
220,632,852
1
0
null
null
null
null
UTF-8
C++
false
false
1,139
cpp
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define vi vector<int> using namespace std; int main(){ ios::sync_with_stdio(0), cin.tie(0); int N, K; cin >> N >> K; vi in(N), mp(N); for(int i = 0; i < N; ++i) cin >> in[i], mp[i] = in[i]; sort(all(mp)); mp.resize(unique(all(mp)) - mp.begin()); vector<vi> sm(N, vi(mp.size() + 1)), dp(N, vi(N)), an(N, vi(K + 1, 1e9)), ct(N, vi(K)); for(auto &i: in) i = lower_bound(all(mp), i) - mp.begin(); for(int i = 0; i < N; ++i) ++sm[i][in[i]]; for(int i = 0; i < N; ++i) for(int j = mp.size() - 1; j >= 0; --j) sm[i][j] += sm[i][j + 1] + (i? sm[i - 1][j] : 0) - (i? sm[i - 1][j + 1] : 0); for(int i = 0; i < N; ++i) for(int j = i + 1; j < N; ++j) dp[i][j] = dp[i][j - 1] + sm[j - 1][in[j] + 1] - (i? sm[i - 1][in[j] + 1] : 0); for(int i = 0; i < N; ++i) an[i][0] = dp[0][i]; for(int i = 1; i < N; ++i) for(int j = min(i, K - 1), ck = 0; j; --j, ck = 1) for(int k = max(ct[i - 1][j], j - 1); k <= (ck? ct[i][j + 1] : i - 1); ++k) if(an[i][j] >= an[k][j - 1] + dp[k + 1][i]) an[i][j] = an[k][j - 1] + dp[k + 1][i], ct[i][j] = k; cout << an[N - 1][K - 1]; }
[ "datasup12@gmail.com" ]
datasup12@gmail.com
e4a7da3cfc299c882554219ec0feda779dfb06c4
645847547bc80c462143fcf0e6c996626dbe3d46
/private/windows/opengl/scrsave/common/scrnsave.cxx
e82e5f48bb2a797a27b47210bf3aea51fe5e945a
[]
no_license
v-jush/win2k
8834ed687e04f2b9475d36673fe4e8986020581b
b6f6742e44e41c7fd5c4e75ca3e6605e426239de
refs/heads/master
2020-09-24T18:05:38.920032
2019-08-15T03:13:13
2019-08-15T03:13:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,227
cxx
// SCRNSAVE.C -- skeleton for screen saver application // 4/5/94 francish merged NT and Win4 saver code, folded in SCRNSAVE.SCR // - 3/14/96: marcfo Pulled this file in from shell\control\scrnsave\common. // All changes marked with GL_SCRNSAVE. #define GL_SCRNSAVE 1 #define WIN31 #include <windows.h> #include <windowsx.h> #include "scrnsave.h" #include <regstr.h> #include <imm.h> #ifdef GL_SCRNSAVE #include "glscrnsv.h" #endif #define DBG_MSGS 0 const TCHAR szScreenSaverKey[] = REGSTR_PATH_SCREENSAVE; TCHAR szPasswordActiveValue[] = REGSTR_VALUE_USESCRPASSWORD; const TCHAR szPasswordValue[] = REGSTR_VALUE_SCRPASSWORD; TCHAR szPwdDLL[] = TEXT("PASSWORD.CPL"); CHAR szFnName[] = "VerifyScreenSavePwd"; // Proc name, must be ANSI TCHAR szImmDLL[] = TEXT("IMM32.DLL"); CHAR szImmFnc[] = "ImmAssociateContext"; // Proc name, must be ANSI #if 0 TCHAR szCoolSaverHacks[] = REGSTR_PATH_SETUP TEXT("\\Screen Savers"); TCHAR szMouseThreshold[] = TEXT("Mouse Threshold"); TCHAR szPasswordDelay[] = TEXT("Password Delay"); #endif typedef BOOL (FAR PASCAL * VERIFYPWDPROC) (HWND); typedef HIMC (FAR PASCAL * IMMASSOCPROC) (HWND,HIMC); // variables declared in SCRNSAVE.H HINSTANCE hMainInstance = 0; HWND hMainWindow = 0; BOOL fChildPreview = FALSE; // other globals POINT ptMouse; BOOL fClosing = FALSE; BOOL fCheckingPassword = FALSE; HINSTANCE hInstPwdDLL = NULL; VERIFYPWDPROC VerifyPassword = NULL; static BOOL preview_like_fullscreen = FALSE; static UINT uShellAutoPlayQueryMessage = 0; HINSTANCE hInstImm = NULL; IMMASSOCPROC ImmFnc = NULL; HIMC hPrevImc = (HIMC)0L; static BOOL fOnWin95 = FALSE; //TRUE if on Chicago, FALSE if on Cairo // random junk DWORD dwWakeThreshold = 4; //default to slight movement DWORD dwPasswordDelay = 0; DWORD dwBlankTime = 0; #define MAX_PASSWORD_DELAY_IN_SECONDS (60) // forward declarations of internal fns #ifndef GL_SCRNSAVE // These are hooked out to glscrnsv.cxx static INT_PTR DoScreenSave( HWND hParent ); static INT_PTR DoConfigBox( HWND hParent ); #endif static INT_PTR DoSaverPreview( LPCTSTR szUINTHandle ); static INT_PTR DoChangePw( LPCTSTR szUINTHandle ); static BOOL DoPasswordCheck( HWND hParent ); VOID LoadPwdDLL(VOID); VOID UnloadPwdDLL(VOID); // helper for time static DWORD GetElapsedTime(DWORD from, DWORD to) { return (to >= from)? (to - from) : (1 + to + (((DWORD)-1) - from)); } // helper to convert text to unsigned int static UINT_PTR atoui( LPCTSTR szUINT ) { UINT_PTR uValue = 0; while( ( *szUINT >= TEXT('0') ) && ( *szUINT <= TEXT('9') ) ) uValue = ( ( uValue * 10 ) + ( *szUINT++ - TEXT('0') ) ); return uValue; } // Local reboot and hotkey control (on Win95) static void HogMachine( BOOL value ) { BOOL dummy; // NT is always secure, therefore we don't need to call this on Cairo/NT if (fOnWin95) { SystemParametersInfo( SPI_SCREENSAVERRUNNING, value, &dummy, 0 ); } } // entry point (duh) INT_PTR PASCAL WinMainN( HINSTANCE hInst, HINSTANCE hPrev, LPTSTR szCmdLine, int nCmdShow ) { LPCTSTR pch = szCmdLine; HWND hParent = 0; OSVERSIONINFO osvi; hMainInstance = hInst; osvi.dwOSVersionInfoSize = sizeof(osvi); fOnWin95 = (GetVersionEx(&osvi) && osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS); #ifdef GL_SCRNSAVE // the shell sends this message to the foreground window before running an // AutoPlay app. we return 1 to cancel autoplay if we are password protected if (fOnWin95) { uShellAutoPlayQueryMessage = RegisterWindowMessage(TEXT("QueryCancelAutoPlay")); } else { uShellAutoPlayQueryMessage = 0; } #endif _try { for(;;) switch( *pch ) { case TEXT('S'): case TEXT('s'): return DoScreenSave( NULL ); #ifdef GL_SCRNSAVE case TEXT('W'): case TEXT('w'): do pch++; while( *pch == TEXT(' ') ); // size parameters return DoWindowedScreenSave( pch ); #endif case TEXT('L'): case TEXT('l'): // special switch for tests such as WinBench // this is NOT a hack to make bechmarks look good // it's a hack to allow you to benchmark a screen saver // many bechmarking apps require the whole screen in foreground // which makes it hard to measure how a screensaver adds CPU load // you must provide a parent window (just like preview mode) preview_like_fullscreen = TRUE; case TEXT('P'): case TEXT('p'): do pch++; while( *pch == TEXT(' ') ); // skip to the good stuff return DoSaverPreview( pch ); case TEXT('A'): case TEXT('a'): if (!fOnWin95) return -1; do pch++; while( *pch == TEXT(' ') ); // skip to the good stuff return DoChangePw( pch ); case TEXT('C'): case TEXT('c'): { HWND hwndParent = NULL ; // Look for optional parent window after the "C", // syntax is "C:hwnd_value" if (*(++pch) == TEXT(':')) { hwndParent = (HWND)atoui( ++pch ); } if (hwndParent == NULL || !IsWindow(hwndParent)) hwndParent = GetForegroundWindow(); return DoConfigBox( hwndParent ); } case TEXT('\0'): return DoConfigBox( NULL ); case TEXT(' '): case TEXT('-'): case TEXT('/'): pch++; // skip spaces and common switch prefixes break; default: return -1; } } _except(UnhandledExceptionFilter(GetExceptionInformation())) { // don't leave local reboot and hotkeys disabled on Win95 HogMachine( FALSE ); } } // default screen-saver proc, declared in SCRNSAVE.H // intended to be called by the consumer's ScreenSaverProc where // DefWindowProc would normally be called LRESULT WINAPI DefScreenSaverProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { #if DBG_MSGS TCHAR szBuff[80]; wsprintf( szBuff, TEXT("** DefSSP received:\t0x%04lx 0x%08lx 0x%08lx\n"), uMsg, wParam, lParam ); OutputDebugString(szBuff); #endif if( !fChildPreview && !fClosing ) { switch( uMsg ) { case WM_CLOSE: // Only do password check if on Windows 95. WinNT (Cairo) has // the password check built into the security desktop for // C2 compliance. if (fOnWin95) { if( !DoPasswordCheck( hWnd ) ) { GetCursorPos( &ptMouse ); // re-establish return FALSE; } } #ifdef GL_SCRNSAVE // We need to know when we're being terminated, so we can do // various clean-up stuff SendMessage( hWnd, SS_WM_CLOSING, 0, 0 ); #endif break; case SCRM_VERIFYPW: if (fOnWin95) return ( VerifyPassword? (LRESULT)VerifyPassword( hWnd ) : 1L ); break; default: { POINT ptMove, ptCheck; if( fCheckingPassword ) break; switch( uMsg ) { case WM_SHOWWINDOW: if( (BOOL)wParam ) SetCursor( NULL ); break; case WM_SETCURSOR: SetCursor( NULL ); return TRUE; case WM_MOUSEMOVE: GetCursorPos( &ptCheck ); if( ( ptMove.x = ptCheck.x - ptMouse.x ) && ( ptMove.x < 0 ) ) ptMove.x *= -1; if( ( ptMove.y = ptCheck.y - ptMouse.y ) && ( ptMove.y < 0 ) ) ptMove.y *= -1; if( ((DWORD)ptMove.x + (DWORD)ptMove.y) > dwWakeThreshold ) { PostMessage( hWnd, WM_CLOSE, 0, 0l ); ptMouse = ptCheck; } break; case WM_POWERBROADCAST: switch (wParam) { case PBT_APMRESUMECRITICAL: case PBT_APMRESUMESUSPEND: case PBT_APMRESUMESTANDBY: case PBT_APMRESUMEAUTOMATIC: // If the system is resuming from a real suspend // (as opposed to a failed suspend) deactivate // the screensaver. if ((lParam & PBTF_APMRESUMEFROMFAILURE) == 0) goto PostClose; break; default: // The standard screensaver code shuts down on // all power broadcast messages. This doesn't // make much sense, but match the behavior so // that all screensavers operate the same way. goto PostClose; } break; case WM_POWER: // a critical resume does not generate a WM_POWERBROADCAST // to windows for some reason, but it does generate an old // WM_POWER message. if (wParam == PWR_CRITICALRESUME) goto PostClose; break; case WM_ACTIVATEAPP: if( wParam ) break; case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: case WM_KEYDOWN: case WM_SYSKEYDOWN: PostClose: PostMessage( hWnd, WM_CLOSE, 0, 0l ); break; } } } } // the shell sends this message to the foreground window before running an // AutoPlay app. On Win95, we return 1 to cancel autoplay if we are password protected // On WinNT, secure screen savers run on a secure separate desktop, and will never see // this message, therefore, this code will never get executed. // BUGBUG - // On NT we don't want to take down the screen saver unless it is running // on the same desktop as the autoplay shell. There is code in the // NT autoplay shell that looks for this and does not run the app if // that is the case; however, I not positive that the uShellAutoPlayQueryMessage // will not go between desktops. (BradG assures me that it will not, but you // never know.) If secure screensavers on NT randomly close when you put // an autoplay cd in the drive, then this code should be examined closely. if ((uMsg == uShellAutoPlayQueryMessage) && uMsg) { PostMessage(hWnd, WM_CLOSE, 0, 0L); return (VerifyPassword != NULL); } return DefWindowProc( hWnd, uMsg, wParam, lParam ); } // This window procedure takes care of important stuff before calling the // consumer's ScreenSaverProc. This helps to prevent us from getting hosed by wacky consumer code. LRESULT WINAPI RealScreenSaverProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { switch( uMsg ) { case WM_CREATE: // screen saver does not need the IME if ((hInstImm = GetModuleHandle(szImmDLL)) && (ImmFnc = (IMMASSOCPROC)GetProcAddress(hInstImm,szImmFnc))) hPrevImc = ImmFnc(hWnd, (HIMC)0); // establish the mouse position GetCursorPos( &ptMouse ); if( !fChildPreview ) SetCursor( NULL ); break; case WM_DESTROY: // screen saver does not need the IME if( hInstImm && ImmFnc && hPrevImc ) ImmFnc(hWnd, hPrevImc); PostQuitMessage( 0 ); break; case WM_SETTEXT: // don't let some fool change our title // we need to be able to use FindWindow() to find running instances // of full-screen windows screen savers // NOTE: USER slams our title in during WM_NCCREATE by calling the // defproc for WM_SETTEXT directly, so the initial title will get // there. If this ever changes, we can simply set a bypass flag // during WM_NCCREATE processing. return FALSE; case WM_SYSCOMMAND: if (!fChildPreview) { switch (wParam) { case SC_NEXTWINDOW: // no Alt-tabs case SC_PREVWINDOW: // no shift-alt-tabs case SC_SCREENSAVE: // no more screensavers return FALSE; } } break; case WM_HELP: case WM_CONTEXTMENU: if( fChildPreview ) { // if we're in preview mode, pump the help stuff to our owner HWND hParent = GetParent( hWnd ); if( hParent && IsWindow( hParent ) ) PostMessage( hParent, uMsg, (WPARAM)hParent, lParam ); return TRUE; } break; case WM_TIMER: if( fClosing ) return FALSE; Sleep( 0 ); break; case WM_IME_NOTIFY: // Eat IMN_OPENSTATUSWINDOW so that the status window // isn't displayed. if (wParam == IMN_OPENSTATUSWINDOW) { return 0; } break; case WM_MOUSEMOVE: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: case WM_KEYDOWN: case WM_SYSKEYDOWN: if( fClosing ) return DefWindowProc( hWnd, uMsg, wParam, lParam ); break; case WM_PAINT: if( fClosing ) return DefWindowProc( hWnd, uMsg, wParam, lParam ); if( !fChildPreview ) SetCursor( NULL ); break; } return ScreenSaverProc( hWnd, uMsg, wParam, lParam ); } #ifdef GL_SCRNSAVE void #else static void #endif InitRealScreenSave() { #if 0 HKEY hkey; if (RegOpenKey(HKEY_CURRENT_USER, szCoolSaverHacks, &hkey) == ERROR_SUCCESS) { DWORD data, len, type; len = sizeof(data); if ((RegQueryValueEx(hkey, szMouseThreshold, NULL, &type, (LPBYTE)&data, &len) == ERROR_SUCCESS) && (type == REG_DWORD)) { dwWakeThreshold = max(dwWakeThreshold, data); } len = sizeof(data); if ((RegQueryValueEx(hkey, szPasswordDelay, NULL, &type, (LPBYTE)&data, &len) == ERROR_SUCCESS) && (type == REG_DWORD) && data) { data = min(MAX_PASSWORD_DELAY_IN_SECONDS, data); dwPasswordDelay = data * 1000; dwBlankTime = GetTickCount(); } } #endif LoadPwdDLL(); } #ifndef GL_SCRNSAVE static INT_PTR DoScreenSave( HWND hParent ) { LPCTSTR pszWindowClass = TEXT("WindowsScreenSaverClass"); LPCTSTR pszWindowTitle; WNDCLASS cls; MSG msg; UINT uStyle; UINT uExStyle; int ncx, ncy; int nx, ny; cls.hCursor = NULL; cls.hIcon = LoadIcon( hMainInstance, MAKEINTATOM( ID_APP ) ); cls.lpszMenuName = NULL; cls.lpszClassName = pszWindowClass; cls.hbrBackground = GetStockObject( BLACK_BRUSH ); cls.hInstance = hMainInstance; cls.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS | CS_OWNDC; cls.lpfnWndProc = RealScreenSaverProc; cls.cbWndExtra = 0; cls.cbClsExtra = 0; if( hParent ) { RECT rcParent; GetClientRect( hParent, &rcParent ); ncx = rcParent.right; ncy = rcParent.bottom; nx = 0; ny = 0; uStyle = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN; uExStyle = 0; fChildPreview = TRUE; pszWindowTitle = TEXT("Preview"); // MUST differ from full screen } else { HWND hOther; #ifdef SM_CXVIRTUALSCREEN nx = GetSystemMetrics( SM_XVIRTUALSCREEN ); ny = GetSystemMetrics( SM_YVIRTUALSCREEN ); ncx = GetSystemMetrics( SM_CXVIRTUALSCREEN ); ncy = GetSystemMetrics( SM_CYVIRTUALSCREEN ); if (ncx == 0 || ncy == 0) #endif { RECT rc; HDC hdc = GetDC(NULL); GetClipBox(hdc, &rc); ReleaseDC(NULL, hdc); nx = rc.left; ny = rc.top; ncx = rc.right - rc.left; ncy = rc.bottom - rc.top; } uStyle = WS_POPUP | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; uExStyle = WS_EX_TOPMOST; pszWindowTitle = TEXT("Screen Saver"); // MUST differ from preview // if there is another NORMAL screen save instance, switch to it hOther = FindWindow( pszWindowClass, pszWindowTitle ); if( hOther && IsWindow( hOther ) ) { SetForegroundWindow( hOther ); return 0; } InitRealScreenSave(); } // the shell sends this message to the foreground window before running an // AutoPlay app. we return 1 to cancel autoplay if we are password protected if (fOnWin95) { uShellAutoPlayQueryMessage = RegisterWindowMessage(TEXT("QueryCancelAutoPlay")); } else { uShellAutoPlayQueryMessage = 0; } if( RegisterClass( &cls ) ) { hMainWindow = CreateWindowEx( uExStyle, pszWindowClass, pszWindowTitle, uStyle, nx, ny, ncx, ncy, hParent, (HMENU)NULL, hMainInstance, (LPVOID)NULL ); } if( hMainWindow ) { if( !fChildPreview ) SetForegroundWindow( hMainWindow ); while( GetMessage( &msg, NULL, 0, 0 ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } // free password-handling DLL if loaded UnloadPwdDLL(); return msg.wParam; } #endif static INT_PTR DoSaverPreview( LPCTSTR szUINTHandle ) { // get parent handle from string HWND hParent = (HWND)atoui( szUINTHandle ); // only preview on a valid parent window (NOT full screen) return ( (hParent && IsWindow( hParent ))? DoScreenSave( hParent ) : -1 ); } #ifndef GL_SCRNSAVE static INT_PTR DoConfigBox( HWND hParent ) { // let the consumer register any special controls for the dialog if( !RegisterDialogClasses( hMainInstance ) ) return FALSE; return DialogBox( hMainInstance, MAKEINTRESOURCE( DLG_SCRNSAVECONFIGURE ), hParent, (DLGPROC)ScreenSaverConfigureDialog ); } #endif static INT_PTR DoChangePw( LPCTSTR szUINTHandle ) { // get parent handle from string HWND hParent = (HWND)atoui( szUINTHandle ); if( !hParent || !IsWindow( hParent ) ) hParent = GetForegroundWindow(); // allow the library to be hooked ScreenSaverChangePassword( hParent ); return 0; } static const TCHAR szMprDll[] = TEXT("MPR.DLL"); // not to be localized static const TCHAR szProviderName[] = TEXT("SCRSAVE"); // not to be localized #ifdef UNICODE static const CHAR szPwdChangePW[] = "PwdChangePasswordW"; // not to be localized #else static const CHAR szPwdChangePW[] = "PwdChangePasswordA"; // not to be localized #endif // bogus prototype typedef DWORD (FAR PASCAL *PWCHGPROC)( LPCTSTR, HWND, DWORD, LPVOID ); void WINAPI ScreenSaverChangePassword( HWND hParent ) { HINSTANCE mpr = LoadLibrary( szMprDll ); if( mpr ) { // netland hasn't cracked MNRENTRY yet PWCHGPROC pwd = (PWCHGPROC)GetProcAddress( mpr, szPwdChangePW ); if( pwd ) pwd( szProviderName, hParent, 0, NULL ); FreeLibrary( mpr ); } } static BOOL DoPasswordCheck( HWND hParent ) { // don't reenter and don't check when we've already decided if( fCheckingPassword || fClosing ) return FALSE; if( VerifyPassword ) { static DWORD lastcheck = (DWORD)-1; DWORD curtime = GetTickCount(); MSG msg; if (dwPasswordDelay && (GetElapsedTime(dwBlankTime, curtime) < dwPasswordDelay)) { fClosing = TRUE; goto _didcheck; } // no rapid checking... if ((lastcheck != (DWORD)-1) && (GetElapsedTime(lastcheck, curtime) < 200)) { goto _didcheck; } // do the check fCheckingPassword = TRUE; #ifdef GL_SCRNSAVE // Put ss in idle mode during password dialog processing SendMessage( hParent, SS_WM_IDLE, SS_IDLE_ON, 0L ); #endif // flush WM_TIMER messages before putting up the dialog PeekMessage( &msg, hParent, WM_TIMER, WM_TIMER, PM_REMOVE | PM_NOYIELD ); PeekMessage( &msg, hParent, WM_TIMER, WM_TIMER, PM_REMOVE | PM_NOYIELD ); // call the password verify proc fClosing = (BOOL)SendMessage( hParent, SCRM_VERIFYPW, 0, 0L ); fCheckingPassword = FALSE; #ifdef GL_SCRNSAVE // Restore normal display mode SendMessage( hParent, SS_WM_IDLE, SS_IDLE_OFF, 0L ); #endif if (!fClosing) SetCursor(NULL); // curtime may be outdated by now lastcheck = GetTickCount(); } else { // passwords disabled or unable to load handler DLL, always allow exit fClosing = TRUE; } _didcheck: return fClosing; } // stolen from the CRT, used to shirink our code int _stdcall DummyEntry( void ) { int i; STARTUPINFO si; LPTSTR pszCmdLine = GetCommandLine(); if ( *pszCmdLine == TEXT('\"')) { /* * Scan, and skip over, subsequent characters until * another double-quote or a null is encountered. */ while (*(pszCmdLine = CharNext(pszCmdLine)) && (*pszCmdLine != TEXT('\"')) ); /* * If we stopped on a double-quote (usual case), skip * over it. */ if ( *pszCmdLine == TEXT('\"') ) pszCmdLine++; } else { while ((UINT)*pszCmdLine > (UINT)TEXT(' ')) pszCmdLine = CharNext(pszCmdLine); } /* * Skip past any white space preceeding the second token. */ while (*pszCmdLine && ((UINT)*pszCmdLine <= (UINT)TEXT(' '))) { pszCmdLine = CharNext(pszCmdLine); } si.dwFlags = 0; GetStartupInfo(&si); i = (int)WinMainN(GetModuleHandle(NULL), NULL, pszCmdLine, si.dwFlags & STARTF_USESHOWWINDOW ? si.wShowWindow : SW_SHOWDEFAULT); ExitProcess(i); return i; // We never comes here. } // main() entry point to satisfy old NT screen savers void _cdecl main( int argc, char *argv[] ) { DummyEntry(); } // WinMain() entry point to satisfy old NT screen savers int PASCAL WinMain( HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow ) { DummyEntry(); return 0; // reference unreferenced parameters (void)hInst; (void)hPrev; (void)szCmdLine; (void)nCmdShow; } VOID LoadPwdDLL(VOID) { HKEY hKey; if (!fOnWin95) return; if (hInstPwdDLL) UnloadPwdDLL(); // look in registry to see if password turned on, otherwise don't // bother to load password handler DLL if (RegOpenKey(HKEY_CURRENT_USER,szScreenSaverKey,&hKey) == ERROR_SUCCESS) { DWORD dwVal,dwSize=sizeof(dwVal); if ((RegQueryValueEx(hKey,szPasswordActiveValue, NULL,NULL,(BYTE *) &dwVal,&dwSize) == ERROR_SUCCESS) && dwVal) { // try to load the DLL that contains password proc. hInstPwdDLL = LoadLibrary(szPwdDLL); if (hInstPwdDLL) { VerifyPassword = (VERIFYPWDPROC) GetProcAddress(hInstPwdDLL, szFnName); if( VerifyPassword ) HogMachine( TRUE ); else UnloadPwdDLL(); } } RegCloseKey(hKey); } } VOID UnloadPwdDLL(VOID) { if (!fOnWin95) return; if (hInstPwdDLL) { FreeLibrary(hInstPwdDLL); hInstPwdDLL = NULL; if( VerifyPassword ) { VerifyPassword = NULL; HogMachine( FALSE ); } } } // compatbility stuff (to make porting easier) TCHAR szAppName[ APPNAMEBUFFERLEN ]; TCHAR szName[ TITLEBARNAMELEN ]; TCHAR szIniFile[ MAXFILELEN ]; TCHAR szScreenSaver[ 22 ]; TCHAR szHelpFile[ MAXFILELEN ]; TCHAR szNoHelpMemory[ BUFFLEN ]; // Quick fix for old screen savers that don't know about context // sensitive help UINT MyHelpMessage = WM_HELP;
[ "112426112@qq.com" ]
112426112@qq.com
e36d2cf1a869617128c0c3e1b4f790a60273caf8
ee6c236ba07ddd2f1328e38f3b0a00c3eaf3a38a
/Code/server/FindingTreasure_Test_Blending_20170529/IOCP_Client.cpp
c174715e0dc501099de4667a840526a728aff394
[]
no_license
GreeeeeShot/Graduation-Work
b01b4662813a1a25a0ed82f0a43af92c38801bbc
53e2c000241b71da222d065d0697ec79b0ded65c
refs/heads/master
2021-01-11T01:55:47.025089
2017-10-18T10:25:06
2017-10-18T10:25:06
70,653,275
0
1
null
null
null
null
UTF-8
C++
false
false
6,663
cpp
#include "stdafx.h" #include "IOCP_Init.h" #include "IOCP_Client.h" #include "GameManager.h" #include "GameFramework.h" //CPlayer player; #pragma comment (lib, "ws2_32.lib") SOCKET g_mysocket; WSABUF send_wsabuf; char send_buffer[BUF_SIZE]; WSABUF recv_wsabuf; char recv_buffer[BUF_SIZE]; char packet_buffer[BUF_SIZE]; DWORD in_packet_size = 0; int saved_packet_size = 0; int g_myid; int g_left_x = 0; int g_top_y = 0; Client_Data player; void clienterror() { exit(-1); } void ProcessPacket(char *ptr) { static bool first_time = true; float x = 0, y = 0, z = 0; int id=-1; float px=0.0, py = 0.0, pz = 0.0; switch (ptr[1]) { case SC_PUT_PLAYER: { sc_packet_put_player *my_packet = reinterpret_cast<sc_packet_put_player *>(ptr); CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[my_packet->id]->SetPosition(D3DXVECTOR3(my_packet->x, my_packet->y, my_packet->z)); break; } case SC_POS: { sc_packet_pos *my_packet = reinterpret_cast<sc_packet_pos *>(ptr); //CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[my_packet->id]->SetPosition(D3DXVECTOR3(my_packet->x, my_packet->y, my_packet->z)); x = my_packet->x; z = my_packet->z; id = my_packet->id; y = my_packet->y; //y = CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[id]->GetPosition().y; //std::cout<<"Position: " << x<<", " << y << ", " << z << std::endl; //CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[id]->SetMove(x, y, z); CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[id]->SetPosition(D3DXVECTOR3(x,y, z)); break; } case SC_REMOVE_PLAYER: { sc_packet_remove_player *my_packet = reinterpret_cast<sc_packet_remove_player *>(ptr); break; } case SC_INIT: { sc_packet_init *my_packet = reinterpret_cast<sc_packet_init *>(ptr); CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_iMyPlayerID = my_packet->id; CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[my_packet->id]->SetPosition(D3DXVECTOR3(my_packet->x, my_packet->y, my_packet->z)); } /* case SC_CHAT: { sc_packet_chat *my_packet = reinterpret_cast<sc_packet_chat *>(ptr); int other_id = my_packet->id; if (other_id == g_myid) { wcsncpy_s(player.message, my_packet->message, 256); player.message_time = GetTickCount(); } else if (other_id < NPC_START) { wcsncpy_s(skelaton[other_id].message, my_packet->message, 256); skelaton[other_id].message_time = GetTickCount(); } else { wcsncpy_s(npc[other_id - NPC_START].message, my_packet->message, 256); npc[other_id - NPC_START].message_time = GetTickCount(); } break; }*/ default: printf("Unknown PACKET type [%d]\n", ptr[1]); } } void ReadPacket(SOCKET sock) { DWORD io_byte, io_flag = 0; int ret = WSARecv(sock, &recv_wsabuf, 1, &io_byte, &io_flag, NULL, NULL); if (ret) { int err_code = WSAGetLastError(); printf("Recv Error [%d]\n", err_code); } BYTE *ptr = reinterpret_cast<BYTE *>(recv_buffer); while (0 != io_byte) { if (0 == in_packet_size) in_packet_size = ptr[0]; if (io_byte + saved_packet_size >= in_packet_size) { memcpy(packet_buffer + saved_packet_size, ptr, in_packet_size - saved_packet_size); ProcessPacket(packet_buffer); ptr += in_packet_size - saved_packet_size; io_byte -= in_packet_size - saved_packet_size; in_packet_size = 0; saved_packet_size = 0; } else { memcpy(packet_buffer + saved_packet_size, ptr, io_byte); saved_packet_size += io_byte; io_byte = 0; } } } void ClientMain(HWND main_window_handle,const char* serverip) { WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); g_mysocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0); SOCKADDR_IN ServerAddr; ZeroMemory(&ServerAddr, sizeof(SOCKADDR_IN)); ServerAddr.sin_family = AF_INET; ServerAddr.sin_port = htons(MY_SERVER_PORT); ServerAddr.sin_addr.s_addr = inet_addr(serverip); int Result = WSAConnect(g_mysocket, (sockaddr *)&ServerAddr, sizeof(ServerAddr), NULL, NULL, NULL, NULL); WSAAsyncSelect(g_mysocket, main_window_handle, WM_SOCKET, FD_CLOSE | FD_READ); send_wsabuf.buf = send_buffer; send_wsabuf.len = BUF_SIZE; recv_wsabuf.buf = recv_buffer; recv_wsabuf.len = BUF_SIZE; } void SetPacket(int x,int y, int z) { cs_packet_up *my_packet = reinterpret_cast<cs_packet_up *>(send_buffer); int id = CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_iMyPlayerID; my_packet->size = sizeof(my_packet); send_wsabuf.len = sizeof(my_packet); DWORD iobyte; my_packet->Lookx = CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->GetMyPlayer()->m_CameraOperator.GetLook().x; my_packet->Lookz = CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->GetMyPlayer()->m_CameraOperator.GetLook().z; //std::cout<<"Client Look" << (float)my_packet->Lookx << ", " <<(float)my_packet->Lookz << std::endl; if (x>0) { my_packet->type = CS_RIGHT; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } if (x<0) { my_packet->type = CS_LEFT; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } if (z>0) { my_packet->type = CS_UP; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } if (z<0) { my_packet->type = CS_DOWN; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } if (y>0) { my_packet->type = CS_JUMP; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } /* if (move == X_STOP) { my_packet->type = CS_XSTOP; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } if (move == Z_STOP) { my_packet->type = CS_ZSTOP; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } }*/ }
[ "joonbum638@naver.com" ]
joonbum638@naver.com
56e617b004faee96d11dafc9165b6e986adeece0
79ce7b21cb9eead164c6df9355014d33ba9f702a
/caffe2/utils/filler.h
6dadfa69bcbed227f11a7d3c5d63769970562bbd
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
FDecaYed/pytorch
7c7d3fb762c1aae3d41ec214b44dc0b28c0e7353
a5e9500a5672595f5ee8a242a411d80adb265dd7
refs/heads/master
2021-11-18T18:21:47.397464
2018-08-29T23:38:07
2018-08-29T23:38:07
131,061,037
1
0
NOASSERTION
2021-11-09T02:58:16
2018-04-25T20:40:00
C++
UTF-8
C++
false
false
2,980
h
#ifndef CAFFE2_FILLER_H_ #define CAFFE2_FILLER_H_ #include <sstream> #include "caffe2/core/logging.h" #include "caffe2/core/tensor.h" #include "caffe2/utils/math.h" namespace caffe2 { class TensorFiller { public: template <class Type, class Context> void Fill(Tensor* tensor, Context* context) const { CAFFE_ENFORCE(context, "context is null"); CAFFE_ENFORCE(tensor, "tensor is null"); auto min = static_cast<Type>(min_); auto max = static_cast<Type>(max_); CAFFE_ENFORCE_LE(min, max); Tensor temp_tensor(shape_, Context::GetDeviceType()); tensor->swap(temp_tensor); Type* data = tensor->template mutable_data<Type>(); // TODO: Come up with a good distribution abstraction so that // the users could plug in their own distribution. if (has_fixed_sum_) { auto fixed_sum = static_cast<Type>(fixed_sum_); CAFFE_ENFORCE_LE(min * tensor->size(), fixed_sum); CAFFE_ENFORCE_GE(max * tensor->size(), fixed_sum); math::RandFixedSum<Type, Context>( tensor->size(), min, max, fixed_sum_, data, context); } else { math::RandUniform<Type, Context>(tensor->size(), min, max, data, context); } } template <class Type> TensorFiller& Min(Type min) { min_ = (double)min; return *this; } template <class Type> TensorFiller& Max(Type max) { max_ = (double)max; return *this; } template <class Type> TensorFiller& FixedSum(Type fixed_sum) { has_fixed_sum_ = true; fixed_sum_ = (double)fixed_sum; return *this; } // a helper function to construct the lengths vector for sparse features template <class Type> TensorFiller& SparseLengths(Type total_length) { return FixedSum(total_length).Min(0).Max(total_length); } // a helper function to construct the segments vector for sparse features template <class Type> TensorFiller& SparseSegments(Type max_segment) { CAFFE_ENFORCE(!has_fixed_sum_); return Min(0).Max(max_segment); } TensorFiller& Shape(const std::vector<TIndex>& shape) { shape_ = shape; return *this; } template <class Type> TensorFiller(const std::vector<TIndex>& shape, Type fixed_sum) : shape_(shape), has_fixed_sum_(true), fixed_sum_((double)fixed_sum) {} TensorFiller(const std::vector<TIndex>& shape) : shape_(shape), has_fixed_sum_(false), fixed_sum_(0) {} TensorFiller() : TensorFiller(std::vector<TIndex>()) {} std::string DebugString() const { std::stringstream stream; stream << "shape = [" << shape_ << "]; min = " << min_ << "; max = " << max_; if (has_fixed_sum_) { stream << "; fixed sum = " << fixed_sum_; } return stream.str(); } private: std::vector<TIndex> shape_; // TODO: type is unknown until a user starts to fill data; // cast everything to double for now. double min_ = 0.0; double max_ = 1.0; bool has_fixed_sum_; double fixed_sum_; }; } // namespace caffe2 #endif // CAFFE2_FILLER_H_
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
b48fbfef673cdef5f3ab4f21c1e9cb6cc05959b7
c3bbdbbbc5f47577e332a280f81bd905617423c9
/Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_MethodImpl.cpp
757871880768abc7e96d23a552e4516a6a9f379c
[ "MIT" ]
permissive
DeanRoddey/CIDLib
65850f56cb60b16a63bbe7d6d67e4fddd3ecce57
82014e064eef51cad998bf2c694ed9c1c8cceac6
refs/heads/develop
2023-03-11T03:08:59.207530
2021-11-06T16:40:44
2021-11-06T16:40:44
174,652,391
227
33
MIT
2020-09-16T11:33:26
2019-03-09T05:26:26
C++
UTF-8
C++
false
false
83,514
cpp
// // FILE NAME: CIDMacroEng_MethodImpl.cpp // // AUTHOR: Dean Roddey // // CREATED: 01/12/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements TMEngMethodImpl class. This class represents the // actual implementation of a 'method' in the macro engine system. External // methods (those handled by C++ code) can each provide a derivative of // this class and override the Invoke() method. We provide a single, generic // one that is used to do all native (opcode based) methods. It's Invoke() // override is the one that interprets opcodes. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Facility specific includes // --------------------------------------------------------------------------- #include "CIDMacroEng_.hpp" // --------------------------------------------------------------------------- // Magic RTTI macros // --------------------------------------------------------------------------- RTTIDecls(TMEngMethodImpl,TMEngNamedItem) RTTIDecls(TMEngOpMethodImpl,TMEngMethodImpl) // --------------------------------------------------------------------------- // CLASS: TMEngJumpTableItem // PREFIX: jtbli // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngJumpTableItem: Constructors and Destructor // --------------------------------------------------------------------------- TMEngJumpTableItem:: TMEngJumpTableItem( const tCIDLib::TCard4 c4IPToSet , TMEngClassVal* const pmecvToAdopt) : m_c4IP(c4IPToSet) , m_pmecvCase(pmecvToAdopt) { } TMEngJumpTableItem::~TMEngJumpTableItem() { delete m_pmecvCase; } // --------------------------------------------------------------------------- // TMEngJumpTableItem: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::ESortComps TMEngJumpTableItem::eComp( const TMEngClassVal& mecvToCheck , tCIDLib::TCard4& c4IP) const { #if CID_DEBUG_ON if (m_pmecvCase->c2ClassId() != mecvToCheck.c2ClassId()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_DifferentCaseTypes , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(m_pmecvCase->c2ClassId()) , TCardinal(mecvToCheck.c2ClassId()) ); } #endif tCIDLib::ESortComps eRet = tCIDLib::ESortComps::Equal; switch(tCIDMacroEng::EIntrinsics(mecvToCheck.c2ClassId())) { case tCIDMacroEng::EIntrinsics::Card1 : { const TMEngCard1Val& mecvThis = *static_cast<const TMEngCard1Val*>(m_pmecvCase); const TMEngCard1Val& mecvThat = static_cast<const TMEngCard1Val&>(mecvToCheck); if (mecvThis.c1Value() < mecvThat.c1Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c1Value() > mecvThat.c1Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Card2 : { const TMEngCard2Val& mecvThis = *static_cast<const TMEngCard2Val*>(m_pmecvCase); const TMEngCard2Val& mecvThat = static_cast<const TMEngCard2Val&>(mecvToCheck); if (mecvThis.c2Value() < mecvThat.c2Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c2Value() > mecvThat.c2Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Card4 : { const TMEngCard4Val& mecvThis = *static_cast<const TMEngCard4Val*>(m_pmecvCase); const TMEngCard4Val& mecvThat = static_cast<const TMEngCard4Val&>(mecvToCheck); if (mecvThis.c4Value() < mecvThat.c4Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c4Value() > mecvThat.c4Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Int1 : { const TMEngInt1Val& mecvThis = *static_cast<const TMEngInt1Val*>(m_pmecvCase); const TMEngInt1Val& mecvThat= static_cast<const TMEngInt1Val&>(mecvToCheck); if (mecvThis.i1Value() < mecvThat.i1Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.i1Value() > mecvThat.i1Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Int2 : { const TMEngInt2Val& mecvThis = *static_cast<const TMEngInt2Val*>(m_pmecvCase); const TMEngInt2Val& mecvThat= static_cast<const TMEngInt2Val&>(mecvToCheck); if (mecvThis.i2Value() < mecvThat.i2Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.i2Value() > mecvThat.i2Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Int4 : { const TMEngInt4Val& mecvThis = *static_cast<const TMEngInt4Val*>(m_pmecvCase); const TMEngInt4Val& mecvThat= static_cast<const TMEngInt4Val&>(mecvToCheck); if (mecvThis.i4Value() < mecvThat.i4Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.i4Value() > mecvThat.i4Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Char : { const TMEngCharVal& mecvThis = *static_cast<const TMEngCharVal*>(m_pmecvCase); const TMEngCharVal& mecvThat= static_cast<const TMEngCharVal&>(mecvToCheck); if (mecvThis.chValue() < mecvThat.chValue()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.chValue() > mecvThat.chValue()) eRet = tCIDLib::ESortComps::FirstGreater; break; } default : { // // It should be some enum derivative. If debugging, then use our C++ // level RTTI to insure it is. // #if CID_DEBUG_ON if (!mecvToCheck.bIsDescendantOf(TMEngEnumVal::clsThis())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_UnknownSwitchType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(mecvToCheck.c2ClassId()) ); } #endif const TMEngEnumVal& mecvThis = *static_cast<const TMEngEnumVal*>(m_pmecvCase); const TMEngEnumVal& mecvThat= static_cast<const TMEngEnumVal&>(mecvToCheck); if (mecvThis.c4Ordinal() < mecvThat.c4Ordinal()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c4Ordinal() > mecvThat.c4Ordinal()) eRet = tCIDLib::ESortComps::FirstGreater; break; } } if (eRet == tCIDLib::ESortComps::Equal) c4IP = m_c4IP; return eRet; } // --------------------------------------------------------------------------- // CLASS: TMEngJumpTable // PREFIX: jtbl // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngJumpTable: Constructors and Destructor // --------------------------------------------------------------------------- TMEngJumpTable::TMEngJumpTable() : m_c4DefIP(kCIDLib::c4MaxCard) , m_colCases(tCIDLib::EAdoptOpts::Adopt) { } TMEngJumpTable::~TMEngJumpTable() { } // --------------------------------------------------------------------------- // TMEngJumpTable: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TVoid TMEngJumpTable::AddDefaultItem(const tCIDLib::TCard4 c4IPToSet) { m_c4DefIP = c4IPToSet; } tCIDLib::TVoid TMEngJumpTable::AddItem(const tCIDLib::TCard4 c4IPToSet , TMEngClassVal* const pmecvToAdopt) { m_colCases.Add(new TMEngJumpTableItem(c4IPToSet, pmecvToAdopt)); } tCIDLib::TBoolean TMEngJumpTable::bFindMatch( const TMEngClassVal& mecvToCheck , tCIDLib::TCard4& c4IP) const { const tCIDLib::TCard4 c4Count = m_colCases.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { if (m_colCases[c4Index]->eComp(mecvToCheck, c4IP) == tCIDLib::ESortComps::Equal) return kCIDLib::True; } return kCIDLib::False; } tCIDLib::TBoolean TMEngJumpTable::bHasRequiredItems() const { return (!m_colCases.bIsEmpty() && (m_c4DefIP != kCIDLib::c4MaxCard)); } tCIDLib::TCard4 TMEngJumpTable::c4DefCaseIP() const { return m_c4DefIP; } TMEngJumpTableItem& TMEngJumpTable::jtbliAt(const tCIDLib::TCard4 c4At) { #if CID_DEBUG_ON if (c4At >= m_colCases.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_BadJmpTableIndex , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c4At) ); } #endif return *m_colCases[c4At]; } // --------------------------------------------------------------------------- // CLASS: TMEngMethodImpl // PREFIX: memeth // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngMethodImpl: Public, static methods // --------------------------------------------------------------------------- const TString& TMEngMethodImpl::strKey(const TMEngMethodImpl& memethSrc) { return memethSrc.strName(); } // --------------------------------------------------------------------------- // TMEngMethodImpl: Destructor // --------------------------------------------------------------------------- TMEngMethodImpl::~TMEngMethodImpl() { // Clean up the locals and string pool collections delete m_pcolLocalList; delete m_pcolStringPool; } // --------------------------------------------------------------------------- // TMEngMethodImpl: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TCard2 TMEngMethodImpl::c2AddLocal(const TMEngLocalInfo& meliToAdd) { // If not allocated yet, create the locals collection if (!m_pcolLocalList) m_pcolLocalList = new TLocalList(16); // Make sure we don't have one with this name already const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { if (m_pcolLocalList->objAt(c4Index).strName() == meliToAdd.strName()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_DupLocalName , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , meliToAdd.strName() ); } } facCIDMacroEng().CheckIdOverflow(c4Count, L"Locals"); // Looks ok, so take it const tCIDLib::TCard2 c2Id = tCIDLib::TCard2(c4Count); TMEngLocalInfo& meliNew = m_pcolLocalList->objAdd(meliToAdd); meliNew.c2Id(c2Id); return c2Id; } tCIDLib::TCard2 TMEngMethodImpl::c2AddString(const TString& strToAdd , const tCIDLib::TBoolean bFindDups) { // Allocate the pool collection if not already if (!m_pcolStringPool) m_pcolStringPool = new TStringPool(tCIDLib::EAdoptOpts::Adopt, 8); // // If we are to find dups, then see if we already have this string in // the pool and don't add a new copy, just give back the existing id. // if (bFindDups && !m_pcolStringPool->bIsEmpty()) { const tCIDLib::TCard4 c4Count = m_pcolStringPool->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { if (strToAdd == m_pcolStringPool->pobjAt(c4Index)->strValue()) return tCIDLib::TCard2(c4Index); } } // Create a string value object with the passed value const tCIDLib::TCard2 c2NewId(tCIDLib::TCard2(m_pcolStringPool->c4ElemCount())); TString strName(L"PoolItem"); strName.AppendFormatted(c2NewId); TMEngStringVal* pmecvNew = new TMEngStringVal ( strName , tCIDMacroEng::EConstTypes::Const , strToAdd ); // Add it, and set it's id to the next id pmecvNew->c2Id(c2NewId); m_pcolStringPool->Add(pmecvNew); return pmecvNew->c2Id(); } tCIDLib::TCard4 TMEngMethodImpl::c4LocalCount() const { // If not allocated yet, then zero definitely if (!m_pcolLocalList) return 0; return m_pcolLocalList->c4ElemCount(); } tCIDLib::TCard4 TMEngMethodImpl::c4StringCount() const { // If not allocated yet, then zero definitely if (!m_pcolStringPool) return 0; return m_pcolStringPool->c4ElemCount(); } const TMEngClassVal& TMEngMethodImpl::mecvFindPoolItem(const tCIDLib::TCard2 c2Id) const { if (!m_pcolStringPool || (c2Id >= m_pcolStringPool->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadStringPoolId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return *m_pcolStringPool->pobjAt(c2Id); } TMEngClassVal& TMEngMethodImpl::mecvFindPoolItem(const tCIDLib::TCard2 c2Id) { if (!m_pcolStringPool || (c2Id >= m_pcolStringPool->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadStringPoolId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return *m_pcolStringPool->pobjAt(c2Id); } const TMEngLocalInfo& TMEngMethodImpl::meliFind(const tCIDLib::TCard2 c2Id) const { if (!m_pcolLocalList || (c2Id >= m_pcolLocalList->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadLocalId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return m_pcolLocalList->objAt(c2Id); } TMEngLocalInfo& TMEngMethodImpl::meliFind(const tCIDLib::TCard2 c2Id) { if (!m_pcolLocalList || (c2Id >= m_pcolLocalList->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadLocalId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return m_pcolLocalList->objAt(c2Id); } const TMEngLocalInfo* TMEngMethodImpl::pmeliFind(const TString& strName) const { // If we've not allocated the collection, obviously not if (!m_pcolLocalList) return nullptr; // Make sure we don't have one with this name already const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { const TMEngLocalInfo& meliCur = m_pcolLocalList->objAt(c4Index); if (meliCur.strName() == strName) return &meliCur; } return nullptr; } TMEngLocalInfo* TMEngMethodImpl::pmeliFind(const TString& strName) { // If we've not allocated the collection, obviously not if (!m_pcolLocalList) return nullptr; // Make sure we don't have one with this name already const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { TMEngLocalInfo& meliCur = m_pcolLocalList->objAt(c4Index); if (meliCur.strName() == strName) return &meliCur; } return nullptr; } tCIDLib::TVoid TMEngMethodImpl::PushLocals(TCIDMacroEngine& meOwner) { // If not allocated yet, create the locals collection if (!m_pcolLocalList) m_pcolLocalList = new TLocalList(16); const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { TMEngLocalInfo& meliCur = m_pcolLocalList->objAt(c4Index); // // Look up the type of this parm and create a value. // // <TBD> We cannot use pool values for locals, because the negate // opcode will convert a non-const pool value in place instead // of replacing it. We have to have some way to say it's a pool // value, so it get's cleaned up ok, but also say it's a local // so that it get's treated correctly. // // For now, we just create a new object for all locals. // const tCIDLib::TCard2 c2Id = meliCur.c2ClassId(); TMEngClassVal* pmecvLocal = meOwner.meciFind(c2Id).pmecvMakeStorage ( meliCur.strName(), meOwner, meliCur.eConst() ); meOwner.PushValue(pmecvLocal, tCIDMacroEng::EStackItems::Local); } } // --------------------------------------------------------------------------- // TMEngMethodImpl: Hidden Constructors // --------------------------------------------------------------------------- TMEngMethodImpl::TMEngMethodImpl(const TString& strName , const tCIDLib::TCard2 c2MethodId) : TMEngNamedItem(strName, c2MethodId) , m_pcolLocalList(nullptr) , m_pcolStringPool(nullptr) { } // --------------------------------------------------------------------------- // CLASS: TMEngOpMethodImpl // PREFIX: memeth // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Constructors and Destructor // --------------------------------------------------------------------------- TMEngOpMethodImpl::TMEngOpMethodImpl(const TString& strName , const tCIDLib::TCard2 c2MethodId) : TMEngMethodImpl(strName, c2MethodId) , m_colOpCodes(128) , m_pjtblSwitches(nullptr) { } TMEngOpMethodImpl::~TMEngOpMethodImpl() { // Delete the jump table list if we have one try { delete m_pjtblSwitches; } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } catch(...) { } } // --------------------------------------------------------------------------- // TMEngMethodImpl: Public operators // --------------------------------------------------------------------------- const TMEngOpCode& TMEngOpMethodImpl::operator[](const tCIDLib::TCard4 c4Index) const { if (c4Index >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4Index) ); } return m_colOpCodes[c4Index]; } TMEngOpCode& TMEngOpMethodImpl::operator[](const tCIDLib::TCard4 c4Index) { if (c4Index >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4Index) ); } return m_colOpCodes[c4Index]; } // --------------------------------------------------------------------------- // TMEngOpMethodImpl: Public, inherited methods // --------------------------------------------------------------------------- tCIDLib::TVoid TMEngOpMethodImpl::Invoke( TMEngClassVal& mecvInstance , const TMEngClassInfo& meciTarget , const TMEngMethodInfo& methiThis , TCIDMacroEngine& meOwner) { // // Remember the stack top upon entry. If we throw out of here, we have // to remember to clean up back to there again. // const tCIDLib::TCard4 c4BasePointer = meOwner.c4StackTop(); // // We have two levels of exception handling, one for exceptions coming out of // a called method and one that occurs within the current method. We need // to know that the inner one was done, so that we don't do some redundant // work on the second one after the inner rethrows. // tCIDLib::TBoolean bThrowReported = kCIDLib::False; // // Get a pointer to the debugger interface. The macro engine owns this, // so we just get a pointer to avoid having to call his getter over and // over. We'll call back on this every time we hit a line opcode. It will // usually be zero, in which case we do nothing with it. // MMEngDebugIntf* pmedbgToCall = meOwner.pmedbgToUse(); #if CID_DEBUG_ON tCIDLib::TBoolean bDoDump = kCIDLib::False; if (bDoDump) { DumpOpCodes(*meOwner.pstrmConsole(), meOwner); meOwner.pstrmConsole()->Flush(); } #endif // // If we have any locals, then push them now. Their ids are relative // to the base pointer we stored above. // if (c4LocalCount()) { PushLocals(meOwner); // If we have a debug callback, tell him new locals were created if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::True); } // // And now let's enter the opcode processing loop. We process opcodes // in the order found, except when we hit jump opcodes. If we hit the // end of the opcodes or we hit a return opcode, we will break out. // try { // We need an index, which is our 'instruction pointer' tCIDLib::TCard4 c4IP = 0; // // Remember the opcode count. If we get to this, then we are at // the end of the method. // const tCIDLib::TCard4 c4EndIndex = m_colOpCodes.c4ElemCount(); tCIDLib::TBoolean bDone = kCIDLib::False; tCIDLib::TBoolean bNoIncIP = kCIDLib::False; while (!bDone) { // Get the current opcode const TMEngOpCode& meopCur = m_colOpCodes[c4IP]; switch(meopCur.eOpCode()) { case tCIDMacroEng::EOpCodes::CallExcept : case tCIDMacroEng::EOpCodes::CallLocal : case tCIDMacroEng::EOpCodes::CallMember : case tCIDMacroEng::EOpCodes::CallParent : case tCIDMacroEng::EOpCodes::CallParm : case tCIDMacroEng::EOpCodes::CallStack : case tCIDMacroEng::EOpCodes::CallThis : { TMEngClassVal* pmecvTarget = nullptr; const TMEngClassInfo* pmeciTarget = nullptr; tCIDLib::TCard2 c2MethId = kCIDMacroEng::c2BadId; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallExcept) { pmecvTarget = &meOwner.mecvExceptionThrown(); pmeciTarget = &meOwner.meciFind(pmecvTarget->c2ClassId()); c2MethId = meopCur[0]; } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallStack) { pmecvTarget = &meOwner.mecvStackAt ( meOwner.c4StackTop() - meopCur[0] ); pmeciTarget = &meOwner.meciFind(pmecvTarget->c2ClassId()); c2MethId = meopCur[1]; } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallThis) { pmecvTarget = &mecvInstance; pmeciTarget = &meciTarget; c2MethId = meopCur[0]; } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallParent) { pmecvTarget = &mecvInstance; pmeciTarget = &meOwner.meciFind(meciTarget.c2ParentClassId()); c2MethId = meopCur[0]; } else { // // The first index is the id of the member, local, or // parm that the call is being made against. So, // according to the opcode, look up the target value // object. // if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallLocal) { // // The local ids are relative to the base pointer // for our stack frame. // pmecvTarget = &meOwner.mecvStackAt ( c4BasePointer + meopCur[0] ); } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallMember) { // Get the indicated member, in the first index pmecvTarget = &mecvInstance.mecvFind(meopCur[0], meOwner); } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallParm) { // It's a parm already on the stack pmecvTarget = &meOwner.mecvStackAt ( (c4BasePointer - (methiThis.c4ParmCount() + 1)) + meopCur[0] ); } else { // Not a known target type, so throw facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_UnknownCallType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Unknown , TInteger(tCIDLib::i4EnumOrd(meopCur.eOpCode())) ); // Won't happen but makes analyzer happy break; } // Get the class info for the class of the target pmeciTarget = &meOwner.meciFind(pmecvTarget->c2ClassId()); c2MethId = meopCur[1]; } // // And invoke it. The parameters are on the call stack, // but we have to push the method onto the call stack // before invoking it. // try { // // Push a call item on the stack and if we have a debugger // installed, let it know about the change. // meOwner.meciPushMethodCall ( pmeciTarget->c2Id() , c2MethId , &meciTarget , this , &methiThis , &mecvInstance , meOwner.c4CurLine() , c4IP ); if (pmedbgToCall) pmedbgToCall->CallStackChange(); // // Looks ok, so call the class with the instance and // method info. It will pass it on to the appropriate // method. // // If we are doing a parent call, that's a monomorphic // dispatch, else do polymorphic to go to the most // derived. // tCIDMacroEng::EDispatch eDispatch = tCIDMacroEng::EDispatch::Poly; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallParent) eDispatch = tCIDMacroEng::EDispatch::Mono; pmeciTarget->Invoke(meOwner, *pmecvTarget, c2MethId, eDispatch); // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); } catch(TError& errToCatch) { // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (facCIDMacroEng().bLogFailures() && !meOwner.bInIDE()) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ExceptionFrom , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::AppStatus , pmeciTarget->strClassPath() , pmeciTarget->methiFind(c2MethId).strName() ); } // If the error itself hasn't been logged, then do it if (facCIDMacroEng().bShouldLog(errToCatch)) TModule::LogEventObj(errToCatch); // Let the error handler know about it, if not already if (!errToCatch.bReported()) meOwner.Exception(errToCatch); bThrowReported = kCIDLib::True; errToCatch.AddStackLevel(CID_FILE, CID_LINE); throw; } catch(const TDbgExitException&) { // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); // Just rethrow. We are being forced down throw; } catch(const TExceptException&) { // // The called method threw a macro level exception // and didn't handle it. So we need to see if we // have a handler. If so, jump to the catch block, // else, rethrow. // tCIDLib::TCard4 c4New = 0; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) throw; // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); if (pmedbgToCall) pmedbgToCall->CallStackChange(); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } catch(...) { // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (facCIDMacroEng().bLogFailures()) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_UnknownExceptFrom , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus , pmeciTarget->strClassPath() , pmeciTarget->methiFind(c2MethId).strName() ); } // Tell the engine about it meOwner.UnknownException(); bThrowReported = kCIDLib::True; throw; } break; } case tCIDMacroEng::EOpCodes::ColIndex : { // // The top of stack is an index value, and the one before // that is a collection object. // const tCIDLib::TCard4 c4Top = meOwner.c4StackTop(); TMEngClassVal& mecvIndex = meOwner.mecvStackAt(c4Top - 1); TMEngClassVal& mecvCollect = meOwner.mecvStackAt(c4Top - 2); #if CID_DEBUG_ON if (!mecvCollect.bIsDescendantOf(TMEngCollectVal::clsThis())) { TMEngClassInfo& meciCol = meOwner.meciFind(mecvCollect.c2ClassId()); facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_NotCollectionType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::TypeMatch , meciCol.strClassPath() ); } #endif // // Cast the value object to the (C++ level) base collection // value class, and ask it to get us the object at the // indicated index. // // It will throw a macro level index error if the index is // not good. // try { TMEngCollectVal& mecvActual ( static_cast<TMEngCollectVal&>(mecvCollect) ); TMEngClassVal* pmecvElem ( mecvActual.pmecvGetAt(meOwner, mecvIndex) ); // Pop the two values off the stack top meOwner.MultiPop(2); // And push the new value meOwner.PushValue(pmecvElem, tCIDMacroEng::EStackItems::ColElem); } catch(const TExceptException&) { // Do the macro level try/catch handling tCIDLib::TCard4 c4New = 0; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) throw; // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } break; }; case tCIDMacroEng::EOpCodes::Copy : { const tCIDLib::TCard4 c4Top = meOwner.c4StackTop(); TMEngClassVal& mecvSrc = meOwner.mecvStackAt(c4Top - 1); TMEngClassVal& mecvTar = meOwner.mecvStackAt(c4Top - 2); if (meOwner.bValidation()) { TMEngClassInfo& meciSrc = meOwner.meciFind(mecvSrc.c2ClassId()); TMEngClassInfo& meciTar = meOwner.meciFind(mecvTar.c2ClassId()); if (!meciSrc.bIsCopyable() || !meciTar.bIsCopyable()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcRT_BadCopyOpParms , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::TypeMatch , meciSrc.strClassPath() , meciTar.strClassPath() ); } } // If the source and target are not the same, do the copy if (&mecvSrc != &mecvTar) mecvTar.CopyFrom(mecvSrc, meOwner); // And pop them both off meOwner.MultiPop(2); break; } case tCIDMacroEng::EOpCodes::CondEnumInc : case tCIDMacroEng::EOpCodes::ResetEnum : { // // The top of stack must be an enumerated object. We will // look at it and if it is not at it's max, we will // increment it, else we'll do nothing. We leave a boolean // value on the stack to indicate whether we incremented // it or not. // TMEngClassVal& mecvTop = meOwner.mecvStackAtTop(); // If validating, make sure it's an enum if (meOwner.bValidation()) { if (!meOwner.bIsDerivedFrom(mecvTop.c2ClassId() , tCIDMacroEng::EIntrinsics::Enum)) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_WrongStackTopType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TString(L"enumerated") , meOwner.strClassPathForId(mecvTop.c2ClassId()) ); } if (mecvTop.bIsConst()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_NotNConstStackItem , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TString(L"enumerated") ); } } TMEngEnumVal& mecvEnum = static_cast<TMEngEnumVal&>(mecvTop); if (tCIDMacroEng::EOpCodes::CondEnumInc == meopCur.eOpCode()) { if (mecvEnum.bAtMax()) { meOwner.PushBoolean(kCIDLib::False, tCIDMacroEng::EConstTypes::Const); } else { mecvEnum.Increment(); meOwner.PushBoolean(kCIDLib::True, tCIDMacroEng::EConstTypes::Const); } } else { mecvEnum.c4Ordinal(0); } break; } case tCIDMacroEng::EOpCodes::CondJump : { // // The top of stack is a boolean value. We get it's // value then pop it. Then we either jump or not // depending on it's value and whether we are a jump // not jump. // tCIDLib::TBoolean bJump = meOwner.bStackValAt ( meOwner.c4StackTop() - 1 ); meOwner.PopTop(); // If we need to jump, the new IP is in an immedate if (bJump) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::CondJumpNP : { // If we need to jump, the new IP is in an immedate if (meOwner.bStackValAt(meOwner.c4StackTop() - 1)) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::CurLine : { // Just store the line number stored meOwner.c4CurLine(meopCur.c4Immediate()); // // If we have a debugger installed, then we need to // call it and take action based on what it returns. // if (pmedbgToCall) { tCIDMacroEng::EDbgActs eAct = pmedbgToCall->eAtLine ( meciTarget , methiThis , *this , mecvInstance , meopCur.c4Immediate() , c4IP ); // // If he tells us to exit, then throw an exception // that will dump us back to the top level, who will // tell the debugger we've exited. // if ((eAct == tCIDMacroEng::EDbgActs::CloseSession) || (eAct == tCIDMacroEng::EDbgActs::Exit)) { throw TDbgExitException(eAct); } } break; } case tCIDMacroEng::EOpCodes::EndTry : { // // The top of stack must be a try item, which we want // to pop. If validating, then check it. // if (meOwner.bValidation()) { if (meOwner.mecsiTop().eType() != tCIDMacroEng::EStackItems::Try) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ExpectedTry , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(meOwner.c4CurLine()) , meciTarget.strClassPath() ); } } meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::FlipTop : { // Just ask the engine to flip the top two stack items meOwner.FlipStackTop(); break; } case tCIDMacroEng::EOpCodes::Jump : { // Get the new IP out const tCIDLib::TCard4 c4New = meopCur.c4Immediate(); // // If debugging, make sure that we aren't going to jump // out of the valid range. // if (c4New >= c4EndIndex) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadJump , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(c4IP) , meciTarget.strClassPath() , strName() ); } // Looks ok, so set it c4IP = c4New; bNoIncIP = kCIDLib::True; break; } case tCIDMacroEng::EOpCodes::LogicalAnd : case tCIDMacroEng::EOpCodes::LogicalOr : case tCIDMacroEng::EOpCodes::LogicalXor : { // Get the two top items as booleans tCIDLib::TBoolean bFirst = meOwner.bStackValAt ( meOwner.c4StackTop() - 1 ); tCIDLib::TBoolean bSecond = meOwner.bStackValAt ( meOwner.c4StackTop() - 2 ); // Do the indicated operation if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::LogicalAnd) bFirst &= bSecond; else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::LogicalOr) bFirst |= bSecond; else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::LogicalXor) bFirst ^= bSecond; // Now pop the top two items off meOwner.MultiPop(2); // And put our new result on the top meOwner.PushBoolean(bFirst, tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::MultiPop : { meOwner.MultiPop(meopCur.c4Immediate()); break; } case tCIDMacroEng::EOpCodes::Negate : { // // The top of stack must be a boolean value. We have // to pop it and push back the negated version We // cannot modify the value on the stack itself, even if // a temp, since it may be referred to again later. // TMEngCallStackItem& mecsiTop = meOwner.mecsiTop(); if (meOwner.bValidation()) { if (mecsiTop.mecvPushed().c2ClassId() != tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Boolean)) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_NotStackItemType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , meOwner.strClassPathForId(tCIDMacroEng::EIntrinsics::Boolean) ); } } TMEngBooleanVal& mecvTop = static_cast<TMEngBooleanVal&> ( mecsiTop.mecvPushed() ); const tCIDMacroEng::EConstTypes eConst = mecvTop.eConst(); const tCIDLib::TBoolean bSave = !mecvTop.bValue(); meOwner.PopTop(); meOwner.PushBoolean(bSave, eConst); break; } case tCIDMacroEng::EOpCodes::NoOp : // Do nothing break; case tCIDMacroEng::EOpCodes::NotCondJump : { // // The top of stack is a boolean value. We get it's // value then pop it. Then we either jump or not // depending on it's value and whether we are a jump // not jump. // tCIDLib::TBoolean bJump = meOwner.bStackValAt ( meOwner.c4StackTop() - 1 ); meOwner.PopTop(); // If we need to jump, the new IP is in an immedate if (!bJump) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::NotCondJumpNP : { if (!meOwner.bStackValAt(meOwner.c4StackTop() - 1)) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::PopTop : { // Just pop the stack meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::PopToReturn : { // // Get the value on the top of the stack, and copy it to // the return value object. If debugging, make sure that // the types are the same and that the type is copyable. // TMEngClassVal& mecvTop = meOwner.mecvStackAtTop(); TMEngClassVal& mecvRet = meOwner.mecvStackAt ( c4BasePointer - (methiThis.c4ParmCount() + 2) ); mecvRet.CopyFrom(mecvTop, meOwner); meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::PushCurLine : { meOwner.PushCard4(meOwner.c4CurLine(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushEnum : { meOwner.PushEnum(meopCur[0], meopCur[1], tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushException : { meOwner.PushException(); break; } case tCIDMacroEng::EOpCodes::PushImBoolean : { meOwner.PushBoolean(meopCur.bImmediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard1 : { meOwner.PushCard1(meopCur.c1Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard2 : { meOwner.PushCard2(meopCur.c2Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard4 : { meOwner.PushCard4(meopCur.c4Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard8 : { meOwner.PushCard8(meopCur.c8Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImChar : { meOwner.PushChar(meopCur.chImmediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImFloat4 : { meOwner.PushFloat4(meopCur.f4Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImFloat8 : { meOwner.PushFloat8(meopCur.f8Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImInt1 : { meOwner.PushInt1(meopCur.i1Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImInt2 : { meOwner.PushInt2(meopCur.i2Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImInt4 : { meOwner.PushInt4(meopCur.i4Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushLocal : { // // The first index is the index of the local. In this // case, we are repushing a value already on the stack. // The offset of the local relative to the base pointer // is in the immediate field. // meOwner.RepushAt(c4BasePointer + meopCur[0]); break; } case tCIDMacroEng::EOpCodes::PushMember : { // The first index is the index of the member meOwner.PushValue ( &mecvInstance.mecvFind(meopCur[0], meOwner) , tCIDMacroEng::EStackItems::Member ); break; } case tCIDMacroEng::EOpCodes::PushParm : { // // The first index is the id of the parameter. In this // case, we are just repushing a value already on the // stack as a parameter. Subtracting the parm count plus // one get's us to the first parm. Then we add the parm // id minus one (they are 1 based) to get to the actual // value. // meOwner.RepushAt ( (c4BasePointer - (methiThis.c4ParmCount() + 1)) + meopCur[0] ); break; } case tCIDMacroEng::EOpCodes::PushStrPoolItem : { // Just push the pool item meOwner.PushValue ( &mecvFindPoolItem(meopCur[0]) , tCIDMacroEng::EStackItems::StringPool ); break; } case tCIDMacroEng::EOpCodes::PushTempConst : { // // The c2Immediate field holds the id of the type to push. // meOwner.PushPoolValue(meopCur.c2Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushTempVar : { // // The c2Immediate field holds the id of the type to push. // The context object has a method to push a value of a // give type id onto the stack from the temp pool. // meOwner.PushPoolValue ( meopCur.c2Immediate() , tCIDMacroEng::EConstTypes::NonConst ); break; } case tCIDMacroEng::EOpCodes::PushThis : { meOwner.PushValue(&mecvInstance, tCIDMacroEng::EStackItems::This); break; } case tCIDMacroEng::EOpCodes::Return : { // // There can be try blocks still on the stack at this // point, so we have to remove them. Any return value has // been extracted at this point, so there should only be // tries above the current base pointer. // tCIDLib::TCard4 c4New = 0; while (kCIDLib::True) { const tCIDLib::TCard4 c4PopTo = meOwner.c4FindNextTry(c4New); if ((c4PopTo == kCIDLib::c4MaxCard) || (c4PopTo < c4BasePointer)) { break; } // We found one in our method scope, so pop back to there meOwner.PopBackTo(c4PopTo); } // Break out of this method bDone = kCIDLib::True; break; } case tCIDMacroEng::EOpCodes::TableJump : { // // This is an indirect table jump, probably for a switch // statement. The first index indicates index of the // jump table that we are to use. // TMEngJumpTable& jtblToUse = jtblById(meopCur[0]); // // The value to switch on must be no the top of the stack, // so get it and ask the table which one matches it. // TMEngClassVal& mecvCase = meOwner.mecvStackAtTop(); // // Look this guy up. Note that if it doesn't match, // we will use the deafult. // tCIDLib::TCard4 c4New; if (!jtblToUse.bFindMatch(mecvCase, c4New)) c4New = jtblToUse.c4DefCaseIP(); // We can trash the stack top now meOwner.PopTop(); // And set the IP to the IP of the target case block bNoIncIP = kCIDLib::True; c4IP = c4New; break; } case tCIDMacroEng::EOpCodes::Throw : { // // This can be either a throw, or a rethrow, according // to the immediate boolean value. If a throw, then // get the exception info set. // // There must be an enumerated type on the stack, which // is the error to throw. We will use this to set up an // exception instance that we keep around for this // purpose. // if (!meopCur.bImmediate()) { TMEngEnumVal& mecvErr = meOwner.mecvStackAtTopAs<TMEngEnumVal>(); TMEngEnumInfo& meciErr = static_cast<TMEngEnumInfo&> ( meOwner.meciFind(mecvErr.c2ClassId()) ); // And now we can set the exception info meOwner.SetException ( mecvErr.c2ClassId() , meciTarget.strClassPath() , mecvErr.c4Ordinal() , meciErr.strFullName(mecvErr) , meciErr.strTextValue(mecvErr) , meOwner.c4CurLine() ); } // // Look for the next try block up the call chain. If it // isn't within our call frame, then we throw a special // C++ exception to cause the propogation. Else, we will // unwind the stack back to (and including) the try // block, and jump to the offset that it indicates it's // catch block is at. // tCIDLib::TCard4 c4New; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) { throw TExceptException(); } else { // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } break; } case tCIDMacroEng::EOpCodes::ThrowFmt : { // // This is a special form of throw that is used to // pass in values to be used to replace tokens in the // error text. c4Immediate indicates how many of them // there are, pushed after the error enum. So start // off by getting the error enum out, and get the // text that we will format tokens into. // TMEngEnumVal& mecvErr = meOwner.mecvStackAtAs<TMEngEnumVal> ( meOwner.c4StackTop() - (1 + meopCur.c4Immediate()) ); TMEngEnumInfo& meciErr = static_cast<TMEngEnumInfo&> ( meOwner.meciFind(mecvErr.c2ClassId()) ); TString strText(meciErr.strTextValue(mecvErr), 128); // // Now, according to how many tokens indicated in the // immediate value, work down and format each one and // replace that tokens. This requires a bit of code to // do, so we call a helper method to do it. // FormatErrTokens ( meOwner , meopCur.c4Immediate() , strText ); // And now we can set the exception info meOwner.SetException ( mecvErr.c2ClassId() , meciTarget.strClassPath() , mecvErr.c4Ordinal() , meciErr.strFullName(mecvErr) , strText , meOwner.c4CurLine() ); // // Look for the next try block up the call chain. If it // isn't within our call frame, then we throw a special // C++ exception to cause the propogation. Else, we will // unwind the stack back to (and including) the try // block, and jump to the offset that it indicates it's // catch block is at. // tCIDLib::TCard4 c4New; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) { throw TExceptException(); } else { // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } break; } case tCIDMacroEng::EOpCodes::Try : { // // We need to push a try block on the stack. The opcode // has the IP of the start of the catch block in the // c4Immediate field, which we need to push along with it. // meOwner.PushTry(meopCur.c4Immediate()); break; } case tCIDMacroEng::EOpCodes::TypeCast : { // // The first index is the type to cast to. The value to // cast is on the top of stack, and must be a numeric or // enumerated type, as must be the type to cast to. // // So we need to get the value on the top of the stack, // convert it to the cast type, pop the old value off, // and replace it with a new value from the temp pool. // TMEngClassVal& mecvToCast = meOwner.mecvStackAtTop(); // Push a temp pool value of the target type meOwner.PushPoolValue ( meopCur.c2Immediate(), tCIDMacroEng::EConstTypes::Const ); TMEngClassVal& mecvTmp = meOwner.mecvStackAtTop(); // And ask the temp object to cast from the stack top value TMEngClassInfo& meciTarType = meOwner.meciFind(meopCur.c2Immediate()); const tCIDMacroEng::ECastRes eRes = meciTarType.eCastFrom ( meOwner, mecvToCast, mecvTmp ); if (eRes == tCIDMacroEng::ECastRes::Incompatible) { // This should have been checked up front facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcPrs_CannotCast , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , meOwner.strClassPathForId(mecvToCast.c2ClassId()) , meciTarType.strClassPath() ); } // Flip and pop the original off meOwner.FlipStackTop(); meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::None : { // // We shouldn't be see this one in the opcode stream // because it's just a place holder for internal use. // facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_NoneOpCode , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format , TCardinal(meOwner.c4CurLine()) , meciTarget.strClassPath() , strName() ); break; } default : { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_UnknownOpCode , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format , TInteger(tCIDLib::i4EnumOrd(meopCur.eOpCode())) , TCardinal(meOwner.c4CurLine()) , meciTarget.strClassPath() , strName() ); break; } } // Move forward to the next opcode if (bNoIncIP) bNoIncIP = kCIDLib::False; else c4IP++; // If at the end, we are done if (c4IP == c4EndIndex) break; } } catch(TError& errToCatch) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (!bThrowReported) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ExceptionIn , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus , meciTarget.strClassPath() , strName() ); // If the error itself hasn't been logged, then do it if (facCIDMacroEng().bShouldLog(errToCatch)) TModule::LogEventObj(errToCatch); // Let the engine know about it, if not already, then rethrow if (errToCatch.bReported()) meOwner.Exception(errToCatch); } errToCatch.AddStackLevel(CID_FILE, CID_LINE); throw; } catch(const TDbgExitException&) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); throw; } catch(const TExceptException&) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); throw; } catch(...) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (!bThrowReported) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_UnknownExceptIn , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus , meciTarget.strClassPath() , strName() ); // Tell the engine about it and then rethrow meOwner.UnknownException(); } throw; } // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); } // --------------------------------------------------------------------------- // TMEngOpMethodImpl: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TMEngOpMethodImpl::bMoreLines(const tCIDLib::TCard4 c4LastIP) const { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); for (tCIDLib::TCard4 c4Index = c4LastIP + 1; c4Index < c4Count; c4Index++) { const TMEngOpCode& meopCur = m_colOpCodes[c4Index]; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CurLine) { // // Check to see if the next opcode is the last one and a no-op. // If so, then this line is the one on the EndMethod, which is // really past the end of the method from a call stack point of // view, so we'll return false if so. // if ((c4Index + 2 == c4Count) && (m_colOpCodes[c4Index + 1].eOpCode() == tCIDMacroEng::EOpCodes::NoOp)) { return kCIDLib::False; } return kCIDLib::True; } } return kCIDLib::False; } tCIDLib::TCard2 TMEngOpMethodImpl::c2AddJumpTable() { if (!m_pjtblSwitches) m_pjtblSwitches = new TMEngJumpTableTable(tCIDLib::EAdoptOpts::Adopt); const tCIDLib::TCard4 c4Ret = m_pjtblSwitches->c4ElemCount(); m_pjtblSwitches->Add(new TMEngJumpTable); return tCIDLib::TCard2(c4Ret); } tCIDLib::TCard4 TMEngOpMethodImpl::c4AddOpCode(const TMEngOpCode& meopToAdd) { // // Add this opcode and return the index of the opcode, which is the // current (pre-addition) count. // tCIDLib::TCard4 c4Ret = m_colOpCodes.c4ElemCount(); m_colOpCodes.objAdd(meopToAdd); return c4Ret; } tCIDLib::TCard4 TMEngOpMethodImpl::c4CurOffset() const { return m_colOpCodes.c4ElemCount(); } tCIDLib::TCard4 TMEngOpMethodImpl::c4FirstLineNum() const { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { const TMEngOpCode& meopCur = m_colOpCodes[c4Index]; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CurLine) return meopCur.c4Immediate(); } // Just return 1, since we didn't find any current line opcodes return 1; } tCIDLib::TVoid TMEngOpMethodImpl::DumpOpCodes( TTextOutStream& strmTarget , const TCIDMacroEngine& meOwner) const { const TTextOutStream::Width widNums(4); const TTextOutStream::Width widZero(0); TStreamJanitor janStream(&strmTarget); const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmTarget << widNums << c4Index << widZero << L"- "; m_colOpCodes[c4Index].Format(strmTarget, meOwner); strmTarget << kCIDLib::NewLn; } } TMEngJumpTable& TMEngOpMethodImpl::jtblById(const tCIDLib::TCard2 c2Id) { // Make sure this index is valid if (!m_pjtblSwitches || (c2Id >= m_pjtblSwitches->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadJumpTableId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return *m_pjtblSwitches->pobjAt(c2Id); } const TMEngOpCode& TMEngOpMethodImpl::meopAt(const tCIDLib::TCard4 c4At) const { if (c4At >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4At) ); } return m_colOpCodes[c4At]; } TMEngOpCode& TMEngOpMethodImpl::meopAt(const tCIDLib::TCard4 c4At) { if (c4At >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4At) ); } return m_colOpCodes[c4At]; } const TMEngOpCode& TMEngOpMethodImpl::meopLast() const { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); if (!c4Count) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TInteger(0) ); } return m_colOpCodes[c4Count - 1]; } TMEngOpCode& TMEngOpMethodImpl::meopLast() { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); if (!c4Count) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TInteger(0) ); } return m_colOpCodes[c4Count - 1]; } // --------------------------------------------------------------------------- // TMEngOpMethodImpl: Private, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TVoid TMEngOpMethodImpl::FormatErrTokens( TCIDMacroEngine& meOwner , const tCIDLib::TCard4 c4Tokens , TString& strToFill) { // Create a macro level string out stream TMEngClassInfo& meciStrm = meOwner.meciFind ( tCIDMacroEng::EIntrinsics::StringOutStream ); TMEngTextOutStreamVal* pmecvStrm = static_cast<TMEngTextOutStreamVal*> ( meciStrm.pmecvMakeStorage ( L"TempStream" , meOwner , tCIDMacroEng::EConstTypes::NonConst ) ); TJanitor<TMEngTextOutStreamVal> janStream(pmecvStrm); // // Give it a stream, since we won't be constructing it at the macro // language level, which normally is how it gets one. // TTextStringOutStream* pstrmTarget = new TTextStringOutStream(1024UL); pmecvStrm->SetStream(pstrmTarget, tCIDLib::EAdoptOpts::Adopt); tCIDLib::TCh chToken(kCIDLib::chDigit1); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Tokens; c4Index++) { // // Get the current formattable object. One gets us down to the actual // top item, then add the current index to get to the current one. // TMEngFormattableVal& mecvCur = meOwner.mecvStackAtAs<TMEngFormattableVal> ( (meOwner.c4StackTop() - c4Tokens) + c4Index ); TMEngClassInfo& meciTarget = meOwner.meciFind(mecvCur.c2ClassId()); // // Generate a macro level call to format this guy to the stream. Tell // the call stack that the stream is a 'repush', though its not, so // that it won't try to delete it on us. // meOwner.PushPoolValue(tCIDMacroEng::EIntrinsics::Void, tCIDMacroEng::EConstTypes::Const); meOwner.PushValue(pmecvStrm, tCIDMacroEng::EStackItems::Parm, kCIDLib::True); meOwner.meciPushMethodCall ( meciTarget.c2Id() , TMEngFormattableInfo::c2FormatToId() ); meciTarget.Invoke ( meOwner , mecvCur , TMEngFormattableInfo::c2FormatToId() , tCIDMacroEng::EDispatch::Poly ); // // We cheated this one, so we have to pop the method item as well // the parm and return! // meOwner.MultiPop(3); // And now replace the current token with this result. Flush first! pmecvStrm->Flush(); strToFill.eReplaceToken(pstrmTarget->strData(), chToken); // And reset it for the next round pstrmTarget->Reset(); // Move up to the next token digit chToken++; } }
[ "droddey@charmedquark.com" ]
droddey@charmedquark.com
2c064cb569c3e2789098a813f1c039e89f2e819f
b067b1fc5239eaf4354871dcb9d64f10901af2a8
/Labor_4/L4_A4/Circle.cpp
9220fc9696c532b5bcbe51b79b2318fc4b79b73f
[]
no_license
Dream-Dev-Team/Labor_OOS1
37d9282de9da0d87745a63ac91d917e06d74e45b
cf6c6679acaf4a4844f8955896af16e2b2b7229d
refs/heads/master
2022-11-26T01:44:59.534960
2020-07-24T08:39:20
2020-07-24T08:39:20
261,707,092
2
1
null
null
null
null
UTF-8
C++
false
false
1,225
cpp
#include "Circle.hpp" extern bool debugConstructor; Circle::Circle(Point p, double r) { if (debugConstructor) { cout << "Konstruktor der Klasse Circle(param), Objekt:" << this->getID() << endl; } centre = p; radius = r; } Circle::Circle(string str) { if (debugConstructor) { cout << "Konstruktor der Klasse Circle(convert), Objekt:" << this->getID() << endl; } radius = 0; istringstream ss(str); ss >> *this; } const Point& Circle::getCentre() const { return centre; } double Circle::getRadius() const { return radius; } void Circle::setCentre(Point p) { centre = p; } // setzt den Radius void Circle::setRadius(double r) { radius = r; } void Circle::move(double dx, double dy) { centre.move(dx, dy); } void Circle::print(bool nl) const { cout << "<"; centre.print(false); cout << ", " << radius << ">"; if (nl) cout << endl; } string Circle::toString() const { stringstream ss; ss << "<" << centre.toString() << ", " << radius << ">"; return ss.str(); } istream& operator>>(istream& is, Circle& circ) { char c; is >> c >> circ.centre >> c >> circ.radius >> c; return is; } ostream& operator<<(ostream& os, Circle& c) { os << c.toString(); return os; } Circle::~Circle() { }
[ "aamuit00@hs-esslingen.de" ]
aamuit00@hs-esslingen.de
07e92d79f7c924eeb78e2863d327ad82d811f508
1061216c2c33c1ed4ffb33e6211565575957e48f
/cpp-restsdk/model/CodedError.h
79717c88ac75358944c52948ff47692c4c4084b7
[]
no_license
MSurfer20/test2
be9532f54839e8f58b60a8e4587348c2810ecdb9
13b35d72f33302fa532aea189e8f532272f1f799
refs/heads/main
2023-07-03T04:19:57.548080
2021-08-11T19:16:42
2021-08-11T19:16:42
393,920,506
0
0
null
null
null
null
UTF-8
C++
false
false
2,104
h
/** * Zulip REST API * Powerful open source group chat * * The version of the OpenAPI document: 1.0.0 * * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0. * https://openapi-generator.tech * Do not edit the class manually. */ /* * CodedError.h * * */ #ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_CodedError_H_ #define ORG_OPENAPITOOLS_CLIENT_MODEL_CodedError_H_ #include "../ModelBase.h" #include "CodedError_allOf.h" #include "CodedErrorBase.h" #include "AnyType.h" namespace org { namespace openapitools { namespace client { namespace model { /// <summary> /// /// </summary> class CodedError : public ModelBase { public: CodedError(); virtual ~CodedError(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; bool fromJson(const web::json::value& json) override; void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override; bool fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override; ///////////////////////////////////////////// /// CodedError members /// <summary> /// /// </summary> std::shared_ptr<AnyType> getResult() const; bool resultIsSet() const; void unsetResult(); void setResult(const std::shared_ptr<AnyType>& value); /// <summary> /// /// </summary> std::shared_ptr<AnyType> getMsg() const; bool msgIsSet() const; void unsetMsg(); void setMsg(const std::shared_ptr<AnyType>& value); /// <summary> /// /// </summary> std::shared_ptr<AnyType> getCode() const; bool codeIsSet() const; void unsetCode(); void setCode(const std::shared_ptr<AnyType>& value); protected: std::shared_ptr<AnyType> m_Result; bool m_ResultIsSet; std::shared_ptr<AnyType> m_Msg; bool m_MsgIsSet; std::shared_ptr<AnyType> m_Code; bool m_CodeIsSet; }; } } } } #endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_CodedError_H_ */
[ "suyash.mathur@research.iiit.ac.in" ]
suyash.mathur@research.iiit.ac.in
9152054fc11cf84608216c2146f5142d92382c9d
1ec086253005570c211cf55fe74c8886b2c483ef
/TKDGTT/Tuan 6/BT6.Nhom5/doitien.cpp
8d91ae72702d6ccac8a772628496da2c687123b9
[]
no_license
Du0ngkylan/C-Cpp
8be2fc9632bb1c49b0eaac6166f9ead5deac4c83
37d973d510bafc5512fce2f2a81b0a4aa746b2e3
refs/heads/master
2021-06-26T05:58:17.969765
2020-11-27T03:52:06
2020-11-27T03:52:06
172,220,624
0
1
null
null
null
null
UTF-8
C++
false
false
1,061
cpp
#include<stdio.h> #include<conio.h> #define hs 50 int C[hs][hs]; int d[hs],chon[hs]; int n,m; void nhap(){ int i; for ( i=1; i<=n; i++){ printf("Nhap d[%d]= ",i); scanf("%d",&d[i]); } } void in(){ int i; for ( i=1; i<=n; i++){ printf("%4d",d[i]); } printf("\n"); } void doitien(){ int i,j; for (i=0; i<=n; i++){ C[i][0] = 0; } for (j=1; j<=m; j++){ C[0][j] = hs; } for ( i=1; i<=n; i++){ for ( j=1; j<=m; j++){ C[i][j] = C[i-1][j]; if( (d[i]<=j) &&((C[i][j-d[i]]+1)<C[i][j])) C[i][j] = C[i][j-d[i]] + 1; } } } void truyvet(){ int i,j; i=n; j = m; while( j>0 ){ if( C[i][j] == C[i-1][j]){ i = i-1; chon[i] = 0; } if( C[i][j] == ( C[i][j-d[i]] + 1) ){ j = j-d[i]; printf("%4d",d[i]); } } } int main(){ int i; printf("Nhap vso so loai menh gia: n = "); scanf("%d",&n); printf("Nhap vao tung loai menh gia: \n"); nhap(); printf("Nhap vao so tien can doi: m ( m < 50 ) = "); scanf("%d",&m); doitien(); printf("Cach doi: "); truyvet(); getch(); return 0; }
[ "duongmaixuan.k55tt@gmail.com" ]
duongmaixuan.k55tt@gmail.com
8b2896d700fb6ae4849b4f2f4730aa039484e18c
7d1040c025f91911cefba2fa748b813d275a95f6
/CreatureEditorAndPlugin/CreaturePlugin/Source/CreaturePlugin/Private/CreatureMetaAsset.cpp
8387a2ca51cf5f4630d1c22d3ada61d84913d3c0
[ "LicenseRef-scancode-public-domain" ]
permissive
sepinood/Creature_UE4
85f79ed1d805bd5f1036c4bb6f97dfcf056f08ed
cd0a3f87e411985cfe80761f67bc8cdd860e04e4
refs/heads/master
2021-01-21T08:28:36.968275
2016-09-02T18:05:29
2016-09-02T18:05:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,059
cpp
#include "CreaturePluginPCH.h" #include "CreatureMetaAsset.h" #include "CreatureCore.h" FString& UCreatureMetaAsset::GetJsonString() { return jsonString; } void UCreatureMetaAsset::Serialize(FArchive& Ar) { Super::Serialize(Ar); } void UCreatureMetaAsset::BuildMetaData() { TSharedPtr<FJsonObject> jsonObject = MakeShareable(new FJsonObject); TSharedRef< TJsonReader<> > reader = TJsonReaderFactory<>::Create(jsonString); meta_data.clear(); if (FJsonSerializer::Deserialize(reader, jsonObject)) { // Fill mesh data if (jsonObject->HasField(TEXT("meshes"))) { auto meshes_obj = jsonObject->GetObjectField(TEXT("meshes")); for (auto cur_data : meshes_obj->Values) { auto cur_json = cur_data.Value->AsObject(); auto cur_id = cur_json->GetIntegerField(TEXT("id")); auto cur_start_index = cur_json->GetIntegerField(TEXT("startIndex")); auto cur_end_index = cur_json->GetIntegerField(TEXT("endIndex")); meta_data.mesh_map.Add(cur_id, std::pair<int, int>(cur_start_index, cur_end_index)); } } // Fill switch order data if (jsonObject->HasField(TEXT("regionOrders"))) { auto orders_obj = jsonObject->GetObjectField(TEXT("regionOrders")); for (auto cur_data : orders_obj->Values) { auto cur_anim_name = cur_data.Key; TMap<int, std::vector<int> > cur_switch_order_map; auto cur_obj_array = cur_data.Value->AsArray(); for (auto cur_switch_json : cur_obj_array) { auto switch_obj = cur_switch_json->AsObject(); auto cur_switch_list = switch_obj->GetArrayField(TEXT("switch_order")); std::vector<int> cur_switch_ints; for (auto cur_switch_val : cur_switch_list) { cur_switch_ints.push_back((int)cur_switch_val->AsNumber()); } auto cur_switch_time = switch_obj->GetIntegerField(TEXT("switch_time")); cur_switch_order_map.Add(cur_switch_time, cur_switch_ints); } meta_data.anim_order_map.Add(cur_anim_name, cur_switch_order_map); } } } } CreatureMetaData * UCreatureMetaAsset::GetMetaData() { return &meta_data; }
[ "creature@kestrelmoon.com" ]
creature@kestrelmoon.com
251fa57b6d943041be67645af8518081706328e4
0a626f9383a7a9b5085f63e6ce214ae8e19203cc
/src/wasm/function-body-decoder-impl.h
6c47141d375da513a9231086b3485e7a2d40c305
[ "BSD-3-Clause", "bzip2-1.0.6", "SunPro" ]
permissive
xtuc/v8
8a494f80ad65f6597f766bf8b295740ae07a4adc
86894d98bfe79f46c51e27b0699f7bfcc07fe0b2
refs/heads/master
2021-09-28T21:30:37.358269
2018-11-20T04:58:57
2018-11-20T06:36:53
153,456,519
0
0
NOASSERTION
2018-11-06T14:37:55
2018-10-17T12:53:24
C++
UTF-8
C++
false
false
98,300
h
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_ #define V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_ // Do only include this header for implementing new Interface of the // WasmFullDecoder. #include "src/base/platform/elapsed-timer.h" #include "src/bit-vector.h" #include "src/wasm/decoder.h" #include "src/wasm/function-body-decoder.h" #include "src/wasm/wasm-features.h" #include "src/wasm/wasm-limits.h" #include "src/wasm/wasm-module.h" #include "src/wasm/wasm-opcodes.h" namespace v8 { namespace internal { namespace wasm { struct WasmGlobal; struct WasmException; #define TRACE(...) \ do { \ if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \ } while (false) #define TRACE_INST_FORMAT " @%-8d #%-20s|" // Return the evaluation of `condition` if validate==true, DCHECK that it's // true and always return true otherwise. #define VALIDATE(condition) \ (validate ? (condition) : [&] { \ DCHECK(condition); \ return true; \ }()) #define RET_ON_PROTOTYPE_OPCODE(feat) \ DCHECK(!this->module_ || this->module_->origin == kWasmOrigin); \ if (!this->enabled_.feat) { \ this->error("Invalid opcode (enable with --experimental-wasm-" #feat ")"); \ } else { \ this->detected_->feat = true; \ } #define CHECK_PROTOTYPE_OPCODE(feat) \ DCHECK(!this->module_ || this->module_->origin == kWasmOrigin); \ if (!this->enabled_.feat) { \ this->error("Invalid opcode (enable with --experimental-wasm-" #feat ")"); \ break; \ } else { \ this->detected_->feat = true; \ } #define OPCODE_ERROR(opcode, message) \ (this->errorf(this->pc_, "%s: %s", WasmOpcodes::OpcodeName(opcode), \ (message))) #define ATOMIC_OP_LIST(V) \ V(AtomicWake, Uint32) \ V(I32AtomicWait, Uint32) \ V(I32AtomicLoad, Uint32) \ V(I64AtomicLoad, Uint64) \ V(I32AtomicLoad8U, Uint8) \ V(I32AtomicLoad16U, Uint16) \ V(I64AtomicLoad8U, Uint8) \ V(I64AtomicLoad16U, Uint16) \ V(I64AtomicLoad32U, Uint32) \ V(I32AtomicAdd, Uint32) \ V(I32AtomicAdd8U, Uint8) \ V(I32AtomicAdd16U, Uint16) \ V(I64AtomicAdd, Uint64) \ V(I64AtomicAdd8U, Uint8) \ V(I64AtomicAdd16U, Uint16) \ V(I64AtomicAdd32U, Uint32) \ V(I32AtomicSub, Uint32) \ V(I64AtomicSub, Uint64) \ V(I32AtomicSub8U, Uint8) \ V(I32AtomicSub16U, Uint16) \ V(I64AtomicSub8U, Uint8) \ V(I64AtomicSub16U, Uint16) \ V(I64AtomicSub32U, Uint32) \ V(I32AtomicAnd, Uint32) \ V(I64AtomicAnd, Uint64) \ V(I32AtomicAnd8U, Uint8) \ V(I32AtomicAnd16U, Uint16) \ V(I64AtomicAnd8U, Uint8) \ V(I64AtomicAnd16U, Uint16) \ V(I64AtomicAnd32U, Uint32) \ V(I32AtomicOr, Uint32) \ V(I64AtomicOr, Uint64) \ V(I32AtomicOr8U, Uint8) \ V(I32AtomicOr16U, Uint16) \ V(I64AtomicOr8U, Uint8) \ V(I64AtomicOr16U, Uint16) \ V(I64AtomicOr32U, Uint32) \ V(I32AtomicXor, Uint32) \ V(I64AtomicXor, Uint64) \ V(I32AtomicXor8U, Uint8) \ V(I32AtomicXor16U, Uint16) \ V(I64AtomicXor8U, Uint8) \ V(I64AtomicXor16U, Uint16) \ V(I64AtomicXor32U, Uint32) \ V(I32AtomicExchange, Uint32) \ V(I64AtomicExchange, Uint64) \ V(I32AtomicExchange8U, Uint8) \ V(I32AtomicExchange16U, Uint16) \ V(I64AtomicExchange8U, Uint8) \ V(I64AtomicExchange16U, Uint16) \ V(I64AtomicExchange32U, Uint32) \ V(I32AtomicCompareExchange, Uint32) \ V(I64AtomicCompareExchange, Uint64) \ V(I32AtomicCompareExchange8U, Uint8) \ V(I32AtomicCompareExchange16U, Uint16) \ V(I64AtomicCompareExchange8U, Uint8) \ V(I64AtomicCompareExchange16U, Uint16) \ V(I64AtomicCompareExchange32U, Uint32) #define ATOMIC_STORE_OP_LIST(V) \ V(I32AtomicStore, Uint32) \ V(I64AtomicStore, Uint64) \ V(I32AtomicStore8U, Uint8) \ V(I32AtomicStore16U, Uint16) \ V(I64AtomicStore8U, Uint8) \ V(I64AtomicStore16U, Uint16) \ V(I64AtomicStore32U, Uint32) // Helpers for decoding different kinds of immediates which follow bytecodes. template <Decoder::ValidateFlag validate> struct LocalIndexImmediate { uint32_t index; ValueType type = kWasmStmt; unsigned length; inline LocalIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "local index"); } }; template <Decoder::ValidateFlag validate> struct ExceptionIndexImmediate { uint32_t index; const WasmException* exception = nullptr; unsigned length; inline ExceptionIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "exception index"); } }; template <Decoder::ValidateFlag validate> struct ImmI32Immediate { int32_t value; unsigned length; inline ImmI32Immediate(Decoder* decoder, const byte* pc) { value = decoder->read_i32v<validate>(pc + 1, &length, "immi32"); } }; template <Decoder::ValidateFlag validate> struct ImmI64Immediate { int64_t value; unsigned length; inline ImmI64Immediate(Decoder* decoder, const byte* pc) { value = decoder->read_i64v<validate>(pc + 1, &length, "immi64"); } }; template <Decoder::ValidateFlag validate> struct ImmF32Immediate { float value; unsigned length = 4; inline ImmF32Immediate(Decoder* decoder, const byte* pc) { // Avoid bit_cast because it might not preserve the signalling bit of a NaN. uint32_t tmp = decoder->read_u32<validate>(pc + 1, "immf32"); memcpy(&value, &tmp, sizeof(value)); } }; template <Decoder::ValidateFlag validate> struct ImmF64Immediate { double value; unsigned length = 8; inline ImmF64Immediate(Decoder* decoder, const byte* pc) { // Avoid bit_cast because it might not preserve the signalling bit of a NaN. uint64_t tmp = decoder->read_u64<validate>(pc + 1, "immf64"); memcpy(&value, &tmp, sizeof(value)); } }; template <Decoder::ValidateFlag validate> struct GlobalIndexImmediate { uint32_t index; ValueType type = kWasmStmt; const WasmGlobal* global = nullptr; unsigned length; inline GlobalIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "global index"); } }; template <Decoder::ValidateFlag validate> struct BlockTypeImmediate { unsigned length = 1; ValueType type = kWasmStmt; uint32_t sig_index = 0; FunctionSig* sig = nullptr; inline BlockTypeImmediate(const WasmFeatures& enabled, Decoder* decoder, const byte* pc) { uint8_t val = decoder->read_u8<validate>(pc + 1, "block type"); if (!decode_local_type(val, &type)) { // Handle multi-value blocks. if (!VALIDATE(enabled.mv)) { decoder->error(pc + 1, "invalid block type"); return; } if (!VALIDATE(decoder->ok())) return; int32_t index = decoder->read_i32v<validate>(pc + 1, &length, "block arity"); if (!VALIDATE(length > 0 && index >= 0)) { decoder->error(pc + 1, "invalid block type index"); return; } sig_index = static_cast<uint32_t>(index); } } // Decode a byte representing a local type. Return {false} if the encoded // byte was invalid or the start of a type index. inline bool decode_local_type(uint8_t val, ValueType* result) { switch (static_cast<ValueTypeCode>(val)) { case kLocalVoid: *result = kWasmStmt; return true; case kLocalI32: *result = kWasmI32; return true; case kLocalI64: *result = kWasmI64; return true; case kLocalF32: *result = kWasmF32; return true; case kLocalF64: *result = kWasmF64; return true; case kLocalS128: *result = kWasmS128; return true; case kLocalAnyFunc: *result = kWasmAnyFunc; return true; case kLocalAnyRef: *result = kWasmAnyRef; return true; default: *result = kWasmVar; return false; } } uint32_t in_arity() const { if (type != kWasmVar) return 0; return static_cast<uint32_t>(sig->parameter_count()); } uint32_t out_arity() const { if (type == kWasmStmt) return 0; if (type != kWasmVar) return 1; return static_cast<uint32_t>(sig->return_count()); } ValueType in_type(uint32_t index) { DCHECK_EQ(kWasmVar, type); return sig->GetParam(index); } ValueType out_type(uint32_t index) { if (type == kWasmVar) return sig->GetReturn(index); DCHECK_NE(kWasmStmt, type); DCHECK_EQ(0, index); return type; } }; template <Decoder::ValidateFlag validate> struct BreakDepthImmediate { uint32_t depth; unsigned length; inline BreakDepthImmediate(Decoder* decoder, const byte* pc) { depth = decoder->read_u32v<validate>(pc + 1, &length, "break depth"); } }; template <Decoder::ValidateFlag validate> struct CallIndirectImmediate { uint32_t table_index; uint32_t sig_index; FunctionSig* sig = nullptr; unsigned length = 0; inline CallIndirectImmediate(Decoder* decoder, const byte* pc) { unsigned len = 0; sig_index = decoder->read_u32v<validate>(pc + 1, &len, "signature index"); if (!VALIDATE(decoder->ok())) return; table_index = decoder->read_u8<validate>(pc + 1 + len, "table index"); if (!VALIDATE(table_index == 0)) { decoder->errorf(pc + 1 + len, "expected table index 0, found %u", table_index); } length = 1 + len; } }; template <Decoder::ValidateFlag validate> struct CallFunctionImmediate { uint32_t index; FunctionSig* sig = nullptr; unsigned length; inline CallFunctionImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "function index"); } }; template <Decoder::ValidateFlag validate> struct MemoryIndexImmediate { uint32_t index; unsigned length = 1; inline MemoryIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u8<validate>(pc + 1, "memory index"); if (!VALIDATE(index == 0)) { decoder->errorf(pc + 1, "expected memory index 0, found %u", index); } } }; template <Decoder::ValidateFlag validate> struct TableIndexImmediate { uint32_t index; unsigned length = 1; inline TableIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u8<validate>(pc + 1, "table index"); if (!VALIDATE(index == 0)) { decoder->errorf(pc + 1, "expected table index 0, found %u", index); } } }; template <Decoder::ValidateFlag validate> struct BranchTableImmediate { uint32_t table_count; const byte* start; const byte* table; inline BranchTableImmediate(Decoder* decoder, const byte* pc) { DCHECK_EQ(kExprBrTable, decoder->read_u8<validate>(pc, "opcode")); start = pc + 1; unsigned len = 0; table_count = decoder->read_u32v<validate>(pc + 1, &len, "table count"); table = pc + 1 + len; } }; // A helper to iterate over a branch table. template <Decoder::ValidateFlag validate> class BranchTableIterator { public: unsigned cur_index() { return index_; } bool has_next() { return VALIDATE(decoder_->ok()) && index_ <= table_count_; } uint32_t next() { DCHECK(has_next()); index_++; unsigned length; uint32_t result = decoder_->read_u32v<validate>(pc_, &length, "branch table entry"); pc_ += length; return result; } // length, including the length of the {BranchTableImmediate}, but not the // opcode. unsigned length() { while (has_next()) next(); return static_cast<unsigned>(pc_ - start_); } const byte* pc() { return pc_; } BranchTableIterator(Decoder* decoder, const BranchTableImmediate<validate>& imm) : decoder_(decoder), start_(imm.start), pc_(imm.table), table_count_(imm.table_count) {} private: Decoder* decoder_; const byte* start_; const byte* pc_; uint32_t index_ = 0; // the current index. uint32_t table_count_; // the count of entries, not including default. }; template <Decoder::ValidateFlag validate> struct MemoryAccessImmediate { uint32_t alignment; uint32_t offset; unsigned length = 0; inline MemoryAccessImmediate(Decoder* decoder, const byte* pc, uint32_t max_alignment) { unsigned alignment_length; alignment = decoder->read_u32v<validate>(pc + 1, &alignment_length, "alignment"); if (!VALIDATE(alignment <= max_alignment)) { decoder->errorf(pc + 1, "invalid alignment; expected maximum alignment is %u, " "actual alignment is %u", max_alignment, alignment); } if (!VALIDATE(decoder->ok())) return; unsigned offset_length; offset = decoder->read_u32v<validate>(pc + 1 + alignment_length, &offset_length, "offset"); length = alignment_length + offset_length; } }; // Immediate for SIMD lane operations. template <Decoder::ValidateFlag validate> struct SimdLaneImmediate { uint8_t lane; unsigned length = 1; inline SimdLaneImmediate(Decoder* decoder, const byte* pc) { lane = decoder->read_u8<validate>(pc + 2, "lane"); } }; // Immediate for SIMD shift operations. template <Decoder::ValidateFlag validate> struct SimdShiftImmediate { uint8_t shift; unsigned length = 1; inline SimdShiftImmediate(Decoder* decoder, const byte* pc) { shift = decoder->read_u8<validate>(pc + 2, "shift"); } }; // Immediate for SIMD S8x16 shuffle operations. template <Decoder::ValidateFlag validate> struct Simd8x16ShuffleImmediate { uint8_t shuffle[kSimd128Size] = {0}; inline Simd8x16ShuffleImmediate(Decoder* decoder, const byte* pc) { for (uint32_t i = 0; i < kSimd128Size; ++i) { shuffle[i] = decoder->read_u8<validate>(pc + 2 + i, "shuffle"); if (!VALIDATE(decoder->ok())) return; } } }; template <Decoder::ValidateFlag validate> struct MemoryInitImmediate { MemoryIndexImmediate<validate> memory; uint32_t data_segment_index; unsigned length; inline MemoryInitImmediate(Decoder* decoder, const byte* pc) : memory(decoder, pc + 1) { data_segment_index = decoder->read_i32v<validate>( pc + 2 + memory.length, &length, "data segment index"); length += memory.length; } }; template <Decoder::ValidateFlag validate> struct MemoryDropImmediate { uint32_t index; unsigned length; inline MemoryDropImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_i32v<validate>(pc + 2, &length, "data segment index"); } }; template <Decoder::ValidateFlag validate> struct TableInitImmediate { TableIndexImmediate<validate> table; uint32_t elem_segment_index; unsigned length; inline TableInitImmediate(Decoder* decoder, const byte* pc) : table(decoder, pc + 1) { elem_segment_index = decoder->read_i32v<validate>( pc + 2 + table.length, &length, "elem segment index"); length += table.length; } }; template <Decoder::ValidateFlag validate> struct TableDropImmediate { uint32_t index; unsigned length; inline TableDropImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_i32v<validate>(pc + 2, &length, "elem segment index"); } }; // An entry on the value stack. struct ValueBase { const byte* pc; ValueType type; // Named constructors. static ValueBase Unreachable(const byte* pc) { return {pc, kWasmVar}; } static ValueBase New(const byte* pc, ValueType type) { return {pc, type}; } }; template <typename Value> struct Merge { uint32_t arity; union { Value* array; Value first; } vals; // Either multiple values or a single value. // Tracks whether this merge was ever reached. Uses precise reachability, like // Reachability::kReachable. bool reached; Merge(bool reached = false) : reached(reached) {} Value& operator[](uint32_t i) { DCHECK_GT(arity, i); return arity == 1 ? vals.first : vals.array[i]; } }; enum ControlKind : uint8_t { kControlIf, kControlIfElse, kControlBlock, kControlLoop, kControlTry, kControlTryCatch, kControlTryCatchAll }; enum Reachability : uint8_t { // reachable code. kReachable, // reachable code in unreachable block (implies normal validation). kSpecOnlyReachable, // code unreachable in its own block (implies polymorphic validation). kUnreachable }; // An entry on the control stack (i.e. if, block, loop, or try). template <typename Value> struct ControlBase { ControlKind kind; uint32_t stack_depth; // stack height at the beginning of the construct. const byte* pc; Reachability reachability = kReachable; // Values merged into the start or end of this control construct. Merge<Value> start_merge; Merge<Value> end_merge; ControlBase() = default; ControlBase(ControlKind kind, uint32_t stack_depth, const byte* pc) : kind(kind), stack_depth(stack_depth), pc(pc) {} // Check whether the current block is reachable. bool reachable() const { return reachability == kReachable; } // Check whether the rest of the block is unreachable. // Note that this is different from {!reachable()}, as there is also the // "indirect unreachable state", for which both {reachable()} and // {unreachable()} return false. bool unreachable() const { return reachability == kUnreachable; } // Return the reachability of new control structs started in this block. Reachability innerReachability() const { return reachability == kReachable ? kReachable : kSpecOnlyReachable; } bool is_if() const { return is_onearmed_if() || is_if_else(); } bool is_onearmed_if() const { return kind == kControlIf; } bool is_if_else() const { return kind == kControlIfElse; } bool is_block() const { return kind == kControlBlock; } bool is_loop() const { return kind == kControlLoop; } bool is_incomplete_try() const { return kind == kControlTry; } bool is_try_catch() const { return kind == kControlTryCatch; } bool is_try_catchall() const { return kind == kControlTryCatchAll; } bool is_try() const { return is_incomplete_try() || is_try_catch() || is_try_catchall(); } inline Merge<Value>* br_merge() { return is_loop() ? &this->start_merge : &this->end_merge; } // Named constructors. static ControlBase Block(const byte* pc, uint32_t stack_depth) { return {kControlBlock, stack_depth, pc}; } static ControlBase If(const byte* pc, uint32_t stack_depth) { return {kControlIf, stack_depth, pc}; } static ControlBase Loop(const byte* pc, uint32_t stack_depth) { return {kControlLoop, stack_depth, pc}; } static ControlBase Try(const byte* pc, uint32_t stack_depth) { return {kControlTry, stack_depth, pc}; } }; #define CONCRETE_NAMED_CONSTRUCTOR(concrete_type, abstract_type, name) \ template <typename... Args> \ static concrete_type name(Args&&... args) { \ concrete_type val; \ static_cast<abstract_type&>(val) = \ abstract_type::name(std::forward<Args>(args)...); \ return val; \ } // Provide the default named constructors, which default-initialize the // ConcreteType and the initialize the fields of ValueBase correctly. // Use like this: // struct Value : public ValueWithNamedConstructors<Value> { int new_field; }; template <typename ConcreteType> struct ValueWithNamedConstructors : public ValueBase { // Named constructors. CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ValueBase, Unreachable) CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ValueBase, New) }; // Provide the default named constructors, which default-initialize the // ConcreteType and the initialize the fields of ControlBase correctly. // Use like this: // struct Control : public ControlWithNamedConstructors<Control, Value> { // int my_uninitialized_field; // char* other_field = nullptr; // }; template <typename ConcreteType, typename Value> struct ControlWithNamedConstructors : public ControlBase<Value> { // Named constructors. CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, Block) CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, If) CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, Loop) CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, Try) }; // This is the list of callback functions that an interface for the // WasmFullDecoder should implement. // F(Name, args...) #define INTERFACE_FUNCTIONS(F) \ /* General: */ \ F(StartFunction) \ F(StartFunctionBody, Control* block) \ F(FinishFunction) \ F(OnFirstError) \ F(NextInstruction, WasmOpcode) \ /* Control: */ \ F(Block, Control* block) \ F(Loop, Control* block) \ F(Try, Control* block) \ F(If, const Value& cond, Control* if_block) \ F(FallThruTo, Control* c) \ F(PopControl, Control* block) \ F(EndControl, Control* block) \ /* Instructions: */ \ F(UnOp, WasmOpcode opcode, FunctionSig*, const Value& value, Value* result) \ F(BinOp, WasmOpcode opcode, FunctionSig*, const Value& lhs, \ const Value& rhs, Value* result) \ F(I32Const, Value* result, int32_t value) \ F(I64Const, Value* result, int64_t value) \ F(F32Const, Value* result, float value) \ F(F64Const, Value* result, double value) \ F(RefNull, Value* result) \ F(Drop, const Value& value) \ F(DoReturn, Vector<Value> values, bool implicit) \ F(GetLocal, Value* result, const LocalIndexImmediate<validate>& imm) \ F(SetLocal, const Value& value, const LocalIndexImmediate<validate>& imm) \ F(TeeLocal, const Value& value, Value* result, \ const LocalIndexImmediate<validate>& imm) \ F(GetGlobal, Value* result, const GlobalIndexImmediate<validate>& imm) \ F(SetGlobal, const Value& value, const GlobalIndexImmediate<validate>& imm) \ F(Unreachable) \ F(Select, const Value& cond, const Value& fval, const Value& tval, \ Value* result) \ F(Br, Control* target) \ F(BrIf, const Value& cond, Control* target) \ F(BrTable, const BranchTableImmediate<validate>& imm, const Value& key) \ F(Else, Control* if_block) \ F(LoadMem, LoadType type, const MemoryAccessImmediate<validate>& imm, \ const Value& index, Value* result) \ F(StoreMem, StoreType type, const MemoryAccessImmediate<validate>& imm, \ const Value& index, const Value& value) \ F(CurrentMemoryPages, Value* result) \ F(MemoryGrow, const Value& value, Value* result) \ F(CallDirect, const CallFunctionImmediate<validate>& imm, \ const Value args[], Value returns[]) \ F(CallIndirect, const Value& index, \ const CallIndirectImmediate<validate>& imm, const Value args[], \ Value returns[]) \ F(SimdOp, WasmOpcode opcode, Vector<Value> args, Value* result) \ F(SimdLaneOp, WasmOpcode opcode, const SimdLaneImmediate<validate>& imm, \ const Vector<Value> inputs, Value* result) \ F(SimdShiftOp, WasmOpcode opcode, const SimdShiftImmediate<validate>& imm, \ const Value& input, Value* result) \ F(Simd8x16ShuffleOp, const Simd8x16ShuffleImmediate<validate>& imm, \ const Value& input0, const Value& input1, Value* result) \ F(Throw, const ExceptionIndexImmediate<validate>& imm, \ const Vector<Value>& args) \ F(Rethrow, Control* block) \ F(CatchException, const ExceptionIndexImmediate<validate>& imm, \ Control* block, Vector<Value> caught_values) \ F(CatchAll, Control* block) \ F(AtomicOp, WasmOpcode opcode, Vector<Value> args, \ const MemoryAccessImmediate<validate>& imm, Value* result) \ F(MemoryInit, const MemoryInitImmediate<validate>& imm, Vector<Value> args) \ F(MemoryDrop, const MemoryDropImmediate<validate>& imm) \ F(MemoryCopy, const MemoryIndexImmediate<validate>& imm, Vector<Value> args) \ F(MemoryFill, const MemoryIndexImmediate<validate>& imm, Vector<Value> args) \ F(TableInit, const TableInitImmediate<validate>& imm, Vector<Value> args) \ F(TableDrop, const TableDropImmediate<validate>& imm) \ F(TableCopy, const TableIndexImmediate<validate>& imm, Vector<Value> args) // Generic Wasm bytecode decoder with utilities for decoding immediates, // lengths, etc. template <Decoder::ValidateFlag validate> class WasmDecoder : public Decoder { public: WasmDecoder(const WasmModule* module, const WasmFeatures& enabled, WasmFeatures* detected, FunctionSig* sig, const byte* start, const byte* end, uint32_t buffer_offset = 0) : Decoder(start, end, buffer_offset), module_(module), enabled_(enabled), detected_(detected), sig_(sig), local_types_(nullptr) {} const WasmModule* module_; const WasmFeatures enabled_; WasmFeatures* detected_; FunctionSig* sig_; ZoneVector<ValueType>* local_types_; uint32_t total_locals() const { return local_types_ == nullptr ? 0 : static_cast<uint32_t>(local_types_->size()); } static bool DecodeLocals(const WasmFeatures& enabled, Decoder* decoder, const FunctionSig* sig, ZoneVector<ValueType>* type_list) { DCHECK_NOT_NULL(type_list); DCHECK_EQ(0, type_list->size()); // Initialize from signature. if (sig != nullptr) { type_list->assign(sig->parameters().begin(), sig->parameters().end()); } // Decode local declarations, if any. uint32_t entries = decoder->consume_u32v("local decls count"); if (decoder->failed()) return false; TRACE("local decls count: %u\n", entries); while (entries-- > 0 && VALIDATE(decoder->ok()) && decoder->more()) { uint32_t count = decoder->consume_u32v("local count"); if (decoder->failed()) return false; DCHECK_LE(type_list->size(), kV8MaxWasmFunctionLocals); if (count > kV8MaxWasmFunctionLocals - type_list->size()) { decoder->error(decoder->pc() - 1, "local count too large"); return false; } byte code = decoder->consume_u8("local type"); if (decoder->failed()) return false; ValueType type; switch (code) { case kLocalI32: type = kWasmI32; break; case kLocalI64: type = kWasmI64; break; case kLocalF32: type = kWasmF32; break; case kLocalF64: type = kWasmF64; break; case kLocalAnyRef: if (enabled.anyref) { type = kWasmAnyRef; break; } decoder->error(decoder->pc() - 1, "invalid local type"); return false; case kLocalExceptRef: if (enabled.eh) { type = kWasmExceptRef; break; } decoder->error(decoder->pc() - 1, "invalid local type"); return false; case kLocalS128: if (enabled.simd) { type = kWasmS128; break; } V8_FALLTHROUGH; default: decoder->error(decoder->pc() - 1, "invalid local type"); return false; } type_list->insert(type_list->end(), count, type); } DCHECK(decoder->ok()); return true; } static BitVector* AnalyzeLoopAssignment(Decoder* decoder, const byte* pc, uint32_t locals_count, Zone* zone) { if (pc >= decoder->end()) return nullptr; if (*pc != kExprLoop) return nullptr; // The number of locals_count is augmented by 2 so that 'locals_count - 2' // can be used to track mem_size, and 'locals_count - 1' to track mem_start. BitVector* assigned = new (zone) BitVector(locals_count, zone); int depth = 0; // Iteratively process all AST nodes nested inside the loop. while (pc < decoder->end() && VALIDATE(decoder->ok())) { WasmOpcode opcode = static_cast<WasmOpcode>(*pc); unsigned length = 1; switch (opcode) { case kExprLoop: case kExprIf: case kExprBlock: case kExprTry: length = OpcodeLength(decoder, pc); depth++; break; case kExprSetLocal: // fallthru case kExprTeeLocal: { LocalIndexImmediate<validate> imm(decoder, pc); if (assigned->length() > 0 && imm.index < static_cast<uint32_t>(assigned->length())) { // Unverified code might have an out-of-bounds index. assigned->Add(imm.index); } length = 1 + imm.length; break; } case kExprMemoryGrow: case kExprCallFunction: case kExprCallIndirect: // Add instance cache nodes to the assigned set. // TODO(titzer): make this more clear. assigned->Add(locals_count - 1); length = OpcodeLength(decoder, pc); break; case kExprEnd: depth--; break; default: length = OpcodeLength(decoder, pc); break; } if (depth <= 0) break; pc += length; } return VALIDATE(decoder->ok()) ? assigned : nullptr; } inline bool Validate(const byte* pc, LocalIndexImmediate<validate>& imm) { if (!VALIDATE(imm.index < total_locals())) { errorf(pc + 1, "invalid local index: %u", imm.index); return false; } imm.type = local_types_ ? local_types_->at(imm.index) : kWasmStmt; return true; } inline bool Validate(const byte* pc, ExceptionIndexImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.index < module_->exceptions.size())) { errorf(pc + 1, "Invalid exception index: %u", imm.index); return false; } imm.exception = &module_->exceptions[imm.index]; return true; } inline bool Validate(const byte* pc, GlobalIndexImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.index < module_->globals.size())) { errorf(pc + 1, "invalid global index: %u", imm.index); return false; } imm.global = &module_->globals[imm.index]; imm.type = imm.global->type; return true; } inline bool Complete(const byte* pc, CallFunctionImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.index < module_->functions.size())) { return false; } imm.sig = module_->functions[imm.index].sig; return true; } inline bool Validate(const byte* pc, CallFunctionImmediate<validate>& imm) { if (Complete(pc, imm)) { return true; } errorf(pc + 1, "invalid function index: %u", imm.index); return false; } inline bool Complete(const byte* pc, CallIndirectImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.sig_index < module_->signatures.size())) { return false; } imm.sig = module_->signatures[imm.sig_index]; return true; } inline bool Validate(const byte* pc, CallIndirectImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && !module_->tables.empty())) { error("function table has to exist to execute call_indirect"); return false; } if (!Complete(pc, imm)) { errorf(pc + 1, "invalid signature index: #%u", imm.sig_index); return false; } return true; } inline bool Validate(const byte* pc, BreakDepthImmediate<validate>& imm, size_t control_depth) { if (!VALIDATE(imm.depth < control_depth)) { errorf(pc + 1, "invalid break depth: %u", imm.depth); return false; } return true; } bool Validate(const byte* pc, BranchTableImmediate<validate>& imm, size_t block_depth) { if (!VALIDATE(imm.table_count < kV8MaxWasmFunctionSize)) { errorf(pc + 1, "invalid table count (> max function size): %u", imm.table_count); return false; } return checkAvailable(imm.table_count); } inline bool Validate(const byte* pc, WasmOpcode opcode, SimdLaneImmediate<validate>& imm) { uint8_t num_lanes = 0; switch (opcode) { case kExprF32x4ExtractLane: case kExprF32x4ReplaceLane: case kExprI32x4ExtractLane: case kExprI32x4ReplaceLane: num_lanes = 4; break; case kExprI16x8ExtractLane: case kExprI16x8ReplaceLane: num_lanes = 8; break; case kExprI8x16ExtractLane: case kExprI8x16ReplaceLane: num_lanes = 16; break; default: UNREACHABLE(); break; } if (!VALIDATE(imm.lane >= 0 && imm.lane < num_lanes)) { error(pc_ + 2, "invalid lane index"); return false; } else { return true; } } inline bool Validate(const byte* pc, WasmOpcode opcode, SimdShiftImmediate<validate>& imm) { uint8_t max_shift = 0; switch (opcode) { case kExprI32x4Shl: case kExprI32x4ShrS: case kExprI32x4ShrU: max_shift = 32; break; case kExprI16x8Shl: case kExprI16x8ShrS: case kExprI16x8ShrU: max_shift = 16; break; case kExprI8x16Shl: case kExprI8x16ShrS: case kExprI8x16ShrU: max_shift = 8; break; default: UNREACHABLE(); break; } if (!VALIDATE(imm.shift >= 0 && imm.shift < max_shift)) { error(pc_ + 2, "invalid shift amount"); return false; } else { return true; } } inline bool Validate(const byte* pc, Simd8x16ShuffleImmediate<validate>& imm) { uint8_t max_lane = 0; for (uint32_t i = 0; i < kSimd128Size; ++i) { max_lane = std::max(max_lane, imm.shuffle[i]); } // Shuffle indices must be in [0..31] for a 16 lane shuffle. if (!VALIDATE(max_lane <= 2 * kSimd128Size)) { error(pc_ + 2, "invalid shuffle mask"); return false; } return true; } inline bool Complete(BlockTypeImmediate<validate>& imm) { if (imm.type != kWasmVar) return true; if (!VALIDATE((module_ && imm.sig_index < module_->signatures.size()))) { return false; } imm.sig = module_->signatures[imm.sig_index]; return true; } inline bool Validate(BlockTypeImmediate<validate>& imm) { if (!Complete(imm)) { errorf(pc_, "block type index %u out of bounds (%zu signatures)", imm.sig_index, module_ ? module_->signatures.size() : 0); return false; } return true; } inline bool Validate(MemoryIndexImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && module_->has_memory)) { errorf(pc_ + 1, "memory instruction with no memory"); return false; } return true; } inline bool Validate(MemoryInitImmediate<validate>& imm) { if (!Validate(imm.memory)) return false; // TODO(binji): validate imm.data_segment_index return true; } inline bool Validate(MemoryDropImmediate<validate>& imm) { // TODO(binji): validate imm.data_segment_index return true; } inline bool Validate(const byte* pc, TableIndexImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.index < module_->tables.size())) { errorf(pc_ + 1, "invalid table index: %u", imm.index); return false; } return true; } inline bool Validate(TableInitImmediate<validate>& imm) { if (!Validate(pc_ + 1, imm.table)) return false; if (!VALIDATE(module_ != nullptr && imm.elem_segment_index < module_->table_inits.size())) { errorf(pc_ + 2, "invalid element segment index: %u", imm.elem_segment_index); return false; } return true; } inline bool Validate(TableDropImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.index < module_->table_inits.size())) { errorf(pc_ + 2, "invalid element segment index: %u", imm.index); return false; } return true; } static unsigned OpcodeLength(Decoder* decoder, const byte* pc) { WasmOpcode opcode = static_cast<WasmOpcode>(*pc); switch (opcode) { #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE) FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE { MemoryAccessImmediate<validate> imm(decoder, pc, UINT32_MAX); return 1 + imm.length; } case kExprRethrow: case kExprBr: case kExprBrIf: { BreakDepthImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprSetGlobal: case kExprGetGlobal: { GlobalIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprCallFunction: { CallFunctionImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprCallIndirect: { CallIndirectImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprTry: case kExprIf: // fall through case kExprLoop: case kExprBlock: { BlockTypeImmediate<validate> imm(kAllWasmFeatures, decoder, pc); return 1 + imm.length; } case kExprThrow: case kExprCatch: { ExceptionIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprSetLocal: case kExprTeeLocal: case kExprGetLocal: { LocalIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprBrTable: { BranchTableImmediate<validate> imm(decoder, pc); BranchTableIterator<validate> iterator(decoder, imm); return 1 + iterator.length(); } case kExprI32Const: { ImmI32Immediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprI64Const: { ImmI64Immediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprRefNull: { return 1; } case kExprMemoryGrow: case kExprMemorySize: { MemoryIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprF32Const: return 5; case kExprF64Const: return 9; case kNumericPrefix: { byte numeric_index = decoder->read_u8<validate>(pc + 1, "numeric_index"); WasmOpcode opcode = static_cast<WasmOpcode>(kNumericPrefix << 8 | numeric_index); switch (opcode) { case kExprI32SConvertSatF32: case kExprI32UConvertSatF32: case kExprI32SConvertSatF64: case kExprI32UConvertSatF64: case kExprI64SConvertSatF32: case kExprI64UConvertSatF32: case kExprI64SConvertSatF64: case kExprI64UConvertSatF64: return 2; case kExprMemoryInit: { MemoryInitImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprMemoryDrop: { MemoryDropImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprMemoryCopy: case kExprMemoryFill: { MemoryIndexImmediate<validate> imm(decoder, pc + 1); return 2 + imm.length; } case kExprTableInit: { TableInitImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprTableDrop: { TableDropImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprTableCopy: { TableIndexImmediate<validate> imm(decoder, pc + 1); return 2 + imm.length; } default: decoder->error(pc, "invalid numeric opcode"); return 2; } } case kSimdPrefix: { byte simd_index = decoder->read_u8<validate>(pc + 1, "simd_index"); WasmOpcode opcode = static_cast<WasmOpcode>(kSimdPrefix << 8 | simd_index); switch (opcode) { #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_SIMD_0_OPERAND_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE return 2; #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_SIMD_1_OPERAND_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE return 3; #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_SIMD_MEM_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE { MemoryAccessImmediate<validate> imm(decoder, pc + 1, UINT32_MAX); return 2 + imm.length; } // Shuffles require a byte per lane, or 16 immediate bytes. case kExprS8x16Shuffle: return 2 + kSimd128Size; default: decoder->error(pc, "invalid SIMD opcode"); return 2; } } case kAtomicPrefix: { byte atomic_index = decoder->read_u8<validate>(pc + 1, "atomic_index"); WasmOpcode opcode = static_cast<WasmOpcode>(kAtomicPrefix << 8 | atomic_index); switch (opcode) { #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_ATOMIC_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE { MemoryAccessImmediate<validate> imm(decoder, pc + 1, UINT32_MAX); return 2 + imm.length; } default: decoder->error(pc, "invalid Atomics opcode"); return 2; } } default: return 1; } } std::pair<uint32_t, uint32_t> StackEffect(const byte* pc) { WasmOpcode opcode = static_cast<WasmOpcode>(*pc); // Handle "simple" opcodes with a fixed signature first. FunctionSig* sig = WasmOpcodes::Signature(opcode); if (!sig) sig = WasmOpcodes::AsmjsSignature(opcode); if (sig) return {sig->parameter_count(), sig->return_count()}; #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: // clang-format off switch (opcode) { case kExprSelect: return {3, 1}; FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE) return {2, 0}; FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE) case kExprTeeLocal: case kExprMemoryGrow: return {1, 1}; case kExprSetLocal: case kExprSetGlobal: case kExprDrop: case kExprBrIf: case kExprBrTable: case kExprIf: return {1, 0}; case kExprGetLocal: case kExprGetGlobal: case kExprI32Const: case kExprI64Const: case kExprF32Const: case kExprF64Const: case kExprRefNull: case kExprMemorySize: return {0, 1}; case kExprCallFunction: { CallFunctionImmediate<validate> imm(this, pc); CHECK(Complete(pc, imm)); return {imm.sig->parameter_count(), imm.sig->return_count()}; } case kExprCallIndirect: { CallIndirectImmediate<validate> imm(this, pc); CHECK(Complete(pc, imm)); // Indirect calls pop an additional argument for the table index. return {imm.sig->parameter_count() + 1, imm.sig->return_count()}; } case kExprBr: case kExprBlock: case kExprLoop: case kExprEnd: case kExprElse: case kExprNop: case kExprReturn: case kExprUnreachable: return {0, 0}; case kNumericPrefix: case kAtomicPrefix: case kSimdPrefix: { opcode = static_cast<WasmOpcode>(opcode << 8 | *(pc + 1)); switch (opcode) { FOREACH_SIMD_1_OPERAND_1_PARAM_OPCODE(DECLARE_OPCODE_CASE) return {1, 1}; FOREACH_SIMD_1_OPERAND_2_PARAM_OPCODE(DECLARE_OPCODE_CASE) FOREACH_SIMD_MASK_OPERAND_OPCODE(DECLARE_OPCODE_CASE) return {2, 1}; default: { sig = WasmOpcodes::Signature(opcode); if (sig) { return {sig->parameter_count(), sig->return_count()}; } } } V8_FALLTHROUGH; } default: V8_Fatal(__FILE__, __LINE__, "unimplemented opcode: %x (%s)", opcode, WasmOpcodes::OpcodeName(opcode)); return {0, 0}; } #undef DECLARE_OPCODE_CASE // clang-format on } }; #define CALL_INTERFACE(name, ...) interface_.name(this, ##__VA_ARGS__) #define CALL_INTERFACE_IF_REACHABLE(name, ...) \ do { \ DCHECK(!control_.empty()); \ if (VALIDATE(this->ok()) && control_.back().reachable()) { \ interface_.name(this, ##__VA_ARGS__); \ } \ } while (false) #define CALL_INTERFACE_IF_PARENT_REACHABLE(name, ...) \ do { \ DCHECK(!control_.empty()); \ if (VALIDATE(this->ok()) && \ (control_.size() == 1 || control_at(1)->reachable())) { \ interface_.name(this, ##__VA_ARGS__); \ } \ } while (false) template <Decoder::ValidateFlag validate, typename Interface> class WasmFullDecoder : public WasmDecoder<validate> { using Value = typename Interface::Value; using Control = typename Interface::Control; using MergeValues = Merge<Value>; // All Value types should be trivially copyable for performance. We push, pop, // and store them in local variables. ASSERT_TRIVIALLY_COPYABLE(Value); public: template <typename... InterfaceArgs> WasmFullDecoder(Zone* zone, const WasmModule* module, const WasmFeatures& enabled, WasmFeatures* detected, const FunctionBody& body, InterfaceArgs&&... interface_args) : WasmDecoder<validate>(module, enabled, detected, body.sig, body.start, body.end, body.offset), zone_(zone), interface_(std::forward<InterfaceArgs>(interface_args)...), local_type_vec_(zone), stack_(zone), control_(zone), args_(zone), last_end_found_(false) { this->local_types_ = &local_type_vec_; } Interface& interface() { return interface_; } bool Decode() { DCHECK(stack_.empty()); DCHECK(control_.empty()); base::ElapsedTimer decode_timer; if (FLAG_trace_wasm_decode_time) { decode_timer.Start(); } if (this->end_ < this->pc_) { this->error("function body end < start"); return false; } DCHECK_EQ(0, this->local_types_->size()); WasmDecoder<validate>::DecodeLocals(this->enabled_, this, this->sig_, this->local_types_); CALL_INTERFACE(StartFunction); DecodeFunctionBody(); if (!this->failed()) CALL_INTERFACE(FinishFunction); if (this->failed()) return this->TraceFailed(); if (!control_.empty()) { // Generate a better error message whether the unterminated control // structure is the function body block or an innner structure. if (control_.size() > 1) { this->error(control_.back().pc, "unterminated control structure"); } else { this->error("function body must end with \"end\" opcode"); } return TraceFailed(); } if (!last_end_found_) { this->error("function body must end with \"end\" opcode"); return false; } if (FLAG_trace_wasm_decode_time) { double ms = decode_timer.Elapsed().InMillisecondsF(); PrintF("wasm-decode %s (%0.3f ms)\n\n", VALIDATE(this->ok()) ? "ok" : "failed", ms); } else { TRACE("wasm-decode %s\n\n", VALIDATE(this->ok()) ? "ok" : "failed"); } return true; } bool TraceFailed() { TRACE("wasm-error module+%-6d func+%d: %s\n\n", this->error_offset_, this->GetBufferRelativeOffset(this->error_offset_), this->error_msg_.c_str()); return false; } const char* SafeOpcodeNameAt(const byte* pc) { if (pc >= this->end_) return "<end>"; return WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(*pc)); } inline Zone* zone() const { return zone_; } inline uint32_t NumLocals() { return static_cast<uint32_t>(local_type_vec_.size()); } inline ValueType GetLocalType(uint32_t index) { return local_type_vec_[index]; } inline WasmCodePosition position() { int offset = static_cast<int>(this->pc_ - this->start_); DCHECK_EQ(this->pc_ - this->start_, offset); // overflows cannot happen return offset; } inline uint32_t control_depth() const { return static_cast<uint32_t>(control_.size()); } inline Control* control_at(uint32_t depth) { DCHECK_GT(control_.size(), depth); return &control_.back() - depth; } inline uint32_t stack_size() const { DCHECK_GE(kMaxUInt32, stack_.size()); return static_cast<uint32_t>(stack_.size()); } inline Value* stack_value(uint32_t depth) { DCHECK_GT(stack_.size(), depth); return &stack_[stack_.size() - depth - 1]; } inline Value& GetMergeValueFromStack( Control* c, Merge<Value>* merge, uint32_t i) { DCHECK(merge == &c->start_merge || merge == &c->end_merge); DCHECK_GT(merge->arity, i); DCHECK_GE(stack_.size(), c->stack_depth + merge->arity); return stack_[stack_.size() - merge->arity + i]; } private: static constexpr size_t kErrorMsgSize = 128; Zone* zone_; Interface interface_; ZoneVector<ValueType> local_type_vec_; // types of local variables. ZoneVector<Value> stack_; // stack of values. ZoneVector<Control> control_; // stack of blocks, loops, and ifs. ZoneVector<Value> args_; // parameters of current block or call bool last_end_found_; bool CheckHasMemory() { if (!VALIDATE(this->module_->has_memory)) { this->error(this->pc_ - 1, "memory instruction with no memory"); return false; } return true; } bool CheckHasSharedMemory() { if (!VALIDATE(this->module_->has_shared_memory)) { this->error(this->pc_ - 1, "Atomic opcodes used without shared memory"); return false; } return true; } class TraceLine { public: static constexpr int kMaxLen = 512; ~TraceLine() { if (!FLAG_trace_wasm_decoder) return; PrintF("%.*s\n", len_, buffer_); } // Appends a formatted string. PRINTF_FORMAT(2, 3) void Append(const char* format, ...) { if (!FLAG_trace_wasm_decoder) return; va_list va_args; va_start(va_args, format); size_t remaining_len = kMaxLen - len_; Vector<char> remaining_msg_space(buffer_ + len_, remaining_len); int len = VSNPrintF(remaining_msg_space, format, va_args); va_end(va_args); len_ += len < 0 ? remaining_len : len; } private: char buffer_[kMaxLen]; int len_ = 0; }; // Decodes the body of a function. void DecodeFunctionBody() { TRACE("wasm-decode %p...%p (module+%u, %d bytes)\n", reinterpret_cast<const void*>(this->start()), reinterpret_cast<const void*>(this->end()), this->pc_offset(), static_cast<int>(this->end() - this->start())); // Set up initial function block. { auto* c = PushBlock(); InitMerge(&c->start_merge, 0, [](uint32_t) -> Value { UNREACHABLE(); }); InitMerge(&c->end_merge, static_cast<uint32_t>(this->sig_->return_count()), [&] (uint32_t i) { return Value::New(this->pc_, this->sig_->GetReturn(i)); }); CALL_INTERFACE(StartFunctionBody, c); } while (this->pc_ < this->end_) { // decoding loop. unsigned len = 1; WasmOpcode opcode = static_cast<WasmOpcode>(*this->pc_); CALL_INTERFACE_IF_REACHABLE(NextInstruction, opcode); #if DEBUG TraceLine trace_msg; #define TRACE_PART(...) trace_msg.Append(__VA_ARGS__) if (!WasmOpcodes::IsPrefixOpcode(opcode)) { TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(opcode)); } #else #define TRACE_PART(...) #endif FunctionSig* sig = const_cast<FunctionSig*>(kSimpleOpcodeSigs[opcode]); if (sig) { BuildSimpleOperator(opcode, sig); } else { // Complex bytecode. switch (opcode) { case kExprNop: break; case kExprBlock: { BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; PopArgs(imm.sig); auto* block = PushBlock(); SetBlockType(block, imm); CALL_INTERFACE_IF_REACHABLE(Block, block); PushMergeValues(block, &block->start_merge); len = 1 + imm.length; break; } case kExprRethrow: { CHECK_PROTOTYPE_OPCODE(eh); BreakDepthImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm, control_.size())) break; Control* c = control_at(imm.depth); if (!VALIDATE(c->is_try_catchall() || c->is_try_catch())) { this->error("rethrow not targeting catch or catch-all"); break; } CALL_INTERFACE_IF_REACHABLE(Rethrow, c); len = 1 + imm.length; EndControl(); break; } case kExprThrow: { CHECK_PROTOTYPE_OPCODE(eh); ExceptionIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; PopArgs(imm.exception->ToFunctionSig()); CALL_INTERFACE_IF_REACHABLE(Throw, imm, VectorOf(args_)); EndControl(); break; } case kExprTry: { CHECK_PROTOTYPE_OPCODE(eh); BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; PopArgs(imm.sig); auto* try_block = PushTry(); SetBlockType(try_block, imm); len = 1 + imm.length; CALL_INTERFACE_IF_REACHABLE(Try, try_block); PushMergeValues(try_block, &try_block->start_merge); break; } case kExprCatch: { CHECK_PROTOTYPE_OPCODE(eh); ExceptionIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; len = 1 + imm.length; if (!VALIDATE(!control_.empty())) { this->error("catch does not match any try"); break; } Control* c = &control_.back(); if (!VALIDATE(c->is_try())) { this->error("catch does not match any try"); break; } if (!VALIDATE(!c->is_try_catchall())) { this->error("catch after catch-all for try"); break; } c->kind = kControlTryCatch; FallThruTo(c); stack_.resize(c->stack_depth); const WasmExceptionSig* sig = imm.exception->sig; for (size_t i = 0, e = sig->parameter_count(); i < e; ++i) { Push(sig->GetParam(i)); } Vector<Value> values(stack_.data() + c->stack_depth, sig->parameter_count()); c->reachability = control_at(1)->innerReachability(); CALL_INTERFACE_IF_PARENT_REACHABLE(CatchException, imm, c, values); break; } case kExprCatchAll: { CHECK_PROTOTYPE_OPCODE(eh); if (!VALIDATE(!control_.empty())) { this->error("catch-all does not match any try"); break; } Control* c = &control_.back(); if (!VALIDATE(c->is_try())) { this->error("catch-all does not match any try"); break; } if (!VALIDATE(!c->is_try_catchall())) { this->error("catch-all already present for try"); break; } c->kind = kControlTryCatchAll; FallThruTo(c); stack_.resize(c->stack_depth); c->reachability = control_at(1)->innerReachability(); CALL_INTERFACE_IF_PARENT_REACHABLE(CatchAll, c); break; } case kExprLoop: { BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; PopArgs(imm.sig); auto* block = PushLoop(); SetBlockType(&control_.back(), imm); len = 1 + imm.length; CALL_INTERFACE_IF_REACHABLE(Loop, block); PushMergeValues(block, &block->start_merge); break; } case kExprIf: { BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; auto cond = Pop(0, kWasmI32); PopArgs(imm.sig); if (!VALIDATE(this->ok())) break; auto* if_block = PushIf(); SetBlockType(if_block, imm); CALL_INTERFACE_IF_REACHABLE(If, cond, if_block); len = 1 + imm.length; PushMergeValues(if_block, &if_block->start_merge); break; } case kExprElse: { if (!VALIDATE(!control_.empty())) { this->error("else does not match any if"); break; } Control* c = &control_.back(); if (!VALIDATE(c->is_if())) { this->error(this->pc_, "else does not match an if"); break; } if (c->is_if_else()) { this->error(this->pc_, "else already present for if"); break; } FallThruTo(c); c->kind = kControlIfElse; CALL_INTERFACE_IF_PARENT_REACHABLE(Else, c); PushMergeValues(c, &c->start_merge); c->reachability = control_at(1)->innerReachability(); break; } case kExprEnd: { if (!VALIDATE(!control_.empty())) { this->error("end does not match any if, try, or block"); return; } Control* c = &control_.back(); if (!VALIDATE(!c->is_incomplete_try())) { this->error(this->pc_, "missing catch or catch-all in try"); break; } if (c->is_onearmed_if()) { // Emulate empty else arm. FallThruTo(c); if (this->failed()) break; CALL_INTERFACE_IF_PARENT_REACHABLE(Else, c); PushMergeValues(c, &c->start_merge); c->reachability = control_at(1)->innerReachability(); } if (c->is_try_catch()) { // Emulate catch-all + re-throw. FallThruTo(c); c->reachability = control_at(1)->innerReachability(); CALL_INTERFACE_IF_PARENT_REACHABLE(CatchAll, c); CALL_INTERFACE_IF_REACHABLE(Rethrow, c); EndControl(); } FallThruTo(c); // A loop just leaves the values on the stack. if (!c->is_loop()) PushMergeValues(c, &c->end_merge); if (control_.size() == 1) { // If at the last (implicit) control, check we are at end. if (!VALIDATE(this->pc_ + 1 == this->end_)) { this->error(this->pc_ + 1, "trailing code after function end"); break; } last_end_found_ = true; // The result of the block is the return value. TRACE_PART("\n" TRACE_INST_FORMAT, startrel(this->pc_), "(implicit) return"); DoReturn(c, true); } PopControl(c); break; } case kExprSelect: { auto cond = Pop(2, kWasmI32); auto fval = Pop(); auto tval = Pop(0, fval.type); auto* result = Push(tval.type == kWasmVar ? fval.type : tval.type); CALL_INTERFACE_IF_REACHABLE(Select, cond, fval, tval, result); break; } case kExprBr: { BreakDepthImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm, control_.size())) break; Control* c = control_at(imm.depth); if (!TypeCheckBreak(c)) break; if (control_.back().reachable()) { CALL_INTERFACE(Br, c); c->br_merge()->reached = true; } len = 1 + imm.length; EndControl(); break; } case kExprBrIf: { BreakDepthImmediate<validate> imm(this, this->pc_); auto cond = Pop(0, kWasmI32); if (this->failed()) break; if (!this->Validate(this->pc_, imm, control_.size())) break; Control* c = control_at(imm.depth); if (!TypeCheckBreak(c)) break; if (control_.back().reachable()) { CALL_INTERFACE(BrIf, cond, c); c->br_merge()->reached = true; } len = 1 + imm.length; break; } case kExprBrTable: { BranchTableImmediate<validate> imm(this, this->pc_); BranchTableIterator<validate> iterator(this, imm); auto key = Pop(0, kWasmI32); if (this->failed()) break; if (!this->Validate(this->pc_, imm, control_.size())) break; uint32_t br_arity = 0; std::vector<bool> br_targets(control_.size()); while (iterator.has_next()) { const uint32_t i = iterator.cur_index(); const byte* pos = iterator.pc(); uint32_t target = iterator.next(); if (!VALIDATE(target < control_.size())) { this->errorf(pos, "improper branch in br_table target %u (depth %u)", i, target); break; } // Avoid redundant break target checks. if (br_targets[target]) continue; br_targets[target] = true; // Check that label types match up. Control* c = control_at(target); uint32_t arity = c->br_merge()->arity; if (i == 0) { br_arity = arity; } else if (!VALIDATE(br_arity == arity)) { this->errorf(pos, "inconsistent arity in br_table target %u" " (previous was %u, this one %u)", i, br_arity, arity); } if (!TypeCheckBreak(c)) break; } if (this->failed()) break; if (control_.back().reachable()) { CALL_INTERFACE(BrTable, imm, key); for (uint32_t depth = control_depth(); depth-- > 0;) { if (!br_targets[depth]) continue; control_at(depth)->br_merge()->reached = true; } } len = 1 + iterator.length(); EndControl(); break; } case kExprReturn: { DoReturn(&control_.back(), false); break; } case kExprUnreachable: { CALL_INTERFACE_IF_REACHABLE(Unreachable); EndControl(); break; } case kExprI32Const: { ImmI32Immediate<validate> imm(this, this->pc_); auto* value = Push(kWasmI32); CALL_INTERFACE_IF_REACHABLE(I32Const, value, imm.value); len = 1 + imm.length; break; } case kExprI64Const: { ImmI64Immediate<validate> imm(this, this->pc_); auto* value = Push(kWasmI64); CALL_INTERFACE_IF_REACHABLE(I64Const, value, imm.value); len = 1 + imm.length; break; } case kExprF32Const: { ImmF32Immediate<validate> imm(this, this->pc_); auto* value = Push(kWasmF32); CALL_INTERFACE_IF_REACHABLE(F32Const, value, imm.value); len = 1 + imm.length; break; } case kExprF64Const: { ImmF64Immediate<validate> imm(this, this->pc_); auto* value = Push(kWasmF64); CALL_INTERFACE_IF_REACHABLE(F64Const, value, imm.value); len = 1 + imm.length; break; } case kExprRefNull: { CHECK_PROTOTYPE_OPCODE(anyref); auto* value = Push(kWasmAnyRef); CALL_INTERFACE_IF_REACHABLE(RefNull, value); len = 1; break; } case kExprGetLocal: { LocalIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; auto* value = Push(imm.type); CALL_INTERFACE_IF_REACHABLE(GetLocal, value, imm); len = 1 + imm.length; break; } case kExprSetLocal: { LocalIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; auto value = Pop(0, local_type_vec_[imm.index]); CALL_INTERFACE_IF_REACHABLE(SetLocal, value, imm); len = 1 + imm.length; break; } case kExprTeeLocal: { LocalIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; auto value = Pop(0, local_type_vec_[imm.index]); auto* result = Push(value.type); CALL_INTERFACE_IF_REACHABLE(TeeLocal, value, result, imm); len = 1 + imm.length; break; } case kExprDrop: { auto value = Pop(); CALL_INTERFACE_IF_REACHABLE(Drop, value); break; } case kExprGetGlobal: { GlobalIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; auto* result = Push(imm.type); CALL_INTERFACE_IF_REACHABLE(GetGlobal, result, imm); break; } case kExprSetGlobal: { GlobalIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; if (!VALIDATE(imm.global->mutability)) { this->errorf(this->pc_, "immutable global #%u cannot be assigned", imm.index); break; } auto value = Pop(0, imm.type); CALL_INTERFACE_IF_REACHABLE(SetGlobal, value, imm); break; } case kExprI32LoadMem8S: len = 1 + DecodeLoadMem(LoadType::kI32Load8S); break; case kExprI32LoadMem8U: len = 1 + DecodeLoadMem(LoadType::kI32Load8U); break; case kExprI32LoadMem16S: len = 1 + DecodeLoadMem(LoadType::kI32Load16S); break; case kExprI32LoadMem16U: len = 1 + DecodeLoadMem(LoadType::kI32Load16U); break; case kExprI32LoadMem: len = 1 + DecodeLoadMem(LoadType::kI32Load); break; case kExprI64LoadMem8S: len = 1 + DecodeLoadMem(LoadType::kI64Load8S); break; case kExprI64LoadMem8U: len = 1 + DecodeLoadMem(LoadType::kI64Load8U); break; case kExprI64LoadMem16S: len = 1 + DecodeLoadMem(LoadType::kI64Load16S); break; case kExprI64LoadMem16U: len = 1 + DecodeLoadMem(LoadType::kI64Load16U); break; case kExprI64LoadMem32S: len = 1 + DecodeLoadMem(LoadType::kI64Load32S); break; case kExprI64LoadMem32U: len = 1 + DecodeLoadMem(LoadType::kI64Load32U); break; case kExprI64LoadMem: len = 1 + DecodeLoadMem(LoadType::kI64Load); break; case kExprF32LoadMem: len = 1 + DecodeLoadMem(LoadType::kF32Load); break; case kExprF64LoadMem: len = 1 + DecodeLoadMem(LoadType::kF64Load); break; case kExprI32StoreMem8: len = 1 + DecodeStoreMem(StoreType::kI32Store8); break; case kExprI32StoreMem16: len = 1 + DecodeStoreMem(StoreType::kI32Store16); break; case kExprI32StoreMem: len = 1 + DecodeStoreMem(StoreType::kI32Store); break; case kExprI64StoreMem8: len = 1 + DecodeStoreMem(StoreType::kI64Store8); break; case kExprI64StoreMem16: len = 1 + DecodeStoreMem(StoreType::kI64Store16); break; case kExprI64StoreMem32: len = 1 + DecodeStoreMem(StoreType::kI64Store32); break; case kExprI64StoreMem: len = 1 + DecodeStoreMem(StoreType::kI64Store); break; case kExprF32StoreMem: len = 1 + DecodeStoreMem(StoreType::kF32Store); break; case kExprF64StoreMem: len = 1 + DecodeStoreMem(StoreType::kF64Store); break; case kExprMemoryGrow: { if (!CheckHasMemory()) break; MemoryIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; DCHECK_NOT_NULL(this->module_); if (!VALIDATE(this->module_->origin == kWasmOrigin)) { this->error("grow_memory is not supported for asmjs modules"); break; } auto value = Pop(0, kWasmI32); auto* result = Push(kWasmI32); CALL_INTERFACE_IF_REACHABLE(MemoryGrow, value, result); break; } case kExprMemorySize: { if (!CheckHasMemory()) break; MemoryIndexImmediate<validate> imm(this, this->pc_); auto* result = Push(kWasmI32); len = 1 + imm.length; CALL_INTERFACE_IF_REACHABLE(CurrentMemoryPages, result); break; } case kExprCallFunction: { CallFunctionImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; // TODO(clemensh): Better memory management. PopArgs(imm.sig); auto* returns = PushReturns(imm.sig); CALL_INTERFACE_IF_REACHABLE(CallDirect, imm, args_.data(), returns); break; } case kExprCallIndirect: { CallIndirectImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; auto index = Pop(0, kWasmI32); PopArgs(imm.sig); auto* returns = PushReturns(imm.sig); CALL_INTERFACE_IF_REACHABLE(CallIndirect, index, imm, args_.data(), returns); break; } case kNumericPrefix: { ++len; byte numeric_index = this->template read_u8<validate>( this->pc_ + 1, "numeric index"); opcode = static_cast<WasmOpcode>(opcode << 8 | numeric_index); if (opcode < kExprMemoryInit) { CHECK_PROTOTYPE_OPCODE(sat_f2i_conversions); } else { CHECK_PROTOTYPE_OPCODE(bulk_memory); } TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(opcode)); len += DecodeNumericOpcode(opcode); break; } case kSimdPrefix: { CHECK_PROTOTYPE_OPCODE(simd); len++; byte simd_index = this->template read_u8<validate>(this->pc_ + 1, "simd index"); opcode = static_cast<WasmOpcode>(opcode << 8 | simd_index); TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(opcode)); len += DecodeSimdOpcode(opcode); break; } case kAtomicPrefix: { CHECK_PROTOTYPE_OPCODE(threads); if (!CheckHasSharedMemory()) break; len++; byte atomic_index = this->template read_u8<validate>(this->pc_ + 1, "atomic index"); opcode = static_cast<WasmOpcode>(opcode << 8 | atomic_index); TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(opcode)); len += DecodeAtomicOpcode(opcode); break; } // Note that prototype opcodes are not handled in the fastpath // above this switch, to avoid checking a feature flag. #define SIMPLE_PROTOTYPE_CASE(name, opc, sig) \ case kExpr##name: /* fallthrough */ FOREACH_SIMPLE_PROTOTYPE_OPCODE(SIMPLE_PROTOTYPE_CASE) #undef SIMPLE_PROTOTYPE_CASE BuildSimplePrototypeOperator(opcode); break; default: { // Deal with special asmjs opcodes. if (this->module_ != nullptr && this->module_->origin == kAsmJsOrigin) { sig = WasmOpcodes::AsmjsSignature(opcode); if (sig) { BuildSimpleOperator(opcode, sig); } } else { this->error("Invalid opcode"); return; } } } } #if DEBUG if (FLAG_trace_wasm_decoder) { TRACE_PART(" "); for (Control& c : control_) { switch (c.kind) { case kControlIf: TRACE_PART("I"); break; case kControlBlock: TRACE_PART("B"); break; case kControlLoop: TRACE_PART("L"); break; case kControlTry: TRACE_PART("T"); break; default: break; } if (c.start_merge.arity) TRACE_PART("%u-", c.start_merge.arity); TRACE_PART("%u", c.end_merge.arity); if (!c.reachable()) TRACE_PART("%c", c.unreachable() ? '*' : '#'); } TRACE_PART(" | "); for (size_t i = 0; i < stack_.size(); ++i) { auto& val = stack_[i]; WasmOpcode opcode = static_cast<WasmOpcode>(*val.pc); if (WasmOpcodes::IsPrefixOpcode(opcode)) { opcode = static_cast<WasmOpcode>(opcode << 8 | *(val.pc + 1)); } TRACE_PART(" %c@%d:%s", ValueTypes::ShortNameOf(val.type), static_cast<int>(val.pc - this->start_), WasmOpcodes::OpcodeName(opcode)); // If the decoder failed, don't try to decode the immediates, as this // can trigger a DCHECK failure. if (this->failed()) continue; switch (opcode) { case kExprI32Const: { ImmI32Immediate<Decoder::kNoValidate> imm(this, val.pc); TRACE_PART("[%d]", imm.value); break; } case kExprGetLocal: case kExprSetLocal: case kExprTeeLocal: { LocalIndexImmediate<Decoder::kNoValidate> imm(this, val.pc); TRACE_PART("[%u]", imm.index); break; } case kExprGetGlobal: case kExprSetGlobal: { GlobalIndexImmediate<Decoder::kNoValidate> imm(this, val.pc); TRACE_PART("[%u]", imm.index); break; } default: break; } } } #endif this->pc_ += len; } // end decode loop if (!VALIDATE(this->pc_ == this->end_) && this->ok()) { this->error("Beyond end of code"); } } void EndControl() { DCHECK(!control_.empty()); auto* current = &control_.back(); stack_.resize(current->stack_depth); CALL_INTERFACE_IF_REACHABLE(EndControl, current); current->reachability = kUnreachable; } template<typename func> void InitMerge(Merge<Value>* merge, uint32_t arity, func get_val) { merge->arity = arity; if (arity == 1) { merge->vals.first = get_val(0); } else if (arity > 1) { merge->vals.array = zone_->NewArray<Value>(arity); for (unsigned i = 0; i < arity; i++) { merge->vals.array[i] = get_val(i); } } } void SetBlockType(Control* c, BlockTypeImmediate<validate>& imm) { DCHECK_EQ(imm.in_arity(), this->args_.size()); const byte* pc = this->pc_; Value* args = this->args_.data(); InitMerge(&c->end_merge, imm.out_arity(), [pc, &imm](uint32_t i) { return Value::New(pc, imm.out_type(i)); }); InitMerge(&c->start_merge, imm.in_arity(), [args](uint32_t i) { return args[i]; }); } // Pops arguments as required by signature into {args_}. V8_INLINE void PopArgs(FunctionSig* sig) { int count = sig ? static_cast<int>(sig->parameter_count()) : 0; args_.resize(count); for (int i = count - 1; i >= 0; --i) { args_[i] = Pop(i, sig->GetParam(i)); } } ValueType GetReturnType(FunctionSig* sig) { DCHECK_GE(1, sig->return_count()); return sig->return_count() == 0 ? kWasmStmt : sig->GetReturn(); } Control* PushControl(Control&& new_control) { Reachability reachability = control_.empty() ? kReachable : control_.back().innerReachability(); control_.emplace_back(std::move(new_control)); Control* c = &control_.back(); c->reachability = reachability; c->start_merge.reached = c->reachable(); return c; } Control* PushBlock() { return PushControl(Control::Block(this->pc_, stack_size())); } Control* PushLoop() { return PushControl(Control::Loop(this->pc_, stack_size())); } Control* PushIf() { return PushControl(Control::If(this->pc_, stack_size())); } Control* PushTry() { // current_catch_ = static_cast<int32_t>(control_.size() - 1); return PushControl(Control::Try(this->pc_, stack_size())); } void PopControl(Control* c) { DCHECK_EQ(c, &control_.back()); CALL_INTERFACE_IF_PARENT_REACHABLE(PopControl, c); bool reached = c->end_merge.reached; control_.pop_back(); // If the parent block was reachable before, but the popped control does not // return to here, this block becomes indirectly unreachable. if (!control_.empty() && !reached && control_.back().reachable()) { control_.back().reachability = kSpecOnlyReachable; } } int DecodeLoadMem(LoadType type, int prefix_len = 0) { if (!CheckHasMemory()) return 0; MemoryAccessImmediate<validate> imm(this, this->pc_ + prefix_len, type.size_log_2()); auto index = Pop(0, kWasmI32); auto* result = Push(type.value_type()); CALL_INTERFACE_IF_REACHABLE(LoadMem, type, imm, index, result); return imm.length; } int DecodeStoreMem(StoreType store, int prefix_len = 0) { if (!CheckHasMemory()) return 0; MemoryAccessImmediate<validate> imm(this, this->pc_ + prefix_len, store.size_log_2()); auto value = Pop(1, store.value_type()); auto index = Pop(0, kWasmI32); CALL_INTERFACE_IF_REACHABLE(StoreMem, store, imm, index, value); return imm.length; } unsigned SimdExtractLane(WasmOpcode opcode, ValueType type) { SimdLaneImmediate<validate> imm(this, this->pc_); if (this->Validate(this->pc_, opcode, imm)) { Value inputs[] = {Pop(0, kWasmS128)}; auto* result = Push(type); CALL_INTERFACE_IF_REACHABLE(SimdLaneOp, opcode, imm, ArrayVector(inputs), result); } return imm.length; } unsigned SimdReplaceLane(WasmOpcode opcode, ValueType type) { SimdLaneImmediate<validate> imm(this, this->pc_); if (this->Validate(this->pc_, opcode, imm)) { Value inputs[2]; inputs[1] = Pop(1, type); inputs[0] = Pop(0, kWasmS128); auto* result = Push(kWasmS128); CALL_INTERFACE_IF_REACHABLE(SimdLaneOp, opcode, imm, ArrayVector(inputs), result); } return imm.length; } unsigned SimdShiftOp(WasmOpcode opcode) { SimdShiftImmediate<validate> imm(this, this->pc_); if (this->Validate(this->pc_, opcode, imm)) { auto input = Pop(0, kWasmS128); auto* result = Push(kWasmS128); CALL_INTERFACE_IF_REACHABLE(SimdShiftOp, opcode, imm, input, result); } return imm.length; } unsigned Simd8x16ShuffleOp() { Simd8x16ShuffleImmediate<validate> imm(this, this->pc_); if (this->Validate(this->pc_, imm)) { auto input1 = Pop(1, kWasmS128); auto input0 = Pop(0, kWasmS128); auto* result = Push(kWasmS128); CALL_INTERFACE_IF_REACHABLE(Simd8x16ShuffleOp, imm, input0, input1, result); } return 16; } unsigned DecodeSimdOpcode(WasmOpcode opcode) { unsigned len = 0; switch (opcode) { case kExprF32x4ExtractLane: { len = SimdExtractLane(opcode, kWasmF32); break; } case kExprI32x4ExtractLane: case kExprI16x8ExtractLane: case kExprI8x16ExtractLane: { len = SimdExtractLane(opcode, kWasmI32); break; } case kExprF32x4ReplaceLane: { len = SimdReplaceLane(opcode, kWasmF32); break; } case kExprI32x4ReplaceLane: case kExprI16x8ReplaceLane: case kExprI8x16ReplaceLane: { len = SimdReplaceLane(opcode, kWasmI32); break; } case kExprI32x4Shl: case kExprI32x4ShrS: case kExprI32x4ShrU: case kExprI16x8Shl: case kExprI16x8ShrS: case kExprI16x8ShrU: case kExprI8x16Shl: case kExprI8x16ShrS: case kExprI8x16ShrU: { len = SimdShiftOp(opcode); break; } case kExprS8x16Shuffle: { len = Simd8x16ShuffleOp(); break; } case kExprS128LoadMem: len = DecodeLoadMem(LoadType::kS128Load, 1); break; case kExprS128StoreMem: len = DecodeStoreMem(StoreType::kS128Store, 1); break; default: { FunctionSig* sig = WasmOpcodes::Signature(opcode); if (!VALIDATE(sig != nullptr)) { this->error("invalid simd opcode"); break; } PopArgs(sig); auto* results = sig->return_count() == 0 ? nullptr : Push(GetReturnType(sig)); CALL_INTERFACE_IF_REACHABLE(SimdOp, opcode, VectorOf(args_), results); } } return len; } unsigned DecodeAtomicOpcode(WasmOpcode opcode) { unsigned len = 0; ValueType ret_type; FunctionSig* sig = WasmOpcodes::Signature(opcode); if (sig != nullptr) { MachineType memtype; switch (opcode) { #define CASE_ATOMIC_STORE_OP(Name, Type) \ case kExpr##Name: { \ memtype = MachineType::Type(); \ ret_type = kWasmStmt; \ break; \ } ATOMIC_STORE_OP_LIST(CASE_ATOMIC_STORE_OP) #undef CASE_ATOMIC_OP #define CASE_ATOMIC_OP(Name, Type) \ case kExpr##Name: { \ memtype = MachineType::Type(); \ ret_type = GetReturnType(sig); \ break; \ } ATOMIC_OP_LIST(CASE_ATOMIC_OP) #undef CASE_ATOMIC_OP default: this->error("invalid atomic opcode"); return 0; } MemoryAccessImmediate<validate> imm( this, this->pc_ + 1, ElementSizeLog2Of(memtype.representation())); len += imm.length; PopArgs(sig); auto result = ret_type == kWasmStmt ? nullptr : Push(GetReturnType(sig)); CALL_INTERFACE_IF_REACHABLE(AtomicOp, opcode, VectorOf(args_), imm, result); } else { this->error("invalid atomic opcode"); } return len; } unsigned DecodeNumericOpcode(WasmOpcode opcode) { unsigned len = 0; FunctionSig* sig = WasmOpcodes::Signature(opcode); if (sig != nullptr) { switch (opcode) { case kExprI32SConvertSatF32: case kExprI32UConvertSatF32: case kExprI32SConvertSatF64: case kExprI32UConvertSatF64: case kExprI64SConvertSatF32: case kExprI64UConvertSatF32: case kExprI64SConvertSatF64: case kExprI64UConvertSatF64: BuildSimpleOperator(opcode, sig); break; case kExprMemoryInit: { MemoryInitImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(MemoryInit, imm, VectorOf(args_)); break; } case kExprMemoryDrop: { MemoryDropImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; CALL_INTERFACE_IF_REACHABLE(MemoryDrop, imm); break; } case kExprMemoryCopy: { MemoryIndexImmediate<validate> imm(this, this->pc_ + 1); if (!this->Validate(imm)) break; len += imm.length; PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(MemoryCopy, imm, VectorOf(args_)); break; } case kExprMemoryFill: { MemoryIndexImmediate<validate> imm(this, this->pc_ + 1); if (!this->Validate(imm)) break; len += imm.length; PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(MemoryFill, imm, VectorOf(args_)); break; } case kExprTableInit: { TableInitImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(TableInit, imm, VectorOf(args_)); break; } case kExprTableDrop: { TableDropImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; CALL_INTERFACE_IF_REACHABLE(TableDrop, imm); break; } case kExprTableCopy: { TableIndexImmediate<validate> imm(this, this->pc_ + 1); if (!this->Validate(this->pc_ + 1, imm)) break; len += imm.length; PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(TableCopy, imm, VectorOf(args_)); break; } default: this->error("invalid numeric opcode"); break; } } else { this->error("invalid numeric opcode"); } return len; } void DoReturn(Control* c, bool implicit) { int return_count = static_cast<int>(this->sig_->return_count()); args_.resize(return_count); // Pop return values off the stack in reverse order. for (int i = return_count - 1; i >= 0; --i) { args_[i] = Pop(i, this->sig_->GetReturn(i)); } // Simulate that an implicit return morally comes after the current block. if (implicit && c->end_merge.reached) c->reachability = kReachable; CALL_INTERFACE_IF_REACHABLE(DoReturn, VectorOf(args_), implicit); EndControl(); } inline Value* Push(ValueType type) { DCHECK_NE(kWasmStmt, type); stack_.push_back(Value::New(this->pc_, type)); return &stack_.back(); } void PushMergeValues(Control* c, Merge<Value>* merge) { DCHECK_EQ(c, &control_.back()); DCHECK(merge == &c->start_merge || merge == &c->end_merge); stack_.resize(c->stack_depth); if (merge->arity == 1) { stack_.push_back(merge->vals.first); } else { for (unsigned i = 0; i < merge->arity; i++) { stack_.push_back(merge->vals.array[i]); } } DCHECK_EQ(c->stack_depth + merge->arity, stack_.size()); } Value* PushReturns(FunctionSig* sig) { size_t return_count = sig->return_count(); if (return_count == 0) return nullptr; size_t old_size = stack_.size(); for (size_t i = 0; i < return_count; ++i) { Push(sig->GetReturn(i)); } return stack_.data() + old_size; } Value Pop(int index, ValueType expected) { auto val = Pop(); if (!VALIDATE(val.type == expected || val.type == kWasmVar || expected == kWasmVar)) { this->errorf(val.pc, "%s[%d] expected type %s, found %s of type %s", SafeOpcodeNameAt(this->pc_), index, ValueTypes::TypeName(expected), SafeOpcodeNameAt(val.pc), ValueTypes::TypeName(val.type)); } return val; } Value Pop() { DCHECK(!control_.empty()); uint32_t limit = control_.back().stack_depth; if (stack_.size() <= limit) { // Popping past the current control start in reachable code. if (!VALIDATE(control_.back().unreachable())) { this->errorf(this->pc_, "%s found empty stack", SafeOpcodeNameAt(this->pc_)); } return Value::Unreachable(this->pc_); } auto val = stack_.back(); stack_.pop_back(); return val; } int startrel(const byte* ptr) { return static_cast<int>(ptr - this->start_); } void FallThruTo(Control* c) { DCHECK_EQ(c, &control_.back()); if (!TypeCheckFallThru(c)) return; if (!c->reachable()) return; if (!c->is_loop()) CALL_INTERFACE(FallThruTo, c); c->end_merge.reached = true; } bool TypeCheckMergeValues(Control* c, Merge<Value>* merge) { DCHECK(merge == &c->start_merge || merge == &c->end_merge); DCHECK_GE(stack_.size(), c->stack_depth + merge->arity); // Typecheck the topmost {merge->arity} values on the stack. for (uint32_t i = 0; i < merge->arity; ++i) { auto& val = GetMergeValueFromStack(c, merge, i); auto& old = (*merge)[i]; if (val.type != old.type) { // If {val.type} is polymorphic, which results from unreachable, make // it more specific by using the merge value's expected type. // If it is not polymorphic, this is a type error. if (!VALIDATE(val.type == kWasmVar)) { this->errorf( this->pc_, "type error in merge[%u] (expected %s, got %s)", i, ValueTypes::TypeName(old.type), ValueTypes::TypeName(val.type)); return false; } val.type = old.type; } } return true; } bool TypeCheckFallThru(Control* c) { DCHECK_EQ(c, &control_.back()); if (!validate) return true; uint32_t expected = c->end_merge.arity; DCHECK_GE(stack_.size(), c->stack_depth); uint32_t actual = static_cast<uint32_t>(stack_.size()) - c->stack_depth; // Fallthrus must match the arity of the control exactly. if (!InsertUnreachablesIfNecessary(expected, actual) || actual > expected) { this->errorf( this->pc_, "expected %u elements on the stack for fallthru to @%d, found %u", expected, startrel(c->pc), actual); return false; } return TypeCheckMergeValues(c, &c->end_merge); } bool TypeCheckBreak(Control* c) { // Breaks must have at least the number of values expected; can have more. uint32_t expected = c->br_merge()->arity; DCHECK_GE(stack_.size(), control_.back().stack_depth); uint32_t actual = static_cast<uint32_t>(stack_.size()) - control_.back().stack_depth; if (!InsertUnreachablesIfNecessary(expected, actual)) { this->errorf(this->pc_, "expected %u elements on the stack for br to @%d, found %u", expected, startrel(c->pc), actual); return false; } return TypeCheckMergeValues(c, c->br_merge()); } inline bool InsertUnreachablesIfNecessary(uint32_t expected, uint32_t actual) { if (V8_LIKELY(actual >= expected)) { return true; // enough actual values are there. } if (!VALIDATE(control_.back().unreachable())) { // There aren't enough values on the stack. return false; } // A slow path. When the actual number of values on the stack is less // than the expected number of values and the current control is // unreachable, insert unreachable values below the actual values. // This simplifies {TypeCheckMergeValues}. auto pos = stack_.begin() + (stack_.size() - actual); stack_.insert(pos, (expected - actual), Value::Unreachable(this->pc_)); return true; } void onFirstError() override { this->end_ = this->pc_; // Terminate decoding loop. TRACE(" !%s\n", this->error_msg_.c_str()); CALL_INTERFACE(OnFirstError); } void BuildSimplePrototypeOperator(WasmOpcode opcode) { if (WasmOpcodes::IsSignExtensionOpcode(opcode)) { RET_ON_PROTOTYPE_OPCODE(se); } if (WasmOpcodes::IsAnyRefOpcode(opcode)) { RET_ON_PROTOTYPE_OPCODE(anyref); } FunctionSig* sig = WasmOpcodes::Signature(opcode); BuildSimpleOperator(opcode, sig); } inline void BuildSimpleOperator(WasmOpcode opcode, FunctionSig* sig) { switch (sig->parameter_count()) { case 1: { auto val = Pop(0, sig->GetParam(0)); auto* ret = sig->return_count() == 0 ? nullptr : Push(sig->GetReturn(0)); CALL_INTERFACE_IF_REACHABLE(UnOp, opcode, sig, val, ret); break; } case 2: { auto rval = Pop(1, sig->GetParam(1)); auto lval = Pop(0, sig->GetParam(0)); auto* ret = sig->return_count() == 0 ? nullptr : Push(sig->GetReturn(0)); CALL_INTERFACE_IF_REACHABLE(BinOp, opcode, sig, lval, rval, ret); break; } default: UNREACHABLE(); } } }; #undef CALL_INTERFACE #undef CALL_INTERFACE_IF_REACHABLE #undef CALL_INTERFACE_IF_PARENT_REACHABLE class EmptyInterface { public: static constexpr Decoder::ValidateFlag validate = Decoder::kValidate; using Value = ValueBase; using Control = ControlBase<Value>; using FullDecoder = WasmFullDecoder<validate, EmptyInterface>; #define DEFINE_EMPTY_CALLBACK(name, ...) \ void name(FullDecoder* decoder, ##__VA_ARGS__) {} INTERFACE_FUNCTIONS(DEFINE_EMPTY_CALLBACK) #undef DEFINE_EMPTY_CALLBACK }; #undef TRACE #undef TRACE_INST_FORMAT #undef VALIDATE #undef CHECK_PROTOTYPE_OPCODE #undef OPCODE_ERROR } // namespace wasm } // namespace internal } // namespace v8 #endif // V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
71b890bbfa8cd04edb2d3e90575cff7cc89ef617
9f2b07eb0e9467e17448de413162a14f8207e5d0
/tests/libtests/feassemble/data/obsolete/QuadratureData2Din3DLinearXZ.hh
47471d569ccdd6ef604d51660f6ccae6cb36559c
[ "MIT" ]
permissive
fjiaqi/pylith
2aa3f7fdbd18f1205a5023f8c6c4182ff533c195
67bfe2e75e0a20bb55c93eb98bef7a9b3694523a
refs/heads/main
2023-09-04T19:24:51.783273
2021-10-19T17:01:41
2021-10-19T17:01:41
373,739,198
0
0
MIT
2021-06-04T06:12:08
2021-06-04T06:12:07
null
UTF-8
C++
false
false
1,876
hh
// -*- C++ -*- // // ====================================================================== // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ====================================================================== // // DO NOT EDIT THIS FILE // This file was generated from python application quadratureapp. #if !defined(pylith_feassemble_quadraturedata2din3dlinearxz_hh) #define pylith_feassemble_quadraturedata2din3dlinearxz_hh #include "QuadratureData.hh" namespace pylith { namespace feassemble { class QuadratureData2Din3DLinearXZ; } // pylith } // feassemble class pylith::feassemble::QuadratureData2Din3DLinearXZ : public QuadratureData { public: /// Constructor QuadratureData2Din3DLinearXZ(void); /// Destructor ~QuadratureData2Din3DLinearXZ(void); private: static const int _numVertices; static const int _spaceDim; static const int _numCells; static const int _cellDim; static const int _numBasis; static const int _numQuadPts; static const PylithScalar _vertices[]; static const int _cells[]; static const PylithScalar _verticesRef[]; static const PylithScalar _quadPtsRef[]; static const PylithScalar _quadWts[]; static const PylithScalar _quadPts[]; static const PylithScalar _basis[]; static const PylithScalar _basisDerivRef[]; static const PylithScalar _basisDeriv[]; static const PylithScalar _jacobian[]; static const PylithScalar _jacobianDet[]; static const PylithScalar _jacobianInv[]; }; #endif // pylith_feassemble_quadraturedata2din3dlinearxz_hh // End of file
[ "baagaard@usgs.gov" ]
baagaard@usgs.gov
76bd14cd1938eb0cd5b35e165787ce859d098eb0
5d7d151f671c5bb36c80bc43cfbe6b159c6d2e87
/baitap2_quanlisinhvien_2051120281/Menu.cpp
1ab3b1f8b055773d2914417cd889828ba7b6925a
[]
no_license
thanhnhut1112/baitap2_quanlisinhvien_2051120281
635249facb03e77692e1b0b3df50452766134039
3fd714d99f36e64ebbfec289439a9c0389ac9fa1
refs/heads/master
2023-08-25T03:48:24.530566
2021-10-10T10:17:00
2021-10-10T10:17:00
415,545,511
0
0
null
null
null
null
UTF-8
C++
false
false
781
cpp
#include "Menu.h" #include <iostream> using namespace std; Menu::Menu(string tieude) { this->tieude = tieude; } void Menu::themLuachon(string luachon) { dsLuachon.push_back(luachon); } void Menu::xuat() { cout << "\n-----" << tieude << "-----\n"; for (int i = 0; i < dsLuachon.size(); i++) cout << i << ". " << dsLuachon[i] << endl; } int Menu::chon() { int ch; do { xuat(); cout << "Moi chon?"; cin >> ch; //xoa ky tu xuong dong de cac lenh getline sau nay khong bi anh huong string tmp; getline(cin, tmp); if (ch < 0 || ch >= dsLuachon.size()) cout << "Chon sai, moi chon lai!!!\n"; } while (ch < 0 || ch >= dsLuachon.size());//Lap lai neu user chon sai return ch; }
[ "ACER@LAPTOP-OJ2GO58H" ]
ACER@LAPTOP-OJ2GO58H
672e494ccd23432ae64d7bf860354a9f58349334
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/boost/process/detail/windows/start_dir.hpp
09fdbbccf0337a971fb1e63ac819ff1807dc7de4
[ "BSL-1.0" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,035
hpp
// Copyright (c) 2006, 2007 Julio M. Merino Vidal // Copyright (c) 2008 Ilya Sokolov, Boris Schaeling // Copyright (c) 2009 Boris Schaeling // Copyright (c) 2010 Felipe Tanus, Boris Schaeling // Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling // // 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_PROCESS_DETAIL_WINDOWS_START_DIR_HPP #define BOOST_PROCESS_DETAIL_WINDOWS_START_DIR_HPP #include <string> #include <sstd/boost/process/detail/windows/handler.hpp> namespace boost { namespace process { namespace detail { namespace windows { template<typename Char> struct start_dir_init : handler_base_ext { start_dir_init(const std::basic_string<Char> &s) : s_(s) {} template <class Executor> void on_setup(Executor& exec) const { exec.work_dir = s_.c_str(); } const std::basic_string<Char> &str() const {return s_;} private: std::basic_string<Char> s_; }; }}}} #endif
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
d22653bdf8f35da66622bb14454648ae1b545001
44616f4a859b5b0ced95d77e3d6157fe569a8338
/src/ld24/Objects/Player.cpp
5af0d11709c8db8e65ca83c2da000f02b9511e74
[]
no_license
ydnax/ld24
857a0e136a0280de60765660198a479b9be5fa39
bec93f177847455b546be692368d2f5e7124c633
refs/heads/master
2016-08-05T13:03:43.514347
2012-08-27T21:46:04
2012-08-27T21:46:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,611
cpp
#include "Player.hpp" #include <ld24/Objects/Powerup.hpp> #include <SDL/SDL.h> namespace ld24{ Player::Player(Level *lvl, int x, int y): levelObject(lvl), x(x),y(y),xx(x),xy(y),xspeed(0), yspeed(0), images{{Image("resources/gfx/player/player-anim0.png", 50, 50), Image("resources/gfx/player/player-anim1.png", 50, 50), Image("resources/gfx/player/player-anim2.png", 50, 50) }}, r(this, mainwindow::player){ } bool Player::exit(){ SDL_Event event; while( SDL_PollEvent( &event ) ) { if( event.type == SDL_QUIT ) return true; } return false; } void Player::update(int ticks){ Uint8 *keystates = SDL_GetKeyState( NULL ); if( keystates[ SDLK_UP ] && onfloor && up_canjump){ yspeed+=-1*jumpspeed; } if( keystates[ SDLK_LEFT ] ){ xspeed =-1*(movespeed+up_walkspeed); chCount+=ticks; }else if( keystates[ SDLK_RIGHT ] ){ xspeed = (movespeed+up_walkspeed); chCount+=ticks; }else{ xspeed=0; } yspeed+=gravity*ticks/1000.; if(yspeed>maxdown){ yspeed=maxdown; } /* while(udChk(ticks)){ int dpx=yspeed*ticks/1000.; if( (dpx>5)||(dpx<-5)){ yspeed/=1.5; }else{ yspeed=0; } } //*/ if(udChk(ticks)){ yspeed=0; } if(rlChk(ticks)){ xspeed=0; } xx=xx+xspeed*ticks/1000.; x=xx; xy=xy+yspeed*ticks/1000.; y=xy; if(chCount>animationSpeed){ chCount=0; imgIndex++; imgIndex=imgIndex%images.size(); } checkPowerups(); auto img=images[imgIndex]; mwindow->ccx(xx+(img.w()/2)); } bool Player::udChk(int ticks){ auto img=images[imgIndex]; float ny=xy+yspeed*ticks/1000.; for(auto &&box:obstacles){ if(boxCollide({{int(xx+0.5),int(ny+0.5)},img.w(), img.h()}, box)){ if(yspeed>0) onfloor=true; return true; } } onfloor=false; return false; } bool Player::rlChk(int ticks){ auto img=images[imgIndex]; float nx=xx+xspeed*ticks/1000.; for(auto &&box: obstacles){ if(boxCollide({{int(nx+0.5),int(xy+0.5)},img.w(), img.h()}, box)){ return true; } } return false; } void Player::checkPowerups(){ auto img=images[imgIndex]; powerups.realDelete(); for(auto i : powerups.data()){ if(boxCollide({{x,y},img.w(), img.h()}, i->getInfo())){ i->Use()(this); return; } } } }
[ "gitmail.xandy@xoxy.net" ]
gitmail.xandy@xoxy.net
d7c9c437835516e835c27fb9d597e95e296deaaa
b00c54389a95d81a22e361fa9f8bdf5a2edc93e3
/external/lldb/source/Plugins/SymbolFile/DWARF/DWARFLocationList.h
85e11d90b36ba595b841c6d6c22bb59a248e0287
[ "NCSA" ]
permissive
mirek190/x86-android-5.0
9d1756fa7ff2f423887aa22694bd737eb634ef23
eb1029956682072bb7404192a80214189f0dc73b
refs/heads/master
2020-05-27T01:09:51.830208
2015-10-07T22:47:36
2015-10-07T22:47:36
41,942,802
15
20
null
2020-03-09T00:21:03
2015-09-05T00:11:19
null
UTF-8
C++
false
false
1,039
h
//===-- DWARFLocationList.h -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef SymbolFileDWARF_DWARFLocationList_h_ #define SymbolFileDWARF_DWARFLocationList_h_ #include "SymbolFileDWARF.h" class DWARFLocationList { public: static dw_offset_t Dump (lldb_private::Stream &s, const DWARFCompileUnit* cu, const lldb_private::DataExtractor& debug_loc_data, lldb::offset_t offset); static bool Extract (const lldb_private::DataExtractor& debug_loc_data, lldb::offset_t* offset_ptr, lldb_private::DataExtractor& location_list_data); static size_t Size (const lldb_private::DataExtractor& debug_loc_data, lldb::offset_t offset); }; #endif // SymbolFileDWARF_DWARFLocationList_h_
[ "mirek190@gmail.com" ]
mirek190@gmail.com
63627b98e20697c67425c5e795be608dfd7178a2
8d86646bc8e2835cf41c7548227dea11f43817f4
/p2/p2.ino
683d50b35b65072174239c013252d92eeab3f3ec
[]
no_license
mandrewcito/GEI-DHI
5d04fe4b4f230c9c514772c3929ec058ba4e49a5
df5b0c9bbd5f48d38b5328fd1295cc0f59598255
refs/heads/master
2020-12-03T05:25:00.071129
2015-01-30T21:09:54
2015-01-30T21:09:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,479
ino
/* p2 DHI andres baamonde lozano hora en hh:mm:ss(actualiza mediante interrupcion) por USART led rojo y verde encendidos con ss%2 (alternando) la puesta en hora enviando los datos desde la misma ventana de monitorización del puerto serie del IDE Arduino ->poner en modo de bajo consumo power-down mediante el envío de un valor de hora, minuto o segundo que exceda el valor máximo permitido, se apagan los 2 leds y con el pulsador (mediante interrupt ) se reinicia */ #include <MsTimer2.h> #include <avr/interrupt.h> #include <avr/sleep.h> const int buttonPin =3; const int verde =5; const int rojo = 10; boolean output = HIGH; String str=""; volatile int hora=0; volatile int minuto=0; volatile int segundo=0; volatile int darHora=HIGH; char horaE[3]; char minutoE[3]; char segundoE[3]; void flash() { digitalWrite(rojo, output); digitalWrite(verde, !output); output = !output; segundo++; if(segundo == 60) { minuto++; segundo=0; if (minuto==60){ hora++; minuto=0; if (hora==24){ minuto=0;segundo=0;hora=0; } } } darHora=HIGH; } void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); pinMode(buttonPin, INPUT); pinMode(verde, OUTPUT); pinMode(rojo, OUTPUT); set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here MsTimer2::set(1000, flash); // 1000ms period MsTimer2::start(); sleep_enable(); } void wakeUpNow(){ sleep_disable(); } void sleepNow(){ sleep_mode(); } // the loop routine runs over and over again forever: void loop() { /* si lo introducido no es valido */ while(Serial.available() > 0) { str = Serial.readStringUntil('\n'); horaE[0]=str.charAt(0);horaE[1]=str.charAt(1);minutoE[0]=str.charAt(3);minutoE[1]=str.charAt(4);segundoE[0]=str.charAt(6);segundoE[1]=str.charAt(7); if(atoi(horaE)>23 || atoi(minutoE)>59 ||atoi(segundoE)>59){ Serial.println("paso a modo power-down"); Serial.flush(); digitalWrite(rojo, LOW); digitalWrite(verde, LOW); attachInterrupt(1, wakeUpNow, HIGH); sleepNow(); detachInterrupt(1); }else{ hora=atoi(horaE); minuto=atoi(minutoE); segundo=atoi(segundoE); } } if (darHora){ Serial.print(hora); Serial.print(":"); Serial.print(minuto); Serial.print(":"); Serial.print(segundo); Serial.print("\n"); darHora=LOW; } }
[ "anbaalo@gmail.com" ]
anbaalo@gmail.com
52d01452c58ef32728d1d612324793e3bc746953
cee3d4b65ead71f22db1d1aacad1e0958657b8f3
/LAB4.cpp
92d3aaea85e840e2c132b0a8abd548b849880768
[]
no_license
IliaTrofimov/Object-table-viewer
431a203a15bf8e200a041964fa8af4172ca57989
fdb5f22ef8efec736994097e53a26c575ab2ac63
refs/heads/main
2023-04-09T11:23:02.741674
2021-04-25T09:00:30
2021-04-25T09:00:30
361,372,093
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,162
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include <tchar.h> //--------------------------------------------------------------------------- USEFORM("NumberEntryFormClass.cpp", formNumEntry); USEFORM("ResultFormClass.cpp", formResult); USEFORM("SearchFormClass.cpp", searchForm); USEFORM("MainFormClass.cpp", mainForm); USEFORM("ABOUT.cpp", AboutBox); USEFORM("EditFormClass.cpp", formEdit); //--------------------------------------------------------------------------- int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int) { try { setlocale(LC_ALL,"russian"); Application->Initialize(); Application->MainFormOnTaskBar = true; Application->Title = "Список зоопарков"; Application->CreateForm(__classid(TmainForm), &mainForm); Application->Run(); } catch (Exception &exception) { Application->ShowException(&exception); } catch (...) { try { throw Exception(""); } catch (Exception &exception) { Application->ShowException(&exception); } } return 0; } //---------------------------------------------------------------------------
[ "ilia.trofimov2001@icloud.com" ]
ilia.trofimov2001@icloud.com
3a828da55345c4cfa9088ce1a363f849e4421212
e2227524377dbb7641d3eabb7d7a4db835ee2bae
/maxProfit3/maxProfit3/maxProfit3.cpp
49a610653f434c7c06db91eb463cc73a4a30342d
[]
no_license
tezheng/LeetCode
a7a920e0e9c880a0589efc98ad4f551243af2dc3
1ae450d469076228b5e720480d1d2ff877ffc14e
refs/heads/master
2021-01-16T18:01:08.048098
2013-05-11T13:23:20
2013-05-11T13:23:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
994
cpp
#include <vector> using namespace std; int main() { vector<int> prices; prices.push_back(1); if(prices.size() == 0) return 0; vector<int> firstprofit; firstprofit.push_back(0); firstprofit.push_back(0); vector<int> secondprofit; secondprofit.push_back(0); secondprofit.push_back(0); int min = prices[0]; int profit = 0; for(int i = 1; i< prices.size(); i++) { if(prices[i] < min) min =prices[i]; if(prices[i] - min > profit) profit = prices[i] - min; firstprofit.push_back(profit); } reverse(prices.begin(),prices.end()); min = prices[0]; profit = 0; for(int i = 1; i< prices.size(); i++) { if(prices[i] > min) min =prices[i]; if(prices[i] - min < profit) profit = prices[i] - min; secondprofit.push_back(-profit); } reverse(secondprofit.begin(),secondprofit.end()); int maxprofit = 0; for(int i = 0;i<firstprofit.size();i++) { if(firstprofit[i] + secondprofit[i] > maxprofit) maxprofit = firstprofit[i] + secondprofit[i]; } return 0; }
[ "liumengxinfly@gmail.com" ]
liumengxinfly@gmail.com
4f1b210e15c07227fd419ea3bd7797549dca96ad
bd6e36612cd2e00f4e523af0adeccf0c5796185e
/include/clasp/core/lightProfiler.h
c06c5bba42ef71ebd0c8afbf7843c6c6c0c8331f
[]
no_license
robert-strandh/clasp
9efc8787501c0c5aa2480e82bb72b2a270bc889a
1e00c7212d6f9297f7c0b9b20b312e76e206cac2
refs/heads/master
2021-01-21T20:07:39.855235
2015-03-27T20:23:46
2015-03-27T20:23:46
33,315,546
1
0
null
2015-04-02T15:13:04
2015-04-02T15:13:04
null
UTF-8
C++
false
false
3,709
h
/* File: lightProfiler.h */ /* Copyright (c) 2014, Christian E. Schafmeister CLASP is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. See directory 'clasp/licenses' for full details. 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. */ /* -^- */ #ifdef darwin #include <stdint.h> #include <mach/mach_time.h> #else #include <time.h> #endif #include <clasp/core/foundation.h> #ifndef LightProfiler_H #define LightProfiler_H namespace core { class LightProfiler; class LightTimer { private: LightProfiler* _Profiler; uint _Id; bool _IsOn; double _AccumulatedTime; uint _Calls; uint _ClockResolutionFails; string _Description; uint _Parent; uint _Sibling; uint _Child; clock_t _StartTime; public: LightTimer(LightProfiler* profiler=NULL); void setup(uint id, const string& description, uint parent ) { this->_Id = id; this->_Description = description; this->_Parent = parent; } void reset() { this->_AccumulatedTime = 0.0; }; uint getId() { return this->_Id; }; bool getIsOn() { return this->_IsOn;}; uint getCalls() { return this->_Calls;}; string getDescription() { return this->_Description;}; uint getParent() { return this->_Parent;}; uint getSibling() { return this->_Sibling;}; uint getClockResolutionFails() { return this->_ClockResolutionFails;}; uint getChild() { return this->_Child;}; clock_t getStartTime() { return this->_StartTime;}; void setStartTime( const clock_t& t) { this->_StartTime = t;}; void start(); void stop(); void addChild(uint child); uint getNumberOfCalls() { return this->_Calls;}; double getAccumulatedTime() { return this->_AccumulatedTime;}; }; class LightEventCounter { private: string _Description; uint _Calls; uint _Problems; public: void setDescription(string desc) { this->_Description = desc;}; string getDescription() { return this->_Description;}; void recordCallAndProblem(bool problem); uint getCalls() {return this->_Calls;}; uint getProblems() {return this->_Problems;}; LightEventCounter(); virtual ~LightEventCounter(); }; class LightProfiler { public: LightProfiler(); private: vector<LightTimer> _Timers; vector<LightEventCounter> _EventCounters; vector< vector<bool> > _TimerStateStack; bool _MessagesEnabled; public: // LightTimer* getTimer(int id); // LightTimer* createTimer(uint parent, uint id, // const string& name); void createTimers(uint num); void resetAllTimers(); void stopAllTimers(); double getLongestTime(); uint createTimer(uint parent, const string& name); uint createEventCounter(string name); void pushTimerStates(); void popTimerStates(); void disableMessages(); LightTimer& timer(uint c); LightEventCounter& eventCounter(uint c); void dumpChildTimers(uint level, uint top); void dump(); virtual ~LightProfiler(); }; }; #endif
[ "chris.schaf@verizon.net" ]
chris.schaf@verizon.net
abcc79025bec29a21345f46cd35e39df7e0db8e5
272788cb066f9a29864b1b1da0396dbe6fa43304
/src/base58.h
7538a4eef54d1142db1869593e73c2b42b2f6fb0
[ "MIT" ]
permissive
cryptoandcoffee/pvp
223f43c96dbdf3ed9a0fb68ae64ab5aeec7a49ec
8233a7b21db0f6a2a56fbe46a81f79330c705c62
refs/heads/master
2020-12-13T17:26:53.940410
2020-01-17T06:17:05
2020-01-17T06:17:05
234,483,724
0
0
null
null
null
null
UTF-8
C++
false
false
5,817
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /** * Why base-58 instead of standard base-64 encoding? * - Don't want 0OIl characters that look the same in some fonts and * could be used to create visually identical looking data. * - A string with non-alphanumeric characters is not as easily accepted as input. * - E-mail usually won't line-break if there's no punctuation to break at. * - Double-clicking selects the whole string as one word if it's all alphanumeric. */ #ifndef BITCOIN_BASE58_H #define BITCOIN_BASE58_H #include "chainparams.h" #include "key.h" #include "pubkey.h" #include "script/script.h" #include "script/standard.h" #include "support/allocators/zeroafterfree.h" #include <string> #include <vector> /** * Encode a byte sequence as a base58-encoded string. * pbegin and pend cannot be NULL, unless both are. */ std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend); /** * Encode a byte vector as a base58-encoded string */ std::string EncodeBase58(const std::vector<unsigned char>& vch); /** * Decode a base58-encoded string (psz) into a byte vector (vchRet). * return true if decoding is successful. * psz cannot be NULL. */ bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet); /** * Decode a base58-encoded string (str) into a byte vector (vchRet). * return true if decoding is successful. */ bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet); /** * Encode a byte vector into a base58-encoded string, including checksum */ std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn); /** * Decode a base58-encoded string (psz) that includes a checksum into a byte * vector (vchRet), return true if decoding is successful */ inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet); /** * Decode a base58-encoded string (str) that includes a checksum into a byte * vector (vchRet), return true if decoding is successful */ inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet); /** * Base class for all base58-encoded data */ class CBase58Data { protected: //! the version byte(s) std::vector<unsigned char> vchVersion; //! the actually encoded data typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar; vector_uchar vchData; CBase58Data(); void SetData(const std::vector<unsigned char> &vchVersionIn, const void* pdata, size_t nSize); void SetData(const std::vector<unsigned char> &vchVersionIn, const unsigned char *pbegin, const unsigned char *pend); public: bool SetString(const char* psz, unsigned int nVersionBytes = 1); bool SetString(const std::string& str); std::string ToString() const; int CompareTo(const CBase58Data& b58) const; bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; } bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; } bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; } bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; } bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; } }; /** base58-encoded PlayerVsPlayerCoin addresses. * Public-key-hash-addresses have version 76 (or 140 testnet). * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key. * Script-hash-addresses have version 16 (or 19 testnet). * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script. */ class CBitcoinAddress : public CBase58Data { public: bool Set(const CKeyID &id); bool Set(const CScriptID &id); bool Set(const CTxDestination &dest); bool IsValid() const; bool IsValid(const CChainParams &params) const; CBitcoinAddress() {} CBitcoinAddress(const CTxDestination &dest) { Set(dest); } CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); } CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); } CTxDestination Get() const; bool GetKeyID(CKeyID &keyID) const; bool GetIndexKey(uint160& hashBytes, int& type) const; bool IsScript() const; }; /** * A base58-encoded secret key */ class CBitcoinSecret : public CBase58Data { public: void SetKey(const CKey& vchSecret); CKey GetKey(); bool IsValid() const; bool SetString(const char* pszSecret); bool SetString(const std::string& strSecret); CBitcoinSecret(const CKey& vchSecret) { SetKey(vchSecret); } CBitcoinSecret() {} }; template<typename K, int Size, CChainParams::Base58Type Type> class CBitcoinExtKeyBase : public CBase58Data { public: void SetKey(const K &key) { unsigned char vch[Size]; key.Encode(vch); SetData(Params().Base58Prefix(Type), vch, vch+Size); } K GetKey() { K ret; if (vchData.size() == Size) { // If base58 encoded data does not hold an ext key, return a !IsValid() key ret.Decode(&vchData[0]); } return ret; } CBitcoinExtKeyBase(const K &key) { SetKey(key); } CBitcoinExtKeyBase(const std::string& strBase58c) { SetString(strBase58c.c_str(), Params().Base58Prefix(Type).size()); } CBitcoinExtKeyBase() {} }; typedef CBitcoinExtKeyBase<CExtKey, BIP32_EXTKEY_SIZE, CChainParams::EXT_SECRET_KEY> CBitcoinExtKey; typedef CBitcoinExtKeyBase<CExtPubKey, BIP32_EXTKEY_SIZE, CChainParams::EXT_PUBLIC_KEY> CBitcoinExtPubKey; #endif // BITCOIN_BASE58_H
[ "wildsf@djfrencht0ast.com" ]
wildsf@djfrencht0ast.com
f01270a0d22554283d01efc7cd027707706b8251
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/git/gumtree/git_patch_hunk_211.cpp
581bb823fedd728675c71c8458167603aaf487c5
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,003
cpp
* alias twice, because that implies that there were actually two * different files with aliasing names! * * So we use the CE_ADDED flag to verify that the alias was an old * one before we accept it as */ -static struct cache_entry *create_alias_ce(struct cache_entry *ce, struct cache_entry *alias) +static struct cache_entry *create_alias_ce(struct index_state *istate, + struct cache_entry *ce, + struct cache_entry *alias) { int len; struct cache_entry *new; if (alias->ce_flags & CE_ADDED) die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name); /* Ok, create the new entry using the name of the existing alias */ len = ce_namelen(alias); new = xcalloc(1, cache_entry_size(len)); memcpy(new->name, alias->name, len); copy_cache_entry(new, ce); - free(ce); + save_or_free_index_entry(istate, ce); return new; } void set_object_name_for_intent_to_add_entry(struct cache_entry *ce) { unsigned char sha1[20];
[ "993273596@qq.com" ]
993273596@qq.com
f8d7b6804b696b4bf745573231ef68f1aefbc0b1
07aaed7174217ad11f873ec37776f1bacff5d314
/src/bindings/openFrameworks/ofMesh.cpp
cf490f131fd657d5317a5c2059506484f53939fe
[]
no_license
hackathon-ro/ofxMoonLight
2d774fb7a0e01c8f948989669f6f2cbd8df00b4c
94e3075b1c3a22c4f99a1628ceceb33dbcbc8635
refs/heads/master
2021-01-22T12:08:50.954001
2013-05-01T13:54:07
2013-05-01T13:54:07
9,562,505
1
2
null
null
null
null
UTF-8
C++
false
false
47,141
cpp
/** * * MACHINE GENERATED FILE. DO NOT EDIT. * * Bindings for class ofMesh * * This file has been generated by dub 2.1.~. */ #include "dub/dub.h" #include "3d/ofMesh.h" /** ofMesh::ofMesh() * api/openFrameworks/3d/ofMesh.h:13 */ static int ofMesh_ofMesh(lua_State *L) { try { int top__ = lua_gettop(L); if (top__ >= 2) { ofPrimitiveMode mode = (ofPrimitiveMode)dub_checkint(L, 1); vector< ofVec3f > *verts = *((vector< ofVec3f > **)dub_checksdata(L, 2, "vector< ofVec3f >")); ofMesh *retval__ = new ofMesh(mode, *verts); dub_pushudata(L, retval__, "ofMesh", true); return 1; } else { ofMesh *retval__ = new ofMesh(); dub_pushudata(L, retval__, "ofMesh", true); return 1; } } catch (std::exception &e) { lua_pushfstring(L, "new: %s", e.what()); } catch (...) { lua_pushfstring(L, "new: Unknown exception"); } return dub_error(L); } /** virtual ofMesh::~ofMesh() * api/openFrameworks/3d/ofMesh.h:15 */ static int ofMesh__ofMesh(lua_State *L) { try { DubUserdata *userdata = ((DubUserdata*)dub_checksdata_d(L, 1, "ofMesh")); if (userdata->gc) { ofMesh *self = (ofMesh *)userdata->ptr; delete self; } userdata->gc = false; return 0; } catch (std::exception &e) { lua_pushfstring(L, "__gc: %s", e.what()); } catch (...) { lua_pushfstring(L, "__gc: Unknown exception"); } return dub_error(L); } /** void ofMesh::setMode(ofPrimitiveMode mode) * api/openFrameworks/3d/ofMesh.h:17 */ static int ofMesh_setMode(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofPrimitiveMode mode = (ofPrimitiveMode)dub_checkint(L, 2); self->setMode(mode); return 0; } catch (std::exception &e) { lua_pushfstring(L, "setMode: %s", e.what()); } catch (...) { lua_pushfstring(L, "setMode: Unknown exception"); } return dub_error(L); } /** ofPrimitiveMode ofMesh::getMode() const * api/openFrameworks/3d/ofMesh.h:18 */ static int ofMesh_getMode(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushnumber(L, self->getMode()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getMode: %s", e.what()); } catch (...) { lua_pushfstring(L, "getMode: Unknown exception"); } return dub_error(L); } /** void ofMesh::clear() * api/openFrameworks/3d/ofMesh.h:20 */ static int ofMesh_clear(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->clear(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "clear: %s", e.what()); } catch (...) { lua_pushfstring(L, "clear: Unknown exception"); } return dub_error(L); } /** void ofMesh::setupIndicesAuto() * api/openFrameworks/3d/ofMesh.h:22 */ static int ofMesh_setupIndicesAuto(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->setupIndicesAuto(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "setupIndicesAuto: %s", e.what()); } catch (...) { lua_pushfstring(L, "setupIndicesAuto: Unknown exception"); } return dub_error(L); } /** ofVec3f ofMesh::getVertex(ofIndexType i) const * api/openFrameworks/3d/ofMesh.h:24 */ static int ofMesh_getVertex(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *i = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); dub_pushudata(L, new ofVec3f(self->getVertex(*i)), "ofVec3f", true); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getVertex: %s", e.what()); } catch (...) { lua_pushfstring(L, "getVertex: Unknown exception"); } return dub_error(L); } /** void ofMesh::addVertex(const ofVec3f &v) * api/openFrameworks/3d/ofMesh.h:25 */ static int ofMesh_addVertex(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofVec3f *v = *((ofVec3f **)dub_checksdata(L, 2, "ofVec3f")); self->addVertex(*v); return 0; } catch (std::exception &e) { lua_pushfstring(L, "addVertex: %s", e.what()); } catch (...) { lua_pushfstring(L, "addVertex: Unknown exception"); } return dub_error(L); } /** void ofMesh::addVertices(const vector< ofVec3f > &verts) * api/openFrameworks/3d/ofMesh.h:26 */ static int ofMesh_addVertices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); int top__ = lua_gettop(L); if (top__ >= 3) { ofVec3f *verts = *((ofVec3f **)dub_checksdata(L, 2, "ofVec3f")); int amt = dub_checkint(L, 3); self->addVertices(verts, amt); return 0; } else { vector< ofVec3f > *verts = *((vector< ofVec3f > **)dub_checksdata(L, 2, "vector< ofVec3f >")); self->addVertices(*verts); return 0; } } catch (std::exception &e) { lua_pushfstring(L, "addVertices: %s", e.what()); } catch (...) { lua_pushfstring(L, "addVertices: Unknown exception"); } return dub_error(L); } /** void ofMesh::removeVertex(ofIndexType index) * api/openFrameworks/3d/ofMesh.h:28 */ static int ofMesh_removeVertex(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *index = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); self->removeVertex(*index); return 0; } catch (std::exception &e) { lua_pushfstring(L, "removeVertex: %s", e.what()); } catch (...) { lua_pushfstring(L, "removeVertex: Unknown exception"); } return dub_error(L); } /** void ofMesh::setVertex(ofIndexType index, const ofVec3f &v) * api/openFrameworks/3d/ofMesh.h:29 */ static int ofMesh_setVertex(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *index = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); ofVec3f *v = *((ofVec3f **)dub_checksdata(L, 3, "ofVec3f")); self->setVertex(*index, *v); return 0; } catch (std::exception &e) { lua_pushfstring(L, "setVertex: %s", e.what()); } catch (...) { lua_pushfstring(L, "setVertex: Unknown exception"); } return dub_error(L); } /** void ofMesh::clearVertices() * api/openFrameworks/3d/ofMesh.h:30 */ static int ofMesh_clearVertices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->clearVertices(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "clearVertices: %s", e.what()); } catch (...) { lua_pushfstring(L, "clearVertices: Unknown exception"); } return dub_error(L); } /** ofVec3f ofMesh::getNormal(ofIndexType i) const * api/openFrameworks/3d/ofMesh.h:32 */ static int ofMesh_getNormal(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *i = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); dub_pushudata(L, new ofVec3f(self->getNormal(*i)), "ofVec3f", true); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getNormal: %s", e.what()); } catch (...) { lua_pushfstring(L, "getNormal: Unknown exception"); } return dub_error(L); } /** void ofMesh::addNormal(const ofVec3f &n) * api/openFrameworks/3d/ofMesh.h:33 */ static int ofMesh_addNormal(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofVec3f *n = *((ofVec3f **)dub_checksdata(L, 2, "ofVec3f")); self->addNormal(*n); return 0; } catch (std::exception &e) { lua_pushfstring(L, "addNormal: %s", e.what()); } catch (...) { lua_pushfstring(L, "addNormal: Unknown exception"); } return dub_error(L); } /** void ofMesh::addNormals(const vector< ofVec3f > &norms) * api/openFrameworks/3d/ofMesh.h:34 */ static int ofMesh_addNormals(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); int top__ = lua_gettop(L); if (top__ >= 3) { ofVec3f *norms = *((ofVec3f **)dub_checksdata(L, 2, "ofVec3f")); int amt = dub_checkint(L, 3); self->addNormals(norms, amt); return 0; } else { vector< ofVec3f > *norms = *((vector< ofVec3f > **)dub_checksdata(L, 2, "vector< ofVec3f >")); self->addNormals(*norms); return 0; } } catch (std::exception &e) { lua_pushfstring(L, "addNormals: %s", e.what()); } catch (...) { lua_pushfstring(L, "addNormals: Unknown exception"); } return dub_error(L); } /** void ofMesh::removeNormal(ofIndexType index) * api/openFrameworks/3d/ofMesh.h:36 */ static int ofMesh_removeNormal(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *index = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); self->removeNormal(*index); return 0; } catch (std::exception &e) { lua_pushfstring(L, "removeNormal: %s", e.what()); } catch (...) { lua_pushfstring(L, "removeNormal: Unknown exception"); } return dub_error(L); } /** void ofMesh::setNormal(ofIndexType index, const ofVec3f &n) * api/openFrameworks/3d/ofMesh.h:37 */ static int ofMesh_setNormal(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *index = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); ofVec3f *n = *((ofVec3f **)dub_checksdata(L, 3, "ofVec3f")); self->setNormal(*index, *n); return 0; } catch (std::exception &e) { lua_pushfstring(L, "setNormal: %s", e.what()); } catch (...) { lua_pushfstring(L, "setNormal: Unknown exception"); } return dub_error(L); } /** void ofMesh::clearNormals() * api/openFrameworks/3d/ofMesh.h:38 */ static int ofMesh_clearNormals(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->clearNormals(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "clearNormals: %s", e.what()); } catch (...) { lua_pushfstring(L, "clearNormals: Unknown exception"); } return dub_error(L); } /** ofFloatColor ofMesh::getColor(ofIndexType i) const * api/openFrameworks/3d/ofMesh.h:40 */ static int ofMesh_getColor(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *i = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); dub_pushudata(L, new ofFloatColor(self->getColor(*i)), "ofFloatColor", true); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getColor: %s", e.what()); } catch (...) { lua_pushfstring(L, "getColor: Unknown exception"); } return dub_error(L); } /** void ofMesh::addColor(const ofFloatColor &c) * api/openFrameworks/3d/ofMesh.h:41 */ static int ofMesh_addColor(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofFloatColor *c = *((ofFloatColor **)dub_checksdata(L, 2, "ofFloatColor")); self->addColor(*c); return 0; } catch (std::exception &e) { lua_pushfstring(L, "addColor: %s", e.what()); } catch (...) { lua_pushfstring(L, "addColor: Unknown exception"); } return dub_error(L); } /** void ofMesh::addColors(const vector< ofFloatColor > &cols) * api/openFrameworks/3d/ofMesh.h:42 */ static int ofMesh_addColors(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); int top__ = lua_gettop(L); if (top__ >= 3) { ofFloatColor *cols = *((ofFloatColor **)dub_checksdata(L, 2, "ofFloatColor")); int amt = dub_checkint(L, 3); self->addColors(cols, amt); return 0; } else { vector< ofFloatColor > *cols = *((vector< ofFloatColor > **)dub_checksdata(L, 2, "vector< ofFloatColor >")); self->addColors(*cols); return 0; } } catch (std::exception &e) { lua_pushfstring(L, "addColors: %s", e.what()); } catch (...) { lua_pushfstring(L, "addColors: Unknown exception"); } return dub_error(L); } /** void ofMesh::removeColor(ofIndexType index) * api/openFrameworks/3d/ofMesh.h:44 */ static int ofMesh_removeColor(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *index = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); self->removeColor(*index); return 0; } catch (std::exception &e) { lua_pushfstring(L, "removeColor: %s", e.what()); } catch (...) { lua_pushfstring(L, "removeColor: Unknown exception"); } return dub_error(L); } /** void ofMesh::setColor(ofIndexType index, const ofFloatColor &c) * api/openFrameworks/3d/ofMesh.h:45 */ static int ofMesh_setColor(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *index = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); ofFloatColor *c = *((ofFloatColor **)dub_checksdata(L, 3, "ofFloatColor")); self->setColor(*index, *c); return 0; } catch (std::exception &e) { lua_pushfstring(L, "setColor: %s", e.what()); } catch (...) { lua_pushfstring(L, "setColor: Unknown exception"); } return dub_error(L); } /** void ofMesh::clearColors() * api/openFrameworks/3d/ofMesh.h:46 */ static int ofMesh_clearColors(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->clearColors(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "clearColors: %s", e.what()); } catch (...) { lua_pushfstring(L, "clearColors: Unknown exception"); } return dub_error(L); } /** ofVec2f ofMesh::getTexCoord(ofIndexType i) const * api/openFrameworks/3d/ofMesh.h:48 */ static int ofMesh_getTexCoord(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *i = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); dub_pushudata(L, new ofVec2f(self->getTexCoord(*i)), "ofVec2f", true); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getTexCoord: %s", e.what()); } catch (...) { lua_pushfstring(L, "getTexCoord: Unknown exception"); } return dub_error(L); } /** void ofMesh::addTexCoord(const ofVec2f &t) * api/openFrameworks/3d/ofMesh.h:49 */ static int ofMesh_addTexCoord(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofVec2f *t = *((ofVec2f **)dub_checksdata(L, 2, "ofVec2f")); self->addTexCoord(*t); return 0; } catch (std::exception &e) { lua_pushfstring(L, "addTexCoord: %s", e.what()); } catch (...) { lua_pushfstring(L, "addTexCoord: Unknown exception"); } return dub_error(L); } /** void ofMesh::addTexCoords(const vector< ofVec2f > &tCoords) * api/openFrameworks/3d/ofMesh.h:50 */ static int ofMesh_addTexCoords(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); int top__ = lua_gettop(L); if (top__ >= 3) { ofVec2f *tCoords = *((ofVec2f **)dub_checksdata(L, 2, "ofVec2f")); int amt = dub_checkint(L, 3); self->addTexCoords(tCoords, amt); return 0; } else { vector< ofVec2f > *tCoords = *((vector< ofVec2f > **)dub_checksdata(L, 2, "vector< ofVec2f >")); self->addTexCoords(*tCoords); return 0; } } catch (std::exception &e) { lua_pushfstring(L, "addTexCoords: %s", e.what()); } catch (...) { lua_pushfstring(L, "addTexCoords: Unknown exception"); } return dub_error(L); } /** void ofMesh::removeTexCoord(ofIndexType index) * api/openFrameworks/3d/ofMesh.h:52 */ static int ofMesh_removeTexCoord(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *index = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); self->removeTexCoord(*index); return 0; } catch (std::exception &e) { lua_pushfstring(L, "removeTexCoord: %s", e.what()); } catch (...) { lua_pushfstring(L, "removeTexCoord: Unknown exception"); } return dub_error(L); } /** void ofMesh::setTexCoord(ofIndexType index, const ofVec2f &t) * api/openFrameworks/3d/ofMesh.h:53 */ static int ofMesh_setTexCoord(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *index = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); ofVec2f *t = *((ofVec2f **)dub_checksdata(L, 3, "ofVec2f")); self->setTexCoord(*index, *t); return 0; } catch (std::exception &e) { lua_pushfstring(L, "setTexCoord: %s", e.what()); } catch (...) { lua_pushfstring(L, "setTexCoord: Unknown exception"); } return dub_error(L); } /** void ofMesh::clearTexCoords() * api/openFrameworks/3d/ofMesh.h:54 */ static int ofMesh_clearTexCoords(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->clearTexCoords(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "clearTexCoords: %s", e.what()); } catch (...) { lua_pushfstring(L, "clearTexCoords: Unknown exception"); } return dub_error(L); } /** ofIndexType ofMesh::getIndex(ofIndexType i) const * api/openFrameworks/3d/ofMesh.h:56 */ static int ofMesh_getIndex(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *i = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); dub_pushudata(L, new ofIndexType(self->getIndex(*i)), "ofIndexType", true); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getIndex: %s", e.what()); } catch (...) { lua_pushfstring(L, "getIndex: Unknown exception"); } return dub_error(L); } /** void ofMesh::addIndex(ofIndexType i) * api/openFrameworks/3d/ofMesh.h:57 */ static int ofMesh_addIndex(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *i = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); self->addIndex(*i); return 0; } catch (std::exception &e) { lua_pushfstring(L, "addIndex: %s", e.what()); } catch (...) { lua_pushfstring(L, "addIndex: Unknown exception"); } return dub_error(L); } /** void ofMesh::addIndices(const vector< ofIndexType > &inds) * api/openFrameworks/3d/ofMesh.h:58 */ static int ofMesh_addIndices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); int top__ = lua_gettop(L); if (top__ >= 3) { ofIndexType *inds = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); int amt = dub_checkint(L, 3); self->addIndices(inds, amt); return 0; } else { vector< ofIndexType > *inds = *((vector< ofIndexType > **)dub_checksdata(L, 2, "vector< ofIndexType >")); self->addIndices(*inds); return 0; } } catch (std::exception &e) { lua_pushfstring(L, "addIndices: %s", e.what()); } catch (...) { lua_pushfstring(L, "addIndices: Unknown exception"); } return dub_error(L); } /** void ofMesh::removeIndex(ofIndexType index) * api/openFrameworks/3d/ofMesh.h:60 */ static int ofMesh_removeIndex(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *index = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); self->removeIndex(*index); return 0; } catch (std::exception &e) { lua_pushfstring(L, "removeIndex: %s", e.what()); } catch (...) { lua_pushfstring(L, "removeIndex: Unknown exception"); } return dub_error(L); } /** void ofMesh::setIndex(ofIndexType index, ofIndexType val) * api/openFrameworks/3d/ofMesh.h:61 */ static int ofMesh_setIndex(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *index = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); ofIndexType *val = *((ofIndexType **)dub_checksdata(L, 3, "ofIndexType")); self->setIndex(*index, *val); return 0; } catch (std::exception &e) { lua_pushfstring(L, "setIndex: %s", e.what()); } catch (...) { lua_pushfstring(L, "setIndex: Unknown exception"); } return dub_error(L); } /** void ofMesh::clearIndices() * api/openFrameworks/3d/ofMesh.h:62 */ static int ofMesh_clearIndices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->clearIndices(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "clearIndices: %s", e.what()); } catch (...) { lua_pushfstring(L, "clearIndices: Unknown exception"); } return dub_error(L); } /** void ofMesh::addTriangle(ofIndexType index1, ofIndexType index2, ofIndexType index3) * api/openFrameworks/3d/ofMesh.h:64 */ static int ofMesh_addTriangle(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *index1 = *((ofIndexType **)dub_checksdata(L, 2, "ofIndexType")); ofIndexType *index2 = *((ofIndexType **)dub_checksdata(L, 3, "ofIndexType")); ofIndexType *index3 = *((ofIndexType **)dub_checksdata(L, 4, "ofIndexType")); self->addTriangle(*index1, *index2, *index3); return 0; } catch (std::exception &e) { lua_pushfstring(L, "addTriangle: %s", e.what()); } catch (...) { lua_pushfstring(L, "addTriangle: Unknown exception"); } return dub_error(L); } /** int ofMesh::getNumVertices() const * api/openFrameworks/3d/ofMesh.h:66 */ static int ofMesh_getNumVertices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushnumber(L, self->getNumVertices()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getNumVertices: %s", e.what()); } catch (...) { lua_pushfstring(L, "getNumVertices: Unknown exception"); } return dub_error(L); } /** int ofMesh::getNumColors() const * api/openFrameworks/3d/ofMesh.h:67 */ static int ofMesh_getNumColors(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushnumber(L, self->getNumColors()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getNumColors: %s", e.what()); } catch (...) { lua_pushfstring(L, "getNumColors: Unknown exception"); } return dub_error(L); } /** int ofMesh::getNumNormals() const * api/openFrameworks/3d/ofMesh.h:68 */ static int ofMesh_getNumNormals(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushnumber(L, self->getNumNormals()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getNumNormals: %s", e.what()); } catch (...) { lua_pushfstring(L, "getNumNormals: Unknown exception"); } return dub_error(L); } /** int ofMesh::getNumTexCoords() const * api/openFrameworks/3d/ofMesh.h:69 */ static int ofMesh_getNumTexCoords(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushnumber(L, self->getNumTexCoords()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getNumTexCoords: %s", e.what()); } catch (...) { lua_pushfstring(L, "getNumTexCoords: Unknown exception"); } return dub_error(L); } /** int ofMesh::getNumIndices() const * api/openFrameworks/3d/ofMesh.h:70 */ static int ofMesh_getNumIndices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushnumber(L, self->getNumIndices()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getNumIndices: %s", e.what()); } catch (...) { lua_pushfstring(L, "getNumIndices: Unknown exception"); } return dub_error(L); } /** ofVec3f* ofMesh::getVerticesPointer() * api/openFrameworks/3d/ofMesh.h:72 */ static int ofMesh_getVerticesPointer(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofVec3f *retval__ = self->getVerticesPointer(); if (!retval__) return 0; dub_pushudata(L, retval__, "ofVec3f", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getVerticesPointer: %s", e.what()); } catch (...) { lua_pushfstring(L, "getVerticesPointer: Unknown exception"); } return dub_error(L); } /** ofFloatColor* ofMesh::getColorsPointer() * api/openFrameworks/3d/ofMesh.h:73 */ static int ofMesh_getColorsPointer(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofFloatColor *retval__ = self->getColorsPointer(); if (!retval__) return 0; dub_pushudata(L, retval__, "ofFloatColor", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getColorsPointer: %s", e.what()); } catch (...) { lua_pushfstring(L, "getColorsPointer: Unknown exception"); } return dub_error(L); } /** ofVec3f* ofMesh::getNormalsPointer() * api/openFrameworks/3d/ofMesh.h:74 */ static int ofMesh_getNormalsPointer(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofVec3f *retval__ = self->getNormalsPointer(); if (!retval__) return 0; dub_pushudata(L, retval__, "ofVec3f", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getNormalsPointer: %s", e.what()); } catch (...) { lua_pushfstring(L, "getNormalsPointer: Unknown exception"); } return dub_error(L); } /** ofVec2f* ofMesh::getTexCoordsPointer() * api/openFrameworks/3d/ofMesh.h:75 */ static int ofMesh_getTexCoordsPointer(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofVec2f *retval__ = self->getTexCoordsPointer(); if (!retval__) return 0; dub_pushudata(L, retval__, "ofVec2f", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getTexCoordsPointer: %s", e.what()); } catch (...) { lua_pushfstring(L, "getTexCoordsPointer: Unknown exception"); } return dub_error(L); } /** ofIndexType* ofMesh::getIndexPointer() * api/openFrameworks/3d/ofMesh.h:76 */ static int ofMesh_getIndexPointer(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); ofIndexType *retval__ = self->getIndexPointer(); if (!retval__) return 0; dub_pushudata(L, retval__, "ofIndexType", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getIndexPointer: %s", e.what()); } catch (...) { lua_pushfstring(L, "getIndexPointer: Unknown exception"); } return dub_error(L); } /** vector<ofVec3f>& ofMesh::getVertices() * api/openFrameworks/3d/ofMesh.h:84 */ static int ofMesh_getVertices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); dub_pushudata(L, &self->getVertices(), "vector< ofVec3f >", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getVertices: %s", e.what()); } catch (...) { lua_pushfstring(L, "getVertices: Unknown exception"); } return dub_error(L); } /** vector<ofFloatColor>& ofMesh::getColors() * api/openFrameworks/3d/ofMesh.h:85 */ static int ofMesh_getColors(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); dub_pushudata(L, &self->getColors(), "vector< ofFloatColor >", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getColors: %s", e.what()); } catch (...) { lua_pushfstring(L, "getColors: Unknown exception"); } return dub_error(L); } /** vector<ofVec3f>& ofMesh::getNormals() * api/openFrameworks/3d/ofMesh.h:86 */ static int ofMesh_getNormals(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); dub_pushudata(L, &self->getNormals(), "vector< ofVec3f >", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getNormals: %s", e.what()); } catch (...) { lua_pushfstring(L, "getNormals: Unknown exception"); } return dub_error(L); } /** vector<ofVec2f>& ofMesh::getTexCoords() * api/openFrameworks/3d/ofMesh.h:87 */ static int ofMesh_getTexCoords(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); dub_pushudata(L, &self->getTexCoords(), "vector< ofVec2f >", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getTexCoords: %s", e.what()); } catch (...) { lua_pushfstring(L, "getTexCoords: Unknown exception"); } return dub_error(L); } /** vector<ofIndexType>& ofMesh::getIndices() * api/openFrameworks/3d/ofMesh.h:88 */ static int ofMesh_getIndices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); dub_pushudata(L, &self->getIndices(), "vector< ofIndexType >", false); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getIndices: %s", e.what()); } catch (...) { lua_pushfstring(L, "getIndices: Unknown exception"); } return dub_error(L); } /** ofVec3f ofMesh::getCentroid() const * api/openFrameworks/3d/ofMesh.h:98 */ static int ofMesh_getCentroid(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); dub_pushudata(L, new ofVec3f(self->getCentroid()), "ofVec3f", true); return 1; } catch (std::exception &e) { lua_pushfstring(L, "getCentroid: %s", e.what()); } catch (...) { lua_pushfstring(L, "getCentroid: Unknown exception"); } return dub_error(L); } /** void ofMesh::setName(string name_) * api/openFrameworks/3d/ofMesh.h:100 */ static int ofMesh_setName(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); size_t name__sz_; const char *name_ = dub_checklstring(L, 2, &name__sz_); self->setName(std::string(name_, name__sz_)); return 0; } catch (std::exception &e) { lua_pushfstring(L, "setName: %s", e.what()); } catch (...) { lua_pushfstring(L, "setName: Unknown exception"); } return dub_error(L); } /** bool ofMesh::haveVertsChanged() * api/openFrameworks/3d/ofMesh.h:102 */ static int ofMesh_haveVertsChanged(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->haveVertsChanged()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "haveVertsChanged: %s", e.what()); } catch (...) { lua_pushfstring(L, "haveVertsChanged: Unknown exception"); } return dub_error(L); } /** bool ofMesh::haveColorsChanged() * api/openFrameworks/3d/ofMesh.h:103 */ static int ofMesh_haveColorsChanged(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->haveColorsChanged()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "haveColorsChanged: %s", e.what()); } catch (...) { lua_pushfstring(L, "haveColorsChanged: Unknown exception"); } return dub_error(L); } /** bool ofMesh::haveNormalsChanged() * api/openFrameworks/3d/ofMesh.h:104 */ static int ofMesh_haveNormalsChanged(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->haveNormalsChanged()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "haveNormalsChanged: %s", e.what()); } catch (...) { lua_pushfstring(L, "haveNormalsChanged: Unknown exception"); } return dub_error(L); } /** bool ofMesh::haveTexCoordsChanged() * api/openFrameworks/3d/ofMesh.h:105 */ static int ofMesh_haveTexCoordsChanged(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->haveTexCoordsChanged()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "haveTexCoordsChanged: %s", e.what()); } catch (...) { lua_pushfstring(L, "haveTexCoordsChanged: Unknown exception"); } return dub_error(L); } /** bool ofMesh::haveIndicesChanged() * api/openFrameworks/3d/ofMesh.h:106 */ static int ofMesh_haveIndicesChanged(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->haveIndicesChanged()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "haveIndicesChanged: %s", e.what()); } catch (...) { lua_pushfstring(L, "haveIndicesChanged: Unknown exception"); } return dub_error(L); } /** bool ofMesh::hasVertices() * api/openFrameworks/3d/ofMesh.h:108 */ static int ofMesh_hasVertices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->hasVertices()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "hasVertices: %s", e.what()); } catch (...) { lua_pushfstring(L, "hasVertices: Unknown exception"); } return dub_error(L); } /** bool ofMesh::hasColors() * api/openFrameworks/3d/ofMesh.h:109 */ static int ofMesh_hasColors(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->hasColors()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "hasColors: %s", e.what()); } catch (...) { lua_pushfstring(L, "hasColors: Unknown exception"); } return dub_error(L); } /** bool ofMesh::hasNormals() * api/openFrameworks/3d/ofMesh.h:110 */ static int ofMesh_hasNormals(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->hasNormals()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "hasNormals: %s", e.what()); } catch (...) { lua_pushfstring(L, "hasNormals: Unknown exception"); } return dub_error(L); } /** bool ofMesh::hasTexCoords() * api/openFrameworks/3d/ofMesh.h:111 */ static int ofMesh_hasTexCoords(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->hasTexCoords()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "hasTexCoords: %s", e.what()); } catch (...) { lua_pushfstring(L, "hasTexCoords: Unknown exception"); } return dub_error(L); } /** bool ofMesh::hasIndices() * api/openFrameworks/3d/ofMesh.h:112 */ static int ofMesh_hasIndices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->hasIndices()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "hasIndices: %s", e.what()); } catch (...) { lua_pushfstring(L, "hasIndices: Unknown exception"); } return dub_error(L); } /** void ofMesh::drawVertices() * api/openFrameworks/3d/ofMesh.h:114 */ static int ofMesh_drawVertices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->drawVertices(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "drawVertices: %s", e.what()); } catch (...) { lua_pushfstring(L, "drawVertices: Unknown exception"); } return dub_error(L); } /** void ofMesh::drawWireframe() * api/openFrameworks/3d/ofMesh.h:115 */ static int ofMesh_drawWireframe(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->drawWireframe(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "drawWireframe: %s", e.what()); } catch (...) { lua_pushfstring(L, "drawWireframe: Unknown exception"); } return dub_error(L); } /** void ofMesh::drawFaces() * api/openFrameworks/3d/ofMesh.h:116 */ static int ofMesh_drawFaces(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->drawFaces(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "drawFaces: %s", e.what()); } catch (...) { lua_pushfstring(L, "drawFaces: Unknown exception"); } return dub_error(L); } /** void ofMesh::draw() * api/openFrameworks/3d/ofMesh.h:117 */ static int ofMesh_draw(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->draw(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "draw: %s", e.what()); } catch (...) { lua_pushfstring(L, "draw: Unknown exception"); } return dub_error(L); } /** void ofMesh::load(string path) * api/openFrameworks/3d/ofMesh.h:119 */ static int ofMesh_load(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); size_t path_sz_; const char *path = dub_checklstring(L, 2, &path_sz_); self->load(std::string(path, path_sz_)); return 0; } catch (std::exception &e) { lua_pushfstring(L, "load: %s", e.what()); } catch (...) { lua_pushfstring(L, "load: Unknown exception"); } return dub_error(L); } /** void ofMesh::save(string path, bool useBinary=false) * api/openFrameworks/3d/ofMesh.h:120 */ static int ofMesh_save(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); int top__ = lua_gettop(L); if (top__ >= 3) { size_t path_sz_; const char *path = dub_checklstring(L, 2, &path_sz_); bool useBinary = dub_checkboolean(L, 3); self->save(std::string(path, path_sz_), useBinary); return 0; } else { size_t path_sz_; const char *path = dub_checklstring(L, 2, &path_sz_); self->save(std::string(path, path_sz_)); return 0; } } catch (std::exception &e) { lua_pushfstring(L, "save: %s", e.what()); } catch (...) { lua_pushfstring(L, "save: Unknown exception"); } return dub_error(L); } /** virtual void ofMesh::enableColors() * api/openFrameworks/3d/ofMesh.h:122 */ static int ofMesh_enableColors(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->enableColors(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "enableColors: %s", e.what()); } catch (...) { lua_pushfstring(L, "enableColors: Unknown exception"); } return dub_error(L); } /** virtual void ofMesh::enableTextures() * api/openFrameworks/3d/ofMesh.h:123 */ static int ofMesh_enableTextures(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->enableTextures(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "enableTextures: %s", e.what()); } catch (...) { lua_pushfstring(L, "enableTextures: Unknown exception"); } return dub_error(L); } /** virtual void ofMesh::enableNormals() * api/openFrameworks/3d/ofMesh.h:124 */ static int ofMesh_enableNormals(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->enableNormals(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "enableNormals: %s", e.what()); } catch (...) { lua_pushfstring(L, "enableNormals: Unknown exception"); } return dub_error(L); } /** virtual void ofMesh::enableIndices() * api/openFrameworks/3d/ofMesh.h:125 */ static int ofMesh_enableIndices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->enableIndices(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "enableIndices: %s", e.what()); } catch (...) { lua_pushfstring(L, "enableIndices: Unknown exception"); } return dub_error(L); } /** virtual void ofMesh::disableColors() * api/openFrameworks/3d/ofMesh.h:127 */ static int ofMesh_disableColors(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->disableColors(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "disableColors: %s", e.what()); } catch (...) { lua_pushfstring(L, "disableColors: Unknown exception"); } return dub_error(L); } /** virtual void ofMesh::disableTextures() * api/openFrameworks/3d/ofMesh.h:128 */ static int ofMesh_disableTextures(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->disableTextures(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "disableTextures: %s", e.what()); } catch (...) { lua_pushfstring(L, "disableTextures: Unknown exception"); } return dub_error(L); } /** virtual void ofMesh::disableNormals() * api/openFrameworks/3d/ofMesh.h:129 */ static int ofMesh_disableNormals(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->disableNormals(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "disableNormals: %s", e.what()); } catch (...) { lua_pushfstring(L, "disableNormals: Unknown exception"); } return dub_error(L); } /** virtual void ofMesh::disableIndices() * api/openFrameworks/3d/ofMesh.h:130 */ static int ofMesh_disableIndices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); self->disableIndices(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "disableIndices: %s", e.what()); } catch (...) { lua_pushfstring(L, "disableIndices: Unknown exception"); } return dub_error(L); } /** virtual bool ofMesh::usingColors() * api/openFrameworks/3d/ofMesh.h:132 */ static int ofMesh_usingColors(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->usingColors()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "usingColors: %s", e.what()); } catch (...) { lua_pushfstring(L, "usingColors: Unknown exception"); } return dub_error(L); } /** virtual bool ofMesh::usingTextures() * api/openFrameworks/3d/ofMesh.h:133 */ static int ofMesh_usingTextures(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->usingTextures()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "usingTextures: %s", e.what()); } catch (...) { lua_pushfstring(L, "usingTextures: Unknown exception"); } return dub_error(L); } /** virtual bool ofMesh::usingNormals() * api/openFrameworks/3d/ofMesh.h:134 */ static int ofMesh_usingNormals(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->usingNormals()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "usingNormals: %s", e.what()); } catch (...) { lua_pushfstring(L, "usingNormals: Unknown exception"); } return dub_error(L); } /** virtual bool ofMesh::usingIndices() * api/openFrameworks/3d/ofMesh.h:135 */ static int ofMesh_usingIndices(lua_State *L) { try { ofMesh *self = *((ofMesh **)dub_checksdata(L, 1, "ofMesh")); lua_pushboolean(L, self->usingIndices()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "usingIndices: %s", e.what()); } catch (...) { lua_pushfstring(L, "usingIndices: Unknown exception"); } return dub_error(L); } // --=============================================== __tostring static int ofMesh___tostring(lua_State *L) { ofMesh *self = *((ofMesh **)dub_checksdata_n(L, 1, "ofMesh")); lua_pushfstring(L, "ofMesh: %p", self); return 1; } // --=============================================== METHODS static const struct luaL_Reg ofMesh_member_methods[] = { { "new" , ofMesh_ofMesh }, { "__gc" , ofMesh__ofMesh }, { "setMode" , ofMesh_setMode }, { "getMode" , ofMesh_getMode }, { "clear" , ofMesh_clear }, { "setupIndicesAuto", ofMesh_setupIndicesAuto }, { "getVertex" , ofMesh_getVertex }, { "addVertex" , ofMesh_addVertex }, { "addVertices" , ofMesh_addVertices }, { "removeVertex" , ofMesh_removeVertex }, { "setVertex" , ofMesh_setVertex }, { "clearVertices", ofMesh_clearVertices }, { "getNormal" , ofMesh_getNormal }, { "addNormal" , ofMesh_addNormal }, { "addNormals" , ofMesh_addNormals }, { "removeNormal" , ofMesh_removeNormal }, { "setNormal" , ofMesh_setNormal }, { "clearNormals" , ofMesh_clearNormals }, { "getColor" , ofMesh_getColor }, { "addColor" , ofMesh_addColor }, { "addColors" , ofMesh_addColors }, { "removeColor" , ofMesh_removeColor }, { "setColor" , ofMesh_setColor }, { "clearColors" , ofMesh_clearColors }, { "getTexCoord" , ofMesh_getTexCoord }, { "addTexCoord" , ofMesh_addTexCoord }, { "addTexCoords" , ofMesh_addTexCoords }, { "removeTexCoord", ofMesh_removeTexCoord }, { "setTexCoord" , ofMesh_setTexCoord }, { "clearTexCoords", ofMesh_clearTexCoords }, { "getIndex" , ofMesh_getIndex }, { "addIndex" , ofMesh_addIndex }, { "addIndices" , ofMesh_addIndices }, { "removeIndex" , ofMesh_removeIndex }, { "setIndex" , ofMesh_setIndex }, { "clearIndices" , ofMesh_clearIndices }, { "addTriangle" , ofMesh_addTriangle }, { "getNumVertices", ofMesh_getNumVertices }, { "getNumColors" , ofMesh_getNumColors }, { "getNumNormals", ofMesh_getNumNormals }, { "getNumTexCoords", ofMesh_getNumTexCoords }, { "getNumIndices", ofMesh_getNumIndices }, { "getVerticesPointer", ofMesh_getVerticesPointer }, { "getColorsPointer", ofMesh_getColorsPointer }, { "getNormalsPointer", ofMesh_getNormalsPointer }, { "getTexCoordsPointer", ofMesh_getTexCoordsPointer }, { "getIndexPointer", ofMesh_getIndexPointer }, { "getVertices" , ofMesh_getVertices }, { "getColors" , ofMesh_getColors }, { "getNormals" , ofMesh_getNormals }, { "getTexCoords" , ofMesh_getTexCoords }, { "getIndices" , ofMesh_getIndices }, { "getCentroid" , ofMesh_getCentroid }, { "setName" , ofMesh_setName }, { "haveVertsChanged", ofMesh_haveVertsChanged }, { "haveColorsChanged", ofMesh_haveColorsChanged }, { "haveNormalsChanged", ofMesh_haveNormalsChanged }, { "haveTexCoordsChanged", ofMesh_haveTexCoordsChanged }, { "haveIndicesChanged", ofMesh_haveIndicesChanged }, { "hasVertices" , ofMesh_hasVertices }, { "hasColors" , ofMesh_hasColors }, { "hasNormals" , ofMesh_hasNormals }, { "hasTexCoords" , ofMesh_hasTexCoords }, { "hasIndices" , ofMesh_hasIndices }, { "drawVertices" , ofMesh_drawVertices }, { "drawWireframe", ofMesh_drawWireframe }, { "drawFaces" , ofMesh_drawFaces }, { "draw" , ofMesh_draw }, { "load" , ofMesh_load }, { "save" , ofMesh_save }, { "enableColors" , ofMesh_enableColors }, { "enableTextures", ofMesh_enableTextures }, { "enableNormals", ofMesh_enableNormals }, { "enableIndices", ofMesh_enableIndices }, { "disableColors", ofMesh_disableColors }, { "disableTextures", ofMesh_disableTextures }, { "disableNormals", ofMesh_disableNormals }, { "disableIndices", ofMesh_disableIndices }, { "usingColors" , ofMesh_usingColors }, { "usingTextures", ofMesh_usingTextures }, { "usingNormals" , ofMesh_usingNormals }, { "usingIndices" , ofMesh_usingIndices }, { "__tostring" , ofMesh___tostring }, { "deleted" , dub_isDeleted }, { NULL, NULL}, }; extern "C" int luaopen_ofMesh(lua_State *L) { // Create the metatable which will contain all the member methods luaL_newmetatable(L, "ofMesh"); // <mt> // register member methods luaL_register(L, NULL, ofMesh_member_methods); // save meta-table in _G dub_register(L, "_G", "ofMesh", "ofMesh"); // <mt> lua_pop(L, 1); return 0; }
[ "leonard.chioveanu@gmail.com" ]
leonard.chioveanu@gmail.com
b40e5a5f11f2081a7afc4021d4e108909fa08b2a
9f7fbef81d1e4e7577192f8021dc5d0a74a558ce
/gr8/targets/function_enter.cpp
973fe4c395baea26ba9c9bca39909c243e995afb
[]
no_license
ist424865/co-2017-18
0bda7c3c66aae9051e7ef63605658eeb9991d5e5
388a040c9a815dc90af6790cd01285a7897c5112
refs/heads/master
2021-09-15T03:15:06.078394
2018-05-24T23:34:20
2018-05-24T23:34:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,293
cpp
#include "targets/function_enter.h" #include "ast/all.h" // all.h is automatically generated void gr8::function_enter::do_integer_node(cdk::integer_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_double_node(cdk::double_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_string_node(cdk::string_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_nil_node(cdk::nil_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_data_node(cdk::data_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_null_node(gr8::null_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_tweet_node(gr8::tweet_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_evaluation_node(gr8::evaluation_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_if_else_node(gr8::if_else_node *const node, int lvl) { node->thenblock()->accept(this, lvl); node->elseblock()->accept(this, lvl); } void gr8::function_enter::do_again_node(gr8::again_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_sweeping_node(gr8::sweeping_node *const node, int lvl) { node->block()->accept(this, lvl); } void gr8::function_enter::do_return_node(gr8::return_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_alloc_node(gr8::alloc_node *const node, int lvl) { if (node->type()->name() == basic_type::TYPE_INT || node->type()->name() == basic_type::TYPE_POINTER || node->type()->name() == basic_type::TYPE_STRING) _counter += 4 * dynamic_cast<cdk::integer_node*>(node->argument())->value(); else if (node->type()->name() == basic_type::TYPE_DOUBLE) _counter += 8 * dynamic_cast<cdk::integer_node*>(node->argument())->value(); } void gr8::function_enter::do_function_invocation_node(gr8::function_invocation_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_identity_node(gr8::identity_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_address_of_node(gr8::address_of_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_sequence_node(cdk::sequence_node * const node, int lvl) { for (size_t i = 0; i < node->size(); i++) { node->node(i)->accept(this, lvl); } } void gr8::function_enter::do_block_node(gr8::block_node *const node, int lvl) { if (node->declarations() != nullptr) node->declarations()->accept(this, lvl); if (node->instructions() != nullptr) node->instructions()->accept(this, lvl); } void gr8::function_enter::do_post_node(gr8::post_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_variable_declaration_node(gr8::variable_declaration_node *const node, int lvl) { if (node->type()->name() == basic_type::TYPE_INT || node->type()->name() == basic_type::TYPE_POINTER || node->type()->name() == basic_type::TYPE_STRING) _counter += 4; else if (node->type()->name() == basic_type::TYPE_DOUBLE) _counter += 8; } void gr8::function_enter::do_function_definition_node(gr8::function_definition_node *const node, int lvl) { node->body()->accept(this, lvl); } void gr8::function_enter::do_index_node(gr8::index_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_function_declaration_node(gr8::function_declaration_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_stop_node(gr8::stop_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_read_node(gr8::read_node *const node, int lvl) { // EMPTY } void gr8::function_enter::do_neg_node(cdk::neg_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_not_node(cdk::not_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_and_node(cdk::and_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_or_node(cdk::or_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_add_node(cdk::add_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_sub_node(cdk::sub_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_mul_node(cdk::mul_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_div_node(cdk::div_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_mod_node(cdk::mod_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_lt_node(cdk::lt_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_le_node(cdk::le_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_ge_node(cdk::ge_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_gt_node(cdk::gt_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_ne_node(cdk::ne_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_eq_node(cdk::eq_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_identifier_node(cdk::identifier_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_rvalue_node(cdk::rvalue_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_assignment_node(cdk::assignment_node * const node, int lvl) { // EMPTY } void gr8::function_enter::do_if_node(gr8::if_node * const node, int lvl) { node->block()->accept(this, lvl); }
[ "rui.m.ribeiro@tecnico.ulisboa.pt" ]
rui.m.ribeiro@tecnico.ulisboa.pt
f48941e2f927a0f2dc873d0176f07763043a20ab
8759f4361a1253980dfb0c5a3901e3f73b2f19c4
/src/vcl/hid/spacenavigatorhandler.h
6d1cedd75fc826ac55e798e6cdfd7367015ec9f8
[ "MIT" ]
permissive
bfierz/vcl.hid
53b3f37e2b671fbcb4da448d1ad08670250f5aa1
4193fe488d6759306e297b225e3a3c4da58716b0
refs/heads/master
2021-09-10T06:46:56.669621
2018-03-21T20:00:36
2018-03-21T20:00:36
102,975,343
1
0
null
null
null
null
UTF-8
C++
false
false
2,935
h
/* * This file is part of the Visual Computing Library (VCL) release under the * license. * * Copyright (c) 2017 Basil Fierz * * 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 once // VCL configuration #include <vcl/config/global.h> // C++ standard library #include <array> // VCL #include <vcl/hid/spacenavigatorvirtualkeys.h> namespace Vcl { namespace HID { //! Forward declaration class SpaceNavigator; //! Callback interface class SpaceNavigatorHandler { public: /*! * \brief onSpaceMouseMove is invoked when new 3d mouse data is * available. * * \param device Pointer to the device that triggered the callback * \param motion_data Contains the displacement data, using a * right-handed coordinate system with z down. * See 'Programing for the 3dmouse' document * available at www.3dconnexion.com. * Entries 0, 1, 2 is the incremental pan zoom * displacement vector (x,y,z). * Entries 3, 4, 5 is the incremental rotation vector * (NOT Euler angles). */ virtual void onSpaceMouseMove(const SpaceNavigator* device, std::array<float, 6> motion_data) = 0; /*! * \brief onSpaceMouseKeyDown processes the 3d mouse key presses * * \param device Pointer to the device that triggered the callback * \param virtual_key 3d mouse key code */ virtual void onSpaceMouseKeyDown(const SpaceNavigator* device, unsigned int virtual_key) = 0; /*! * \brief onSpaceMouseKeyUp processes the 3d mouse key releases * * \param device Pointer to the device that triggered the callback * \param virtual_key 3d mouse key code */ virtual void onSpaceMouseKeyUp(const SpaceNavigator* device, unsigned int virtual_key) = 0; }; }}
[ "basil.fierz@hotmail.com" ]
basil.fierz@hotmail.com
1ca331be3e4d166c674372e1978471b08a77ffd0
99c5155ad8c762459bb2d46c48aa261ddc06baa1
/ChuckNorris.h
0741be036aad52acefa6d3b974e85a3bcbe2696c
[]
no_license
CS1103/practica-calificada-2-JosephPenaQuino
13e11e477a85aab6d2bc27baa488eb1a071423cf
533c36b3934b4915bfed54562838fd5666c9b665
refs/heads/master
2022-01-15T15:54:35.686641
2019-05-10T18:29:34
2019-05-10T18:29:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
187
h
#ifndef PC2_CHUCKNORRIS_H #define PC2_CHUCKNORRIS_H #include "Fighter.h" class ChuckNorris : public Fighter { public: explicit ChuckNorris(int id); }; #endif //PC2_CHUCKNORRIS_H
[ "joseph.pena@utec.edu.pe" ]
joseph.pena@utec.edu.pe
97a0c9ee0551abd5fcf21d3c151ffa3936efc777
fe754becf524e7489016b949b22f48db7805febf
/Algorithm/DP/LIS.cpp
134b4c011f1c00b4c1c506403ec447e2f0660b9a
[]
no_license
Jayliu227/codings
ef64a295da4894e22073c6ab626aeb59a75cbaf8
73c223b8f877c6e031d880bd57f5f1f4228d40a0
refs/heads/master
2021-10-09T08:55:40.345838
2018-12-25T02:30:37
2018-12-25T02:30:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
711
cpp
#include<bits/stdc++.h> using namespace std; int main(){ int N; cin >> N; int a[N]; int dp[N][2]; memset(dp, 0, sizeof(dp)); for(int i = 0; i < N; i++){ scanf("%d", &a[i]); } dp[0][0] = 1; dp[0][1] = -1; for(int i = 1; i < N; i++){ dp[i][0] = 1; dp[i][1] = -1; int m = 1; for(int j = i - 1; j >= 0; j--){ if(a[j] <= a[i]){ if(dp[j][0] + 1 > m){ m = dp[j][0] + 1; dp[i][0] = m; dp[i][1] = j; } } } } int mi = 0; int mv = dp[0][0]; for(int i = 1; i < N; i++){ if(dp[i][0] > mv){ mv = dp[i][0]; mi = i; } } cout << dp[mi][0] << endl; while(dp[mi][1] != -1){ cout << a[mi] << " "; mi = dp[mi][1]; } cout << a[mi]; return 0; }
[ "jl7895@nyu.edu" ]
jl7895@nyu.edu
f3f290731e82f8f5bc5c49f5d967ebfd6191525d
21618cdadcde69e4d4084431e43638ebd19f8b76
/slave.h
4af0db48d39be26dd2eec1f93017a97d7aad2732
[ "BSD-2-Clause" ]
permissive
aykevl/domo-avr
3b5ab4fe6dd6c2f57ccfe2481d71311788a736e5
30aa607b498b60ca6ae4e5d5112a98ddf1afa48f
refs/heads/master
2020-09-21T00:56:05.559204
2016-08-30T15:18:54
2016-08-30T15:18:54
66,936,265
0
0
null
null
null
null
UTF-8
C++
false
false
209
h
#ifndef SLAVE_H #define SLAVE_H // Communicate with the Raspberry Pi. class Slave { public: inline Slave() __attribute__((always_inline)); inline void loop() __attribute__((always_inline)); }; #endif
[ "aykevanlaethem@gmail.com" ]
aykevanlaethem@gmail.com
6119e15f85ff5fae8d26e191c3e9dc0fa66f9d33
f9dd7fb236f557f46dc7b627f3b271b072b70b18
/code/cgame/cg_draw.cpp
70919cb1167736e147d404ac93126b4ad7e30123
[]
no_license
emileb/JK3
b74a782de237326dabbf454e8174bb442fa7393f
dee58b46ee31690fae82fd5671d2c0b5b806840d
refs/heads/master
2021-01-19T05:25:21.632760
2014-02-27T17:48:52
2014-02-27T17:48:52
17,257,706
2
0
null
null
null
null
UTF-8
C++
false
false
95,784
cpp
// cg_draw.c -- draw all of the graphical elements during // active (after loading) gameplay // this line must stay at top so the whole PCH thing works... #include "cg_headers.h" //#include "cg_local.h" #include "cg_media.h" #include "../game/objectives.h" #include "../game/g_vehicles.h" #include "../game/g_local.h" #ifdef _XBOX #include "../client/fffx.h" #endif extern vmCvar_t cg_debugHealthBars; extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); void CG_DrawIconBackground(void); void CG_DrawMissionInformation( void ); void CG_DrawInventorySelect( void ); void CG_DrawForceSelect( void ); qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y); qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y); extern float g_crosshairEntDist; extern int g_crosshairSameEntTime; extern int g_crosshairEntNum; extern int g_crosshairEntTime; qboolean cg_forceCrosshair = qfalse; // bad cheating extern int g_rocketLockEntNum; extern int g_rocketLockTime; extern int g_rocketSlackTime; vec3_t vfwd; vec3_t vright; vec3_t vup; vec3_t vfwd_n; vec3_t vright_n; vec3_t vup_n; int infoStringCount; int cgRageTime = 0; int cgRageFadeTime = 0; float cgRageFadeVal = 0; int cgRageRecTime = 0; int cgRageRecFadeTime = 0; float cgRageRecFadeVal = 0; int cgAbsorbTime = 0; int cgAbsorbFadeTime = 0; float cgAbsorbFadeVal = 0; int cgProtectTime = 0; int cgProtectFadeTime = 0; float cgProtectFadeVal = 0; //=============================================================== /* ================ CG_DrawMessageLit ================ */ static void CG_DrawMessageLit(centity_t *cent,int x,int y) { cgi_R_SetColor(colorTable[CT_WHITE]); if (cg.missionInfoFlashTime > cg.time ) { if (!((cg.time / 600 ) & 1)) { if (!cg.messageLitActive) { /* kef 4/16/03 -- as fun as this was, its time has passed. I will, however, hijack this cvar at James' recommendation and use it for another nefarious purpose if (cg_neverHearThatDumbBeepingSoundAgain.integer == 0) { cgi_S_StartSound( NULL, 0, CHAN_AUTO, cgs.media.messageLitSound ); } */ cg.messageLitActive = qtrue; } cgi_R_SetColor(colorTable[CT_HUD_RED]); CG_DrawPic( x + 33,y + 41, 16,16, cgs.media.messageLitOn); } else { cg.messageLitActive = qfalse; } } cgi_R_SetColor(colorTable[CT_WHITE]); CG_DrawPic( x + 33,y + 41, 16,16, cgs.media.messageLitOff); } /* ================ CG_DrawForcePower Draw the force power graphics (tics) and the force power numeric amount. Any tics that are partial will be alphaed out. ================ */ static void CG_DrawForcePower(const centity_t *cent,const int xPos,const int yPos) { int i; qboolean flash=qfalse; vec4_t calcColor; float value,extra=0,inc,percent; if ( !cent->gent->client->ps.forcePowersKnown ) { return; } // Make the hud flash by setting forceHUDTotalFlashTime above cg.time if (cg.forceHUDTotalFlashTime > cg.time ) { flash = qtrue; if (cg.forceHUDNextFlashTime < cg.time) { cg.forceHUDNextFlashTime = cg.time + 400; cgi_S_StartSound( NULL, 0, CHAN_AUTO, cgs.media.noforceSound ); if (cg.forceHUDActive) { cg.forceHUDActive = qfalse; } else { cg.forceHUDActive = qtrue; } } } else // turn HUD back on if it had just finished flashing time. { cg.forceHUDNextFlashTime = 0; cg.forceHUDActive = qtrue; } // I left the funtionality for flashing in because I might be needed yet. // if (!cg.forceHUDActive) // { // return; // } inc = (float) cent->gent->client->ps.forcePowerMax / MAX_HUD_TICS; value = cent->gent->client->ps.forcePower; if ( value > cent->gent->client->ps.forcePowerMax ) {//supercharged with force extra = value - cent->gent->client->ps.forcePowerMax; value = cent->gent->client->ps.forcePowerMax; } for (i=MAX_HUD_TICS-1;i>=0;i--) { if ( extra ) {//supercharged memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); percent = 0.75f + (sinf( cg.time * 0.005f )*((extra/cent->gent->client->ps.forcePowerMax)*0.25f)); calcColor[0] *= percent; calcColor[1] *= percent; calcColor[2] *= percent; } else if ( value <= 0 ) // no more { break; } else if (value < inc) // partial tic { if (flash) { memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); } else { memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); } percent = value / inc; calcColor[3] = percent; } else { if (flash) { memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); } else { memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); } } cgi_R_SetColor( calcColor); CG_DrawPic( forceTics[i].xPos, forceTics[i].yPos, forceTics[i].width, forceTics[i].height, forceTics[i].background ); value -= inc; } if (flash) { cgi_R_SetColor( colorTable[CT_RED] ); } else { cgi_R_SetColor( otherHUDBits[OHB_FORCEAMOUNT].color ); } // Print force numeric amount CG_DrawNumField ( otherHUDBits[OHB_FORCEAMOUNT].xPos, otherHUDBits[OHB_FORCEAMOUNT].yPos, 3, cent->gent->client->ps.forcePower, otherHUDBits[OHB_FORCEAMOUNT].width, otherHUDBits[OHB_FORCEAMOUNT].height, NUM_FONT_SMALL, qfalse); } /* ================ CG_DrawSaberStyle If the weapon is a light saber (which needs no ammo) then draw a graphic showing the saber style (fast, medium, strong) ================ */ static void CG_DrawSaberStyle(const centity_t *cent,const int xPos,const int yPos) { int index; if (!cent->currentState.weapon ) // We don't have a weapon right now { return; } if ( cent->currentState.weapon != WP_SABER || !cent->gent ) { return; } cgi_R_SetColor( colorTable[CT_WHITE] ); if ( !cg.saberAnimLevelPending && cent->gent->client ) {//uninitialized after a loadgame, cheat across and get it cg.saberAnimLevelPending = cent->gent->client->ps.saberAnimLevel; } // don't need to draw ammo, but we will draw the current saber style in this window if (cg.saberAnimLevelPending == SS_FAST || cg.saberAnimLevelPending == SS_TAVION ) { index = OHB_SABERSTYLE_FAST; } else if (cg.saberAnimLevelPending == SS_MEDIUM || cg.saberAnimLevelPending == SS_DUAL || cg.saberAnimLevelPending == SS_STAFF ) { index = OHB_SABERSTYLE_MEDIUM; } else { index = OHB_SABERSTYLE_STRONG; } cgi_R_SetColor( otherHUDBits[index].color); CG_DrawPic( otherHUDBits[index].xPos, otherHUDBits[index].yPos, otherHUDBits[index].width, otherHUDBits[index].height, otherHUDBits[index].background ); } /* ================ CG_DrawAmmo Draw the ammo graphics (tics) and the ammo numeric amount. Any tics that are partial will be alphaed out. ================ */ static void CG_DrawAmmo(const centity_t *cent,const int xPos,const int yPos) { playerState_t *ps; int i; vec4_t calcColor; float currValue=0,inc; if (!cent->currentState.weapon ) // We don't have a weapon right now { return; } if ( cent->currentState.weapon == WP_STUN_BATON ) { return; } ps = &cg.snap->ps; currValue = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; if (currValue < 0) // No ammo { return; } // // ammo // if (cg.oldammo < currValue) { cg.oldAmmoTime = cg.time + 200; } cg.oldammo = currValue; // Determine the color of the numeric field // Firing or reloading? if (( cg.predicted_player_state.weaponstate == WEAPON_FIRING && cg.predicted_player_state.weaponTime > 100 )) { memcpy(calcColor, colorTable[CT_LTGREY], sizeof(vec4_t)); } else { if ( currValue > 0 ) { if (cg.oldAmmoTime > cg.time) { memcpy(calcColor, colorTable[CT_YELLOW], sizeof(vec4_t)); } else { memcpy(calcColor, otherHUDBits[OHB_AMMOAMOUNT].color, sizeof(vec4_t)); } } else { memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); } } // Print number amount cgi_R_SetColor( calcColor ); CG_DrawNumField ( otherHUDBits[OHB_AMMOAMOUNT].xPos, otherHUDBits[OHB_AMMOAMOUNT].yPos, 3, ps->ammo[weaponData[cent->currentState.weapon].ammoIndex], otherHUDBits[OHB_AMMOAMOUNT].width, otherHUDBits[OHB_AMMOAMOUNT].height, NUM_FONT_SMALL, qfalse); inc = (float) ammoData[weaponData[cent->currentState.weapon].ammoIndex].max / MAX_HUD_TICS; currValue =ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); for (i=MAX_HUD_TICS-1;i>=0;i--) { if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { memcpy(calcColor, ammoTics[i].color, sizeof(vec4_t)); float percent = currValue / inc; calcColor[3] *= percent; } cgi_R_SetColor( calcColor); CG_DrawPic( ammoTics[i].xPos, ammoTics[i].yPos, ammoTics[i].width, ammoTics[i].height, ammoTics[i].background ); currValue -= inc; } } /* ================ CG_DrawHealth ================ */ static void CG_DrawHealth(const int x,const int y,const int w,const int h) { vec4_t calcColor; playerState_t *ps = &cg.snap->ps; // Print all the tics of the health graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health float inc = (float) ps->stats[STAT_MAX_HEALTH] / MAX_HUD_TICS; float currValue = ps->stats[STAT_HEALTH]; memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); int i; for (i=(MAX_HUD_TICS-1);i>=0;i--) { if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { memcpy(calcColor, healthTics[i].color, sizeof(vec4_t)); float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } cgi_R_SetColor( calcColor); CG_DrawPic( healthTics[i].xPos, healthTics[i].yPos, healthTics[i].width, healthTics[i].height, healthTics[i].background ); currValue -= inc; } // Print force health amount cgi_R_SetColor( otherHUDBits[OHB_HEALTHAMOUNT].color ); CG_DrawNumField ( otherHUDBits[OHB_HEALTHAMOUNT].xPos, otherHUDBits[OHB_HEALTHAMOUNT].yPos, 3, ps->stats[STAT_HEALTH], otherHUDBits[OHB_HEALTHAMOUNT].width, otherHUDBits[OHB_HEALTHAMOUNT].height, NUM_FONT_SMALL, qfalse); } /* ================ CG_DrawArmor Draw the armor graphics (tics) and the armor numeric amount. Any tics that are partial will be alphaed out. ================ */ static void CG_DrawArmor(const int x,const int y,const int w,const int h) { vec4_t calcColor; playerState_t *ps = &cg.snap->ps; // Print all the tics of the armor graphic // Look at the amount of armor left and show only as much of the graphic as there is armor. // Use alpha to fade out partial section of armor // MAX_HEALTH is the same thing as max armor float inc = (float) ps->stats[STAT_MAX_HEALTH] / MAX_HUD_TICS; float currValue = ps->stats[STAT_ARMOR]; memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); int i; for (i=(MAX_HUD_TICS-1);i>=0;i--) { if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { memcpy(calcColor, armorTics[i].color, sizeof(vec4_t)); float percent = currValue / inc; calcColor[3] *= percent; } cgi_R_SetColor( calcColor); if ((i==(MAX_HUD_TICS-1)) && (currValue < inc)) { if (cg.HUDArmorFlag) { CG_DrawPic( armorTics[i].xPos, armorTics[i].yPos, armorTics[i].width, armorTics[i].height, armorTics[i].background ); } } else { CG_DrawPic( armorTics[i].xPos, armorTics[i].yPos, armorTics[i].width, armorTics[i].height, armorTics[i].background ); } currValue -= inc; } // Print armor amount cgi_R_SetColor( otherHUDBits[OHB_ARMORAMOUNT].color ); CG_DrawNumField ( otherHUDBits[OHB_ARMORAMOUNT].xPos, otherHUDBits[OHB_ARMORAMOUNT].yPos, 3, ps->stats[STAT_ARMOR], otherHUDBits[OHB_ARMORAMOUNT].width, otherHUDBits[OHB_ARMORAMOUNT].height, NUM_FONT_SMALL, qfalse); // If armor is low, flash a graphic to warn the player if (ps->stats[STAT_ARMOR]) // Is there armor? Draw the HUD Armor TIC { float quarterArmor = (float) (ps->stats[STAT_MAX_HEALTH] / 4.0f); // Make tic flash if armor is at 25% of full armor if (ps->stats[STAT_ARMOR] < quarterArmor) // Do whatever the flash timer says { if (cg.HUDTickFlashTime < cg.time) // Flip at the same time { cg.HUDTickFlashTime = cg.time + 400; if (cg.HUDArmorFlag) { cg.HUDArmorFlag = qfalse; } else { cg.HUDArmorFlag = qtrue; } } } else { cg.HUDArmorFlag=qtrue; } } else // No armor? Don't show it. { cg.HUDArmorFlag=qfalse; } } #define MAX_VHUD_SHIELD_TICS 12 #define MAX_VHUD_SPEED_TICS 5 #define MAX_VHUD_ARMOR_TICS 5 #define MAX_VHUD_AMMO_TICS 5 static void CG_DrawVehicleSheild( const centity_t *cent, const Vehicle_t *pVeh ) { int xPos,yPos,width,height,i; vec4_t color,calcColor; qhandle_t background; char itemName[64]; float inc, currValue,maxHealth; //riding some kind of living creature if ( pVeh->m_pVehicleInfo->type == VH_ANIMAL || pVeh->m_pVehicleInfo->type == VH_FLIER ) { maxHealth = 100.0f; currValue = pVeh->m_pParentEntity->health; } else //normal vehicle { maxHealth = pVeh->m_pVehicleInfo->armor; currValue = pVeh->m_iArmor; } if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "shieldbackground", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health inc = (float) maxHealth / MAX_VHUD_SHIELD_TICS; for (i=1;i <= MAX_VHUD_SHIELD_TICS;i++) { sprintf( itemName, "shield_tic%d", i ); if (!cgi_UI_GetMenuItemInfo( "swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } cgi_R_SetColor( calcColor); CG_DrawPic( xPos, yPos, width, height, background ); currValue -= inc; } } // The HUD.menu file has the graphic print with a negative height, so it will print from the bottom up. static void CG_DrawVehicleTurboRecharge( const centity_t *cent, const Vehicle_t *pVeh ) { int xPos,yPos,width,height; qhandle_t background; vec4_t color; if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "turborecharge", &xPos, &yPos, &width, &height, color, &background)) { float percent=0.0f; int diff = ( cg.time - pVeh->m_iTurboTime ); // Calc max time if (diff > pVeh->m_pVehicleInfo->turboRecharge) { percent = 1.0f; cgi_R_SetColor( colorTable[CT_GREEN] ); } else { percent = (float) diff / pVeh->m_pVehicleInfo->turboRecharge; if (percent < 0.0f) { percent = 0.0f; } cgi_R_SetColor( colorTable[CT_RED] ); } height *= percent; CG_DrawPic(xPos,yPos, width, height, cgs.media.whiteShader); // Top } } static void CG_DrawVehicleSpeed( const centity_t *cent, const Vehicle_t *pVeh, const char *entHud ) { int xPos,yPos,width,height; qhandle_t background; gentity_t *parent = pVeh->m_pParentEntity; playerState_t *parentPS = &parent->client->ps; float currValue,maxSpeed; vec4_t color,calcColor; float inc; int i; char itemName[64]; if (cgi_UI_GetMenuItemInfo( entHud, "speedbackground", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } maxSpeed = pVeh->m_pVehicleInfo->speedMax; currValue = parentPS->speed; // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health inc = (float) maxSpeed / MAX_VHUD_SPEED_TICS; for (i=1;i<=MAX_VHUD_SPEED_TICS;i++) { sprintf( itemName, "speed_tic%d", i ); if (!cgi_UI_GetMenuItemInfo( entHud, itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } if ( level.time > pVeh->m_iTurboTime ) { memcpy(calcColor, color, sizeof(vec4_t)); } else // In turbo mode { if (cg.VHUDFlashTime < cg.time) { cg.VHUDFlashTime = cg.time + 400; if (cg.VHUDTurboFlag) { cg.VHUDTurboFlag = qfalse; } else { cg.VHUDTurboFlag = qtrue; } } if (cg.VHUDTurboFlag) { memcpy(calcColor, colorTable[CT_LTRED1], sizeof(vec4_t)); } else { memcpy(calcColor, color, sizeof(vec4_t)); } } if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } cgi_R_SetColor( calcColor); CG_DrawPic( xPos, yPos, width, height, background ); currValue -= inc; } } static void CG_DrawVehicleArmor( const centity_t *cent, const Vehicle_t *pVeh ) { int xPos,yPos,width,height,i; qhandle_t background; char itemName[64]; float inc, currValue,maxArmor; vec4_t color,calcColor; if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "armorbackground", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } maxArmor = pVeh->m_iArmor; currValue = pVeh->m_pVehicleInfo->armor; // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health inc = (float) maxArmor / MAX_VHUD_ARMOR_TICS; for (i=1;i<=MAX_VHUD_ARMOR_TICS;i++) { sprintf( itemName, "armor_tic%d", i ); if (!cgi_UI_GetMenuItemInfo( "swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } cgi_R_SetColor( calcColor); CG_DrawPic( xPos, yPos, width, height, background ); currValue -= inc; } } static void CG_DrawVehicleAmmo( const centity_t *cent, const Vehicle_t *pVeh ) { int xPos,yPos,width,height,i; qhandle_t background; char itemName[64]; float inc, currValue,maxAmmo; vec4_t color,calcColor; if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "ammobackground", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } maxAmmo = pVeh->m_pVehicleInfo->weapon[0].ammoMax; currValue = pVeh->weaponStatus[0].ammo; inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; for (i=1;i<=MAX_VHUD_AMMO_TICS;i++) { sprintf( itemName, "ammo_tic%d", i ); if (!cgi_UI_GetMenuItemInfo( "swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } cgi_R_SetColor( calcColor ); CG_DrawPic( xPos, yPos, width, height, background ); currValue -= inc; } } static void CG_DrawVehicleAmmoUpper( const centity_t *cent, const Vehicle_t *pVeh ) { int xPos,yPos,width,height,i; qhandle_t background; char itemName[64]; float inc, currValue,maxAmmo; vec4_t color,calcColor; if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "ammoupperbackground", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } maxAmmo = pVeh->m_pVehicleInfo->weapon[0].ammoMax; currValue = pVeh->weaponStatus[0].ammo; inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; for (i=1;i<MAX_VHUD_AMMO_TICS;i++) { sprintf( itemName, "ammoupper_tic%d", i ); if (!cgi_UI_GetMenuItemInfo( "swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } cgi_R_SetColor( calcColor ); CG_DrawPic( xPos, yPos, width, height, background ); currValue -= inc; } } static void CG_DrawVehicleAmmoLower( const centity_t *cent, const Vehicle_t *pVeh ) { int xPos,yPos,width,height,i; qhandle_t background; char itemName[64]; float inc, currValue,maxAmmo; vec4_t color,calcColor; if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "ammolowerbackground", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } maxAmmo = pVeh->m_pVehicleInfo->weapon[1].ammoMax; currValue = pVeh->weaponStatus[1].ammo; inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; for (i=1;i<MAX_VHUD_AMMO_TICS;i++) { sprintf( itemName, "ammolower_tic%d", i ); if (!cgi_UI_GetMenuItemInfo( "swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } cgi_R_SetColor( calcColor ); CG_DrawPic( xPos, yPos, width, height, background ); currValue -= inc; } } static void CG_DrawVehicleHud( const centity_t *cent, const Vehicle_t *pVeh ) { int xPos,yPos,width,height; vec4_t color; qhandle_t background; CG_DrawVehicleTurboRecharge( cent, pVeh ); // Draw frame if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "leftframe", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "rightframe", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } CG_DrawVehicleSheild( cent, pVeh ); CG_DrawVehicleSpeed( cent, pVeh, "swoopvehiclehud" ); CG_DrawVehicleArmor( cent, pVeh ); CG_DrawVehicleAmmo( cent, pVeh ); if (0) { CG_DrawVehicleAmmoUpper( cent, pVeh ); } if (0) { CG_DrawVehicleAmmoLower( cent, pVeh ); } } static void CG_DrawTauntaunHud( const centity_t *cent, const Vehicle_t *pVeh ) { int xPos,yPos,width,height; vec4_t color; qhandle_t background; CG_DrawVehicleTurboRecharge( cent, pVeh ); // Draw frame if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "leftframe", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "rightframe", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } CG_DrawVehicleSheild( cent, pVeh ); CG_DrawVehicleSpeed( cent, pVeh, "tauntaunhud" ); if (0) { CG_DrawVehicleAmmoUpper( cent, pVeh ); } if (0) { CG_DrawVehicleAmmoLower( cent, pVeh ); } } static void CG_DrawEmplacedGunHealth( const centity_t *cent ) { int xPos,yPos,width,height,i, health=0; vec4_t color,calcColor; qhandle_t background; char itemName[64]; float inc, currValue,maxHealth; if ( cent->gent && cent->gent->owner ) { if (( cent->gent->owner->flags & FL_GODMODE )) { // chair is in godmode, so render the health of the player instead health = cent->gent->health; } else { // render the chair health health = cent->gent->owner->health; } } else { return; } //riding some kind of living creature maxHealth = (float)cent->gent->max_health; currValue = health; if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "shieldbackground", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health inc = (float) maxHealth / MAX_VHUD_SHIELD_TICS; for (i=1;i <= MAX_VHUD_SHIELD_TICS;i++) { sprintf( itemName, "shield_tic%d", i ); if (!cgi_UI_GetMenuItemInfo( "swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } cgi_R_SetColor( calcColor); CG_DrawPic( xPos, yPos, width, height, background ); currValue -= inc; } } static void CG_DrawEmplacedGunHud( const centity_t *cent ) { int xPos,yPos,width,height; vec4_t color; qhandle_t background; // Draw frame if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "leftframe", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "rightframe", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } CG_DrawEmplacedGunHealth( cent ); } static void CG_DrawItemHealth( float currValue, float maxHealth ) { int xPos,yPos,width,height,i; vec4_t color,calcColor; qhandle_t background; char itemName[64]; float inc; if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "shieldbackground", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health inc = (float) maxHealth / MAX_VHUD_SHIELD_TICS; for (i=1;i <= MAX_VHUD_SHIELD_TICS;i++) { sprintf( itemName, "shield_tic%d", i ); if (!cgi_UI_GetMenuItemInfo( "swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); if (currValue <= 0) // don't show tic { break; } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; calcColor[3] *= percent; // Fade it out } cgi_R_SetColor( calcColor); CG_DrawPic( xPos, yPos, width, height, background ); currValue -= inc; } } static void CG_DrawPanelTurretHud( void ) { int xPos,yPos,width,height; vec4_t color; qhandle_t background; // Draw frame if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "leftframe", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "rightframe", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } CG_DrawItemHealth( g_entities[cg.snap->ps.viewEntity].health, (float)g_entities[cg.snap->ps.viewEntity].max_health ); } static void CG_DrawATSTHud( centity_t *cent ) { int xPos,yPos,width,height; vec4_t color; qhandle_t background; float health; if ( !cg.snap ||!g_entities[cg.snap->ps.viewEntity].activator ) { return; } // Draw frame if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "leftframe", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } if (cgi_UI_GetMenuItemInfo( "swoopvehiclehud", "rightframe", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } // we just calc the display value from the sum of health and armor if ( g_entities[cg.snap->ps.viewEntity].activator ) // ensure we can look back to the atst_drivable to get the max health { health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR] ); } else { health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR] ); } CG_DrawItemHealth(health,g_entities[cg.snap->ps.viewEntity].activator->max_health ); if (cgi_UI_GetMenuItemInfo( "atsthud", "background", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } if (cgi_UI_GetMenuItemInfo( "atsthud", "outer_frame", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } if (cgi_UI_GetMenuItemInfo( "atsthud", "left_pic", &xPos, &yPos, &width, &height, color, &background)) { cgi_R_SetColor( color ); CG_DrawPic( xPos, yPos, width, height, background ); } } //----------------------------------------------------- static qboolean CG_DrawCustomHealthHud( centity_t *cent ) { Vehicle_t *pVeh; // In a Weapon? if (( cent->currentState.eFlags & EF_LOCKED_TO_WEAPON )) { CG_DrawEmplacedGunHud(cent); // DRAW emplaced HUD /* color[0] = color[1] = color[2] = 0.0f; color[3] = 0.3f; cgi_R_SetColor( color ); CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader ); // NOTE: this looks ugly if ( cent->gent && cent->gent->owner ) { if (( cent->gent->owner->flags & FL_GODMODE )) { // chair is in godmode, so render the health of the player instead health = cent->gent->health / (float)cent->gent->max_health; } else { // render the chair health health = cent->gent->owner->health / (float)cent->gent->owner->max_health; } } color[0] = 1.0f; color[3] = 0.5f; cgi_R_SetColor( color ); CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader ); cgi_R_SetColor( colorTable[CT_WHITE] ); CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader); */ return qfalse; // drew this hud, so don't draw the player one } // In an ATST else if (( cent->currentState.eFlags & EF_IN_ATST )) { /* // we are an ATST... color[0] = color[1] = color[2] = 0.0f; color[3] = 0.3f; cgi_R_SetColor( color ); CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader ); // we just calc the display value from the sum of health and armor if ( g_entities[cg.snap->ps.viewEntity].activator ) // ensure we can look back to the atst_drivable to get the max health { health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR] ) / (float)(g_entities[cg.snap->ps.viewEntity].max_health + g_entities[cg.snap->ps.viewEntity].activator->max_health ); } else { health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR]) / (float)(g_entities[cg.snap->ps.viewEntity].max_health + 800 ); // hacked max armor since we don't have an activator...should never happen } color[1] = 0.25f; // blue-green color[2] = 1.0f; color[3] = 0.5f; cgi_R_SetColor( color ); CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader ); cgi_R_SetColor( colorTable[CT_WHITE] ); CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader); */ CG_DrawATSTHud(cent); return qfalse; // drew this hud, so don't draw the player one } // In a vehicle else if ( (pVeh = G_IsRidingVehicle( cent->gent ) ) != 0 ) { //riding some kind of living creature if ( pVeh->m_pVehicleInfo->type == VH_ANIMAL ) { CG_DrawTauntaunHud( cent, pVeh ); } else { CG_DrawVehicleHud( cent, pVeh ); } return qtrue; // draw this hud AND the player one } // Other? else if ( cg.snap->ps.viewEntity && ( g_entities[cg.snap->ps.viewEntity].dflags & DAMAGE_CUSTOM_HUD )) { CG_DrawPanelTurretHud(); return qfalse; // drew this hud, so don't draw the player one } return qtrue; } //-------------------------------------- static void CG_DrawBatteryCharge( void ) { if ( cg.batteryChargeTime > cg.time ) { vec4_t color; // FIXME: drawing it here will overwrite zoom masks...find a better place if ( cg.batteryChargeTime < cg.time + 1000 ) { // fading out for the last second color[0] = color[1] = color[2] = 1.0f; color[3] = (cg.batteryChargeTime - cg.time) / 1000.0f; } else { // draw full color[0] = color[1] = color[2] = color[3] = 1.0f; } cgi_R_SetColor( color ); // batteries were just charged CG_DrawPic( 605, 295, 24, 32, cgs.media.batteryChargeShader ); } } /* ================ CG_DrawHUD ================ */ static void CG_DrawHUD( centity_t *cent ) { int value; int sectionXPos,sectionYPos,sectionWidth,sectionHeight; // Draw the lower left section of the HUD if (cgi_UI_GetMenuInfo("lefthud",&sectionXPos,&sectionYPos,&sectionWidth,&sectionHeight)) { // Draw armor & health values if ( cg_drawStatus.integer == 2 ) { CG_DrawSmallStringColor(sectionXPos+5, sectionYPos - 60,va("Armor:%d",cg.snap->ps.stats[STAT_ARMOR]), colorTable[CT_HUD_GREEN] ); CG_DrawSmallStringColor(sectionXPos+5, sectionYPos - 40,va("Health:%d",cg.snap->ps.stats[STAT_HEALTH]), colorTable[CT_HUD_GREEN] ); } // Print scanline cgi_R_SetColor( otherHUDBits[OHB_SCANLINE_LEFT].color); CG_DrawPic( otherHUDBits[OHB_SCANLINE_LEFT].xPos, otherHUDBits[OHB_SCANLINE_LEFT].yPos, otherHUDBits[OHB_SCANLINE_LEFT].width, otherHUDBits[OHB_SCANLINE_LEFT].height, otherHUDBits[OHB_SCANLINE_LEFT].background ); // Print frame cgi_R_SetColor( otherHUDBits[OHB_FRAME_LEFT].color); CG_DrawPic( otherHUDBits[OHB_FRAME_LEFT].xPos, otherHUDBits[OHB_FRAME_LEFT].yPos, otherHUDBits[OHB_FRAME_LEFT].width, otherHUDBits[OHB_FRAME_LEFT].height, otherHUDBits[OHB_FRAME_LEFT].background ); CG_DrawArmor(sectionXPos,sectionYPos,sectionWidth,sectionHeight); CG_DrawHealth(sectionXPos,sectionYPos,sectionWidth,sectionHeight); } // Draw the lower right section of the HUD if (cgi_UI_GetMenuInfo("righthud",&sectionXPos,&sectionYPos,&sectionWidth,&sectionHeight)) { // Draw armor & health values if ( cg_drawStatus.integer == 2 ) { if ( cent->currentState.weapon != WP_SABER && cent->currentState.weapon != WP_STUN_BATON && cent->gent ) { value = cg.snap->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex]; CG_DrawSmallStringColor(sectionXPos, sectionYPos - 60,va("Ammo:%d",value), colorTable[CT_HUD_GREEN] ); } CG_DrawSmallStringColor(sectionXPos, sectionYPos - 40,va("Force:%d",cent->gent->client->ps.forcePower), colorTable[CT_HUD_GREEN] ); } // Print scanline cgi_R_SetColor( otherHUDBits[OHB_SCANLINE_RIGHT].color); CG_DrawPic( otherHUDBits[OHB_SCANLINE_RIGHT].xPos, otherHUDBits[OHB_SCANLINE_RIGHT].yPos, otherHUDBits[OHB_SCANLINE_RIGHT].width, otherHUDBits[OHB_SCANLINE_RIGHT].height, otherHUDBits[OHB_SCANLINE_RIGHT].background ); // Print frame cgi_R_SetColor( otherHUDBits[OHB_FRAME_RIGHT].color); CG_DrawPic( otherHUDBits[OHB_FRAME_RIGHT].xPos, otherHUDBits[OHB_FRAME_RIGHT].yPos, otherHUDBits[OHB_FRAME_RIGHT].width, otherHUDBits[OHB_FRAME_RIGHT].height, otherHUDBits[OHB_FRAME_RIGHT].background ); CG_DrawForcePower(cent,sectionXPos,sectionYPos); // Draw ammo tics or saber style if ( cent->currentState.weapon == WP_SABER ) { CG_DrawSaberStyle(cent,sectionXPos,sectionYPos); } else { CG_DrawAmmo(cent,sectionXPos,sectionYPos); } // CG_DrawMessageLit(cent,x,y); } } /* ================ CG_ClearDataPadCvars ================ */ void CG_ClearDataPadCvars( void ) { cg_updatedDataPadForcePower1.integer = 0; //don't wait for the cvar-refresh. cg_updatedDataPadForcePower2.integer = 0; //don't wait for the cvar-refresh. cg_updatedDataPadForcePower3.integer = 0; //don't wait for the cvar-refresh. cgi_Cvar_Set( "cg_updatedDataPadForcePower1", "0" ); cgi_Cvar_Set( "cg_updatedDataPadForcePower2", "0" ); cgi_Cvar_Set( "cg_updatedDataPadForcePower3", "0" ); cg_updatedDataPadObjective.integer = 0; //don't wait for the cvar-refresh. cgi_Cvar_Set( "cg_updatedDataPadObjective", "0" ); } /* ================ CG_DrawDataPadHUD ================ */ void CG_DrawDataPadHUD( centity_t *cent ) { int x,y; x = 34; y = 286; CG_DrawHealth(x,y,80,80); x = 526; if ((missionInfo_Updated) && ((cg_updatedDataPadForcePower1.integer) || (cg_updatedDataPadObjective.integer))) { // Stop flashing light cg.missionInfoFlashTime = 0; missionInfo_Updated = qfalse; // Set which force power to show. // cg_updatedDataPadForcePower is set from Q3_Interface, because force powers would only be given // from a script. if (cg_updatedDataPadForcePower1.integer) { cg.DataPadforcepowerSelect = cg_updatedDataPadForcePower1.integer - 1; // Not pretty, I know if (cg.DataPadforcepowerSelect >= MAX_DPSHOWPOWERS) { //duh cg.DataPadforcepowerSelect = MAX_DPSHOWPOWERS-1; } else if (cg.DataPadforcepowerSelect<0) { cg.DataPadforcepowerSelect=0; } } // CG_ClearDataPadCvars(); } CG_DrawForcePower(cent,x,y); CG_DrawAmmo(cent,x,y); CG_DrawMessageLit(cent,x,y); cgi_R_SetColor( colorTable[CT_WHITE]); CG_DrawPic( 0, 0, 640, 480, cgs.media.dataPadFrame ); } //------------------------ // CG_DrawZoomMask //------------------------ static void CG_DrawBinocularNumbers( qboolean power ) { vec4_t color1; cgi_R_SetColor( colorTable[CT_BLACK]); CG_DrawPic( 212, 367, 200, 40, cgs.media.whiteShader ); if ( power ) { // Numbers should be kind of greenish color1[0] = 0.2f; color1[1] = 0.4f; color1[2] = 0.2f; color1[3] = 0.3f; cgi_R_SetColor( color1 ); // Draw scrolling numbers, use intervals 10 units apart--sorry, this section of code is just kind of hacked // up with a bunch of magic numbers..... int val = ((int)((cg.refdefViewAngles[YAW] + 180) / 10)) * 10; float off = (cg.refdefViewAngles[YAW] + 180) - val; for ( int i = -10; i < 30; i += 10 ) { val -= 10; if ( val < 0 ) { val += 360; } // we only want to draw the very far left one some of the time, if it's too far to the left it will poke outside the mask. if (( off > 3.0f && i == -10 ) || i > -10 ) { // draw the value, but add 200 just to bump the range up...arbitrary, so change it if you like CG_DrawNumField( 155 + i * 10 + off * 10, 374, 3, val + 200, 24, 14, NUM_FONT_CHUNKY, qtrue ); CG_DrawPic( 245 + (i-1) * 10 + off * 10, 376, 6, 6, cgs.media.whiteShader ); } } CG_DrawPic( 212, 367, 200, 28, cgs.media.binocularOverlay ); } } /* ================ CG_DrawZoomMask ================ */ extern float cg_zoomFov; //from cg_view.cpp static void CG_DrawZoomMask( void ) { vec4_t color1; centity_t *cent; float level; static qboolean flip = qtrue; float charge = cg.snap->ps.batteryCharge / (float)MAX_BATTERIES; // convert charge to a percentage qboolean power = qfalse; cent = &cg_entities[0]; if ( charge > 0.0f ) { power = qtrue; } //------------- // Binoculars //-------------------------------- if ( cg.zoomMode == 1 ) { CG_RegisterItemVisuals( ITM_BINOCULARS_PICKUP ); // zoom level level = (float)(80.0f - cg_zoomFov) / 80.0f; // ...so we'll clamp it if ( level < 0.0f ) { level = 0.0f; } else if ( level > 1.0f ) { level = 1.0f; } // Using a magic number to convert the zoom level to scale amount level *= 162.0f; if ( power ) { // draw blue tinted distortion mask, trying to make it as small as is necessary to fill in the viewable area cgi_R_SetColor( colorTable[CT_WHITE] ); CG_DrawPic( 34, 48, 570, 362, cgs.media.binocularStatic ); } CG_DrawBinocularNumbers( power ); // Black out the area behind the battery display cgi_R_SetColor( colorTable[CT_DKGREY]); CG_DrawPic( 50, 389, 161, 16, cgs.media.whiteShader ); if ( power ) { color1[0] = sinf( cg.time * 0.01f ) * 0.5f + 0.5f; color1[0] = color1[0] * color1[0]; color1[1] = color1[0]; color1[2] = color1[0]; color1[3] = 1.0f; cgi_R_SetColor( color1 ); CG_DrawPic( 82, 94, 16, 16, cgs.media.binocularCircle ); } CG_DrawPic( 0, 0, 640, 480, cgs.media.binocularMask ); if ( power ) { // Flickery color color1[0] = 0.7f + crandom() * 0.1f; color1[1] = 0.8f + crandom() * 0.1f; color1[2] = 0.7f + crandom() * 0.1f; color1[3] = 1.0f; cgi_R_SetColor( color1 ); CG_DrawPic( 4, 282 - level, 16, 16, cgs.media.binocularArrow ); } else { // No power color color1[0] = 0.15f; color1[1] = 0.15f; color1[2] = 0.15f; color1[3] = 1.0f; cgi_R_SetColor( color1 ); } // The top triangle bit randomly flips when the power is on if ( flip && power ) { CG_DrawPic( 330, 60, -26, -30, cgs.media.binocularTri ); } else { CG_DrawPic( 307, 40, 26, 30, cgs.media.binocularTri ); } if ( randomLava() > 0.98f && ( cg.time & 1024 )) { flip = !flip; } if ( power ) { color1[0] = 1.0f * ( charge < 0.2f ? !!(cg.time & 256) : 1 ); color1[1] = charge * color1[0]; color1[2] = 0.0f; color1[3] = 0.2f; cgi_R_SetColor( color1 ); CG_DrawPic( 60, 394.5f, charge * 141, 5, cgs.media.whiteShader ); } } //------------ // Disruptor //-------------------------------- else if ( cg.zoomMode == 2 ) { level = (float)(80.0f - cg_zoomFov) / 80.0f; // ...so we'll clamp it if ( level < 0.0f ) { level = 0.0f; } else if ( level > 1.0f ) { level = 1.0f; } // Using a magic number to convert the zoom level to a rotation amount that correlates more or less with the zoom artwork. level *= 103.0f; // Draw target mask cgi_R_SetColor( colorTable[CT_WHITE] ); CG_DrawPic( 0, 0, 640, 480, cgs.media.disruptorMask ); // apparently 99.0f is the full zoom level if ( level >= 99 ) { // Fully zoomed, so make the rotating insert pulse color1[0] = 1.0f; color1[1] = 1.0f; color1[2] = 1.0f; color1[3] = 0.7f + sinf( cg.time * 0.01f ) * 0.3f; cgi_R_SetColor( color1 ); } // Draw rotating insert CG_DrawRotatePic2( 320, 240, 640, 480, -level, cgs.media.disruptorInsert ); float cx, cy; float max; max = cg_entities[0].gent->client->ps.ammo[weaponData[WP_DISRUPTOR].ammoIndex] / (float)ammoData[weaponData[WP_DISRUPTOR].ammoIndex].max; if ( max > 1.0f ) { max = 1.0f; } color1[0] = (1.0f - max) * 2.0f; color1[1] = max * 1.5f; color1[2] = 0.0f; color1[3] = 1.0f; // If we are low on ammo, make us flash if ( max < 0.15f && ( cg.time & 512 )) { VectorClear( color1 ); } if ( color1[0] > 1.0f ) { color1[0] = 1.0f; } if ( color1[1] > 1.0f ) { color1[1] = 1.0f; } cgi_R_SetColor( color1 ); max *= 58.0f; for ( float i = 18.5f; i <= 18.5f + max; i+= 3 ) // going from 15 to 45 degrees, with 5 degree increments { cx = 320 + sinf( (i+90.0f)/57.296f ) * 190; cy = 240 + cosf( (i+90.0f)/57.296f ) * 190; CG_DrawRotatePic2( cx, cy, 12, 24, 90 - i, cgs.media.disruptorInsertTick ); } // FIXME: doesn't know about ammo!! which is bad because it draws charge beyond what ammo you may have.. if ( cg_entities[0].gent->client->ps.weaponstate == WEAPON_CHARGING_ALT ) { cgi_R_SetColor( colorTable[CT_WHITE] ); // draw the charge level max = ( cg.time - cg_entities[0].gent->client->ps.weaponChargeTime ) / ( 150.0f * 10.0f ); // bad hardcodedness 150 is disruptor charge unit and 10 is max charge units allowed. if ( max > 1.0f ) { max = 1.0f; } CG_DrawPic2( 257, 435, 134 * max, 34, 0,0,max,1,cgi_R_RegisterShaderNoMip( "gfx/2d/crop_charge" )); } } //----------- // Light Amp //-------------------------------- else if ( cg.zoomMode == 3 ) { CG_RegisterItemVisuals( ITM_LA_GOGGLES_PICKUP ); if ( power ) { cgi_R_SetColor( colorTable[CT_WHITE] ); CG_DrawPic( 34, 29, 580, 410, cgs.media.laGogglesStatic ); CG_DrawPic( 570, 140, 12, 160, cgs.media.laGogglesSideBit ); float light = (128-cent->gent->lightLevel) * 0.5f; if ( light < -81 ) // saber can really jack up local light levels....?magic number?? { light = -81; } float pos1 = 220 + light; float pos2 = 220 + cosf( cg.time * 0.0004f + light * 0.05f ) * 40 + sinf( cg.time * 0.0013f + 1 ) * 20 + sinf( cg.time * 0.0021f ) * 5; // Flickery color color1[0] = 0.7f + crandom() * 0.2f; color1[1] = 0.8f + crandom() * 0.2f; color1[2] = 0.7f + crandom() * 0.2f; color1[3] = 1.0f; cgi_R_SetColor( color1 ); CG_DrawPic( 565, pos1, 22, 8, cgs.media.laGogglesBracket ); CG_DrawPic( 558, pos2, 14, 5, cgs.media.laGogglesArrow ); } // Black out the area behind the battery display cgi_R_SetColor( colorTable[CT_DKGREY]); CG_DrawPic( 236, 357, 164, 16, cgs.media.whiteShader ); if ( power ) { // Power bar color1[0] = 1.0f * ( charge < 0.2f ? !!(cg.time & 256) : 1 ); color1[1] = charge * color1[0]; color1[2] = 0.0f; color1[3] = 0.4f; cgi_R_SetColor( color1 ); CG_DrawPic( 247.0f, 362.5f, charge * 143.0f, 6, cgs.media.whiteShader ); // pulsing dot bit color1[0] = sinf( cg.time * 0.01f ) * 0.5f + 0.5f; color1[0] = color1[0] * color1[0]; color1[1] = color1[0]; color1[2] = color1[0]; color1[3] = 1.0f; cgi_R_SetColor( color1 ); CG_DrawPic( 65, 94, 16, 16, cgs.media.binocularCircle ); } CG_DrawPic( 0, 0, 640, 480, cgs.media.laGogglesMask ); } } /* ================ CG_DrawStats ================ */ static void CG_DrawStats( void ) { centity_t *cent; playerState_t *ps; if ( cg_drawStatus.integer == 0 ) { return; } cent = &cg_entities[cg.snap->ps.clientNum]; ps = &cg.snap->ps; if ((cg.snap->ps.viewEntity>0&&cg.snap->ps.viewEntity<ENTITYNUM_WORLD)) { // MIGHT try and draw a custom hud if it wants... CG_DrawCustomHealthHud( cent ); return; } cgi_UI_MenuPaintAll(); qboolean drawHud = qtrue; if ( cent && cent->gent ) { drawHud = CG_DrawCustomHealthHud( cent ); } if (( drawHud ) && ( cg_drawHUD.integer )) { CG_DrawHUD( cent ); } } /* =================== CG_DrawPickupItem =================== */ static void CG_DrawPickupItem( void ) { int value; float *fadeColor; value = cg.itemPickup; if ( value && cg_items[ value ].icon != -1 ) { fadeColor = CG_FadeColor( cg.itemPickupTime, 3000 ); if ( fadeColor ) { CG_RegisterItemVisuals( value ); cgi_R_SetColor( fadeColor ); CG_DrawPic( 573, 320, ICON_SIZE, ICON_SIZE, cg_items[ value ].icon ); //CG_DrawBigString( ICON_SIZE + 16, 398, bg_itemlist[ value ].classname, fadeColor[0] ); //CG_DrawProportionalString( ICON_SIZE + 16, 398, // bg_itemlist[ value ].classname, CG_SMALLFONT,fadeColor ); cgi_R_SetColor( NULL ); } } } extern int cgi_EndGame(void); /* =================== CG_DrawPickupItem =================== */ void CG_DrawCredits(void) { if (!cg.creditsStart) { // cg.creditsStart = qtrue; CG_Credits_Init("CREDITS_RAVEN", &colorTable[CT_ICON_BLUE]); if ( cg_skippingcin.integer ) {//Were skipping a cinematic and it's over now gi.cvar_set("timescale", "1"); gi.cvar_set("skippingCinematic", "0"); } } if (cg.creditsStart) { if ( !CG_Credits_Running() ) { cgi_Cvar_Set( "cg_endcredits", "0" ); cgi_EndGame(); } } } //draw the health bar based on current "health" and maxhealth void CG_DrawHealthBar(centity_t *cent, float chX, float chY, float chW, float chH) { vec4_t aColor; vec4_t bColor; vec4_t cColor; float x = chX-(chW/2); float y = chY-chH; float percent = 0.0f; if ( !cent || !cent->gent ) { return; } percent = ((float)cent->gent->health/(float)cent->gent->max_health); if (percent <= 0) { return; } //color of the bar //hostile aColor[0] = 1.0f; aColor[1] = 0.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; //color of the border bColor[0] = 0.0f; bColor[1] = 0.0f; bColor[2] = 0.0f; bColor[3] = 0.3f; //color of greyed out "missing health" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.4f; //draw the background (black) CG_DrawRect(x, y, chW, chH, 1.0f, colorTable[CT_BLACK]); //now draw the part to show how much health there is in the color specified CG_FillRect(x+1.0f, y+1.0f, (percent*chW)-1.0f, chH-1.0f, aColor); //then draw the other part greyed out CG_FillRect(x+(percent*chW), y+1.0f, chW-(percent*chW)-1.0f, chH-1.0f, cColor); } #define MAX_HEALTH_BAR_ENTS 32 int cg_numHealthBarEnts = 0; int cg_healthBarEnts[MAX_HEALTH_BAR_ENTS]; #define HEALTH_BAR_WIDTH 50 #define HEALTH_BAR_HEIGHT 5 void CG_DrawHealthBars( void ) { float chX=0, chY=0; centity_t *cent; vec3_t pos; for ( int i = 0; i < cg_numHealthBarEnts; i++ ) { cent = &cg_entities[cg_healthBarEnts[i]]; if ( cent && cent->gent ) { VectorCopy( cent->lerpOrigin, pos ); pos[2] += cent->gent->maxs[2]+HEALTH_BAR_HEIGHT+8; if ( CG_WorldCoordToScreenCoordFloat( pos, &chX, &chY ) ) {//on screen CG_DrawHealthBar( cent, chX, chY, HEALTH_BAR_WIDTH, HEALTH_BAR_HEIGHT ); } } } } #define HEALTHBARRANGE 422 void CG_AddHealthBarEnt( int entNum ) { if ( cg_numHealthBarEnts >= MAX_HEALTH_BAR_ENTS ) {//FIXME: Debug error message? return; } if (DistanceSquared( cg_entities[entNum].lerpOrigin, g_entities[0].client->renderInfo.eyePoint ) < (HEALTHBARRANGE*HEALTHBARRANGE) ) { cg_healthBarEnts[cg_numHealthBarEnts++] = entNum; } } void CG_ClearHealthBarEnts( void ) { if ( cg_numHealthBarEnts ) { cg_numHealthBarEnts = 0; memset( &cg_healthBarEnts, 0, MAX_HEALTH_BAR_ENTS ); } } /* ================================================================================ CROSSHAIR ================================================================================ */ /* ================= CG_DrawCrosshair ================= */ #ifdef AUTOAIM short cg_crossHairStatus = 0; #endif static void CG_DrawCrosshair( vec3_t worldPoint ) { float w, h; qhandle_t hShader; qboolean corona = qfalse; vec4_t ecolor; float f; float x, y; if ( !cg_drawCrosshair.integer ) { return; } if ( cg.zoomMode > 0 && cg.zoomMode < 3 ) { //not while scoped return; } #ifdef AUTOAIM cg_crossHairStatus = 0; #endif //set color based on what kind of ent is under crosshair if ( g_crosshairEntNum >= ENTITYNUM_WORLD ) { ecolor[0] = ecolor[1] = ecolor[2] = 1.0f; } else if ( cg_forceCrosshair && cg_crosshairForceHint.integer ) { ecolor[0] = 0.2f; ecolor[1] = 0.5f; ecolor[2] = 1.0f; corona = qtrue; } else if ( cg_crosshairIdentifyTarget.integer ) { gentity_t *crossEnt = &g_entities[g_crosshairEntNum]; if ( crossEnt->client ) { if ( crossEnt->client->ps.powerups[PW_CLOAKED] ) {//cloaked don't show up ecolor[0] = 1.0f;//R ecolor[1] = 1.0f;//G ecolor[2] = 1.0f;//B } else if ( g_entities[0].client && g_entities[0].client->playerTeam == TEAM_FREE ) {//evil player: everyone is red #ifdef AUTOAIM cg_crossHairStatus = 1; #endif //Enemies are red ecolor[0] = 1.0f;//R ecolor[1] = 0.1f;//G ecolor[2] = 0.1f;//B } else if ( crossEnt->client->playerTeam == TEAM_PLAYER ) { //Allies are green ecolor[0] = 0.0f;//R ecolor[1] = 1.0f;//G ecolor[2] = 0.0f;//B } else if ( crossEnt->client->playerTeam == TEAM_NEUTRAL ) { // NOTE: was yellow, but making it white unless they really decide they want to see colors ecolor[0] = 1.0f;//R ecolor[1] = 1.0f;//G ecolor[2] = 1.0f;//B } else { #ifdef AUTOAIM cg_crossHairStatus = 1; #endif //Enemies are red ecolor[0] = 1.0f;//R ecolor[1] = 0.1f;//G ecolor[2] = 0.1f;//B } } else if ( crossEnt->s.weapon == WP_TURRET && (crossEnt->svFlags&SVF_NONNPC_ENEMY) ) { // a turret if ( crossEnt->noDamageTeam == TEAM_PLAYER ) { // mine are green ecolor[0] = 0.0;//R ecolor[1] = 1.0;//G ecolor[2] = 0.0;//B } else { // hostile ones are red #ifdef AUTOAIM cg_crossHairStatus = 1; #endif ecolor[0] = 1.0;//R ecolor[1] = 0.0;//G ecolor[2] = 0.0;//B } } else if ( crossEnt->s.weapon == WP_TRIP_MINE ) { // tripmines are red #ifdef AUTOAIM cg_crossHairStatus = 1; #endif ecolor[0] = 1.0;//R ecolor[1] = 0.0;//G ecolor[2] = 0.0;//B } else if ( (crossEnt->flags&FL_RED_CROSSHAIR) ) {//special case flagged to turn crosshair red #ifdef AUTOAIM cg_crossHairStatus = 1; #endif ecolor[0] = 1.0;//R ecolor[1] = 0.0;//G ecolor[2] = 0.0;//B } else { VectorCopy( crossEnt->startRGBA, ecolor ); if ( !ecolor[0] && !ecolor[1] && !ecolor[2] ) { // We don't want a black crosshair, so use white since it will show up better ecolor[0] = 1.0f;//R ecolor[1] = 1.0f;//G ecolor[2] = 1.0f;//B } } } else // cg_crosshairIdentifyTarget is not on, so make it white { ecolor[0] = ecolor[1] = ecolor[2] = 1.0f; } ecolor[3] = 1.0; cgi_R_SetColor( ecolor ); if ( cg.forceCrosshairStartTime ) { // both of these calcs will fade the corona in one direction if ( cg.forceCrosshairEndTime ) { ecolor[3] = (cg.time - cg.forceCrosshairEndTime) / 500.0f; } else { ecolor[3] = (cg.time - cg.forceCrosshairStartTime) / 300.0f; } // clamp if ( ecolor[3] < 0 ) { ecolor[3] = 0; } else if ( ecolor[3] > 1.0f ) { ecolor[3] = 1.0f; } if ( !cg.forceCrosshairEndTime ) { // but for the other direction, we'll need to reverse it ecolor[3] = 1.0f - ecolor[3]; } } if ( corona ) // we are pointing at a crosshair item { if ( !cg.forceCrosshairStartTime ) { // must have just happened because we are not fading in yet...start it now cg.forceCrosshairStartTime = cg.time; cg.forceCrosshairEndTime = 0; } if ( cg.forceCrosshairEndTime ) { // must have just gone over a force thing again...and we were in the process of fading out. Set fade in level to the level where the fade left off cg.forceCrosshairStartTime = cg.time - ( 1.0f - ecolor[3] ) * 300.0f; cg.forceCrosshairEndTime = 0; } } else // not pointing at a crosshair item { if ( cg.forceCrosshairStartTime && !cg.forceCrosshairEndTime ) // were currently fading in { // must fade back out, but we will have to set the fadeout time to be equal to the current level of faded-in-edness cg.forceCrosshairEndTime = cg.time - ecolor[3] * 500.0f; } if ( cg.forceCrosshairEndTime && cg.time - cg.forceCrosshairEndTime > 500.0f ) // not pointing at anything and fade out is totally done { // reset everything cg.forceCrosshairStartTime = 0; cg.forceCrosshairEndTime = 0; } } w = h = cg_crosshairSize.value; // pulse the size of the crosshair when picking up items f = cg.time - cg.itemPickupBlendTime; if ( f > 0 && f < ITEM_BLOB_TIME ) { f /= ITEM_BLOB_TIME; w *= ( 1 + f ); h *= ( 1 + f ); } if ( worldPoint && VectorLength( worldPoint ) ) { if ( !CG_WorldCoordToScreenCoordFloat( worldPoint, &x, &y ) ) {//off screen, don't draw it return; } x -= 320;//???? y -= 240;//???? } else { x = cg_crosshairX.integer; y = cg_crosshairY.integer; } if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) { if ( !Q_stricmp( "misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname )) { // draws a custom crosshair that is twice as large as normal cgi_R_DrawStretchPic( x + cg.refdef.x + 320 - w, y + cg.refdef.y + 240 - h, w * 2, h * 2, 0, 0, 1, 1, cgs.media.turretCrossHairShader ); } } else { hShader = cgs.media.crosshairShader[ cg_drawCrosshair.integer % NUM_CROSSHAIRS ]; cgi_R_DrawStretchPic( x + cg.refdef.x + 0.5 * (640 - w), y + cg.refdef.y + 0.5 * (480 - h), w, h, 0, 0, 1, 1, hShader ); } if ( cg.forceCrosshairStartTime && cg_crosshairForceHint.integer ) // drawing extra bits { ecolor[0] = ecolor[1] = ecolor[2] = (1 - ecolor[3]) * ( sinf( cg.time * 0.001f ) * 0.08f + 0.35f ); // don't draw full color ecolor[3] = 1.0f; cgi_R_SetColor( ecolor ); w *= 2.0f; h *= 2.0f; cgi_R_DrawStretchPic( x + cg.refdef.x + 0.5f * ( 640 - w ), y + cg.refdef.y + 0.5f * ( 480 - h ), w, h, 0, 0, 1, 1, cgs.media.forceCoronaShader ); } } /* qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y) Take any world coord and convert it to a 2D virtual 640x480 screen coord */ qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) { float xcenter, ycenter; vec3_t local, transformed; // xcenter = cg.refdef.width / 2;//gives screen coords adjusted for resolution // ycenter = cg.refdef.height / 2;//gives screen coords adjusted for resolution //NOTE: did it this way because most draw functions expect virtual 640x480 coords // and adjust them for current resolution xcenter = 640.0f / 2.0f;//gives screen coords in virtual 640x480, to be adjusted when drawn ycenter = 480.0f / 2.0f;//gives screen coords in virtual 640x480, to be adjusted when drawn VectorSubtract (worldCoord, cg.refdef.vieworg, local); transformed[0] = DotProduct(local,vright); transformed[1] = DotProduct(local,vup); transformed[2] = DotProduct(local,vfwd); // Make sure Z is not negative. if(transformed[2] < 0.01f) { return qfalse; } // Simple convert to screen coords. float xzi = xcenter / transformed[2] * (100.0f/cg.refdef.fov_x); float yzi = ycenter / transformed[2] * (100.0f/cg.refdef.fov_y); *x = xcenter + xzi * transformed[0]; *y = ycenter - yzi * transformed[1]; return qtrue; } qboolean CG_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y ) { float xF, yF; qboolean retVal = CG_WorldCoordToScreenCoordFloat( worldCoord, &xF, &yF ); *x = (int)xF; *y = (int)yF; return retVal; } // I'm keeping the rocket tracking code separate for now since I may want to do different logic...but it still uses trace info from scanCrosshairEnt //----------------------------------------- static void CG_ScanForRocketLock( void ) //----------------------------------------- { gentity_t *traceEnt; static qboolean tempLock = qfalse; // this will break if anything else uses this locking code ( other than the player ) traceEnt = &g_entities[g_crosshairEntNum]; if ( !traceEnt || g_crosshairEntNum <= 0 || g_crosshairEntNum >= ENTITYNUM_WORLD || (!traceEnt->client && traceEnt->s.weapon != WP_TURRET ) || !traceEnt->health || ( traceEnt && traceEnt->client && traceEnt->client->ps.powerups[PW_CLOAKED] )) { // see how much locking we have int dif = ( cg.time - g_rocketLockTime ) / ( 1200.0f / 8.0f ); // 8 is full locking....also if we just traced onto the world, // give them 1/2 second of slop before dropping the lock if ( dif < 8 && g_rocketSlackTime + 500 < cg.time ) { // didn't have a full lock and not in grace period, so drop the lock g_rocketLockTime = 0; g_rocketSlackTime = 0; tempLock = qfalse; } if ( g_rocketSlackTime + 500 >= cg.time && g_rocketLockEntNum < ENTITYNUM_WORLD ) { // were locked onto an ent, aren't right now.....but still within the slop grace period // keep the current lock amount g_rocketLockTime += cg.frametime; } if ( !tempLock && g_rocketLockEntNum < ENTITYNUM_WORLD && dif >= 8 ) { tempLock = qtrue; if ( g_rocketLockTime + 1200 < cg.time ) { g_rocketLockTime = cg.time - 1200; // doh, hacking the time so the targetting still gets drawn full } } // keep locking to this thing for one second after it gets out of view if ( g_rocketLockTime + 2000.0f < cg.time ) // since time was hacked above, I'm compensating so that 2000ms is really only 1000ms { // too bad, you had your chance g_rocketLockEntNum = ENTITYNUM_NONE; g_rocketSlackTime = 0; g_rocketLockTime = 0; } } else { tempLock = qfalse; if ( g_rocketLockEntNum >= ENTITYNUM_WORLD ) { if ( g_rocketSlackTime + 500 < cg.time ) { // we just locked onto something, start the lock at the current time g_rocketLockEntNum = g_crosshairEntNum; g_rocketLockTime = cg.time; g_rocketSlackTime = cg.time; } } else { if ( g_rocketLockEntNum != g_crosshairEntNum ) { g_rocketLockTime = cg.time; } // may as well always set this when we can potentially lock to something g_rocketSlackTime = cg.time; g_rocketLockEntNum = g_crosshairEntNum; } } } /* ================= CG_ScanForCrosshairEntity ================= */ extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); extern float forcePushPullRadius[]; static void CG_ScanForCrosshairEntity( qboolean scanAll ) { trace_t trace; gentity_t *traceEnt = NULL; vec3_t start, end; int content; int ignoreEnt = cg.snap->ps.clientNum; Vehicle_t *pVeh = NULL; //FIXME: debounce this to about 10fps? cg_forceCrosshair = qfalse; if ( cg_entities[0].gent && cg_entities[0].gent->client ) // <-Mike said it should always do this //if (cg_crosshairForceHint.integer && {//try to check for force-affectable stuff first vec3_t d_f, d_rt, d_up; // If you're riding a vehicle and not being drawn. if ( ( pVeh = G_IsRidingVehicle( cg_entities[0].gent ) ) != NULL && cg_entities[0].currentState.eFlags & EF_NODRAW ) { VectorCopy( cg_entities[pVeh->m_pParentEntity->s.number].lerpOrigin, start ); AngleVectors( cg_entities[pVeh->m_pParentEntity->s.number].lerpAngles, d_f, d_rt, d_up ); } else { VectorCopy( g_entities[0].client->renderInfo.eyePoint, start ); AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up ); } VectorMA( start, 2048, d_f, end );//4028 is max for mind trick //YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James. gi.trace( &trace, start, vec3_origin, vec3_origin, end, ignoreEnt, MASK_OPAQUE|CONTENTS_SHOTCLIP|CONTENTS_BODY|CONTENTS_ITEM|CONTENTS_TERRAIN, G2_NOCOLLIDE, 10 );// ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys aren't shown, could just remove their body earlier too... if ( trace.entityNum < ENTITYNUM_WORLD ) {//hit something traceEnt = &g_entities[trace.entityNum]; if ( traceEnt ) { // Check for mind trickable-guys if ( traceEnt->client ) {//is a client if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_TELEPATHY] && traceEnt->health > 0 && VALIDSTRING(traceEnt->behaviorSet[BSET_MINDTRICK]) ) {//I have the ability to mind-trick and he is alive and he has a mind trick script //NOTE: no need to check range since it's always 2048 cg_forceCrosshair = qtrue; } } // No? Check for force-push/pullable doors and func_statics else if ( traceEnt->s.eType == ET_MOVER ) {//hit a mover if ( !Q_stricmp( "func_door", traceEnt->classname ) ) {//it's a func_door if ( traceEnt->spawnflags & 2/*MOVER_FORCE_ACTIVATE*/ ) {//it's force-usable if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] || cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] ) {//player has push or pull float maxRange; if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] ) {//use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]]; } else {//use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]]; } if ( maxRange >= trace.fraction * 2048 ) {//actually close enough to use one of our force powers on it cg_forceCrosshair = qtrue; } } } } else if ( !Q_stricmp( "func_static", traceEnt->classname ) ) {//it's a func_static if ( (traceEnt->spawnflags & 1/*F_PUSH*/) && (traceEnt->spawnflags & 2/*F_PULL*/) ) {//push or pullable float maxRange; if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] ) {//use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]]; } else {//use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]]; } if ( maxRange >= trace.fraction * 2048 ) {//actually close enough to use one of our force powers on it cg_forceCrosshair = qtrue; } } else if ( (traceEnt->spawnflags & 1/*F_PUSH*/) ) {//pushable only if ( forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]] >= trace.fraction * 2048 ) {//actually close enough to use force push on it cg_forceCrosshair = qtrue; } } else if ( (traceEnt->spawnflags & 2/*F_PULL*/) ) {//pullable only if ( forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]] >= trace.fraction * 2048 ) {//actually close enough to use force pull on it cg_forceCrosshair = qtrue; } } } } } } } if ( !cg_forceCrosshair ) { if ( 1 ) //(cg_dynamicCrosshair.integer ) {//100% accurate vec3_t d_f, d_rt, d_up; // If you're riding a vehicle and not being drawn. if ( ( pVeh = G_IsRidingVehicle( cg_entities[0].gent ) ) != NULL && cg_entities[0].currentState.eFlags & EF_NODRAW ) { VectorCopy( cg_entities[pVeh->m_pParentEntity->s.number].lerpOrigin, start ); AngleVectors( cg_entities[pVeh->m_pParentEntity->s.number].lerpAngles, d_f, d_rt, d_up ); } else if ( cg.snap->ps.weapon == WP_NONE || cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_STUN_BATON ) { if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) {//in camera ent view ignoreEnt = cg.snap->ps.viewEntity; if ( g_entities[cg.snap->ps.viewEntity].client ) { VectorCopy( g_entities[cg.snap->ps.viewEntity].client->renderInfo.eyePoint, start ); } else { VectorCopy( cg_entities[cg.snap->ps.viewEntity].lerpOrigin, start ); } AngleVectors( cg_entities[cg.snap->ps.viewEntity].lerpAngles, d_f, d_rt, d_up ); } else { VectorCopy( g_entities[0].client->renderInfo.eyePoint, start ); AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up ); } } else { extern void CalcMuzzlePoint( gentity_t *const ent, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint, float lead_in ); AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up ); CalcMuzzlePoint( &g_entities[0], d_f, d_rt, d_up, start , 0 ); } //VectorCopy( g_entities[0].client->renderInfo.muzzlePoint, start ); //FIXME: increase this? Increase when zoom in? VectorMA( start, 4096, d_f, end );//was 8192 } else {//old way VectorCopy( cg.refdef.vieworg, start ); //FIXME: increase this? Increase when zoom in? VectorMA( start, 4096, cg.refdef.viewaxis[0], end );//was 8192 } //YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James. gi.trace( &trace, start, vec3_origin, vec3_origin, end, ignoreEnt, MASK_OPAQUE|CONTENTS_TERRAIN|CONTENTS_SHOTCLIP|CONTENTS_BODY|CONTENTS_ITEM, G2_NOCOLLIDE, 10 );// ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys aren't shown, could just remove their body earlier too... /* CG_Trace( &trace, start, vec3_origin, vec3_origin, end, cg.snap->ps.clientNum, MASK_PLAYERSOLID|CONTENTS_CORPSE|CONTENTS_ITEM ); */ //FIXME: pick up corpses if ( trace.startsolid || trace.allsolid ) { // trace should not be allowed to pick up anything if it started solid. I tried actually moving the trace start back, which also worked, // but the dynamic cursor drawing caused it to render around the clip of the gun when I pushed the blaster all the way into a wall. // It looked quite horrible...but, if this is bad for some reason that I don't know trace.entityNum = ENTITYNUM_NONE; } traceEnt = &g_entities[trace.entityNum]; } // if the object is "dead", don't show it /* if ( cg.crosshairClientNum && g_entities[cg.crosshairClientNum].health <= 0 ) { cg.crosshairClientNum = 0; return; } */ //CROSSHAIR is now always drawn from this trace so it's 100% accurate if ( 1 ) //(cg_dynamicCrosshair.integer ) {//draw crosshair at endpoint CG_DrawCrosshair( trace.endpos ); } g_crosshairEntNum = trace.entityNum; g_crosshairEntDist = 4096*trace.fraction; if ( !traceEnt ) { //not looking at anything g_crosshairSameEntTime = 0; g_crosshairEntTime = 0; } else {//looking at a valid ent //store the distance if ( trace.entityNum != g_crosshairEntNum ) {//new crosshair ent g_crosshairSameEntTime = 0; } else if ( g_crosshairEntDist < 256 ) {//close enough to start counting how long you've been looking g_crosshairSameEntTime += cg.frametime; } //remember the last time you looked at the person g_crosshairEntTime = cg.time; } if ( !traceEnt ) { if ( traceEnt && scanAll ) { } else { return; } } // if the player is in fog, don't show it content = cgi_CM_PointContents( trace.endpos, 0 ); if ( content & CONTENTS_FOG ) { return; } // if the player is cloaked, don't show it if ( cg_entities[ trace.entityNum ].currentState.powerups & ( 1 << PW_CLOAKED )) { return; } // update the fade timer if ( cg.crosshairClientNum != trace.entityNum ) { infoStringCount = 0; } cg.crosshairClientNum = trace.entityNum; cg.crosshairClientTime = cg.time; } /* ===================== CG_DrawCrosshairNames ===================== */ static void CG_DrawCrosshairNames( void ) { qboolean scanAll = qfalse; centity_t *player = &cg_entities[0]; if ( 1 ) //cg_dynamicCrosshair.integer ) { // still need to scan for dynamic crosshair CG_ScanForCrosshairEntity( scanAll ); return; } if ( !player->gent ) { return; } if ( !player->gent->client ) { return; } // scan the known entities to see if the crosshair is sighted on one // This is currently being called by the rocket tracking code, so we don't necessarily want to do duplicate traces :) CG_ScanForCrosshairEntity( scanAll ); } //-------------------------------------------------------------- static void CG_DrawActivePowers(void) //-------------------------------------------------------------- { int icon_size = 40; int startx = icon_size*2+16; int starty = SCREEN_HEIGHT - icon_size*2; int endx = icon_size; int endy = icon_size; if (cg.zoomMode) { //don't display over zoom mask return; } /* //draw icon for duration powers so we know what powers are active cuttently int i = 0; while (i < NUM_FORCE_POWERS) { if ((cg.snap->ps.forcePowersActive & (1 << forcePowerSorted[i])) && CG_IsDurationPower(forcePowerSorted[i])) { CG_DrawPic( startx, starty, endx, endy, cgs.media.forcePowerIcons[forcePowerSorted[i]]); startx += (icon_size+2); //+2 for spacing if ((startx+icon_size) >= SCREEN_WIDTH-80) { startx = icon_size*2+16; starty += (icon_size+2); } } i++; } */ //additionally, draw an icon force force rage recovery if (cg.snap->ps.forceRageRecoveryTime > cg.time) { CG_DrawPic( startx, starty, endx, endy, cgs.media.rageRecShader); } } //-------------------------------------------------------------- static void CG_DrawRocketLocking( int lockEntNum, int lockTime ) //-------------------------------------------------------------- { gentity_t *gent = &g_entities[lockEntNum]; if ( !gent ) { return; } int cx, cy; vec3_t org; static int oldDif = 0; VectorCopy( gent->currentOrigin, org ); org[2] += (gent->mins[2] + gent->maxs[2]) * 0.5f; if ( CG_WorldCoordToScreenCoord( org, &cx, &cy )) { // we care about distance from enemy to eye, so this is good enough float sz = Distance( gent->currentOrigin, cg.refdef.vieworg ) / 1024.0f; if ( cg.zoomMode > 0 ) { if ( cg.overrides.active & CG_OVERRIDE_FOV ) { sz -= ( cg.overrides.fov - cg_zoomFov ) / 80.0f; } else { sz -= ( cg_fov.value - cg_zoomFov ) / 80.0f; } } if ( sz > 1.0f ) { sz = 1.0f; } else if ( sz < 0.0f ) { sz = 0.0f; } sz = (1.0f - sz) * (1.0f - sz) * 32 + 6; vec4_t color={0.0f,0.0f,0.0f,0.0f}; cy += sz * 0.5f; // well now, take our current lock time and divide that by 8 wedge slices to get the current lock amount int dif = ( cg.time - g_rocketLockTime ) / ( 1200.0f / 8.0f ); if ( dif < 0 ) { oldDif = 0; return; } else if ( dif > 8 ) { dif = 8; } // do sounds if ( oldDif != dif ) { if ( dif == 8 ) { cgi_S_StartSound( org, 0, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/rocket/lock.wav" )); } else { cgi_S_StartSound( org, 0, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/rocket/tick.wav" )); } } oldDif = dif; for ( int i = 0; i < dif; i++ ) { color[0] = 1.0f; color[1] = 0.0f; color[2] = 0.0f; color[3] = 0.1f * i + 0.2f; cgi_R_SetColor( color ); // our slices are offset by about 45 degrees. CG_DrawRotatePic( cx - sz, cy - sz, sz, sz, i * 45.0f, cgi_R_RegisterShaderNoMip( "gfx/2d/wedge" )); } // we are locked and loaded baby if ( dif == 8 ) { color[0] = color[1] = color[2] = sinf( cg.time * 0.05f ) * 0.5f + 0.5f; color[3] = 1.0f; // this art is additive, so the alpha value does nothing cgi_R_SetColor( color ); CG_DrawPic( cx - sz, cy - sz * 2, sz * 2, sz * 2, cgi_R_RegisterShaderNoMip( "gfx/2d/lock" )); } } } //------------------------------------ static void CG_RunRocketLocking( void ) //------------------------------------ { centity_t *player = &cg_entities[0]; // Only bother with this when the player is holding down the alt-fire button of the rocket launcher if ( player->currentState.weapon == WP_ROCKET_LAUNCHER ) { if ( player->currentState.eFlags & EF_ALT_FIRING ) { CG_ScanForRocketLock(); if ( g_rocketLockEntNum > 0 && g_rocketLockEntNum < ENTITYNUM_WORLD && g_rocketLockTime > 0 ) { #ifdef _XBOX FFFX_START( fffx_StartConst ); #endif CG_DrawRocketLocking( g_rocketLockEntNum, g_rocketLockTime ); } #ifdef _XBOX else { FFFX_START( fffx_StopConst ); } #endif } else { // disengage any residual locking #ifdef _XBOX FFFX_START( fffx_StopConst ); #endif g_rocketLockEntNum = ENTITYNUM_WORLD; g_rocketLockTime = 0; } } } /* ================= CG_DrawIntermission ================= */ static void CG_DrawIntermission( void ) { CG_DrawScoreboard(); } /* ================== CG_DrawSnapshot ================== */ static float CG_DrawSnapshot( float y ) { char *s; int w; s = va( "time:%i snap:%i cmd:%i", cg.snap->serverTime, cg.latestSnapshotNum, cgs.serverCommandSequence ); w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); cgi_R_Font_DrawString(635 - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); return y + BIGCHAR_HEIGHT + 10; } /* ================== CG_DrawFPS ================== */ #define FPS_FRAMES 16 static float CG_DrawFPS( float y ) { char *s; static unsigned short previousTimes[FPS_FRAMES]; static unsigned short index; static int previous, lastupdate; int t, i, fps, total; unsigned short frameTime; #ifdef _XBOX const int xOffset = 30; #else const int xOffset = 0; #endif // don't use serverTime, because that will be drifting to // correct for internet lag changes, timescales, timedemos, etc t = cgi_Milliseconds(); frameTime = t - previous; previous = t; if (t - lastupdate > 50) //don't sample faster than this { lastupdate = t; previousTimes[index % FPS_FRAMES] = frameTime; index++; } // average multiple frames together to smooth changes out a bit total = 0; for ( i = 0 ; i < FPS_FRAMES ; i++ ) { total += previousTimes[i]; } if ( !total ) { total = 1; } fps = 1000 * FPS_FRAMES / total; s = va( "%ifps", fps ); const int w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); cgi_R_Font_DrawString(635-xOffset - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); return y + BIGCHAR_HEIGHT + 10; } /* ================= CG_DrawTimer ================= */ static float CG_DrawTimer( float y ) { char *s; int w; int mins, seconds, tens; seconds = cg.time / 1000; mins = seconds / 60; seconds -= mins * 60; tens = seconds / 10; seconds -= tens * 10; s = va( "%i:%i%i", mins, tens, seconds ); w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); cgi_R_Font_DrawString(635 - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); return y + BIGCHAR_HEIGHT + 10; } /* ================= CG_DrawAmmoWarning ================= */ static void CG_DrawAmmoWarning( void ) { char text[1024]={0}; int w; if ( cg_drawAmmoWarning.integer == 0 ) { return; } if ( !cg.lowAmmoWarning ) { return; } if ( weaponData[cg.snap->ps.weapon].ammoIndex == AMMO_NONE ) {//doesn't use ammo, so no warning return; } if ( cg.lowAmmoWarning == 2 ) { cgi_SP_GetStringTextString( "SP_INGAME_INSUFFICIENTENERGY", text, sizeof(text) ); } else { return; //s = "LOW AMMO WARNING"; } w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); cgi_R_Font_DrawString(320 - w/2, 64, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 1.0f); } //--------------------------------------- static qboolean CG_RenderingFromMiscCamera() { //centity_t *cent; //cent = &cg_entities[cg.snap->ps.clientNum]; if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD )// cent && cent->gent && cent->gent->client && cent->gent->client->ps.viewEntity) { // Only check viewEntities if ( !Q_stricmp( "misc_camera", g_entities[cg.snap->ps.viewEntity].classname )) { // Only doing a misc_camera, so check health. if ( g_entities[cg.snap->ps.viewEntity].health > 0 ) { CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/workingCamera" )); } else { CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/brokenCamera" )); } // don't render other 2d stuff return qtrue; } else if ( !Q_stricmp( "misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname )) { // could do a panel turret screen overlay...this is a cheesy placeholder CG_DrawPic( 30, 90, 128, 300, cgs.media.turretComputerOverlayShader ); CG_DrawPic( 610, 90, -128, 300, cgs.media.turretComputerOverlayShader ); } else { // FIXME: make sure that this assumption is correct...because I'm assuming that I must be a droid. CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/droid_view" )); } } // not in misc_camera, render other stuff. return qfalse; } qboolean cg_usingInFrontOf = qfalse; qboolean CanUseInfrontOf(gentity_t*); static void CG_UseIcon() { cg_usingInFrontOf = CanUseInfrontOf(cg_entities[cg.snap->ps.clientNum].gent); if (cg_usingInFrontOf) { cgi_R_SetColor( NULL ); CG_DrawPic( 50, 285, 64, 64, cgs.media.useableHint ); } } static void CG_Draw2DScreenTints( void ) { float rageTime, rageRecTime, absorbTime, protectTime; vec4_t hcolor; //force effects if (cg.snap->ps.forcePowersActive & (1 << FP_RAGE)) { if (!cgRageTime) { cgRageTime = cg.time; } rageTime = (float)(cg.time - cgRageTime); rageTime /= 9000; if ( rageTime < 0 ) { rageTime = 0; } if ( rageTime > 0.15f ) { rageTime = 0.15f; } hcolor[3] = rageTime; hcolor[0] = 0.7f; hcolor[1] = 0; hcolor[2] = 0; if (!cg.renderingThirdPerson) { CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } cgRageFadeTime = 0; cgRageFadeVal = 0; } else if (cgRageTime) { if (!cgRageFadeTime) { cgRageFadeTime = cg.time; cgRageFadeVal = 0.15f; } rageTime = cgRageFadeVal; cgRageFadeVal -= (cg.time - cgRageFadeTime)*0.000005; if (rageTime < 0) { rageTime = 0; } if ( rageTime > 0.15f ) { rageTime = 0.15f; } if ( cg.snap->ps.forceRageRecoveryTime > cg.time ) { float checkRageRecTime = rageTime; if ( checkRageRecTime < 0.15f ) { checkRageRecTime = 0.15f; } hcolor[3] = checkRageRecTime; hcolor[0] = rageTime*4; if ( hcolor[0] < 0.2f ) { hcolor[0] = 0.2f; } hcolor[1] = 0.2f; hcolor[2] = 0.2f; } else { hcolor[3] = rageTime; hcolor[0] = 0.7f; hcolor[1] = 0; hcolor[2] = 0; } if (!cg.renderingThirdPerson && rageTime) { CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } else { if (cg.snap->ps.forceRageRecoveryTime > cg.time) { hcolor[3] = 0.15f; hcolor[0] = 0.2f; hcolor[1] = 0.2f; hcolor[2] = 0.2f; CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } cgRageTime = 0; } } else if (cg.snap->ps.forceRageRecoveryTime > cg.time) { if (!cgRageRecTime) { cgRageRecTime = cg.time; } rageRecTime = (float)(cg.time - cgRageRecTime); rageRecTime /= 9000; if ( rageRecTime < 0.15f )//0) { rageRecTime = 0.15f;//0; } if ( rageRecTime > 0.15f ) { rageRecTime = 0.15f; } hcolor[3] = rageRecTime; hcolor[0] = 0.2f; hcolor[1] = 0.2f; hcolor[2] = 0.2f; if ( !cg.renderingThirdPerson ) { CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } cgRageRecFadeTime = 0; cgRageRecFadeVal = 0; } else if (cgRageRecTime) { if (!cgRageRecFadeTime) { cgRageRecFadeTime = cg.time; cgRageRecFadeVal = 0.15f; } rageRecTime = cgRageRecFadeVal; cgRageRecFadeVal -= (cg.time - cgRageRecFadeTime)*0.000005; if (rageRecTime < 0) { rageRecTime = 0; } if ( rageRecTime > 0.15f ) { rageRecTime = 0.15f; } hcolor[3] = rageRecTime; hcolor[0] = 0.2f; hcolor[1] = 0.2f; hcolor[2] = 0.2f; if (!cg.renderingThirdPerson && rageRecTime) { CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } else { cgRageRecTime = 0; } } if (cg.snap->ps.forcePowersActive & (1 << FP_ABSORB)) { if (!cgAbsorbTime) { cgAbsorbTime = cg.time; } absorbTime = (float)(cg.time - cgAbsorbTime); absorbTime /= 9000; if ( absorbTime < 0 ) { absorbTime = 0; } if ( absorbTime > 0.15f ) { absorbTime = 0.15f; } hcolor[3] = absorbTime/2; hcolor[0] = 0; hcolor[1] = 0; hcolor[2] = 0.7f; if ( !cg.renderingThirdPerson ) { CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } cgAbsorbFadeTime = 0; cgAbsorbFadeVal = 0; } else if (cgAbsorbTime) { if (!cgAbsorbFadeTime) { cgAbsorbFadeTime = cg.time; cgAbsorbFadeVal = 0.15f; } absorbTime = cgAbsorbFadeVal; cgAbsorbFadeVal -= (cg.time - cgAbsorbFadeTime)*0.000005; if ( absorbTime < 0 ) { absorbTime = 0; } if ( absorbTime > 0.15f ) { absorbTime = 0.15f; } hcolor[3] = absorbTime/2; hcolor[0] = 0; hcolor[1] = 0; hcolor[2] = 0.7f; if ( !cg.renderingThirdPerson && absorbTime ) { CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } else { cgAbsorbTime = 0; } } if (cg.snap->ps.forcePowersActive & (1 << FP_PROTECT)) { if (!cgProtectTime) { cgProtectTime = cg.time; } protectTime = (float)(cg.time - cgProtectTime); protectTime /= 9000; if (protectTime < 0) { protectTime = 0; } if ( protectTime > 0.15f ) { protectTime = 0.15f; } hcolor[3] = protectTime/2; hcolor[0] = 0; hcolor[1] = 0.7f; hcolor[2] = 0; if ( !cg.renderingThirdPerson ) { CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } cgProtectFadeTime = 0; cgProtectFadeVal = 0; } else if ( cgProtectTime ) { if ( !cgProtectFadeTime ) { cgProtectFadeTime = cg.time; cgProtectFadeVal = 0.15f; } protectTime = cgProtectFadeVal; cgProtectFadeVal -= (cg.time - cgProtectFadeTime)*0.000005; if (protectTime < 0) { protectTime = 0; } if (protectTime > 0.15f) { protectTime = 0.15f; } hcolor[3] = protectTime/2; hcolor[0] = 0; hcolor[1] = 0.7f; hcolor[2] = 0; if ( !cg.renderingThirdPerson && protectTime ) { CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } else { cgProtectTime = 0; } } if ( (cg.refdef.viewContents&CONTENTS_LAVA) ) {//tint screen red float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; hcolor[3] = 0.5 + (0.15f*sinf( phase )); hcolor[0] = 0.7f; hcolor[1] = 0; hcolor[2] = 0; CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } else if ( (cg.refdef.viewContents&CONTENTS_SLIME) ) {//tint screen green float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; hcolor[3] = 0.4 + (0.1f*sinf( phase )); hcolor[0] = 0; hcolor[1] = 0.7f; hcolor[2] = 0; CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } else if ( (cg.refdef.viewContents&CONTENTS_WATER) ) {//tint screen light blue -- FIXME: check to see if in fog? float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; hcolor[3] = 0.3 + (0.05f*sinf( phase )); hcolor[0] = 0; hcolor[1] = 0.2f; hcolor[2] = 0.8f; CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); } } /* ================= CG_Draw2D ================= */ extern void CG_SaberClashFlare( void ); static void CG_Draw2D( void ) { char text[1024]={0}; int w,y_pos; centity_t *cent = &cg_entities[cg.snap->ps.clientNum]; // if we are taking a levelshot for the menu, don't draw anything if ( cg.levelShot ) { return; } if ( cg_draw2D.integer == 0 ) { return; } if ( cg.snap->ps.pm_type == PM_INTERMISSION ) { CG_DrawIntermission(); return; } CG_Draw2DScreenTints(); //end credits if (cg_endcredits.integer) { if (!CG_Credits_Draw()) { CG_DrawCredits(); // will probably get rid of this soon } } CGCam_DrawWideScreen(); CG_DrawBatteryCharge(); if (cg.snap->ps.forcePowersActive || cg.snap->ps.forceRageRecoveryTime > cg.time) { CG_DrawActivePowers(); } // Draw this before the text so that any text won't get clipped off if ( !in_camera ) { CG_DrawZoomMask(); } CG_DrawScrollText(); CG_DrawCaptionText(); if ( in_camera ) {//still draw the saber clash flare, but nothing else CG_SaberClashFlare(); return; } if ( CG_RenderingFromMiscCamera()) { // purposely doing an early out when in a misc_camera, change it if needed. // allowing center print when in camera mode, probably just an alpha thing - dmv CG_DrawCenterString(); return; } if ( (cg.snap->ps.forcePowersActive&(1<<FP_SEE)) ) {//force sight is on //indicate this with sight cone thingy CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/jsense" )); CG_DrawHealthBars(); } else if ( cg_debugHealthBars.integer ) { CG_DrawHealthBars(); } // don't draw any status if dead if ( cg.snap->ps.stats[STAT_HEALTH] > 0 ) { if ( !(cent->gent && cent->gent->s.eFlags & (EF_LOCKED_TO_WEAPON )))//|EF_IN_ATST { //CG_DrawIconBackground(); } CG_DrawWeaponSelect(); if ( cg.zoomMode == 0 ) { CG_DrawStats(); } CG_DrawAmmoWarning(); //CROSSHAIR is now done from the crosshair ent trace //if ( !cg.renderingThirdPerson && !cg_dynamicCrosshair.integer ) // disruptor draws it's own crosshair artwork; binocs draw nothing; third person draws its own crosshair //{ // CG_DrawCrosshair( NULL ); //} CG_DrawCrosshairNames(); CG_RunRocketLocking(); CG_DrawInventorySelect(); CG_DrawForceSelect(); CG_DrawPickupItem(); CG_UseIcon(); } CG_SaberClashFlare(); #ifdef _XBOX float y = 32; #else float y = 0; #endif if (cg_drawSnapshot.integer) { y=CG_DrawSnapshot(y); } if (cg_drawFPS.integer) { y=CG_DrawFPS(y); } if (cg_drawTimer.integer) { y=CG_DrawTimer(y); } // don't draw center string if scoreboard is up if ( !CG_DrawScoreboard() ) { CG_DrawCenterString(); } /* if (cg.showInformation) { // CG_DrawMissionInformation(); } else */ if (missionInfo_Updated) { if (cg.predicted_player_state.pm_type != PM_DEAD) { // Was a objective given? /* if ((cg_updatedDataPadForcePower.integer) || (cg_updatedDataPadObjective.integer)) { // How long has the game been running? If within 15 seconds of starting, throw up the datapad. if (cg.dataPadLevelStartTime>cg.time) { // Make it pop up if (!in_camera) { cgi_SendConsoleCommand( "datapad" ); cg.dataPadLevelStartTime=cg.time; //and don't do it again this level! } } } */ if (!cg.missionInfoFlashTime) { cg.missionInfoFlashTime = cg.time + cg_missionInfoFlashTime.integer; } if (cg.missionInfoFlashTime < cg.time) // Time's up. They didn't read it. { cg.missionInfoFlashTime = 0; missionInfo_Updated = qfalse; CG_ClearDataPadCvars(); } cgi_SP_GetStringTextString( "SP_INGAME_NEW_OBJECTIVE_INFO", text, sizeof(text) ); int x_pos = 0; y_pos = 20; w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontSmall, 1.0f); x_pos = (SCREEN_WIDTH/2)-(w/2); cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f); } } if (cg.weaponPickupTextTime > cg.time ) { int x_pos = 0; y_pos = 5; gi.Cvar_VariableStringBuffer( "cg_WeaponPickupText", text, sizeof(text) ); w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontSmall, 0.8f); x_pos = (SCREEN_WIDTH/2)-(w/2); cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_WHITE], cgs.media.qhFontMedium, -1, 0.8f); } } /* =================== CG_DrawIconBackground Choose the proper background for the icons, scale it depending on if your opening or closing the icon section of the HU =================== */ void CG_DrawIconBackground(void) { int backgroundXPos,backgroundYPos; int backgroundWidth,backgroundHeight; qhandle_t background; const float shutdownTime = 130.0f; // Are we in zoom mode or the HUD is turned off? if (( cg.zoomMode != 0 ) || !( cg_drawHUD.integer )) { return; } if ((cg.snap->ps.viewEntity>0 && cg.snap->ps.viewEntity<ENTITYNUM_WORLD)) { return; } // Get size and location of bakcround specified in the HUD.MENU file if (!cgi_UI_GetMenuInfo("iconbackground",&backgroundXPos,&backgroundYPos,&backgroundWidth,&backgroundHeight)) { return; } // Use inventory background? if (((cg.inventorySelectTime+WEAPON_SELECT_TIME)>cg.time) || (cgs.media.currentBackground == ICON_INVENTORY)) { background = cgs.media.inventoryIconBackground; } // Use weapon background? else if (((cg.weaponSelectTime+WEAPON_SELECT_TIME)>cg.time) || (cgs.media.currentBackground == ICON_WEAPONS)) { background = 0; //background = cgs.media.weaponIconBackground; } // Use force background? else { background = cgs.media.forceIconBackground; } // Time is up, shutdown the icon section of the HUD if ((cg.iconSelectTime+WEAPON_SELECT_TIME)<cg.time) { // Scale background down as it goes away if (background && cg.iconHUDActive) { cg.iconHUDPercent = (cg.time - (cg.iconSelectTime+WEAPON_SELECT_TIME))/ shutdownTime; cg.iconHUDPercent = 1.0f - cg.iconHUDPercent; if (cg.iconHUDPercent<0.0f) { cg.iconHUDActive = qfalse; cg.iconHUDPercent=0.f; } float holdFloat = (float) backgroundHeight; backgroundHeight = (int) (holdFloat*cg.iconHUDPercent); CG_DrawPic( backgroundXPos, backgroundYPos, backgroundWidth, -backgroundHeight, background); // Top half CG_DrawPic( backgroundXPos, backgroundYPos,backgroundWidth, backgroundHeight, background); // Bottom half } return; } // Scale background up as it comes up if (!cg.iconHUDActive) { cg.iconHUDPercent = (cg.time - cg.iconSelectTime)/ shutdownTime; // Calc how far into opening sequence we are if (cg.iconHUDPercent>1.0f) { cg.iconHUDActive = qtrue; cg.iconHUDPercent=1.0f; } else if (cg.iconHUDPercent<0.0f) { cg.iconHUDPercent=0.0f; } } else { cg.iconHUDPercent=1.0f; } // Print the background if (background) { cgi_R_SetColor( colorTable[CT_WHITE] ); float holdFloat = (float) backgroundHeight; backgroundHeight = (int) (holdFloat*cg.iconHUDPercent); CG_DrawPic( backgroundXPos, backgroundYPos, backgroundWidth, -backgroundHeight, background); // Top half CG_DrawPic( backgroundXPos, backgroundYPos,backgroundWidth, backgroundHeight, background); // Bottom half } if ((cg.inventorySelectTime+WEAPON_SELECT_TIME)>cg.time) { cgs.media.currentBackground = ICON_INVENTORY; } else if ((cg.weaponSelectTime+WEAPON_SELECT_TIME)>cg.time) { cgs.media.currentBackground = ICON_WEAPONS; } else { cgs.media.currentBackground = ICON_FORCE; } } /* ===================== CG_DrawActive Perform all drawing needed to completely fill the screen ===================== */ void CG_DrawActive( stereoFrame_t stereoView ) { float separation; vec3_t baseOrg; // optionally draw the info screen instead if ( !cg.snap ) { CG_DrawInformation(); return; } //FIXME: these globals done once at start of frame for various funcs AngleVectors (cg.refdefViewAngles, vfwd, vright, vup); VectorCopy( vfwd, vfwd_n ); VectorCopy( vright, vright_n ); VectorCopy( vup, vup_n ); VectorNormalize( vfwd_n ); VectorNormalize( vright_n ); VectorNormalize( vup_n ); switch ( stereoView ) { case STEREO_CENTER: separation = 0; break; case STEREO_LEFT: separation = -cg_stereoSeparation.value / 2; break; case STEREO_RIGHT: separation = cg_stereoSeparation.value / 2; break; default: separation = 0; CG_Error( "CG_DrawActive: Undefined stereoView" ); } // clear around the rendered view if sized down CG_TileClear(); // offset vieworg appropriately if we're doing stereo separation VectorCopy( cg.refdef.vieworg, baseOrg ); if ( separation != 0 ) { VectorMA( cg.refdef.vieworg, -separation, cg.refdef.viewaxis[1], cg.refdef.vieworg ); } if ( cg.zoomMode == 3 && cg.snap->ps.batteryCharge ) // doing the Light amp goggles thing { cgi_R_LAGoggles(); } if ( (cg.snap->ps.forcePowersActive&(1<<FP_SEE)) ) { cg.refdef.rdflags |= RDF_ForceSightOn; } cg.refdef.rdflags |= RDF_DRAWSKYBOX; // draw 3D view cgi_R_RenderScene( &cg.refdef ); // restore original viewpoint if running stereo if ( separation != 0 ) { VectorCopy( baseOrg, cg.refdef.vieworg ); } // draw status bar and other floating elements CG_Draw2D(); if (cg.zoomMode) { float scale = 20 - (20 * (cg_zoomFov / 80)); int scale_int = (int)scale; //LOGI("zoom scale %d",scale_int); cgi_ANDROID_SetLookScale(scale_int); } else cgi_ANDROID_SetLookScale(1); }
[ "emile.belanger@gmail.com" ]
emile.belanger@gmail.com
fbd831beee42d7770200615c8c326111f20bb76d
ec8d9b2487efa2b1d8f3a9ca48e85b931fae9c6f
/Arduino/lib/Collections/ArrayList.h
a38bf5ba8b727e6135edd583b1cf697d2d0903bc
[]
no_license
slavasemeniuk/Relays
d9e16b4b0d2ff1aa2a35a18cae37cec7aafd8682
08b60eac2d3205d9b29a34381fd76374cec1d379
refs/heads/master
2021-01-22T20:49:25.452300
2017-10-05T18:57:02
2017-10-05T18:57:02
85,363,979
0
0
null
null
null
null
UTF-8
C++
false
false
3,872
h
#ifndef ArrayList_h #define ArrayList_h #include "List.h" #include "MemoryFree.h"//TODO:@Deprecated template<typename T> class ArrayList : public List<T> { public: ArrayList(); ArrayList(uint16_t initialCapacity); ~ArrayList(); void add(T item); void add(uint16_t index, T item); T set(uint16_t index, T item); T get(uint16_t index); T remove(uint16_t index); void clear(); uint16_t size(); bool isEmpty(); void trimToSize(); //@Deprecated void print(); private: bool rangeCheck(uint16_t index); void ensureCapacity(uint16_t index); void grow(uint16_t minCapacity); uint16_t capacity; uint16_t valuesSize; T* values; static const uint8_t DEFAULT_CAPACITY = 1; }; template< typename T > ArrayList<T>::ArrayList() { values = new T[DEFAULT_CAPACITY]; capacity = DEFAULT_CAPACITY; valuesSize = 0; } template< typename T > ArrayList<T>::ArrayList(uint16_t initialCapacity) { values = new T[initialCapacity]; capacity = initialCapacity; valuesSize = 0; } template< typename T > ArrayList<T>::~ArrayList() { delete[] values; } template< typename T > void ArrayList<T>::add(T item) { ensureCapacity(valuesSize + 1); values[valuesSize++] = item; } template< typename T > void ArrayList<T>::add(uint16_t index, T item) { if (rangeCheck(index == valuesSize ? index - 1 : index)) { ensureCapacity(valuesSize + 1); memmove(&values[index + 1], &values[index], (valuesSize - index) * sizeof(T)); values[index] = item; valuesSize++; } } template< typename T > T ArrayList<T>::set(uint16_t index, T item) { if (rangeCheck(index)) { T oldValue = values[index]; values[index] = item; return oldValue; } else return (T) NULL; } template< typename T > T ArrayList<T>::get(uint16_t index) { if (rangeCheck(index)) { return values[index]; } else return (T) NULL; } template< typename T > T ArrayList<T>::remove(uint16_t index) {//TODO: check if (rangeCheck(index)) { T removed = values[index]; if (index < valuesSize - 1) { memmove(&values[index], &values[index + 1], (valuesSize - index - 1) * sizeof(T));//TODO: check } valuesSize--; return removed; } else return (T) NULL; } template< typename T > void ArrayList<T>::clear() { valuesSize = 0; } template< typename T > uint16_t ArrayList<T>::size() { return valuesSize; } template< typename T > bool ArrayList<T>::isEmpty() { return valuesSize == 0; } template< typename T > void ArrayList<T>::trimToSize() { if (capacity > valuesSize) { values = (T*) realloc(values, valuesSize * sizeof(T)); capacity = valuesSize; } } template< typename T > bool ArrayList<T>::rangeCheck(uint16_t index) { if (index < size()) { return true; } else { Serial.print(F("IndexOutOfBoundsException: Index: ")); Serial.print(index); Serial.print(F(", Size: ")); Serial.println(valuesSize); return false; } } template< typename T > void ArrayList<T>::ensureCapacity(uint16_t minCapacity) { if (capacity < minCapacity) grow(minCapacity); } template< typename T > void ArrayList<T>::grow(uint16_t minCapacity) { if (capacity < minCapacity) { capacity += (capacity >> 1); if (capacity < minCapacity) capacity = minCapacity; values = (T*) realloc(values, capacity * sizeof(T)); } } //@Deprecated template< typename T > void ArrayList<T>::print() { Serial.println(F("-------------------")); // Serial.print(F("RAM: ")); Serial.println(freeMemory()); Serial.print(F("Capacity: ")); Serial.print(capacity); Serial.print(F(" | size = ")); Serial.println(valuesSize); for (uint16_t i = 0; i < valuesSize; i++) { Serial.print(F("@")); Serial.print((uint16_t) &values[i]); //Serial.print(F(" = ")); Serial.print(values[i]); Serial.print(F(", ")); } Serial.println(F("\n-------------------")); } #endif
[ "slavasemeniuk@gmail.com" ]
slavasemeniuk@gmail.com
adef5d2ec738c540c7c15dd2460378e5a53c2871
259329665605d26dd12e3e99896d20a46ff6ae8b
/Capter13/1309.cpp
85a089ef95cf9469a70897c405d7ba68793002d5
[]
no_license
wada811/MeikaiClangNyumon
55cc45ae9411347d6d57d176dab3946db2f17a0f
b68a426a783654ca0a5f5c7b5676321f751dcbc6
refs/heads/master
2021-01-20T11:25:21.724263
2012-02-23T14:18:32
2012-02-23T14:18:32
3,524,224
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
980
cpp
/* 演習13-9:List13-7のプログラムをもとに、すべての英小文字を英大文字に変換しながらコピーするプログラムを作成せよ。 */ #include <stdio.h> #include <ctype.h> int main(void){ int ch; FILE *sfp, *dfp; char sname[64], dname[64]; printf("コピー元ファイル名:"); scanf("%s", sname); printf("コピー先ファイル名:"); scanf("%s", dname); if((sfp = fopen(sname, "r")) == NULL ){ printf("\aコピー元ファイルをオープンできません。\n"); }else{ if((dfp = fopen(dname, "w")) == NULL){ printf("\aコピー先ファイルをオープンできません。\n"); }else{ while((ch = fgetc(sfp)) != EOF){ ch = toupper(ch); fputc(ch, dfp); } fclose(dfp); } fclose(sfp); } return 0; }
[ "89.at.usi@gmail.com" ]
89.at.usi@gmail.com
42a28e2524374784c06010ba028e486ab2d36fc7
3dbdf3cf83418d139f14ad0d82df996477434114
/MyTetris/Figure.cpp
e22b65f956f4d6bff3dba9b38585a374162eab30
[]
no_license
Sergey978/MyTetris
2f536605c4b36eb6ff66709f8f6ea4c55f06502a
716cbacf25a140171d30ef80d914f5b7d9b47ae8
refs/heads/master
2020-03-25T23:41:15.434717
2018-08-10T13:13:27
2018-08-10T13:13:27
140,558,330
0
0
null
null
null
null
UTF-8
C++
false
false
1,862
cpp
#include "Figure.h" #include "CoordMask.h" #include<array> Figure::Figure(Coord metaPointCoords) { this->metaPointCoord = metaPointCoords; this->currentRotation = RotationMode::NORMAL; this->form = FigureForm::getRandomForm(); } Figure::Figure(Coord metaPointCoords, RotationMode::Mode rotation, FigureForm::Form form) { this->metaPointCoord = metaPointCoords; this->currentRotation = rotation; this->form = form; } std::array<Coord, Constants::MAX_FIGURE_WIDTH> Figure::getCoords() { return CoordMask::generateFigure(metaPointCoord, currentRotation , form); } std::array<Coord, Constants::MAX_FIGURE_WIDTH> Figure::getRotatedCoords() { return CoordMask::generateFigure(metaPointCoord, RotationMode::getNextRotationFrom(currentRotation), form); } void Figure::rotate() { currentRotation = RotationMode::getNextRotationFrom(currentRotation); } std::array<Coord, Constants::MAX_FIGURE_WIDTH> Figure::getShiftedCoords(ShiftDirection direction) { Coord newFirstCell ; switch (direction) { case LEFT: newFirstCell = Coord(metaPointCoord.x - 1, metaPointCoord.y); break; case RIGHT: newFirstCell = Coord(metaPointCoord.x + 1, metaPointCoord.y); break; } return CoordMask::generateFigure(newFirstCell, currentRotation, form); } void Figure::shift(ShiftDirection direction) { switch (direction) { case LEFT: metaPointCoord.x--; break; case RIGHT: metaPointCoord.x++; break; } } std::array<Coord, Constants::MAX_FIGURE_WIDTH> Figure::getFallenCoords() { Coord newFirstCell = Coord(metaPointCoord.x, metaPointCoord.y - 1); return CoordMask::generateFigure(newFirstCell, currentRotation, form); } void Figure::fall() { metaPointCoord.y--; } Figure::~Figure() { }
[ "Sergey@service1" ]
Sergey@service1
981199026e15a560a16bf3e389ca8e6f4f783bd0
befd896d301d3040fbd6ccda39aa217bf388a0a4
/tensorflow/core/kernels/quantize_and_dequantize_op.h
6b0c5e5a466baf60a771d7aa7754975a0c121138
[ "Apache-2.0" ]
permissive
mktshhr/tensorflow-theta
98369caf55f676c6ae9a5c82ab151bb53d395f36
fe378e1b690d97ed24bad144dee9efffce893c86
refs/heads/master
2020-03-26T14:29:34.200902
2018-10-21T13:39:56
2018-10-21T13:39:56
144,990,240
5
2
Apache-2.0
2018-10-21T13:39:57
2018-08-16T13:17:25
C++
UTF-8
C++
false
false
4,592
h
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_KERNELS_QUANTIZE_AND_DEQUANTIZE_OP_H_ #define TENSORFLOW_CORE_KERNELS_QUANTIZE_AND_DEQUANTIZE_OP_H_ #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/kernels/cwise_ops.h" namespace tensorflow { namespace functor { // TODO(pauldonnelly): 'signed_input' should really be called 'signed_output'. template <typename Device, typename T> struct QuantizeAndDequantizeOneScaleFunctor { void operator()(const Device& d, typename TTypes<T>::ConstVec input, bool signed_input, int num_bits, bool range_given, Tensor* input_min_tensor, Tensor* input_max_tensor, typename TTypes<T>::Vec out); }; // The implementation below runs on both CPU and GPU. template <typename Device, typename T> struct QuantizeAndDequantizeOneScaleImpl { static void Compute(const Device& d, typename TTypes<T>::ConstVec input, bool signed_input, int num_bits, bool range_given, Tensor* input_min_tensor, Tensor* input_max_tensor, typename TTypes<T>::Vec out) { T min_range; T max_range; auto input_min = input_min_tensor->scalar<T>(); auto input_max = input_max_tensor->scalar<T>(); if (!range_given) { input_min.device(d) = input.minimum(); input_max.device(d) = input.maximum(); d.memcpyDeviceToHost(&min_range, input_min.data(), sizeof(T)); d.memcpyDeviceToHost(&max_range, input_max.data(), sizeof(T)); } else { // Copy the range values from their respective tensors on the host. min_range = input_min_tensor->scalar<T>()(); max_range = input_max_tensor->scalar<T>()(); } // Calculate the range for the simulated integer quantization: // e.g. [-128,127] for signed = true, num_bits = 8, // or [0, 255] for signed = false, num_bits = 8. const int64 min_quantized = signed_input ? -(1ULL << (num_bits - 1)) : 0; const int64 max_quantized = min_quantized + ((1ULL << num_bits) - 1); // Determine the maximum scaling factor that would scale // [min_range, max_range] to not exceed [min_quantized, max_quantized], // while keeping 0 unchanged. const T scale_from_min_side = (min_quantized * min_range > 0) ? min_quantized / min_range : std::numeric_limits<T>::max(); const T scale_from_max_side = (max_quantized * max_range > 0) ? max_quantized / max_range : std::numeric_limits<T>::max(); // Note: Avoids changing the side of the range that determines scale. T scale, inverse_scale; if (scale_from_min_side < scale_from_max_side) { scale = scale_from_min_side; inverse_scale = min_range / min_quantized; max_range = max_quantized * inverse_scale; } else { scale = scale_from_max_side; inverse_scale = max_range / max_quantized; min_range = min_quantized * inverse_scale; } if (range_given) { // Note: The clamping here is to avoid overflow in the quantized type. // The semantics of the op does not guarantee to clamp to the specified // min_range and max_range - because we may have changed either min_range // or max_range. out.device(d) = (input.cwiseMin(max_range).cwiseMax(min_range) * scale) .unaryExpr(Eigen::internal::scalar_round_op_google<T>()) * inverse_scale; } else { out.device(d) = (input * scale) .unaryExpr(Eigen::internal::scalar_round_op_google<T>()) * inverse_scale; } } }; } // end of namespace functor } // end of namespace tensorflow #endif // TENSORFLOW_CORE_KERNELS_QUANTIZE_AND_DEQUANTIZE_OP_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
36ecb1fc3a8d0e0f28c7ac69195152001d0d5eb6
cf703624da441b080d3fb3025ea2cd28223bd5ee
/RoboticCommunications/Pkt_Def.cpp
a66de16e91b5c7247d719a78475fc190d6e5455d
[ "MIT" ]
permissive
gponimansky/fictional-robot
d0b309f05c7d05694a467bdd5fa45880e4f66468
d15131d10f0fe84487058e1d4cf27a653297c4d2
refs/heads/master
2021-05-11T09:02:02.428093
2018-02-24T01:47:05
2018-02-24T01:47:05
118,067,833
1
0
null
null
null
null
UTF-8
C++
false
false
5,991
cpp
#include "Pkt_Def.h" // A default constructor that places the PktDef object in a safe state PktDef::PktDef() { // Set all Header information set to zero packet.header.PktCount = 0; packet.header.Drive = 0; packet.header.Status = 0; packet.header.Sleep = 0; packet.header.Arm = 0; packet.header.Claw = 0; packet.header.Ack = 0; packet.header.Padding = 0; packet.header.Length = HEADERSIZE + sizeof(char); // Set data pointer to nullptr packet.data = nullptr; // CRC set to zero packet.CRC = 0; } // An overloaded constructor that takes a RAW data buffer PktDef::PktDef(char * dataBuffer) { // Populate PktCount and Command Flags int * ptrInt = (int *)&dataBuffer[0]; packet.header.PktCount = *ptrInt++; packet.header.Drive = (char)(*ptrInt) & 0x01; packet.header.Status = (char)(*ptrInt >> 1) & 0x01; packet.header.Sleep = (char)(*ptrInt >> 2) & 0x01; packet.header.Arm = (char)(*ptrInt >> 3) & 0x01; packet.header.Claw = (char)(*ptrInt >> 4) & 0x01; packet.header.Ack = (char)(*ptrInt >> 5) & 0x01; packet.header.Padding = 0; // Populate length in Header char * ptrChar = &dataBuffer[5]; packet.header.Length = (*ptrChar++); // Populate the packet bodydata packet.data = new char[packet.header.Length - HEADERSIZE - sizeof(char)]; for (int i = 0; i < packet.header.Length - HEADERSIZE - sizeof(char); i++) packet.data[i] = *ptrChar++; // Populate the CRC packet.CRC = (*ptrChar); } // A set function that sets the packets command flag based on the CmdType void PktDef::SetCmd(CmdType ct) { switch (ct) { case DRIVE: packet.header.Drive = 1; packet.header.Status = 0; packet.header.Sleep = 0; packet.header.Arm = 0; packet.header.Claw = 0; packet.header.Ack = 0; break; case STATUS: packet.header.Status = 1; break; case SLEEP: packet.header.Drive = 0; packet.header.Status = 0; packet.header.Sleep = 1; packet.header.Arm = 0; packet.header.Claw = 0; packet.header.Ack = 0; delete packet.data; packet.data = nullptr; packet.header.Length = HEADERSIZE + sizeof(char); break; case ARM: packet.header.Drive = 0; packet.header.Status = 0; packet.header.Sleep = 0; packet.header.Arm = 1; packet.header.Claw = 0; packet.header.Ack = 0; break; case CLAW: packet.header.Drive = 0; packet.header.Status = 0; packet.header.Sleep = 0; packet.header.Arm = 0; packet.header.Claw = 1; packet.header.Ack = 0; break; case ACK: packet.header.Ack = 1; break; } } // A set function that takes a pointer to a RAW data buffer and the size of the buffer in bytes. void PktDef::SetBodyData(char * data, int size) { // Set the new packet length with body data packet.header.Length = HEADERSIZE + size + sizeof(char); // Allocate amount of space for data packet.data = new char[size]; // Copies the provided data for (int i = 0; i < size; i++) packet.data[i] = *data++; } // Set function that sets the objects PktCount header variable void PktDef::SetPktCount(int pc) { packet.header.PktCount = pc; } // A query function that returns the CmdType based on the set command flag bit CmdType PktDef::GetCmd() { if (packet.header.Drive & 0x01) return DRIVE; else if (packet.header.Status & 0x01) return STATUS; else if (packet.header.Sleep & 0x01) return SLEEP; else if (packet.header.Arm & 0x01) return ARM; else if (packet.header.Claw & 0x01) return CLAW; else if (packet.header.Ack & 0x01) return ACK; else return EMPTY; } // A query function that returns True / False based on the Ack flag in the header bool PktDef::GetAck() { return packet.header.Ack; } // A query function that returns the packet length in bytes int PktDef::GetLength() { return packet.header.Length; } // A query function that returns a pointer to the objects Body field char * PktDef::GetBodyData() { return packet.data; } // A query function that returns the PktCount value int PktDef::GetPktCount() { return packet.header.PktCount; } /* A function that takes a pointer to a RAW data buffer, the size of the buffer in bytes, and calculates the CRC.If the calculated CRC matches the CRC of the packet in the buffer the function returns TRUE, otherwise FALSE. */ bool PktDef::CheckCRC(char * data, int size) { // Set count variable int count = 0; // Count the CRC of data for (int i = 0; i < size - sizeof(char); i++) for (int j = 0; j < 8; j++) count += ((data[i] >> j) & 0x01); // Compare the CRC of the data to the counted CRC return (count == data[size - sizeof(char)]) ? true : false; } // A function that calculates the CRC and sets the objects packet CRC parameter void PktDef::CalcCRC() { // Set count variable int count = 0; // Count the Header char * ptr = (char*)&packet.header; for (int i = 0; i < HEADERSIZE; i++) for (int j = 0; j < 8; j++) count += ((ptr[i] >> j) & 0x01); // If body data isn't empty if (packet.data != nullptr) { // Count the body data ptr = packet.data; for (int i = 0; i < (packet.header.Length - HEADERSIZE - sizeof(char)); i++) for (int j = 0; j < 8; j++) count += ((ptr[i] >> j) & 0x01); } // Set the CRC count packet.CRC = count; } /* A function that allocates the private RawBuffer and transfers the contents from the objects member variables into a RAW data packet (RawBuffer) for transmission. The address of the allocated RawBuffer is returned. */ char * PktDef::GenPacket() { // Allocate the RawBuffer RawBuffer = new char[packet.header.Length]; // Transfer header data into RawBuffer char * ptr = (char*)&packet.header; for (int i = 0; i < HEADERSIZE; i++) RawBuffer[i] = ptr[i]; // If body data isn't empty if (packet.data != nullptr) { // Transfer body data into RawBuffer ptr = (char*)packet.data; for (int i = 0; i < (packet.header.Length - HEADERSIZE - sizeof(char)); i++) RawBuffer[HEADERSIZE + i] = ptr[i]; } // Transfer the CRC into RawBuffer RawBuffer[packet.header.Length - sizeof(char)] = packet.CRC; // Return RawBuffer return RawBuffer; }
[ "ponimansky.guy@gmail.com" ]
ponimansky.guy@gmail.com
8b4ce849f5c89f421530ae790381948e582e5df1
5740ea2c2d9d5fb5626ff5ad651f3789048ae86b
/Extensions/LightningShaders/LightningShaderIRTranslationPass.hpp
f9f9e222ecebd06b50846cf2078f0694be1c2f3e
[ "MIT" ]
permissive
donovan680/Plasma
4945b92b7c6e642a557f12e05c7d53819186de55
51d40ef0669b7a3015f95e3c84c6d639d5469b62
refs/heads/master
2022-04-15T02:42:26.469268
2020-02-26T22:32:12
2020-02-26T22:32:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,213
hpp
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2018, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once struct spv_diagnostic_t; typedef spv_diagnostic_t* spv_diagnostic; struct spv_optimizer_options_t; typedef spv_optimizer_options_t* spv_optimizer_options; namespace Plasma { //-------------------------------------------------------------------ShaderTranslationPassResult class ShaderTranslationPassResult { public: String ToString() { return mByteStream.ToString(); } ShaderByteStream mByteStream; ShaderStageInterfaceReflection mReflectionData; LightningRefLink(ShaderTranslationPassResult); }; //-------------------------------------------------------------------LightningShaderIRTranslationPass class LightningShaderIRTranslationPass : public Lightning::EventHandler { public: virtual ~LightningShaderIRTranslationPass() {}; /// Runs a translation pass that transforms the input data into the output data. /// This pass could be something like a tool (e.g. the optimizer) or a backend. /// Reflection data will be filled out that describes what transformations took place on the /// input data to produce the output data. Most tools will not change the reflection mapping /// (other than removing bindings) but backends may have to do significant transformations. virtual bool RunTranslationPass(ShaderTranslationPassResult& inputData, ShaderTranslationPassResult& outputData) = 0; virtual String GetErrorLog() { return String(); } LightningRefLink(LightningShaderIRTranslationPass); protected: /// Internal helper that converts a spirv diagnostic object into a string. String SpirvDiagnosticToString(spv_diagnostic& diagnostic); }; //-------------------------------------------------------------------LightningShaderIRBackend class LightningShaderIRBackend : public LightningShaderIRTranslationPass { public: /// Return an extension for the given backend. Mostly used for unit /// testing so that a backend can be written to a file. virtual String GetExtension() = 0; }; }//namespace Plasma
[ "dragonCASTjosh@gmail.com" ]
dragonCASTjosh@gmail.com
83128928acea7de0941491cd521b5ae5ea6d7506
57370e163d07ceee075decd8bc25c8925a1262a7
/test/repeat_test.cpp
cffbc06a972203e6030e05c1f0488ff96ae1d8b5
[]
no_license
Infinoid/halide-sar-app
e195834ca694758b8a45f7a58b398d2c80ef20f6
65eec21ba534d0e4a36b98e79d0ec3e4cc520e84
refs/heads/master
2023-04-11T12:42:05.128153
2021-01-29T16:16:24
2021-01-29T16:16:24
304,348,129
0
0
null
null
null
null
UTF-8
C++
false
false
969
cpp
#include <stdio.h> #include <Halide.h> #include "repeat1.h" #include "test.h" using namespace std; using Halide::Runtime::Buffer; #define INPUT_NUM 10 #define REPEAT 2.5 #define OUTPUT_NUM (size_t)(INPUT_NUM * REPEAT) static void reference(float *ref) { for (size_t i = 0; i < OUTPUT_NUM; i++) { ref[i] = i % INPUT_NUM; } } int main(int argc, char **argv) { float in[INPUT_NUM]; for (size_t i = 0; i < INPUT_NUM; i++) { in[i] = i; } Buffer<float, 1> in_buf(in, INPUT_NUM); float ref[OUTPUT_NUM] = { 0 }; Buffer<float, 1> out(OUTPUT_NUM); int rv = repeat1(in_buf, out); if (!rv) { print_1d(out); reference(ref); float *obuf = out.begin(); for (size_t i = 0; i < OUTPUT_NUM; i++) { if (abs(ref[i] - obuf[i]) >= 0.1f) { cerr << "Verification failed at index " << i << endl; return -1; } } } return rv; }
[ "cimes@isi.edu" ]
cimes@isi.edu
0c73090def61de4dd6efdbcbe2b8adbb3654238d
f6607972b5a6f3eac63d350c2cee89ac87c2d45e
/Round.cpp
fe3ad22bb2589130ebca0e1464b0574e63c1b67f
[]
no_license
redwoudt/CrimeTime
c2adec108409b2eb74b0ffeb96b2a12673a5ecbd
cc6bab6b037d0e39d60872029261af46d02fda42
refs/heads/master
2021-01-10T05:05:23.899128
2015-09-25T09:10:02
2015-09-25T09:10:02
43,125,372
0
0
null
null
null
null
UTF-8
C++
false
false
179
cpp
// // Round.cpp // BytePlay // // Created by Redelinghuys, Ferdinand on 08/07/2015. // Copyright (c) 2015 Redelinghuys, Ferdinand. All rights reserved. // #include "Round.h"
[ "fcredelinghuys@gmail.com" ]
fcredelinghuys@gmail.com
9474d4c4cbea4e848c752d033b59575fa1ac5ca5
703ec46ee5493dcd169e8100d0cfd3555c719144
/d3d12/LabProjects/LabProject03-1/Scene.cpp
275dfb2ee0755559ad95f4fc7bfdbe0a49aada64
[]
no_license
kimduuukbae/Today-I-Learned
e8ca001c815fc7fb02a738bc3eb564e89791bb6a
496a3603f65bedfba83d1a9f2f2fd83b4d0c0269
refs/heads/master
2022-08-07T03:52:46.875576
2022-08-01T05:45:55
2022-08-01T05:45:55
214,361,320
4
0
null
null
null
null
UTF-8
C++
false
false
2,799
cpp
#include "stdafx.h" #include "Scene.h" #include "Shader.h" CScene::CScene() {} CScene::~CScene() {} void CScene::BuildObjects(const ComPtr<ID3D12Device>& device, ID3D12GraphicsCommandList* commandList) { m_pd3dGraphicsRootSignature = CreateGraphicsRootSignature(device.Get()); shaderCount = 1; shaders = new CShader * [shaderCount]; CShader* pShader{ new CShader{} }; pShader->CreateShader(device.Get(), m_pd3dGraphicsRootSignature.Get()); pShader->BuildObjects(device.Get(), commandList); shaders[0] = pShader; } void CScene::ReleaseObjects() { if (m_pd3dGraphicsRootSignature) m_pd3dGraphicsRootSignature->Release(); if (shaders) { for (int i = 0; i < shaderCount; ++i) { shaders[i]->ReleaseShaderVariables(); shaders[i]->ReleaseObjects(); shaders[i]->Release(); } delete[] shaders; } } bool CScene::ProcessInput(){ return false; } void CScene::AnimateObjects(float fTimeElapsed){ for (int i = 0; i < shaderCount; ++i) shaders[i]->AnimateObjects(fTimeElapsed); } void CScene::Render(const ComPtr<ID3D12GraphicsCommandList>& pd3dCommandList){ pd3dCommandList->SetGraphicsRootSignature(m_pd3dGraphicsRootSignature.Get()); for (int i = 0; i < shaderCount; ++i) shaders[i]->Render(pd3dCommandList.Get()); //pd3dCommandList->SetPipelineState(m_pd3dPipelineState.Get()); //pd3dCommandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); //pd3dCommandList->DrawInstanced(3, 1, 0, 0); } ID3D12RootSignature* CScene::CreateGraphicsRootSignature(ID3D12Device* device){ ID3D12RootSignature* rootSignature{ nullptr }; D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc{}; rootSignatureDesc.NumParameters = 0; rootSignatureDesc.pParameters = nullptr; rootSignatureDesc.NumStaticSamplers = 0; rootSignatureDesc.pStaticSamplers = nullptr; rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; ID3DBlob* signatureBlob{ nullptr }; ID3DBlob* errorBlob{ nullptr }; D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signatureBlob, &errorBlob); device->CreateRootSignature(0, signatureBlob->GetBufferPointer(), signatureBlob->GetBufferSize(), IID_PPV_ARGS(&rootSignature)); if (signatureBlob) signatureBlob->Release(); if (errorBlob) errorBlob->Release(); return rootSignature; } ID3D12RootSignature* CScene::GetGraphicsRootSignature(){ return m_pd3dGraphicsRootSignature.Get(); } void CScene::ReleaseUploadBuffers(){ if (shaders) { for (int i = 0; i < shaderCount; ++i) { if (shaders[i]) shaders[i]->ReleaseUploadBuffers(); } } } bool CScene::OnProcessingMouseMessage(HWND hWnd, UINT nMessageID, WPARAM wParam, LPARAM lParam) { return false; } bool CScene::OnProcessingKeyboardMessage(HWND hWnd, UINT nMessageID, WPARAM wParam, LPARAM lParam) { return false; }
[ "qlccksdlf@gmail.com" ]
qlccksdlf@gmail.com
87397ec3977948bfddc36171d974cc3ea12ac354
fd5178b83eb0cfc7ce205220c3d80b2d25bec656
/headers/FGTrain.h
869b1a645ecca2d1ab2f96ed4394d72f5123e515
[]
no_license
ficsit/community-resources
e2d916ed3709562318369c81f7e70645ce005326
974089a84046b524ed5e2d19de4c09e8230ac7bf
refs/heads/master
2021-01-04T15:50:29.879718
2020-03-11T17:02:14
2020-03-11T17:02:14
240,621,430
0
0
null
null
null
null
UTF-8
C++
false
false
17,549
h
// Copyright 2016-2019 Coffee Stain Studios. All Rights Reserved. #pragma once #include "GameFramework/Actor.h" #include "FGSaveInterface.h" #include "FGSignificanceInterface.h" #include "RailroadNavigation.h" #include "FGTrain.generated.h" class UFGRailroadTrackConnectionComponent; /** * Error codes for the self driving locomotives. */ UENUM( BlueprintType ) enum class ESelfDrivingLocomotiveError : uint8 { SDLE_NoError UMETA( DisplayName = "No Error" ), SDLE_NoPower UMETA( DisplayName = "No Power" ), SDLE_NoTimeTable UMETA( DisplayName = "No Time Table" ), SDLE_InvalidNextStop UMETA( DisplayName = "Invalid Next Stop" ), SDLE_InvalidLocomotivePlacement UMETA( DisplayName = "Invalid Locomotive Placement" ), SDLE_NoPath UMETA( DisplayName = "No Path" ) }; /** * Signal aspects used for signaling and ATC points. */ UENUM( BlueprintType ) enum class ERailroadSignalAspect : uint8 { RSA_None UMETA( DisplayName = "None" ), RSA_Clear UMETA( DisplayName = "Clear" ), RSA_ClearThenStop UMETA( DisplayName = "Clear Then Stop" ), RSA_Stop UMETA( DisplayName = "Stop" ), RSA_Dock UMETA( DisplayName = "Dock" ) }; /** * Docked state. */ UENUM( BlueprintType ) enum class ETrainDockingState : uint8 { TDS_None UMETA( DisplayName = "None" ), TDS_ReadyToDock UMETA( DisplayName = "Ready To Dock" ), TDS_Docked UMETA( DisplayName = "Docked" ) }; /** Global constants for trains. */ struct TrainConstants { // At which distance can a station start catching the train. [cm] static float CATCH_DISTANCE; // At which offset should a locomotive stop at a signal or station. [cm] static float STOP_OFFSET; // At which distance a locomotive can dock to a station. [cm] static float DOCK_DISTANCE; // At which speed is docking allowed. [cm/s] static float DOCK_SPEED; // This is the speed on a restricted section, e.g. before docking. [cm/s] static float RESTRICTED_SPEED; }; /** * Describes the static properties of a train consist. * I.e. the locomotives, railcars, length and tare weight. */ USTRUCT( BlueprintType ) struct FTrainConsist { GENERATED_BODY() public: /** The vehicles in this consist. */ UPROPERTY( BlueprintReadOnly ) TArray< TSubclassOf< AFGRailroadVehicle > > Vehicles; //@todotrains Orientations. //@todotrains Fill percentages. /** Length of the consist, [cm] */ UPROPERTY( BlueprintReadOnly ) float Length = 0.f; /** Mass of the consist, [kg] */ UPROPERTY( BlueprintReadOnly ) float Mass = 0.f; /** Maximum speed for the slowest vehicle in the consist. [cm/s] */ UPROPERTY( BlueprintReadOnly ) float MaxSpeed = 0.f; /** The sustained braking force the consist can apply in it's operational speed range. [N] [kg cm/s^2] */ float MaxAirBrakingEffort = 0.f; float HighSpeedDynamicBrakingEffort = 0.f; float LimitedSpeedDynamicBrakingEffort = 0.f; float MaxTractiveEffort = 0.f; }; USTRUCT( BlueprintType ) struct FTrainAtcPoint { GENERATED_BODY() public: /** The track connection. */ UPROPERTY() UFGRailroadTrackConnectionComponent* TrackConnection = nullptr; /** How far away is this point in whole segments. */ float LongDistance = 0.f; /** How far away is this point. */ float Distance = 0.f; /** How high up is this. */ float AverageGrade = 0.f; /** The speed the train should have when passing this point. No limit if 0. */ float SpeedLimit = 0.f; /** Signal output at this point. If any. */ ERailroadSignalAspect SignalAspect = ERailroadSignalAspect::RSA_None; }; /** * Data for the automatic train control system. * For the AI to make the correct decisions. * As a safety/guidance system for when the player is driving. */ USTRUCT( BlueprintType ) struct FTrainAtcData { GENERATED_BODY() public: /** Functions to help manage the path. */ bool SetPath( const FRailroadPathFindingResult& result ); void ClearPath(); bool HasPath() const; /** Update the target points ahead from the current connection. */ void UpdateTargetPoints( UFGRailroadTrackConnectionComponent* current ); /** Function to update which path segment we're on based on what our current connection is up ahead. */ bool UpdateCurrentPathSegment( UFGRailroadTrackConnectionComponent* current ); /** If a connection is relevant for controlling the train. */ static bool IsRelevantForATC( const UFGRailroadTrackConnectionComponent* connection ); public: /** The route this train should follow. */ FRailroadPathSharedPtr Path; /** Index of the next point along the route. */ int32 CurrentPathSegment = INDEX_NONE; /** The next connection up ahead. */ TWeakObjectPtr< UFGRailroadTrackConnectionComponent > CurrentConnection = nullptr; float CurrentConnectionDistance = 0.f; /** * Connection points ahead we'll pass on our way forward and the distance to them. * Does not contain a point that is only a pass-through (not relevant). * Index 0 may not be the same as NextConnection. */ TArray< FTrainAtcPoint > TargetPoints; /** Speed and distance indicators. */ float CurrentSpeed = 0.f; float TargetSpeed = 0.f; /** * Next upcoming signal. * A signal in this context is something that announces a change in speed, e.g. a station we should dock to. * This is not necessarily the first signal that appears in target points but rather the most restricting for our speed. */ TWeakObjectPtr< UFGRailroadTrackConnectionComponent > NextSignalConnection = nullptr; float NextSignalSpeed = 0.f; float NextSignalDistance = 0.f; float NextSignalGrade = 0.f; // [%] ERailroadSignalAspect NextSignalAspect = ERailroadSignalAspect::RSA_None; /** If >= 0 we want to be catched at that distance. */ float CatchAtSignalDistance = -1.f; }; /** * States for self driving locomotives. */ UENUM() enum class ESelfDrivingLocomotiveState : uint8 { SDLS_Idle, SDLS_FollowPath, SDLS_Docking, SDLS_DockingCompleted, }; /** * Realtime data for the ai. */ USTRUCT() struct FTrainSelfDrivingData { GENERATED_BODY() public: /** The state the ai is in, determines which functions to run. */ ESelfDrivingLocomotiveState State = ESelfDrivingLocomotiveState::SDLS_Idle; /** Next stop we're aiming for, also look at the current stop in the time table, this is updated from there. */ int32 NextStop = INDEX_NONE; // Enabled // Last error /** When did we find this path. */ float TimeOfLastFindPath = 0.0f; /** If the last speed was up or down or none. */ int8 LastSpeedControl = 0; }; /** * The physics simulation data for the trains. */ USTRUCT() struct FTrainSimulationData { GENERATED_BODY() public: /** Is this train simulating physics and not just moving along the track. */ bool IsSimulatingPhysics = false; /** Cached vehicles in the direction of travel. */ UPROPERTY() TArray< class AFGRailroadVehicle* > SimulatedVehicles; /** Cached movements in the same order as the vehicles. */ UPROPERTY() TArray< class UFGRailroadVehicleMovementComponent* > SimulatedMovements; /** If we're simulating the train front to back (1) or back to front (-1). */ float SimulationDirection = 0.f; /** Cached master locomotive. */ UPROPERTY() class UFGLocomotiveMovementComponent* MasterMovement = nullptr; // Real-time measurements from the simulation. float GravitationalForce = 0.f; float TractiveForce = 0.f; float GradientForce = 0.f; float ResistiveForce = 0.f; float BrakingForce = 0.f; // Velocity of this train [directional] [cm/s] UPROPERTY( SaveGame ) float Velocity = 0.f; }; // Delegates for blueprint DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam( FIsSelfDrivingDelegate, bool, enabled ); DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam( FDockingStateDelegate, ETrainDockingState, state ); /** * The AFGTrain class is concept of multiple rolling stock that is connected in series and move together as one unit. * It's responsible for functionality that does not apply to the individual locomotives or rail car. * This functionality includes but are not limited to: * * Time tables, there can only be one time table for the train. * Simulation, the physics simulation is per train, the cars are just following the first vehicle. * ATC, the automatic train control system */ UCLASS( NotBlueprintable, notplaceable ) class FACTORYGAME_API AFGTrain : public AActor, public IFGSaveInterface, public IFGSignificanceInterface { GENERATED_BODY() public: AFGTrain(); // Begin AActor Interface virtual void GetLifetimeReplicatedProps( TArray< FLifetimeProperty >& OutLifetimeProps ) const override; virtual void Tick( float DeltaSeconds ); virtual void BeginPlay() override; virtual void Destroyed() override; virtual void EndPlay( const EEndPlayReason::Type EndPlayReason ) override; virtual bool IsLevelBoundsRelevant() const override; // End AActor Interface // Begin IFGSaveInterface virtual void PreSaveGame_Implementation( int32 saveVersion, int32 gameVersion ) override; virtual void PostSaveGame_Implementation( int32 saveVersion, int32 gameVersion ) override; virtual void PreLoadGame_Implementation( int32 saveVersion, int32 gameVersion ) override; virtual void PostLoadGame_Implementation( int32 saveVersion, int32 gameVersion ) override; virtual void GatherDependencies_Implementation( TArray< UObject* >& out_dependentObjects ) override; virtual bool NeedTransform_Implementation() override; virtual bool ShouldSave_Implementation() const override; // End IFSaveInterface //@todotrains Put stat counters in these. void TickAtc( float dt ); void TickSelfDriving( float dt ); // Begin IFGSignificanceInterface virtual void GainedSignificance_Implementation() override; virtual void LostSignificance_Implementation() override; virtual void GainedSignificance_Native() override; virtual void LostSignificance_Native() override; virtual float GetSignificanceRange() override; // Significance helpers FORCEINLINE bool IsSignificant() const { return mIsSignificant; } FVector GetSignificanceLocation() const { return mSignificanceLocation; } float GetSignificanceRadius() const { return mSignificanceRadius; } // End IFGSignificanceInterface /** Get the name of this train. */ UFUNCTION( BlueprintPure, Category = "FactoryGame|Railroad|Train" ) FText GetTrainName() const { return mTrainName; } /** Get the name of this train, must be called on server. */ UFUNCTION( BlueprintCallable, Category = "FactoryGame|Railroad|Train" ) void SetTrainName( const FText& name ); /** Get the track for this train. */ UFUNCTION( BlueprintPure, Category = "FactoryGame|Railroad|Train" ) int32 GetTrackGraphID() const { return mTrackGraphID; } /** Is this train driven by a player. */ bool IsPlayerDriven() const; /** @return true if the train has the autopilot enabled. */ UFUNCTION( BlueprintPure, Category = "FactoryGame|Railroad|SelfDriving" ) bool IsSelfDrivingEnabled() const; /** Enable/disable the autopilot on a train, does nothing if enabled/disabled twice, must be called server. */ UFUNCTION( BlueprintCallable, Category = "FactoryGame|Railroad|SelfDriving" ) void SetSelfDrivingEnabled( bool isEnabled ); /** Get the self driving error for this locomotive. */ UFUNCTION( BlueprintPure, Category = "FactoryGame|Railroad|SelfDriving" ) ESelfDrivingLocomotiveError GetSelfDrivingError() const { return mSelfDrivingError; } /** @return The master locomotive in the train; nullptr if MU is disabled. */ class AFGLocomotive* GetMultipleUnitMaster() const; /** @return true if we can set the multiple unit master to be the given locomotive without forcing; false if we cannot. */ bool CanSetMultipleUnitMaster( const class AFGLocomotive* locomotive ) const; /** * Set the new master locomotive in the train. * @param trainID The trains ID, if invalid this function does nothing. * @param locomotive The new master or nullptr to disable MU. * @param if true the new master is forced; if false the new master will only be set if MU is disabled (current master is nullptr). * @return true a new master was set or forced; false if not set. */ bool SetMultipleUnitMaster( class AFGLocomotive* locomotive, bool force ); /** @return true if input is blocked, e.g. we're docked or self driving is enabled. */ UFUNCTION( BlueprintPure, Category = "FactoryGame|Railroad|SelfDriving" ) bool IsInputDisabled() const; /** Get the time table for this train. */ UFUNCTION( BlueprintCallable, BlueprintPure = false, Category = "FactoryGame|Railroad|Train" ) class AFGRailroadTimeTable* GetTimeTable() const; /** Create a new time table for this train. */ UFUNCTION( BlueprintCallable, Category = "FactoryGame|Railroad|Train" ) class AFGRailroadTimeTable* NewTimeTable(); /** If this train has a valid time table. */ UFUNCTION( BlueprintPure, Category = "FactoryGame|Railroad|Train" ) bool HasTimeTable() const; /** Get the first vehicle in the consist. */ UFUNCTION( BlueprintPure, Category = "FactoryGame|Railroad|Train" ) class AFGRailroadVehicle* GetFirstVehicle() const; /** Get the last vehicle in the consist. */ UFUNCTION( BlueprintPure, Category = "FactoryGame|Railroad|Train" ) class AFGRailroadVehicle* GetLastVehicle() const; /** Dock this train to the station we're at, must be called on the server. */ UFUNCTION( BlueprintCallable, Category = "FactoryGame|Railroad|Train" ) void Dock(); /** Get the current status on the docking. */ UFUNCTION( BlueprintPure, Category = "FactoryGame|Railroad|Train" ) ETrainDockingState GetDockingState() const { return mDockingState; } /** If this train has docked at a station. */ UFUNCTION( BlueprintPure, Category = "FactoryGame|Railroad|Train" ) bool IsDocked() const { return mDockingState == ETrainDockingState::TDS_Docked; } /** Callbacks from the station with regards to docking. */ void OnDocked( AFGBuildableRailroadStation* station ); void OnDockingComplete(); /** Called when the train consist changes so constants can be recalculated. */ void OnConsistChanged(); private: void ReportSelfDrivingError( ESelfDrivingLocomotiveError error ); void ClearSelfDrivingError(); /** Try to find a path for this train, in any direction. */ bool FindPath( class AFGBuildableRailroadStation* station ); /** Called to set the current docking state. */ void SetDockingState( ETrainDockingState state ); /** Called to toggle state for next tick. */ void GotoSelfDrivingState( ESelfDrivingLocomotiveState newState ); /** Self driving state handlers. */ void TickSelfDriving_Idle(); void TickSelfDriving_FollowPath(); void TickSelfDriving_Docking(); void TickSelfDriving_DockingCompleted(); /** Help functions for speed related calculations. */ float CalcBrakeDistance( float currentSpeed, float targetSpeed, float deceleration ) const; float CalcTargetSpeed( float targetSpeed, float distance, float deceleration ) const; float CalcTargetAcceleration( float currentSpeed, float targetSpeed, float distance ) const; float CalcTargetDeceleration( float currentSpeed, float targetSpeed, float distance ) const; /** On reps */ UFUNCTION() void OnRep_DockingState(); UFUNCTION() void OnRep_IsSelfDrivingEnabled(); public: /** Called when the self driving is turn on or off. */ UPROPERTY( BlueprintAssignable, Category = "FactoryGame|Railroad|Train" ) FIsSelfDrivingDelegate mOnSelfDrivingChanged; /** Called when the docking state changes. */ UPROPERTY( BlueprintAssignable, Category = "FactoryGame|Railroad|Train" ) FDockingStateDelegate mOnDockingStateChanged; public: /** Static information about the consist, it changes when rolling stock is added/removed or a container is loaded/unloaded. */ UPROPERTY() FTrainConsist mConsistData; /** Runtime data for the automatic train control. See struct for more info. */ UPROPERTY() FTrainAtcData mAtcData; //@todotrains This should be simulated on the client as well without the need for replication. /** Physics simulation for the train */ UPROPERTY( SaveGame ) FTrainSimulationData mSimulationData; /** Runtime data for the self driving AI. */ FTrainSelfDrivingData mSelfDrivingData; public: //@todotrains private /** The name of this train. */ UPROPERTY( SaveGame, Replicated ) FText mTrainName; /** The track this train is on. */ UPROPERTY( Replicated ) int32 mTrackGraphID; /** Train are a doubly linked list, use TTrainIterator to iterate over a train. */ UPROPERTY( SaveGame ) class AFGRailroadVehicle* FirstVehicle; UPROPERTY( SaveGame ) class AFGRailroadVehicle* LastVehicle; /** This is the master locomotives that sends its input (throttle/brake/etc) to all other locomotives in the train. */ UPROPERTY( Replicated ) class AFGLocomotive* mMultipleUnitMaster; /** This trains time table. */ UPROPERTY( SaveGame, Replicated ) class AFGRailroadTimeTable* TimeTable; /** Is this train self driving */ UPROPERTY( SaveGame, ReplicatedUsing = OnRep_IsSelfDrivingEnabled ) bool mIsSelfDrivingEnabled; /** Error reported by the AI. */ UPROPERTY( Replicated ) ESelfDrivingLocomotiveError mSelfDrivingError; /** The status for an ongoing dock, this is not saved, it's updated from the station we're docked to on load. */ UPROPERTY( ReplicatedUsing = OnRep_DockingState ) ETrainDockingState mDockingState; /** How much the brakes decelerate the train. [cm/s^2] */ float MaxAirBrakeDeceleration; private: /** Sound component controlling all the moving/idle sounds for the train */ UPROPERTY() class UFGRailroadVehicleSoundComponent* mSoundComponent; /** Significance data */ bool mIsSignificant; FVector mSignificanceLocation; float mSignificanceRadius; float mSignificanceRange; };
[ "ian@nevir.net" ]
ian@nevir.net
46231253d3cd6d337c64e9ae83f928498d848b5d
84642b969685d0a35578bc9dc8dbd964a3a177e4
/lf_stack.h
07b5cbbe502a15c89d777a13119db3a41b065004
[]
no_license
linfan255/tiny_stl
cde5519e4d5a2c300263d087bd72aff220a4f100
e6f4b326c1a90a1b5b5132d1aa23d9207ea53b94
refs/heads/master
2021-01-18T11:41:29.360064
2017-09-07T09:06:44
2017-09-07T09:06:44
100,361,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,676
h
// // Created by van on 17-8-24. // #ifndef TINY_STL_LF_STACK_H #define TINY_STL_LF_STACK_H #include "allocator.h" #include "lf_deque.h" namespace lf { template <typename T, typename Container = deque<T> > class stack { public: typedef typename Container::value_type value_type; typedef typename Container::pointer pointer; typedef typename Container::reference reference; typedef typename Container::const_pointer const_pointer; typedef typename Container::const_reference const_reference; typedef typename Container::size_type size_type; typedef typename Container::difference_type difference_type; private: Container cc; public: stack() = default; stack(const stack& other); stack(size_type n, const value_type& val); ~stack() = default; stack& operator=(const stack& rhs); void push(const value_type& val) { cc.push_back(val); } void pop() { cc.pop_back(); } size_type size() const { return cc.size(); } bool empty() const { return cc.empty(); } reference top() { return cc.back(); } const_reference top() const { return cc.back(); } }; template <typename T, typename Container> stack<T,Container>::stack(size_type n, const value_type &val): cc(n, val) {} template <typename T, typename Container> stack<T,Container>::stack(const stack &other): cc(other.cc) {} template <typename T, typename Container> stack<T,Container>& stack<T,Container>::operator=(const stack& rhs) { cc = rhs.cc; } } #endif //TINY_STL_LF_STACK_H
[ "linfan255@163.com" ]
linfan255@163.com
ece5c2d8e52d31b23c3f5c302c34ad1341e1ffba
72ca613537ffb197cf7048dadcac360b9a00b5e5
/rfid/RFID_ACCESS.ino
85815a79d14e2f56fa9d0c3ffe4aaa3b563366ff
[]
no_license
Mohamed-Trabelsi/Smart_Cinema-2A2-
346ac74783b5e4ad501ba96984daddaa9f0753da
03f24275d911696b68ac17bc925e55c3f6e54245
refs/heads/master
2023-02-14T01:42:22.476645
2021-01-08T11:29:08
2021-01-08T11:29:08
315,463,670
0
1
null
null
null
null
UTF-8
C++
false
false
3,807
ino
#include <SPI.h> #include <MFRC522.h> #include <Servo.h> #include <LCD.h> #include <LiquidCrystal_I2C.h> //Define variables #define I2C_ADDR 0x27 //Define I2C Address where the PCF8574A is #define BACKLIGHT_PIN 3 #define En_pin 2 #define Rw_pin 1 #define Rs_pin 0 #define D4_pin 4 #define D5_pin 5 #define D6_pin 6 #define D7_pin 7 //Initialise the LCD #define SS_PIN 10 #define RST_PIN 9 #define LED_G 5 //define green LED pin #define LED_R 4 //define red LED #define BUZZER 2 //buzzer pin MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance. Servo myServo; //define servo name LiquidCrystal_I2C lcd(I2C_ADDR, En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin); void setup() { lcd.begin (16,2); lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE); lcd.setBacklight(HIGH); Serial.begin(9600); // Initiate a serial communication SPI.begin(); // Initiate SPI bus mfrc522.PCD_Init(); // Initiate MFRC522 myServo.attach(3); //servo pin myServo.write(0); //servo start position pinMode(LED_G, OUTPUT); pinMode(LED_R, OUTPUT); pinMode(BUZZER, OUTPUT); noTone(BUZZER); } void loop() { char data ; lcd.setCursor(0,0); lcd.print("Put Card.."); if(Serial.available()) { data=Serial.read(); if(data=='3') { lcd.setCursor(0,0); lcd.print(" ADMIN ACTION"); lcd.setCursor(0,1); lcd.print(" Door Open "); myServo.write(90); delay(5000); lcd.setCursor(0,1); lcd.print(" "); lcd.setCursor(0,0); lcd.print(" "); } else if(data=='4') { lcd.setCursor(0,0); lcd.print(" ADMIN ACTION"); lcd.setCursor(0,1); lcd.print(" Door Close "); myServo.write(0); delay(5000); lcd.setCursor(0,1); lcd.print(" "); lcd.setCursor(0,0); lcd.print(" "); } } // Look for new cards if ( ! mfrc522.PICC_IsNewCardPresent()) { return; } // Select one of the cards if ( ! mfrc522.PICC_ReadCardSerial()) { return; } //Show UID on serial monitor lcd.setCursor(0,0); lcd.print(" "); //lcd.print("UID tag :"); String content= ""; byte letter; for (byte i = 0; i < mfrc522.uid.size; i++) { //lcd.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "); //lcd.print(mfrc522.uid.uidByte[i], HEX); content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ")); content.concat(String(mfrc522.uid.uidByte[i], HEX)); } lcd.setCursor(0,0); lcd.print("Message : "); content.toUpperCase(); if ((content.substring(1) == "EA 46 57 1A")) //change here the UID of the card/cards that you want to give access { Serial.print("1"); lcd.setCursor(0,1); lcd.print(" Welcome Yosri"); data=2; delay(500); digitalWrite(LED_G, HIGH); tone(BUZZER, 500); delay(300); digitalWrite(LED_G, LOW); noTone(BUZZER); myServo.write(90); delay(1000); myServo.write(0); digitalWrite(LED_G, LOW); } else { if ((content.substring(1) == "27 17 4C 34")) { Serial.print("2"); lcd.setCursor(0,1); lcd.print(" Welcome Mohamed"); data=1; digitalWrite(LED_R, HIGH); tone(BUZZER, 500); delay(300); digitalWrite(LED_R, LOW); noTone(BUZZER); myServo.write(90); delay(1000); myServo.write(0); delay(300); } else { lcd.setCursor(0,1); lcd.print(" Access Denied!"); digitalWrite(LED_R, HIGH); tone(BUZZER, 300); delay(1000); digitalWrite(LED_R, LOW); noTone(BUZZER); } } delay(100); lcd.setCursor(0,1); lcd.print(" "); lcd.setCursor(0,0); lcd.print(" "); }
[ "wiem.trifi@esprit.tn" ]
wiem.trifi@esprit.tn
2ae06808d0e23b7c9ddd91e550f0190293e9d93f
ba86279dd568979d29b7f3b92840dfb6bc1f3ba0
/TankWar1_9/TankMoveMsg.cpp
5d2a8131556119c07dcd902410c7819f3f4ab539
[]
no_license
ChenYilei2016/MyTankWar
5e690ea6e9defc3bc579b18c1b8c69dd816e51df
6ce8495bf8587fa74f4ab9d259e3e11297c14f0b
refs/heads/master
2020-03-27T05:23:01.420150
2019-01-01T05:14:34
2019-01-01T05:14:34
146,014,430
2
1
null
null
null
null
UTF-8
C++
false
false
1,360
cpp
#include "TankMoveMsg.h" #include <QList> TankMoveMsg::TankMoveMsg(int id, Direction dir, int x, int y) { this->id = id; this->x = x; this->y = y; this->dir = dir; } TankMoveMsg::TankMoveMsg(TankClient *tc, const QJsonObject &obj) { this->tc = tc; this->obj = obj; } void TankMoveMsg::sendMsg(NetClient *client, QString IP, int Port) { QJsonDocument doc; QJsonObject obj; obj.insert("msgtype",this->msgType); obj.insert("id",this->id); obj.insert("x",this->x); obj.insert("y",this->y); obj.insert("dir",this->dir); doc.setObject(obj); QByteArray buf = doc.toJson(QJsonDocument::Compact); client->sendMsg(buf,IP,Port); } void TankMoveMsg::parse() { int id = obj.value("id").toInt(); if( id == tc->mytank->getOneTankID()) { return ; } else { bool exist =false; for(int i= 0 ; i<tc->tanks.size();i++) { Tank * t = tc->tanks.at(i); if(id == t->getOneTankID() ) { Direction dir = (Direction)obj.value("dir").toInt(); int x = obj.value("x").toInt(); int y = obj.value("y").toInt(); t->setX(x); t->setY(y); t->setDir(dir); exist = true; break; } } } }
[ "705029004@qq.com" ]
705029004@qq.com
689a29cabd9c80aeb6a6d095e1029760b0d7323a
504665f830424caf004e4782a50cb8cab2356f9e
/src/data/example_parser.h
88d1857dc9e40d0e6fb3a3e3575aa9774b28195c
[ "Apache-2.0" ]
permissive
ChenglongChen/parameter_server
4d5a402a4d0e34e8269641fb754786ca8dfc4553
ba358357ba33a94a2af5798e49428a8d15bb12a8
refs/heads/master
2020-04-29T18:08:35.827133
2014-10-19T22:41:23
2014-10-19T22:41:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
693
h
#pragma once #include "util/common.h" #include "proto/example.pb.h" #include "proto/config.pb.h" namespace PS { static const int kSlotIDmax = 4096; class ExampleParser { public: typedef DataConfig::TextFormat TextFormat; void init(TextFormat format, bool ignore_fea_slot = false); void clear(); bool toProto(char*, Example*); ExampleInfo info(); int maxSlotID() { return ignore_fea_slot_ ? 2 : kSlotIDmax; } private: bool parseLibsvm(char*, Example*); bool parseAdfea(char*, Example*); ExampleInfo info_; SlotInfo slot_info_[kSlotIDmax]; bool ignore_fea_slot_; size_t num_ex_ = 0; TextFormat format_; std::function<bool(char*, Example*)> parser_; }; }
[ "muli@cs.cmu.edu" ]
muli@cs.cmu.edu
7a0f5e48f44fa247195947ce6b6340cfeafab3c2
116894caf8dcccf6f70211e386b943c43485087f
/vendor/Qt5.14.2/msvc2017/include/QtCore/5.14.2/QtCore/private/qeventdispatcher_winrt_p.h
2672f11123642c060caca22f40851815f827beb4
[ "MIT" ]
permissive
kiseop91/Pomordor
04498276ea73daef37ad50b6f351a2ffd2ed7ab5
5bfbfaa9ceecdf147058ca49dc3c4fa8b442717c
refs/heads/develop
2023-03-25T22:15:59.964938
2021-03-20T07:59:37
2021-03-20T07:59:37
276,431,994
2
2
MIT
2020-12-21T04:31:02
2020-07-01T16:44:31
C++
UTF-8
C++
false
false
3,887
h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QEVENTDISPATCHER_WINRT_P_H #define QEVENTDISPATCHER_WINRT_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <QtCore/private/qglobal_p.h> #include "QtCore/qabstracteventdispatcher.h" #include <qt_windows.h> #include <functional> QT_BEGIN_NAMESPACE quint64 qt_msectime(); class QEventDispatcherWinRTPrivate; class Q_CORE_EXPORT QEventDispatcherWinRT : public QAbstractEventDispatcher { Q_OBJECT Q_DECLARE_PRIVATE(QEventDispatcherWinRT) public: explicit QEventDispatcherWinRT(QObject *parent = 0); ~QEventDispatcherWinRT(); static HRESULT runOnXamlThread(const std::function<HRESULT()> &delegate, bool waitForRun = true); static HRESULT runOnMainThread(const std::function<HRESULT()> &delegate, int timeout = 100); bool processEvents(QEventLoop::ProcessEventsFlags flags); bool hasPendingEvents(); void registerSocketNotifier(QSocketNotifier *notifier); void unregisterSocketNotifier(QSocketNotifier *notifier); void registerTimer(int timerId, int interval, Qt::TimerType timerType, QObject *object); bool unregisterTimer(int timerId); bool unregisterTimers(QObject *object); QList<TimerInfo> registeredTimers(QObject *object) const; int remainingTime(int timerId); bool registerEventNotifier(QWinEventNotifier *notifier); void unregisterEventNotifier(QWinEventNotifier *notifier); void wakeUp(); void interrupt(); void flush(); void startingUp(); void closingDown(); protected: QEventDispatcherWinRT(QEventDispatcherWinRTPrivate &dd, QObject *parent = 0); virtual bool sendPostedEvents(QEventLoop::ProcessEventsFlags flags); bool event(QEvent *); int activateTimers(); }; QT_END_NAMESPACE #endif // QEVENTDISPATCHER_WINRT_P_H
[ "kiseop91@naver.com" ]
kiseop91@naver.com
a461ad78fa8f1a1f90c52b49bc8dcfda9cc6c46a
0de652685d9926570b59a74b5bf403a0795644b5
/h/Activeman.h
a8a582658b0e886641166ca43900c179ca80dda1
[]
no_license
zayac/runningram
b49215378f3ecfee3d24cb64ab2bb56f0c6bfc24
01ffeca795602b97583a4a6e089b8830e702e5f0
refs/heads/master
2020-03-30T21:59:14.160199
2011-09-30T19:15:41
2011-09-30T19:15:41
32,114,091
0
0
null
2020-02-28T21:18:31
2015-03-13T01:16:28
C++
UTF-8
C++
false
false
773
h
/* * File: Activeman.h * Author: necto * * Created on January 12, 2010, 12:32 AM */ #ifndef _ACTIVEMAN_H #define _ACTIVEMAN_H #include <list> #include "Transmitted.h" using std::list; class Canvas; class Active; class Battlefield; class Activeman :public list <Active*>, public Transmitted { void kill(iterator start, iterator finish); public: Activeman(); // Activeman(const Activeman& orig); // virtual ~Activeman(); void activate (float dt); void draw (Canvas*); void collisBrd (const Battlefield* bf); void processCollisions(); bool deleteDeadalives();//returns true when one or more of Deadalives have found and deleted int exp (char* buffer, int size) const; int imp (char* buffer, int size); bool ok() const; }; #endif /* _ACTIVEMAN_H */
[ "necto.ne@0b8b07ca-f9fe-11de-aabd-2bfef65f77b5" ]
necto.ne@0b8b07ca-f9fe-11de-aabd-2bfef65f77b5
d242920ea7d00bde505815cf9c0eca9219ebb36a
f660c3b78634794e1b32ee9c139e9fb9539bc1a3
/SE-SEM2-Assigns/CGL/DottedLine1.cpp
ef2429af1f3829bf7b8767a0d51d41dc763683af
[]
no_license
ManishDV/Engineering-Assignments
2054f4bc3139df535e4c96c3affe21f1a510c522
a4fcb14793e4818b72c5a065708735a83cfbe55a
refs/heads/master
2021-06-11T20:01:43.607742
2021-05-30T09:30:31
2021-05-30T09:30:31
194,872,155
3
1
null
null
null
null
UTF-8
C++
false
false
4,179
cpp
#include <iostream> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <math.h> #include <string.h> using namespace std; struct point{ GLfloat x; GLfloat y; }; struct point p1; struct point p2; int count = 0; int CountDraw = 0; int SB = 0; void print(int x, int y,int z, char *string) { //set the position of the text in the window using the x and y coordinates glRasterPos2f(x,y); //get the length of the string to display int len = (int)strlen(string); //loop to display character by character for (int i = 0; i<len; i++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12,string[i]); } } void drawDDA(struct point p1,struct point p2){ GLfloat dx = p2.x - p1.x; GLfloat dy = p2.y - p1.y; GLfloat x1 = p1.x; GLfloat y1 = p1.y; GLfloat step = 0; if (abs(dx) > abs(dy)) { step = abs(dx); } else { step = abs(dy); } GLfloat xInc = dx / step; GLfloat yInc = dy / step; glBegin(GL_POINTS); for (float i = 1; i <= step; i++) { cout<<"\nCountDraw: "<<CountDraw; cout<<"\nI: "<<i; CountDraw++; //For( _____ _ ____ _ ______ _ ________ _ _______) this type of line. // if(CountDraw < 50 && SB == 0){ // glColor3f(0.0,0.0,0.0); // } // if(CountDraw > 50 && CountDraw < 65 && SB == 0){ // glColor3f(1.0,1.0,1.0); // } // if(CountDraw > 65 && SB == 0){ // CountDraw = 0; // SB = 1; // } // if(CountDraw < 15 && SB == 1){ // glColor3f(0.0,0.0,0.0); // } // if(CountDraw > 15 && CountDraw < 30 && SB == 1){ // glColor3f(1.0,1.0,1.0); // } // if(CountDraw > 30 && SB == 1){ // CountDraw = 0; // SB = 0; // } // For (--------------------) this type of line. if(CountDraw < 50){ glColor3f(0.0,0.0,0.0); } if(CountDraw > 50 && CountDraw < 100){ glColor3f(1.0,1.0,1.0); } if(CountDraw > 100){ CountDraw = 0; } // For (_ _ _ _ _ _ _ _ _ _ _ _ _) this type of line. // if(CountDraw < 20){ // glColor3f(0.0,0.0,0.0); // } // if(CountDraw > 20 && CountDraw < 30){ // glColor3f(1.0,1.0,1.0); // } // if(CountDraw > 40){ // CountDraw = 0; // } glVertex2f(ceil(x1), ceil(y1)); x1 += xInc; y1 += yInc; } glEnd(); glFlush(); } void mouse(int button,int state,int x,int y){ if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){ cout<<"\nX: "<<x; cout<<"\nY: "<<y; p1.x =2*x - 400; p1.y =400 - 2*y; count++; cout<<"\nX: "<<p1.x; cout<<"\nY: "<<p1.y; cout<<"\n\n"; } if(count == 1) p2 = p1; if(count == 2){ drawDDA(p2,p1); count = 0; } } void render(){ struct point p3 = {-400,0}; struct point p4 = {400,0}; // drawDDA(p3,p4); glBegin(GL_LINES); glVertex2f(p3.x,p3.y); glVertex2f(p4.x,p4.y); glEnd(); p3 = {0,400}; p4 = {0,-400}; // drawDDA(p3,p4); glPointSize(5.0); glBegin(GL_LINES); glVertex2f(p3.x,p3.y); glVertex2f(p4.x,p4.y); glEnd(); glEnable(GL_LINE_SMOOTH); print(-70,-25,10,(char *)"(0,0)"); glFlush(); } void Init(){ glClearColor(1.0,1.0,1.0,0.0); glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0,0.0,0.0); gluOrtho2D(-400,400,-400,400); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFlush(); } int main(int argc ,char** argv){ glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE); glutInitWindowPosition(400,400); glutInitWindowSize(400,400); glutCreateWindow("Dotted Line Pattern 1"); Init(); glutDisplayFunc(render); glutMouseFunc(mouse); glutMainLoop(); return 0; }
[ "manishvisave149@gmail.com" ]
manishvisave149@gmail.com
eaf622101605305179c545e5166a23cb56b43f41
75ee9d3ea8560eacada7049107b88d126ed85c23
/devel/include/gazebo_msgs/SetJointTrajectoryRequest.h
51ded98c5ea8a2adf868b7a577d25479c2fe42eb
[]
no_license
LordBismaya/FrenchVanilla
f1cf9047127884733bfdd53d5a4a2e5723f61a93
fe6f0cd608373814558281878b90da41ae8ed32b
refs/heads/master
2021-05-04T10:09:09.957348
2016-04-06T08:49:09
2016-04-06T08:49:09
55,325,248
0
2
null
2018-11-28T16:21:21
2016-04-03T02:05:36
C++
UTF-8
C++
false
false
9,540
h
// Generated by gencpp from file gazebo_msgs/SetJointTrajectoryRequest.msg // DO NOT EDIT! #ifndef GAZEBO_MSGS_MESSAGE_SETJOINTTRAJECTORYREQUEST_H #define GAZEBO_MSGS_MESSAGE_SETJOINTTRAJECTORYREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <trajectory_msgs/JointTrajectory.h> #include <geometry_msgs/Pose.h> namespace gazebo_msgs { template <class ContainerAllocator> struct SetJointTrajectoryRequest_ { typedef SetJointTrajectoryRequest_<ContainerAllocator> Type; SetJointTrajectoryRequest_() : model_name() , joint_trajectory() , model_pose() , set_model_pose(false) , disable_physics_updates(false) { } SetJointTrajectoryRequest_(const ContainerAllocator& _alloc) : model_name(_alloc) , joint_trajectory(_alloc) , model_pose(_alloc) , set_model_pose(false) , disable_physics_updates(false) { } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _model_name_type; _model_name_type model_name; typedef ::trajectory_msgs::JointTrajectory_<ContainerAllocator> _joint_trajectory_type; _joint_trajectory_type joint_trajectory; typedef ::geometry_msgs::Pose_<ContainerAllocator> _model_pose_type; _model_pose_type model_pose; typedef uint8_t _set_model_pose_type; _set_model_pose_type set_model_pose; typedef uint8_t _disable_physics_updates_type; _disable_physics_updates_type disable_physics_updates; typedef boost::shared_ptr< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> const> ConstPtr; }; // struct SetJointTrajectoryRequest_ typedef ::gazebo_msgs::SetJointTrajectoryRequest_<std::allocator<void> > SetJointTrajectoryRequest; typedef boost::shared_ptr< ::gazebo_msgs::SetJointTrajectoryRequest > SetJointTrajectoryRequestPtr; typedef boost::shared_ptr< ::gazebo_msgs::SetJointTrajectoryRequest const> SetJointTrajectoryRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace gazebo_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'sensor_msgs': ['/opt/ros/indigo/share/sensor_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'trajectory_msgs': ['/opt/ros/indigo/share/trajectory_msgs/cmake/../msg'], 'gazebo_msgs': ['/home/bismaya/catkin_ws/src/gazebo_ros_pkgs/gazebo_msgs/msg'], 'geometry_msgs': ['/opt/ros/indigo/share/geometry_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> > { static const char* value() { return "649dd2eba5ffd358069238825f9f85ab"; } static const char* value(const ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x649dd2eba5ffd358ULL; static const uint64_t static_value2 = 0x069238825f9f85abULL; }; template<class ContainerAllocator> struct DataType< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> > { static const char* value() { return "gazebo_msgs/SetJointTrajectoryRequest"; } static const char* value(const ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> > { static const char* value() { return "string model_name\n\ trajectory_msgs/JointTrajectory joint_trajectory\n\ geometry_msgs/Pose model_pose\n\ bool set_model_pose\n\ bool disable_physics_updates\n\ \n\ ================================================================================\n\ MSG: trajectory_msgs/JointTrajectory\n\ Header header\n\ string[] joint_names\n\ JointTrajectoryPoint[] points\n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ \n\ ================================================================================\n\ MSG: trajectory_msgs/JointTrajectoryPoint\n\ # Each trajectory point specifies either positions[, velocities[, accelerations]]\n\ # or positions[, effort] for the trajectory to be executed.\n\ # All specified values are in the same order as the joint names in JointTrajectory.msg\n\ \n\ float64[] positions\n\ float64[] velocities\n\ float64[] accelerations\n\ float64[] effort\n\ duration time_from_start\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Pose\n\ # A representation of pose in free space, composed of postion and orientation. \n\ Point position\n\ Quaternion orientation\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Point\n\ # This contains the position of a point in free space\n\ float64 x\n\ float64 y\n\ float64 z\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Quaternion\n\ # This represents an orientation in free space in quaternion form.\n\ \n\ float64 x\n\ float64 y\n\ float64 z\n\ float64 w\n\ "; } static const char* value(const ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.model_name); stream.next(m.joint_trajectory); stream.next(m.model_pose); stream.next(m.set_model_pose); stream.next(m.disable_physics_updates); } ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct SetJointTrajectoryRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::gazebo_msgs::SetJointTrajectoryRequest_<ContainerAllocator>& v) { s << indent << "model_name: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.model_name); s << indent << "joint_trajectory: "; s << std::endl; Printer< ::trajectory_msgs::JointTrajectory_<ContainerAllocator> >::stream(s, indent + " ", v.joint_trajectory); s << indent << "model_pose: "; s << std::endl; Printer< ::geometry_msgs::Pose_<ContainerAllocator> >::stream(s, indent + " ", v.model_pose); s << indent << "set_model_pose: "; Printer<uint8_t>::stream(s, indent + " ", v.set_model_pose); s << indent << "disable_physics_updates: "; Printer<uint8_t>::stream(s, indent + " ", v.disable_physics_updates); } }; } // namespace message_operations } // namespace ros #endif // GAZEBO_MSGS_MESSAGE_SETJOINTTRAJECTORYREQUEST_H
[ "bsahoo@uwaterloo.ca" ]
bsahoo@uwaterloo.ca
f9e4520fe27d561f95128f61759c894e290a8d4c
c03615f53093643e3c1e323b83cbe77970966575
/PRT/3rdParty/cgal/cgal/include/CGAL/RS/rs3_k_refiner_1.h
c9a47446539b19570f2d973ba676372382f636b3
[]
no_license
fangguanya/PRT
0925b28671e756a6e9431fd57149cf2eebc94818
77c1b8e5f3a7a149825ad0cc3ef6002816222622
refs/heads/master
2021-06-08T20:54:22.954395
2016-11-24T07:38:11
2016-11-24T07:38:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,123
h
// Copyright (c) 2006-2013 INRIA Nancy-Grand Est (France). All rights reserved. // // This file is part of CGAL (www.cgal.org); 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. // See the file LICENSE.LGPL distributed with CGAL. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // Author: Luis Peñaranda <luis.penaranda@gmx.com> #ifndef CGAL_RS_RS3_K_REFINER_1_H #define CGAL_RS_RS3_K_REFINER_1_H #include <CGAL/Polynomial_traits_d.h> #include "rs2_calls.h" #include <rs3_fncts.h> #include "Gmpfr_make_unique.h" namespace CGAL{ namespace RS3{ template <class Polynomial_,class Bound_> struct RS3_k_refiner_1{ void operator()(const Polynomial_&,Bound_&,Bound_&,int); }; // class RS3_k_refiner_1 template <class Polynomial_,class Bound_> void RS3_k_refiner_1<Polynomial_,Bound_>:: operator()(const Polynomial_&,Bound_&,Bound_&,int){ CGAL_error_msg("RS3 k-refiner not implemented for these types"); return; } template<> void RS3_k_refiner_1<Polynomial<Gmpz>,Gmpfr>:: operator() (const Polynomial<Gmpz> &pol,Gmpfr &left,Gmpfr &right,int prec){ typedef Polynomial<Gmpz> Polynomial; typedef Polynomial_traits_d<Polynomial> Ptraits; typedef Ptraits::Degree Degree; CGAL_precondition(left<=right); // TODO: add precondition to check whether the interval is a point // or the evaluations on its endpoints have different signs //std::cout<<"refining ["<<left<<","<<right<<"]"<<std::endl; int deg=Degree()(pol); mpz_t* coefficients=(mpz_t*)malloc((deg+1)*sizeof(mpz_t)); __mpfi_struct interval; CGAL_RS_GMPFR_MAKE_UNIQUE(left,temp_left); CGAL_RS_GMPFR_MAKE_UNIQUE(right,temp_right); interval.left=*(left.fr()); interval.right=*(right.fr()); for(int i=0;i<=deg;++i) coefficients[i][0]=*(pol[i].mpz()); RS2::RS2_calls::init_solver(); rs3_refine_u_root(&interval, coefficients, deg, prec+CGAL::max(left.get_precision(), right.get_precision()), 1, 1); free(coefficients); mpfr_clear(left.fr()); mpfr_clear(right.fr()); mpfr_custom_init_set(left.fr(), mpfr_custom_get_kind(&interval.left), mpfr_custom_get_exp(&interval.left), mpfr_get_prec(&interval.left), mpfr_custom_get_mantissa(&interval.left)); mpfr_custom_init_set(right.fr(), mpfr_custom_get_kind(&interval.right), mpfr_custom_get_exp(&interval.right), mpfr_get_prec(&interval.right), mpfr_custom_get_mantissa(&interval.right)); CGAL_postcondition(left<=right); //std::cout<<"ref root is ["<<left<<","<<right<<"]"<<std::endl; return; } template<> void RS3_k_refiner_1<Polynomial<Gmpq>,Gmpfr>:: operator() (const Polynomial<Gmpq> &qpol,Gmpfr &left,Gmpfr &right,int prec){ typedef Polynomial<Gmpz> ZPolynomial; typedef Polynomial_traits_d<ZPolynomial> ZPtraits; typedef ZPtraits::Degree ZDegree; CGAL_precondition(left<=right); // TODO: add precondition to check whether the interval is a point // or the evaluations on its endpoints have different signs //std::cout<<"refining ["<<left<<","<<right<<"]"<<std::endl; Polynomial<Gmpz> zpol=CGAL::RS_AK1::Polynomial_converter_1< CGAL::Polynomial<Gmpq>, CGAL::Polynomial<Gmpz> >()(qpol); int deg=ZDegree()(zpol); mpz_t* coefficients=(mpz_t*)malloc((deg+1)*sizeof(mpz_t)); __mpfi_struct interval; CGAL_RS_GMPFR_MAKE_UNIQUE(left,temp_left); CGAL_RS_GMPFR_MAKE_UNIQUE(right,temp_right); interval.left=*(left.fr()); interval.right=*(right.fr()); for(int i=0;i<=deg;++i) coefficients[i][0]=*(zpol[i].mpz()); RS2::RS2_calls::init_solver(); rs3_refine_u_root(&interval, coefficients, deg, prec+CGAL::max(left.get_precision(), right.get_precision()), 1, 1); free(coefficients); mpfr_clear(left.fr()); mpfr_clear(right.fr()); mpfr_custom_init_set(left.fr(), mpfr_custom_get_kind(&interval.left), mpfr_custom_get_exp(&interval.left), mpfr_get_prec(&interval.left), mpfr_custom_get_mantissa(&interval.left)); mpfr_custom_init_set(right.fr(), mpfr_custom_get_kind(&interval.right), mpfr_custom_get_exp(&interval.right), mpfr_get_prec(&interval.right), mpfr_custom_get_mantissa(&interval.right)); CGAL_postcondition(left<=right); //std::cout<<"ref root is ["<<left<<","<<right<<"]"<<std::endl; return; } } // namespace RS3 } // namespace CGAL #endif // CGAL_RS_RS3_K_REFINER_1_H
[ "succeed.2009@163.com" ]
succeed.2009@163.com
481b23ce530639bf61e8b383ef6e479aa291e08f
3714fc7d4748b915fa32cda77218d7d4328f0d43
/minimoscuadrados.cpp
a3cccb8a9f7e99fd00a695d5c14b625576e540dd
[]
no_license
cnpoe/M-todos-num-ricos
987a30a272c059f67af30da09c0ca2e190b5962a
9b5551c085e9af449f11b1dcade0c57fe4fad78f
refs/heads/master
2021-01-11T16:55:35.786563
2017-01-28T05:57:26
2017-01-28T05:57:26
79,696,507
0
0
null
null
null
null
UTF-8
C++
false
false
589
cpp
#include<iostream> using namespace std; double a0, a1; void minimosCuadrados(int n, double *x, double *y){ double Sx = 0.0, Sx2 = 0.0, Sy = 0.0, Sxy = 0.0; for(int i = 0; i < n; i++){ Sx += x[i]; Sx2 = Sx2 + x[i] * x[i]; Sy += y[i]; Sxy = Sxy + x[i] * y[i]; } a1 = (n * Sxy - Sx * Sy) / (n * Sx2 - Sx * Sx); a0 = (Sy - a1 * Sx) / n; cout << "a0 = " << a0 << " , a1 = " << a1 << endl; } int main(void){ double x[10] = {12, 6.4, 95, 159, 120, 40, 73, 98, 112, 200}; double y[10] = {3, 2, 15, 40, 32, 0.8, 12, 15, 30, 48}; minimosCuadrados(10, x, y); return 0; }
[ "cnpoek@gmail.com" ]
cnpoek@gmail.com
6253092fbc5f00e5d06dacbc94b3a85d6578df46
756fce0e51a4888fd6190b925262d88d49e17c84
/BSGenLib/Include/Common/BSUtil.h
0fe09d242ff7634b20d9037d8020df80c99a9231
[ "Apache-2.0" ]
permissive
kivzcu/BSGenLib
15d32495e9985ed91896bfcd322eec9fce53b2f4
1aeb245eb873f8f23d4a03cd31d5534fa3f4500d
refs/heads/master
2021-07-13T12:11:13.689415
2020-06-12T09:15:03
2020-06-12T09:15:03
124,209,186
0
1
null
null
null
null
UTF-8
C++
false
false
195
h
#pragma once class CBSUtil { public: //formats time given in milliseconds static CString FormatTime(double time); //formats time given is bytes static CString FormatSize(DWORD dwBytes); };
[ "besoft@kiv.zcu.cz" ]
besoft@kiv.zcu.cz
cd624ac9c9ed132f40e8be8ed38914e3d3ec2728
401d9120db1750d65312479e5e99ff7ab1a867b3
/poj-3150-循环矩阵快速幂.cpp
5ffeb89b5ef410b9b8804052af1b60140c3de779
[ "MIT" ]
permissive
ZxMYS/Xiaos-ACM-Solution-Set
ff14348149bae56a7689a87ef5796533fff70aed
cfd7fc34deac27f4e0267a4eb3cc396c0a8dbe8f
refs/heads/master
2021-01-01T15:54:39.868855
2013-02-01T11:32:41
2013-02-01T11:32:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,390
cpp
#include<stdio.h> #include<stdlib.h> #include<time.h> #include<string.h> #include<math.h> #include<assert.h> #include<iostream> #include<algorithm> #include<numeric> #include<vector> #include<map> #include<queue> #include<list> #include<sstream> using namespace std; #define LOOP(x,y,z) for((x)=(y);(x)<=(z);(x)++) #define LOOPB(x,y,z) for((x)=(y);(x)<(z);(x)++) #define RLOOP(x,y,z) for((x)=(y);(x)>=(z);(x)--) #define RLOOPB(x,y,z) for((x)=(y);(x)>(z);(x)--) #define MAX(x,y) ((x)>(y)?(x):(y)) #define MIN(x,y) ((x)<(y)?(x):(y)) #define PI 3.1415926535898 template<class T> string i2s(T x){ostringstream o; o<<x;return o.str();} int i,j,k,a,d,m,n,s,t,l,tt; unsigned long long int matrix[500],matrix3[500],matrix4[500]; inline void mul(unsigned long long int a[],unsigned long long int b[]){ int i,j; LOOPB(i,0,n){ matrix4[i]=0; LOOPB(j,0,n) matrix4[i]+=a[j]*b[i>=j?i-j:n+i-j]; } LOOPB(i,0,n) b[i]=matrix4[i]%m; } int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); freopen("out","w",stdout); #endif scanf("%d%d%d%d",&n,&m,&d,&k); LOOPB(i,0,n)scanf("%llu",&matrix[i]); LOOP(i,0,d)matrix3[i]=1; LOOP(i,d+1,n-d)matrix3[i]=0; LOOPB(i,n-d,n)matrix3[i]=1; while(k){ if(k&1) mul(matrix3,matrix); mul(matrix3,matrix3); k>>=1; } printf("%llu",matrix[0]); LOOPB(i,1,n)printf(" %llu",matrix[i]); printf("\n"); }
[ "manyoushen@gmail.com" ]
manyoushen@gmail.com
23a70cc46fed2cd56bcfc379f4a6166b497bedae
a5f28e6f80a2e0ddf1fb2c8cdb2e74de2e4ff499
/src/image.h
9a7340566e25aea10335fc2e168334502f3e6230
[ "MIT" ]
permissive
fmdunlap/Art2Ascii
bdc3b1db0f7376305146dec6d7ca654b82a8e670
aab23cfba608c5e964c4c14126d4636dc96ebc37
refs/heads/master
2021-07-10T10:53:55.039243
2017-10-09T22:14:45
2017-10-09T22:14:45
105,313,402
0
0
null
null
null
null
UTF-8
C++
false
false
1,678
h
#include "../libs/CImg.h" #include <string> const int MAX_BRIGHTNESS = 255; const int DEFAULT_RESOLUTION = 6; enum PROCESS_TYPE{ standard, color, edge, transparency }; class image{ public: image(char* filename); image(char* filename, PROCESS_TYPE pt); ~image(); /*Computes the average brightness of a 'block' A block is a square of pixels that starts at a pixel(x,y) and extends to x+resolution, and y+resolution. */ int compute_block_average(int start_x, int start_y, int res); /* Computes the average distance from a given color in a block. */ int compute_block_color_distance(int start_x, int start_y, int res, int* color_values); /*Returns character in ascii_darkness_string that should be assosciated with the given brightness. NOTE: 0 <= BRIGHNTESS <= MAX_BRIGHTNESS NOTE: Automatically maps from 0-MAX_BRIGHTNESS into 'ascii_darkness_string' Function does not need to be updated if ascii_darkness_string is updated. */ char get_char_by_brightness(int brightness); //Prints current output_string to file at of_path void print_ascii_to_file(char* of_path); //If possible, updates the output ascii string to the current image & resolution. //Also returns the output string. std::string update_output_string(); //Getters & setters int get_resolution(); //NOTE: CAN BE A LONG RUNNING FUNCTION IN CHANGING RESOLUTION ON LARGE IMAGE. void set_resolution(int res); //Returns output_string std::string get_image_ascii(); private: int* base_color; int resolution; cimg_library::CImg<unsigned char>* raw_image; std::string ascii_darkness_string = "@#%*+=-:. "; std::string ascii_output_string; PROCESS_TYPE pType; };
[ "Fdunlap@usc.edu" ]
Fdunlap@usc.edu
379310db1822d85f36ab4942501aaf1783bccdfd
054ba082469edd7e25c0c52abaebe5ce1f1eec06
/hhcards/Classes/PokerStateInitial.h
1ba9010fa84ba192ca936359d9bb44d33a155070
[ "MIT" ]
permissive
duhone/HeadstoneHarryCards
3d5ddf8f865a81c3b85eaad187cfc60226bebc14
1a08d671835c659e543faca238a5661b4b59262f
refs/heads/master
2020-12-29T12:56:28.444477
2020-02-06T13:43:18
2020-02-06T13:43:18
238,614,611
1
0
null
null
null
null
UTF-8
C++
false
false
1,295
h
/* * PokerStateInitial.h * hhcards * * Created by Eric Duhon on 3/7/10. * Copyright 2010 Apple Inc. All rights reserved. * */ #pragma once #include "PokerHand.h" #include "Graphics.h" #include "PokerState.h" namespace CR { namespace HHCards { template<typename DeckType> class PokerStateInitial : public PokerState { public: PokerStateInitial(CR::Cards::PokerHand<DeckType> &_hand,std::vector<CR::Graphics::Sprite*> &_sprites); virtual void Deal() {m_goNext = true;} virtual int Process(); private: virtual bool Begin(); CR::Cards::PokerHand<DeckType> &m_hand; std::vector<CR::Graphics::Sprite*> &m_sprites; bool m_goNext; }; template<typename DeckType> PokerStateInitial<DeckType>::PokerStateInitial(CR::Cards::PokerHand<DeckType> &_hand,std::vector<CR::Graphics::Sprite*> &_sprites) : m_hand(_hand), m_sprites(_sprites) { } template<typename DeckType> bool PokerStateInitial<DeckType>::Begin() { m_hand.Reset(); for(int i = 0;i < m_sprites.size(); ++i) { m_sprites[i]->Visible(false); } m_goNext = false; return true; } template<typename DeckType> int PokerStateInitial<DeckType>::Process() { if(m_goNext) return NEXT; else return UNCHANGED; } } }
[ "duhone@outlook.com" ]
duhone@outlook.com
a8666ee9164e30040e9b8df8ce4ff91d2223961d
b3f3a5ac8c57d6fe96fc74df732143b36fa2479b
/chapter12/12-23.cpp
df4f6e9d178e3773a6ad3b6b4a3296996fa79ae0
[]
no_license
wangzhengyang/MyC-PrimerAnswer
19ef7064b7e48f63e86e896e914dd8c92300d49e
c86ceea1667d3bb9078c22a55ec806c098773f46
refs/heads/master
2022-12-09T14:58:47.218957
2020-09-01T09:49:15
2020-09-01T09:49:15
261,182,915
0
0
null
null
null
null
UTF-8
C++
false
false
810
cpp
#include <iostream> #include <string> #include <cstdlib> #include <cstring> using namespace std; int main() { /* char *pc1 = "hello"; char *pc2 = "world"; size_t len = strlen(pc1) + strlen(pc2) + 1; char src[len] = {}; char *p = strcat(src, pc1); printf("%s\r\n", src); strcat(p, pc2); printf("%s\r\n", src); cout << "len:" << len << endl; char *pc = new char[len](); for(size_t i = 0; i < len; i++){ pc[i] = src[i]; cout << pc[i]; } cout << endl; delete[] p; */ string s1 = "hello"; string s2 = "world"; string s = s1 + s2; size_t len = s.size(); char *p = new char[len]; for(size_t i = 0; i < len; ++i){ p[i] = s[i]; cout << p[i]; } cout << endl; delete[] p; return 0; }
[ "1484413135@qq.com" ]
1484413135@qq.com
1261141cbf8dab5ac05af792568f606cef3b34d3
6b5d6690678f05a71837b85016db3da52359a2f6
/src/net/base/network_delegate.h
81d81902412f89f952976e569132b9949d08e1fb
[ "BSD-3-Clause", "MIT" ]
permissive
bopopescu/MQUIC
eda5477bacc68f30656488e3cef243af6f7460e6
703e944ec981366cfd2528943b1def2c72b7e49d
refs/heads/master
2022-11-22T07:41:11.374401
2016-04-08T22:27:32
2016-04-08T22:27:32
282,352,335
0
0
MIT
2020-07-25T02:05:49
2020-07-25T02:05:49
null
UTF-8
C++
false
false
13,924
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_BASE_NETWORK_DELEGATE_H_ #define NET_BASE_NETWORK_DELEGATE_H_ #include <stdint.h> #include <string> #include "base/callback.h" #include "base/strings/string16.h" #include "base/threading/non_thread_safe.h" #include "net/base/auth.h" #include "net/base/completion_callback.h" #include "net/cookies/canonical_cookie.h" class GURL; namespace base { class FilePath; } namespace net { // NOTE: Layering violations! // We decided to accept these violations (depending // on other net/ submodules from net/base/), because otherwise NetworkDelegate // would have to be broken up into too many smaller interfaces targeted to each // submodule. Also, since the lower levels in net/ may callback into higher // levels, we may encounter dangerous casting issues. // // NOTE: It is not okay to add any compile-time dependencies on symbols outside // of net/base here, because we have a net_base library. Forward declarations // are ok. class CookieOptions; class HttpRequestHeaders; class HttpResponseHeaders; class ProxyInfo; class URLRequest; class NET_EXPORT NetworkDelegate : public base::NonThreadSafe { public: // AuthRequiredResponse indicates how a NetworkDelegate handles an // OnAuthRequired call. It's placed in this file to prevent url_request.h // from having to include network_delegate.h. enum AuthRequiredResponse { AUTH_REQUIRED_RESPONSE_NO_ACTION, AUTH_REQUIRED_RESPONSE_SET_AUTH, AUTH_REQUIRED_RESPONSE_CANCEL_AUTH, AUTH_REQUIRED_RESPONSE_IO_PENDING, }; typedef base::Callback<void(AuthRequiredResponse)> AuthCallback; virtual ~NetworkDelegate() {} // Notification interface called by the network stack. Note that these // functions mostly forward to the private virtuals. They also add some sanity // checking on parameters. See the corresponding virtuals for explanations of // the methods and their arguments. int NotifyBeforeURLRequest(URLRequest* request, const CompletionCallback& callback, GURL* new_url); int NotifyBeforeSendHeaders(URLRequest* request, const CompletionCallback& callback, HttpRequestHeaders* headers); void NotifyBeforeSendProxyHeaders(URLRequest* request, const ProxyInfo& proxy_info, HttpRequestHeaders* headers); void NotifySendHeaders(URLRequest* request, const HttpRequestHeaders& headers); int NotifyHeadersReceived( URLRequest* request, const CompletionCallback& callback, const HttpResponseHeaders* original_response_headers, scoped_refptr<HttpResponseHeaders>* override_response_headers, GURL* allowed_unsafe_redirect_url); void NotifyBeforeRedirect(URLRequest* request, const GURL& new_location); void NotifyResponseStarted(URLRequest* request); void NotifyNetworkBytesReceived(URLRequest* request, int64_t bytes_received); void NotifyNetworkBytesSent(URLRequest* request, int64_t bytes_sent); void NotifyCompleted(URLRequest* request, bool started); void NotifyURLRequestDestroyed(URLRequest* request); void NotifyPACScriptError(int line_number, const base::string16& error); AuthRequiredResponse NotifyAuthRequired(URLRequest* request, const AuthChallengeInfo& auth_info, const AuthCallback& callback, AuthCredentials* credentials); bool CanGetCookies(const URLRequest& request, const CookieList& cookie_list); bool CanSetCookie(const URLRequest& request, const std::string& cookie_line, CookieOptions* options); bool CanAccessFile(const URLRequest& request, const base::FilePath& path) const; bool CanEnablePrivacyMode(const GURL& url, const GURL& first_party_for_cookies) const; bool AreExperimentalCookieFeaturesEnabled() const; // TODO(jww): Remove this once we ship strict secure cookies: // https://crbug.com/546820 bool AreStrictSecureCookiesEnabled() const; bool CancelURLRequestWithPolicyViolatingReferrerHeader( const URLRequest& request, const GURL& target_url, const GURL& referrer_url) const; private: // This is the interface for subclasses of NetworkDelegate to implement. These // member functions will be called by the respective public notification // member function, which will perform basic sanity checking. // Called before a request is sent. Allows the delegate to rewrite the URL // being fetched by modifying |new_url|. If set, the URL must be valid. The // reference fragment from the original URL is not automatically appended to // |new_url|; callers are responsible for copying the reference fragment if // desired. // |callback| and |new_url| are valid only until OnURLRequestDestroyed is // called for this request. Returns a net status code, generally either OK to // continue with the request or ERR_IO_PENDING if the result is not ready yet. // A status code other than OK and ERR_IO_PENDING will cancel the request and // report the status code as the reason. // // The default implementation returns OK (continue with request). virtual int OnBeforeURLRequest(URLRequest* request, const CompletionCallback& callback, GURL* new_url) = 0; // Called right before the HTTP headers are sent. Allows the delegate to // read/write |headers| before they get sent out. |callback| and |headers| are // valid only until OnCompleted or OnURLRequestDestroyed is called for this // request. // See OnBeforeURLRequest for return value description. Returns OK by default. virtual int OnBeforeSendHeaders(URLRequest* request, const CompletionCallback& callback, HttpRequestHeaders* headers) = 0; // Called after a proxy connection. Allows the delegate to read/write // |headers| before they get sent out. |headers| is valid only until // OnCompleted or OnURLRequestDestroyed is called for this request. virtual void OnBeforeSendProxyHeaders(URLRequest* request, const ProxyInfo& proxy_info, HttpRequestHeaders* headers) = 0; // Called right before the HTTP request(s) are being sent to the network. // |headers| is only valid until OnCompleted or OnURLRequestDestroyed is // called for this request. virtual void OnSendHeaders(URLRequest* request, const HttpRequestHeaders& headers) = 0; // Called for HTTP requests when the headers have been received. // |original_response_headers| contains the headers as received over the // network, these must not be modified. |override_response_headers| can be set // to new values, that should be considered as overriding // |original_response_headers|. // If the response is a redirect, and the Location response header value is // identical to |allowed_unsafe_redirect_url|, then the redirect is never // blocked and the reference fragment is not copied from the original URL // to the redirection target. // // |callback|, |original_response_headers|, and |override_response_headers| // are only valid until OnURLRequestDestroyed is called for this request. // See OnBeforeURLRequest for return value description. Returns OK by default. virtual int OnHeadersReceived( URLRequest* request, const CompletionCallback& callback, const HttpResponseHeaders* original_response_headers, scoped_refptr<HttpResponseHeaders>* override_response_headers, GURL* allowed_unsafe_redirect_url) = 0; // Called right after a redirect response code was received. // |new_location| is only valid until OnURLRequestDestroyed is called for this // request. virtual void OnBeforeRedirect(URLRequest* request, const GURL& new_location) = 0; // This corresponds to URLRequestDelegate::OnResponseStarted. virtual void OnResponseStarted(URLRequest* request) = 0; // Called when bytes are received from the network, such as after receiving // headers or reading raw response bytes. This includes localhost requests. // |bytes_received| is the number of bytes measured at the application layer // that have been received over the network for this request since the last // time OnNetworkBytesReceived was called. |bytes_received| will always be // greater than 0. // Currently, this is only implemented for HTTP transactions, and // |bytes_received| does not include TLS overhead or TCP retransmits. virtual void OnNetworkBytesReceived(URLRequest* request, int64_t bytes_received) = 0; // Called when bytes are sent over the network, such as when sending request // headers or uploading request body bytes. This includes localhost requests. // |bytes_sent| is the number of bytes measured at the application layer that // have been sent over the network for this request since the last time // OnNetworkBytesSent was called. |bytes_sent| will always be greater than 0. // Currently, this is only implemented for HTTP transactions, and |bytes_sent| // does not include TLS overhead or TCP retransmits. virtual void OnNetworkBytesSent(URLRequest* request, int64_t bytes_sent) = 0; // Indicates that the URL request has been completed or failed. // |started| indicates whether the request has been started. If false, // some information like the socket address is not available. virtual void OnCompleted(URLRequest* request, bool started) = 0; // Called when an URLRequest is being destroyed. Note that the request is // being deleted, so it's not safe to call any methods that may result in // a virtual method call. virtual void OnURLRequestDestroyed(URLRequest* request) = 0; // Corresponds to ProxyResolverJSBindings::OnError. virtual void OnPACScriptError(int line_number, const base::string16& error) = 0; // Called when a request receives an authentication challenge // specified by |auth_info|, and is unable to respond using cached // credentials. |callback| and |credentials| must be non-NULL, and must // be valid until OnURLRequestDestroyed is called for |request|. // // The following return values are allowed: // - AUTH_REQUIRED_RESPONSE_NO_ACTION: |auth_info| is observed, but // no action is being taken on it. // - AUTH_REQUIRED_RESPONSE_SET_AUTH: |credentials| is filled in with // a username and password, which should be used in a response to // |auth_info|. // - AUTH_REQUIRED_RESPONSE_CANCEL_AUTH: The authentication challenge // should not be attempted. // - AUTH_REQUIRED_RESPONSE_IO_PENDING: The action will be decided // asynchronously. |callback| will be invoked when the decision is made, // and one of the other AuthRequiredResponse values will be passed in with // the same semantics as described above. virtual AuthRequiredResponse OnAuthRequired( URLRequest* request, const AuthChallengeInfo& auth_info, const AuthCallback& callback, AuthCredentials* credentials) = 0; // Called when reading cookies to allow the network delegate to block access // to the cookie. This method will never be invoked when // LOAD_DO_NOT_SEND_COOKIES is specified. virtual bool OnCanGetCookies(const URLRequest& request, const CookieList& cookie_list) = 0; // Called when a cookie is set to allow the network delegate to block access // to the cookie. This method will never be invoked when // LOAD_DO_NOT_SAVE_COOKIES is specified. virtual bool OnCanSetCookie(const URLRequest& request, const std::string& cookie_line, CookieOptions* options) = 0; // Called when a file access is attempted to allow the network delegate to // allow or block access to the given file path. Returns true if access is // allowed. virtual bool OnCanAccessFile(const URLRequest& request, const base::FilePath& path) const = 0; // Returns true if the given |url| has to be requested over connection that // is not tracked by the server. Usually is false, unless user privacy // settings block cookies from being get or set. virtual bool OnCanEnablePrivacyMode( const GURL& url, const GURL& first_party_for_cookies) const = 0; // Returns true if the embedder has enabled the experimental features, and // false otherwise. virtual bool OnAreExperimentalCookieFeaturesEnabled() const = 0; // Returns true if the embedder has enabled experimental features or // specifically strict secure cookies, and false otherwise. // // TODO(jww): Remove this once we ship strict secure cookies: // https://crbug.com/546820. virtual bool OnAreStrictSecureCookiesEnabled() const = 0; // Called when the |referrer_url| for requesting |target_url| during handling // of the |request| is does not comply with the referrer policy (e.g. a // secure referrer for an insecure initial target). // Returns true if the request should be cancelled. Otherwise, the referrer // header is stripped from the request. virtual bool OnCancelURLRequestWithPolicyViolatingReferrerHeader( const URLRequest& request, const GURL& target_url, const GURL& referrer_url) const = 0; }; } // namespace net #endif // NET_BASE_NETWORK_DELEGATE_H_
[ "alyssar@google.com" ]
alyssar@google.com
034d241f110b11f3fa8acbfec92763b24270f9e1
a8e9dc87186626e726ebadfa490e4f7850a07d8e
/wpfib_essentials/fiberapp/fiber/webrtc/webrtc/modules/video_capture/windows/win_capture_feature_flags.h
83537477383e8453de916065e6b36cc9160d736a
[]
no_license
ymusiychuk-lohika/FreeSWITCH_test
25ca23bee1178c081abd002438888ea15a37187d
2ca7a992e1087442b6484699d24706085fc2851d
refs/heads/master
2021-01-12T10:51:55.561944
2016-12-12T11:57:27
2016-12-12T11:57:27
72,739,774
0
1
null
null
null
null
UTF-8
C++
false
false
2,227
h
#ifndef __WIN_CAPTURER_FEATURE_FLAGS_H_ #define __WIN_CAPTURER_FEATURE_FLAGS_H_ namespace BJN { // Feature type description, used by windows app capture process typedef enum _FeatureType { CaptureApp2UsingLatest = 1, // AppCapture2 with hooks and magnification CaptureScreenUsingDDBasic = 2, // primary & secondary (partial) monitor using dd CaptureScreenUsingDDComplete = 3, // all monitor support & smart presenter widget filtering CaptureAppUsingDDComplete = 4 // Capture application using dd }FeatureType; // Exit code for app capture process typedef enum _AppCaptureExitCode { ExitSuccess = 0, // App capture process exit successfully ExitFailureGeneric = -1, // App capture process exit with failure ExitFailureDDScreenShare = -2 // Problem with current DD screen capture mechanism request to fallback to existing mechanism }; class AppCaptureProcessParameters { public: typedef struct _ProcessData{ FeatureType requestedFeatureType; FeatureType deliveredFeatureType; bool bInfoBarEnabled; } ProcessData; // Create new app capture params AppCaptureProcessParameters(bool bCreate); // Open existing app capture params AppCaptureProcessParameters(LPCTSTR lpSharedDataId); ~AppCaptureProcessParameters(); bool IsValid() const { return _isValid; }; bool SetRequestedFeatureType(FeatureType requestedFeatureType); bool GetRequestedFeatureType(FeatureType& requestedFeatureType) const; bool SetDeliveredFeatureType(FeatureType deliveredFeatureType); bool GetDeliveredFeatureType(FeatureType& deliveredFeatureType) const; bool SetInfoBarEnabled(bool enabled); bool GetInfoBarEnabled(bool& enabled) const; bool GetSharedDataId(std::wstring& sharedDataId) const; private: bool _isValid; ProcessData* _pProcessData; std::wstring _sharedDataId; HANDLE _sharedMemory; }; bool GetGUID(std::wstring& sGuid); } // namespace BJN #endif //__WIN_CAPTURER_FEATURE_FLAGS_H_
[ "ymusiychuk@lohika.com" ]
ymusiychuk@lohika.com
193a989413c56a0b704462539d265b8d4251950a
5cdd9c1b6adb67fec94f6349ad6203ce2702fecb
/third_party/Windows-CalcEngine/src/SpectralAveraging/src/SpectralSample.cpp
8059abab1fd086bb4128fe977e9d40a0717347d3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
NREL/EnergyPlus
9d8fc6936b5a0c81d2469ab9cdabe55405ccb8f2
50b8a5511ce559e5175524b943c26cc5b99d712d
refs/heads/develop
2023-09-04T08:20:29.804559
2023-09-01T13:58:55
2023-09-01T13:58:55
14,620,185
1,013
406
NOASSERTION
2023-09-14T19:52:57
2013-11-22T14:47:34
C++
UTF-8
C++
false
false
12,527
cpp
#include <stdexcept> #include <cassert> #include "SpectralSample.hpp" #include "MeasuredSampleData.hpp" #include "WCECommon.hpp" using namespace FenestrationCommon; namespace SpectralAveraging { ////////////////////////////////////////////////////////////////////////////////////// //// CSample ////////////////////////////////////////////////////////////////////////////////////// CSample::CSample(const CSeries & t_SourceData, IntegrationType integrationType, double t_NormalizationCoefficient) : m_SourceData(t_SourceData), m_WavelengthSet(WavelengthSet::Data), m_IntegrationType(integrationType), m_NormalizationCoefficient(t_NormalizationCoefficient), m_StateCalculated(false) { CSample::reset(); } CSample::CSample() : m_WavelengthSet(WavelengthSet::Data), m_IntegrationType(IntegrationType::Trapezoidal), m_NormalizationCoefficient(1), m_StateCalculated(false) { CSample::reset(); } CSample & CSample::operator=(const CSample & t_Sample) { m_StateCalculated = t_Sample.m_StateCalculated; m_IntegrationType = t_Sample.m_IntegrationType; m_NormalizationCoefficient = t_Sample.m_NormalizationCoefficient; m_WavelengthSet = t_Sample.m_WavelengthSet; m_IncomingSource = t_Sample.m_IncomingSource; for(const auto & prop : EnumProperty()) { for(const auto & side : EnumSide()) { m_EnergySource[std::make_pair(prop, side)] = t_Sample.m_EnergySource.at(std::make_pair(prop, side)); } } return *this; } CSample::CSample(const CSample & t_Sample) { operator=(t_Sample); } CSeries & CSample::getSourceData() { calculateState(); // must interpolate data to same wavelengths return m_SourceData; } void CSample::setSourceData(CSeries & t_SourceData) { m_SourceData = t_SourceData; reset(); } void CSample::setDetectorData(const CSeries & t_DetectorData) { m_DetectorData = t_DetectorData; reset(); } FenestrationCommon::IntegrationType CSample::getIntegrator() const { return m_IntegrationType; } double CSample::getNormalizationCoeff() const { return m_NormalizationCoefficient; } void CSample::assignDetectorAndWavelengths(std::shared_ptr<CSample> const & t_Sample) { m_DetectorData = t_Sample->m_DetectorData; m_Wavelengths = t_Sample->m_Wavelengths; m_WavelengthSet = t_Sample->m_WavelengthSet; } void CSample::setWavelengths(WavelengthSet const t_WavelengthSet, const std::vector<double> & t_Wavelenghts) { m_WavelengthSet = t_WavelengthSet; switch(t_WavelengthSet) { case WavelengthSet::Custom: m_Wavelengths = t_Wavelenghts; break; case WavelengthSet::Source: if(m_SourceData.size() == 0) { throw std::runtime_error( "Cannot extract wavelenghts from source. Source is empty."); } m_Wavelengths = m_SourceData.getXArray(); break; case WavelengthSet::Data: m_Wavelengths = getWavelengthsFromSample(); break; default: throw std::runtime_error("Incorrect definition of wavelength set source."); break; } reset(); } double CSample::getEnergy(double const minLambda, double const maxLambda, Property const t_Property, Side const t_Side) { calculateState(); return m_EnergySource.at(std::make_pair(t_Property, t_Side)).sum(minLambda, maxLambda); } std::vector<double> CSample::getWavelengths() const { return m_Wavelengths; } double CSample::getProperty(double const minLambda, double const maxLambda, Property const t_Property, Side const t_Side) { calculateState(); auto Prop = 0.0; // Incoming energy can be calculated only if user has defined incoming source. // Otherwise just assume zero property. if(m_IncomingSource.size() > 0) { auto incomingEnergy = m_IncomingSource.sum(minLambda, maxLambda); double propertyEnergy = m_EnergySource.at(std::make_pair(t_Property, t_Side)).sum(minLambda, maxLambda); Prop = propertyEnergy / incomingEnergy; } return Prop; } CSeries & CSample::getEnergyProperties(const Property t_Property, const Side t_Side) { calculateState(); return m_EnergySource.at(std::make_pair(t_Property, t_Side)); } size_t CSample::getBandSize() const { return m_Wavelengths.size(); } void CSample::reset() { m_StateCalculated = false; m_IncomingSource = CSeries(); for(const auto & prop : EnumProperty()) { for(const auto & side : EnumSide()) { m_EnergySource[std::make_pair(prop, side)] = CSeries(); } } } void CSample::calculateState() { if(!m_StateCalculated) { if(m_WavelengthSet != WavelengthSet::Custom) { setWavelengths(m_WavelengthSet); } // In case source data are set then apply solar radiation to the calculations. // Otherwise, just use measured data. if(m_SourceData.size() > 0) { m_IncomingSource = m_SourceData.interpolate(m_Wavelengths); if(m_DetectorData.size() > 0) { const auto interpolatedDetector = m_DetectorData.interpolate(m_Wavelengths); m_IncomingSource = m_IncomingSource * interpolatedDetector; } calculateProperties(); m_IncomingSource = *m_IncomingSource.integrate(m_IntegrationType, m_NormalizationCoefficient); for(const auto & prop : EnumProperty()) { for(const auto & side : EnumSide()) { m_EnergySource[std::make_pair(prop, side)] = *m_EnergySource.at(std::make_pair(prop, side)) .integrate(m_IntegrationType, m_NormalizationCoefficient); } } m_StateCalculated = true; } } } ////////////////////////////////////////////////////////////////////////////////////// //// CSpectralSample ////////////////////////////////////////////////////////////////////////////////////// CSpectralSample::CSpectralSample(std::shared_ptr<CSpectralSampleData> const & t_SampleData, const CSeries & t_SourceData, FenestrationCommon::IntegrationType integrationType, double NormalizationCoefficient) : CSample(t_SourceData, integrationType, NormalizationCoefficient), m_SampleData(t_SampleData) { if(t_SampleData == nullptr) { throw std::runtime_error("Sample must have measured data."); } for(const auto & prop : EnumProperty()) { for(const auto & side : EnumSide()) { m_Property[std::make_pair(prop, side)] = CSeries(); } } } CSpectralSample::CSpectralSample(std::shared_ptr<CSpectralSampleData> const & t_SampleData) : CSample(), m_SampleData(t_SampleData) { if(t_SampleData == nullptr) { throw std::runtime_error("Sample must have measured data."); } for(const auto & prop : EnumProperty()) { for(const auto & side : EnumSide()) { m_Property[std::make_pair(prop, side)] = CSeries(); } } } std::shared_ptr<CSpectralSampleData> CSpectralSample::getMeasuredData() { calculateState(); // Interpolation is needed before returning the data return m_SampleData; } std::vector<double> CSpectralSample::getWavelengthsFromSample() const { return m_SampleData->getWavelengths(); } CSeries CSpectralSample::getWavelengthsProperty(const Property t_Property, const Side t_Side) { calculateState(); return m_Property.at(std::make_pair(t_Property, t_Side)); } void CSpectralSample::calculateProperties() { for(const auto & prop : EnumProperty()) { for(const auto & side : EnumSide()) { m_Property[std::make_pair(prop, side)] = m_SampleData->properties(prop, side); // No need to do interpolation if wavelength set is already from the data. if(m_WavelengthSet != WavelengthSet::Data) { m_Property[std::make_pair(prop, side)] = m_Property[std::make_pair(prop, side)].interpolate(m_Wavelengths); } } } // Calculation of energy balances for(const auto & prop : EnumProperty()) { for(const auto & side : EnumSide()) { m_EnergySource[std::make_pair(prop, side)] = m_Property.at(std::make_pair(prop, side)) * m_IncomingSource; } } } void CSpectralSample::calculateState() { CSample::calculateState(); if(m_SourceData.size() == 0) { for(const auto & prop : EnumProperty()) { for(const auto & side : EnumSide()) { m_Property[std::make_pair(prop, side)] = m_SampleData->properties(prop, side); } } m_StateCalculated = true; } } void CSpectralSample::cutExtraData(const double minLambda, const double maxLambda) { m_SampleData->cutExtraData(minLambda, maxLambda); } void CSpectralSample::Flipped(bool flipped) { m_SampleData->Filpped(flipped); } ///////////////////////////////////////////////////////////////////////////////////// /// CPhotovoltaicSample ///////////////////////////////////////////////////////////////////////////////////// CPhotovoltaicSample::CPhotovoltaicSample( const std::shared_ptr<PhotovoltaicSampleData> & t_PhotovoltaicData, const FenestrationCommon::CSeries & t_SourceData, FenestrationCommon::IntegrationType integrationType, double NormalizationCoefficient) : CSpectralSample( t_PhotovoltaicData, t_SourceData, integrationType, NormalizationCoefficient), m_JcsPrime{{Side::Front, CSeries()}, {Side::Back, CSeries()}} {} void CPhotovoltaicSample::calculateState() { CSpectralSample::calculateProperties(); for(const auto & side : EnumSide()) { const CSeries eqe{getSample()->eqe(side)}; const auto wl = getWavelengthsFromSample(); CSeries jscPrime; for(auto i = 0u; i < wl.size(); ++i) { const double pceVal = jscPrimeCalc(wl[i], eqe[i].value()); jscPrime.addProperty(wl[i], pceVal); } m_JcsPrime[side] = jscPrime; } } PhotovoltaicSampleData * CPhotovoltaicSample::getSample() const { return dynamic_cast<PhotovoltaicSampleData *>(m_SampleData.get()); } double CPhotovoltaicSample::jscPrimeCalc(double wavelength, double eqe) { double const microMeterToMeter{1e-6}; return eqe * wavelength * ConstantsData::ELECTRON_CHARGE * microMeterToMeter / (ConstantsData::SPEEDOFLIGHT * ConstantsData::PLANKCONSTANT); } FenestrationCommon::CSeries & CPhotovoltaicSample::jscPrime(const FenestrationCommon::Side side) { calculateState(); return m_JcsPrime.at(side); } } // namespace SpectralAveraging
[ "dvvidanovic@lbl.gov" ]
dvvidanovic@lbl.gov
26e8f2ff90c0516841762f150b644e502fcd1ac0
80afdd987b0a8cf093d17ca3cd45a58cd0b97ead
/std-bind/copy-semantics/copy-semantics.cpp
6d273eb136ab5876d5fd20078dbeed67bf256d79
[]
no_license
dkambam/purer-interface
de6f739c8c1d8395a64b1a27420c4aae2846133e
b425a95ce8b5450183601d0c0d8fc32511986659
refs/heads/master
2021-01-19T11:15:39.379940
2015-03-17T00:14:50
2015-03-17T00:14:50
31,994,138
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
#include <iostream> int sub(int a, int b); int main(){ int x = 10; std::function< int(void) > f; f = std::bind( sub, 29, x ); x = 20; f(); // o/p: (29 - 10) = 19 f = std::bind( sub, 29, std::ref(x) ); // std::ref avoids copy f(); // o/p: (29 - 20) = 9 return 0; } int sub(int a, int b){ int result = a - b; std::cout << "sub: " << "(" << a << " - " << b << ")" ; std::cout << " = " << result << std::endl; return result; }
[ "kdr.code@gmail.com" ]
kdr.code@gmail.com
190e39e9df0cbb5bb6cff08434721f2565aaf74e
364447971631437542a0240cfc1725eabecccc57
/Userland/Libraries/LibJS/Runtime/SymbolPrototype.h
7d0a92a5dbcda9726381994a237e98279e04b856
[ "BSD-2-Clause" ]
permissive
Jicgiebcden/serenity
aeb749fd18edb0191f5631b467ec7cd6a0e4eefb
f54a6d273e04f1739950c86dfcb026d746454f6a
refs/heads/master
2023-04-15T06:30:41.710696
2021-04-22T10:38:44
2021-04-22T11:05:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
568
h
/* * Copyright (c) 2020, Matthew Olsson <matthewcolsson@gmail.com> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <LibJS/Runtime/Object.h> namespace JS { class SymbolPrototype final : public Object { JS_OBJECT(SymbolPrototype, Object); public: explicit SymbolPrototype(GlobalObject&); virtual void initialize(GlobalObject&) override; virtual ~SymbolPrototype() override; private: JS_DECLARE_NATIVE_GETTER(description_getter); JS_DECLARE_NATIVE_FUNCTION(to_string); JS_DECLARE_NATIVE_FUNCTION(value_of); }; }
[ "kling@serenityos.org" ]
kling@serenityos.org
77210713f8502f747963a6832fc90417e0004e04
60619a8daa4603fb65f4f86f383a6ddde841e326
/2014-06-13/b.cpp
3682644ffc1f692ce807f1420d673c08b93b4f8b
[]
no_license
MYREarth/secret-weapon
f4b1d4b995951546b2fb1e40190707a805fb88b5
77f3ff1111aafaaae8f56893b78e3be9134437a9
refs/heads/master
2020-05-22T02:29:43.024017
2015-10-03T08:17:46
2015-10-03T08:17:46
186,199,326
3
0
null
2019-05-12T01:46:13
2019-05-12T01:46:13
null
UTF-8
C++
false
false
712
cpp
#include <cstdio> #include <cstring> bool vis[3010][3010]; double f[3010][3010]; int n,A,B,me; double dp(int a,int b) { if (vis[a][b]) return(f[a][b]); vis[a][b]=true; double &ret=f[a][b]; if (a+b==n) ret=0; else { int da=A-a,db=B-b; double tot=da*2.0+db+me; ret=me/tot; if (a<A) ret+=dp(a+1,b)*da*2/tot; if (b<B) ret+=dp(a,b+1)*db/tot; } return(ret); } int main() { freopen("bonus.in","r",stdin); freopen("bonus.out","w",stdout); scanf("%d%d%d",&n,&A,&B); me=2; printf("%.15f\n",dp(0,0)); memset(vis,0,sizeof(vis)); me=1; printf("%.15f\n",dp(0,0)); return(0); }
[ "ftiasch0@gmail.com" ]
ftiasch0@gmail.com
79ca4bfb5b67faa5fb3b4feb7b0d096ba7ccc137
bc287c241c7778ec33866af38f4f7919d591477e
/libraries/ADC/ADC.cpp
481877bcc96f07fee64af65e220097f174402ee1
[]
no_license
tomsmalley/strobe
11ef147664775b8b78901bb5b75c76cb1b688802
f65a0158c29370bda5164facf8b8b967a2971d23
refs/heads/master
2020-12-25T14:12:40.883073
2016-07-06T16:27:50
2016-07-06T16:27:50
60,713,867
22
2
null
null
null
null
UTF-8
C++
false
false
44,113
cpp
/* Teensy 3.x, LC ADC library * https://github.com/pedvide/ADC * Copyright (c) 2015 Pedro Villanueva * * 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. */ /* ADC.cpp: Implements the control of one or more ADC modules of Teensy 3.x, LC * */ #include "ADC.h" /* #if ADC_USE_DMA==1 uint8_t ADC::dma_Ch0 = -1; uint8_t ADC::dma_Ch1 = -1; #endif */ // translate pin number to SC1A nomenclature and viceversa // we need to create this static const arrays so that we can assign the "normal arrays" to the correct one // depending on which ADC module we will be. /* channel2sc1aADCx converts a pin number to their value for the SC1A register, for the ADC0 and ADC1 * numbers with +ADC_SC1A_PIN_MUX (128) means those pins use mux a, the rest use mux b. * numbers with +ADC_SC1A_PIN_DIFF (64) means it's also a differential pin (treated also in the channel2sc1a_diff_ADCx) * For channel2sc1a_diff_ADCx, +ADC_SC1A_PIN_PGA means the pin can use PGA on that ADC * channel2sc1a_diff uses "base A10", that is channel2sc1a_diff[0] corresponds to A10, * this assumes that the differential pins will always start at A10-A11, etc. */ #if defined(ADC_TEENSY_3_0) || defined(ADC_TEENSY_3_1) const uint8_t ADC::channel2sc1aADC0[]= { // new version, gives directly the sc1a number. 0x1F=31 deactivates the ADC. 5, 14, 8, 9, 13, 12, 6, 7, 15, 4, 0, 19, 3, 21, // 0-13, we treat them as A0-A13 5, 14, 8, 9, 13, 12, 6, 7, 15, 4, // 14-23 (A0-A9) 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, // 24-33 0+ADC_SC1A_PIN_DIFF, 19+ADC_SC1A_PIN_DIFF, 3+ADC_SC1A_PIN_DIFF, 21+ADC_SC1A_PIN_DIFF, // 34-37 (A10-A13) 26, 22, 23, 27, 29, 30 // 38-43: temp. sensor, VREF_OUT, A14, bandgap, VREFH, VREFL. A14 isn't connected to anything in Teensy 3.0. }; const uint8_t ADC::channel2sc1a_diff_ADC0[]= { 0+ADC_SC1A_PIN_PGA, 0+ADC_SC1A_PIN_PGA, 3, 3 // A10-A11 (DAD0, PGA0), A12-A13 (DAD3) }; #elif defined(ADC_TEENSY_LC) // Teensy LC const uint8_t ADC::channel2sc1aADC0[]= { // new version, gives directly the sc1a number. 0x1F=31 deactivates the ADC. 5, 14, 8, 9, 13, 12, 6, 7, 15, 11, 0, 4+ADC_SC1A_PIN_MUX, 23, 31, // 0-13, we treat them as A0-A12 + A13= doesn't exist 5, 14, 8, 9, 13, 12, 6, 7, 15, 11, // 14-23 (A0-A9) 0+ADC_SC1A_PIN_DIFF, 4+ADC_SC1A_PIN_MUX+ADC_SC1A_PIN_DIFF, 23, 31, 31, 31, 31, 31, 31, 31, // 24-33 ((A10-A12) + nothing), A11 uses mux a 31, 31, 31, 31, // 34-37 nothing 26, 31, 31, 27, 29, 30 // 38-43: temp. sensor, , , bandgap, VREFH, VREFL. }; const uint8_t ADC::channel2sc1a_diff_ADC0[]= { 0, 0, 31, 31 // A10-A11 (DAD0), A12 is single-ended and A13 doesn't exist }; #endif // defined #if defined(ADC_TEENSY_3_1) const uint8_t ADC::channel2sc1aADC1[]= { // new version, gives directly the sc1a number. 0x1F=31 deactivates the ADC. 31, 31, 8, 9, 31, 31, 31, 31, 31, 31, 3, 31, 0, 19, // 0-13, we treat them as A0-A13 31, 31, 8, 9, 31, 31, 31, 31, 31, 31, // 14-23 (A0-A9) 31, 31, // 24,25 are digital only pins 5+ADC_SC1A_PIN_MUX, 5, 4, 6, 7, 4+ADC_SC1A_PIN_MUX, 31, 31, // 26-33 26=5a, 27=5b, 28=4b, 29=6b, 30=7b, 31=4a, 32,33 are digital only 3+ADC_SC1A_PIN_DIFF, 31+ADC_SC1A_PIN_DIFF, 0+ADC_SC1A_PIN_DIFF, 19+ADC_SC1A_PIN_DIFF, // 34-37 (A10-A13) A11 isn't connected. 26, 18, 31, 27, 29, 30 // 38-43: temp. sensor, VREF_OUT, A14 (not connected), bandgap, VREFH, VREFL. }; const uint8_t ADC::channel2sc1a_diff_ADC1[]= { 3, 3, 0+ADC_SC1A_PIN_PGA, 0+ADC_SC1A_PIN_PGA // A10-A11 (DAD3), A12-A13 (DAD0, PGA1) }; #endif // translate SC1A to pin number #if defined(ADC_TEENSY_3_0) || defined(ADC_TEENSY_3_1) const uint8_t ADC::sc1a2channelADC0[]= { // new version, gives directly the pin number 34, 0, 0, 36, 23, 14, 20, 21, 16, 17, 0, 0, 19, 18, // 0-13 15, 22, 23, 0, 0, 35, 0, 37, // 14-21 39, 40, 0, 0, 38, 41, 42, 43, // VREF_OUT, A14, temp. sensor, bandgap, VREFH, VREFL. 0 // 31 means disabled, but just in case }; #elif defined(ADC_TEENSY_LC) // Teensy LC const uint8_t ADC::sc1a2channelADC0[]= { // new version, gives directly the pin number 24, 0, 0, 0, 25, 14, 20, 21, 16, 17, 0, 23, 19, 18, // 0-13 15, 22, 23, 0, 0, 0, 0, 0, // 14-21 26, 0, 0, 0, 38, 41, 0, 42, 43, // A12, temp. sensor, bandgap, VREFH, VREFL. 0 // 31 means disabled, but just in case }; #endif // defined #if defined(ADC_TEENSY_3_1) const uint8_t ADC::sc1a2channelADC1[]= { // new version, gives directly the pin number 36, 0, 0, 34, 28, 26, 29, 30, 16, 17, 0, 0, 0, 0, // 0-13. 5a=26, 5b=27, 4b=28, 4a=31 0, 0, 0, 0, 39, 37, 0, 0, // 14-21 0, 0, 0, 0, 38, 41, 0, 42, // 22-29. VREF_OUT, A14, temp. sensor, bandgap, VREFH, VREFL. 43 }; #endif ADC::ADC() { //ctor // make sure the clocks to the ADC are on SIM_SCGC6 |= SIM_SCGC6_ADC0; #if ADC_NUM_ADCS>1 SIM_SCGC3 |= SIM_SCGC3_ADC1; #endif adc0 = new ADC_Module(0, channel2sc1aADC0, channel2sc1a_diff_ADC0); #if ADC_NUM_ADCS>1 adc1 = new ADC_Module(1, channel2sc1aADC1, channel2sc1a_diff_ADC1); #endif } /* Set the voltage reference you prefer, * type can be ADC_REF_3V3, ADC_REF_1V2 (not for Teensy LC) or ADC_REF_EXT */ void ADC::setReference(uint8_t type, int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->setReference(type); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->setReference(type); // adc_num isn't changed or has selected ADC0 return; } // Change the resolution of the measurement. /* * \param bits is the number of bits of resolution. * For single-ended measurements: 8, 10, 12 or 16 bits. * For differential measurements: 9, 11, 13 or 16 bits. * If you want something in between (11 bits single-ended for example) select the inmediate higher * and shift the result one to the right. * If you select, for example, 9 bits and then do a single-ended reading, the resolution will be adjusted to 8 bits * In this case the comparison values will still be correct for analogRead and analogReadDifferential, but not * for startSingle* or startContinous*, so whenever you change the resolution, change also the comparison values. */ void ADC::setResolution(uint8_t bits, int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->setResolution(bits); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->setResolution(bits); // adc_num isn't changed or has selected ADC0 return; } //! Returns the resolution of the ADC_Module. uint8_t ADC::getResolution(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 return adc1->getResolution(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return 0; } return adc0->getResolution(); // adc_num isn't changed or has selected ADC0 } //! Returns the maximum value for a measurement. uint32_t ADC::getMaxValue(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 return adc1->getMaxValue(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return 1; } return adc0->getMaxValue(); } // Sets the conversion speed /* * \param speed can be ADC_LOW_SPEED, ADC_MED_SPEED or ADC_HIGH_SPEED * * It recalibrates at the end. */ void ADC::setConversionSpeed(uint8_t speed, int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->setConversionSpeed(speed); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->setConversionSpeed(speed); // adc_num isn't changed or has selected ADC0 return; } // Sets the sampling speed /* * \param speed can be ADC_LOW_SPEED, ADC_MED_SPEED or ADC_HIGH_SPEED * * It recalibrates at the end. */ void ADC::setSamplingSpeed(uint8_t speed, int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->setSamplingSpeed(speed); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->setSamplingSpeed(speed); // adc_num isn't changed or has selected ADC0 return; } // Set the number of averages /* * \param num can be 0, 4, 8, 16 or 32. */ void ADC::setAveraging(uint8_t num, int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->setAveraging(num); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->setAveraging(num); // adc_num isn't changed or has selected ADC0 return; } //! Enable interrupts /** An IRQ_ADC0 Interrupt will be raised when the conversion is completed * (including hardware averages and if the comparison (if any) is true). */ void ADC::enableInterrupts(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->enableInterrupts(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->enableInterrupts(); return; } //! Disable interrupts void ADC::disableInterrupts(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->disableInterrupts(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->disableInterrupts(); return; } //! Enable DMA request /** An ADC DMA request will be raised when the conversion is completed * (including hardware averages and if the comparison (if any) is true). */ void ADC::enableDMA(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->enableDMA(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->enableDMA(); return; } //! Disable ADC DMA request void ADC::disableDMA(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->disableDMA(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->disableDMA(); return; } // Enable the compare function to a single value /* A conversion will be completed only when the ADC value * is >= compValue (greaterThan=true) or < compValue (greaterThan=false) * Call it after changing the resolution * Use with interrupts or poll conversion completion with isComplete() */ void ADC::enableCompare(int16_t compValue, bool greaterThan, int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->enableCompare(compValue, greaterThan); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->enableCompare(compValue, greaterThan); return; } // Enable the compare function to a range /* A conversion will be completed only when the ADC value is inside (insideRange=1) or outside (=0) * the range given by (lowerLimit, upperLimit),including (inclusive=1) the limits or not (inclusive=0). * See Table 31-78, p. 617 of the freescale manual. * Call it after changing the resolution * Use with interrupts or poll conversion completion with isComplete() */ void ADC::enableCompareRange(int16_t lowerLimit, int16_t upperLimit, bool insideRange, bool inclusive, int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->enableCompareRange(lowerLimit, upperLimit, insideRange, inclusive); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->enableCompareRange(lowerLimit, upperLimit, insideRange, inclusive); return; } //! Disable the compare function void ADC::disableCompare(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->disableCompare(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->disableCompare(); return; } // Enable and set PGA /* Enables the PGA and sets the gain * Use only for signals lower than 1.2 V * \param gain can be 1, 2, 4, 8, 16, 32 or 64 * */ void ADC::enablePGA(uint8_t gain, int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->enablePGA(gain); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->enablePGA(gain); return; } //! Returns the PGA level /** PGA level = 2^gain, from 0 to 64 */ uint8_t ADC::getPGA(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 return adc1->getPGA(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; return 1; #endif } return adc0->getPGA(); } //! Disable PGA void ADC::disablePGA(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->disablePGA(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->disablePGA(); return; } //! Is the ADC converting at the moment? bool ADC::isConverting(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 return adc1->isConverting(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return false; } return adc0->isConverting(); } // Is an ADC conversion ready? /* * \return 1 if yes, 0 if not. * When a value is read this function returns 0 until a new value exists * So it only makes sense to call it before analogReadContinuous() or readSingle() */ bool ADC::isComplete(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 return adc1->isComplete(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return false; } return adc0->isComplete();; } //! Is the ADC in differential mode? bool ADC::isDifferential(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 return adc1->isDifferential(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return false; } return adc0->isDifferential(); } //! Is the ADC in continuous mode? bool ADC::isContinuous(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 return adc1->isContinuous(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return false; } return adc0->isContinuous(); } /* Returns the analog value of the pin. * It waits until the value is read and then returns the result. * If a comparison has been set up and fails, it will return ADC_ERROR_VALUE. * This function is interrupt safe, so it will restore the adc to the state it was before being called * If more than one ADC exists, it will select the module with less workload, you can force a selection using * adc_num. If you select ADC1 in Teensy 3.0 it will return ADC_ERROR_VALUE. */ int ADC::analogRead(uint8_t pin, int8_t adc_num) { #if ADC_NUM_ADCS==1 /* Teensy 3.0, LC */ if( adc_num==1 ) { // If asked to use ADC1, return error adc0->fail_flag |= ADC_ERROR_WRONG_ADC; return ADC_ERROR_VALUE; } return adc0->analogRead(pin); // use ADC0 #elif ADC_NUM_ADCS==2 /* Teensy 3.1 */ if( adc_num==-1 ) { // use no ADC in particular // check which ADC can read the pin bool adc0Pin = adc0->checkPin(pin); bool adc1Pin = adc1->checkPin(pin); if(adc0Pin && adc1Pin) { // Both ADCs if( (adc0->num_measurements) > (adc1->num_measurements)) { // use the ADC with less workload return adc1->analogRead(pin); } else { return adc0->analogRead(pin); } } else if(adc0Pin) { // ADC0 return adc0->analogRead(pin); } else if(adc1Pin) { // ADC1 return adc1->analogRead(pin); } else { // pin not valid in any ADC adc0->fail_flag |= ADC_ERROR_WRONG_PIN; adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return ADC_ERROR_VALUE; // all others are invalid } } else if( adc_num==0 ) { // user wants ADC0 return adc0->analogRead(pin); } else if( adc_num==1 ){ // user wants ADC 1 return adc1->analogRead(pin); } adc0->fail_flag |= ADC_ERROR_OTHER; return ADC_ERROR_VALUE; #endif } /* Reads the differential analog value of two pins (pinP - pinN). * It waits until the value is read and then returns the result. * If a comparison has been set up and fails, it will return ADC_ERROR_VALUE. * \param pinP must be A10 or A12. * \param pinN must be A11 (if pinP=A10) or A13 (if pinP=A12). * Other pins will return ADC_ERROR_VALUE. * This function is interrupt safe, so it will restore the adc to the state it was before being called * If more than one ADC exists, it will select the module with less workload, you can force a selection using * adc_num. If you select ADC1 in Teensy 3.0 it will return ADC_ERROR_VALUE. */ int ADC::analogReadDifferential(uint8_t pinP, uint8_t pinN, int8_t adc_num) { #if ADC_NUM_ADCS==1 /* Teensy 3.0, LC */ if( adc_num==1 ) { // If asked to use ADC1, return error adc0->fail_flag |= ADC_ERROR_WRONG_ADC; return ADC_ERROR_VALUE; } return adc0->analogReadDifferential(pinP, pinN); // use ADC0 #elif ADC_NUM_ADCS==2 /* Teensy 3.1 */ if( adc_num==-1 ) { // use no ADC in particular // check which ADC can read the pin bool adc0Pin = adc0->checkDifferentialPins(pinP, pinN); bool adc1Pin = adc1->checkDifferentialPins(pinP, pinN); if(adc0Pin && adc1Pin) { // Both ADCs if( (adc0->num_measurements) > (adc1->num_measurements)) { // use the ADC with less workload return adc1->analogReadDifferential(pinP, pinN); } else { return adc0->analogReadDifferential(pinP, pinN); } } else if(adc0Pin) { // ADC0 return adc0->analogReadDifferential(pinP, pinN); } else if(adc1Pin) { // ADC1 return adc1->analogReadDifferential(pinP, pinN); } else { // pins not valid in any ADC adc0->fail_flag |= ADC_ERROR_WRONG_PIN; adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return ADC_ERROR_VALUE; // all others are invalid } } else if( adc_num==0 ) { // user wants ADC0 return adc0->analogReadDifferential(pinP, pinN); } else if( adc_num==1 ){ // user wants ADC 1 return adc1->analogReadDifferential(pinP, pinN); } adc0->fail_flag |= ADC_ERROR_OTHER; return ADC_ERROR_VALUE; #endif } // Starts an analog measurement on the pin and enables interrupts. /* It returns immediately, get value with readSingle(). * If the pin is incorrect it returns ADC_ERROR_VALUE * This function is interrupt safe. The ADC interrupt will restore the adc to its previous settings and * restart the adc if it stopped a measurement. If you modify the adc_isr then this won't happen. */ bool ADC::startSingleRead(uint8_t pin, int8_t adc_num) { #if ADC_NUM_ADCS==1 /* Teensy 3.0, LC */ if( adc_num==1 ) { // If asked to use ADC1, return error adc0->fail_flag |= ADC_ERROR_WRONG_ADC; return false; } return adc0->startSingleRead(pin); // use ADC0 #elif ADC_NUM_ADCS==2 /* Teensy 3.1 */ if( adc_num==-1 ) { // use no ADC in particular // check which ADC can read the pin bool adc0Pin = adc0->checkPin(pin); bool adc1Pin = adc1->checkPin(pin); if(adc0Pin && adc1Pin) { // Both ADCs if( (adc0->num_measurements) > (adc1->num_measurements)) { // use the ADC with less workload return adc1->startSingleRead(pin); } else { return adc0->startSingleRead(pin); } } else if(adc0Pin) { // ADC0 return adc0->startSingleRead(pin); } else if(adc1Pin) { // ADC1 return adc1->startSingleRead(pin); } else { // pin not valid in any ADC adc0->fail_flag |= ADC_ERROR_WRONG_PIN; adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return false; // all others are invalid } } else if( adc_num==0 ) { // user wants ADC0 return adc0->startSingleRead(pin); } else if( adc_num==1 ){ // user wants ADC 1 return adc1->startSingleRead(pin); } adc0->fail_flag |= ADC_ERROR_OTHER; return false; #endif } // Start a differential conversion between two pins (pinP - pinN) and enables interrupts. /* It returns inmediately, get value with readSingle(). * \param pinP must be A10 or A12. * \param pinN must be A11 (if pinP=A10) or A13 (if pinP=A12). * Other pins will return ADC_ERROR_DIFF_VALUE. * This function is interrupt safe. The ADC interrupt will restore the adc to its previous settings and * restart the adc if it stopped a measurement. If you modify the adc_isr then this won't happen. */ bool ADC::startSingleDifferential(uint8_t pinP, uint8_t pinN, int8_t adc_num) { #if ADC_NUM_ADCS==1 /* Teensy 3.0, LC */ if( adc_num==1 ) { // If asked to use ADC1, return error adc0->fail_flag |= ADC_ERROR_WRONG_ADC; return false; } return adc0->startSingleDifferential(pinP, pinN); // use ADC0 #elif ADC_NUM_ADCS==2 /* Teensy 3.1 */ if( adc_num==-1 ) { // use no ADC in particular // check which ADC can read the pin bool adc0Pin = adc0->checkDifferentialPins(pinP, pinN); bool adc1Pin = adc1->checkDifferentialPins(pinP, pinN); if(adc0Pin && adc1Pin) { // Both ADCs if( (adc0->num_measurements) > (adc1->num_measurements)) { // use the ADC with less workload return adc1->startSingleDifferential(pinP, pinN); } else { return adc0->startSingleDifferential(pinP, pinN); } } else if(adc0Pin) { // ADC0 return adc0->startSingleDifferential(pinP, pinN); } else if(adc1Pin) { // ADC1 return adc1->startSingleDifferential(pinP, pinN); } else { // pins not valid in any ADC adc0->fail_flag |= ADC_ERROR_WRONG_PIN; adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return false; // all others are invalid } } else if( adc_num==0 ) { // user wants ADC0 return adc0->startSingleDifferential(pinP, pinN); } else if( adc_num==1 ){ // user wants ADC 1 return adc1->startSingleDifferential(pinP, pinN); } adc0->fail_flag |= ADC_ERROR_OTHER; return false; #endif } // Reads the analog value of a single conversion. /* Set the conversion with with startSingleRead(pin) or startSingleDifferential(pinP, pinN). * \return the converted value. */ int ADC::readSingle(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 return adc1->readSingle(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; return ADC_ERROR_VALUE; #endif } return adc0->readSingle(); } // Starts continuous conversion on the pin. /* It returns as soon as the ADC is set, use analogReadContinuous() to read the value. */ bool ADC::startContinuous(uint8_t pin, int8_t adc_num) { #if ADC_NUM_ADCS==1 /* Teensy 3.0, LC */ if( adc_num==1 ) { // If asked to use ADC1, return error adc0->fail_flag |= ADC_ERROR_WRONG_ADC; return false; } return adc0->startContinuous(pin); // use ADC0 #elif ADC_NUM_ADCS==2 /* Teensy 3.1 */ if( adc_num==-1 ) { // use no ADC in particular // check which ADC can read the pin bool adc0Pin = adc0->checkPin(pin); bool adc1Pin = adc1->checkPin(pin); if(adc0Pin && adc1Pin) { // Both ADCs if( (adc0->num_measurements) > (adc1->num_measurements)) { // use the ADC with less workload return adc1->startContinuous(pin); } else { return adc0->startContinuous(pin); } } else if(adc0Pin) { // ADC0 return adc0->startContinuous(pin); } else if(adc1Pin) { // ADC1 return adc1->startContinuous(pin); } else { // pin not valid in any ADC adc0->fail_flag |= ADC_ERROR_WRONG_PIN; adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return false; // all others are invalid } } else if( adc_num==0 ) { // user wants ADC0 return adc0->startContinuous(pin); } else if( adc_num==1 ){ // user wants ADC 1 return adc1->startContinuous(pin); } adc0->fail_flag |= ADC_ERROR_OTHER; return false; #endif } // Starts continuous conversion between the pins (pinP-pinN). /* It returns as soon as the ADC is set, use analogReadContinuous() to read the value. * \param pinP must be A10 or A12. * \param pinN must be A11 (if pinP=A10) or A13 (if pinP=A12). * Other pins will return ADC_ERROR_DIFF_VALUE. */ bool ADC::startContinuousDifferential(uint8_t pinP, uint8_t pinN, int8_t adc_num) { #if ADC_NUM_ADCS==1 /* Teensy 3.0, LC */ if( adc_num==1 ) { // If asked to use ADC1, return error adc0->fail_flag |= ADC_ERROR_WRONG_ADC; return false; } return adc0->startContinuousDifferential(pinP, pinN); // use ADC0 #elif ADC_NUM_ADCS==2 /* Teensy 3.1 */ if( adc_num==-1 ) { // use no ADC in particular // check which ADC can read the pin bool adc0Pin = adc0->checkDifferentialPins(pinP, pinN); bool adc1Pin = adc1->checkDifferentialPins(pinP, pinN); if(adc0Pin && adc1Pin) { // Both ADCs if( (adc0->num_measurements) > (adc1->num_measurements)) { // use the ADC with less workload return adc1->startContinuousDifferential(pinP, pinN); } else { return adc0->startContinuousDifferential(pinP, pinN); } } else if(adc0Pin) { // ADC0 return adc0->startContinuousDifferential(pinP, pinN); } else if(adc1Pin) { // ADC1 return adc1->startContinuousDifferential(pinP, pinN); } else { // pins not valid in any ADC adc0->fail_flag |= ADC_ERROR_WRONG_PIN; adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return false; // all others are invalid } } else if( adc_num==0 ) { // user wants ADC0 return adc0->startContinuousDifferential(pinP, pinN); } else if( adc_num==1 ){ // user wants ADC 1 return adc1->startContinuousDifferential(pinP, pinN); } adc0->fail_flag |= ADC_ERROR_OTHER; return false; #endif } //! Reads the analog value of a continuous conversion. /** Set the continuous conversion with with analogStartContinuous(pin) or startContinuousDifferential(pinP, pinN). * \return the last converted value. * If single-ended and 16 bits it's necessary to typecast it to an unsigned type (like uint16_t), * otherwise values larger than 3.3/2 V are interpreted as negative! */ int ADC::analogReadContinuous(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 return adc1->analogReadContinuous(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return false; } return adc0->analogReadContinuous(); } //! Stops continuous conversion void ADC::stopContinuous(int8_t adc_num) { if(adc_num==1){ // user wants ADC 1, do nothing if it's a Teensy 3.0 #if ADC_NUM_ADCS>=2 // Teensy 3.1 adc1->stopContinuous(); #else adc0->fail_flag |= ADC_ERROR_WRONG_ADC; #endif return; } adc0->stopContinuous(); return; } //////////////// SYNCHRONIZED BLOCKING METHODS ////////////////// ///// IF THE BOARD HAS ONLY ONE ADC, THEY ARE EMPYT METHODS ///// ///////////////////////////////////////////////////////////////// #if ADC_NUM_ADCS>1 /*Returns the analog values of both pins, measured at the same time by the two ADC modules. * It waits until the value is read and then returns the result as a struct Sync_result, * use Sync_result.result_adc0 and Sync_result.result_adc1. * If a comparison has been set up and fails, it will return ADC_ERROR_VALUE in both fields of the struct. */ ADC::Sync_result ADC::analogSynchronizedRead(uint8_t pin0, uint8_t pin1) { Sync_result res = {ADC_ERROR_VALUE, ADC_ERROR_VALUE}; // check pins if ( !adc0->checkPin(pin0) ) { adc0->fail_flag |= ADC_ERROR_WRONG_PIN; return res; } if ( !adc1->checkPin(pin1) ) { adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return res; } // check if we are interrupting a measurement, store setting if so. // vars to save the current state of the ADC in case it's in use ADC_Module::ADC_Config old_adc0_config = {0}; uint8_t wasADC0InUse = adc0->isConverting(); // is the ADC running now? if(wasADC0InUse) { // this means we're interrupting a conversion // save the current conversion config, the adc isr will restore the adc __disable_irq(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc0->saveConfig(&old_adc0_config); __enable_irq(); } ADC_Module::ADC_Config old_adc1_config = {0}; uint8_t wasADC1InUse = adc1->isConverting(); // is the ADC running now? if(wasADC1InUse) { // this means we're interrupting a conversion // save the current conversion config, the adc isr will restore the adc __disable_irq(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc1->saveConfig(&old_adc1_config); __enable_irq(); } // no continuous mode adc0->singleMode(); adc1->singleMode(); // start both measurements adc0->startReadFast(pin0); adc1->startReadFast(pin1); // wait for both ADCs to finish while( (adc0->isConverting()) || (adc1->isConverting()) ) { // wait for both to finish yield(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); } __disable_irq(); // make sure nothing interrupts this part if ( adc0->isComplete() ) { // conversion succeded res.result_adc0 = adc0->readSingle(); } else { // comparison was false adc0->fail_flag |= ADC_ERROR_COMPARISON; } if ( adc1->isComplete() ) { // conversion succeded res.result_adc1 = adc1->readSingle(); } else { // comparison was false adc1->fail_flag |= ADC_ERROR_COMPARISON; } __enable_irq(); // if we interrupted a conversion, set it again if (wasADC0InUse) { //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc0->loadConfig(&old_adc0_config); } if (wasADC1InUse) { //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc1->loadConfig(&old_adc1_config); } //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); return res; } /*Returns the diff analog values of both sets of pins, measured at the same time by the two ADC modules. * It waits until the value is read and then returns the result as a struct Sync_result, * use Sync_result.result_adc0 and Sync_result.result_adc1. * If a comparison has been set up and fails, it will return ADC_ERROR_VALUE in both fields of the struct. */ ADC::Sync_result ADC::analogSynchronizedReadDifferential(uint8_t pin0P, uint8_t pin0N, uint8_t pin1P, uint8_t pin1N) { Sync_result res = {ADC_ERROR_VALUE, ADC_ERROR_VALUE};; // check pins if(!adc0->checkDifferentialPins(pin0P, pin0N)) { adc0->fail_flag |= ADC_ERROR_WRONG_PIN; return res; // all others are invalid } if(!adc1->checkDifferentialPins(pin1P, pin1N)) { adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return res; // all others are invalid } // check if we are interrupting a measurement, store setting if so. // vars to save the current state of the ADC in case it's in use ADC_Module::ADC_Config old_adc0_config = {0}; uint8_t wasADC0InUse = adc0->isConverting(); // is the ADC running now? if(wasADC0InUse) { // this means we're interrupting a conversion // save the current conversion config, the adc isr will restore the adc __disable_irq(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc0->saveConfig(&old_adc0_config); __enable_irq(); } ADC_Module::ADC_Config old_adc1_config = {0}; uint8_t wasADC1InUse = adc1->isConverting(); // is the ADC running now? if(wasADC1InUse) { // this means we're interrupting a conversion // save the current conversion config, the adc isr will restore the adc __disable_irq(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc1->saveConfig(&old_adc1_config); __enable_irq(); } // no continuous mode adc0->singleMode(); adc1->singleMode(); // start both measurements adc0->startDifferentialFast(pin0P, pin0N); adc1->startDifferentialFast(pin1P, pin1N); // wait for both ADCs to finish while( (adc0->isConverting()) || (adc1->isConverting()) ) { yield(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); } __disable_irq(); // make sure nothing interrupts this part if (adc0->isComplete()) { // conversion succeded res.result_adc0 = adc0->readSingle(); } else { // comparison was false adc0->fail_flag |= ADC_ERROR_COMPARISON; } if (adc1->isComplete()) { // conversion succeded res.result_adc1 = adc1->readSingle(); } else { // comparison was false adc1->fail_flag |= ADC_ERROR_COMPARISON; } __enable_irq(); // if we interrupted a conversion, set it again if (wasADC0InUse) { //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc0->loadConfig(&old_adc0_config); } if (wasADC1InUse) { //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc1->loadConfig(&old_adc1_config); } //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); return res; } /////////////// SYNCHRONIZED NON-BLOCKING METHODS ////////////// // Starts an analog measurement at the same time on the two ADC modules /* It returns inmediately, get value with readSynchronizedSingle(). * If the pin is incorrect it returns false * If this function interrupts a measurement, it stores the settings in adc_config */ bool ADC::startSynchronizedSingleRead(uint8_t pin0, uint8_t pin1) { // check pins if ( !adc0->checkPin(pin0) ) { adc0->fail_flag |= ADC_ERROR_WRONG_PIN; return false; } if ( !adc1->checkPin(pin1) ) { adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return false; } // check if we are interrupting a measurement, store setting if so. adc0->adcWasInUse = adc0->isConverting(); // is the ADC running now? if(adc0->adcWasInUse) { // this means we're interrupting a conversion // save the current conversion config, the adc isr will restore the adc __disable_irq(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc0->saveConfig(&adc0->adc_config); __enable_irq(); } adc1->adcWasInUse = adc1->isConverting(); // is the ADC running now? if(adc1->adcWasInUse) { // this means we're interrupting a conversion // save the current conversion config, the adc isr will restore the adc __disable_irq(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc1->saveConfig(&adc1->adc_config); __enable_irq(); } // no continuous mode adc0->singleMode(); adc1->singleMode(); // start both measurements adc0->startReadFast(pin0); adc1->startReadFast(pin1); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); return true; } // Start a differential conversion between two pins (pin0P - pin0N) and (pin1P - pin1N) /* It returns inmediately, get value with readSynchronizedSingle(). * \param pinP must be A10 or A12. * \param pinN must be A11 (if pinP=A10) or A13 (if pinP=A12). * Other pins will return false. * If this function interrupts a measurement, it stores the settings in adc_config */ bool ADC::startSynchronizedSingleDifferential(uint8_t pin0P, uint8_t pin0N, uint8_t pin1P, uint8_t pin1N) { // check pins if(!adc0->checkDifferentialPins(pin0P, pin0N)) { adc0->fail_flag |= ADC_ERROR_WRONG_PIN; return false; // all others are invalid } if(!adc1->checkDifferentialPins(pin1P, pin1N)) { adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return false; // all others are invalid } // check if we are interrupting a measurement, store setting if so. adc0->adcWasInUse = adc0->isConverting(); // is the ADC running now? if(adc0->adcWasInUse) { // this means we're interrupting a conversion // save the current conversion config, the adc isr will restore the adc __disable_irq(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc0->saveConfig(&adc0->adc_config); __enable_irq(); } adc1->adcWasInUse = adc1->isConverting(); // is the ADC running now? if(adc1->adcWasInUse) { // this means we're interrupting a conversion // save the current conversion config, the adc isr will restore the adc __disable_irq(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc1->saveConfig(&adc1->adc_config); __enable_irq(); } // no continuous mode adc0->singleMode(); adc1->singleMode(); // start both measurements adc0->startDifferentialFast(pin0P, pin0N); adc1->startDifferentialFast(pin1P, pin1N); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); return true; } // Reads the analog value of a single conversion. /* * \return the converted value. */ ADC::Sync_result ADC::readSynchronizedSingle() { ADC::Sync_result res; res.result_adc0 = adc0->readSingle(); res.result_adc1 = adc1->readSingle(); return res; } ///////////// SYNCHRONIZED CONTINUOUS CONVERSION METHODS //////////// //! Starts a continuous conversion in both ADCs simultaneously /** Use readSynchronizedContinuous to get the values * */ bool ADC::startSynchronizedContinuous(uint8_t pin0, uint8_t pin1) { // check pins if ( !adc0->checkPin(pin0) ) { adc0->fail_flag |= ADC_ERROR_WRONG_PIN; return false; } if ( !adc1->checkPin(pin1) ) { adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return false; } adc0->startContinuous(pin0); adc1->startContinuous(pin1); // setup the conversions the usual way, but to make sure that they are // as synchronized as possible we stop and restart them one after the other. const uint32_t temp_ADC0_SC1A = ADC0_SC1A; ADC0_SC1A = 0x1F; const uint32_t temp_ADC1_SC1A = ADC1_SC1A; ADC1_SC1A = 0x1F; __disable_irq(); // both measurements should have a maximum delay of an instruction time ADC0_SC1A = temp_ADC0_SC1A; ADC1_SC1A = temp_ADC1_SC1A; __enable_irq(); return true; } //! Starts a continuous differential conversion in both ADCs simultaneously /** Use readSynchronizedContinuous to get the values * */ bool ADC::startSynchronizedContinuousDifferential(uint8_t pin0P, uint8_t pin0N, uint8_t pin1P, uint8_t pin1N) { // check pins if(!adc0->checkDifferentialPins(pin0P, pin0N)) { adc0->fail_flag |= ADC_ERROR_WRONG_PIN; return false; // all others are invalid } if(!adc1->checkDifferentialPins(pin1P, pin1N)) { adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return false; // all others are invalid } adc0->startContinuousDifferential(pin0P, pin0N); adc1->startContinuousDifferential(pin1P, pin1N); // setup the conversions the usual way, but to make sure that they are // as synchronized as possible we stop and restart them one after the other. const uint32_t temp_ADC0_SC1A = ADC0_SC1A; ADC0_SC1A = 0x1F; const uint32_t temp_ADC1_SC1A = ADC1_SC1A; ADC1_SC1A = 0x1F; __disable_irq(); ADC0_SC1A = temp_ADC0_SC1A; ADC1_SC1A = temp_ADC1_SC1A; __enable_irq(); return true; } //! Returns the values of both ADCs. ADC::Sync_result ADC::readSynchronizedContinuous() { ADC::Sync_result res; res.result_adc0 = adc0->analogReadContinuous(); res.result_adc1 = adc1->analogReadContinuous(); return res; } //! Stops synchronous continuous conversion void ADC::stopSynchronizedContinuous() { adc0->stopContinuous(); adc1->stopContinuous(); } #else // ADC_NUM_ADCS=1 // Empty definitions so code written for all Teensy will compile ADC::Sync_result ADC::analogSynchronizedRead(uint8_t pin0, uint8_t pin1) {ADC::Sync_result res={0}; return res;} ADC::Sync_result ADC::analogSynchronizedReadDifferential(uint8_t pin0P, uint8_t pin0N, uint8_t pin1P, uint8_t pin1N) { ADC::Sync_result res={0}; return res; } bool ADC::startSynchronizedSingleRead(uint8_t pin0, uint8_t pin1) { return false; } bool ADC::startSynchronizedSingleDifferential(uint8_t pin0P, uint8_t pin0N, uint8_t pin1P, uint8_t pin1N) { return false; } ADC::Sync_result ADC::readSynchronizedSingle() {ADC::Sync_result res={0}; return res;} bool ADC::startSynchronizedContinuous(uint8_t pin0, uint8_t pin1) {return false;} bool ADC::startSynchronizedContinuousDifferential(uint8_t pin0P, uint8_t pin0N, uint8_t pin1P, uint8_t pin1N) {return false;} ADC::Sync_result ADC::readSynchronizedContinuous() {ADC::Sync_result res={0}; return res;} void ADC::stopSynchronizedContinuous() {} #endif
[ "tfsmalley@gmail.com" ]
tfsmalley@gmail.com
d90917b0c97a5053f752d85b996b6de6977b8f3b
cdd97aba68281f2a862d8441c9ec0456bf108163
/benchmarks/src/453.povray/src/objects.cpp
f53b5f219b325a8ccfd01040b89ac4874709f1a1
[]
no_license
elbrandt/CS752_Proj
894cf78096d8d8916c30acfbadda36729e69006a
546a5d0602211fcf8b93492e3cabf61dce6194c0
refs/heads/main
2023-02-02T07:33:15.191093
2020-12-16T02:44:18
2020-12-16T02:44:18
312,392,830
1
1
null
null
null
null
UTF-8
C++
false
false
17,197
cpp
/**************************************************************************** * objects.cpp * * This module implements the methods for objects and composite objects. * * from Persistence of Vision(tm) Ray Tracer version 3.6. * Copyright 1991-2003 Persistence of Vision Team * Copyright 2003-2004 Persistence of Vision Raytracer Pty. Ltd. *--------------------------------------------------------------------------- * NOTICE: This source code file is provided so that users may experiment * with enhancements to POV-Ray and to port the software to platforms other * than those supported by the POV-Ray developers. There are strict rules * regarding how you are permitted to use this file. These rules are contained * in the distribution and derivative versions licenses which should have been * provided with this file. * * These licences may be found online, linked from the end-user license * agreement that is located at http://www.povray.org/povlegal.html *--------------------------------------------------------------------------- * This program is based on the popular DKB raytracer version 2.12. * DKBTrace was originally written by David K. Buck. * DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins. *--------------------------------------------------------------------------- * $File: //depot/povray/3.5/source/objects.cpp $ * $Revision: #26 $ * $Change: 3010 $ * $DateTime: 2004/07/27 14:06:43 $ * $Author: thorsten $ * $Log$ *****************************************************************************/ #include "frame.h" #include "povray.h" #include "vector.h" #include "interior.h" #include "objects.h" #include "texture.h" #include "matrices.h" BEGIN_POV_NAMESPACE /***************************************************************************** * Local preprocessor defines ******************************************************************************/ /***************************************************************************** * Local typedefs ******************************************************************************/ /***************************************************************************** * Local variables ******************************************************************************/ unsigned int Number_of_istacks = 0; // GLOBAL VARIABLE unsigned int Max_Intersections = 64; // GLOBAL VARIABLE ISTACK *free_istack; // GLOBAL VARIABLE /***************************************************************************** * Static functions ******************************************************************************/ static OBJECT *Copy_Bound_Clip (OBJECT *Old); static void create_istack (void); /***************************************************************************** * * FUNCTION * * Intersection * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ bool Intersection (INTERSECTION *Ray_Intersection, OBJECT *Object, RAY *Ray) { ISTACK *Depth_Stack; INTERSECTION *Local; DBL Closest = HUGE_VAL; if (Object == NULL) { return (false); } if (!Ray_In_Bound (Ray,Object->Bound)) { return (false); } Depth_Stack = open_istack (); if (All_Intersections (Object, Ray, Depth_Stack)) { while ((Local = pop_entry(Depth_Stack)) != NULL) { if (Local->Depth < Closest) { *Ray_Intersection = *Local; Closest = Local->Depth; } } close_istack (Depth_Stack); return (true); } else { close_istack (Depth_Stack); return (false); } } /***************************************************************************** * * FUNCTION * * Inside_Object * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ bool Inside_Object (VECTOR IPoint, OBJECT *Object) { OBJECT *Sib; for (Sib = Object->Clip; Sib != NULL; Sib = Sib->Sibling) { if (!Inside_Object(IPoint, Sib)) { return(false); } } return (Inside(IPoint,Object)); } /***************************************************************************** * * FUNCTION * * Ray_In_Bound * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ bool Ray_In_Bound (RAY *Ray, OBJECT *Bounding_Object) { OBJECT *Bound; INTERSECTION Local; for (Bound = Bounding_Object; Bound != NULL; Bound = Bound->Sibling) { Increase_Counter(stats[Bounding_Region_Tests]); if (!Intersection (&Local, Bound, Ray)) { if (!Inside_Object(Ray->Initial, Bound)) { return (false); } } Increase_Counter(stats[Bounding_Region_Tests_Succeeded]); } return (true); } /***************************************************************************** * * FUNCTION * * Point_In_Clip * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ bool Point_In_Clip (VECTOR IPoint, OBJECT *Clip) { OBJECT *Local_Clip; for (Local_Clip = Clip; Local_Clip != NULL; Local_Clip = Local_Clip->Sibling) { Increase_Counter(stats[Clipping_Region_Tests]); if (!Inside_Object(IPoint, Local_Clip)) { return (false); } Increase_Counter(stats[Clipping_Region_Tests_Succeeded]); } return (true); } /***************************************************************************** * * FUNCTION * * Translate_Object * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void Translate_Object (OBJECT *Object, VECTOR Vector, TRANSFORM *Trans) { OBJECT *Sib; if (Object == NULL) { return; } for (Sib = Object->Bound; Sib != NULL; Sib = Sib->Sibling) { Translate_Object(Sib, Vector, Trans); } if (Object->Clip != Object->Bound) { for (Sib = Object->Clip; Sib != NULL; Sib = Sib->Sibling) { Translate_Object(Sib, Vector, Trans); } } /* NK 1998 added if */ if (!Test_Flag(Object, UV_FLAG)) { Transform_Textures(Object->Texture, Trans); Transform_Textures(Object->Interior_Texture, Trans); } if (Object->UV_Trans == NULL) Object->UV_Trans = Create_Transform(); Compose_Transforms(Object->UV_Trans, Trans); Transform_Interior(Object->Interior, Trans); Translate(Object, Vector, Trans); } /***************************************************************************** * * FUNCTION * * Rotate_Object * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void Rotate_Object (OBJECT *Object, VECTOR Vector, TRANSFORM *Trans) { OBJECT *Sib; if (Object == NULL) { return; } for (Sib = Object->Bound; Sib != NULL; Sib = Sib->Sibling) { Rotate_Object(Sib, Vector, Trans); } if (Object->Clip != Object->Bound) { for (Sib = Object->Clip; Sib != NULL; Sib = Sib->Sibling) { Rotate_Object(Sib, Vector, Trans); } } /* NK 1998 added if */ if (!Test_Flag(Object, UV_FLAG)) { Transform_Textures(Object->Texture, Trans); Transform_Textures(Object->Interior_Texture, Trans); } if (Object->UV_Trans == NULL) Object->UV_Trans = Create_Transform(); Compose_Transforms(Object->UV_Trans, Trans); Transform_Interior(Object->Interior, Trans); Rotate(Object, Vector, Trans); } /***************************************************************************** * * FUNCTION * * Scale_Object * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void Scale_Object (OBJECT *Object, VECTOR Vector, TRANSFORM *Trans) { OBJECT *Sib; if (Object == NULL) { return; } for (Sib = Object->Bound; Sib != NULL; Sib = Sib->Sibling) { Scale_Object(Sib, Vector, Trans); } if (Object->Clip != Object->Bound) { for (Sib = Object->Clip; Sib != NULL; Sib = Sib->Sibling) { Scale_Object(Sib, Vector, Trans); } } /* NK 1998 added if */ if (!Test_Flag(Object, UV_FLAG)) { Transform_Textures(Object->Texture, Trans); Transform_Textures(Object->Interior_Texture, Trans); } if (Object->UV_Trans == NULL) Object->UV_Trans = Create_Transform(); Compose_Transforms(Object->UV_Trans, Trans); Transform_Interior(Object->Interior, Trans); Scale(Object, Vector, Trans); } /***************************************************************************** * * FUNCTION * * Transform_Object * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void Transform_Object (OBJECT *Object, TRANSFORM *Trans) { OBJECT *Sib; if (Object == NULL) { return; } for (Sib = Object->Bound; Sib != NULL; Sib = Sib->Sibling) { Transform_Object(Sib, Trans); } if (Object->Clip != Object->Bound) { for (Sib = Object->Clip; Sib != NULL; Sib = Sib->Sibling) { Transform_Object(Sib, Trans); } } /* NK 1998 added if */ if (!Test_Flag(Object, UV_FLAG)) { Transform_Textures(Object->Texture, Trans); Transform_Textures(Object->Interior_Texture, Trans); } if (Object->UV_Trans == NULL) Object->UV_Trans = Create_Transform(); Compose_Transforms(Object->UV_Trans, Trans); Transform_Interior(Object->Interior, Trans); Transform(Object,Trans); } /***************************************************************************** * * FUNCTION * * Invert_Object * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void Invert_Object (OBJECT *Object) { if (Object == NULL) { return; } Invert (Object); } /***************************************************************************** * * FUNCTION * * Copy_Bound_Clip * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ static OBJECT *Copy_Bound_Clip (OBJECT *Old) { OBJECT *Current, *New, *Prev, *First; First = Prev = NULL; for (Current = Old; Current != NULL; Current = Current->Sibling) { New = Copy_Object (Current); if (First == NULL) { First = New; } if (Prev != NULL) { Prev->Sibling = New; } Prev = New; } return (First); } /***************************************************************************** * * FUNCTION * * Copy_Object * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ OBJECT *Copy_Object (OBJECT *Old) { OBJECT *New; if (Old == NULL) { return (NULL); } New = (OBJECT *)Copy(Old); /* * The following copying of OBJECT_FIELDS is redundant if Copy * did *New = *Old but we cannot assume it did. It is safe for * Copy to do *New = *Old but it should not otherwise * touch OBJECT_FIELDS. */ New->Methods = Old->Methods; New->Type = Old->Type; New->Sibling = Old->Sibling; New->Texture = Old->Texture; New->Bound = Old->Bound; New->Clip = Old->Clip; New->BBox = Old->BBox; New->Flags = Old->Flags; New->LLights = NULL; /* Important */ New->Sibling = NULL; /* Important */ New->Texture = Copy_Textures (Old->Texture); New->Interior_Texture = Copy_Textures (Old->Interior_Texture); New->Bound = Copy_Bound_Clip (Old->Bound); New->Interior = Copy_Interior(Old->Interior); /* NK 1998 */ New->UV_Trans = Copy_Transform(Old->UV_Trans); /* NK ---- */ if (Old->Bound != Old->Clip) { New->Clip = Copy_Bound_Clip (Old->Clip); } else { New->Clip = New->Bound; } return (New); } /***************************************************************************** * * FUNCTION * * Destroy_Object * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void Destroy_Single_Object (OBJECT **ObjectPtr) { OBJECT *Object; Object = *ObjectPtr; Destroy_Textures(Object->Texture); Destroy_Object(Object->Bound); Destroy_Interior((INTERIOR *)Object->Interior); /* NK 1998 */ Destroy_Transform(Object->UV_Trans); Destroy_Object (Object->Bound); Destroy_Interior((INTERIOR *)Object->Interior); if (Object->Bound != Object->Clip) { Destroy_Object(Object->Clip); } *ObjectPtr = Object->Sibling; Destroy(Object); } void Destroy_Object (OBJECT *Object) { OBJECT *Sib; while (Object != NULL) { Destroy_Textures(Object->Texture); Destroy_Textures(Object->Interior_Texture); Destroy_Object(Object->Bound); Destroy_Interior((INTERIOR *)Object->Interior); /* NK 1998 */ Destroy_Transform(Object->UV_Trans); if (Object->Bound != Object->Clip) { Destroy_Object(Object->Clip); } Sib = Object->Sibling; Destroy(Object); Object = Sib; } } /***************************************************************************** * * FUNCTION * * create_istack * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ static void create_istack() { ISTACK *New; int i; New = (ISTACK *)POV_MALLOC(sizeof (ISTACK), "istack"); New->next = free_istack; free_istack = New; New->istack = (INTERSECTION *)POV_MALLOC(Max_Intersections * sizeof (INTERSECTION), "istack entries"); New->max_entries = Max_Intersections; // make sure we have valid NULL pointers [trf] for(i = 0; i < New->max_entries; i++) New->istack[i].Object = NULL; Number_of_istacks++; } /***************************************************************************** * * FUNCTION * * Destroy_IStacks * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void Destroy_IStacks() { ISTACK *istk, *temp; istk = free_istack; while (istk != NULL) { temp = istk; istk = istk->next; POV_FREE (temp->istack); POV_FREE (temp); } free_istack = NULL; } /***************************************************************************** * * FUNCTION * * open_sstack * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ ISTACK *open_istack() { ISTACK *istk; if (free_istack == NULL) { create_istack (); } istk = free_istack; free_istack = istk->next; istk->top_entry = 0; return (istk); } /***************************************************************************** * * FUNCTION * * close_istack * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void close_istack (ISTACK *istk) { istk->next = free_istack; free_istack = istk; } /***************************************************************************** * * FUNCTION * * incstack * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * POV-Ray Team * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void incstack(ISTACK *istk) { if(++istk->top_entry >= istk->max_entries) { istk->top_entry--; Increase_Counter(stats[Istack_overflows]); } } /***************************************************************************** * * FUNCTION * * Default_UVCoord * * INPUT * * Object - Pointer to blob structure * Inter - Pointer to intersection * * OUTPUT * * * RETURNS * * AUTHOR * * Nathan Kopp * * DESCRIPTION * This is used as a default UVCoord function for objects where UVCoordinates * are not defined. It instead returns the XY coordinates of the intersection. * * CHANGES * * ******************************************************************************/ void Default_UVCoord(UV_VECT Result, OBJECT * /*Object*/, INTERSECTION *Inter) { Result[U] = Inter->IPoint[X]; Result[V] = Inter->IPoint[Y]; } END_POV_NAMESPACE
[ "eric.l.brandt@gmail.com" ]
eric.l.brandt@gmail.com
edfd45a73fd6b8a60b59c00e225cbee75767aa25
1ea8698c8b7a447e172f146c3fa61a686c4862ef
/src/main.cpp
bacf0678f1a1b078e5efa02427626f32ed2a85de
[]
no_license
deniskorobicyn/dip-cpp
db1d44e62c8c07012746f8300d82b22171a4bf4b
9b421063d3e5416b51f21d97a400a1d7913f70ae
refs/heads/master
2020-05-23T10:22:45.129642
2017-09-07T19:38:47
2017-09-07T19:38:47
80,429,199
2
0
null
null
null
null
UTF-8
C++
false
false
506
cpp
#include <iostream> #include <stdio.h> /* defines FILENAME_MAX */ #include "yaml-cpp/yaml.h" #include "arguments.h" #include "dip.h" using namespace dip; int main(int argc, char **argv, char** envp) { Arguments args(argc, argv, envp); if (1 == args.parse()) { std::cout << args.error_message() << std::endl; return 1; } Dip dip(std::make_shared<Arguments>(args)); try { dip.execute(); } catch (YAML::BadFile e) { std::cout << "File dip.yml is not found" << std::endl; } return 0; }
[ "deniskorobitcin@gmail.com" ]
deniskorobitcin@gmail.com
96a58bc8d4fd4762701890e6efd067f045b66fc1
ed6cc29968179d13bb30c73dbf2be2fb6469d495
/pizza/Pizzeria_86_Programma/OrderUI.cpp
6d4603d222fe3d81888e45865ea6988d804cd252
[]
no_license
sindri69/pizza420
e0880eea7eb0dbdeabae3dc675dba732a1778d90
a0f78b59b5830ff67e9b5456a6e6d229869628f5
refs/heads/master
2021-08-28T14:59:32.423484
2017-12-12T14:19:05
2017-12-12T14:19:05
112,332,570
0
0
null
null
null
null
UTF-8
C++
false
false
1,849
cpp
#include <iostream> #include <fstream> #include "MainUI.h" #include "OrderUI.h" #include "Pizza.h" using namespace std; OrderUI::OrderUI() { //ctor } OrderUI::~OrderUI() { //dtor } void OrderUI::start_orderUI() { char selection = '\0'; while (selection != 'q') { cout << "Pizzeria_86_Programma (Orders)" << endl; cout << "1: Add Order" << endl; cout << "2: See list of all Orders" << endl; cout << "3: Return to Main" << endl; cin >> selection; if (selection == '1') { int choice; cout << "How many pizzas do you wish to add to the list? "; cin >> choice; for (int i = 0; i < choice; i++) { Pizza pizza; pizza.setVerbose(true); cin >> pizza; ofstream fout; fout.open("pizza_list.txt", ios::app); pizza.setVerbose(false); fout << pizza; fout.close(); } } else if (selection == '2') { Pizza pizza; ifstream fin; fin.open("pizza_list.txt"); if (fin.is_open()) { int number_of_lines = 0; std::string line; std::ifstream myfile("pizza_list.txt"); while (std::getline(myfile, line)) ++number_of_lines; for (int i = 0; i < (number_of_lines / 2); i++) { pizza.setVerbose(false); fin >> pizza; pizza.setVerbose(true); cout << pizza; } } else { cout << "Could not find pizza list" << endl; } } else if (selection == '3') { selection = 'q'; } } }
[ "sindrii17@ru.ism" ]
sindrii17@ru.ism
165a81454f3fe79f9174a0cec1d1b961fdf8fc18
4be7a3f1465554edc9b31aacc2692daac51c46aa
/SEMPHY/lib/betaDistribution.cpp
9d62f7c53a857b9861cc277658a0cd406738bcb9
[]
no_license
kbavishi/MineBench
b90eaeb485b736cb80a4a5a7d09f966ef3eedf9d
74a8ef895a07f32164b20876798560f02f2b561e
refs/heads/master
2021-01-18T23:13:07.585731
2017-04-17T21:29:44
2017-04-17T21:29:44
87,095,090
2
0
null
null
null
null
UTF-8
C++
false
false
3,301
cpp
// $Id: betaDistribution.cpp 2399 2014-03-13 22:43:51Z wkliao $ #include "betaDistribution.h" #include "gammaUtilities.h" #include "betaUtilities.h" #include "errorMsg.h" #include "logFile.h" #include <cmath> betaDistribution::betaDistribution() { _alpha = 0.0; _beta = 0.0; _boundary.resize(0,0); _rates.resize(0,0); _ratesProb.resize(0,0); _globalRate = 1;//??? 0.5 or 1 } // note that the order of initalization makes a diffrence. betaDistribution::betaDistribution(const betaDistribution& other) : _boundary(other._boundary), _alpha(other._alpha), _beta(other._beta), _rates(other._rates), _ratesProb(other._ratesProb), _globalRate(other._globalRate) { } betaDistribution::betaDistribution(MDOUBLE alpha,MDOUBLE beta,int in_number_of_categories) :distribution(){ _globalRate=1.0; setBetaParameters(in_number_of_categories,alpha,beta); } betaDistribution::~betaDistribution() { _boundary.clear(); _rates.clear(); _ratesProb.clear(); } void betaDistribution::setAlpha(MDOUBLE in_alpha) { if (in_alpha == _alpha) return; setBetaParameters(categories(), in_alpha, _beta); } void betaDistribution::setBeta(MDOUBLE in_beta) { if (in_beta == _beta) return; setBetaParameters( categories(), _alpha, in_beta); } void betaDistribution::change_number_of_categories(int in_number_of_categories) { if (in_number_of_categories == categories()) return; setBetaParameters( in_number_of_categories, _alpha, _beta); } void betaDistribution::setBetaParameters(int in_number_of_categories, MDOUBLE in_alpha, MDOUBLE in_beta) { if ((in_alpha == _alpha) && (in_beta == _beta) && (in_number_of_categories == categories())) return; if (in_alpha < MINIMUM_ALPHA_PARAM) in_alpha = MINIMUM_ALPHA_PARAM;// when alpha is very small there are underflaw problems if (in_beta < MINIMUM_ALPHA_PARAM) in_beta = MINIMUM_ALPHA_PARAM;// when beta is very small there are underflaw problems _alpha = in_alpha; _beta = in_beta; _rates.clear(); _rates.resize(in_number_of_categories); _ratesProb.clear(); _ratesProb.resize(in_number_of_categories, 1.0/in_number_of_categories); _boundary.clear(); _boundary.resize(in_number_of_categories+1); if (in_number_of_categories==1) { _rates[0] = 1.0; return; } if (categories() > 1) { fill_mean(); return ; } } int betaDistribution::fill_mean() { fill_boundaries(); int i; //LOG(5,<<endl<<" alpha = "<<_alpha<<" beta = "<< _beta<<endl); //for (i=0; i<=categories(); ++i) cout<<endl<<_boundary[i]; //LOG(5,<<"\n====== the r categories are =====\n"); for (i=0; i<categories(); ++i) { _rates[i]=computeAverage_r(_boundary[i], _boundary[i+1], _alpha, _beta, categories()); //LOG(5,<<_rates[i]<<endl); } //LOG(5,<<endl<<_alpha<<endl); return 0; } int betaDistribution::fill_boundaries() { int i; //LOG(5,<<endl<<"========BOUNDARY============="<<endl); for (i=1; i<categories(); ++i) { _boundary[i]=inverseCDFBeta(_alpha, _beta,static_cast<MDOUBLE>(i)/categories()); //LOG(5,<<"_boundary[ "<<i<<"] ="<<_boundary[i]<<endl); } _boundary[0]=0; _boundary[i]=1; return 0; } const MDOUBLE betaDistribution::getCumulativeProb(const MDOUBLE x) const {// //since r~gamma(alpha, beta) then beta*r~ gamma(alpha,1)=gammp //here we assume alpha=beta return incompleteBeta(_alpha,_beta,x); }
[ "karan.bavishi90@gmail.com" ]
karan.bavishi90@gmail.com
27808db647ac173bcfe276db4d40b88379c703fc
7a32cee45cdb5bc9357963eb69f458f53bfaffe4
/vol2_src_ref/Plugins/Molecule1/MoleculeUtils.cpp
8bc3eb53f3b3ecc1ec663611711f303dab5ceea7
[]
no_license
kingmax/mayaProgrammingB
464f36027672ed2d911dab7528b27f214f8231d9
13b09747f142b6654b6fcb43107e9d6d476eadf7
refs/heads/master
2021-10-24T02:30:36.708392
2019-03-21T06:13:00
2019-03-21T06:13:00
97,942,873
0
0
null
null
null
null
UTF-8
C++
false
false
3,755
cpp
// // This file accompanies the book "Complete Maya Programming (Volume 2)" // For further information visit http://www.davidgould.com // // Copyright (C) 2004 David Gould // All rights reserved. // #include "MoleculeUtils.h" #include <maya/MTypes.h> #include <maya/MGlobal.h> #include <maya/MVector.h> #include <math.h> int linearIndex( const int r, const int c, const int nRows, const int nCols ) { return ((r % nRows) * nCols) + (c % nCols); } MStatus genBall( const MPoint &centre, const double radius, const unsigned int nSegs, int &nPolys, MPointArray &verts, MIntArray &polyCounts, MIntArray &polyConnects ) { verts.clear(); polyCounts.clear(); polyConnects.clear(); int nAzimuthSegs = nSegs * 2; int nZenithSegs = nSegs; int nAzimuthPts = nAzimuthSegs; // Last point corresponds to the first int nZenithPts = nZenithSegs + 1; // Last point is at other pole double azimIncr = 2.0 * M_PI / nAzimuthSegs; double zenIncr = M_PI / nZenithSegs; MPoint p; double azimuth, zenith; double sinZenith; int azi, zeni; zenith = 0.0; for( zeni=0; zeni < nZenithPts; zeni++, zenith += zenIncr ) { azimuth = 0.0; for( azi=0; azi < nAzimuthPts; azi++, azimuth += azimIncr ) { sinZenith = sin(zenith); p.x = radius * sinZenith * cos(azimuth); p.y = radius * cos(zenith); p.z = radius * sinZenith * sin(azimuth); verts.append( p ); } } // Calculate the number of polygons nPolys = nAzimuthSegs * nZenithSegs; // Each face has four points polyCounts.setLength( nPolys ); int i; for( i=0; i < nPolys; i++ ) polyCounts[i] = 4; // Generate the faces for( zeni=0; zeni < nZenithSegs; zeni++ ) { for( azi=0; azi < nAzimuthSegs; azi++ ) { //MGlobal::displayInfo( MString( "\n" ) + azi + "," + zeni ); polyConnects.append( linearIndex( zeni, azi, nZenithPts, nAzimuthPts ) ); polyConnects.append( linearIndex( zeni, azi+1, nZenithPts, nAzimuthPts ) ); polyConnects.append( linearIndex( zeni+1, azi+1, nZenithPts, nAzimuthPts ) ); polyConnects.append( linearIndex( zeni+1, azi, nZenithPts, nAzimuthPts ) ); } } return MS::kSuccess; } MStatus genRod( const MPoint &p0, const MPoint &p1, const double radius, const unsigned int nSegs, int &nPolys, MPointArray &verts, MIntArray &polyCounts, MIntArray &polyConnects ) { verts.clear(); polyCounts.clear(); polyConnects.clear(); unsigned int nCirclePts = nSegs; unsigned int nVerts = 2 * nCirclePts; // Calculate the local axiis of the rod MVector vec( p1 - p0 ); MVector up( 0.0, 1.0, 0.0 ); MVector xAxis, yAxis, zAxis; yAxis = vec.normal(); if( up.isParallel( yAxis, 0.1 ) ) up = MVector( 1.0, 0.0, 0.0 ); xAxis = yAxis ^ up; zAxis = (xAxis ^ yAxis).normal(); xAxis = (yAxis ^ zAxis ).normal(); // Calculate the vertex positions verts.setLength( nVerts ); double angleIncr = 2.0 * M_PI / nSegs; double angle; MPoint p; double x, z; unsigned int i; for( i=0, angle=0; i < nCirclePts; i++, angle += angleIncr ) { // Calculate position in circle x = radius * cos( angle ); z = radius * sin( angle ); p = p0 + x * xAxis + z * zAxis; verts[ i ] = p; p += vec; verts[ i + nCirclePts ] = p; } nPolys = nSegs; // Generate polycounts polyCounts.setLength( nPolys ); for( i=0; i < polyCounts.length(); i++ ) polyCounts[i] = 4; // Generate polyconnects polyConnects.setLength( nPolys * 4 ); polyConnects.clear(); for( i=0; i < nSegs; i++ ) { polyConnects.append( linearIndex( 0, i, 2, nCirclePts ) ); polyConnects.append( linearIndex( 0, i+1, 2, nCirclePts ) ); polyConnects.append( linearIndex( 1, i+1, 2, nCirclePts ) ); polyConnects.append( linearIndex( 1, i, 2, nCirclePts ) ); } return MS::kSuccess; }
[ "kingmax_res@163.com" ]
kingmax_res@163.com
a5eb55138095c7e9d194d9c12146ea2ec880b807
2f87d0719a1e45bee3ab921682c6abd4d1edcff6
/11.5.1/Linux/Samples/CaptureStills/ImageWriterLinux.cpp
0c1bacae6e0117839f4c024384f15c062a6c2b7a
[]
no_license
LTNGlobal-opensource/bmsdk
28fdadb9db07916473d07f51ffd0bb3ef02dd883
8c7406c2dcd7e7383d69a61cf4c1506835b61570
refs/heads/master
2022-10-11T05:04:35.742445
2020-06-10T16:16:04
2020-06-10T16:16:04
116,147,880
0
2
null
2020-06-10T00:10:25
2018-01-03T14:46:11
C++
UTF-8
C++
false
false
4,206
cpp
/* -LICENSE-START- ** Copyright (c) 2018 Blackmagic Design ** ** Permission is hereby granted, free of charge, to any person or organization ** obtaining a copy of the software and accompanying documentation covered by ** this license (the "Software") to use, reproduce, display, distribute, ** execute, and transmit the Software, and to prepare derivative works of the ** Software, and to permit third-parties to whom the Software is furnished to ** do so, all subject to the following: ** ** The copyright notices in the Software and this entire statement, including ** the above license grant, this restriction and the following disclaimer, ** must be included in all copies of the Software, in whole or in part, and ** all derivative works of the Software, unless such copies or derivative ** works are solely in the form of machine-executable object code generated by ** a source language processor. ** ** 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT ** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE ** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ** DEALINGS IN THE SOFTWARE. ** -LICENSE-END- */ #include <png.h> #include <sys/stat.h> #include <iomanip> #include <sstream> #include "ImageWriter.h" static const uint32_t kPNGSignatureLength = 8; HRESULT ImageWriter::GetNextFilenameWithPrefix(const std::string& path, const std::string& filenamePrefix, std::string& nextFileName) { HRESULT result = E_FAIL; static int idx = 0; struct stat buf; while (idx < 10000) { std::stringstream pngFilenameStream; pngFilenameStream << path << '/' << filenamePrefix << std::setfill('0') << std::setw(4) << idx++ << ".png"; nextFileName = pngFilenameStream.str(); // If file does not exist, return S_OK if (stat(nextFileName.c_str(), &buf) != 0) { result = S_OK; break; } } return result; } HRESULT ImageWriter::WriteBgra32VideoFrameToPNG(IDeckLinkVideoFrame* bgra32VideoFrame, const std::string& pngFilename) { bool result = E_FAIL; png_structp pngDataPtr = nullptr; png_infop pngInfoPtr = nullptr; png_bytep deckLinkBuffer = nullptr; png_bytepp rowPtrs = nullptr; // Ensure video frame has expected pixel format if (bgra32VideoFrame->GetPixelFormat() != bmdFormat8BitBGRA) { fprintf(stderr, "Video frame is not in 8-Bit BGRA pixel format\n"); return E_FAIL; } FILE *pngFile = fopen(pngFilename.c_str(), "wb"); if (!pngFile) { fprintf(stderr, "Could not open PNG file %s for writing\n", pngFilename.c_str()); return false; } pngDataPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!pngDataPtr) { fprintf(stderr, "Could not create PNG write struct\n"); goto bail; } pngInfoPtr = png_create_info_struct(pngDataPtr); if (!pngInfoPtr) { fprintf(stderr, "Could not create PNG info struct\n"); goto bail; } if (setjmp(png_jmpbuf(pngDataPtr))) { fprintf(stderr, "Failed PNG write initialization\n"); goto bail; } png_init_io(pngDataPtr, pngFile); png_set_IHDR(pngDataPtr, pngInfoPtr, bgra32VideoFrame->GetWidth(), bgra32VideoFrame->GetHeight(), 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(pngDataPtr, pngInfoPtr); png_set_bgr(pngDataPtr); if (bgra32VideoFrame->GetBytes((void**)&deckLinkBuffer) != S_OK) { fprintf(stderr, "Could not get DeckLinkVideoFrame buffer pointer\n"); goto bail; } rowPtrs = (png_bytep*)malloc(sizeof(png_bytep) * bgra32VideoFrame->GetHeight()); // Set row pointers from the buffer for (uint32_t row = 0; row < bgra32VideoFrame->GetHeight(); ++row) rowPtrs[row] = &deckLinkBuffer[row * bgra32VideoFrame->GetRowBytes()]; png_write_image(pngDataPtr, rowPtrs); png_write_end(pngDataPtr, NULL); result = S_OK; bail: fclose(pngFile); png_destroy_write_struct(&pngDataPtr, &pngInfoPtr); free(rowPtrs); return result; }
[ "stoth@kernellabs.com" ]
stoth@kernellabs.com
b026619663bbbb230db32d0895194bcced2f02aa
c3ffa07567d3d29a7439e33a6885a5544e896644
/HSNU-OJ/399.cpp
1960ad86cb7470ba6d47101d39bac20599eb1123
[]
no_license
a00012025/Online_Judge_Code
398c90c046f402218bd14867a06ae301c0c67687
7084865a7050fc09ffb0e734f77996172a93d3ce
refs/heads/master
2018-01-08T11:33:26.352408
2015-10-10T23:20:35
2015-10-10T23:20:35
44,031,127
0
0
null
null
null
null
UTF-8
C++
false
false
1,083
cpp
#include<bits/stdc++.h> #define LL long long using namespace std; const int maxn=100000+10 ; int w[maxn] ; vector<int> v1[maxn],v2[maxn] ; bool vis1[maxn],vis2[maxn] ; LL dp[2][maxn] ; void dp1(int x) { if(vis1[x]) return ; vis1[x]=1 ; LL &ans=dp[0][x] ; ans=w[x] ; for(auto i : v1[x]) { dp1(i) ; ans=max(ans,w[x]+dp[0][i]) ; } } void dp2(int x) { if(vis2[x]) return ; vis2[x]=1 ; LL &ans=dp[1][x] ; ans=w[x] ; for(auto i : v2[x]) { dp2(i) ; ans=max(ans,w[x]+dp[1][i]) ; } } main() { int n,m ; scanf("%d%d",&n,&m) ; for(int i=1;i<=n;i++) scanf("%d",&w[i]) ; while(m--) { int x,y ; scanf("%d%d",&x,&y) ; v1[x].push_back(y) ; v2[y].push_back(x) ; } for(int i=1;i<=n;i++) dp1(i) ; for(int i=1;i<=n;i++) dp2(i) ; LL maxl=0LL ; for(int i=1;i<=n;i++) maxl=max(maxl,dp[0][i]) ; for(int i=1;i<=n;i++) { LL l=dp[0][i]+dp[1][i]-w[i] ; printf("%lld\n",maxl-l) ; } }
[ "a00012025@gmail.com" ]
a00012025@gmail.com
a873fcce68083cc35007daa5adc2316f330c9df2
87b1736c19cd79903aaf7df9e8a7f52b0bbe355c
/lab8/cq1.cpp
9b12146d5ca6407f9eb25de9594a3fe10297b6f3
[]
no_license
imagine5am/cs699-pm9
85029a0ab8e41f90038ab86caf0e8db0edb6bee1
0c28d479c688387f66575317bcadf667d8abb78a
refs/heads/main
2023-04-06T15:37:19.828890
2021-04-29T18:27:31
2021-04-29T18:27:31
362,910,668
0
0
null
null
null
null
UTF-8
C++
false
false
2,148
cpp
#include <cstdlib> #include <cstring> #include <iostream> using namespace std; struct eArray{ private: // put data members here int *data_ptr; int nums = 0, heap_size = 0; static const int DEFAULT_SIZE = 32; public: // construct an array with 0 elements eArray(){ data_ptr = (int*) malloc(DEFAULT_SIZE * sizeof(int)); if (data_ptr == NULL){ printf("malloc: Memory not allocated.\n"); } else{ heap_size = DEFAULT_SIZE; } } // return a reference to the ith element of the array int &operator[](int i){ return data_ptr[i]; } // Append v to the current array // Use a simple implementation: allocate a new array to // accommodate the extra element v. Then copy the current // array into it. Copy v, and delete the current array. void push_back(int v){ int *temp_ptr; if (nums == heap_size) { temp_ptr = (int*) malloc(2 * heap_size * sizeof(int)); memcpy(temp_ptr, data_ptr, nums * sizeof(int)); if (temp_ptr == NULL){ printf("malloc: Memory not allocated.\n"); } else { free(data_ptr); data_ptr = temp_ptr; heap_size *= 2; } } data_ptr[nums++] = v; } // return the current size of the array // "const" says this function will not change the receiver int size() const { return nums; } // copy constructor eArray(const eArray &rhs){ data_ptr = (int*) malloc(rhs.heap_size * sizeof(int)); if (data_ptr == NULL){ printf("malloc: Memory not allocated.\n"); } else{ heap_size = rhs.heap_size; nums = rhs.nums; } memcpy(data_ptr, rhs.data_ptr, nums * sizeof(int)); } // destructor ~eArray(){ free(data_ptr); } // assignment operator eArray& operator=(const eArray &rhs){ nums = rhs.nums; heap_size = rhs.heap_size; free(data_ptr); data_ptr = (int*) malloc(rhs.heap_size * sizeof(int)); if (data_ptr == NULL){ printf("malloc: Memory not allocated.\n"); } else{ heap_size = rhs.heap_size * sizeof(int); } memcpy(data_ptr, rhs.data_ptr, nums * sizeof(int)); return *this; } };
[ "ssood@cse.iitb.ac.in" ]
ssood@cse.iitb.ac.in
9074a55bb5784d4e4ebf3a1c35e5d17e79c7a6c5
64892882b204aa9930b5b247a7695e9e466c0ab7
/MKA/Lab2_v4/Lab2_v4/main.cpp
3696ff10c09fe65e803c2f709a081d469c453bac
[]
no_license
zhekaso/ms-homework
13672346007954c518c758775ad39df0f284a7af
5518a18736d43faf7a112d9b08f70e35bb24ea86
refs/heads/master
2020-03-28T07:28:05.084024
2018-09-27T15:31:35
2018-09-27T15:31:35
147,903,240
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,563
cpp
#include "mesh.h" void main() { setlocale(LC_ALL, "Russian"); MESH disk; disk.input(); int user_choise; bool end = false; while (!end) { printf("\t1) По номеру КЭ получить номер его базисых функций;\n\t2) По двум узлам получить номер ребра;\n"); printf("\t3) По номеру ребра узнать номера вершин, составляющих ребро;\n"); printf("\t4) По номеру ребра узнать каким КЭ данное ребро принадлежит;\n\t5) Выход;\n"); printf("Ваш выбор : "); scanf("%d\n", &user_choise); switch (user_choise) { case 1: { int fe_id; printf("Введите номер КЭ : "); scanf("%d\n", &fe_id); vector <int> base_id; base_id = disk.returnTheBasicFuncOfFE(fe_id); printf("В %d - й КЭ входят базисные функции с номерами : \n\t\t", fe_id); for(int i =0;i<base_id.size();i++) printf("%d ",base_id[i]); } break; case 2: { printf("\tВведите номер первой вершины : "); int A_id, B_id; scanf("%d\n", &A_id); printf("\tВведите номер второй вершины : "); scanf("%d\n", &B_id); int edge_id; if(disk.returnTheNumberOfEdge(A_id,B_id,&edge_id)) printf("\tДанные вершины образуют ребро с номером %d\n",edge_id); else printf("\tДанная пара вершин не образуют ребро\n"); } break; case 3: { printf("\tВведите номер ребра : "); int edge_id,A_id, B_id; scanf("%d\n", &edge_id); if (disk.returnPointsFormingAnEdge(&A_id, &B_id, edge_id)) printf("\tРебро %d обрауют вершины с номерами %d и %d\n", edge_id, A_id,B_id); else printf("\tНе существует ребра с таким номером.\n"); } break; case 4: { printf("\tВведите номер ребра : "); int edge_id; vector <int> FE; scanf("%d\n", &edge_id); disk.returnNumberFEIncludingEdge(edge_id); printf("Ребро с номером %d входит в КЭ с номерами: \n\t\t", edge_id); for (int i = 0; i < FE.size(); i++) printf("%d ", FE[i]); } break; case 5: end =! end ; break; default: printf("Ваш выбор не выходит в множество возможных действий! Введите цифру от 1 до 5"); break; } } }
[ "andrei.brenev@mail.ru" ]
andrei.brenev@mail.ru
d0b0dbd17425cb6797e716c509560ae5eaa9961e
1a2244c5b9879492227fec5ac86bf0b8ed8d19b1
/CS470.skel/hw4/HW_resize.cpp
f3f0a55fbb3980b8fbc41627dbcc044f5b5e41e8
[]
no_license
mhasan004/Image-Processing-Program
77b58cdb0a0abd5eac327a4759eb3b68a460ca87
e5b7ee6fc26447306de03fef21024b04e007a621
refs/heads/master
2022-03-17T23:53:19.718885
2019-12-12T06:00:36
2019-12-12T06:00:36
211,395,282
2
0
null
null
null
null
UTF-8
C++
false
false
7,302
cpp
#include "IP.h" using namespace IP; enum FILTERS { BOX, TRIANGLE, CUBIC_CONV, LANCZOS, HANN, HAMMING }; double boxFilter (double, double); double triFilter (double, double); double cubicConv (double, double); double lanczos (double, double); double hann (double, double); double hamming (double, double); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // resize1D: // // Scale 1D scanline. float version. // Input consists of len elements in src. // Output consists of nlen elements in dst. // The inter-pixel distance in src and dst is offst: 1 for rows or row_width for columns // The resampling filter used is specified by mtd (BOX, TRIANGLE, CUBIC_CONV, LANCZOS, HANN, HAMMING) // void resize1D(ChannelPtr<uchar> src, int len, int nlen, int offst, int mtd, double param, ChannelPtr<uchar> dst) { // copy src to dst if no scale change if(len == nlen) { for(int i = 0; i<len; ++i) { *dst = *src; src += offst; dst += offst; } return; } // filter function and filter support (kernel half-width) declarations double (*filter)(double, double); // ptr to filter fct double filterSupport; // 1-sided filter length // default values for filter and its half-width support filter = triFilter; filterSupport = 1; // compute filterSupport: the half-width of the filter switch(mtd) { case FILTERS::BOX: filter = boxFilter; filterSupport = .5; break; case FILTERS::TRIANGLE: filter = triFilter; filterSupport = 1; break; case FILTERS::CUBIC_CONV: filter = cubicConv; filterSupport = 2; break; case FILTERS::LANCZOS: filter = lanczos; filterSupport = param; break; case FILTERS::HANN: filter = hann; filterSupport = param; break; case FILTERS::HAMMING: filter = hamming; filterSupport = param; break; default: fprintf(stderr, "resize1D: Bad filter choice %d\n", mtd); return; } // init filter amplitude (fscale) and width (fwidth), and scale change double fwidth = filterSupport; double fscale = 1.0; double scale = (double) nlen / len; // resampling scale factor // image minification: update fwidth and fscale; // else kernel remains intact for magnification if(scale < 1.0) { // minification: h(x) -> h(x*scale) * scale fwidth = filterSupport / scale; // broaden filter fscale = scale; // lower amplitude } // evaluate size of padding and buffer length int padlen = CEILING(fwidth); // buffer pad length int buflen = len + 2 * padlen; // buffer length // allocate buffer memory if necessary ImagePtr Ibuf; ChannelPtr<uchar> buf; int t=0; IP_getChannel(Ibuf, 0, buf, t); if(Ibuf->width() < buflen || t != UCHAR_TYPE) Ibuf->replaceChannel(0, buflen, 1, UCHAR_TYPE); // copy src into padded buffer buf = Ibuf[0]; // copy src into dst; save space for padding ChannelPtr<uchar> p1 = src; ChannelPtr<uchar> p2 = buf + padlen; for(int x=0; x<len; ++x,p1+=offst) p2[x] = *p1; // pad left and right columns int v1, v2; p1 = buf + padlen; p2 = p1 + len - 1; // replicate border v1 = p1[0]; v2 = p2[0]; for(int x=1; x<= padlen; ++x) { p1[-x] = v1; p2[ x] = v2; } // init srcp to point to first non-padded pixel in padded buffer ChannelPtr<uchar> srcp = buf + padlen; // compute all output pixels int left, right; // kernel extent in input double u; // input coordinate u double acc; // convolution accumulator double pixel; // fetched pixel value double weight; // filter kernel weight for(int x = 0; x<nlen; ++x) { // map output x to input u: inverse mapping u = x / scale; // left and right extent of kernel centered at u if(u - fwidth < 0) left = FLOOR (u - fwidth); else left = CEILING(u - fwidth); right = FLOOR(u + fwidth); // reset acc for collecting convolution products acc = 0; // weigh input pixels around u with kernel double sumWeight = 0; for(int i=left; i <= right; ++i) { // fetch pixel // padding replaces pixel = srcp[CLIP(i, 0, len-1)] to pixel = srcp[i] pixel = srcp[i]; // evaluate weight; multiply it with pixel and add it to accumulator weight = (*filter)((u-i) * fscale, param); sumWeight += weight; acc += (pixel * weight); } // assign weighted accumulator to dst *dst = (int) CLIP(ROUND(acc / sumWeight), 0, MaxGray); dst += offst; } } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // boxFilter: // // Box (nearest neighbor) filter. // double boxFilter(double t, double /*param*/) { if((t > -.5) && (t <= .5)) return(1.0); return(0.0); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // triFilter: // // Triangle filter (used for linear interpolation). // double triFilter(double t, double /*param*/) { if(t < 0) t = -t; if(t < 1.0) return(1.0 - t); return(0.0); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // cubicConv: // // Cubic convolution filter. // double cubicConv(double t, double param = -1) { float A; double t2, t3; if(t < 0) t = -t; t2 = t * t; t3 = t2 * t; A = param; if(t < 1.0) return((A + 2)*t3 - (A + 3)*t2 + 1); if(t < 2.0) return(A * (t3 - 5 * t2 + 8 * t - 4)); return(0.0); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sinc: // // Sinc function. // double sinc(double t) { t *= PI; if(t != 0) return(sin(t) / t); return(1.0); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // lanczos: // // Lanczos filter. // double lanczos(double t, double param=3) { int N; N = (int) param; if(t < 0) t = -t; if(t < N) return(sinc(t) * sinc(t / N)); return(0.0); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // hann: // // Hann windowed sinc function. // double hann(double t, double param=3) { int N; N = (int) param; if(t < 0) t = -t; if(t < N) return(sinc(t) * (.5 + .5*cos(PI*t / N))); return(0.0); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // hamming: // // hamming windowed sinc function. // double hamming(double t, double param=3) { int N; N = (int) param; if(t < 0) t = -t; if(t < N) return(sinc(t) * (.54 + .46*cos(PI*t / N))); return(0.0); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HW_resize: void HW_resize(ImagePtr I1, int ww, int hh, int kernelID, double param, ImagePtr I2) { int w = I1->width (); int h = I1->height(); // handle trivial case where dimensions remain unchanged if(ww == w && hh == h) { if(I1 != I2) IP_copyImage(I1, I2); return; } // init II ImagePtr II; if(I1 == I2) IP_copyImage(I1, II); else II = I1; // init I2 info IP_copyImageHeaderOnly(I1, I2); I2->setWidth (ww); I2->setHeight(hh); I2->initChannels(I1->channelTypes()); // create tmp image to hold horizontal pass ImagePtr I3; I3 = IP_allocImage(ww, h, UCHARCH_TYPE); // 2-pass scale algorithm int t; ChannelPtr<uchar> src, dst; for(int ch = 0; IP_getChannel(II, ch, src, t); ch++) { IP_getChannel(I2, ch, dst, t); // horizontal pass scales rows for(int y = 0; y<h; ++y) { // PUT YOUR CODE HERE } // vertical pass scales columns for(int x = 0; x<ww; ++x) { // PUT YOUR CODE HERE } } // free global buffer if(II != I1) II->freeImage(); I3->freeImage(); }
[ "mhasan0047@gmail.com" ]
mhasan0047@gmail.com
3f18d0ec33b37a07eda83e506ad8b9d23583af76
d0fb46aecc3b69983e7f6244331a81dff42d9595
/live/src/model/CreateMessageAppRequest.cc
51cf0038641ac83a7c7c8b4795991b463c695310
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,955
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * 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 <alibabacloud/live/model/CreateMessageAppRequest.h> using AlibabaCloud::Live::Model::CreateMessageAppRequest; CreateMessageAppRequest::CreateMessageAppRequest() : RpcServiceRequest("live", "2016-11-01", "CreateMessageApp") { setMethod(HttpRequest::Method::Post); } CreateMessageAppRequest::~CreateMessageAppRequest() {} std::map<std::string, std::string> CreateMessageAppRequest::getExtension() const { return extension_; } void CreateMessageAppRequest::setExtension(const std::map<std::string, std::string> &extension) { extension_ = extension; for(auto const &iter1 : extension) { setBodyParameter(std::string("Extension") + "." + iter1.first, iter1.second); } } std::map<std::string, std::string> CreateMessageAppRequest::getAppConfig() const { return appConfig_; } void CreateMessageAppRequest::setAppConfig(const std::map<std::string, std::string> &appConfig) { appConfig_ = appConfig; for(auto const &iter1 : appConfig) { setBodyParameter(std::string("AppConfig") + "." + iter1.first, iter1.second); } } std::string CreateMessageAppRequest::getAppName() const { return appName_; } void CreateMessageAppRequest::setAppName(const std::string &appName) { appName_ = appName; setBodyParameter(std::string("AppName"), appName); }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
9b442b0a14b3130b01b63610d8c4c5dc71954ae8
d92304badb95993099633c5989f6cd8af57f9b1f
/Codeforces/723-B.cpp
6063ccefff2dc690512e105e6bcbcd50437013b7
[]
no_license
tajirhas9/Problem-Solving-and-Programming-Practice
c5e2b77c7ac69982a53d5320cebe874a7adec750
00c298233a9cde21a1cdca1f4a2b6146d0107e73
refs/heads/master
2020-09-25T22:52:00.716014
2019-12-05T13:04:40
2019-12-05T13:04:40
226,103,342
0
0
null
null
null
null
UTF-8
C++
false
false
3,059
cpp
#include <bits/stdc++.h> using namespace std; #define MAX 1000000007 #define MOD 1000000007 #define rep(i,a,b) for(i=a;i<=b;i++) #define repR(i,a,b) for(i=a;i>=b;i--) #define mp(x,y) make_pair(x,y) #define pb(x) emplace_back(x) //#define pb(x) push_back(x) #define all(c) c.begin(),c.end() #define F first #define S second #define RESET(a,b) memset(a,b,sizeof(a)) #define gcd(a,b) __gcd(a,b) #define lcm(a,b) ((a*b)/gcd(a,b)) typedef long long ll; typedef string string; typedef pair<ll,ll> pii; typedef vector<ll> vl; typedef vector<string> vs; typedef set<ll> setl; typedef set<string> sets; typedef set<ll>::iterator setl_it; typedef set<string>::iterator sets_it; typedef vector<ll>::iterator vl_it; typedef vector<string>::iterator vs_it; inline bool isLeapYear(ll y) { return ((y%400==0) || (y%4==0 && y%100!=0)); } inline void optimize(void) { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } inline bool isInside(pii p,ll n,ll m) { return (p.first>=0&&p.first<n&&p.second>=0&&p.second<m); }; inline bool isInside(pii p,ll n) { return (p.first>=0&&p.first<n&&p.second>=0&&p.second<n); }; inline bool isSquare(ll x) { ll s = sqrt(x); return (s*s==x); }; inline bool isFib(ll x) { return isSquare(5*x*x+4)|| isSquare(5*x*x-4); }; inline bool isPowerOfTwo(ll x) { return ((1LL<<(ll)log2(x))==x); }; ll primeMarked[MAX/64 + 2]; inline bool on(ll x) { return (primeMarked[x/64] & (1<<((x%64)/2))); }; inline void mark(ll x) { primeMarked[x/64] |= (1<<((x%64)/2)); }; inline ll bitOn(ll x,ll k) { return x |= 1<<k; } inline ll bitOff(ll x,ll k) { return x ^= 1<<k; } inline bool checkBit(ll x,ll k) { return x &= 1<<k; } const ll mod = 1e9+7; const double pi = acos(-1.0); struct func { //this is a sample overloading function for sorting stl bool operator()(pii const &a, pii const &b) { if(a.first==b.first) return (a.second<b.second); return (a.first>b.first); } };/* void sieve(ll n) { for (ll i=3; i*i<n;i+=2) { if (!on(i)) { for (ll j=i*i;j<=n;j+=i+i) { mark(j); } } } } inline bool isPrime(int num) { return num > 1 && (num == 2 || ((num & 1) && !on(num))); }*/ ll fx[] = {1,1,-1,-1}; ll fy[] = {1,-1,1,-1}; int main() { optimize(); ll i,l,m=0,cnt=0,word=0; string s; bool bracketIsOn,wordCount; bracketIsOn = wordCount = false; cin >> l; cin >> s; rep(i,0,l) { if(s[i]=='(') { m = max(m,cnt); cnt=0; bracketIsOn = true; } if(s[i]==')') { bracketIsOn = false; wordCount = false; } if(s[i]=='\0') { m = max(m,cnt); cnt = 0; } if(s[i]=='_') //RESET everything { if(bracketIsOn) { if(wordCount) { wordCount = false; } } else { //do something for outside bracket m = max(m,cnt); cnt = 0; } } if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i] <= 'Z')) { if(bracketIsOn) { if(!wordCount) { word++; wordCount = true; } } else { cnt++; } } } cout << m << " " << word << endl; return 0; } //?
[ "tajircuet@gmail.com" ]
tajircuet@gmail.com
2639eefe0aae88c9708c95373b259345bd726666
6c766846a9c07523369d3a5b55d77adb3808e5aa
/FinalPass/FinalPass.cpp
65b4029d0872156d4cd24dac597ccab9461d59e6
[]
no_license
danny30312/EECS-583-FinalProject
404133539826d341293d2abc7e3875316d8e0566
ba5d087f971d20687714dcd8a2451fc65537de44
refs/heads/main
2023-01-22T16:45:36.522007
2020-11-28T19:49:04
2020-11-28T19:49:04
316,807,908
0
0
null
null
null
null
UTF-8
C++
false
false
5,123
cpp
#include "llvm/Transforms/Scalar/LICM.h" #include "llvm/ADT/SetOperations.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/AliasSetTracker.h" #include "llvm/Analysis/BasicAliasAnalysis.h" #include "llvm/Analysis/CaptureTracking.h" #include "llvm/Analysis/ConstantFolding.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/GuardUtils.h" #include "llvm/Analysis/Loads.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopIterator.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/MemoryBuiltins.h" #include "llvm/Analysis/MemorySSA.h" #include "llvm/Analysis/MemorySSAUpdater.h" #include "llvm/Analysis/OptimizationRemarkEmitter.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/PatternMatch.h" #include "llvm/IR/PredIteratorCache.h" #include "llvm/InitializePasses.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Scalar/LoopPassManager.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Transforms/Utils/LoopUtils.h" #include "llvm/Transforms/Utils/SSAUpdater.h" #include <algorithm> #include <utility> #include "llvm/Analysis/BranchProbabilityInfo.h" #include "llvm/Analysis/BlockFrequencyInfo.h" using namespace llvm; namespace { struct Statics : public FunctionPass { static char ID; Statics() : FunctionPass(ID) {} void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<BlockFrequencyInfoWrapperPass>(); // Analysis pass to load block execution count AU.addRequired<BranchProbabilityInfoWrapperPass>(); // Analysis pass to load branch probability } bool runOnFunction(Function &F) override { BranchProbabilityInfo &bpi = getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); BlockFrequencyInfo &bfi = getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI(); float DynOpCounts = 0; float IAlu = 0; float FAlu = 0; float Mem = 0; float BBranch = 0; float UBranch = 0; float Other = 0; for (Function::iterator b = F.begin(); b != F.end(); b++) { for (BasicBlock::iterator i = b->begin(); i != b->end(); i++) { uint64_t blockCount = bfi.getBlockProfileCount(&*b).getValue(); DynOpCounts += blockCount; int inst = i->getOpcode(); if (inst == Instruction::Add ||inst == Instruction::Sub ||inst == Instruction::Mul ||inst == Instruction::UDiv ||inst == Instruction::SDiv ||inst == Instruction::URem ||inst == Instruction::Shl ||inst == Instruction::LShr ||inst == Instruction::AShr ||inst == Instruction::And ||inst == Instruction::Or ||inst == Instruction::Xor ||inst == Instruction::ICmp ||inst == Instruction::SRem) {IAlu += blockCount;} else if (inst == Instruction::FAdd ||inst == Instruction::FSub ||inst == Instruction::FMul ||inst == Instruction::FDiv ||inst == Instruction::FRem ||inst == Instruction::FCmp) {FAlu += blockCount;} else if (inst == Instruction::Alloca ||inst == Instruction::Load ||inst == Instruction::Store ||inst == Instruction::GetElementPtr ||inst == Instruction::Fence ||inst == Instruction::AtomicCmpXchg ||inst == Instruction::AtomicRMW) {Mem += blockCount;} else if (inst == Instruction::Br ||inst == Instruction::Switch ||inst == Instruction::IndirectBr){ if (bpi.getHotSucc((BasicBlock*) &*b)){ BBranch += blockCount; } else { UBranch += blockCount; } } else{Other += blockCount;} } } errs() << F.getName() << ", "; errs() << int(DynOpCounts) << ", "; if (DynOpCounts == 0) { errs() << format("%f", 0.0f); } else { errs() << format("%f, ", (IAlu/DynOpCounts)); errs() << format("%f, ",(FAlu/DynOpCounts)); errs() << format("%f, ",(Mem/DynOpCounts)); errs() << format("%f, ",(BBranch/DynOpCounts)); errs() << format("%f, ",(UBranch/DynOpCounts)); errs() << format("%f",(Other/DynOpCounts)); } errs() << "\n"; return true; } }; } char Statics::ID = 0; static RegisterPass<Statics> X("statistics", "Operation Statistics Pass", false /* Only looks at CFG */, false /* Analysis Pass */);
[ "chchuang@eecs583a.eecs.umich.edu" ]
chchuang@eecs583a.eecs.umich.edu
2aa84d3a8a190662ec149cf8e5da3e27e09c996a
b20203514a73611acd5f226ba4c1668140959e8d
/ctraj/pp_util.cc
075abb0709f828a28dfd757eba50290ea23e86a9
[ "MIT" ]
permissive
Edroor/libmsci
978d748e2ec788bc5b28eadf311d4c497d95f705
872dc362292d93ce4966e554494bfa156594c9d9
refs/heads/master
2023-02-22T10:17:52.934272
2021-01-25T05:40:42
2021-01-25T05:40:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,634
cc
#include <stdio.h> #include <stdint.h> #include <gsl/gsl_fft_complex.h> #include "peteys_tmpl_lib.h" #include "error_codes.h" #include "full_util.h" #include "time_class.h" #include "ctraj_defaults.h" #include "pp_util.h" #include "ctraj_3d_fields.h" using namespace libpetey; namespace ctraj { void swap_endian (int32_t *data, int n) { char *fourbyte; char swp; for (int i=0; i<n; i++) { fourbyte=(char *) (data+i); swp=fourbyte[0]; fourbyte[0]=fourbyte[3]; fourbyte[3]=swp; swp=fourbyte[1]; fourbyte[1]=fourbyte[2]; fourbyte[2]=swp; } } int pp_read_all(char *fname, int32_t **headers_all, float ***fields, int nmax) { FILE *fs; int32_t f77recsep; int32_t *header; float **data; int readcount; int nrec; fs=fopen(fname, "r"); if (fs==NULL) { fprintf(stderr, "Error: unable to open %s for input\n", fname); throw UNABLE_TO_OPEN_FILE_FOR_READING; } for (nrec=0; nrec<nmax; nrec++) { readcount=fread(&f77recsep, sizeof(f77recsep), 1, fs); //printf("%d %d\n", nrec, readcount); if (readcount==0) { break; } swap_endian(&f77recsep, 1); //should be 256: //printf("%d\n", f77recsep); if (f77recsep != PP_HEADLEN*4) { fprintf(stderr, "Error: error in record separator--wrong file type\n"); fprintf(stderr, " actual: %d; expected: %d\n", f77recsep, PP_HEADLEN*4); throw FILE_READ_ERROR; } header=new int32_t[PP_HEADLEN]; fread(header, sizeof(int32_t), PP_HEADLEN, fs); swap_endian(header, PP_HEADLEN); headers_all[nrec]=header; fread(&f77recsep, sizeof(f77recsep), 1, fs); fread(&f77recsep, sizeof(f77recsep), 1, fs); swap_endian(&f77recsep, 1); //should be 6912*4: //printf("%d\n", f77recsep); if (header[PP_HEADLOC_N]!=header[PP_HEADLOC_NLAT]*header[PP_HEADLOC_NLON]) { fprintf(stderr, "Error in record header: %d*%d != %d\n", header[PP_HEADLOC_NLAT], header[PP_HEADLOC_NLON], header[PP_HEADLOC_N]); throw FILE_READ_ERROR; } data=allocate_matrix<float, int32_t>(header[PP_HEADLOC_NLAT], header[PP_HEADLOC_NLON]); fread(data[0], sizeof(float), header[PP_HEADLOC_N], fs); swap_endian((int32_t *) data[0], header[PP_HEADLOC_N]); fields[nrec]=data; fread(&f77recsep, sizeof(f77recsep), 1, fs); } fclose(fs); return nrec; } int pp_read_field(FILE *fs, int32_t **headers, float ***fields, int nmax, int field_code, float *plev, int nlev, int toendflag) { int32_t f77recsep; int32_t *header; int nhead_check; //check number of elements read in float **data; int readcount; int nrec; int n, n1; //number of elements read in should match int nlon, nlat; float level; int lastcode=-1; int code=-1; do { readcount=fread(&f77recsep, sizeof(f77recsep), 1, fs); //printf("%d %d\n", nrec, readcount); if (readcount==0) { break; } swap_endian(&f77recsep, 1); //should be 256: //printf("%d\n", f77recsep); if (f77recsep != PP_HEADLEN*sizeof(int32_t)) { fprintf(stderr, "Error: error in record separator--wrong file type\n"); fprintf(stderr, " actual: %d; expected: %d\n", f77recsep, PP_HEADLEN*4); throw FILE_READ_ERROR; } header=new int32_t[PP_HEADLEN]; nhead_check=fread(header, sizeof(int32_t), PP_HEADLEN, fs); if (nhead_check!=PP_HEADLEN) { fprintf(stderr, "Not enough header records read in: %d vs. %d\n", nhead_check, PP_HEADLEN); if (nhead_check==0) break; else throw FILE_READ_ERROR; } swap_endian(header, PP_HEADLEN); headers[nrec]=header; fread(&f77recsep, sizeof(f77recsep), 1, fs); fread(&f77recsep, sizeof(f77recsep), 1, fs); swap_endian(&f77recsep, 1); //should be 6912*4: //printf("%d\n", f77recsep); n=header[PP_HEADLOC_N]; nlat=header[PP_HEADLOC_NLAT]; nlon=header[PP_HEADLOC_NLON]; lastcode=code; code=header[PP_HEADLOC_CODE]; level=*(float *)(header+PP_HEADLOC_LEV); if (n!=nlon*nlat) { fprintf(stderr, "Error in record header: %d*%d != %d\n", nlat, nlon, n); throw FILE_READ_ERROR; } if (n*sizeof(int32_t)!=f77recsep) { fprintf(stderr, "Error in record header: %d != %d\n", header[PP_HEADLOC_NLAT], f77recsep); throw FILE_READ_ERROR; } data=NULL; if (code == field_code) { if (plev!=NULL) { for (int i=0; i<nlev; i++) { if (plev[i]==level) { data=allocate_matrix<float, int32_t>(nlat, nlon); break; } } } else { data=allocate_matrix<float, int32_t>(nlat, nlon); } } if (data!=NULL) { n1=fread(data[0], sizeof(float), n, fs); if (n1!=n) { fprintf(stderr, "Not enough header records read in: %d vs. %d\n", nhead_check, PP_HEADLEN); throw FILE_READ_ERROR; } swap_endian((int32_t *) data[0], n); fields[nrec]=data; nrec++; fread(&f77recsep, sizeof(f77recsep), 1, fs); } else { fseek(fs, n*sizeof(int32_t)+1, SEEK_CUR); } } while (lastcode!=field_code || lastcode==code || toendflag); return nrec; } int pp_extract_uvwtz(float ***data, int32_t **header, int n, float ***&u, float ***&v, float ***&w, float ***&t, float ***&z) { int loc=0; if (header[loc][PP_HEADLOC_CODE] !=PP_U_CODE) goto fail; u=data+loc; for (loc=0; loc<n; loc++) { if (header[loc][PP_HEADLOC_CODE] != PP_U_CODE) break; } if (header[loc][PP_HEADLOC_CODE] !=PP_V_CODE || loc>=n) goto fail; v=data+loc; for ( ; loc<n; loc++) { if (header[loc][PP_HEADLOC_CODE] != PP_V_CODE) break; } if (header[loc][PP_HEADLOC_CODE] !=PP_Z_CODE || loc>=n) goto fail; z=data+loc; for ( ; loc<n; loc++) { if (header[loc][PP_HEADLOC_CODE] != PP_Z_CODE) break; } if (header[loc][PP_HEADLOC_CODE] !=PP_T_CODE || loc>=n) goto fail; t=data+loc; for ( ; loc<n; loc++) { if (header[loc][PP_HEADLOC_CODE] != PP_T_CODE) break; } if (header[loc][PP_HEADLOC_CODE] !=PP_W_CODE || loc>=n) goto fail; w=data+loc; return 0; fail: fprintf(stderr, "Error: formatting of field data; %d vs. %d\n", PP_V_CODE, header[loc][PP_HEADLOC_CODE]); throw FILE_READ_ERROR; } float * pp_extract_levels(int32_t **header, int n, int &nlev) { int32_t code; float *lev; nlev=0; code=header[0][PP_HEADLOC_CODE]; for (int i=1; i<n; i++) { if (code!=header[i][PP_HEADLOC_CODE]) { nlev=i; break; } } lev=new float[nlev]; for (int i=0; i<nlev; i++) { lev[i]=((float *) header[i])[PP_HEADLOC_LEV]; } for (int i=0; i<n; i++) { if (((float *) header[i])[PP_HEADLOC_LEV] != lev[i%nlev]) goto fail; } return lev; fail: fprintf(stderr, "Error: formatting of vertical levels\n"); throw FILE_READ_ERROR; } int pp_interpolate_uv(float ***u, float ***v, int nlev, int nlat, int nlon, float ***unew, float ***vnew) { int nfft=1 << int(log(nlon)/log(2)); double *Spolecirc; double *Npolecirc; float Nx=0, Ny=0; //North pole wind float Sx=0, Sy=0; //South pole wind float sinth, costh; //Spolecirc=new double[nfft*2]; //Npolecirc=new double[nfft*2]; for (int i=0; i<nlev; i++) { for (int j=1; j<nlat; j++) { for (int k=0; k<nlon; k++) { unew[i][j][k]=(u[i][j-1][k]+u[i][j][k])/2; vnew[i][j][k]=(v[i][j-1][k]+v[i][j][k])/2; } } } //do some shit for the poles: for (int i=0; i<nlev; i++) { for (int j=0; j<nlon; j++) { costh=cos(2*M_PI*j/nlon); sinth=sin(2*M_PI*j/nlon); //average to a single point at the pole by rotating to a common //coordinate system: Sx+=u[i][0][j]*costh-v[i][0][j]*sinth; Sy+=v[i][0][j]*sinth+u[i][0][j]*costh; Nx+=u[i][nlat-1][j]*costh-v[i][nlat-1][j]*sinth; Ny+=v[i][nlat-1][j]*sinth+u[i][nlat-1][j]*costh; } Sx/=nlon; Sy/=nlon; Nx/=nlon; Ny/=nlon; //printf("%g %g %g %g\n", Sx, Sy, Nx, Ny); for (int j=0; j<nlon; j++) { costh=cos(2*M_PI*j/nlon); sinth=sin(2*M_PI*j/nlon); //printf("%g %g\n", costh, sinth); //zonal and meridional winds are just this point in rotated //coordinates depeding on the longitude: unew[i][0][j]=Sx*costh+Sy*sinth; vnew[i][0][j]=Sx*sinth-Sy*costh; unew[i][nlat][j]=Nx*costh+Ny*sinth; vnew[i][nlat][j]=Nx*sinth-Ny*costh; //printf("(%g, %g) ", unew[i][0][j], vnew[i][0][j]); } //printf("\n"); } } //finds interpolation coefficients for a set of potential temperature levels float *** pp_interpolate_pt_levels(float *plev, float ***t, int nlev, int nlat, int nlon, float *ptlev, int npt, float pref) { float ***coef; float pt[nlev]; long sind[nlev]; long loc; long lastind=-1; coef=allocate_3D_field<float>(npt, nlat, nlon); for (int i=0; i<nlat; i++) { for (int j=0; j<nlon; j++) { for (int k=0; k<nlev; k++) { pt[k]=t[k][i][j]*pow(pref/plev[k], KAPPA); //printf("%g ", pt[k]); } //printf("\n"); heapsort(pt, sind, nlev); map_vector_inplace(pt, sind, nlev); for (int k=0; k<npt; k++) { loc=bin_search(pt, nlev, ptlev[k], lastind); if (sind[loc]>=nlev-1 || loc < 0) { fprintf(stderr, "Potential temperature level (%g) falls out of sky\n", ptlev[k]); throw PARAMETER_OUT_OF_RANGE; } coef[k][i][j]=sind[(int) loc]+(ptlev[k]-pt[loc])/(pt[loc+1]-pt[loc]); //printf("%g ", coef[k][i][j]); } } //printf("\n"); } return coef; } float *** pp_zinterpolate(float ***field, float ***coef, int nlev, int nlat, int nlon) { float *** fnew; fnew=new float**[nlev]; for (int i=0; i<nlev; i++) { fnew[i]=allocate_matrix<float, int32_t>(nlat, nlon); for (int j=0; j<nlat; j++) { for (int k=0; k<nlon; k++) { int pind=(int) coef[i][j][k]; float frac=coef[i][j][k]-pind; fnew[i][j][k]=field[pind][j][k]*(1-frac) +field[pind+1][j][k]*frac; //printf("%g ", field[pind][j][k]); } //printf("\n"); } } return fnew; } } //end namespace ctraj
[ "peteymills@hotmail.com" ]
peteymills@hotmail.com
d1289cf61b7c7e37a3e19d5c2595093e096350c0
8dc84558f0058d90dfc4955e905dab1b22d12c08
/ash/system/power/power_event_observer.cc
b232f6260595da5e0174a196226af9f0fce1a7c8
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
14,555
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/system/power/power_event_observer.h" #include <map> #include <utility> #include "ash/public/cpp/config.h" #include "ash/root_window_controller.h" #include "ash/session/session_controller.h" #include "ash/shell.h" #include "ash/system/model/clock_model.h" #include "ash/system/model/system_tray_model.h" #include "ash/wallpaper/wallpaper_widget_controller.h" #include "ash/wm/lock_state_controller.h" #include "ash/wm/lock_state_observer.h" #include "base/bind.h" #include "base/location.h" #include "base/scoped_observer.h" #include "base/threading/thread_task_runner_handle.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/user_activity/user_activity_detector.h" #include "ui/compositor/compositor.h" #include "ui/compositor/compositor_observer.h" #include "ui/display/manager/display_configurator.h" namespace ash { namespace { void OnSuspendDisplaysCompleted(base::OnceClosure suspend_callback, bool status) { std::move(suspend_callback).Run(); } // Returns whether the screen should be locked when device is suspended. bool ShouldLockOnSuspend() { SessionController* controller = ash::Shell::Get()->session_controller(); return controller->ShouldLockScreenAutomatically() && controller->CanLockScreen(); } // One-shot class that runs a callback after all compositors start and // complete two compositing cycles. This should ensure that buffer swap with the // current UI has happened. // After the first compositing cycle, the display compositor starts drawing the // UI changes, and schedules a buffer swap. Given that the display compositor // will not start drawing the next frame before the previous swap happens, when // the second compositing cycle ends, it should be safe to assume the required // buffer swap happened at that point. // Note that the compositor watcher will wait for any pending wallpaper // animation for a root window to finish before it starts observing compositor // cycles, to ensure it picks up wallpaper state from after the animation ends, // and avoids issues like https://crbug.com/820436. class CompositorWatcher : public ui::CompositorObserver { public: // |callback| - called when all visible root window compositors complete // required number of compositing cycles. It will not be called after // CompositorWatcher instance is deleted, nor from the CompositorWatcher // destructor. explicit CompositorWatcher(base::OnceClosure callback) : callback_(std::move(callback)), compositor_observer_(this), weak_ptr_factory_(this) { Start(); } ~CompositorWatcher() override = default; // ui::CompositorObserver: void OnCompositingDidCommit(ui::Compositor* compositor) override { if (!pending_compositing_.count(compositor) || pending_compositing_[compositor].state != CompositingState::kWaitingForCommit) { return; } pending_compositing_[compositor].state = CompositingState::kWaitingForStarted; } void OnCompositingStarted(ui::Compositor* compositor, base::TimeTicks start_time) override { if (!pending_compositing_.count(compositor) || pending_compositing_[compositor].state != CompositingState::kWaitingForStarted) { return; } pending_compositing_[compositor].state = CompositingState::kWaitingForEnded; } void OnCompositingEnded(ui::Compositor* compositor) override { if (!pending_compositing_.count(compositor)) return; CompositorInfo& compositor_info = pending_compositing_[compositor]; if (compositor_info.state != CompositingState::kWaitingForEnded) return; compositor_info.observed_cycles++; if (compositor_info.observed_cycles < kRequiredCompositingCycles) { compositor_info.state = CompositingState::kWaitingForCommit; compositor->ScheduleDraw(); return; } compositor_observer_.Remove(compositor); pending_compositing_.erase(compositor); RunCallbackIfAllCompositingEnded(); } void OnCompositingLockStateChanged(ui::Compositor* compositor) override {} void OnCompositingChildResizing(ui::Compositor* compositor) override {} void OnCompositingShuttingDown(ui::Compositor* compositor) override { compositor_observer_.Remove(compositor); pending_compositing_.erase(compositor); RunCallbackIfAllCompositingEnded(); } private: // CompositorWatcher observes compositors for compositing events, in order to // determine whether compositing cycles end for all root window compositors. // This enum is used to track this cycle. Compositing goes through the // following states: DidCommit -> CompositingStarted -> CompositingEnded. enum class CompositingState { kWaitingForWallpaperAnimation, kWaitingForCommit, kWaitingForStarted, kWaitingForEnded, }; struct CompositorInfo { // State of the current compositing cycle. CompositingState state = CompositingState::kWaitingForCommit; // Number of observed compositing cycles. int observed_cycles = 0; }; // Number of compositing cycles that have to complete for each compositor // in order for a CompositorWatcher to run the callback. static constexpr int kRequiredCompositingCycles = 2; // Starts observing all visible root window compositors. void Start() { for (aura::Window* window : Shell::GetAllRootWindows()) { ui::Compositor* compositor = window->GetHost()->compositor(); if (!compositor->IsVisible()) continue; DCHECK(!pending_compositing_.count(compositor)); compositor_observer_.Add(compositor); pending_compositing_[compositor].state = CompositingState::kWaitingForWallpaperAnimation; WallpaperWidgetController* wallpaper_widget_controller = RootWindowController::ForWindow(window) ->wallpaper_widget_controller(); if (wallpaper_widget_controller->IsAnimating()) { wallpaper_widget_controller->AddPendingAnimationEndCallback( base::BindOnce(&CompositorWatcher::StartObservingCompositing, weak_ptr_factory_.GetWeakPtr(), compositor)); } else { StartObservingCompositing(compositor); } } // Post task to make sure callback is not invoked synchronously as watcher // is started. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&CompositorWatcher::RunCallbackIfAllCompositingEnded, weak_ptr_factory_.GetWeakPtr())); } // Called when the wallpaper animations end for the root window associated // with the compositor. It starts observing the compositor's compositing // cycles. void StartObservingCompositing(ui::Compositor* compositor) { if (!pending_compositing_.count(compositor) || pending_compositing_[compositor].state != CompositingState::kWaitingForWallpaperAnimation) { return; } pending_compositing_[compositor].state = CompositingState::kWaitingForCommit; // Schedule a draw to force at least one more compositing cycle. compositor->ScheduleDraw(); } // If all observed root window compositors have gone through a compositing // cycle, runs |callback_|. void RunCallbackIfAllCompositingEnded() { if (pending_compositing_.empty() && callback_) std::move(callback_).Run(); } base::OnceClosure callback_; // Per-compositor compositing state tracked by |this|. The map will // not contain compositors that were not visible at the time the // CompositorWatcher was started - the main purpose of tracking compositing // state is to determine whether compositors can be safely stopped (i.e. their // visibility set to false), so there should be no need for tracking // compositors that were hidden to start with. std::map<ui::Compositor*, CompositorInfo> pending_compositing_; ScopedObserver<ui::Compositor, ui::CompositorObserver> compositor_observer_; base::WeakPtrFactory<CompositorWatcher> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(CompositorWatcher); }; } // namespace PowerEventObserver::PowerEventObserver() : lock_state_(Shell::Get()->session_controller()->IsScreenLocked() ? LockState::kLocked : LockState::kUnlocked), session_observer_(this) { chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver( this); } PowerEventObserver::~PowerEventObserver() { chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->RemoveObserver( this); } void PowerEventObserver::OnLockAnimationsComplete() { VLOG(1) << "Screen locker animations have completed."; if (lock_state_ != LockState::kLocking) return; lock_state_ = LockState::kLockedCompositingPending; // If suspending, run pending animations to the end immediately, as there is // no point in waiting for them to finish given that the device is suspending. if (displays_suspended_callback_) EndPendingWallpaperAnimations(); // The |compositor_watcher_| is owned by this, and the callback passed to it // won't be called after |compositor_watcher_|'s destruction, so // base::Unretained is safe here. compositor_watcher_ = std::make_unique<CompositorWatcher>( base::BindOnce(&PowerEventObserver::OnCompositorsReadyForSuspend, base::Unretained(this))); } void PowerEventObserver::SuspendImminent( power_manager::SuspendImminent::Reason reason) { suspend_in_progress_ = true; displays_suspended_callback_ = chromeos::DBusThreadManager::Get() ->GetPowerManagerClient() ->GetSuspendReadinessCallback(FROM_HERE); // Stop compositing immediately if // * the screen lock flow has already completed // * screen is not locked, and should remain unlocked during suspend if (lock_state_ == LockState::kLocked || (lock_state_ == LockState::kUnlocked && !ShouldLockOnSuspend())) { StopCompositingAndSuspendDisplays(); } else { // If screen is getting locked during suspend, delay suspend until screen // lock finishes, and post-lock frames get picked up by display compositors. if (lock_state_ == LockState::kUnlocked) { VLOG(1) << "Requesting screen lock from PowerEventObserver"; lock_state_ = LockState::kLocking; Shell::Get()->lock_state_controller()->LockWithoutAnimation(); } else if (lock_state_ != LockState::kLocking) { // If the screen is still being locked (i.e. in kLocking state), // EndPendingWallpaperAnimations() will be called in // OnLockAnimationsComplete(). EndPendingWallpaperAnimations(); } } } void PowerEventObserver::SuspendDone(const base::TimeDelta& sleep_duration) { suspend_in_progress_ = false; // TODO(derat): After mus exposes a method for resuming displays, call it // here: http://crbug.com/692193 if (Shell::GetAshConfig() != Config::MASH) Shell::Get()->display_configurator()->ResumeDisplays(); Shell::Get()->system_tray_model()->clock()->NotifyRefreshClock(); // If the suspend request was being blocked while waiting for the lock // animation to complete, clear the blocker since the suspend has already // completed. This prevents rendering requests from being blocked after a // resume if the lock screen took too long to show. displays_suspended_callback_.Reset(); StartRootWindowCompositors(); } void PowerEventObserver::OnLockStateChanged(bool locked) { if (locked) { lock_state_ = LockState::kLocking; // The screen is now locked but the pending suspend, if any, will be blocked // until all the animations have completed. if (displays_suspended_callback_) { VLOG(1) << "Screen locked due to suspend"; } else { VLOG(1) << "Screen locked without suspend"; } } else { lock_state_ = LockState::kUnlocked; compositor_watcher_.reset(); if (suspend_in_progress_) { LOG(WARNING) << "Screen unlocked during suspend"; // If screen gets unlocked during suspend, which could theoretically // happen if the user initiated unlock just as device started unlocking // (though, it seems unlikely this would be encountered in practice), // relock the device if required. Otherwise, if suspend is blocked due to // screen locking, unblock it. if (ShouldLockOnSuspend()) { lock_state_ = LockState::kLocking; Shell::Get()->lock_state_controller()->LockWithoutAnimation(); } else if (displays_suspended_callback_) { StopCompositingAndSuspendDisplays(); } } } } void PowerEventObserver::StartRootWindowCompositors() { for (aura::Window* window : Shell::GetAllRootWindows()) { ui::Compositor* compositor = window->GetHost()->compositor(); if (!compositor->IsVisible()) compositor->SetVisible(true); } } void PowerEventObserver::StopCompositingAndSuspendDisplays() { DCHECK(displays_suspended_callback_); DCHECK(!compositor_watcher_.get()); for (aura::Window* window : Shell::GetAllRootWindows()) { ui::Compositor* compositor = window->GetHost()->compositor(); compositor->SetVisible(false); } ui::UserActivityDetector::Get()->OnDisplayPowerChanging(); // TODO(derat): After mus exposes a method for suspending displays, call it // here: http://crbug.com/692193 if (Shell::GetAshConfig() != Config::MASH) { Shell::Get()->display_configurator()->SuspendDisplays( base::Bind(&OnSuspendDisplaysCompleted, base::Passed(&displays_suspended_callback_))); } else { std::move(displays_suspended_callback_).Run(); } } void PowerEventObserver::EndPendingWallpaperAnimations() { for (aura::Window* window : Shell::GetAllRootWindows()) { WallpaperWidgetController* wallpaper_widget_controller = RootWindowController::ForWindow(window)->wallpaper_widget_controller(); if (wallpaper_widget_controller->IsAnimating()) wallpaper_widget_controller->EndPendingAnimation(); } } void PowerEventObserver::OnCompositorsReadyForSuspend() { compositor_watcher_.reset(); lock_state_ = LockState::kLocked; if (displays_suspended_callback_) StopCompositingAndSuspendDisplays(); } } // namespace ash
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
228f42d80bb03af2317eac133e4f52b7060836a9
99387b630d7657c292dea99c7f1d6987925b667d
/src/snp_clustering.cpp
8035efa204047e26a516689dca54fe670b63de0b
[]
no_license
timdallman/snpaddress
8728b27d4074d2f82b904bb5fe19a0f8fcf0cf45
ee239617ec9ee8e882c055fe3e34412fddddce64
refs/heads/master
2020-04-15T00:06:19.999744
2015-08-04T12:13:14
2015-08-04T12:13:14
40,179,521
1
0
null
null
null
null
UTF-8
C++
false
false
10,758
cpp
#include <iostream> #include <string.h> #include <string> #include <sstream> #include <fstream> #include <iomanip> #include <vector> #include <cmath> #include <map> #include <vector> #include <algorithm> #include <stdio.h> #include <stdlib.h> using namespace std; ////////////////////////////////CLASSES////////////////////////////////// ///////////////////////////////FUNCTIONS///////////////////////////////// //convert string into int double cstr_double(string& str_double) { ostringstream osstr_double; osstr_double<<str_double<<endl; istringstream isstr_double(osstr_double.str()); double doublestr_double; isstr_double>>doublestr_double; return (doublestr_double); } //read matric file into multimap multimap <string, double> read_file(char *a) { //global variables multimap <string,double> mat; char split_char = '\t'; string line; string name1; string name2; double dist; ifstream infile (a); if (infile.is_open()) { while ( getline (infile,line)) { istringstream split(line); string each; int count = 0; while(std::getline(split, each, split_char)) { if(count == 0) { name1 = each; } if(count ==1) { name2 = each; } if(count ==2) { dist = cstr_double(each); } count++; } //Makes multimap of name1:name2 = snp_dist string pair = name1+":"+name2; mat.insert(make_pair(pair,dist)); string pair2 = name2+":"+name1; mat.insert(make_pair(pair2,dist)); } } return mat; } vector <vector <string> > make_links(multimap <string,double> mat, string each) { //global varaiables vector <vector <string> > links; vector <string> matches; string name1, name2; //set cutoff double co = cstr_double(each); multimap <string, double >::iterator it; char split_char = ':'; string old_name = ""; //vector for mathches //Loop through matrix multimap for (it=mat.begin(); it!=mat.end(); it++) { //get pair string pair = it->first; string splitter; istringstream split(pair); int count = 0; while(std::getline(split, splitter, split_char)) { if(count == 0) { name1 = splitter; } if(count == 1) { name2 = splitter; } count++; } //if a new strain if(name1 != old_name) { if(old_name != "") { links.push_back(matches); } //Create somewhere for the mathces matches.clear(); matches.push_back(name1); old_name = name1; } double dist = it->second; // if the distance less or equal to threshold and the strain to the matches if (dist <= co) { if(name1 != name2) { matches.push_back(name2); } } } // add final comparison links.push_back(matches); return links; } vector <vector <string> > define_clusters(vector <vector <string> > links) { //initial dedup sort(links.begin(), links.end()); vector <vector <string> >::iterator d_it; d_it = unique(links.begin(), links.end()); links.resize(distance(links.begin(),d_it)); //globals vector <vector <string> > clusters; clusters.resize(links.size()); //first pass to reduce the links //iterate over first cluster for (int i=0; i<links.size();i++) { vector <string> strains = links[i]; sort(strains.begin(), strains.end()); //iterate over the rest for (int j=i+1; j<links.size();j++) { vector <string> strains2 = links[j]; //sort clusters sort(strains2.begin(), strains2.end()); //check they have anything in common //initalise iterator vector <string>::iterator int_it; //result vector vector <string> int_check; int_check.resize(strains.size()+strains2.size()); int_it = set_intersection(strains.begin(), strains.end(), strains2.begin(), strains2.end(),int_check.begin()); //resize int_check.resize(int_it-int_check.begin()); if (int_check.size() > 0) { //they have a common strain so find the union //initalise iterator vector <string>::iterator union_it; //results vector vector <string> cluster; cluster.resize(strains.size()+strains2.size()); //find union union_it = set_union(strains.begin(), strains.end(), strains2.begin(), strains2.end(),cluster.begin()); //resize cluster.resize(union_it-cluster.begin()); sort(cluster.begin(), cluster.end()); links[j] = cluster; } } //return only unique vectors vector <vector <string> >::iterator d_it; d_it = unique(links.begin(), links.end()); links.resize(distance(links.begin(),d_it)); } //second pass on reduced links make clusters //iterate over first cluster for (int i=0; i<links.size();i++) { vector <string> strains = links[i]; sort(strains.begin(), strains.end()); clusters[i]= strains; //iterate over the rest for (int j=i+1; j<links.size();j++) { vector <string> strains2 = links[j]; //sort clusters sort(strains2.begin(), strains2.end()); //check they have anything in common //initalise iterator vector <string>::iterator int_it; //result vector vector <string> int_check; int_check.resize(strains.size()+strains2.size()); int_it = set_intersection(strains.begin(), strains.end(), strains2.begin(), strains2.end(),int_check.begin()); //resize int_check.resize(int_it-int_check.begin()); if (int_check.size() > 0) { //they have a common strain so find the union //initalise iterator vector <string>::iterator union_it; //results vector vector <string> cluster; cluster.resize(strains.size()+strains2.size()); //find union union_it = set_union(strains.begin(), strains.end(), strains2.begin(), strains2.end(),cluster.begin()); //resize cluster.resize(union_it-cluster.begin()); sort(cluster.begin(), cluster.end()); //can we merge with other clusters for(int k=0; k<clusters.size();k++) { //get strains from clusters vector <string> c_strains = clusters[k]; sort(c_strains.begin(), c_strains.end()); //check they have anything in common //initalise iterator vector <string>::iterator int_it; //result vector vector <string> int_check; int_check.resize(c_strains.size()+cluster.size()); int_it = set_intersection(c_strains.begin(), c_strains.end(), cluster.begin(), cluster.end(),int_check.begin()); //resize int_check.resize(int_it-int_check.begin()); if (int_check.size() > 0) { //initalise iterator vector <string>::iterator int_vector2; //results vector vector <string> cluster2; cluster2.resize(c_strains.size()+cluster.size()); //find union int_vector2 = set_union(c_strains.begin(), c_strains.end(), cluster.begin(), cluster.end(),cluster2.begin()); //resize cluster2.resize(int_vector2-cluster2.begin()); //update clusters clusters[i] = cluster2; clusters[k] = cluster2; } } } } } return clusters; } vector <vector <string> > remove_duplicate_clusters(vector <vector <string> > clusters) { sort(clusters.begin(), clusters.end()); //return only unique vectors vector <vector <string> >::iterator d_it; d_it = unique(clusters.begin(), clusters.end()); clusters.resize(distance(clusters.begin(),d_it)); return clusters; } void print_clusters(multimap <double, vector <vector <string> > > out_clusters, string co) { //globals multimap <double, vector <vector <string> > >::reverse_iterator it; multimap <string, vector <int> > strain_list; //print threshold header cout << "#\t" << co << "\n"; //loop through cutoffs for(it = out_clusters.rbegin(); it!=out_clusters.rend(); it++) { //create variables vector <vector <string> > clusters = it->second; double cutoff = it->first; //cout << cutoff; vector <vector <string> >::iterator c_it; //initialise cluster counter int i = 1; //loop through clusters for (c_it = clusters.begin(); c_it!=clusters.end(); c_it++) { //create variables vector <string>::iterator s_it; vector <string> strains = *c_it; if (strains.size() > 0) { //loop through strains for (s_it = strains.begin(); s_it!=strains.end(); s_it++) { //add to multimap multimap <string, vector <int> >::iterator st_it; //find strain_list for strain st_it = strain_list.find(*s_it); if(st_it != strain_list.end()) { //add cluster no st_it->second.push_back(i); } else { //create first instance vector<int> tmp; tmp.assign(1,i); strain_list.insert(make_pair(*s_it,tmp)); } } //iterate cluster counter i++; } } } //print clusters multimap <string, vector <int> >::iterator p_it; for(p_it = strain_list.begin();p_it!=strain_list.end(); p_it++) { //create variables string name = p_it->first; vector <int> clust = p_it->second; cout << name << "\t"; //iterator vector <int>::iterator v_it; string hier; for(v_it = clust.begin(); v_it!=clust.end();v_it++) { //convet to char and append to string std::stringstream ss; ss << *v_it; std::string str = ss.str(); hier.append(str); hier.append("."); } //remove last . hier.pop_back(); //print cout << hier; cout << "\n"; } } /////////////////////////////////Main//////////////////////////////////// int main(int argc, char *argv[]) { //IO if (argc <= 1) { cout << "Usage: " << argv[0] << "<snp matrix> <snp distances to use for clustering e.g 5:10:25:50>" << endl; exit(1); } //globals char * matrix = argv[1]; char * co = argv[2]; char split_char = ':'; multimap <string,double> mat; string each; istringstream split(co); multimap <double, vector <vector <string> > > out_clusters; //read matrix //cout << "reading matrix......\n"; mat = read_file(matrix); // for each threshold while(std::getline(split, each, split_char)) { //make initial links vector <vector <string> > links = make_links(mat, each); //make single linkage clusters vector <vector <string> > clusters = define_clusters(links); //remove duplicate clusters vector <vector <string> > dedup_clusters = remove_duplicate_clusters(clusters); //add to out_clusters multimap out_clusters.insert(make_pair(cstr_double(each),dedup_clusters)); } //print clusters print_clusters(out_clusters,co); return 0; }
[ "tim.dallman@phe.gov.uk" ]
tim.dallman@phe.gov.uk
9cdce25dba60d2156d236058ead315132f55681f
20b85b68ceb95798832bfc6858ddecc06d86250b
/plugins/mdaAmbience.h
420e4b2c61ff72eb3a04affc13cf8298f64a3d65
[ "MIT" ]
permissive
elk-audio/mda-vst2
6ede7e9bf303e087fa2b123bba8fff32b7a827f5
8ea6ef97946a617d73e48d245777e57fb984357f
refs/heads/master
2020-11-28T11:27:08.490888
2019-12-23T17:42:00
2019-12-23T17:42:00
229,798,075
6
2
null
null
null
null
UTF-8
C++
false
false
1,260
h
#ifndef __mdaAmbience_H #define __mdaAmbience_H #include "audioeffectx.h" class mdaAmbience : public AudioEffectX { public: mdaAmbience(audioMasterCallback audioMaster); ~mdaAmbience(); virtual void process(float **inputs, float **outputs, VstInt32 sampleFrames); virtual void processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames); virtual void setProgramName(char *name); virtual void getProgramName(char *name); virtual bool getProgramNameIndexed (VstInt32 category, VstInt32 index, char* name); virtual void setParameter(VstInt32 index, float value); virtual float getParameter(VstInt32 index); virtual void getParameterLabel(VstInt32 index, char *label); virtual void getParameterDisplay(VstInt32 index, char *text); virtual void getParameterName(VstInt32 index, char *text); virtual void suspend(); virtual bool getEffectName(char *name); virtual bool getVendorString(char *text); virtual bool getProductString(char *text); virtual VstInt32 getVendorVersion() { return 1000; } protected: float fParam0; float fParam1; float fParam2; float fParam3; float fParam4; float *buf1, *buf2, *buf3, *buf4; float fil, fbak, damp, wet, dry, size; VstInt32 pos, den, rdy; char programName[32]; }; #endif
[ "stefano@elk.audio" ]
stefano@elk.audio
41f2a3a27ef5711184ab146abf95e64679788802
39b0b95dc24b1b881ae606a4614b541b3c0329e1
/BJ_11060/BJ_11060_LCH.cpp
5caf5b789946d381a9129eb03663b668269d2f85
[]
no_license
Algorithm-Study-Of-Gist/ProblemSource
46c9c1deafc23e64407e4787a1b240770c4f31ff
f55ed6fe6569e8b82e7a3c5fb944aac33e15a267
refs/heads/master
2022-07-24T08:29:04.177285
2020-05-21T14:45:26
2020-05-21T14:45:26
261,803,305
1
3
null
2020-05-21T14:28:38
2020-05-06T15:35:12
Java
UTF-8
C++
false
false
369
cpp
#include <cstdio> int main(){ int n, jump[2000], dp[2000] = {0}; scanf("%d", &n); for(int i=0; i<n; i++) scanf("%d", &jump[i]); for(int i=1; i<n; i++) dp[i] = 99999999; for(int i=0; i<n; i++){ for(int j=1; j<=jump[i]; j++){ dp[i+j] = dp[i+j] > dp[i]+1 ? dp[i]+1 : dp[i+j]; } } if(dp[n-1] == 99999999) printf("-1"); else printf("%d", dp[n-1]); }
[ "chayhyeon@naver.com" ]
chayhyeon@naver.com
af81201a22708a93eab4e835cbffc31733d54346
8aae71a092645f62d6f835578accc1ceb6416283
/ebobekok adres.cpp
c40d97d4305c30484f3c852d929064d1c6a61795
[]
no_license
dogabaris/C_Ornekleri
9db3c55115bb62b98b7ca157a3aaf50e51a502d5
dc6b3201ccb7165106f2decdeabcf7025eac4f41
refs/heads/master
2021-01-02T08:33:24.874333
2015-03-07T14:27:33
2015-03-07T14:27:33
31,814,348
0
0
null
null
null
null
UTF-8
C++
false
false
600
cpp
#include <stdio.h> #include <conio.h> void kontrol(int *,int *,int *,int *); main() { int girilen,s1,s2,ebob=1,ekok; printf("1. sayiyi girin = "); scanf("%d",&s1); printf("2. sayiyi girin = "); scanf("%d",&s2); kontrol(&s1,&s2,&ebob,&ekok); printf("ebob = %d\n",ebob); printf("ekok = %d",ekok); } void kontrol(int *s1,int *s2,int *ebob,int *ekok) { int kucuk,i,sayi1,sayi2; sayi1=*s1; sayi2=*s2; if(*s1<=*s2) {kucuk=*s1;} if(*s1>*s2) {kucuk=*s2;} for(i=2;i<=kucuk;i++) if(*s1%i==0 && *s2%i==0) { *s1=*s1/i; *s2=*s2/i; *ebob=*ebob*i; } *ekok=(sayi1)*(sayi2)/(*ebob); }
[ "dogabarisozdemir@gmail.com" ]
dogabarisozdemir@gmail.com