hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
473606e9e57605d14cc36446bfc8f714886ae17d
4,619
cpp
C++
documents/code/Chapter7/MarchingTetrahedra/TetrahedraMarcher.cpp
evertonantunes/OpenGLPlayground
1a7a9caaf81b250b90585dcdc128f6d55e391f7e
[ "MIT" ]
null
null
null
documents/code/Chapter7/MarchingTetrahedra/TetrahedraMarcher.cpp
evertonantunes/OpenGLPlayground
1a7a9caaf81b250b90585dcdc128f6d55e391f7e
[ "MIT" ]
null
null
null
documents/code/Chapter7/MarchingTetrahedra/TetrahedraMarcher.cpp
evertonantunes/OpenGLPlayground
1a7a9caaf81b250b90585dcdc128f6d55e391f7e
[ "MIT" ]
null
null
null
#include "TetrahedraMarcher.h" #include <fstream> #include "Tables.h" TetrahedraMarcher::TetrahedraMarcher(void) { XDIM = 256; YDIM = 256; ZDIM = 256; pVolume = NULL; } TetrahedraMarcher::~TetrahedraMarcher(void) { if(pVolume!=NULL) { delete [] pVolume; pVolume = NULL; } } void TetrahedraMarcher::SetVolumeDimensions(const int xdim, const int ydim, const int zdim) { XDIM = xdim; YDIM = ydim; ZDIM = zdim; invDim.x = 1.0f/XDIM; invDim.y = 1.0f/YDIM; invDim.z = 1.0f/ZDIM; } void TetrahedraMarcher::SetNumSamplingVoxels(const int x, const int y, const int z) { X_SAMPLING_DIST = x; Y_SAMPLING_DIST = y; Z_SAMPLING_DIST = z; } void TetrahedraMarcher::SetIsosurfaceValue(const GLubyte value) { isoValue = value; } bool TetrahedraMarcher::LoadVolume(const std::string& filename) { std::ifstream infile(filename.c_str(), std::ios_base::binary); if(infile.good()) { pVolume = new GLubyte[XDIM*YDIM*ZDIM]; infile.read(reinterpret_cast<char*>(pVolume), XDIM*YDIM*ZDIM*sizeof(GLubyte)); infile.close(); return true; } else { return false; } } void TetrahedraMarcher::SampleVoxel(const int x, const int y, const int z, glm::vec3 scale) { GLubyte cubeCornerValues[8]; int flagIndex, edgeFlags, i; glm::vec3 edgeVertices[12]; glm::vec3 edgeNormals[12]; //Make a local copy of the values at the cube's corners for( i = 0; i < 8; i++) { cubeCornerValues[i] = SampleVolume( x + (int)(a2fVertexOffset[i][0]*scale.x), y + (int)(a2fVertexOffset[i][1]*scale.y), z + (int)(a2fVertexOffset[i][2]*scale.z)); } //Find which vertices are inside of the surface and which are outside //Obtain a flagIndex based on if the value at the cube vertex is less //than the given isovalue flagIndex = 0; for( i= 0; i<8; i++) { if(cubeCornerValues[i] <= isoValue) flagIndex |= 1<<i; } //Find which edges are intersected by the surface edgeFlags = aiCubeEdgeFlags[flagIndex]; //If the cube is entirely inside or outside of the surface, then there will be no intersections if(edgeFlags == 0) { return; } //for all edges for(i = 0; i < 12; i++) { //if there is an intersection on this edge if(edgeFlags & (1<<i)) { //get the offset float offset = GetOffset(cubeCornerValues[ a2iEdgeConnection[i][0] ], cubeCornerValues[ a2iEdgeConnection[i][1] ]); //use offset to get the vertex position edgeVertices[i].x = x + (a2fVertexOffset[ a2iEdgeConnection[i][0] ][0] + offset * a2fEdgeDirection[i][0])*scale.x ; edgeVertices[i].y = y + (a2fVertexOffset[ a2iEdgeConnection[i][0] ][1] + offset * a2fEdgeDirection[i][1])*scale.y ; edgeVertices[i].z = z + (a2fVertexOffset[ a2iEdgeConnection[i][0] ][2] + offset * a2fEdgeDirection[i][2])*scale.z ; //use the vertex position to get the normal edgeNormals[i] = GetNormal( (int)edgeVertices[i].x , (int)edgeVertices[i].y , (int)edgeVertices[i].z ); } } //Draw the triangles that were found. There can be up to five per cube for(i = 0; i< 5; i++) { if(a2iTriangleConnectionTable[flagIndex][3*i] < 0) break; for(int j= 0; j< 3; j++) { int vertex = a2iTriangleConnectionTable[flagIndex][3*i+j]; Vertex v; v.normal = (edgeNormals[vertex]); v.pos = (edgeVertices[vertex])*invDim; vertices.push_back(v); } } } void TetrahedraMarcher::MarchVolume() { vertices.clear(); int dx = XDIM/X_SAMPLING_DIST; int dy = YDIM/Y_SAMPLING_DIST; int dz = ZDIM/Z_SAMPLING_DIST; glm::vec3 scale = glm::vec3(dx,dy,dz); for(int z=0;z<ZDIM;z+=dz) { for(int y=0;y<YDIM;y+=dy) { for(int x=0;x<XDIM;x+=dx) { SampleVoxel(x,y,z, scale); } } } } size_t TetrahedraMarcher::GetTotalVertices() { return vertices.size(); } Vertex* TetrahedraMarcher::GetVertexPointer() { return &vertices[0]; } GLubyte TetrahedraMarcher::SampleVolume(const int x, const int y, const int z) { int index = (x+(y*XDIM)) + z*(XDIM*YDIM); if(index<0) index = 0; if(index >= XDIM*YDIM*ZDIM) index = (XDIM*YDIM*ZDIM)-1; return pVolume[index]; } glm::vec3 TetrahedraMarcher::GetNormal (const int x, const int y, const int z) { glm::vec3 N; N.x = (SampleVolume(x-1,y,z)-SampleVolume(x+1,y,z))*0.5f ; N.y = (SampleVolume(x,y-1,z)-SampleVolume(x,y+1,z))*0.5f ; N.z = (SampleVolume(x,y,z-1)-SampleVolume(x,y,z+1))*0.5f ; return glm::normalize(N); } float TetrahedraMarcher::GetOffset(const GLubyte v1, const GLubyte v2) { float delta = (float)(v2-v1); if(delta == 0) return 0.5f; else return (isoValue-v1)/delta; }
27.993939
120
0.652739
evertonantunes
473731e1e9bd21c7cc06f33cff6cb8fdac9b44c1
18,378
cpp
C++
Max Objects/macOS/sofa~.mxo/Contents/Resources/SOFA/src/SOFADate.cpp
APL-Huddersfield/SOFA-for-Max
55e2dbe4b6ffa9e948cfaae2f134fbc00f5b354f
[ "BSD-3-Clause" ]
15
2019-03-31T22:03:21.000Z
2022-02-25T04:15:49.000Z
Max Objects/macOS/sofa~.mxo/Contents/Resources/SOFA/src/SOFADate.cpp
APL-Huddersfield/SOFA-for-Max
55e2dbe4b6ffa9e948cfaae2f134fbc00f5b354f
[ "BSD-3-Clause" ]
1
2022-03-15T16:14:57.000Z
2022-03-30T11:05:04.000Z
Max Objects/macOS/sofa~.mxo/Contents/Resources/SOFA/src/SOFADate.cpp
APL-Huddersfield/SOFA-for-Max
55e2dbe4b6ffa9e948cfaae2f134fbc00f5b354f
[ "BSD-3-Clause" ]
2
2019-03-31T22:04:08.000Z
2020-12-31T08:49:54.000Z
/* Copyright (c) 2013--2017, UMR STMS 9912 - Ircam-Centre Pompidou / CNRS / UPMC All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** Spatial acoustic data file format - AES69-2015 - Standard for File Exchange - Spatial Acoustic Data File Format http://www.aes.org SOFA (Spatially Oriented Format for Acoustics) http://www.sofaconventions.org */ /************************************************************************************/ /*! * @file SOFADate.cpp * @brief Useful methods to represent and manipulate date and time * @author Thibaut Carpentier, UMR STMS 9912 - Ircam-Centre Pompidou / CNRS / UPMC * * @date 10/05/2013 * */ /************************************************************************************/ #include "../src/SOFADate.h" #include "../src/SOFAString.h" #include "../src/SOFAHostArchitecture.h" #include <sstream> #include <iostream> #if( SOFA_UNIX == 1 || SOFA_MAC == 1 ) #include <time.h> #include <sys/time.h> #endif #if( SOFA_MAC == 1 ) #include <sys/time.h> #include <mach/mach_time.h> #endif using namespace sofa; #if ( SOFA_WINDOWS == 1 ) #include <windows.h> #include <time.h> #include <sys/timeb.h> #define literal64bit(longLiteral) ((__int64) longLiteral) #else #define literal64bit(longLiteral) (longLiteral##LL) #endif namespace DateHelper { static struct tm ConvertMillisecondsToLocalTime (const long long millis) { struct tm result; #if ( SOFA_WINDOWS == 1 ) const __int64 seconds = millis / 1000; #else const long long seconds = millis / 1000; #endif if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800)) { // use extended maths for dates beyond 1970 to 2037.. const int timeZoneAdjustment = 31536000 - (int) ( sofa::Date(1971, 0, 1, 0, 0).GetMillisecondsSinceEpoch() / 1000); const long long jdm = seconds + timeZoneAdjustment + literal64bit (210866803200); const int days = (int) (jdm / literal64bit (86400)); const int a = 32044 + days; const int b = (4 * a + 3) / 146097; const int c = a - (b * 146097) / 4; const int d = (4 * c + 3) / 1461; const int e = c - (d * 1461) / 4; const int m = (5 * e + 2) / 153; result.tm_mday = e - (153 * m + 2) / 5 + 1; result.tm_mon = m + 2 - 12 * (m / 10); result.tm_year = b * 100 + d - 6700 + (m / 10); result.tm_wday = (days + 1) % 7; result.tm_yday = -1; int t = (int) (jdm % literal64bit (86400)); result.tm_hour = t / 3600; t %= 3600; result.tm_min = t / 60; result.tm_sec = t % 60; result.tm_isdst = -1; } else { time_t now = static_cast <time_t> (seconds); #if ( SOFA_WINDOWS == 1 ) #ifdef _INC_TIME_INL if (now >= 0 && now <= 0x793406fff) { localtime_s (&result, &now); } else { memset( &result, 0, sizeof (result) ); } #else result = *localtime (&now); #endif #else // more thread-safe localtime_r (&now, &result); #endif } return result; } static int extendedModulo (const long long value, const int modulo) { return (int) (value >= 0 ? (value % modulo) : (value - ((value / modulo) + 1) * modulo)); } } Date Date::GetCurrentDate() { return Date( Date::GetCurrentSystemTime() ); } /************************************************************************************/ /*! * @brief Creates a Date object * * @details This default constructor creates a time of 1st January 1970, (which is * represented internally as 0ms). */ /************************************************************************************/ Date::Date() : millisSinceEpoch( 0 ) { } /************************************************************************************/ /*! * @brief Copy constructor * */ /************************************************************************************/ Date::Date( const Date &other ) : millisSinceEpoch( other.millisSinceEpoch ) { } /************************************************************************************/ /*! * @brief Copy operator * */ /************************************************************************************/ Date & Date::operator= (const Date &other) { millisSinceEpoch = other.millisSinceEpoch; return *this; } /************************************************************************************/ /*! * @brief Creates a Date object based on a number of milliseconds. * * @details The internal millisecond count is set to 0 (1st January 1970). To create a * time object set to the current time, use GetCurrentTime(). */ /************************************************************************************/ Date::Date(const long long millisecondsSinceEpoch) : millisSinceEpoch( millisecondsSinceEpoch ) { } long long Date::GetMillisecondsSinceEpoch() const { return millisSinceEpoch; } /************************************************************************************/ /*! * @brief Creates a date from a string literal in ISO8601 format * i.e. yyyy-mm-dd HH:MM:SS * @param[in] - * @param[out] - * @param[in, out] - * @return - * */ /************************************************************************************/ Date::Date(const std::string &iso8601) : millisSinceEpoch( 0 ) { const bool valid = Date::IsValid( iso8601 ); if( valid == true ) { const std::string yyyy = iso8601.substr( 0, 4 ); const std::string mm = iso8601.substr( 5, 2 ); const std::string dd = iso8601.substr( 8, 2 ); const std::string hh = iso8601.substr( 11, 2 ); const std::string min = iso8601.substr( 14, 2 ); const std::string sec = iso8601.substr( 17, 2 ); const int year = atoi( yyyy.c_str() ); const int month = atoi( mm.c_str() ); const int day = atoi( dd.c_str() ); const int hours = atoi( hh.c_str() ); const int minutes = atoi( min.c_str() ); const int seconds = atoi( sec.c_str() ); if( year < 0 || month < 0 || day < 0 || hours < 0 || minutes < 0 || seconds < 0) { SOFA_ASSERT( false ); } const sofa::Date tmp( year, month, day, hours, minutes, seconds ); *this = tmp; } } /************************************************************************************/ /*! * @brief Creates a Date from a set of date components * @param[in] year : the year, in 4-digit format, e.g. 2004 * @param[in] month : the month, in the range 1 to 12 * @param[in] day : the day of the month, in the range 1 to 31 * @param[in] hours : hours in 24-hour clock format, 0 to 23 * @param[in] minutes : minutes 0 to 59 * @param[in] seconds :seconds 0 to 59 * @param[in] milliseconds : milliseconds 0 to 999 * */ /************************************************************************************/ Date::Date (const unsigned int year, const unsigned int month_, const unsigned int day, const unsigned int hours, const unsigned int minutes, const unsigned int seconds, const unsigned int milliseconds) : millisSinceEpoch( 0 ) { SOFA_ASSERT( year > 100 ); // year must be a 4-digit version SOFA_ASSERT( month_ >= 1 && month_ <= 12); SOFA_ASSERT( day >= 1 && day <= 31); const unsigned int month = month_ - 1; ///< struct tm use [0-11] for month range if( year < 1971 || year >= 2038 ) { // use extended maths for dates beyond 1970 to 2037.. const int timeZoneAdjustment = 0; const int a = (13 - month) / 12; const int y = year + 4800 - a; const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5 + (y * 365) + (y / 4) - (y / 100) + (y / 400) - 32045; const long long s = ((long long) jd) * literal64bit (86400) - literal64bit (210866803200); millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment)) + milliseconds; } else { struct tm t; t.tm_year = year - 1900; t.tm_mon = month; t.tm_mday = day; t.tm_hour = hours; t.tm_min = minutes; t.tm_sec = seconds; t.tm_isdst = -1; millisSinceEpoch = 1000 * (long long) mktime (&t); if (millisSinceEpoch < 0) { millisSinceEpoch = 0; } else { millisSinceEpoch += milliseconds; } } } unsigned long long Date::getMillisecondsSinceStartup() { #if( SOFA_WINDOWS == 1 ) return (unsigned long long) timeGetTime(); #elif( SOFA_MAC == 1 ) const int64_t kOneMillion = 1000 * 1000; static mach_timebase_info_data_t s_timebase_info; if( s_timebase_info.denom == 0 ) { (void) mach_timebase_info( &s_timebase_info ); } // mach_absolute_time() returns billionth of seconds, // so divide by one million to get milliseconds return (unsigned long long)( (mach_absolute_time() * s_timebase_info.numer) / (kOneMillion * s_timebase_info.denom) ); #elif( SOFA_UNIX == 1 ) timespec t; clock_gettime( CLOCK_MONOTONIC, &t ); return t.tv_sec * 1000 + t.tv_nsec / 1000000; #else #error "Unknown host architecture" #endif } /************************************************************************************/ /*! * @brief Returns the current system time * * @details Returns the number of milliseconds since midnight jan 1st 1970 */ /************************************************************************************/ long long Date::GetCurrentSystemTime() { static unsigned int lastCounterResult = 0xffffffff; static long long correction = 0; const unsigned int now = (unsigned int) Date::getMillisecondsSinceStartup(); // check the counter hasn't wrapped (also triggered the first time this function is called) if( now < lastCounterResult ) { // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit. if ( lastCounterResult == 0xffffffff || now < lastCounterResult - 10 ) { // get the time once using normal library calls, and store the difference needed to // turn the millisecond counter into a real time. #if ( SOFA_WINDOWS == 1 ) struct _timeb t; #ifdef _INC_TIME_INL _ftime_s (&t); #else _ftime (&t); #endif correction = (((long long) t.time) * 1000 + t.millitm) - now; #else struct timeval tv; struct timezone tz; gettimeofday (&tv, &tz); correction = (((long long) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now; #endif } } lastCounterResult = now; return correction + now; } unsigned int Date::GetYear() const { return DateHelper::ConvertMillisecondsToLocalTime( this->millisSinceEpoch ).tm_year + 1900; } unsigned int Date::GetMonth() const { ///@n returns month in the range [1-12] return DateHelper::ConvertMillisecondsToLocalTime( this->millisSinceEpoch ).tm_mon + 1; } unsigned int Date::GetDay() const { return DateHelper::ConvertMillisecondsToLocalTime( this->millisSinceEpoch ).tm_mday; } unsigned int Date::GetHours() const { return DateHelper::ConvertMillisecondsToLocalTime( this->millisSinceEpoch ).tm_hour; } unsigned int Date::GetMinutes() const { return DateHelper::ConvertMillisecondsToLocalTime( this->millisSinceEpoch ).tm_min; } unsigned int Date::GetSeconds() const { return DateHelper::extendedModulo ( this->millisSinceEpoch / 1000, 60 ); } unsigned int Date::GetMilliSeconds() const { return DateHelper::extendedModulo( this->millisSinceEpoch, 1000 ); } std::string Date::ToISO8601() const { const unsigned int yyyy = GetYear(); const unsigned int mm = GetMonth(); const unsigned int dd = GetDay(); const unsigned int hh = GetHours(); const unsigned int min = GetMinutes(); const unsigned int ss = GetSeconds(); std::ostringstream str; str << yyyy; str << "-"; if( mm < 10 ) { /// zero-pad str << "0"; } str << mm; str << "-"; if( dd < 10 ) { /// zero-pad str << "0"; } str << dd; str << " "; if( hh < 10 ) { /// zero-pad str << "0"; } str << hh; str << ":"; if( min < 10 ) { /// zero-pad str << "0"; } str << min; str << ":"; if( ss < 10 ) { /// zero-pad str << "0"; } str << ss; return str.str(); } bool Date::IsValid() const { const unsigned int d = GetDay(); const unsigned int m = GetMonth(); const unsigned int y = GetYear(); const unsigned int hh = GetHours(); const unsigned int min = GetMinutes(); const unsigned int sec = GetSeconds(); if( d < 1 || d > 31 ) { return false; } if( m < 1 || m > 12 ) { return false; } if( y < 100 ) { return false; } if( m == 4 || m == 6 || m == 9 || m == 11 ) { if( d > 30 ) { return false; } } if( m == 2 && d > 29 ) { return false; } if( hh > 24 ) { return false; } if( min > 59 ) { return false; } if( sec > 60 ) { return false; } return true; } /************************************************************************************/ /*! * @brief Returns true if a string represents a Date with ISO8601 format * i.e. yyyy-mm-dd HH:MM:SS * @param[in] - * @param[out] - * @param[in, out] - * @return - * */ /************************************************************************************/ bool Date::IsValid(const std::string &iso8601) { const std::size_t length = iso8601.length(); if( length != 19 ) { return false; } const char * content = iso8601.c_str(); if( sofa::String::IsInt( content[0] ) == false || sofa::String::IsInt( content[1] ) == false || sofa::String::IsInt( content[2] ) == false || sofa::String::IsInt( content[3] ) == false || sofa::String::IsInt( content[5] ) == false || sofa::String::IsInt( content[6] ) == false || sofa::String::IsInt( content[8] ) == false || sofa::String::IsInt( content[9] ) == false || sofa::String::IsInt( content[11] ) == false || sofa::String::IsInt( content[12] ) == false || sofa::String::IsInt( content[14] ) == false || sofa::String::IsInt( content[15] ) == false || sofa::String::IsInt( content[17] ) == false || sofa::String::IsInt( content[18] ) == false ) { return false; } if( content[4] != '-' || content[7] != '-' ) { return false; } if( content[10] != ' ' ) { return false; } if( content[13] != ':' || content[16] != ':' ) { return false; } const std::string yyyy = iso8601.substr( 0, 4 ); const std::string mm = iso8601.substr( 5, 2 ); const std::string dd = iso8601.substr( 8, 2 ); const std::string hh = iso8601.substr( 11, 2 ); const std::string min = iso8601.substr( 14, 2 ); const std::string sec = iso8601.substr( 17, 2 ); const int year = sofa::String::String2Int( yyyy ); const int month = sofa::String::String2Int( mm ); const int day = sofa::String::String2Int( dd ); const int hours = sofa::String::String2Int( hh ); const int minutes = sofa::String::String2Int( min ); const int seconds = sofa::String::String2Int( sec ); if( year < 0 || month < 0 || day < 0 || hours < 0 || minutes < 0 || seconds < 0) { return false; } const sofa::Date tmp( year, month, day, hours, minutes, seconds ); return tmp.IsValid(); }
29.594203
127
0.512188
APL-Huddersfield
473ab4f0d92426be9f316ecb4889d8c6965e1e86
2,959
cxx
C++
icetray/private/modules/MaintainInitialValuesModule.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
1
2020-12-24T22:00:01.000Z
2020-12-24T22:00:01.000Z
icetray/private/modules/MaintainInitialValuesModule.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
null
null
null
icetray/private/modules/MaintainInitialValuesModule.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
3
2020-07-17T09:20:29.000Z
2021-03-30T16:44:18.000Z
/** * copyright (C) 2004 * the icecube collaboration * $Id: MaintainInitialValuesModule.cxx 176001 2019-10-09 22:16:53Z olivas $ * * @version $Revision: 176001 $ * @date $Date: 2019-10-09 16:16:53 -0600 (Wed, 09 Oct 2019) $ * @author troy d. straszheim * * This tests that the global GetService<> works; that the underlying * context-switching is done correctly. */ #include <icetray/I3Tray.h> #include <icetray/I3Frame.h> #include <icetray/I3Module.h> #include <icetray/OMKey.h> #include <boost/assign/std/vector.hpp> using namespace boost::assign; static bool bool_param; static unsigned char uchar_param; static int int_param; static long long_param; static double double_param; static std::string string_param; static OMKey omkey_param; struct MyService{}; struct MaintainInitialValuesModule : I3Module { boost::shared_ptr<MyService> service_ptr_param; MaintainInitialValuesModule(const I3Context& context) : I3Module(context) { bool_param = true; AddParameter("bool_param", "description of bool", bool_param); uchar_param = std::numeric_limits<unsigned char>::max(); AddParameter("uchar_param", "description of uchar", uchar_param); int_param = std::numeric_limits<int>::max(); AddParameter("int_param", "description of int", int_param); long_param = std::numeric_limits<long>::max(); AddParameter("long_param", "description of long", long_param); double_param = 3.1415926535897932; AddParameter("double_param", "description of double", double_param); string_param = "We can't stop here. This is Bat Country!"; AddParameter("string_param", "description of string", string_param); omkey_param = OMKey(-666,666); AddParameter("omkey_param", "OMKey!", omkey_param); service_ptr_param = boost::shared_ptr<MyService>( new MyService); AddParameter("service_ptr_param", "pointer to service.",service_ptr_param); } virtual void Configure() { GetParameter("bool_param", bool_param); GetParameter("uchar_param", uchar_param); GetParameter("int_param", int_param); GetParameter("long_param", long_param); GetParameter("double_param", double_param); GetParameter("string_param", string_param); GetParameter("omkey_param", omkey_param); GetParameter("service_ptr_param",service_ptr_param); i3_assert( bool_param == true); i3_assert( uchar_param == std::numeric_limits<unsigned char>::max() ); i3_assert( int_param == std::numeric_limits<int>::max()); i3_assert( long_param == std::numeric_limits<long>::max()); i3_assert( double_param == 3.1415926535897932); i3_assert( string_param == "We can't stop here. This is Bat Country!"); i3_assert( omkey_param == OMKey(-666,666)); i3_assert( service_ptr_param ); } virtual void Process() { I3FramePtr frame = PopFrame(); PushFrame(frame, "OutBox"); } virtual void Finish() { ; } }; I3_MODULE(MaintainInitialValuesModule);
31.478723
79
0.715444
hschwane
473b00feadf6feea3657aeebfd555c7af7f8ed95
635
hpp
C++
BaCa_P2/zadanieA/src/BitSetLib.hpp
arhmichal/P2_BaCa
2567897544c907dac60290c3b727fc170310786c
[ "MIT" ]
1
2018-03-21T18:29:29.000Z
2018-03-21T18:29:29.000Z
BaCa_P2/zadanieA/src/BitSetLib.hpp
arhmichal/P2_BaCa
2567897544c907dac60290c3b727fc170310786c
[ "MIT" ]
null
null
null
BaCa_P2/zadanieA/src/BitSetLib.hpp
arhmichal/P2_BaCa
2567897544c907dac60290c3b727fc170310786c
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <string> #include <sstream> void Emplace(std::string, int*); void Insert(std::string, int*); void Erase(std::string, int*); void Print(int, std::string*); bool Emptiness(int); bool Nonempty(int); bool Member(std::string, int); bool Disjoint(int, int); bool Conjunctive(int, int); bool Equality(int, int); bool Inclusion(int, int); void Union(int, int, int*); void Intersection(int, int, int*); void Symmetric(int, int, int*); void Difference(int, int, int*); void Complement(int, int*); bool LessThen(int, int); bool LessEqual(int, int); bool GreatEqual(int, int); bool GreatThen(int, int);
23.518519
34
0.711811
arhmichal
47413e28fc7ab0bc3482d239c7baba537dc4340b
1,962
cpp
C++
aby3/sh3/Sh3Converter.cpp
cyckun/aby3
99af31ccaef6cd2c22df8ef57d8b7a07d62c66cf
[ "MIT" ]
121
2019-06-25T01:35:50.000Z
2022-03-24T12:53:17.000Z
aby3/sh3/Sh3Converter.cpp
cyckun/aby3
99af31ccaef6cd2c22df8ef57d8b7a07d62c66cf
[ "MIT" ]
33
2020-01-21T16:47:09.000Z
2022-01-23T12:41:22.000Z
aby3/sh3/Sh3Converter.cpp
cyckun/aby3
99af31ccaef6cd2c22df8ef57d8b7a07d62c66cf
[ "MIT" ]
36
2019-09-05T08:35:09.000Z
2022-01-14T11:57:22.000Z
#include "Sh3Converter.h" #include <libOTe/Tools/Tools.h> #include "Sh3BinaryEvaluator.h" using namespace oc; namespace aby3 { void Sh3Converter::toPackedBin(const sbMatrix & in, sPackedBin & dest) { dest.reset(in.rows(), in.bitCount()); for (u64 i = 0; i < 2; ++i) { auto& s = in.mShares[i]; auto& d = dest.mShares[i]; MatrixView<u8> inView( (u8*)(s.data()), (u8*)(s.data() + s.size()), sizeof(i64) * s.cols()); MatrixView<u8> memView( (u8*)(d.data()), (u8*)(d.data() + d.size()), sizeof(i64) * d.cols()); transpose(inView, memView); } } void Sh3Converter::toBinaryMatrix(const sPackedBin & in, sbMatrix & dest) { dest.resize(in.shareCount(), in.bitCount()); for (u64 i = 0; i < 2; ++i) { auto& s = in.mShares[i]; auto& d = dest.mShares[i]; MatrixView<u8> inView( (u8*)(s.data()), (u8*)(s.data() + s.size()), sizeof(i64) * s.cols()); MatrixView<u8> memView( (u8*)(d.data()), (u8*)(d.data() + d.size()), sizeof(i64) * d.cols()); transpose(inView, memView); } } Sh3Task Sh3Converter::toPackedBin(Sh3Task dep, Sh3ShareGen& gen, const si64Matrix& in, sPackedBin& dest) { return dep.then([&](CommPkg & comm, Sh3Task self) { struct State { Sh3BinaryEvaluator mEval; //oc::BetaCircuit mCircuit; }; auto state = std::make_unique<State>(); state->mEval.setCir(mLib.convert_arith_to_bin(in.cols(), 64), in.rows(), gen); throw RTE_LOC; //state->mEval.setInput //for(u64 i =0; i < in.) }); } }
25.815789
108
0.462793
cyckun
4741de12653948415081686fc85895d4ff90ccb1
3,515
cpp
C++
QVES-App/DataPanel.cpp
joaconigro/QVES
66498286838a60dbc7d3c1bd7bc7644208ae05a3
[ "MIT" ]
2
2017-08-09T17:32:47.000Z
2018-04-03T11:05:12.000Z
QVES-App/DataPanel.cpp
joaconigro/QVES
66498286838a60dbc7d3c1bd7bc7644208ae05a3
[ "MIT" ]
null
null
null
QVES-App/DataPanel.cpp
joaconigro/QVES
66498286838a60dbc7d3c1bd7bc7644208ae05a3
[ "MIT" ]
2
2017-10-19T04:44:37.000Z
2019-04-29T08:59:44.000Z
#include "DataPanel.h" #include "ui_DataPanel.h" DataPanel::DataPanel(QVESModelDelegate *delegate, QWidget *parent) : QWidget(parent), ui(new Ui::DataPanel), mainDelegate(delegate) { ui->setupUi(this); ui->radioButtonField->setChecked(true); mResetSelection = false; selectionModel = nullptr; changeShowedData(); ui->tableView->setItemDelegate(new TableDelegate); ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); connect(ui->comboBoxCurrentVes, static_cast<void(QComboBox::*)(int)>(&QComboBox::activated), this, &DataPanel::currentVESIndexChanged); connect(ui->comboBoxVesModel, static_cast<void(QComboBox::*)(int)>(&QComboBox::activated), this, &DataPanel::currentVESModelIndexChanged); } DataPanel::~DataPanel() { delete ui; } void DataPanel::setMyModel() { ui->tableView->reset(); ui->tableView->setModel(mainDelegate->currentModel()); selectionModel = ui->tableView->selectionModel(); connect(selectionModel, &QItemSelectionModel::selectionChanged, this, &DataPanel::selectionChanged); for (int c = 0; c < ui->tableView->horizontalHeader()->count(); ++c) { ui->tableView->horizontalHeader()->setSectionResizeMode(c, QHeaderView::Stretch); } loadVESNames(); loadModelNames(); if (mResetSelection){ selectionModel->select(mPreviousIndex, QItemSelectionModel::Select); mResetSelection = false; } } void DataPanel::loadVESNames() { ui->comboBoxCurrentVes->clear(); ui->comboBoxCurrentVes->addItems(mainDelegate->vesNames()); ui->comboBoxCurrentVes->blockSignals(true); ui->comboBoxCurrentVes->setCurrentIndex(mainDelegate->currentVESIndex()); ui->comboBoxCurrentVes->blockSignals(false); } void DataPanel::loadModelNames() { ui->comboBoxVesModel->clear(); ui->comboBoxVesModel->addItems(mainDelegate->modelNames()); ui->comboBoxVesModel->setCurrentIndex(mainDelegate->currentVESModelIndex()); } void DataPanel::changeShowedData() { if(ui->radioButtonField->isChecked()){ mSelectedData = TableModel::DataType::Field; ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed | QAbstractItemView::AnyKeyPressed); }else if (ui->radioButtonSplice->isChecked()) { mSelectedData = TableModel::DataType::Splice; ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); }else if (ui->radioButtonCalculated->isChecked()) { mSelectedData = TableModel::DataType::Calculated; ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); }else if (ui->radioButtonModeled->isChecked()) { mSelectedData = TableModel::DataType::Model; ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed | QAbstractItemView::AnyKeyPressed); } if (selectionModel) selectionModel->clearSelection(); emit showedDataChanged(mSelectedData); } void DataPanel::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { Q_UNUSED(selected) Q_UNUSED(deselected) QList<int> indices; int i; foreach (const auto &s, selectionModel->selectedIndexes()) { i = s.row(); if(!(indices.contains(i))) indices.append(i); } emit rowSelectionChanged(indices, mSelectedData); } void DataPanel::restoreSelection(const QModelIndex &index) { mPreviousIndex = index; mResetSelection = true; }
33.47619
144
0.714651
joaconigro
474334400e6b7b54ea439df22a9af425ed1fedb4
1,425
cpp
C++
learn_opencv3.1.0/source/chapter/chapter_030.cpp
k9bao/learn_opencv
6fc6ec435ed2223d43f6a79c97ceb2475f7bf5c3
[ "Apache-2.0" ]
null
null
null
learn_opencv3.1.0/source/chapter/chapter_030.cpp
k9bao/learn_opencv
6fc6ec435ed2223d43f6a79c97ceb2475f7bf5c3
[ "Apache-2.0" ]
null
null
null
learn_opencv3.1.0/source/chapter/chapter_030.cpp
k9bao/learn_opencv
6fc6ec435ed2223d43f6a79c97ceb2475f7bf5c3
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <math.h> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; Mat src, dst; const char *output_win = "findcontours-demo"; int threshold_value = 100; int threshold_max = 255; RNG rng; void Demo_Contours(int, void *); int main(int argc, char **argv) { src = imread("happyfish.png"); if (src.empty()) { printf("could not load image...\n"); return -1; } namedWindow("input-image", CV_WINDOW_AUTOSIZE); namedWindow(output_win, CV_WINDOW_AUTOSIZE); imshow("input-image", src); cvtColor(src, src, CV_BGR2GRAY); const char *trackbar_title = "Threshold Value:"; createTrackbar(trackbar_title, output_win, &threshold_value, threshold_max, Demo_Contours); Demo_Contours(0, 0); waitKey(0); return 0; } void Demo_Contours(int, void *) { Mat canny_output; vector<vector<Point>> contours; vector<Vec4i> hierachy; Canny(src, canny_output, threshold_value, threshold_value * 2, 3, false); findContours(canny_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0)); dst = Mat::zeros(src.size(), CV_8UC3); RNG rng(12345); for (size_t i = 0; i < contours.size(); i++) { Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); drawContours(dst, contours, i, color, 2, 8, hierachy, 0, Point(0, 0)); } imshow(output_win, dst); }
30.319149
96
0.666667
k9bao
4745f641e7c0cbfd95ff7354442d29603f99b28e
941
cpp
C++
src/tools/qt-gui/src/editkeycommand.cpp
D-os/libelektra
e39f439bfa5ff1fe56e6c8c7ee290913449d1dde
[ "BSD-3-Clause" ]
null
null
null
src/tools/qt-gui/src/editkeycommand.cpp
D-os/libelektra
e39f439bfa5ff1fe56e6c8c7ee290913449d1dde
[ "BSD-3-Clause" ]
null
null
null
src/tools/qt-gui/src/editkeycommand.cpp
D-os/libelektra
e39f439bfa5ff1fe56e6c8c7ee290913449d1dde
[ "BSD-3-Clause" ]
null
null
null
#include "editkeycommand.hpp" EditKeyCommand::EditKeyCommand(TreeViewModel* model, int index, DataContainer* data, QUndoCommand* parent) : QUndoCommand(parent) , m_model(model) , m_index(index) , m_oldName(data->oldName()) , m_oldValue(data->oldValue()) , m_oldMetaData(data->oldMetadata()) , m_newName(data->newName()) , m_newValue(data->newValue()) , m_newMetaData(data->newMetadata()) { setText("edit"); } void EditKeyCommand::undo() { QModelIndex index = m_model->index(m_index); m_model->setData(index, m_oldName, TreeViewModel::NameRole); m_model->setData(index, m_oldValue, TreeViewModel::ValueRole); m_model->model().at(m_index)->setMeta(m_oldMetaData); } void EditKeyCommand::redo() { QModelIndex index = m_model->index(m_index); m_model->setData(index, m_newName, TreeViewModel::NameRole); m_model->setData(index, m_newValue, TreeViewModel::ValueRole); m_model->model().at(m_index)->setMeta(m_newMetaData); }
29.40625
106
0.746015
D-os
4748eb04b61b468b44e28c9d8ea38544fbddc8c4
1,083
cpp
C++
various/OPENEDG/ch1/unique.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
14
2019-04-23T13:45:10.000Z
2022-03-12T18:26:47.000Z
various/OPENEDG/ch1/unique.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
null
null
null
various/OPENEDG/ch1/unique.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
9
2019-09-01T15:17:45.000Z
2020-11-13T20:31:36.000Z
#include <list> #include <iostream> using namespace std; template<class I> void print (const I & start, const I & end) { for(I it = start; it != end; ++it) { cout<< *it << " "; } cout<<endl; } bool compareInt(double v1, double v2) { if ((int)v1 == (int)v2) { return true; } return false; } int main() { double a[]={1.6,2.3,1.4,3.1,2.4,3.5,4.9,3.2,4.7,7.8,8, 9.1,6.2,6.8,5.5,8.4,9.2,10}; list <int> l1(a,a+18); list <int> l2(a,a+18); print(l1.begin(), l1.end()); cout<<"Deleting all subsequent duplicates - int comparison"<<endl; l1.unique(compareInt); print(l1.begin(), l1.end()); cout<<"Deleting all subsequent duplicates - int comparison - sorted" <<endl; l2.sort(); l2.unique(compareInt); print(l2.begin(), l2.end()); return 0; } /* 1 2 1 3 2 3 4 3 4 7 8 9 6 6 5 8 9 10 Deleting all subsequent duplicates - int comparison 1 2 1 3 2 3 4 3 4 7 8 9 6 5 8 9 10 Deleting all subsequent duplicates - int comparison - sorted 1 2 3 4 5 6 7 8 9 10 */
20.055556
73
0.561404
chgogos
4749bff31a4155950511394e49ba3aece171cec7
4,431
cpp
C++
src/Utils/HttpParser.cpp
lkmaks/caos-http-web-server-by-Lavrik-Karmazin
a2bd3ca9a7f0418e331a7a7f9b874e6c876c8739
[ "MIT" ]
null
null
null
src/Utils/HttpParser.cpp
lkmaks/caos-http-web-server-by-Lavrik-Karmazin
a2bd3ca9a7f0418e331a7a7f9b874e6c876c8739
[ "MIT" ]
null
null
null
src/Utils/HttpParser.cpp
lkmaks/caos-http-web-server-by-Lavrik-Karmazin
a2bd3ca9a7f0418e331a7a7f9b874e6c876c8739
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <map> #include "HttpParser.h" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include "GeneralUtils.h" #include "Debug.hpp" typedef std::string::size_type size_type; bool is_substr(const std::string &t, const std::string &s, int pos) { // is t a susbtr of s from position pos in s // pos is correct position in s if (pos + t.size() > s.size()) { return false; } for (int i = 0; i < t.size(); ++i) { if (t[i] != s[pos + i]) { return false; } } return true; } bool is_okay_uri(const std::string &uri) { return true; // for now } bool is_ok_http_firstline(const std::string &data, int end_pos, std::vector<std::string> &http_methods, HttpFirstLine &first_line) { std::string right_method; for (auto &method : http_methods) { if (is_substr(method, data, 0)) { right_method = method; } } if (right_method.empty()) { return false; } std::string ending("HTTP/1.1"); if (!is_substr(ending, data, (int)end_pos - (int)ending.size())) { return false; } int uri_len = end_pos - (int)(right_method.size() + ending.size() + 2); if (uri_len <= 0 || data[right_method.size()] != ' ' || data[end_pos - ending.size() - 1] != ' ') { return false; } std::string uri = data.substr(right_method.size() + 1, uri_len); if (!is_okay_uri(uri)) { return false; } first_line.method = right_method; first_line.uri = uri; return true; } bool is_ok_header_section(const std::string &data, int start_pos, int end_pos, HttpHeaders &headers) { std::map<std::string, std::string> result; size_type i = start_pos; while (i < end_pos) { size_type j = data.find("\r\n", i); if (j == std::string::npos) { j = data.size(); } std::string cur_str = data.substr(i, j - i); size_type pos = cur_str.find(": "); if (pos == std::string::npos) { return false; } std::string left = cur_str.substr(0, pos); std::string right = cur_str.substr(pos + 2, cur_str.size() - (pos + 2)); result[left] = right; i = j + 2; } headers.dict = std::move(result); return true; } bool is_http_end_of_line(const std::string &data, int pos) { if (pos == 0) { return false; } return data.substr(pos - 1, 2) == "\r\n"; } bool is_http_end_of_headers(const std::string &data, int pos) { if (pos < 3) { return false; } return data.substr(pos - 3, 4) == "\r\n\r\n"; } bool is_ok_path(const std::string &path) { // check if path is of template: // /{s_1}/.../{s_n}, s_i does not contain '/', is not '.' or '..', is not empty auto arr = split(path, '/'); if (arr.empty()) { return false; } if (arr[0] != "") { return false; } for (int i = 1; i < arr.size(); ++i) { if (arr[i] == "" || arr[i] == "." || arr[i] == "..") { return false; } } return true; } bool file_exists(const std::string &path) { // assume is_ok_path(path) FILE *file = fopen(path.c_str(), "r"); if (!file) { return false; } fclose(file); return true; } bool is_gettable_file(const std::string &path, Config &config) { // assume is_ok_path(path), // file_exists(path) == true struct stat statbuf; int status = lstat(path.c_str(), &statbuf); if (!(status == 0 && S_ISREG(statbuf.st_mode))) { return false; } int pos = config.data_dir.size() + 2; // after / after data_dir auto pos2 = path.find("/", pos); // that will be '/' after hostname dir return is_substr("static/", path, pos2 + 1); // have to go through static dir (dir_1 == static) } bool is_ok_qvalue_list(const std::string &str, std::vector<std::string> &mime_types) { auto vec = split(str, ','); for (auto &part : vec) { mime_types.push_back(part.substr(0, part.find(';'))); } return true; // tolerancy, for now } int file_size(const std::string &path) { // assume is_ok_path(path), file_exists(path) struct stat statbuf; lstat(path.c_str(), &statbuf); return statbuf.st_size; } std::string file_contents(const std::string &path) { // assume is_ok_path(path), file_exists(path) FILE *file = fopen(path.c_str(), "r"); int chunk_size = 256; char buf[chunk_size]; std::string res; int cnt; while ((cnt = fread(buf, 1, chunk_size, file)) > 0) { for (int i = 0; i < cnt; ++i) { res.push_back(buf[i]); } } return res; }
24.213115
102
0.60009
lkmaks
4749d5691fdc3d53230a2008b7ea862ed6cc64a6
8,947
cpp
C++
src/Game/Terrain/Block.cpp
NikiNatov/Minecraft_Clone
f3c04d595f06ceca2c060f44d67d2b4be751896c
[ "Apache-2.0" ]
null
null
null
src/Game/Terrain/Block.cpp
NikiNatov/Minecraft_Clone
f3c04d595f06ceca2c060f44d67d2b4be751896c
[ "Apache-2.0" ]
null
null
null
src/Game/Terrain/Block.cpp
NikiNatov/Minecraft_Clone
f3c04d595f06ceca2c060f44d67d2b4be751896c
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "Block.h" #include "Graphics\SpriteManager.h" std::vector<ScopedPtr<Block>> Block::s_Blocks; Block::Block(BlockID id) : m_ID(id) { glm::vec3 positions[8]; positions[0] = { 0.0f, 0.0f, 1.0f }; positions[1] = { 1.0f, 0.0f, 1.0f }; positions[2] = { 1.0f, 1.0f, 1.0f }; positions[3] = { 0.0f, 1.0f, 1.0f }; positions[4] = { 0.0f, 0.0f, 0.0f }; positions[5] = { 1.0f, 0.0f, 0.0f }; positions[6] = { 1.0f, 1.0f, 0.0f }; positions[7] = { 0.0f, 1.0f, 0.0f }; glm::vec3 normals[6]; normals[(uint8_t)BlockFaceID::Front] = { 0.0f, 0.0f, 1.0f }; normals[(uint8_t)BlockFaceID::Back] = { 0.0f, 0.0f, -1.0f }; normals[(uint8_t)BlockFaceID::Left] = { -1.0f, 0.0f, 0.0f }; normals[(uint8_t)BlockFaceID::Right] = { 1.0f, 0.0f, 0.0f }; normals[(uint8_t)BlockFaceID::Up] = { 0.0f, 1.0f, 0.0f }; normals[(uint8_t)BlockFaceID::Down] = { 0.0f, -1.0f, 0.0f }; // Front face m_Faces[(uint8_t)BlockFaceID::Front].Vertices[0].Position = positions[0]; m_Faces[(uint8_t)BlockFaceID::Front].Vertices[1].Position = positions[1]; m_Faces[(uint8_t)BlockFaceID::Front].Vertices[2].Position = positions[2]; m_Faces[(uint8_t)BlockFaceID::Front].Vertices[3].Position = positions[3]; for (int i = 0; i < 4; i++) { m_Faces[(uint8_t)BlockFaceID::Front].Vertices[i].Normal = normals[(uint8_t)BlockFaceID::Front]; m_Faces[(uint8_t)BlockFaceID::Front].Vertices[i].LightLevel = 0.8f; } // Back face m_Faces[(uint8_t)BlockFaceID::Back].Vertices[0].Position = positions[4]; m_Faces[(uint8_t)BlockFaceID::Back].Vertices[1].Position = positions[5]; m_Faces[(uint8_t)BlockFaceID::Back].Vertices[2].Position = positions[6]; m_Faces[(uint8_t)BlockFaceID::Back].Vertices[3].Position = positions[7]; for (int i = 0; i < 4; i++) { m_Faces[(uint8_t)BlockFaceID::Back].Vertices[i].Normal = normals[(uint8_t)BlockFaceID::Back]; m_Faces[(uint8_t)BlockFaceID::Back].Vertices[i].LightLevel = 0.8f; } // Left face m_Faces[(uint8_t)BlockFaceID::Left].Vertices[0].Position = positions[4]; m_Faces[(uint8_t)BlockFaceID::Left].Vertices[1].Position = positions[0]; m_Faces[(uint8_t)BlockFaceID::Left].Vertices[2].Position = positions[3]; m_Faces[(uint8_t)BlockFaceID::Left].Vertices[3].Position = positions[7]; for (int i = 0; i < 4; i++) { m_Faces[(uint8_t)BlockFaceID::Left].Vertices[i].Normal = normals[(uint8_t)BlockFaceID::Left]; m_Faces[(uint8_t)BlockFaceID::Left].Vertices[i].LightLevel = 0.6f; } // Right face m_Faces[(uint8_t)BlockFaceID::Right].Vertices[0].Position = positions[1]; m_Faces[(uint8_t)BlockFaceID::Right].Vertices[1].Position = positions[5]; m_Faces[(uint8_t)BlockFaceID::Right].Vertices[2].Position = positions[6]; m_Faces[(uint8_t)BlockFaceID::Right].Vertices[3].Position = positions[2]; for (int i = 0; i < 4; i++) { m_Faces[(uint8_t)BlockFaceID::Right].Vertices[i].Normal = normals[(uint8_t)BlockFaceID::Right]; m_Faces[(uint8_t)BlockFaceID::Right].Vertices[i].LightLevel = 0.6f; } // Up face m_Faces[(uint8_t)BlockFaceID::Up].Vertices[0].Position = positions[3]; m_Faces[(uint8_t)BlockFaceID::Up].Vertices[1].Position = positions[2]; m_Faces[(uint8_t)BlockFaceID::Up].Vertices[2].Position = positions[6]; m_Faces[(uint8_t)BlockFaceID::Up].Vertices[3].Position = positions[7]; for (int i = 0; i < 4; i++) { m_Faces[(uint8_t)BlockFaceID::Up].Vertices[i].Normal = normals[(uint8_t)BlockFaceID::Up]; m_Faces[(uint8_t)BlockFaceID::Up].Vertices[i].LightLevel = 1.0f; } // Down face m_Faces[(uint8_t)BlockFaceID::Down].Vertices[0].Position = positions[0]; m_Faces[(uint8_t)BlockFaceID::Down].Vertices[1].Position = positions[1]; m_Faces[(uint8_t)BlockFaceID::Down].Vertices[2].Position = positions[5]; m_Faces[(uint8_t)BlockFaceID::Down].Vertices[3].Position = positions[4]; for (int i = 0; i < 4; i++) { m_Faces[(uint8_t)BlockFaceID::Down].Vertices[i].Normal = normals[(uint8_t)BlockFaceID::Down]; m_Faces[(uint8_t)BlockFaceID::Down].Vertices[i].LightLevel = 0.4f; } SetBlockTextures(id); } void Block::SetBlockTextures(BlockID block) { Ref<SubTexture2D> upFace, downFace, leftFace, rightFace, frontFace, backFace; switch (block) { case BlockID::Grass: { upFace = SpriteManager::GetSprite("GrassTop"); downFace = SpriteManager::GetSprite("Dirt"); leftFace = SpriteManager::GetSprite("GrassSide"); rightFace = SpriteManager::GetSprite("GrassSide"); frontFace = SpriteManager::GetSprite("GrassSide"); backFace = SpriteManager::GetSprite("GrassSide"); break; } case BlockID::Dirt: { upFace = SpriteManager::GetSprite("Dirt"); downFace = SpriteManager::GetSprite("Dirt"); leftFace = SpriteManager::GetSprite("Dirt"); rightFace = SpriteManager::GetSprite("Dirt"); frontFace = SpriteManager::GetSprite("Dirt"); backFace = SpriteManager::GetSprite("Dirt"); break; } case BlockID::Stone: { upFace = SpriteManager::GetSprite("Stone"); downFace = SpriteManager::GetSprite("Stone"); leftFace = SpriteManager::GetSprite("Stone"); rightFace = SpriteManager::GetSprite("Stone"); frontFace = SpriteManager::GetSprite("Stone"); backFace = SpriteManager::GetSprite("Stone"); break; } case BlockID::Bedrock: { upFace = SpriteManager::GetSprite("Bedrock"); downFace = SpriteManager::GetSprite("Bedrock"); leftFace = SpriteManager::GetSprite("Bedrock"); rightFace = SpriteManager::GetSprite("Bedrock"); frontFace = SpriteManager::GetSprite("Bedrock"); backFace = SpriteManager::GetSprite("Bedrock"); break; } case BlockID::Water: { upFace = SpriteManager::GetSprite("Water"); downFace = SpriteManager::GetSprite("Water"); leftFace = SpriteManager::GetSprite("Water"); rightFace = SpriteManager::GetSprite("Water"); frontFace = SpriteManager::GetSprite("Water"); backFace = SpriteManager::GetSprite("Water"); break; } case BlockID::Sand: { upFace = SpriteManager::GetSprite("Sand"); downFace = SpriteManager::GetSprite("Sand"); leftFace = SpriteManager::GetSprite("Sand"); rightFace = SpriteManager::GetSprite("Sand"); frontFace = SpriteManager::GetSprite("Sand"); backFace = SpriteManager::GetSprite("Sand"); break; } case BlockID::Wood: { upFace = SpriteManager::GetSprite("WoodTop"); downFace = SpriteManager::GetSprite("WoodTop"); leftFace = SpriteManager::GetSprite("Wood"); rightFace = SpriteManager::GetSprite("Wood"); frontFace = SpriteManager::GetSprite("Wood"); backFace = SpriteManager::GetSprite("Wood"); break; } case BlockID::Leaf: { upFace = SpriteManager::GetSprite("Leaf"); downFace = SpriteManager::GetSprite("Leaf"); leftFace = SpriteManager::GetSprite("Leaf"); rightFace = SpriteManager::GetSprite("Leaf"); frontFace = SpriteManager::GetSprite("Leaf"); backFace = SpriteManager::GetSprite("Leaf"); break; } case BlockID::Plank: { upFace = SpriteManager::GetSprite("Plank"); downFace = SpriteManager::GetSprite("Plank"); leftFace = SpriteManager::GetSprite("Plank"); rightFace = SpriteManager::GetSprite("Plank"); frontFace = SpriteManager::GetSprite("Plank"); backFace = SpriteManager::GetSprite("Plank"); break; } case BlockID::Glass: { upFace = SpriteManager::GetSprite("Glass"); downFace = SpriteManager::GetSprite("Glass"); leftFace = SpriteManager::GetSprite("Glass"); rightFace = SpriteManager::GetSprite("Glass"); frontFace = SpriteManager::GetSprite("Glass"); backFace = SpriteManager::GetSprite("Glass"); break; } } for (int i = 0; i < 4; i++) { m_Faces[(int8_t)BlockFaceID::Up].Vertices[i].TexCoord = upFace->GetTextureCoords()[i]; m_Faces[(int8_t)BlockFaceID::Down].Vertices[i].TexCoord = downFace->GetTextureCoords()[i]; m_Faces[(int8_t)BlockFaceID::Left].Vertices[i].TexCoord = leftFace->GetTextureCoords()[i]; m_Faces[(int8_t)BlockFaceID::Right].Vertices[i].TexCoord = rightFace->GetTextureCoords()[i]; m_Faces[(int8_t)BlockFaceID::Front].Vertices[i].TexCoord = frontFace->GetTextureCoords()[i]; m_Faces[(int8_t)BlockFaceID::Back].Vertices[i].TexCoord = backFace->GetTextureCoords()[i]; } } void Block::CreateBlockTemplates() { s_Blocks.resize(10); s_Blocks[(int8_t)BlockID::Grass] = CreateScoped<Block>(BlockID::Grass); s_Blocks[(int8_t)BlockID::Dirt] = CreateScoped<Block>(BlockID::Dirt); s_Blocks[(int8_t)BlockID::Stone] = CreateScoped<Block>(BlockID::Stone); s_Blocks[(int8_t)BlockID::Bedrock] = CreateScoped<Block>(BlockID::Bedrock); s_Blocks[(int8_t)BlockID::Water] = CreateScoped<Block>(BlockID::Water); s_Blocks[(int8_t)BlockID::Sand] = CreateScoped<Block>(BlockID::Sand); s_Blocks[(int8_t)BlockID::Wood] = CreateScoped<Block>(BlockID::Wood); s_Blocks[(int8_t)BlockID::Leaf] = CreateScoped<Block>(BlockID::Leaf); s_Blocks[(int8_t)BlockID::Plank] = CreateScoped<Block>(BlockID::Plank); s_Blocks[(int8_t)BlockID::Glass] = CreateScoped<Block>(BlockID::Glass); }
37.592437
97
0.692858
NikiNatov
474aa03ad975952cdaf6d8a3f7f1d8b96c02c5c4
676
cpp
C++
CodeForces/Complete/200-299/289B-PoloThePenguinAndMatrix.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/200-299/289B-PoloThePenguinAndMatrix.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/200-299/289B-PoloThePenguinAndMatrix.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> #include <cstdlib> #include <algorithm> int main(){ int n(0), m(0), d(0); scanf("%d %d %d", &n, &m, &d); int *array = new int[n * m]; bool possible(1); int currentMod(-1); for(int k = 0; k < n * m; k++){ scanf("%d", array + k); if(currentMod < 0){currentMod = array[k] % d;} if(array[k] % d != currentMod){possible = 0; break;} } if(possible){ std::sort(array, array + n * m); int median = array[n * m / 2]; long total(0); for(int k = 0; k < m * n; k++){total += abs(array[k] - median) / d;} printf("%ld\n", total); } else{puts("-1");} return 0; }
23.310345
76
0.471893
Ashwanigupta9125
474f001d6896e6253ca001b8bc9fea0976835125
159
cpp
C++
5e/C++11/407_new.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
null
null
null
5e/C++11/407_new.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
null
null
null
5e/C++11/407_new.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
1
2022-01-25T15:51:34.000Z
2022-01-25T15:51:34.000Z
#include <vector> using namespace std; int main(void) { int *pi = new int{1024}; vector<int> *pv = new vector<int>{0, 1, 2, 3, 4, 5}; return 0; }
15.9
56
0.578616
mallius
47533d2ad35f7bc299d1dc4ece17e917ab4ecc2c
38,753
cc
C++
trunk/elsa/elsa/mtype.cc
BackupTheBerlios/codemorpher-svn
997c989fe1ca932771b3908bafffe1f52f965c9d
[ "BSD-3-Clause" ]
null
null
null
trunk/elsa/elsa/mtype.cc
BackupTheBerlios/codemorpher-svn
997c989fe1ca932771b3908bafffe1f52f965c9d
[ "BSD-3-Clause" ]
null
null
null
trunk/elsa/elsa/mtype.cc
BackupTheBerlios/codemorpher-svn
997c989fe1ca932771b3908bafffe1f52f965c9d
[ "BSD-3-Clause" ]
null
null
null
// mtype.cc // code for mtype.h // 2005-08-03: This code is now exercised to 100% statement coverage, // except for the code that deals with MF_POLYMORPHIC and // MF_ISOMORPHIC and the places annotated with gcov-ignore or // gcov-begin/end-ignore, by in/t0511.cc. // // My plan is to re-do the coverage analysis using the entire test // suite once mtype is hooked up to the rest of the program as the // module to use for type comparison and matching. #include "mtype.h" // this module #include "trace.h" // tracingSys #include "cc_env.h" // Env::applyArgumentMap string toString(MatchFlags flags) { static char const * const map[] = { "MF_IGNORE_RETURN", "MF_STAT_EQ_NONSTAT", "MF_IGNORE_IMPLICIT", "MF_RESPECT_PARAM_CV", "MF_IGNORE_TOP_CV", "MF_COMPARE_EXN_SPEC", "MF_SIMILAR", "MF_POLYMORPHIC", "MF_DEDUCTION", "MF_UNASSOC_TPARAMS", "MF_IGNORE_ELT_CV", "MF_MATCH", "MF_NO_NEW_BINDINGS", "MF_ISOMORPHIC", }; STATIC_ASSERT(TABLESIZE(map) == MF_NUM_FLAGS); return bitmapString(flags, map, MF_NUM_FLAGS); } //-------------------------- Binding ------------------------- string toString_or_CV_NONE(CVFlags cv) { if (cv == CV_NONE) { return "CV_NONE"; } else { return toString(cv); } } bool IMType::Binding::operator== (Binding const &obj) const { if (sarg.kind != obj.sarg.kind) { return false; } if (sarg.isType()) { // somewhat complicated case: we need to make sure the types are // the same, *ignoring* their cv-flags, and that the cv-flags in // the Binding objects themselves *are* equal return getType()->equals(obj.getType(), MF_IGNORE_TOP_CV) && cv == obj.cv; } else { // easy, just STemplateArgument equality return sarg.equals(obj.sarg); } } string IMType::Binding::asString() const { if (sarg.isType()) { return stringc << getType()->toString() << " with " << toString_or_CV_NONE(cv); } else { return sarg.toString(); } } // ------------------------- IMType ----------------------------- IMType::IMType() : bindings(), env(NULL), failedDueToDQT(false) {} IMType::~IMType() {} // --------------- IMType: AtomicType and subclasses ------------ STATICDEF bool IMType::canUseAsVariable(Variable *var, MatchFlags flags) { xassert(var); if (!( flags & MF_MATCH )) { // we're not using anything as a variable return false; } if ((flags & MF_UNASSOC_TPARAMS) && var->getParameterizedEntity() != NULL) { // we cannot use 'var' as a variable because, even though it is a // template parameter, it is associated with a specific template // and MF_UNASSOC_TPARAMS means we can only use *unassociated* // variables as such return false; } // no problem return true; } bool IMType::imatchAtomicType(AtomicType const *conc, AtomicType const *pat, MatchFlags flags) { if (conc == pat) { return true; } if (pat->isTypeVariable() && canUseAsVariable(pat->asTypeVariableC()->typedefVar, flags)) { return imatchAtomicTypeWithVariable(conc, pat->asTypeVariableC(), flags); } if (conc->getTag() != pat->getTag()) { // match an instantiation with a PseudoInstantiation if ((flags & MF_MATCH) && pat->isPseudoInstantiation() && conc->isCompoundType() && conc->asCompoundTypeC()->typedefVar->templateInfo() && conc->asCompoundTypeC()->typedefVar->templateInfo()->isCompleteSpecOrInstantiation()) { TemplateInfo *concTI = conc->asCompoundTypeC()->typedefVar->templateInfo(); PseudoInstantiation const *patPI = pat->asPseudoInstantiationC(); // these must be instantiations of the same primary if (concTI->getPrimary() != patPI->primary->templateInfo()->getPrimary()) { return false; } // compare arguments; use the args to the primary, not the args to // the partial spec (if any) return imatchSTemplateArguments(concTI->getArgumentsToPrimary(), patPI->args, flags); } return false; } // for the template-related types, we have some structural equality switch (conc->getTag()) { default: xfailure("bad tag"); case AtomicType::T_SIMPLE: case AtomicType::T_COMPOUND: case AtomicType::T_ENUM: // non-template-related type, physical equality only return false; #define CASE(tag,type) \ case AtomicType::tag: return imatch##type(conc->as##type##C(), pat->as##type##C(), flags) /*user;*/ CASE(T_TYPEVAR, TypeVariable); CASE(T_PSEUDOINSTANTIATION, PseudoInstantiation); CASE(T_DEPENDENTQTYPE, DependentQType); #undef CASE } } bool IMType::imatchTypeVariable(TypeVariable const *conc, TypeVariable const *pat, MatchFlags flags) { // 2005-03-03: Let's try saying that TypeVariables are equal if they // are the same ordinal parameter of the same template. Variable *cparam = conc->typedefVar; Variable *pparam = pat->typedefVar; return cparam->sameTemplateParameter(pparam); } bool IMType::imatchPseudoInstantiation(PseudoInstantiation const *conc, PseudoInstantiation const *pat, MatchFlags flags) { if (conc->primary != pat->primary) { return false; } return imatchSTemplateArguments(conc->args, pat->args, flags); } bool IMType::imatchSTemplateArguments(ObjList<STemplateArgument> const &conc, ObjList<STemplateArgument> const &pat, MatchFlags flags) { ObjListIter<STemplateArgument> concIter(conc); ObjListIter<STemplateArgument> patIter(pat); while (!concIter.isDone() && !patIter.isDone()) { STemplateArgument const *csta = concIter.data(); STemplateArgument const *psta = patIter.data(); if (!imatchSTemplateArgument(csta, psta, flags)) { return false; } concIter.adv(); patIter.adv(); } return concIter.isDone() && patIter.isDone(); } bool IMType::imatchSTemplateArgument(STemplateArgument const *conc, STemplateArgument const *pat, MatchFlags flags) { if (pat->kind == STemplateArgument::STA_DEPEXPR && pat->getDepExpr()->isE_variable() && canUseAsVariable(pat->getDepExpr()->asE_variable()->var, flags)) { return imatchNontypeWithVariable(conc, pat->getDepExpr()->asE_variable(), flags); } if (conc->kind != pat->kind) { return false; } switch (conc->kind) { default: xfailure("bad or unimplemented STemplateArgument kind"); case STemplateArgument::STA_TYPE: { // For convenience I have passed 'STemplateArgument' directly, // but this module's usage of that structure is supposed to be // consistent with it storing 'Type const *' instead of 'Type // *', so this extraction is elaborated to make it clear we are // pulling out const pointers. Type const *ct = conc->getType(); Type const *pt = pat->getType(); return imatchType(ct, pt, flags); } case STemplateArgument::STA_INT: return conc->getInt() == pat->getInt(); case STemplateArgument::STA_ENUMERATOR: return conc->getEnumerator() == pat->getEnumerator(); case STemplateArgument::STA_REFERENCE: return conc->getReference() == pat->getReference(); case STemplateArgument::STA_POINTER: return conc->getPointer() == pat->getPointer(); case STemplateArgument::STA_MEMBER: return conc->getMember() == pat->getMember(); case STemplateArgument::STA_DEPEXPR: return imatchExpression(conc->getDepExpr(), pat->getDepExpr(), flags); } } bool IMType::imatchNontypeWithVariable(STemplateArgument const *conc, E_variable *pat, MatchFlags flags) { // 'conc' should be a nontype argument if (!conc->isObject()) { return false; } if (flags & MF_ISOMORPHIC) { // check that we are only binding to a variable; ideally, this // would only be an STA_DEPEXPR of an E_variable, but infelicities // in other parts of the template-handling code can let this be // an STA_REFERENCE of a Variable that is a template parameter.. // probably, that will be fixed at some point and the STA_REFERENCE // possibility can be eliminated if (conc->isDepExpr() && conc->getDepExpr()->isE_variable() && conc->getDepExpr()->asE_variable()->var->isTemplateParam()) { // ok } else if (conc->kind == STemplateArgument::STA_REFERENCE && conc->getReference()->isTemplateParam()) { // ok, sort of } else { // not compatible with MF_ISOMORPHIC return false; } } StringRef vName = pat->name->getName(); Binding *binding = bindings.get(vName); if (binding) { // check that 'conc' and 'binding->sarg' are equal return imatchSTemplateArgument(conc, &(binding->sarg), flags & ~MF_MATCH); } else { if (flags & MF_NO_NEW_BINDINGS) { return false; } // bind 'pat->name' to 'conc' binding = new Binding; binding->sarg = *conc; return addBinding(vName, binding, flags); } } bool IMType::addBinding(StringRef name, Binding * /*owner*/ value, MatchFlags flags) { if (flags & MF_ISOMORPHIC) { // is anything already bound to 'value'? for (BindingMap::IterC iter(bindings); !iter.isDone(); iter.adv()) { if (value->operator==(*(iter.value()))) { // yes, something is already bound to it, which we cannot // allow in MF_ISOMORPHIC mode delete value; return false; } } } bindings.add(name, value); return true; } bool IMType::imatchDependentQType(DependentQType const *conc, DependentQType const *pat, MatchFlags flags) { // compare first components if (!imatchAtomicType(conc->first, pat->first, flags)) { return false; } // compare sequences of names as just that, names, since their // interpretation depends on what type 'first' ends up being; // I think this behavior is underspecified in the standard, but // it is what gcc and icc seem to do return imatchPQName(conc->rest, pat->rest, flags); } bool IMType::imatchPQName(PQName const *conc, PQName const *pat, MatchFlags flags) { if (conc->kind() != pat->kind()) { return false; } ASTSWITCH2C(PQName, conc, pat) { // recursive case ASTCASE2C(PQ_qualifier, cq, pq) { // compare as names (i.e., syntactically) if (cq->qualifier != pq->qualifier) { return false; } // the template arguments can be compared semantically because // the standard does specify that they are looked up in a // context that is effectively independent of what appears to // the left in the qualified name (cppstd 3.4.3.1p1b3) if (!imatchSTemplateArguments(cq->sargs, pq->sargs, flags)) { return false; } // continue down the chain return imatchPQName(cq->rest, pq->rest, flags); } // base cases ASTNEXT2C(PQ_name, cn, pn) { // compare as names return cn->name == pn->name; } ASTNEXT2C(PQ_operator, co, po) { return co->o == po->o; // gcov-ignore: can only match on types, and operators are not types } ASTNEXT2C(PQ_template, ct, pt) { // like for PQ_qualifier, except there is no 'rest' return ct->name == pt->name && imatchSTemplateArguments(ct->sargs, pt->sargs, flags); } ASTDEFAULT2C { xfailure("bad kind"); } ASTENDCASE2C } } // -------------- IMType: Type and subclasses ------------- bool IMType::imatchType(Type const *conc, Type const *pat, MatchFlags flags) { if (pat->isReferenceType() && // if comparing reference !conc->isReferenceType() && // to non-reference (flags & MF_IGNORE_TOP_CV) && // at top of type (flags & MF_DEDUCTION)) { // during type deduction // (in/t0549.cc) we got here because we just used a binding to // come up with a reference type; without that, we would have stripped // the reference-ness much earlier; but here we are, so strip it pat = pat->asRvalC(); } if (pat->isTypeVariable() && canUseAsVariable(pat->asTypeVariableC()->typedefVar, flags)) { return imatchTypeWithVariable(conc, pat->asTypeVariableC(), pat->getCVFlags(), flags); } if ((flags & MF_MATCH) && !(flags & MF_ISOMORPHIC) && pat->isCVAtomicType() && pat->asCVAtomicTypeC()->atomic->isDependentQType()) { // must resolve a DQT to use it return imatchTypeWithResolvedType(conc, pat, flags); } if (flags & MF_POLYMORPHIC) { if (pat->isSimpleType()) { SimpleTypeId objId = pat->asSimpleTypeC()->type; if (ST_PROMOTED_INTEGRAL <= objId && objId <= ST_ANY_TYPE) { return imatchTypeWithPolymorphic(conc, objId, flags); } } } // further comparison requires that the types have equal tags Type::Tag tag = conc->getTag(); if (pat->getTag() != tag) { return false; } switch (tag) { default: xfailure("bad type tag"); #define CASE(tagName,typeName) \ case Type::tagName: return imatch##typeName(conc->as##typeName##C(), pat->as##typeName##C(), flags) /*user;*/ CASE(T_ATOMIC, CVAtomicType); CASE(T_POINTER, PointerType); CASE(T_REFERENCE, ReferenceType); CASE(T_FUNCTION, FunctionType); CASE(T_ARRAY, ArrayType); CASE(T_POINTERTOMEMBER, PointerToMemberType); #undef CASE } } bool IMType::imatchTypeWithVariable(Type const *conc, TypeVariable const *pat, CVFlags tvCV, MatchFlags flags) { if ((flags & MF_ISOMORPHIC) && !conc->isTypeVariable()) { return false; // MF_ISOMORPHIC requires that we only bind to variables } StringRef tvName = pat->name; Binding *binding = bindings.get(tvName); if (binding) { // 'tvName' is already bound; compare its current // value (as modified by 'tvCV') against 'conc' return equalWithAppliedCV(conc, binding, tvCV, flags); } else { if (flags & MF_NO_NEW_BINDINGS) { // new bindings are disallowed, so unbound variables in 'pat' // cause failure return false; } // bind 'tvName' to 'conc'; 'conc' should have cv-flags // that are a superset of those in 'tvCV', and the // type to which 'tvName' is bound should have the cv-flags // in the difference between 'conc' and 'tvCV' return addTypeBindingWithoutCV(tvName, conc, tvCV, flags); } } bool IMType::imatchTypeWithResolvedType(Type const *conc, Type const *pat, MatchFlags flags) { // It would seem that I need an Env here so I can call // applyArgumentMap. If this assertion fails, it may be sufficient // to change the MType constructor call to provide an Env; but be // careful about the consequences to the constness of the interface. if (!env) { xfailure("in MF_MATCH mode, need to resolve a DQT, so need an Env..."); } // this cast is justified by the private constructors of IMType MType &mtype = static_cast<MType&>(*this); // this cast is justified by the fact that applyArgumentMap is // careful not to modify its argument; it accepts a non-const ptr // only so that it can return it as non-const too (but I then // store the result in the const 'resolvedType', so there isn't // a loss of soundness there either) Type *patNC = const_cast<Type*>(pat); // The following call might need to query the bindings, and there // is considerable difficulty involved in pushing a soundness // argument through in the face of queried bindings. So, I am // forced to correlate the capacity to resolve DQTs with supporting // the const interface. That is why I have now removed setEnv(). xassert(mtype.getAllowNonConst()); Type const *resolvedType = env->applyArgumentMapToType_helper(mtype, patNC); if (resolvedType) { // take the resolved type and compare it directly to 'conc' return imatchType(conc, resolvedType, flags & ~MF_MATCH); } else { // failure to resolve, hence failure to match failedDueToDQT = true; return false; } } // Typical scenario: // conc is 'int const' // binding is 'int' // cv is 'const' // We want to compare the type denoted by 'conc' with the type denoted // by 'binding' with the qualifiers in 'cv' added to it at toplevel. bool IMType::equalWithAppliedCV(Type const *conc, Binding *binding, CVFlags cv, MatchFlags flags) { // turn off type variable binding/substitution flags &= ~MF_MATCH; if (binding->sarg.isType()) { Type const *t = binding->getType(); // cv-flags for 't' are ignored, replaced by the cv-flags stored // in the 'binding' object cv |= binding->cv; return imatchTypeWithSpecifiedCV(conc, t, cv, flags); } if (binding->sarg.isAtomicType()) { if (!conc->isCVAtomicType()) { return false; } // compare the atomics if (!imatchAtomicType(conc->asCVAtomicTypeC()->atomic, binding->sarg.getAtomicType(), flags)) { return false; } // When a name is bound directly to an atomic type, it is compatible // with any binding to a CVAtomicType for the same atomic; that is, // it is compatible with any cv-qualified variant. So, if we // are paying attention to cv-flags at all, simply replace the // original (AtomicType) binding with 'conc' (a CVAtomicType) and // appropriate cv-flags. if (!( flags & MF_OK_DIFFERENT_CV )) { // The 'cv' flags supplied are subtracted from those in 'conc'. CVFlags concCV = conc->getCVFlags(); if (concCV >= cv) { // example: // conc = 'struct B volatile const' // binding = 'struct B' // cv = 'const' // Since 'const' was supplied (e.g., "T const") with the type // variable, we want to remove it from what we bind to, so here // we will bind to 'struct B volatile' ('concCV' = 'volatile'). concCV = (concCV & ~cv); } else { // example: // conc = 'struct B volatile' // binding = 'struct B' // cv = 'const' // This means we are effectively comparing 'struct B volatile' to // 'struct B volatile const' (the latter volatile arising because // being directly bound to an atomic means we can add qualifiers), // and these are not equal. return false; } binding->setType(conc); binding->cv = concCV; return true; } } // I *think* that the language rules that prevent same-named // template params from nesting will have the effect of preventing // this code from being reached, but if it turns out I am wrong, it // should be safe to simply remove the assertion and return false. xfailure("attempt to match a type with a variable bound to a non-type"); return false; // gcov-ignore } bool IMType::imatchTypeWithSpecifiedCV(Type const *conc, Type const *pat, CVFlags cv, MatchFlags flags) { // compare underlying types, ignoring first level of cv return imatchCVFlags(conc->getCVFlags(), cv, flags) && imatchType(conc, pat, flags | MF_IGNORE_TOP_CV); } bool IMType::addTypeBindingWithoutCV(StringRef tvName, Type const *conc, CVFlags tvcv, MatchFlags flags) { CVFlags ccv = conc->getCVFlags(); if ((flags & MF_DEDUCTION) && (flags & MF_IGNORE_TOP_CV)) { // trying to implement 14.8.2.1p2b3 ccv = CV_NONE; } if (tvcv & ~ccv) { // the type variable was something like 'T const' but the concrete // type does not have all of the cv-flags (e.g., just 'int', no // 'const'); this means the match is a failure if (flags & MF_DEDUCTION) { // let it go anyway, as part of my poor approximationg of 14.8.2.1 } else { return false; } } // 'tvName' will be bound to 'conc', except we will ignore the // latter's cv flags Binding *binding = new Binding; binding->setType(conc); // instead, compute the set of flags that are on 'conc' but not // 'tvcv'; this will be the cv-flags of the type to which 'tvName' // is bound binding->cv = (ccv & ~tvcv); // add the binding return addBinding(tvName, binding, flags); } // check if 'conc' matches the "polymorphic" type family 'polyId' bool IMType::imatchTypeWithPolymorphic(Type const *conc, SimpleTypeId polyId, MatchFlags flags) { // check those that can match any type constructor if (polyId == ST_ANY_TYPE) { return true; } if (polyId == ST_ANY_NON_VOID) { return !conc->isVoid(); } if (polyId == ST_ANY_OBJ_TYPE) { return !conc->isFunctionType() && !conc->isVoid(); } // check those that only match atomics if (conc->isSimpleType()) { SimpleTypeId concId = conc->asSimpleTypeC()->type; SimpleTypeFlags concFlags = simpleTypeInfo(concId).flags; // see cppstd 13.6 para 2 if (polyId == ST_PROMOTED_INTEGRAL) { return (concFlags & (STF_INTEGER | STF_PROM)) == (STF_INTEGER | STF_PROM); } if (polyId == ST_PROMOTED_ARITHMETIC) { return (concFlags & (STF_INTEGER | STF_PROM)) == (STF_INTEGER | STF_PROM) || (concFlags & STF_FLOAT); // need not be promoted! } if (polyId == ST_INTEGRAL) { return (concFlags & STF_INTEGER) != 0; } if (polyId == ST_ARITHMETIC) { return (concFlags & (STF_INTEGER | STF_FLOAT)) != 0; } if (polyId == ST_ARITHMETIC_NON_BOOL) { return concId != ST_BOOL && (concFlags & (STF_INTEGER | STF_FLOAT)) != 0; } } // polymorphic type failed to match return false; } bool IMType::imatchAtomicTypeWithVariable(AtomicType const *conc, TypeVariable const *pat, MatchFlags flags) { if ((flags & MF_ISOMORPHIC) && !conc->isTypeVariable()) { return false; // MF_ISOMORPHIC requires that we only bind to variables } StringRef tvName = pat->name; Binding *binding = bindings.get(tvName); if (binding) { // 'tvName' is already bound; it should be bound to the same // atomic as 'conc', possibly with some (extra, ignored) cv flags if (binding->sarg.isType()) { Type const *t = binding->getType(); if (t->isCVAtomicType()) { return imatchAtomicType(conc, t->asCVAtomicTypeC()->atomic, flags & ~MF_MATCH); } else { return false; } } else if (binding->sarg.isAtomicType()) { return imatchAtomicType(conc, binding->sarg.getAtomicType(), flags & ~MF_MATCH); } else { // gcov-ignore: cannot be triggered, the error is return false; // gcov-ignore: diagnosed before mtype is entered } } else { if (flags & MF_NO_NEW_BINDINGS) { // new bindings are disallowed, so unbound variables in 'pat' // cause failure return false; } // bind 'tvName' to 'conc' binding = new Binding; binding->sarg.setAtomicType(conc); return addBinding(tvName, binding, flags); } } bool IMType::imatchCVAtomicType(CVAtomicType const *conc, CVAtomicType const *pat, MatchFlags flags) { // compare cv-flags return imatchCVFlags(conc->cv, pat->cv, flags) && imatchAtomicType(conc->atomic, pat->atomic, flags & MF_PROP); } bool IMType::imatchCVFlags(CVFlags conc, CVFlags pat, MatchFlags flags) { if (flags & MF_OK_DIFFERENT_CV) { // anything goes return true; } else if (flags & MF_DEDUCTION) { // merely require that the pattern flags be a superset of // the concrete flags (in/t0315.cc, in/t0348.cc) // // TODO: this is wrong, as it does not correctly implement // 14.8.2.1; I am only implementing this because it emulates // what matchtype does right now if (pat >= conc) { return true; } else { return false; } } else { // require equality return conc == pat; } } bool IMType::imatchPointerType(PointerType const *conc, PointerType const *pat, MatchFlags flags) { // note how MF_IGNORE_TOP_CV allows *this* type's cv flags to differ, // but it's immediately suppressed once we go one level down; this // behavior is repeated in all 'match' methods return imatchCVFlags(conc->cv, pat->cv, flags) && imatchType(conc->atType, pat->atType, flags & MF_PTR_PROP); } bool IMType::imatchReferenceType(ReferenceType const *conc, ReferenceType const *pat, MatchFlags flags) { if (flags & MF_DEDUCTION) { // (in/t0114.cc, in/d0072.cc) allow pattern to be more cv-qualified; // this only approximates 14.8.2.1, but emulates current matchtype // behavior (actually, it emulates only the intended matchtype // behavior; see comment added 2005-08-03 to MatchTypes::match_ref) if (pat->atType->getCVFlags() >= conc->atType->getCVFlags()) { // disable further comparison of these cv-flags flags |= MF_IGNORE_TOP_CV; } } return imatchType(conc->atType, pat->atType, flags & MF_PTR_PROP); } bool IMType::imatchFunctionType(FunctionType const *conc, FunctionType const *pat, MatchFlags flags) { // I do not compare 'FunctionType::flags' explicitly since their // meaning is generally a summary of other information, or of the // name (which is irrelevant to the type) if (!(flags & MF_IGNORE_RETURN)) { // check return type if (!imatchType(conc->retType, pat->retType, flags & MF_PROP)) { return false; } } if ((conc->flags | pat->flags) & FF_NO_PARAM_INFO) { // at least one of the types does not have parameter info, // so no further comparison is possible return true; // gcov-ignore: cannot trigger in C++ mode } if (!(flags & MF_STAT_EQ_NONSTAT)) { // check that either both are nonstatic methods, or both are not if (conc->isMethod() != pat->isMethod()) { return false; } } // check that both are variable-arg, or both are not if (conc->acceptsVarargs() != pat->acceptsVarargs()) { return false; } // check the parameter lists (do not mask with MF_PROP here, // it happens inside 'imatchParameterLists') if (!imatchParameterLists(conc, pat, flags)) { return false; } if (flags & MF_COMPARE_EXN_SPEC) { // check the exception specs if (!imatchExceptionSpecs(conc, pat, flags & MF_PROP)) { return false; } } return true; } bool IMType::imatchParameterLists(FunctionType const *conc, FunctionType const *pat, MatchFlags flags) { SObjListIter<Variable> concIter(conc->params); SObjListIter<Variable> patIter(pat->params); // skip the 'this' parameter(s) if desired, or if one has it // but the other does not (can arise if MF_STAT_EQ_NONSTAT has // been specified) { bool cm = conc->isMethod(); bool pm = pat->isMethod(); bool ignore = flags & MF_IGNORE_IMPLICIT; if (cm && (!pm || ignore)) { concIter.adv(); } if (pm && (!cm || ignore)) { patIter.adv(); } } // this takes care of imatchFunctionType's obligation to suppress // non-propagated flags after consumption; it is masked *after* // we check MF_IGNORE_IMPLICIT flags &= MF_PROP; // allow toplevel cv flags on parameters to differ if (!( flags & MF_RESPECT_PARAM_CV )) { flags |= MF_IGNORE_TOP_CV; } for (; !concIter.isDone() && !patIter.isDone(); concIter.adv(), patIter.adv()) { // parameter names do not have to match, but // the types do if (imatchType(concIter.data()->type, patIter.data()->type, flags)) { // ok } else { return false; } } return concIter.isDone() == patIter.isDone(); } // almost identical code to the above.. list comparison is // always a pain.. bool IMType::imatchExceptionSpecs(FunctionType const *conc, FunctionType const *pat, MatchFlags flags) { if (conc->exnSpec==NULL && pat->exnSpec==NULL) return true; if (conc->exnSpec==NULL || pat->exnSpec==NULL) return false; // hmm.. this is going to end up requiring that exception specs // be listed in the same order, whereas I think the semantics // imply they're more like a set.. oh well // // but if they are a set, how the heck do you do matching? // I think I see; the matching must have already led to effectively // concrete types on both sides. But, since I only see 'pat' as // the pattern + substitutions, it would still be hard to figure // out the correct correspondence for the set semantics. // this will at least ensure I do not derive any bindings from // the attempt to compare exception specs flags |= MF_NO_NEW_BINDINGS; SObjListIter<Type> concIter(conc->exnSpec->types); SObjListIter<Type> patIter(pat->exnSpec->types); for (; !concIter.isDone() && !patIter.isDone(); concIter.adv(), patIter.adv()) { if (imatchType(concIter.data(), patIter.data(), flags)) { // ok } else { return false; } } return concIter.isDone() == patIter.isDone(); } bool IMType::imatchArrayType(ArrayType const *conc, ArrayType const *pat, MatchFlags flags) { // what flags to propagate? MatchFlags propFlags = (flags & MF_PROP); if (flags & MF_IGNORE_ELT_CV) { if (conc->eltType->isArrayType()) { // propagate the ignore-elt down through as many ArrayTypes // as there are propFlags |= MF_IGNORE_ELT_CV; } else { // the next guy is the element type, ignore *his* cv only propFlags |= MF_IGNORE_TOP_CV; } } if (!( imatchType(conc->eltType, pat->eltType, propFlags) && conc->hasSize() == pat->hasSize() )) { return false; } // TODO: At some point I will implement dependent-sized arrays // (t0435.cc), at which point the size comparison code here will // have to be generalized. if (conc->hasSize()) { return conc->size == pat->size; } else { return true; } } bool IMType::imatchPointerToMemberType(PointerToMemberType const *conc, PointerToMemberType const *pat, MatchFlags flags) { return imatchAtomicType(conc->inClassNAT, pat->inClassNAT, flags) && imatchCVFlags(conc->cv, pat->cv, flags) && imatchType(conc->atType, pat->atType, flags & MF_PTR_PROP); } // -------------------- IMType: Expression --------------------- // This is not full-featured matching as with types, rather this // is mostly just comparison for equality. bool IMType::imatchExpression(Expression const *conc, Expression const *pat, MatchFlags flags) { if (conc->isE_grouping()) { return imatchExpression(conc->asE_groupingC()->expr, pat, flags); } if (pat->isE_grouping()) { return imatchExpression(conc, pat->asE_groupingC()->expr, flags); } if (conc->kind() != pat->kind()) { return false; } // turn off variable matching for this part because expression // comparison should be fairly literal flags &= ~MF_MATCH; ASTSWITCH2C(Expression, conc, pat) { // only the expression constructors that yield integers and do not // have side effects are allowed within type constructors, so that // is all we deconstruct here // // TODO: should 65 and 'A' be regarded as equal here? For now, I // do not regard them as equivalent... ASTCASE2C(E_boolLit, c, p) { return c->b == p->b; } ASTNEXT2C(E_intLit, c, p) { return c->i == p->i; } ASTNEXT2C(E_charLit, c, p) { return c->c == p->c; } ASTNEXT2C(E_variable, c, p) { if (c->var == p->var) { return true; } if (c->var->isTemplateParam() && p->var->isTemplateParam()) { // like for matchTypeVariable return c->var->sameTemplateParameter(p->var); } return false; } ASTNEXT2C(E_sizeof, c, p) { // like above: is sizeof(int) the same as 4? return imatchExpression(c->expr, p->expr, flags); } ASTNEXT2C(E_unary, c, p) { return c->op == p->op && imatchExpression(c->expr, p->expr, flags); } ASTNEXT2C(E_binary, c, p) { return c->op == p->op && imatchExpression(c->e1, p->e1, flags) && imatchExpression(c->e2, p->e2, flags); } ASTNEXT2C(E_cast, c, p) { return imatchType(c->ctype->getType(), p->ctype->getType(), flags) && imatchExpression(c->expr, p->expr, flags); } ASTNEXT2C(E_cond, c, p) { return imatchExpression(c->cond, p->cond, flags) && imatchExpression(c->th, p->th, flags) && imatchExpression(c->el, p->el, flags); } ASTNEXT2C(E_sizeofType, c, p) { return imatchType(c->atype->getType(), p->atype->getType(), flags); } ASTNEXT2C(E_keywordCast, c, p) { return c->key == p->key && imatchType(c->ctype->getType(), p->ctype->getType(), flags) && imatchExpression(c->expr, p->expr, flags); } ASTDEFAULT2C { // For expressions that are *not* const-eval'able, we can't get // here because tcheck reports an error and bails before we get // a chance. So, the only way to trigger this code is to extend // the constant-expression evaluator to handle a new form, and // then fail to update the comparison code here to compare such // forms with each other. xfailure("some kind of expression is const-eval'able but mtype " "does not know how to compare it"); // gcov-ignore } ASTENDCASE2C } } // -------------------------- MType -------------------------- MType::MType(bool allowNonConst_) : allowNonConst(allowNonConst_) {} MType::~MType() {} MType::MType(Env &e) : allowNonConst(true) { env = &e; } bool MType::matchType(Type const *conc, Type const *pat, MatchFlags flags) { // I can only uphold the promise of not modifying 'conc' and 'pat' // if asked to when I was created. xassert(!allowNonConst); return commonMatchType(conc, pat, flags); } bool MType::matchTypeNC(Type *conc, Type *pat, MatchFlags flags) { return commonMatchType(conc, pat, flags); } bool MType::commonMatchType(Type const *conc, Type const *pat, MatchFlags flags) { // 14.8.2.1p2b3 if ((flags & MF_DEDUCTION) && !pat->isReferenceType()) { flags |= MF_IGNORE_TOP_CV; } bool result = imatchType(conc, pat, flags); #ifndef NDEBUG static bool doTrace = tracingSys("mtype"); if (doTrace) { ostream &os = trace("mtype"); os << "conc=`" << conc->toString() << "' pat=`" << pat->toString() << "' flags={" << toString(flags) << "}; match=" << (result? "true" : "false") ; if (failedDueToDQT) { os << " (failedDueToDQT)"; } if (result) { os << bindingsToString(); } os << endl; } #endif // NDEBUG return result; } bool MType::matchSTemplateArguments(ObjList<STemplateArgument> const &conc, ObjList<STemplateArgument> const &pat, MatchFlags flags) { xassert(!allowNonConst); return commonMatchSTemplateArguments(conc, pat, flags); } bool MType::matchSTemplateArgumentsNC(ObjList<STemplateArgument> &conc, ObjList<STemplateArgument> &pat, MatchFlags flags) { return commonMatchSTemplateArguments(conc, pat, flags); } bool MType::commonMatchSTemplateArguments(ObjList<STemplateArgument> const &conc, ObjList<STemplateArgument> const &pat, MatchFlags flags) { bool result = imatchSTemplateArguments(conc, pat, flags); #ifndef NDEBUG static bool doTrace = tracingSys("mtype"); if (doTrace) { ostream &os = trace("mtype"); os << "conc=" << sargsToString(conc) << " pat=" << sargsToString(pat) << " flags={" << toString(flags) << "}; match=" << (result? "true" : "false") ; if (result) { os << bindingsToString(); } os << endl; } #endif // NDEBUG return result; } bool MType::matchAtomicType(AtomicType const *conc, AtomicType const *pat, MatchFlags flags) { xassert(!allowNonConst); return imatchAtomicType(conc, pat, flags); } bool MType::matchSTemplateArgument(STemplateArgument const *conc, STemplateArgument const *pat, MatchFlags flags) { xassert(!allowNonConst); return imatchSTemplateArgument(conc, pat, flags); } bool MType::matchExpression(Expression const *conc, Expression const *pat, MatchFlags flags) { xassert(!allowNonConst); return imatchExpression(conc, pat, flags); } string MType::bindingsToString() const { // extract bindings stringBuilder sb; sb << "; bindings:"; for (BindingMap::IterC iter(bindings); !iter.isDone(); iter.adv()) { sb << " \"" << iter.key() << "\"=`" << iter.value()->asString() << "'"; } return sb; } int MType::getNumBindings() const { return bindings.getNumEntries(); } bool MType::isBound(StringRef name) const { return !!bindings.getC(name); } STemplateArgument MType::getBoundValue(StringRef name, TypeFactory &tfac) const { // you can't do this with the matcher that promises to // only work with const pointers; this assertion provides // the justification for the const_casts below xassert(allowNonConst); Binding const *b = bindings.getC(name); if (!b) { return STemplateArgument(); } if (b->sarg.isAtomicType()) { // the STA_ATOMIC kind is only for internal use by this module; // we translate it into STA_TYPE for external use (but the caller // has to provide a 'tfac' to allow the translation) Type *t = tfac.makeCVAtomicType( const_cast<AtomicType*>(b->sarg.getAtomicType()), CV_NONE); return STemplateArgument(t); } if (b->sarg.isType()) { // similarly, we have to combine the type in 'sarg' with 'cv' // before exposing it to the user Type *t = tfac.setQualifiers(SL_UNKNOWN, b->cv, const_cast<Type*>(b->getType()), NULL /*syntax*/); return STemplateArgument(t); } // other cases are already in the public format return b->sarg; } void MType::setBoundValue(StringRef name, STemplateArgument const &value) { xassert(value.hasValue()); Binding *b = new Binding; b->sarg = value; if (value.isType()) { b->cv = value.getType()->getCVFlags(); } bindings.addReplace(name, b); } // EOF
30.087733
115
0.630093
BackupTheBerlios
4755af93c37ba08eccd693bd20210b7c6ceae211
74,554
cpp
C++
il.cpp
jevinskie/arch-arm64
e4a3d95a0aea1d039c3f47d2283e20bdaff16ba6
[ "Apache-2.0" ]
2
2020-12-14T07:29:55.000Z
2021-08-02T20:27:30.000Z
il.cpp
jevinskie/arch-arm64
e4a3d95a0aea1d039c3f47d2283e20bdaff16ba6
[ "Apache-2.0" ]
null
null
null
il.cpp
jevinskie/arch-arm64
e4a3d95a0aea1d039c3f47d2283e20bdaff16ba6
[ "Apache-2.0" ]
null
null
null
#include "lowlevelilinstruction.h" #include <cstring> #include <inttypes.h> #include <stdarg.h> #include "il.h" #include "neon_intrinsics.h" #include "sysregs.h" using namespace BinaryNinja; #include "il_macros.h" static ExprId GetCondition(LowLevelILFunction& il, Condition cond) { switch (cond) { case COND_EQ: return il.FlagCondition(LLFC_E); case COND_NE: return il.FlagCondition(LLFC_NE); case COND_CS: return il.FlagCondition(LLFC_UGE); case COND_CC: return il.FlagCondition(LLFC_ULT); case COND_MI: return il.FlagCondition(LLFC_NEG); case COND_PL: return il.FlagCondition(LLFC_POS); case COND_VS: return il.FlagCondition(LLFC_O); case COND_VC: return il.FlagCondition(LLFC_NO); case COND_HI: return il.FlagCondition(LLFC_UGT); case COND_LS: return il.FlagCondition(LLFC_ULE); case COND_GE: return il.FlagCondition(LLFC_SGE); case COND_LT: return il.FlagCondition(LLFC_SLT); case COND_GT: return il.FlagCondition(LLFC_SGT); case COND_LE: return il.FlagCondition(LLFC_SLE); case COND_AL: return il.Const(0, 1); // Always branch case COND_NV: default: return il.Const(0, 0); // Never branch } } static void GenIfElse(LowLevelILFunction& il, ExprId clause, ExprId trueCase, ExprId falseCase) { if (falseCase) { LowLevelILLabel trueCode, falseCode, done; il.AddInstruction(il.If(clause, trueCode, falseCode)); il.MarkLabel(trueCode); il.AddInstruction(trueCase); il.AddInstruction(il.Goto(done)); il.MarkLabel(falseCode); il.AddInstruction(falseCase); il.AddInstruction(il.Goto(done)); il.MarkLabel(done); } else { LowLevelILLabel trueCode, done; il.AddInstruction(il.If(clause, trueCode, done)); il.MarkLabel(trueCode); il.AddInstruction(trueCase); il.MarkLabel(done); } return; } ExprId ExtractImmediate(LowLevelILFunction& il, InstructionOperand& operand, int sizeof_imm) { if (operand.operandClass != IMM32 && operand.operandClass != IMM64) return il.Unimplemented(); uint64_t imm = operand.immediate; if (operand.shiftValueUsed) { switch (operand.shiftType) { case ShiftType_LSL: imm = imm << operand.shiftValue; break; case ShiftType_LSR: imm = imm >> operand.shiftValue; break; case ShiftType_MSL: imm = (imm << operand.shiftValue) | ONES(operand.shiftValue); break; case ShiftType_ASR: case ShiftType_ROR: case ShiftType_UXTW: case ShiftType_SXTW: case ShiftType_SXTX: case ShiftType_UXTX: case ShiftType_SXTB: case ShiftType_SXTH: case ShiftType_UXTH: case ShiftType_UXTB: case ShiftType_END: default: return il.Unimplemented(); } } return ILCONST(sizeof_imm, imm & ONES(sizeof_imm * 8)); } // extractSize can be smaller than the register, generating an LLIL_LOWPART // resultSize can be larger than the register, generating sign or zero extension ExprId ExtractRegister(LowLevelILFunction& il, InstructionOperand& operand, size_t regNum, size_t extractSize, bool signExtend, size_t resultSize) { size_t opsz = get_register_size(operand.reg[regNum]); switch (operand.reg[regNum]) { case REG_WZR: case REG_XZR: return il.Const(resultSize, 0); default: break; } ExprId res = 0; switch (operand.operandClass) { case SYS_REG: res = il.Register(opsz, operand.sysreg); break; case REG: default: res = il.Register(opsz, operand.reg[regNum]); break; } if (extractSize < opsz) res = il.LowPart(extractSize, res); if (extractSize < resultSize || opsz < extractSize) { if (signExtend) res = il.SignExtend(resultSize, res); else res = il.ZeroExtend(resultSize, res); } return res; } static ExprId GetFloat(LowLevelILFunction& il, InstructionOperand& operand, int float_sz) { if (operand.operandClass == FIMM32) { switch (float_sz) { case 2: return il.FloatConstRaw(2, operand.immediate); case 4: return il.FloatConstSingle(*(float*)&(operand.immediate)); case 8: return il.FloatConstDouble(*(float*)&(operand.immediate)); default: break; } } else if (operand.operandClass == REG) { return il.FloatConvert( float_sz, ExtractRegister(il, operand, 0, REGSZ_O(operand), false, REGSZ_O(operand))); } return il.Unimplemented(); } static ExprId GetShiftedRegister( LowLevelILFunction& il, InstructionOperand& operand, size_t regNum, size_t resultSize) { ExprId res; // peel off the variants that return early switch (operand.shiftType) { case ShiftType_NONE: res = ExtractRegister(il, operand, regNum, REGSZ_O(operand), false, resultSize); return res; case ShiftType_ASR: res = ExtractRegister(il, operand, regNum, REGSZ_O(operand), false, resultSize); if (operand.shiftValue) res = il.ArithShiftRight(resultSize, res, il.Const(0, operand.shiftValue)); return res; case ShiftType_LSR: res = ExtractRegister(il, operand, regNum, REGSZ_O(operand), false, resultSize); if (operand.shiftValue) res = il.LogicalShiftRight(resultSize, res, il.Const(1, operand.shiftValue)); return res; case ShiftType_ROR: res = ExtractRegister(il, operand, regNum, REGSZ_O(operand), false, resultSize); if (operand.shiftValue) res = il.RotateRight(resultSize, res, il.Const(1, operand.shiftValue)); return res; default: break; } // everything else falls through to maybe be left shifted switch (operand.shiftType) { case ShiftType_LSL: res = ExtractRegister(il, operand, regNum, REGSZ_O(operand), false, resultSize); break; case ShiftType_SXTB: res = ExtractRegister(il, operand, regNum, 1, true, resultSize); break; case ShiftType_SXTH: res = ExtractRegister(il, operand, regNum, 2, true, resultSize); break; case ShiftType_SXTW: res = ExtractRegister(il, operand, regNum, 4, true, resultSize); break; case ShiftType_SXTX: res = ExtractRegister(il, operand, regNum, 8, true, resultSize); break; case ShiftType_UXTB: res = ExtractRegister(il, operand, regNum, 1, false, resultSize); break; case ShiftType_UXTH: res = ExtractRegister(il, operand, regNum, 2, false, resultSize); break; case ShiftType_UXTW: res = ExtractRegister(il, operand, regNum, 4, false, resultSize); break; case ShiftType_UXTX: res = ExtractRegister(il, operand, regNum, 8, false, resultSize); break; default: il.AddInstruction(il.Unimplemented()); return il.Unimplemented(); } if (operand.shiftValue) res = il.ShiftLeft(resultSize, res, il.Const(1, operand.shiftValue)); return res; } static ExprId GetILOperandPreOrPostIndex(LowLevelILFunction& il, InstructionOperand& operand) { if (operand.operandClass != MEM_PRE_IDX && operand.operandClass != MEM_POST_IDX) return 0; if (operand.reg[1] == REG_NONE) { // ..., [Xn], #imm if (IMM_O(operand) == 0) return 0; return ILSETREG_O(operand, ILADDREG_O(operand, il.Const(REGSZ_O(operand), IMM_O(operand)))); } else { // ..., [Xn], <Xm> return ILSETREG_O(operand, ILADDREG_O(operand, il.Register(8, operand.reg[1]))); } } /* Returns an expression that does any pre-incrementing on an operand, if it exists */ static ExprId GetILOperandPreIndex(LowLevelILFunction& il, InstructionOperand& operand) { if (operand.operandClass != MEM_PRE_IDX) return 0; return GetILOperandPreOrPostIndex(il, operand); } /* Returns an expression that does any post-incrementing on an operand, if it exists */ static ExprId GetILOperandPostIndex(LowLevelILFunction& il, InstructionOperand& operand) { if (operand.operandClass != MEM_POST_IDX) return 0; return GetILOperandPreOrPostIndex(il, operand); } /* Returns an IL expression that reads (and only reads) from the operand. It accounts for, but does not generate IL that executes, pre and post indexing. The operand class can be overridden. An additional offset can be applied, convenient for calculating sequential loads and stores. */ static ExprId GetILOperandEffectiveAddress(LowLevelILFunction& il, InstructionOperand& operand, size_t addrSize, OperandClass oclass, size_t extra_offset) { ExprId addr = 0; if (oclass == NONE) oclass = operand.operandClass; switch (oclass) { case MEM_REG: // ldr x0, [x1] case MEM_POST_IDX: // ldr w0, [x1], #4 addr = ILREG_O(operand); if (extra_offset) addr = il.Add(addrSize, addr, il.Const(addrSize, extra_offset)); break; case MEM_OFFSET: // ldr w0, [x1, #4] case MEM_PRE_IDX: // ldr w0, [x1, #4]! addr = il.Add(addrSize, ILREG_O(operand), il.Const(addrSize, operand.immediate + extra_offset)); break; case MEM_EXTENDED: if (operand.shiftType == ShiftType_NONE) { addr = il.Add(addrSize, ILREG_O(operand), il.Const(addrSize, operand.immediate + extra_offset)); } else if (operand.shiftType == ShiftType_LSL) { if (extra_offset) { addr = il.Add(addrSize, ILREG_O(operand), il.Add(addrSize, il.ShiftLeft(addrSize, il.Const(addrSize, operand.immediate), il.Const(0, operand.shiftValue)), il.Const(addrSize, extra_offset))); } else { addr = il.Add(addrSize, ILREG_O(operand), il.ShiftLeft( addrSize, il.Const(addrSize, operand.immediate), il.Const(0, operand.shiftValue))); } } else { // printf("ERROR: dunno how to handle MEM_EXTENDED shiftType %d\n", operand.shiftType); ABORT_LIFT; } break; default: // printf("ERROR: dunno how to handle operand class %d\n", oclass); ABORT_LIFT; } return addr; } static size_t ReadILOperand(LowLevelILFunction& il, InstructionOperand& operand, size_t resultSize) { switch (operand.operandClass) { case IMM32: case IMM64: if (operand.shiftType != ShiftType_NONE && operand.shiftValue) return il.Const(resultSize, operand.immediate << operand.shiftValue); else return il.Const(resultSize, operand.immediate); case LABEL: return il.ConstPointer(8, operand.immediate); case REG: if (operand.reg[0] == REG_WZR || operand.reg[0] == REG_XZR) return il.Const(resultSize, 0); return GetShiftedRegister(il, operand, 0, resultSize); case MEM_REG: return il.Load(resultSize, il.Register(8, operand.reg[0])); case MEM_OFFSET: if (operand.immediate != 0) return il.Load( resultSize, il.Add(8, il.Register(8, operand.reg[0]), il.Const(8, operand.immediate))); else return il.Load(resultSize, il.Register(8, operand.reg[0])); case MEM_EXTENDED: return il.Load(resultSize, GetILOperandEffectiveAddress(il, operand, resultSize, NONE, 0)); case MEM_PRE_IDX: case MEM_POST_IDX: case MULTI_REG: case FIMM32: return GetFloat(il, operand, resultSize); case NONE: default: return il.Unimplemented(); } } unsigned v_unpack_lookup_sz[15] = {0, 1, 2, 4, 8, 16, 1, 2, 4, 8, 1, 2, 4, 1, 1}; extern "C" Register* v_unpack_lookup[15][32]; Register v_consolidate_lookup[32][15] = { // NONE .q .2d .4s .8h .16b .d .2s .4h .8b .s .2h .4b .h .b {REG_V0, REG_V0, REG_V0, REG_V0, REG_V0, REG_V0, REG_V0_D0, REG_V0_D0, REG_V0_D0, REG_V0_D0, REG_V0_S0, REG_V0_S0, REG_V0_S0, REG_V0_H0, REG_V0_B0}, {REG_V1, REG_V1, REG_V1, REG_V1, REG_V1, REG_V1, REG_V1_D0, REG_V1_D0, REG_V1_D0, REG_V1_D0, REG_V1_S0, REG_V1_S0, REG_V1_S0, REG_V1_H0, REG_V1_B0}, {REG_V2, REG_V2, REG_V2, REG_V2, REG_V2, REG_V2, REG_V2_D0, REG_V2_D0, REG_V2_D0, REG_V2_D0, REG_V2_S0, REG_V2_S0, REG_V2_S0, REG_V2_H0, REG_V2_B0}, {REG_V3, REG_V3, REG_V3, REG_V3, REG_V3, REG_V3, REG_V3_D0, REG_V3_D0, REG_V3_D0, REG_V3_D0, REG_V3_S0, REG_V3_S0, REG_V3_S0, REG_V3_H0, REG_V3_B0}, {REG_V4, REG_V4, REG_V4, REG_V4, REG_V4, REG_V4, REG_V4_D0, REG_V4_D0, REG_V4_D0, REG_V4_D0, REG_V4_S0, REG_V4_S0, REG_V4_S0, REG_V4_H0, REG_V4_B0}, {REG_V5, REG_V5, REG_V5, REG_V5, REG_V5, REG_V5, REG_V5_D0, REG_V5_D0, REG_V5_D0, REG_V5_D0, REG_V5_S0, REG_V5_S0, REG_V5_S0, REG_V5_H0, REG_V5_B0}, {REG_V6, REG_V6, REG_V6, REG_V6, REG_V6, REG_V6, REG_V6_D0, REG_V6_D0, REG_V6_D0, REG_V6_D0, REG_V6_S0, REG_V6_S0, REG_V6_S0, REG_V6_H0, REG_V6_B0}, {REG_V7, REG_V7, REG_V7, REG_V7, REG_V7, REG_V7, REG_V7_D0, REG_V7_D0, REG_V7_D0, REG_V7_D0, REG_V7_S0, REG_V7_S0, REG_V7_S0, REG_V7_H0, REG_V7_B0}, {REG_V8, REG_V8, REG_V8, REG_V8, REG_V8, REG_V8, REG_V8_D0, REG_V8_D0, REG_V8_D0, REG_V8_D0, REG_V8_S0, REG_V8_S0, REG_V8_S0, REG_V8_H0, REG_V8_B0}, {REG_V9, REG_V9, REG_V9, REG_V9, REG_V9, REG_V9, REG_V9_D0, REG_V9_D0, REG_V9_D0, REG_V9_D0, REG_V9_S0, REG_V9_S0, REG_V9_S0, REG_V9_H0, REG_V9_B0}, {REG_V10, REG_V10, REG_V10, REG_V10, REG_V10, REG_V10, REG_V10_D0, REG_V10_D0, REG_V10_D0, REG_V10_D0, REG_V10_S0, REG_V10_S0, REG_V10_S0, REG_V10_H0, REG_V10_B0}, {REG_V11, REG_V11, REG_V11, REG_V11, REG_V11, REG_V11, REG_V11_D0, REG_V11_D0, REG_V11_D0, REG_V11_D0, REG_V11_S0, REG_V11_S0, REG_V11_S0, REG_V11_H0, REG_V11_B0}, {REG_V12, REG_V12, REG_V12, REG_V12, REG_V12, REG_V12, REG_V12_D0, REG_V12_D0, REG_V12_D0, REG_V12_D0, REG_V12_S0, REG_V12_S0, REG_V12_S0, REG_V12_H0, REG_V12_B0}, {REG_V13, REG_V13, REG_V13, REG_V13, REG_V13, REG_V13, REG_V13_D0, REG_V13_D0, REG_V13_D0, REG_V13_D0, REG_V13_S0, REG_V13_S0, REG_V13_S0, REG_V13_H0, REG_V13_B0}, {REG_V14, REG_V14, REG_V14, REG_V14, REG_V14, REG_V14, REG_V14_D0, REG_V14_D0, REG_V14_D0, REG_V14_D0, REG_V14_S0, REG_V14_S0, REG_V14_S0, REG_V14_H0, REG_V14_B0}, {REG_V15, REG_V15, REG_V15, REG_V15, REG_V15, REG_V15, REG_V15_D0, REG_V15_D0, REG_V15_D0, REG_V15_D0, REG_V15_S0, REG_V15_S0, REG_V15_S0, REG_V15_H0, REG_V15_B0}, {REG_V16, REG_V16, REG_V16, REG_V16, REG_V16, REG_V16, REG_V16_D0, REG_V16_D0, REG_V16_D0, REG_V16_D0, REG_V16_S0, REG_V16_S0, REG_V16_S0, REG_V16_H0, REG_V16_B0}, {REG_V17, REG_V17, REG_V17, REG_V17, REG_V17, REG_V17, REG_V17_D0, REG_V17_D0, REG_V17_D0, REG_V17_D0, REG_V17_S0, REG_V17_S0, REG_V17_S0, REG_V17_H0, REG_V17_B0}, {REG_V18, REG_V18, REG_V18, REG_V18, REG_V18, REG_V18, REG_V18_D0, REG_V18_D0, REG_V18_D0, REG_V18_D0, REG_V18_S0, REG_V18_S0, REG_V18_S0, REG_V18_H0, REG_V18_B0}, {REG_V19, REG_V19, REG_V19, REG_V19, REG_V19, REG_V19, REG_V19_D0, REG_V19_D0, REG_V19_D0, REG_V19_D0, REG_V19_S0, REG_V19_S0, REG_V19_S0, REG_V19_H0, REG_V19_B0}, {REG_V20, REG_V20, REG_V20, REG_V20, REG_V20, REG_V20, REG_V20_D0, REG_V20_D0, REG_V20_D0, REG_V20_D0, REG_V20_S0, REG_V20_S0, REG_V20_S0, REG_V20_H0, REG_V20_B0}, {REG_V21, REG_V21, REG_V21, REG_V21, REG_V21, REG_V21, REG_V21_D0, REG_V21_D0, REG_V21_D0, REG_V21_D0, REG_V21_S0, REG_V21_S0, REG_V21_S0, REG_V21_H0, REG_V21_B0}, {REG_V22, REG_V22, REG_V22, REG_V22, REG_V22, REG_V22, REG_V22_D0, REG_V22_D0, REG_V22_D0, REG_V22_D0, REG_V22_S0, REG_V22_S0, REG_V22_S0, REG_V22_H0, REG_V22_B0}, {REG_V23, REG_V23, REG_V23, REG_V23, REG_V23, REG_V23, REG_V23_D0, REG_V23_D0, REG_V23_D0, REG_V23_D0, REG_V23_S0, REG_V23_S0, REG_V23_S0, REG_V23_H0, REG_V23_B0}, {REG_V24, REG_V24, REG_V24, REG_V24, REG_V24, REG_V24, REG_V24_D0, REG_V24_D0, REG_V24_D0, REG_V24_D0, REG_V24_S0, REG_V24_S0, REG_V24_S0, REG_V24_H0, REG_V24_B0}, {REG_V25, REG_V25, REG_V25, REG_V25, REG_V25, REG_V25, REG_V25_D0, REG_V25_D0, REG_V25_D0, REG_V25_D0, REG_V25_S0, REG_V25_S0, REG_V25_S0, REG_V25_H0, REG_V25_B0}, {REG_V26, REG_V26, REG_V26, REG_V26, REG_V26, REG_V26, REG_V26_D0, REG_V26_D0, REG_V26_D0, REG_V26_D0, REG_V26_S0, REG_V26_S0, REG_V26_S0, REG_V26_H0, REG_V26_B0}, {REG_V27, REG_V27, REG_V27, REG_V27, REG_V27, REG_V27, REG_V27_D0, REG_V27_D0, REG_V27_D0, REG_V27_D0, REG_V27_S0, REG_V27_S0, REG_V27_S0, REG_V27_H0, REG_V27_B0}, {REG_V28, REG_V28, REG_V28, REG_V28, REG_V28, REG_V28, REG_V28_D0, REG_V28_D0, REG_V28_D0, REG_V28_D0, REG_V28_S0, REG_V28_S0, REG_V28_S0, REG_V28_H0, REG_V28_B0}, {REG_V29, REG_V29, REG_V29, REG_V29, REG_V29, REG_V29, REG_V29_D0, REG_V29_D0, REG_V29_D0, REG_V29_D0, REG_V29_S0, REG_V29_S0, REG_V29_S0, REG_V29_H0, REG_V29_B0}, {REG_V30, REG_V30, REG_V30, REG_V30, REG_V30, REG_V30, REG_V30_D0, REG_V30_D0, REG_V30_D0, REG_V30_D0, REG_V30_S0, REG_V30_S0, REG_V30_S0, REG_V30_H0, REG_V30_B0}, {REG_V31, REG_V31, REG_V31, REG_V31, REG_V31, REG_V31, REG_V31_D0, REG_V31_D0, REG_V31_D0, REG_V31_D0, REG_V31_S0, REG_V31_S0, REG_V31_S0, REG_V31_H0, REG_V31_B0}, }; /* v28.d[1] -> REG_V0_D1 */ static Register vector_reg_minimize(InstructionOperand& oper) { if (!IS_ASIMD_O(oper)) return REG_NONE; if (oper.arrSpec == ARRSPEC_NONE) { if (oper.laneUsed) return REG_NONE; // cannot have lane without an arrangement spec return oper.reg[0]; } int vidx = oper.reg[0] - REG_V0; if (vidx < 0 || vidx > 31) return REG_NONE; if (oper.laneUsed) { switch (oper.arrSpec) { case ARRSPEC_FULL: return oper.reg[0]; case ARRSPEC_1DOUBLE: case ARRSPEC_2DOUBLES: if (oper.lane >= 2) return REG_NONE; return v_unpack_lookup[ARRSPEC_2DOUBLES][vidx][oper.lane]; case ARRSPEC_1SINGLE: case ARRSPEC_2SINGLES: case ARRSPEC_4SINGLES: if (oper.lane >= 4) return REG_NONE; return v_unpack_lookup[ARRSPEC_4SINGLES][vidx][oper.lane]; case ARRSPEC_1HALF: case ARRSPEC_2HALVES: case ARRSPEC_4HALVES: case ARRSPEC_8HALVES: if (oper.lane >= 8) return REG_NONE; return v_unpack_lookup[ARRSPEC_8HALVES][vidx][oper.lane]; case ARRSPEC_1BYTE: case ARRSPEC_4BYTES: case ARRSPEC_8BYTES: case ARRSPEC_16BYTES: if (oper.lane >= 16) return REG_NONE; return v_unpack_lookup[ARRSPEC_16BYTES][vidx][oper.lane]; default: break; } } else { switch (oper.arrSpec) { case ARRSPEC_FULL: case ARRSPEC_2DOUBLES: case ARRSPEC_4SINGLES: case ARRSPEC_8HALVES: case ARRSPEC_16BYTES: return oper.reg[0]; case ARRSPEC_1DOUBLE: case ARRSPEC_2SINGLES: case ARRSPEC_4HALVES: case ARRSPEC_8BYTES: return v_unpack_lookup[ARRSPEC_2DOUBLES][vidx][0]; case ARRSPEC_1SINGLE: case ARRSPEC_2HALVES: case ARRSPEC_4BYTES: return v_unpack_lookup[ARRSPEC_4SINGLES][vidx][0]; case ARRSPEC_1HALF: // case ARRSPEC_2BYTE return v_unpack_lookup[ARRSPEC_8HALVES][vidx][0]; case ARRSPEC_1BYTE: return v_unpack_lookup[ARRSPEC_16BYTES][vidx][0]; default: break; } } return REG_NONE; } /* "promote" the spec to full width so lane can select any */ static ArrangementSpec promote_spec(ArrangementSpec spec) { switch (spec) { case ARRSPEC_1DOUBLE: return ARRSPEC_2DOUBLES; case ARRSPEC_1SINGLE: case ARRSPEC_2SINGLES: return ARRSPEC_4SINGLES; case ARRSPEC_1HALF: case ARRSPEC_2HALVES: case ARRSPEC_4HALVES: return ARRSPEC_8HALVES; case ARRSPEC_1BYTE: case ARRSPEC_4BYTES: case ARRSPEC_8BYTES: return ARRSPEC_16BYTES; default: return spec; } } static int unpack_vector(InstructionOperand& oper, Register* result) { if (oper.operandClass == REG) { /* register without an arrangement specification is just a register examples: "d18", "d6", "v7" */ if (oper.arrSpec == ARRSPEC_NONE) { result[0] = oper.reg[0]; return 1; } /* require V register with valid arrangement spec examples: "v17.2s", "v8.4h", "v21.8b" */ if (oper.reg[0] < REG_V0 || oper.reg[0] > REG_V31) return 0; if (oper.arrSpec <= ARRSPEC_NONE || oper.arrSpec > ARRSPEC_1BYTE) return 0; /* lookup, copy result */ if (oper.laneUsed) { ArrangementSpec spec = promote_spec(oper.arrSpec); int n_lanes = v_unpack_lookup_sz[spec]; if (oper.lane >= n_lanes) return 0; result[0] = v_unpack_lookup[spec][oper.reg[0] - REG_V0][oper.lane]; return 1; } int n = v_unpack_lookup_sz[oper.arrSpec]; for (int i = 0; i < n; ++i) result[i] = v_unpack_lookup[oper.arrSpec][oper.reg[0] - REG_V0][i]; return n; } else if (oper.operandClass == MULTI_REG) { if (oper.laneUsed) { /* multireg with a lane examples: "ld2 {v17.d, v18.d}[1], [x20]" */ ArrangementSpec spec = promote_spec(oper.arrSpec); int n = 0; for (int i = 0; i < 4 && oper.reg[i] != REG_NONE; i++) { int n_lanes = v_unpack_lookup_sz[spec]; if (oper.lane >= n_lanes) return 0; result[i] = v_unpack_lookup[spec][oper.reg[i] - REG_V0][oper.lane]; n += 1; } return n; } else { /* multireg without a lane examples: "{v0.8b, v1.8b}", "{v8.2s, v9.2s}" */ if (oper.arrSpec < ARRSPEC_NONE || oper.arrSpec > ARRSPEC_1BYTE) return 0; int n = 0; for (int i = 0; i < 4 && oper.reg[i] != REG_NONE; i++) { result[i] = v_consolidate_lookup[oper.reg[i] - REG_V0][oper.arrSpec]; n += 1; } return n; } } return 0; } /* if we have two operands that have the same arrangement spec, instead of treating them as distinct sets of registers, see if we can consolidate the set of registers into a single larger register. This allows us to easily lift things like 'mov v0.16b, v1.16b' as 'mov v0, v1' */ static int consolidate_vector( InstructionOperand& operand1, InstructionOperand& operand2, Register *result) { /* make sure both our operand classes are single regs */ if (operand1.operandClass != REG || operand2.operandClass != REG) return 0; /* make sure our arrSpec's match. We need this to deal with cases where the arrSpec might have different sizes, e.g. 'uxtl v2.2d, v8.2s'.*/ if (operand1.arrSpec != operand2.arrSpec) return 0; result[0] = v_consolidate_lookup[operand1.reg[0]-REG_V0][operand1.arrSpec]; result[1] = v_consolidate_lookup[operand2.reg[0]-REG_V0][operand2.arrSpec]; return 1; } static void LoadStoreOperandPair(LowLevelILFunction& il, bool load, InstructionOperand& operand1, InstructionOperand& operand2, InstructionOperand& operand3) { unsigned sz = REGSZ_O(operand1); /* do pre-indexing */ ExprId tmp = GetILOperandPreIndex(il, operand3); if (tmp) il.AddInstruction(tmp); /* compute addresses */ OperandClass oclass = (operand3.operandClass == MEM_PRE_IDX) ? MEM_REG : operand3.operandClass; ExprId addr0 = GetILOperandEffectiveAddress(il, operand3, 8, oclass, 0); ExprId addr1 = GetILOperandEffectiveAddress(il, operand3, 8, oclass, sz); /* load/store */ if (load) { il.AddInstruction(il.SetRegister(sz, REG_O(operand1), il.Load(sz, addr0))); il.AddInstruction(il.SetRegister(sz, REG_O(operand2), il.Load(sz, addr1))); } else { il.AddInstruction(il.Store(sz, addr0, ILREG_O(operand1))); il.AddInstruction(il.Store(sz, addr1, ILREG_O(operand2))); } /* do post-indexing */ tmp = GetILOperandPostIndex(il, operand3); if (tmp) il.AddInstruction(tmp); } static void LoadStoreVector( LowLevelILFunction& il, bool is_load, InstructionOperand& oper0, InstructionOperand& oper1) { /* do pre-indexing */ ExprId tmp = GetILOperandPreIndex(il, oper1); if (tmp) il.AddInstruction(tmp); Register regs[16]; int regs_n = unpack_vector(oper0, regs); /* if we pre-indexed, base sequential effective addresses off the base register */ OperandClass oclass = (oper1.operandClass == MEM_PRE_IDX) ? MEM_REG : oper1.operandClass; int offset = 0; for (int i = 0; i < regs_n; ++i) { int rsize = get_register_size(regs[i]); ExprId eaddr = GetILOperandEffectiveAddress(il, oper1, 8, oclass, offset); if (is_load) il.AddInstruction(il.SetRegister(rsize, regs[i], il.Load(rsize, eaddr))); else il.AddInstruction(il.Store(rsize, eaddr, il.Register(rsize, regs[i]))); offset += rsize; } /* do post-indexing */ tmp = GetILOperandPostIndex(il, oper1); if (tmp) il.AddInstruction(tmp); } static void LoadStoreOperand(LowLevelILFunction& il, bool load, InstructionOperand& operand1, /* register that gets read/written */ InstructionOperand& operand2, /* location the read/write occurs */ int load_store_sz) { if (!load_store_sz) load_store_sz = REGSZ_O(operand1); ExprId tmp; if (load) { switch (operand2.operandClass) { case MEM_REG: // operand1.reg = [operand2.reg] il.AddInstruction( ILSETREG_O(operand1, il.Operand(1, il.Load(load_store_sz, ILREG_O(operand2))))); break; case MEM_OFFSET: if (!load_store_sz) load_store_sz = REGSZ_O(operand1); // operand1.reg = [operand2.reg + operand2.imm] if (IMM_O(operand2) == 0) tmp = ILREG_O(operand2); else tmp = ILADDREG_O(operand2, il.Const(REGSZ_O(operand2), IMM_O(operand2))); il.AddInstruction(ILSETREG_O(operand1, il.Operand(1, il.Load(load_store_sz, tmp)))); break; case MEM_PRE_IDX: // operand2.reg += operand2.imm if (IMM_O(operand2) != 0) il.AddInstruction(ILSETREG_O(operand2, il.Add(REGSZ_O(operand2), ILREG_O(operand2), il.Const(REGSZ_O(operand2), IMM_O(operand2))))); // operand1.reg = [operand2.reg] il.AddInstruction( ILSETREG_O(operand1, il.Operand(1, il.Load(load_store_sz, ILREG_O(operand2))))); break; case MEM_POST_IDX: // operand1.reg = [operand2.reg] il.AddInstruction( ILSETREG_O(operand1, il.Operand(1, il.Load(load_store_sz, ILREG_O(operand2))))); // operand2.reg += operand2.imm if (IMM_O(operand2) != 0) il.AddInstruction(ILSETREG_O(operand2, il.Add(REGSZ_O(operand2), ILREG_O(operand2), il.Const(REGSZ_O(operand2), IMM_O(operand2))))); break; case MEM_EXTENDED: il.AddInstruction(ILSETREG_O(operand1, il.Operand(1, il.Load(load_store_sz, il.Add(REGSZ_O(operand2), ILREG_O(operand2), GetShiftedRegister(il, operand2, 1, REGSZ_O(operand2))))))); break; case LABEL: il.AddInstruction(ILSETREG_O( operand1, il.Operand(1, il.Load(load_store_sz, il.ConstPointer(8, IMM_O(operand2)))))); break; case IMM32: case IMM64: il.AddInstruction(ILSETREG_O(operand1, il.Const(REGSZ_O(operand1), IMM_O(operand2)))); break; default: il.AddInstruction(il.Unimplemented()); break; } } else // store { switch (operand2.operandClass) { case MEM_REG: il.AddInstruction( il.Operand(1, il.Store(load_store_sz, ILREG_O(operand2), ILREG_O(operand1)))); break; case MEM_OFFSET: //[operand2.reg + operand2.immediate] = operand1.reg if (IMM_O(operand2) == 0) tmp = ILREG_O(operand2); else tmp = ILADDREG_O(operand2, il.Const(REGSZ_O(operand2), IMM_O(operand2))); il.AddInstruction(il.Operand(1, il.Store(load_store_sz, tmp, ILREG_O(operand1)))); break; case MEM_PRE_IDX: // operand2.reg = operand2.reg + operand2.immediate if (IMM_O(operand2) != 0) il.AddInstruction(ILSETREG_O( operand2, ILADDREG_O(operand2, il.Const(REGSZ_O(operand2), IMM_O(operand2))))); //[operand2.reg] = operand1.reg il.AddInstruction( il.Operand(1, il.Store(load_store_sz, ILREG_O(operand2), ILREG_O(operand1)))); break; case MEM_POST_IDX: //[operand2.reg] = operand1.reg il.AddInstruction( il.Operand(1, il.Store(load_store_sz, ILREG_O(operand2), ILREG_O(operand1)))); // operand2.reg = operand2.reg + operand2.immediate if (IMM_O(operand2) != 0) il.AddInstruction(ILSETREG_O( operand2, ILADDREG_O(operand2, il.Const(REGSZ_O(operand2), IMM_O(operand2))))); break; case MEM_EXTENDED: il.AddInstruction(il.Operand( 1, il.Store(load_store_sz, il.Add(REGSZ_O(operand2), il.Register(REGSZ_O(operand2), operand2.reg[0]), GetShiftedRegister(il, operand2, 1, REGSZ_O(operand2))), ILREG_O(operand1)))); break; default: il.AddInstruction(il.Unimplemented()); break; } } } static void LoadStoreOperandSize(LowLevelILFunction& il, bool load, bool signedImm, size_t size, InstructionOperand& operand1, InstructionOperand& operand2) { ExprId tmp; if (load) { switch (operand2.operandClass) { case MEM_REG: // operand1.reg = [operand2.reg] tmp = il.Operand(1, il.Load(size, ILREG_O(operand2))); if (signedImm) tmp = il.SignExtend(REGSZ_O(operand1), tmp); else tmp = il.ZeroExtend(REGSZ_O(operand1), tmp); il.AddInstruction(ILSETREG_O(operand1, tmp)); break; case MEM_OFFSET: // operand1.reg = [operand2.reg + operand2.imm] if (IMM_O(operand2) == 0) tmp = ILREG_O(operand2); else tmp = ILADDREG_O(operand2, il.Const(REGSZ_O(operand2), IMM_O(operand2))); tmp = il.Operand(1, il.Load(size, tmp)); if (signedImm) tmp = il.SignExtend(REGSZ_O(operand1), tmp); else tmp = il.ZeroExtend(REGSZ_O(operand1), tmp); il.AddInstruction(ILSETREG_O(operand1, tmp)); break; case MEM_PRE_IDX: // operand2.reg += operand2.imm if (IMM_O(operand2) != 0) il.AddInstruction(ILSETREG_O(operand2, il.Add(REGSZ_O(operand2), ILREG_O(operand2), il.Const(REGSZ_O(operand2), IMM_O(operand2))))); // operand1.reg = [operand2.reg] tmp = il.Operand(1, il.Load(size, ILREG_O(operand2))); if (signedImm) tmp = il.SignExtend(REGSZ_O(operand1), tmp); else tmp = il.ZeroExtend(REGSZ_O(operand1), tmp); il.AddInstruction(ILSETREG_O(operand1, tmp)); break; case MEM_POST_IDX: // operand1.reg = [operand2.reg] tmp = il.Operand(1, il.Load(size, ILREG_O(operand2))); if (signedImm) tmp = il.SignExtend(REGSZ_O(operand1), tmp); else tmp = il.ZeroExtend(REGSZ_O(operand1), tmp); il.AddInstruction(ILSETREG_O(operand1, tmp)); // operand2.reg += operand2.imm if (IMM_O(operand2) != 0) il.AddInstruction(ILSETREG_O(operand2, il.Add(REGSZ_O(operand2), ILREG_O(operand2), il.Const(REGSZ_O(operand2), IMM_O(operand2))))); break; case MEM_EXTENDED: tmp = il.Operand(1, il.Load(size, il.Add(REGSZ_O(operand2), ILREG_O(operand2), GetShiftedRegister(il, operand2, 1, REGSZ_O(operand2))))); if (signedImm) tmp = il.SignExtend(REGSZ_O(operand1), tmp); else tmp = il.ZeroExtend(REGSZ_O(operand1), tmp); il.AddInstruction(ILSETREG_O(operand1, tmp)); break; default: il.AddInstruction(il.Unimplemented()); break; } } else // store { ExprId valToStore = il.Operand(0, ILREG_O(operand1)); if (size < REGSZ_O(operand1)) valToStore = il.LowPart(size, valToStore); switch (operand2.operandClass) { case MEM_REG: il.AddInstruction(il.Operand(1, il.Store(size, ILREG_O(operand2), valToStore))); break; case MEM_OFFSET: //[operand2.reg + operand2.immediate] = operand1.reg if (IMM_O(operand2) == 0) tmp = il.Store(size, ILREG_O(operand2), valToStore); else tmp = il.Store( size, ILADDREG_O(operand2, il.Const(REGSZ_O(operand2), IMM_O(operand2))), valToStore); il.AddInstruction(il.Operand(1, tmp)); break; case MEM_PRE_IDX: // operand2.reg = operand2.reg + operand2.immediate if (IMM_O(operand2) != 0) il.AddInstruction(ILSETREG_O( operand2, ILADDREG_O(operand2, il.Const(REGSZ_O(operand2), IMM_O(operand2))))); //[operand2.reg] = operand1.reg il.AddInstruction(il.Operand(1, il.Store(size, ILREG_O(operand2), valToStore))); break; case MEM_POST_IDX: //[operand2.reg] = operand1.reg il.AddInstruction(il.Operand(1, il.Store(size, ILREG_O(operand2), valToStore))); // operand2.reg = operand2.reg + operand2.immediate if (IMM_O(operand2) != 0) il.AddInstruction(ILSETREG_O( operand2, ILADDREG_O(operand2, il.Const(REGSZ_O(operand2), IMM_O(operand2))))); break; case MEM_EXTENDED: il.AddInstruction(il.Operand( 1, il.Store(size, il.Add(REGSZ_O(operand2), il.Register(REGSZ_O(operand2), operand2.reg[0]), GetShiftedRegister(il, operand2, 1, REGSZ_O(operand2))), valToStore))); break; default: il.AddInstruction(il.Unimplemented()); break; } } } static size_t DirectJump( Architecture* arch, LowLevelILFunction& il, uint64_t target, size_t addrSize) { BNLowLevelILLabel* label = il.GetLabelForAddress(arch, target); if (label) return il.Goto(*label); else return il.Jump(il.ConstPointer(addrSize, target)); return 0; } static ExprId ExtractBits( LowLevelILFunction& il, InstructionOperand& reg, size_t nbits, size_t rightMostBit) { // Get N set bits at offset O #define BITMASK(N, O) (((1LL << nbits) - 1) << O) return il.And(REGSZ_O(reg), ILREG_O(reg), il.Const(REGSZ_O(reg), BITMASK(nbits, rightMostBit))); } static ExprId ExtractBit(LowLevelILFunction& il, InstructionOperand& reg, size_t bit) { return il.And(REGSZ_O(reg), ILREG_O(reg), il.Const(REGSZ_O(reg), (1 << bit))); } static void ConditionalJump(Architecture* arch, LowLevelILFunction& il, size_t cond, size_t addrSize, uint64_t t, uint64_t f) { BNLowLevelILLabel* trueLabel = il.GetLabelForAddress(arch, t); BNLowLevelILLabel* falseLabel = il.GetLabelForAddress(arch, f); if (trueLabel && falseLabel) { il.AddInstruction(il.If(cond, *trueLabel, *falseLabel)); return; } LowLevelILLabel trueCode, falseCode; if (trueLabel) { il.AddInstruction(il.If(cond, *trueLabel, falseCode)); il.MarkLabel(falseCode); il.AddInstruction(il.Jump(il.ConstPointer(addrSize, f))); return; } if (falseLabel) { il.AddInstruction(il.If(cond, trueCode, *falseLabel)); il.MarkLabel(trueCode); il.AddInstruction(il.Jump(il.ConstPointer(addrSize, t))); return; } il.AddInstruction(il.If(cond, trueCode, falseCode)); il.MarkLabel(trueCode); il.AddInstruction(il.Jump(il.ConstPointer(addrSize, t))); il.MarkLabel(falseCode); il.AddInstruction(il.Jump(il.ConstPointer(addrSize, f))); } enum Arm64Intrinsic operation_to_intrinsic(int operation) { switch (operation) { case ARM64_AUTDA: return ARM64_INTRIN_AUTDA; case ARM64_AUTDB: return ARM64_INTRIN_AUTDB; case ARM64_AUTIA: return ARM64_INTRIN_AUTIA; case ARM64_AUTIB: return ARM64_INTRIN_AUTIB; case ARM64_AUTIB1716: return ARM64_INTRIN_AUTIB1716; case ARM64_AUTIBSP: return ARM64_INTRIN_AUTIBSP; case ARM64_AUTIBZ: return ARM64_INTRIN_AUTIBZ; case ARM64_AUTDZA: return ARM64_INTRIN_AUTDZA; case ARM64_AUTDZB: return ARM64_INTRIN_AUTDZB; case ARM64_AUTIZA: return ARM64_INTRIN_AUTIZA; case ARM64_AUTIZB: return ARM64_INTRIN_AUTIZB; case ARM64_PACDA: return ARM64_INTRIN_PACDA; case ARM64_PACDB: return ARM64_INTRIN_PACDB; case ARM64_PACDZA: return ARM64_INTRIN_PACDZA; case ARM64_PACDZB: return ARM64_INTRIN_PACDZB; case ARM64_PACGA: return ARM64_INTRIN_PACGA; case ARM64_PACIA: return ARM64_INTRIN_PACIA; case ARM64_PACIA1716: return ARM64_INTRIN_PACIA1716; case ARM64_PACIASP: return ARM64_INTRIN_PACIASP; case ARM64_PACIAZ: return ARM64_INTRIN_PACIAZ; case ARM64_PACIB: return ARM64_INTRIN_PACIB; case ARM64_PACIB1716: return ARM64_INTRIN_PACIB1716; case ARM64_PACIBSP: return ARM64_INTRIN_PACIBSP; case ARM64_PACIBZ: return ARM64_INTRIN_PACIBZ; case ARM64_PACIZA: return ARM64_INTRIN_PACIZA; case ARM64_PACIZB: return ARM64_INTRIN_PACIZB; case ARM64_XPACD: return ARM64_INTRIN_XPACD; case ARM64_XPACI: return ARM64_INTRIN_XPACI; case ARM64_XPACLRI: return ARM64_INTRIN_XPACLRI; default: return ARM64_INTRIN_INVALID; } } bool GetLowLevelILForInstruction( Architecture* arch, uint64_t addr, LowLevelILFunction& il, Instruction& instr, size_t addrSize) { InstructionOperand& operand1 = instr.operands[0]; InstructionOperand& operand2 = instr.operands[1]; InstructionOperand& operand3 = instr.operands[2]; InstructionOperand& operand4 = instr.operands[3]; int n_instrs_before = il.GetInstructionCount(); // printf("%s() operation:%d encoding:%d\n", __func__, instr.operation, instr.encoding); LowLevelILLabel trueLabel, falseLabel; switch (instr.operation) { case ARM64_ADD: case ARM64_ADDS: il.AddInstruction( ILSETREG_O(operand1, il.Add(REGSZ_O(operand1), ILREG_O(operand2), ReadILOperand(il, operand3, REGSZ_O(operand1)), SETFLAGS))); break; case ARM64_ADC: case ARM64_ADCS: il.AddInstruction(ILSETREG_O(operand1, il.AddCarry(REGSZ_O(operand1), ILREG_O(operand2), ReadILOperand(il, operand3, REGSZ_O(operand1)), il.Flag(IL_FLAG_C), SETFLAGS))); break; case ARM64_AND: case ARM64_ANDS: il.AddInstruction( ILSETREG_O(operand1, il.And(REGSZ_O(operand1), ILREG_O(operand2), ReadILOperand(il, operand3, REGSZ_O(operand1)), SETFLAGS))); break; case ARM64_ADR: case ARM64_ADRP: il.AddInstruction(ILSETREG_O(operand1, il.ConstPointer(REGSZ_O(operand1), IMM_O(operand2)))); break; case ARM64_ASR: il.AddInstruction(ILSETREG_O(operand1, il.ArithShiftRight(REGSZ_O(operand2), ILREG_O(operand2), ReadILOperand(il, operand3, REGSZ_O(operand2))))); break; case ARM64_AESD: il.AddInstruction(il.Intrinsic({RegisterOrFlag::Register(REG_O(operand1))}, ARM64_INTRIN_AESD, {ILREG_O(operand1), ILREG_O(operand2)})); break; case ARM64_AESE: il.AddInstruction(il.Intrinsic({RegisterOrFlag::Register(REG_O(operand1))}, ARM64_INTRIN_AESE, {ILREG_O(operand1), ILREG_O(operand2)})); break; case ARM64_BTI: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_HINT_BTI, {})); break; case ARM64_B: il.AddInstruction(DirectJump(arch, il, IMM_O(operand1), addrSize)); break; case ARM64_B_NE: ConditionalJump(arch, il, il.FlagCondition(LLFC_NE), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_EQ: ConditionalJump(arch, il, il.FlagCondition(LLFC_E), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_CS: ConditionalJump(arch, il, il.FlagCondition(LLFC_UGE), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_CC: ConditionalJump(arch, il, il.FlagCondition(LLFC_ULT), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_MI: ConditionalJump(arch, il, il.FlagCondition(LLFC_NEG), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_PL: ConditionalJump(arch, il, il.FlagCondition(LLFC_POS), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_VS: ConditionalJump(arch, il, il.FlagCondition(LLFC_O), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_VC: ConditionalJump(arch, il, il.FlagCondition(LLFC_NO), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_HI: ConditionalJump(arch, il, il.FlagCondition(LLFC_UGT), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_LS: ConditionalJump(arch, il, il.FlagCondition(LLFC_ULE), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_GE: ConditionalJump(arch, il, il.FlagCondition(LLFC_SGE), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_LT: ConditionalJump(arch, il, il.FlagCondition(LLFC_SLT), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_GT: ConditionalJump(arch, il, il.FlagCondition(LLFC_SGT), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_B_LE: ConditionalJump(arch, il, il.FlagCondition(LLFC_SLE), addrSize, IMM_O(operand1), addr + 4); return false; case ARM64_BL: il.AddInstruction(il.Call(il.ConstPointer(addrSize, IMM_O(operand1)))); break; case ARM64_BLR: case ARM64_BLRAA: case ARM64_BLRAAZ: case ARM64_BLRAB: case ARM64_BLRABZ: il.AddInstruction(il.Call(ILREG_O(operand1))); break; case ARM64_BFC: il.AddInstruction(ILSETREG_O( operand1, il.And(REGSZ_O(operand1), il.Const(REGSZ_O(operand1), ~(ONES(IMM_O(operand3)) << IMM_O(operand2))), ILREG_O(operand1)))); break; case ARM64_BFI: il.AddInstruction(ILSETREG_O(operand1, il.Or(REGSZ_O(operand1), il.And(REGSZ_O(operand1), il.Const(REGSZ_O(operand1), ~(ONES(IMM_O(operand4)) << IMM_O(operand3))), ILREG_O(operand1)), il.ShiftLeft(REGSZ_O(operand1), il.And(REGSZ_O(operand1), il.Const(REGSZ_O(operand1), ONES(IMM_O(operand4))), ILREG_O(operand2)), il.Const(0, IMM_O(operand3)))))); break; case ARM64_BFXIL: il.AddInstruction(ILSETREG_O(operand1, il.Or(REGSZ_O(operand1), il.And(REGSZ_O(operand1), ILREG_O(operand1), il.Const(REGSZ_O(operand1), ~ONES(IMM_O(operand4)))), il.LogicalShiftRight(REGSZ_O(operand1), il.And(REGSZ_O(operand1), ILREG_O(operand2), il.Const(REGSZ_O(operand1), ONES(IMM_O(operand4)) << IMM_O(operand3))), il.Const(0, IMM_O(operand3)))))); break; case ARM64_BR: case ARM64_BRAA: case ARM64_BRAAZ: case ARM64_BRAB: case ARM64_BRABZ: il.AddInstruction(il.Jump(ILREG_O(operand1))); return false; case ARM64_BIC: case ARM64_BICS: il.AddInstruction(ILSETREG_O(operand1, il.And(REGSZ_O(operand2), ILREG_O(operand2), il.Not(REGSZ_O(operand2), ReadILOperand(il, operand3, REGSZ_O(operand2))), SETFLAGS))); break; case ARM64_CAS: // these compare-and-swaps can be 32 or 64 bit case ARM64_CASA: case ARM64_CASAL: case ARM64_CASL: GenIfElse(il, il.CompareEqual( REGSZ_O(operand1), ILREG_O(operand1), il.Load(REGSZ_O(operand1), ILREG_O(operand3))), il.Store(REGSZ_O(operand1), ILREG_O(operand3), ILREG_O(operand2)), 0); break; case ARM64_CASAH: // these compare-and-swaps are 16 bit case ARM64_CASALH: case ARM64_CASH: case ARM64_CASLH: GenIfElse(il, il.CompareEqual(REGSZ_O(operand1), ExtractRegister(il, operand1, 0, 2, false, 2), il.Load(2, ILREG_O(operand3))), il.Store(2, ILREG_O(operand3), ExtractRegister(il, operand2, 0, 2, false, 2)), 0); break; case ARM64_CASAB: // these compare-and-swaps are 8 bit case ARM64_CASALB: case ARM64_CASB: case ARM64_CASLB: GenIfElse(il, il.CompareEqual(REGSZ_O(operand1), ExtractRegister(il, operand1, 0, 1, false, 1), il.Load(1, ILREG_O(operand3))), il.Store(1, ILREG_O(operand3), ExtractRegister(il, operand2, 0, 1, false, 1)), 0); break; case ARM64_CBNZ: ConditionalJump(arch, il, il.CompareNotEqual(REGSZ_O(operand1), ILREG_O(operand1), il.Const(REGSZ_O(operand1), 0)), addrSize, IMM_O(operand2), addr + 4); return false; case ARM64_CBZ: ConditionalJump(arch, il, il.CompareEqual(REGSZ_O(operand1), ILREG_O(operand1), il.Const(REGSZ_O(operand1), 0)), addrSize, IMM_O(operand2), addr + 4); return false; case ARM64_CMN: il.AddInstruction(il.Add(REGSZ_O(operand1), ILREG_O(operand1), ReadILOperand(il, operand2, REGSZ_O(operand1)), SETFLAGS)); break; case ARM64_CCMN: { LowLevelILLabel trueCode, falseCode, done; il.AddInstruction(il.If(GetCondition(il, operand4.cond), trueCode, falseCode)); il.MarkLabel(trueCode); il.AddInstruction(il.Add(REGSZ_O(operand1), ILREG_O(operand1), ReadILOperand(il, operand2, REGSZ_O(operand1)), SETFLAGS)); il.AddInstruction(il.Goto(done)); il.MarkLabel(falseCode); il.AddInstruction(il.SetFlag(IL_FLAG_N, il.Const(0, (IMM_O(operand3) >> 3) & 1))); il.AddInstruction(il.SetFlag(IL_FLAG_Z, il.Const(0, (IMM_O(operand3) >> 2) & 1))); il.AddInstruction(il.SetFlag(IL_FLAG_C, il.Const(0, (IMM_O(operand3) >> 1) & 1))); il.AddInstruction(il.SetFlag(IL_FLAG_V, il.Const(0, (IMM_O(operand3) >> 0) & 1))); il.AddInstruction(il.Goto(done)); il.MarkLabel(done); } break; case ARM64_CMP: il.AddInstruction(il.Sub(REGSZ_O(operand1), ILREG_O(operand1), ReadILOperand(il, operand2, REGSZ_O(operand1)), SETFLAGS)); break; case ARM64_CCMP: { LowLevelILLabel trueCode, falseCode, done; il.AddInstruction(il.If(GetCondition(il, operand4.cond), trueCode, falseCode)); il.MarkLabel(trueCode); il.AddInstruction(il.Sub(REGSZ_O(operand1), ILREG_O(operand1), ReadILOperand(il, operand2, REGSZ_O(operand1)), SETFLAGS)); il.AddInstruction(il.Goto(done)); il.MarkLabel(falseCode); il.AddInstruction(il.SetFlag(IL_FLAG_N, il.Const(0, (IMM_O(operand3) >> 3) & 1))); il.AddInstruction(il.SetFlag(IL_FLAG_Z, il.Const(0, (IMM_O(operand3) >> 2) & 1))); il.AddInstruction(il.SetFlag(IL_FLAG_C, il.Const(0, (IMM_O(operand3) >> 1) & 1))); il.AddInstruction(il.SetFlag(IL_FLAG_V, il.Const(0, (IMM_O(operand3) >> 0) & 1))); il.AddInstruction(il.Goto(done)); il.MarkLabel(done); } break; case ARM64_CLREX: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_CLREX, {})); break; case ARM64_CSEL: case ARM64_FCSEL: GenIfElse(il, GetCondition(il, operand4.cond), ILSETREG_O(operand1, ILREG_O(operand2)), ILSETREG_O(operand1, ILREG_O(operand3))); break; case ARM64_CSINC: GenIfElse(il, GetCondition(il, operand4.cond), ILSETREG_O(operand1, ILREG_O(operand2)), ILSETREG_O(operand1, ILADDREG_O(operand3, il.Const(REGSZ_O(operand1), 1)))); break; case ARM64_CSINV: GenIfElse(il, GetCondition(il, operand4.cond), ILSETREG_O(operand1, ILREG_O(operand2)), ILSETREG_O(operand1, il.Not(REGSZ_O(operand1), ILREG_O(operand3)))); break; case ARM64_CSNEG: GenIfElse(il, GetCondition(il, operand4.cond), ILSETREG_O(operand1, ILREG_O(operand2)), ILSETREG_O(operand1, il.Neg(REGSZ_O(operand1), ILREG_O(operand3)))); break; case ARM64_CSET: GenIfElse(il, GetCondition(il, operand2.cond), ILSETREG_O(operand1, il.Const(REGSZ_O(operand1), 1)), ILSETREG_O(operand1, il.Const(REGSZ_O(operand1), 0))); break; case ARM64_CSETM: GenIfElse(il, GetCondition(il, operand2.cond), ILSETREG_O(operand1, il.Const(REGSZ_O(operand1), -1)), ILSETREG_O(operand1, il.Const(REGSZ_O(operand1), 0))); break; case ARM64_CINC: GenIfElse(il, GetCondition(il, operand3.cond), ILSETREG_O(operand1, ILADDREG_O(operand2, il.Const(REGSZ_O(operand1), 1))), ILSETREG_O(operand1, ILREG_O(operand2))); break; case ARM64_CINV: GenIfElse(il, GetCondition(il, operand3.cond), ILSETREG_O(operand1, il.Not(REGSZ_O(operand1), ILREG_O(operand2))), ILSETREG_O(operand1, ILREG_O(operand2))); break; case ARM64_CNEG: GenIfElse(il, GetCondition(il, operand3.cond), ILSETREG_O(operand1, il.Neg(REGSZ_O(operand1), ILREG_O(operand2))), ILSETREG_O(operand1, ILREG_O(operand2))); break; case ARM64_CLZ: il.AddInstruction(il.Intrinsic( {RegisterOrFlag::Register(REG_O(operand1))}, ARM64_INTRIN_CLZ, {ILREG_O(operand2)})); break; case ARM64_DC: il.AddInstruction( il.Intrinsic({}, ARM64_INTRIN_DC, {ILREG_O(operand2)})); /* operand1 is <dc_op> */ break; case ARM64_DMB: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_DMB, {})); break; case ARM64_DSB: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_DSB, {})); break; case ARM64_EON: il.AddInstruction(ILSETREG_O( operand1, il.Xor(REGSZ_O(operand1), ILREG_O(operand2), il.Not(REGSZ_O(operand1), ReadILOperand(il, operand3, REGSZ_O(operand1)))))); break; case ARM64_EOR: il.AddInstruction(ILSETREG_O(operand1, il.Xor(REGSZ_O(operand1), ILREG_O(operand2), ReadILOperand(il, operand3, REGSZ_O(operand1))))); break; case ARM64_ESB: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_ESB, {})); break; case ARM64_EXTR: il.AddInstruction( ILSETREG_O(operand1, il.LogicalShiftRight(REGSZ_O(operand1) * 2, il.Or(REGSZ_O(operand1) * 2, il.ShiftLeft(REGSZ_O(operand1) * 2, ILREG_O(operand2), il.Const(1, REGSZ_O(operand1) * 8)), ILREG_O(operand3)), il.Const(1, IMM_O(operand4))))); break; case ARM64_FADD: switch (instr.encoding) { case ENC_FADD_H_FLOATDP2: case ENC_FADD_S_FLOATDP2: case ENC_FADD_D_FLOATDP2: il.AddInstruction(ILSETREG_O( operand1, il.FloatAdd(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3)))); break; case ENC_FADD_ASIMDSAME_ONLY: case ENC_FADD_ASIMDSAMEFP16_ONLY: { Register srcs[16], dsts[16]; int dst_n = unpack_vector(operand1, dsts); int src_n = unpack_vector(operand2, srcs); if ((dst_n != src_n) || dst_n == 0) ABORT_LIFT; int rsize = get_register_size(dsts[0]); for (int i = 0; i < dst_n; ++i) il.AddInstruction(il.FloatAdd(rsize, ILREG(dsts[i]), ILREG(srcs[i]))); } break; default: il.AddInstruction(il.Unimplemented()); } break; case ARM64_FCCMP: case ARM64_FCCMPE: { LowLevelILLabel trueCode, falseCode, done; il.AddInstruction(il.If(GetCondition(il, operand4.cond), trueCode, falseCode)); il.MarkLabel(trueCode); il.AddInstruction(il.FloatSub(REGSZ_O(operand1), ILREG_O(operand1), ReadILOperand(il, operand2, REGSZ_O(operand1)), SETFLAGS)); il.AddInstruction(il.Goto(done)); il.MarkLabel(falseCode); il.AddInstruction(il.SetFlag(IL_FLAG_N, il.Const(0, (IMM_O(operand3) >> 3) & 1))); il.AddInstruction(il.SetFlag(IL_FLAG_Z, il.Const(0, (IMM_O(operand3) >> 2) & 1))); il.AddInstruction(il.SetFlag(IL_FLAG_C, il.Const(0, (IMM_O(operand3) >> 1) & 1))); il.AddInstruction(il.SetFlag(IL_FLAG_V, il.Const(0, (IMM_O(operand3) >> 0) & 1))); il.AddInstruction(il.Goto(done)); il.MarkLabel(done); } break; case ARM64_FCMP: case ARM64_FCMPE: il.AddInstruction(il.FloatSub(REGSZ_O(operand1), ILREG_O(operand1), ReadILOperand(il, operand2, REGSZ_O(operand1)), SETFLAGS)); break; case ARM64_FSUB: switch (instr.encoding) { case ENC_FSUB_H_FLOATDP2: case ENC_FSUB_S_FLOATDP2: case ENC_FSUB_D_FLOATDP2: il.AddInstruction(ILSETREG_O( operand1, il.FloatSub(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3)))); break; case ENC_FSUB_ASIMDSAME_ONLY: case ENC_FSUB_ASIMDSAMEFP16_ONLY: { Register srcs[16], dsts[16]; int dst_n = unpack_vector(operand1, dsts); int src_n = unpack_vector(operand2, srcs); if ((dst_n != src_n) || dst_n == 0) ABORT_LIFT; int rsize = get_register_size(dsts[0]); for (int i = 0; i < dst_n; ++i) il.AddInstruction(il.FloatSub(rsize, ILREG(dsts[i]), ILREG(srcs[i]))); } break; default: il.AddInstruction(il.Unimplemented()); } break; case ARM64_FCVT: { int float_sz = 0; switch (instr.encoding) { /* non-SVE is straight register-to-register */ case ENC_FCVT_HS_FLOATDP1: // convert to half (2-byte) case ENC_FCVT_HD_FLOATDP1: float_sz = 2; case ENC_FCVT_SH_FLOATDP1: // convert to single (4-byte) case ENC_FCVT_SD_FLOATDP1: if (!float_sz) float_sz = 4; case ENC_FCVT_DH_FLOATDP1: // convert to double (8-byte) case ENC_FCVT_DS_FLOATDP1: if (!float_sz) float_sz = 8; il.AddInstruction(ILSETREG_O(operand1, GetFloat(il, operand2, float_sz))); break; /* future: support SVE versions with predicated execution and z register file */ default: ABORT_LIFT; } break; } case ARM64_FDIV: switch (instr.encoding) { case ENC_FDIV_H_FLOATDP2: case ENC_FDIV_S_FLOATDP2: case ENC_FDIV_D_FLOATDP2: il.AddInstruction(ILSETREG_O( operand1, il.FloatDiv(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3)))); break; default: il.AddInstruction(il.Unimplemented()); } break; case ARM64_FMOV: switch (instr.encoding) { case ENC_FMOV_64VX_FLOAT2INT: il.AddInstruction(ILSETREG_O(operand1, il.FloatToInt(REGSZ_O(operand1), ILREG(vector_reg_minimize(instr.operands[1]))))); break; case ENC_FMOV_V64I_FLOAT2INT: { Register minreg = vector_reg_minimize(instr.operands[0]); il.AddInstruction(il.SetRegister(get_register_size(minreg), minreg, il.FloatToInt(REGSZ_O(operand1), ILREG_O(instr.operands[1])))); break; } case ENC_FMOV_32H_FLOAT2INT: case ENC_FMOV_32S_FLOAT2INT: case ENC_FMOV_64H_FLOAT2INT: case ENC_FMOV_64D_FLOAT2INT: case ENC_FMOV_D64_FLOAT2INT: case ENC_FMOV_H32_FLOAT2INT: case ENC_FMOV_H64_FLOAT2INT: case ENC_FMOV_S32_FLOAT2INT: il.AddInstruction( ILSETREG_O(operand1, il.FloatToInt(REGSZ_O(operand1), ILREG_O(instr.operands[1])))); break; case ENC_FMOV_H_FLOATIMM: case ENC_FMOV_S_FLOATIMM: case ENC_FMOV_D_FLOATIMM: { int float_sz = 2; if (instr.encoding == ENC_FMOV_S_FLOATIMM) float_sz = 4; if (instr.encoding == ENC_FMOV_D_FLOATIMM) float_sz = 8; il.AddInstruction(ILSETREG_O(operand1, GetFloat(il, operand2, float_sz))); break; } case ENC_FMOV_H_FLOATDP1: case ENC_FMOV_S_FLOATDP1: case ENC_FMOV_D_FLOATDP1: il.AddInstruction(ILSETREG_O(operand1, ILREG_O(operand2))); break; case ENC_FMOV_ASIMDIMM_D2_D: case ENC_FMOV_ASIMDIMM_H_H: case ENC_FMOV_ASIMDIMM_S_S: { int float_sz = 2; if (instr.encoding == ENC_FMOV_ASIMDIMM_S_S) float_sz = 4; if (instr.encoding == ENC_FMOV_ASIMDIMM_D2_D) float_sz = 8; Register regs[16]; int dst_n = unpack_vector(operand1, regs); for (int i = 0; i < dst_n; ++i) il.AddInstruction(ILSETREG(regs[i], GetFloat(il, operand2, float_sz))); break; } default: il.AddInstruction(il.Unimplemented()); } break; case ARM64_FMUL: switch (instr.encoding) { case ENC_FMUL_H_FLOATDP2: case ENC_FMUL_S_FLOATDP2: case ENC_FMUL_D_FLOATDP2: il.AddInstruction(ILSETREG_O( operand1, il.FloatMult(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3)))); break; default: il.AddInstruction(il.Unimplemented()); } break; case ARM64_ERET: case ARM64_ERETAA: case ARM64_ERETAB: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_ERET, {})); il.AddInstruction(il.Trap(0)); return false; case ARM64_ISB: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_ISB, {})); break; case ARM64_LDAR: case ARM64_LDAXR: LoadStoreOperand(il, true, instr.operands[0], instr.operands[1], 0); break; case ARM64_LDARB: case ARM64_LDAXRB: LoadStoreOperandSize(il, true, false, 1, instr.operands[0], instr.operands[1]); break; case ARM64_LDARH: case ARM64_LDAXRH: LoadStoreOperandSize(il, true, false, 2, instr.operands[0], instr.operands[1]); break; case ARM64_LDP: case ARM64_LDNP: LoadStoreOperandPair(il, true, instr.operands[0], instr.operands[1], instr.operands[2]); break; case ARM64_LDR: case ARM64_LDUR: case ARM64_LDRAA: case ARM64_LDRAB: LoadStoreOperand(il, true, instr.operands[0], instr.operands[1], 0); break; case ARM64_LDRB: case ARM64_LDURB: LoadStoreOperandSize(il, true, false, 1, instr.operands[0], instr.operands[1]); break; case ARM64_LDRH: case ARM64_LDURH: LoadStoreOperandSize(il, true, false, 2, instr.operands[0], instr.operands[1]); break; case ARM64_LDRSB: case ARM64_LDURSB: LoadStoreOperandSize(il, true, true, 1, instr.operands[0], instr.operands[1]); break; case ARM64_LDRSH: case ARM64_LDURSH: LoadStoreOperandSize(il, true, true, 2, instr.operands[0], instr.operands[1]); break; case ARM64_LDRSW: case ARM64_LDURSW: LoadStoreOperandSize(il, true, true, 4, instr.operands[0], instr.operands[1]); break; case ARM64_LD1: LoadStoreVector(il, true, instr.operands[0], instr.operands[1]); break; case ARM64_LDADD: case ARM64_LDADDA: case ARM64_LDADDL: case ARM64_LDADDAL: LoadStoreOperand(il, true, operand2, operand3, 0); il.AddInstruction(il.Store(REGSZ_O(operand3), ILREG_O(operand3), il.Add(REGSZ_O(operand1), ILREG_O(operand1), ILREG_O(operand2)))); break; case ARM64_LDADDB: case ARM64_LDADDAB: case ARM64_LDADDLB: case ARM64_LDADDALB: LoadStoreOperand(il, true, operand2, operand3, 1); il.AddInstruction(il.Store(REGSZ_O(operand3), ILREG_O(operand3), il.Add(1, il.LowPart(1, ILREG_O(operand1)), il.LowPart(1, ILREG_O(operand2))))); break; case ARM64_LDADDH: case ARM64_LDADDAH: case ARM64_LDADDLH: case ARM64_LDADDALH: LoadStoreOperand(il, true, operand2, operand3, 2); il.AddInstruction(il.Store(REGSZ_O(operand3), ILREG_O(operand3), il.Add(2, il.LowPart(2, ILREG_O(operand1)), il.LowPart(2, ILREG_O(operand2))))); break; case ARM64_LSL: il.AddInstruction(ILSETREG_O(operand1, il.ShiftLeft(REGSZ_O(operand2), ILREG_O(operand2), ReadILOperand(il, operand3, REGSZ_O(operand2))))); break; case ARM64_LSR: il.AddInstruction( ILSETREG_O(operand1, il.LogicalShiftRight(REGSZ_O(operand2), ILREG_O(operand2), ReadILOperand(il, operand3, REGSZ_O(operand2))))); break; case ARM64_MOV: { Register regs[16]; int n = unpack_vector(operand1, regs); if (n == 1) { il.AddInstruction(ILSETREG(regs[0], ReadILOperand(il, operand2, get_register_size(regs[0])))); } else { Register cregs[2]; if (consolidate_vector(operand1, operand2, cregs)) il.AddInstruction(ILSETREG(cregs[0], ILREG(cregs[1]))); else ABORT_LIFT; } break; } case ARM64_MOVI: { Register regs[16]; int n = unpack_vector(operand1, regs); for (int i = 0; i < n; ++i) il.AddInstruction(ILSETREG(regs[i], ILCONST_O(get_register_size(regs[i]), operand2))); break; } case ARM64_MVN: il.AddInstruction(ILSETREG_O( operand1, il.Not(REGSZ_O(operand1), ReadILOperand(il, operand2, REGSZ_O(operand1))))); break; case ARM64_MOVK: il.AddInstruction(ILSETREG_O( operand1, il.Or(REGSZ_O(operand1), ILREG_O(operand1), il.Const(REGSZ_O(operand1), IMM_O(operand2) << operand2.shiftValue)))); break; case ARM64_MOVZ: il.AddInstruction( ILSETREG_O(operand1, il.Const(REGSZ_O(operand1), IMM_O(operand2) << operand2.shiftValue))); break; case ARM64_MUL: il.AddInstruction( ILSETREG_O(operand1, il.Mult(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3)))); break; case ARM64_MADD: il.AddInstruction(ILSETREG_O(operand1, ILADDREG_O(operand4, il.Mult(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3))))); break; case ARM64_MRS: { ExprId reg = ILREG_O(operand2); const char* name = get_system_register_name((SystemReg)operand2.sysreg); if (strlen(name) == 0) { LogWarn("Unknown system register %d @ 0x%" PRIx64 ": S%d_%d_c%d_c%d_%d, using generic system register instead\n", operand2.sysreg, addr, operand2.implspec[0], operand2.implspec[1], operand2.implspec[2], operand2.implspec[3], operand2.implspec[4]); reg = il.Register(8, FAKEREG_SYSREG_UNKNOWN); } il.AddInstruction( il.Intrinsic({RegisterOrFlag::Register(REG_O(operand1))}, ARM64_INTRIN_MRS, {reg})); break; } case ARM64_MSUB: il.AddInstruction(ILSETREG_O( operand1, il.Sub(REGSZ_O(operand1), ILREG_O(operand4), il.Mult(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3))))); break; case ARM64_MNEG: il.AddInstruction(ILSETREG_O( operand1, il.Sub(REGSZ_O(operand1), il.Const(8, 0), il.Mult(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3))))); break; case ARM64_MSR: { uint32_t dst = operand1.sysreg; const char* name = get_system_register_name((SystemReg)dst); if (strlen(name) == 0) { LogWarn("Unknown system register %d @ 0x%" PRIx64 ": S%d_%d_c%d_c%d_%d, using generic system register instead\n", dst, addr, operand1.implspec[0], operand1.implspec[1], operand1.implspec[2], operand1.implspec[3], operand1.implspec[4]); dst = FAKEREG_SYSREG_UNKNOWN; } switch (operand2.operandClass) { case IMM32: il.AddInstruction(il.Intrinsic( {RegisterOrFlag::Register(dst)}, ARM64_INTRIN_MSR, {il.Const(4, IMM_O(operand2))})); break; case REG: il.AddInstruction( il.Intrinsic({RegisterOrFlag::Register(dst)}, ARM64_INTRIN_MSR, {ILREG_O(operand2)})); break; default: LogError("unknown MSR operand class: %x\n", operand2.operandClass); break; } break; } case ARM64_NEG: case ARM64_NEGS: il.AddInstruction(ILSETREG_O( operand1, il.Neg(REGSZ_O(operand1), ReadILOperand(il, instr.operands[1], REGSZ_O(operand1)), SETFLAGS))); break; case ARM64_NOP: il.AddInstruction(il.Nop()); break; case ARM64_AUTDA: case ARM64_AUTDB: case ARM64_AUTIA: case ARM64_AUTIB: case ARM64_PACDA: case ARM64_PACDB: case ARM64_PACIA: case ARM64_PACIB: // <Xd> is address, <Xn> is modifier il.AddInstruction(il.Intrinsic({RegisterOrFlag::Register(REG_O(operand1))}, operation_to_intrinsic(instr.operation), {ILREG_O(operand2)})); break; case ARM64_PACGA: // <Xd> is address, <Xn>, <Xm> are modifiers, keys il.AddInstruction(il.Intrinsic({RegisterOrFlag::Register(REG_O(operand1))}, operation_to_intrinsic(instr.operation), {ILREG_O(operand2), ILREG_O(operand3)})); break; case ARM64_AUTIB1716: case ARM64_PACIA1716: case ARM64_PACIB1716: // x17 is address, x16 is modifier il.AddInstruction(il.Intrinsic({RegisterOrFlag::Register(REG_X17)}, operation_to_intrinsic(instr.operation), {il.Register(8, REG_X16)})); break; case ARM64_AUTDZA: case ARM64_AUTDZB: case ARM64_AUTIZA: case ARM64_AUTIZB: case ARM64_PACDZA: case ARM64_PACDZB: case ARM64_PACIZA: case ARM64_PACIZB: case ARM64_XPACI: case ARM64_XPACD: // <Xd> is address, modifier is omitted or 0 il.AddInstruction(il.Intrinsic( {RegisterOrFlag::Register(REG_O(operand1))}, operation_to_intrinsic(instr.operation), {})); break; case ARM64_AUTIBZ: case ARM64_PACIAZ: case ARM64_PACIBZ: case ARM64_XPACLRI: // x30 is address, modifier is omitted or 0 il.AddInstruction(il.Intrinsic( {RegisterOrFlag::Register(REG_X30)}, operation_to_intrinsic(instr.operation), {})); break; case ARM64_AUTIBSP: case ARM64_PACIASP: case ARM64_PACIBSP: // x30 is address, sp is modifier il.AddInstruction(il.Intrinsic({RegisterOrFlag::Register(REG_X30)}, operation_to_intrinsic(instr.operation), {il.Register(8, REG_SP)})); break; case ARM64_PRFUM: case ARM64_PRFM: // TODO use the PRFM types when we have a better option than defining 18 different intrinsics to // account for: // - 3 types {PLD, PLI, PST} // - 3 targets {L1, L2, L3} // - 2 policies {KEEP, STM} il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_PRFM, {ReadILOperand(il, operand2, 8)})); break; case ARM64_ORN: il.AddInstruction(ILSETREG_O( operand1, il.Or(REGSZ_O(operand1), ILREG_O(operand2), il.Not(REGSZ_O(operand1), ReadILOperand(il, operand3, REGSZ_O(operand1)))))); break; case ARM64_ORR: case ARM64_ORRS: il.AddInstruction( ILSETREG_O(operand1, il.Or(REGSZ_O(operand1), ILREG_O(operand2), ReadILOperand(il, operand3, REGSZ_O(operand1)), SETFLAGS))); break; case ARM64_PSB: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_PSBCSYNC, {})); break; case ARM64_RET: case ARM64_RETAA: case ARM64_RETAB: { ExprId reg = (operand1.operandClass == REG) ? ILREG_O(operand1) : il.Register(8, REG_X30); il.AddInstruction(il.Return(reg)); break; } case ARM64_REVB: // SVE only case ARM64_REVH: case ARM64_REVW: il.AddInstruction(il.Unimplemented()); break; case ARM64_REV16: case ARM64_REV32: case ARM64_REV64: case ARM64_REV: if (IS_SVE_O(operand1)) { il.AddInstruction(il.Unimplemented()); break; } // if LLIL_BSWAP ever gets added, replace il.AddInstruction(il.Intrinsic( {RegisterOrFlag::Register(REG_O(operand1))}, ARM64_INTRIN_REV, {ILREG_O(operand2)})); break; case ARM64_RBIT: il.AddInstruction(il.Intrinsic( {RegisterOrFlag::Register(REG_O(operand1))}, ARM64_INTRIN_RBIT, {ILREG_O(operand2)})); break; case ARM64_ROR: il.AddInstruction(ILSETREG_O(operand1, il.RotateRight(REGSZ_O(operand2), ILREG_O(operand2), ReadILOperand(il, operand3, REGSZ_O(operand2))))); break; case ARM64_SBC: case ARM64_SBCS: il.AddInstruction(ILSETREG_O(operand1, il.SubBorrow(REGSZ_O(operand1), ILREG_O(operand2), ReadILOperand(il, operand3, REGSZ_O(operand1)), il.Not(0, il.Flag(IL_FLAG_C)), SETFLAGS))); break; case ARM64_SBFIZ: il.AddInstruction(ILSETREG_O( operand1, il.ArithShiftRight(REGSZ_O(operand1), il.ShiftLeft(REGSZ_O(operand1), ExtractBits(il, operand2, IMM_O(operand4), 0), il.Const(1, (REGSZ_O(operand1) * 8) - IMM_O(operand4))), il.Const(1, (REGSZ_O(operand1) * 8) - IMM_O(operand3) - IMM_O(operand4))))); break; case ARM64_SBFX: il.AddInstruction(ILSETREG_O( operand1, il.ArithShiftRight(REGSZ_O(operand1), il.ShiftLeft(REGSZ_O(operand1), ExtractBits(il, operand2, IMM_O(operand4), IMM_O(operand3)), il.Const(1, (REGSZ_O(operand1) * 8) - IMM_O(operand4) - IMM_O(operand3))), il.Const(1, (REGSZ_O(operand1) * 8) - IMM_O(operand4))))); break; case ARM64_SDIV: il.AddInstruction(ILSETREG_O( operand1, il.DivSigned(REGSZ_O(operand2), ILREG_O(operand2), ILREG_O(operand3)))); break; case ARM64_SEV: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_SEV, {})); break; case ARM64_SEVL: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_SEVL, {})); break; case ARM64_SHL: { Register srcs[16], dsts[16]; int dst_n = unpack_vector(operand1, dsts); int src_n = unpack_vector(operand2, srcs); if ((dst_n != src_n) || dst_n == 0) ABORT_LIFT; int rsize = get_register_size(dsts[0]); for (int i = 0; i < dst_n; ++i) { il.AddInstruction(il.SetRegister(rsize, dsts[i], il.ShiftLeft(rsize, il.Register(rsize, srcs[i]), il.Const(0, IMM_O(operand3))))); } break; } case ARM64_ST1: LoadStoreVector(il, false, instr.operands[0], instr.operands[1]); break; case ARM64_STP: case ARM64_STNP: LoadStoreOperandPair(il, false, instr.operands[0], instr.operands[1], instr.operands[2]); break; case ARM64_STR: case ARM64_STLR: case ARM64_STUR: LoadStoreOperand(il, false, instr.operands[0], instr.operands[1], 0); break; case ARM64_STRB: case ARM64_STLRB: case ARM64_STURB: LoadStoreOperandSize(il, false, false, 1, instr.operands[0], instr.operands[1]); break; case ARM64_STRH: case ARM64_STLRH: case ARM64_STURH: LoadStoreOperandSize(il, false, false, 2, instr.operands[0], instr.operands[1]); break; case ARM64_SUB: case ARM64_SUBS: il.AddInstruction(ILSETREG_O( operand1, il.Sub(REGSZ_O(operand1), ILREG_O(operand2), ReadILOperand(il, instr.operands[2], REGSZ_O(operand1)), SETFLAGS))); break; case ARM64_SVC: case ARM64_HVC: case ARM64_SMC: { /* b31,b30==xx of fake register mark transition to ELxx */ uint32_t el_mark = 0; if (instr.operation == ARM64_SVC) el_mark = 0x40000000; else if (instr.operation == ARM64_HVC) el_mark = 0x80000000; else if (instr.operation == ARM64_SMC) el_mark = 0xC0000000; /* b15..b0 of fake register still holds syscall number */ il.AddInstruction( il.SetRegister(4, FAKEREG_SYSCALL_INFO, il.Const(4, el_mark | IMM_O(operand1)))); il.AddInstruction(il.SystemCall()); break; } case ARM64_SWP: /* word (4) or doubleword (8) */ case ARM64_SWPA: case ARM64_SWPL: case ARM64_SWPAL: LoadStoreOperand(il, true, operand2, operand3, 0); LoadStoreOperand(il, false, operand1, operand3, 0); break; case ARM64_SWPB: /* byte (1) */ case ARM64_SWPAB: case ARM64_SWPLB: case ARM64_SWPALB: LoadStoreOperand(il, true, operand2, operand3, 1); il.AddInstruction(il.Store(1, ILREG_O(operand3), il.LowPart(1, ILREG_O(operand1)))); break; case ARM64_SWPH: /* half-word (2) */ case ARM64_SWPAH: case ARM64_SWPLH: case ARM64_SWPALH: LoadStoreOperand(il, true, operand2, operand3, 2); il.AddInstruction(il.Store(2, ILREG_O(operand3), il.LowPart(2, ILREG_O(operand1)))); break; case ARM64_SXTB: il.AddInstruction( ILSETREG_O(operand1, ExtractRegister(il, operand2, 0, 1, true, REGSZ_O(operand1)))); break; case ARM64_SXTH: il.AddInstruction( ILSETREG_O(operand1, ExtractRegister(il, operand2, 0, 2, true, REGSZ_O(operand1)))); break; case ARM64_SXTW: il.AddInstruction( ILSETREG_O(operand1, ExtractRegister(il, operand2, 0, 4, true, REGSZ_O(operand1)))); break; case ARM64_TBNZ: ConditionalJump(arch, il, il.CompareNotEqual(REGSZ_O(operand1), ExtractBit(il, operand1, IMM_O(operand2)), il.Const(REGSZ_O(operand1), 0)), addrSize, IMM_O(operand3), addr + 4); return false; case ARM64_TBZ: ConditionalJump(arch, il, il.CompareEqual(REGSZ_O(operand1), ExtractBit(il, operand1, IMM_O(operand2)), il.Const(REGSZ_O(operand1), 0)), addrSize, IMM_O(operand3), addr + 4); return false; case ARM64_TST: il.AddInstruction(il.And(REGSZ_O(operand1), ILREG_O(operand1), ReadILOperand(il, operand2, REGSZ_O(operand1)), SETFLAGS)); break; case ARM64_UMADDL: il.AddInstruction(ILSETREG_O(operand1, il.Add(REGSZ_O(operand1), ILREG_O(operand4), il.MultDoublePrecUnsigned(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3))))); break; case ARM64_UMULL: il.AddInstruction(ILSETREG_O(operand1, il.MultDoublePrecUnsigned(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3)))); break; case ARM64_UMSUBL: il.AddInstruction(ILSETREG_O(operand1, il.Sub(REGSZ_O(operand1), ILREG_O(operand4), il.MultDoublePrecUnsigned(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3))))); break; case ARM64_UMNEGL: il.AddInstruction(ILSETREG_O(operand1, il.Sub(REGSZ_O(operand1), il.Const(8, 0), il.MultDoublePrecUnsigned(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3))))); break; case ARM64_UXTL: case ARM64_UXTL2: { Register srcs[16], dsts[16]; int dst_n = unpack_vector(operand1, dsts); int src_n = unpack_vector(operand2, srcs); if (src_n == 0 || dst_n == 0) ABORT_LIFT; if (instr.operation == ARM64_UXTL && (src_n != dst_n)) ABORT_LIFT; if (instr.operation == ARM64_UXTL2 && (src_n != 2 * dst_n)) ABORT_LIFT; for (int i = 0; i < dst_n; ++i) { if (instr.operation == ARM64_UXTL) il.AddInstruction(ILSETREG(dsts[i], ILREG(srcs[i]))); else il.AddInstruction(ILSETREG(dsts[i], ILREG(srcs[i + src_n / 2]))); } break; } case ARM64_SMADDL: il.AddInstruction(ILSETREG_O(operand1, il.Add(REGSZ_O(operand1), ILREG_O(operand4), il.MultDoublePrecSigned(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3))))); break; case ARM64_USHR: { Register srcs[16], dsts[16]; int dst_n = unpack_vector(operand1, dsts); int src_n = unpack_vector(operand2, srcs); if ((dst_n != src_n) || dst_n == 0) ABORT_LIFT; int rsize = get_register_size(dsts[0]); for (int i = 0; i < dst_n; ++i) { il.AddInstruction(il.SetRegister(rsize, dsts[i], il.LogicalShiftRight(rsize, il.Register(rsize, srcs[i]), il.Const(0, IMM_O(operand3))))); } break; } case ARM64_SMULL: il.AddInstruction(ILSETREG_O(operand1, il.MultDoublePrecSigned(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3)))); break; case ARM64_SMSUBL: il.AddInstruction(ILSETREG_O(operand1, il.Sub(REGSZ_O(operand1), ILREG_O(operand4), il.MultDoublePrecSigned(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3))))); break; case ARM64_SMNEGL: il.AddInstruction(ILSETREG_O(operand1, il.Sub(REGSZ_O(operand1), il.Const(8, 0), il.MultDoublePrecSigned(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3))))); break; case ARM64_UMULH: il.AddInstruction(ILSETREG_O(operand1, il.LogicalShiftRight(16, il.MultDoublePrecUnsigned(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3)), il.Const(1, 8)))); break; case ARM64_SMULH: il.AddInstruction(ILSETREG_O(operand1, il.LogicalShiftRight(16, il.MultDoublePrecSigned(REGSZ_O(operand1), ILREG_O(operand2), ILREG_O(operand3)), il.Const(1, 8)))); break; case ARM64_UDIV: il.AddInstruction(ILSETREG_O( operand1, il.DivUnsigned(REGSZ_O(operand2), ILREG_O(operand2), ILREG_O(operand3)))); break; case ARM64_UBFIZ: il.AddInstruction( ILSETREG_O(operand1, il.ZeroExtend(REGSZ_O(operand1), il.ShiftLeft(REGSZ_O(operand2), il.And(REGSZ_O(operand2), ILREG_O(operand2), il.Const(REGSZ_O(operand2), (1LL << IMM_O(operand4)) - 1)), il.Const(1, IMM_O(operand3)))))); break; case ARM64_UBFX: { // ubfx <dst>, <src>, <src_lsb>, <src_len> int src_lsb = IMM_O(operand3); int src_len = IMM_O(operand4); if (src_lsb == 0 && (src_len == 8 || src_len == 16 || src_len == 32 || src_len == 64)) { il.AddInstruction(ILSETREG_O(operand1, il.LowPart(src_len / 8, ILREG_O(operand2)))); } else { il.AddInstruction(ILSETREG_O( operand1, il.ZeroExtend(REGSZ_O(operand1), il.And(REGSZ_O(operand2), il.LogicalShiftRight( REGSZ_O(operand2), ILREG_O(operand2), il.Const(1, IMM_O(operand3))), il.Const(REGSZ_O(operand2), (1LL << IMM_O(operand4)) - 1))))); } break; } case ARM64_UXTB: il.AddInstruction( ILSETREG_O(operand1, ExtractRegister(il, operand2, 0, 1, false, REGSZ_O(operand1)))); break; case ARM64_UXTH: il.AddInstruction( ILSETREG_O(operand1, ExtractRegister(il, operand2, 0, 2, false, REGSZ_O(operand1)))); break; case ARM64_WFE: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_WFE, {})); break; case ARM64_WFI: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_WFI, {})); break; case ARM64_BRK: il.AddInstruction( il.Trap(IMM_O(operand1))); // FIXME Breakpoint may need a parameter (IMM_O(operand1))); return false; case ARM64_DUP: { if (instr.encoding != ENC_DUP_ASIMDINS_DR_R) ABORT_LIFT; Register regs[16]; int regs_n = unpack_vector(operand1, regs); if (regs_n <= 0) ABORT_LIFT; int lane_sz = REGSZ(regs[0]); for (int i = 0; i < regs_n; ++i) il.AddInstruction(ILSETREG(regs[i], ExtractRegister(il, operand2, 0, lane_sz, 0, lane_sz))); } break; case ARM64_DGH: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_HINT_DGH, {})); break; case ARM64_TSB: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_HINT_TSB, {})); break; case ARM64_CSDB: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_HINT_CSDB, {})); break; case ARM64_HINT: if ((IMM_O(operand1) & ~0b110) == 0b100000) il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_HINT_BTI, {})); else LogWarn("unknown hint operand: 0x%" PRIx64 "\n", IMM_O(operand1)); break; case ARM64_HLT: il.AddInstruction(il.Trap(IMM_O(operand1))); return false; case ARM64_YIELD: il.AddInstruction(il.Intrinsic({}, ARM64_INTRIN_YIELD, {})); break; default: break; } if (il.GetInstructionCount() > n_instrs_before) return true; NeonGetLowLevelILForInstruction(arch, addr, il, instr, addrSize); if (il.GetInstructionCount() > n_instrs_before) return true; il.AddInstruction(il.Unimplemented()); return true; }
32.713471
99
0.698608
jevinskie
e6dc53a9c9792921fb33953893da983f745e749e
610
cpp
C++
src/base/network/Hook.cpp
svalat/iocatcher
4845e20d938c816f6ca5ee8d3308aa9a0e0abaff
[ "Apache-2.0" ]
2
2022-01-28T16:03:14.000Z
2022-02-18T07:35:22.000Z
src/base/network/Hook.cpp
svalat/iocatcher
4845e20d938c816f6ca5ee8d3308aa9a0e0abaff
[ "Apache-2.0" ]
2
2022-02-10T10:22:02.000Z
2022-02-11T18:00:47.000Z
src/base/network/Hook.cpp
svalat/iocatcher
4845e20d938c816f6ca5ee8d3308aa9a0e0abaff
[ "Apache-2.0" ]
1
2022-01-31T21:09:15.000Z
2022-01-31T21:09:15.000Z
/***************************************************** PROJECT : IO Catcher VERSION : 0.0.0-dev DATE : 10/2020 LICENSE : ???????? *****************************************************/ /****************************************************/ #include "Hook.hpp" #include "LibfabricConnection.hpp" /****************************************************/ using namespace IOC; /****************************************************/ /** * Terminate the request handling and repost the recive buffer. **/ void LibfabricClientRequest::terminate(void) { this->connection->repostReceive(*this); }
26.521739
63
0.372131
svalat
e6de82ae4e2a066e80b761b1deadf809da51b245
9,385
cpp
C++
plugins/it/src/vs_it_c.cpp
darcyg/vapoursynth-plugins
5aaf090d3523cb8c53841949f2da286688ba33bb
[ "BSD-2-Clause" ]
null
null
null
plugins/it/src/vs_it_c.cpp
darcyg/vapoursynth-plugins
5aaf090d3523cb8c53841949f2da286688ba33bb
[ "BSD-2-Clause" ]
null
null
null
plugins/it/src/vs_it_c.cpp
darcyg/vapoursynth-plugins
5aaf090d3523cb8c53841949f2da286688ba33bb
[ "BSD-2-Clause" ]
1
2020-04-06T16:52:59.000Z
2020-04-06T16:52:59.000Z
/* VS_IT Copyright(C) 2002 thejam79, 2003 minamina, 2014 msg7086 This program is free software; you can redistribute it and / or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or(at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110 - 1301, USA. */ #ifdef __C #include "vs_it.h" __forceinline unsigned char eval_iv_asm( unsigned const char * eax, unsigned const char * ebx, unsigned const char * ecx, int i) { auto a = eax[i]; auto b = ebx[i]; auto c = ecx[i]; auto ab = a > b ? a - b : b - a; auto ac = a > c ? a - c : c - a; auto bc = (b + c + 1) >> 1; auto a_bc = a > bc ? a - bc : bc - a; auto min_ab_ac = VSMIN(ab, ac); return VSMIN(a_bc, min_ab_ac); } __forceinline unsigned char _mm_subs_abs_epu8(unsigned char a, unsigned char b) { return a > b ? a - b : b - a; } void IT::EvalIV_YV12(IScriptEnvironment * env, int n, const VSFrameRef * ref, long & counter, long & counterp) { const VSFrameRef * srcC = env->GetFrame(clipFrame(n)); auto th = 40; auto th2 = 6; MakeDEmap_YV12(env, ref, 1); const int widthminus16 = (width - 16) >> 1; int sum = 0, sum2 = 0; for (int yy = 16; yy < height - 16; yy += 2) { int y; y = yy + 1; const unsigned char * pT = env->SYP(srcC, y - 1); const unsigned char * pC = env->SYP(ref, y); const unsigned char * pB = env->SYP(srcC, y + 1); const unsigned char * pT_U = env->SYP(srcC, y - 1, 1); const unsigned char * pC_U = env->SYP(ref, y, 1); const unsigned char * pB_U = env->SYP(srcC, y + 1, 1); const unsigned char * pT_V = env->SYP(srcC, y - 1, 2); const unsigned char * pC_V = env->SYP(ref, y, 2); const unsigned char * pB_V = env->SYP(srcC, y + 1, 2); const unsigned char * peT = &env->m_edgeMap[clipY(y - 1) * width]; const unsigned char * peC = &env->m_edgeMap[clipY(y) * width]; const unsigned char * peB = &env->m_edgeMap[clipY(y + 1) * width]; for (int i = 16; i < widthminus16; i++) { auto yl = eval_iv_asm(pC, pT, pB, i * 2); auto yh = eval_iv_asm(pC, pT, pB, i * 2 + 1); auto u = eval_iv_asm(pC_U, pT_U, pB_U, i); auto v = eval_iv_asm(pC_V, pT_V, pB_V, i); auto uv = VSMAX(u, v); auto mm0l = VSMAX(yl, uv); auto mm0h = VSMAX(yh, uv); // mm0 <- max(y, max(u, v)) auto peCl = peC[i * 2]; auto peCh = peC[i * 2 + 1]; auto peTl = peT[i * 2]; auto peTh = peT[i * 2 + 1]; auto peBl = peB[i * 2]; auto peBh = peB[i * 2 + 1]; auto pel = VSMAX(peTl, peBl); auto peh = VSMAX(peTh, peBh); pel = VSMAX(pel, peCl); peh = VSMAX(peh, peCh); // pe <- max(peC, peT, peB) // Saturate Subtract mm0 - pe * 2 mm0l = mm0l > pel ? mm0l - pel : 0; mm0l = mm0l > pel ? mm0l - pel : 0; mm0h = mm0h > peh ? mm0h - peh : 0; mm0h = mm0h > peh ? mm0h - peh : 0; sum += mm0l > th ? 1 : 0; sum += mm0h > th ? 1 : 0; sum2 += mm0l > th2 ? 1 : 0; sum2 += mm0h > th2 ? 1 : 0; } if (sum > m_iPThreshold) { sum = m_iPThreshold; break; } } counter = sum; counterp = sum2; env->FreeFrame(srcC); return; } __forceinline unsigned char make_de_map_asm( unsigned const char * eax, unsigned const char * ebx, unsigned const char * ecx, int i, int step, int offset) { // return abs(a - (b + c) / 2) auto a = eax[i * step + offset]; auto b = ebx[i * step + offset]; auto c = ecx[i * step + offset]; auto bc = (b + c + 1) >> 1; return _mm_subs_abs_epu8(a, bc); } void IT::MakeDEmap_YV12(IScriptEnvironment * env, const VSFrameRef * ref, int offset) { const int twidth = width >> 1; for (int yy = 0; yy < height; yy += 2) { int y = yy + offset; const unsigned char * pTT = env->SYP(ref, y - 2); const unsigned char * pC = env->SYP(ref, y); const unsigned char * pBB = env->SYP(ref, y + 2); const unsigned char * pTT_U = env->SYP(ref, y - 2, 1); const unsigned char * pC_U = env->SYP(ref, y, 1); const unsigned char * pBB_U = env->SYP(ref, y + 2, 1); const unsigned char * pTT_V = env->SYP(ref, y - 2, 2); const unsigned char * pC_V = env->SYP(ref, y, 2); const unsigned char * pBB_V = env->SYP(ref, y + 2, 2); unsigned char * pED = env->m_edgeMap + y * width; unsigned char y0, y1, u0, v0, uv; for (int i = 0; i < twidth; i++) { y0 = make_de_map_asm(pC, pTT, pBB, i, 2, 0); y1 = make_de_map_asm(pC, pTT, pBB, i, 2, 1); u0 = make_de_map_asm(pC_U, pTT_U, pBB_U, i, 1, 0); v0 = make_de_map_asm(pC_V, pTT_V, pBB_V, i, 1, 0); uv = VSMAX(u0, v0); pED[i * 2] = VSMAX(uv, y0); pED[i * 2 + 1] = VSMAX(uv, y1); } } } void IT::MakeMotionMap_YV12(IScriptEnvironment * env, int n, bool flag) { n = clipFrame(n); if (flag == false && m_frameInfo[n].diffP0 >= 0) return; const int twidth = width; const int widthminus8 = width - 8; const int widthminus16 = width - 16; int i; const VSFrameRef * srcP = env->GetFrame(clipFrame(n - 1)); const VSFrameRef * srcC = env->GetFrame(n); short bufP0[MAX_WIDTH]; unsigned char bufP1[MAX_WIDTH]; int pe0 = 0, po0 = 0, pe1 = 0, po1 = 0; for (int yy = 16; yy < height - 16; ++yy) { int y = yy; const unsigned char * pC = env->SYP(srcC, y); const unsigned char * pP = env->SYP(srcP, y); for (i = 0; i < twidth; i++) { bufP0[i] = static_cast<short>(pC[i]) - static_cast<short>(pP[i]); } for (i = 8; i < widthminus8; i++) { auto A = bufP0[i - 1]; auto B = bufP0[i]; auto C = bufP0[i + 1]; auto delta = A - B + C - B; // Abs(B) B = B >= 0 ? B : -B; // Abs(delta) delta = delta >= 0 ? delta : -delta; // Saturate Subtract (B-delta) To 8-bit bufP1[i] = VSMIN(255, VSMAX(0, B - delta)); } int tsum = 0, tsum1 = 0; for (i = 16; i < widthminus16; i++) { auto A = bufP1[i - 1]; auto B = bufP1[i + 1]; auto C = bufP1[i]; auto ABC = A + B + C; if (ABC > 36) tsum++; if (ABC > 18) tsum1++; } if ((y & 1) == 0) { pe0 += tsum; pe1 += tsum1; } else { po0 += tsum; po1 += tsum1; } } m_frameInfo[n].diffP0 = pe0; m_frameInfo[n].diffP1 = po0; m_frameInfo[n].diffS0 = pe1; m_frameInfo[n].diffS1 = po1; env->FreeFrame(srcC); env->FreeFrame(srcP); } __forceinline unsigned char make_motion_map2_asm( const unsigned char * eax, const unsigned char * ebx, int i) { return _mm_subs_abs_epu8(eax[i], ebx[i]); } void IT::MakeMotionMap2Max_YV12(IScriptEnvironment * env, int n) { const int twidth = width >> 1; const VSFrameRef * srcP = env->GetFrame(n - 1); const VSFrameRef * srcC = env->GetFrame(n); const VSFrameRef * srcN = env->GetFrame(n + 1); for (int y = 0; y < height; y++) { unsigned char * pD = env->m_motionMap4DIMax + y * width; const unsigned char * pC = env->SYP(srcC, y); const unsigned char * pP = env->SYP(srcP, y); const unsigned char * pN = env->SYP(srcN, y); const unsigned char * pC_U = env->SYP(srcC, y, 1); const unsigned char * pP_U = env->SYP(srcP, y, 1); const unsigned char * pN_U = env->SYP(srcN, y, 1); const unsigned char * pC_V = env->SYP(srcC, y, 2); const unsigned char * pP_V = env->SYP(srcP, y, 2); const unsigned char * pN_V = env->SYP(srcN, y, 2); for (int i = 0; i < twidth; i++) { ///P auto yl = make_motion_map2_asm(pC, pP, i * 2); auto yh = make_motion_map2_asm(pC, pP, i * 2 + 1); auto u = make_motion_map2_asm(pC_U, pP_U, i); auto v = make_motion_map2_asm(pC_V, pP_V, i); auto uv = VSMAX(u, v); auto pl = VSMAX(uv, yl); auto ph = VSMAX(uv, yh); ///N yl = make_motion_map2_asm(pC, pN, i * 2); yh = make_motion_map2_asm(pC, pN, i * 2 + 1); u = make_motion_map2_asm(pC_U, pN_U, i); v = make_motion_map2_asm(pC_V, pN_V, i); uv = VSMAX(u, v); auto nl = VSMAX(uv, yl); auto nh = VSMAX(uv, yh); pD[i * 2] = VSMAX(pl, nl); pD[i * 2 + 1] = VSMAX(ph, nh); } } env->FreeFrame(srcC); env->FreeFrame(srcP); env->FreeFrame(srcN); } void IT::MakeSimpleBlurMap_YV12(IScriptEnvironment * env, int n) { int twidth = width; const VSFrameRef * srcC = env->GetFrame(n); const VSFrameRef * srcR; switch (toupper(env->m_iUseFrame)) { default: case 'C': srcR = srcC; break; case 'P': srcR = env->GetFrame(n - 1); break; case 'N': srcR = env->GetFrame(n + 1); break; } const unsigned char * pT; const unsigned char * pC; const unsigned char * pB; for (int y = 0; y < height; y++) { unsigned char * pD = env->m_motionMap4DI + y * width; if (y % 2) { pT = env->SYP(srcC, y - 1); pC = env->SYP(srcR, y); pB = env->SYP(srcC, y + 1); } else { pT = env->SYP(srcR, y - 1); pC = env->SYP(srcC, y); pB = env->SYP(srcR, y + 1); } for (int i = 0; i < twidth; i++) { auto c = pC[i]; auto t = pT[i]; auto b = pB[i]; auto ct = _mm_subs_abs_epu8(c, t); auto cb = _mm_subs_abs_epu8(c, b); auto tb = _mm_subs_abs_epu8(t, b); int delta = ct; delta = VSMIN(255, delta + cb); delta = VSMAX(0, delta - tb - tb); pD[i] = static_cast<unsigned char>(delta); } } if (srcC != srcR) env->FreeFrame(srcR); env->FreeFrame(srcC); } #endif
28.525836
112
0.599467
darcyg
e6df7175e64f904976d2bdc4555fd81e363172fd
656
cpp
C++
Subiecte 2009/V16 II 5.cpp
jbara2002/Informatica_LCIB
ff9db6d7d6119ba835750cc2d408079f76b852df
[ "CC0-1.0" ]
1
2022-03-31T21:45:03.000Z
2022-03-31T21:45:03.000Z
Subiecte 2009/V16 II 5.cpp
jbara2002/Informatica_LCIB
ff9db6d7d6119ba835750cc2d408079f76b852df
[ "CC0-1.0" ]
null
null
null
Subiecte 2009/V16 II 5.cpp
jbara2002/Informatica_LCIB
ff9db6d7d6119ba835750cc2d408079f76b852df
[ "CC0-1.0" ]
null
null
null
#include <iostream> using namespace std; int main() { int a[16][16], n, i, j; cin >> n; for(i=1; i<=n; i++) { for(j=1; j<=n; j++) { if(i+j==n+1) /// Suntem pe diagonala secundara. { a[i][j] = 4; } else if(i==j) /// Suntem pe diagonala principala. { a[i][j] = 4; } else { a[i][j] = 3; } } } for(i=1; i<=n; i++) { for(j=1; j<=n; j++) { cout << a[i][j] << " "; } cout << endl; } return 0; }
15.619048
62
0.291159
jbara2002
e6e04edd1bad9f7d4a65eea3cf4ab66a324c93e7
2,971
cpp
C++
apps/ExampleMatcher/Filter/CsvSubRouteWriter.cpp
boundter/os-matcher
92d72bb1645a64bdd5230c0107a6cdda7a78cf48
[ "Apache-2.0" ]
null
null
null
apps/ExampleMatcher/Filter/CsvSubRouteWriter.cpp
boundter/os-matcher
92d72bb1645a64bdd5230c0107a6cdda7a78cf48
[ "Apache-2.0" ]
null
null
null
apps/ExampleMatcher/Filter/CsvSubRouteWriter.cpp
boundter/os-matcher
92d72bb1645a64bdd5230c0107a6cdda7a78cf48
[ "Apache-2.0" ]
null
null
null
/* * SPDX-FileCopyrightText: © 2018 Ambrosys GmbH * * SPDX-License-Identifier: Apache-2.0 */ #include "CsvSubRouteWriter.h" #include <Core/Common/Geometry/Conversion.h> #include <Core/Common/Time/Helper.h> #include <amblog/global.h> namespace Applications::ExampleMatcher::Filter { CsvSubRouteWriter::CsvSubRouteWriter(std::ostream & output) : Filter("CsvSubRouteWriter"), output_(output) { setRequirements({"RouteList", "GraphEdgeMap", "NodeMap", "TimeList", "SegmentList", "SamplingPointList"}); setOptionals({}); setFulfillments({"route written"}); } bool CsvSubRouteWriter::operator()( AppComponents::Common::Types::Routing::RouteList const & routeList, AppComponents::Common::Types::Graph::GraphEdgeMap const & graphEdgeMap, AppComponents::Common::Types::Graph::NodeMap const & nodeMap, AppComponents::Common::Types::Track::TimeList const & timeList, AppComponents::Common::Types::Street::SegmentList const & segmentList, AppComponents::Common::Types::Routing::SamplingPointList const & samplingPointList) { APP_LOG_TAG(noise, "I/O") << "Writing sub routes"; output_ << "osm_id;route;length;cost;sourceNode;targetNode;sourceSamplingPointTime;targetSamplingPointTime;sourceSamplingPointCandidateIndex;targetSamplingPointCandidateIndex;sourceSamplingPointCandidateConsideredForwards;targetSamplingPointCandidateConsideredForwards\n"; output_ << std::setprecision(14); for (auto const & route : routeList) { auto const & source = route->source; auto const & target = route->target; auto const & subRoutes = route->subRoutes; for (auto const & [edge, cost, route, length] : subRoutes) { auto streetEdge = graphEdgeMap.at(edge); auto segment = segmentList[streetEdge.streetIndex]; std::vector<Core::Common::Geometry::Point> points; std::transform(route.begin(), route.end(), std::back_inserter(points), [](const auto point) { return point; }); output_ << segment.originId << ';'; output_ << Core::Common::Geometry::toWkt(points) << ';'; output_ << length << ';'; output_ << cost << ';'; output_ << nodeMap.at(source.node) << ';'; output_ << nodeMap.at(target.node) << ';'; output_ << Core::Common::Time::toIsoString(timeList.at(samplingPointList.at(source.samplingPoint.index).trackIndex)) << ';'; output_ << Core::Common::Time::toIsoString(timeList.at(samplingPointList.at(target.samplingPoint.index).trackIndex)) << ';'; output_ << source.samplingPoint.candidate.index << ';'; output_ << target.samplingPoint.candidate.index << ';'; output_ << source.samplingPoint.candidate.consideredForwards << ';'; output_ << target.samplingPoint.candidate.consideredForwards << '\n'; } } return true; } } // namespace Applications::ExampleMatcher::Filter
45.015152
272
0.672837
boundter
e6e13e4fb4ad558e7a2c66389e0817740bdaf028
432
cpp
C++
src/format.cpp
julesser/CppND-System-Monitor
8480d73ef2bb9c70d1c4e0eba7dbb861f87c05de
[ "MIT" ]
null
null
null
src/format.cpp
julesser/CppND-System-Monitor
8480d73ef2bb9c70d1c4e0eba7dbb861f87c05de
[ "MIT" ]
null
null
null
src/format.cpp
julesser/CppND-System-Monitor
8480d73ef2bb9c70d1c4e0eba7dbb861f87c05de
[ "MIT" ]
null
null
null
#include "format.h" #include <string> using std::string; // DONE: Complete this helper function // INPUT: Long int measuring seconds // OUTPUT: HH:MM:SS string Format::ElapsedTime(long seconds) { int min = int((seconds / (60)) % 60); int sec = int(seconds % (60)); int hrs = int(min / (60 * 60)); string time = std::to_string(hrs) + ":" + std::to_string(min) + ":" + std::to_string(sec); return time; }
24
71
0.611111
julesser
e6e82a72fea08c5bea940bc545aca53d20de3d6a
66,403
cpp
C++
EndlessReachHD/Private/EndlessReachHDPawn.cpp
Soverance/EndlessReachHD
1e670fa265e78ea8c8c30d510282a39176c7215d
[ "Apache-2.0" ]
11
2017-07-25T11:57:28.000Z
2020-10-24T04:26:20.000Z
EndlessReachHD/Private/EndlessReachHDPawn.cpp
Soverance/EndlessReachHD
1e670fa265e78ea8c8c30d510282a39176c7215d
[ "Apache-2.0" ]
null
null
null
EndlessReachHD/Private/EndlessReachHDPawn.cpp
Soverance/EndlessReachHD
1e670fa265e78ea8c8c30d510282a39176c7215d
[ "Apache-2.0" ]
4
2018-03-30T10:53:09.000Z
2020-06-27T22:40:14.000Z
// © 2012 - 2019 Soverance Studios // https://soverance.com // 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 "EndlessReachHD.h" #include "EndlessReachHDPawn.h" #include "Enemies/EnemyMaster.h" #include "Environment/Asteroid.h" #include "Pickups/PickupMaster.h" #include "Pickups/Orb.h" #include "Pickups/FuelCell.h" #include "Pickups/Laser.h" #include "Pickups/BombCore.h" #include "Projectiles/Cannonball.h" #include "Projectiles/Bomb.h" #include "TimerManager.h" // Create bindings for input - these are originally declared in DefaultInput.ini // AXIS const FName AEndlessReachHDPawn::MoveForwardBinding("MoveForward"); const FName AEndlessReachHDPawn::MoveRightBinding("MoveRight"); const FName AEndlessReachHDPawn::FireForwardBinding("FireForward"); const FName AEndlessReachHDPawn::FireRightBinding("FireRight"); // ACTIONS const FName AEndlessReachHDPawn::LaserBinding("Laser"); const FName AEndlessReachHDPawn::ThrustersBinding("Thrusters"); const FName AEndlessReachHDPawn::ActionBinding("Action"); const FName AEndlessReachHDPawn::BackBinding("Back"); const FName AEndlessReachHDPawn::DebugBinding("Debug"); const FName AEndlessReachHDPawn::MenuBinding("Menu"); const FName AEndlessReachHDPawn::LeftBinding("Left"); const FName AEndlessReachHDPawn::RightBinding("Right"); // Construct pawn AEndlessReachHDPawn::AEndlessReachHDPawn() { // Ship Default Specs CurrentHP = 1000; MaxHP = 1000; ATK = 25.0f; DEF = 25.0f; OrbCount = 0; bCanMove = true; MoveSpeed = 50.0f; MaxVelocity = 500.0f; MaxThrustVelocity = 1000.0f; FanSpeed = 50.0f; FuelLevel = 1000.0f; MaxFuel = 1000.0f; bThustersActive = false; bLowFuel = false; bMissilesEnabled = false; bMagnetEnabled = false; GunOffset = FVector(140.f, 0.f, 0.f); FireRate = 0.2f; bCanFire = true; bLaserUnlocked = false; bLaserEnabled = false; LaserChargeCount = 0; LaserChargeMax = 0; bIsDocked = false; bBombsUnlocked = false; bCanFireBomb = true; BombCount = 0; BombMax = 0; LookSensitivity = 5.0f; CamRotSpeed = 5.0f; ClampDegreeMin = -40.0f; ClampDegreeMax = 40.0f; RollX = 0; PitchY = 0; YawZ = 0; bIsDead = false; // Upgrade Level Initialization ShipTypeLevel = 0; HealthLevel = 0; ThrustersLevel = 0; CannonLevel = 0; LaserLevel = 0; MagnetLevel = 0; MissilesLevel = 0; ShieldLevel = 0; BombLevel = 0; // Ship Body static ConstructorHelpers::FObjectFinder<UStaticMesh> ShipMesh(TEXT("/Game/ShipScout_Upgrades/Meshes/SM_ShipScout_Set1_Body.SM_ShipScout_Set1_Body")); ShipMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ShipBody")); RootComponent = ShipMeshComponent; ShipMeshComponent->SetCollisionProfileName(UCollisionProfile::Pawn_ProfileName); ShipMeshComponent->SetStaticMesh(ShipMesh.Object); ShipMeshComponent->SetRelativeRotation(FRotator(0, -90, 0)); ShipMeshComponent->SetWorldScale3D(FVector(0.3f, 0.3f, 0.3f)); ShipMeshComponent->SetSimulatePhysics(true); ShipMeshComponent->BodyInstance.bLockZTranslation = true; ShipMeshComponent->BodyInstance.bLockXRotation = true; ShipMeshComponent->BodyInstance.bLockYRotation = true; // Gun Attachments static ConstructorHelpers::FObjectFinder<UStaticMesh> ShipGuns(TEXT("/Game/ShipScout_Upgrades/Meshes/SM_ShipScout_Set1_Attachments.SM_ShipScout_Set1_Attachments")); ShipMeshGuns = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ShipGuns")); ShipMeshGuns->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); ShipMeshGuns->SetStaticMesh(ShipGuns.Object); // Left Fan static ConstructorHelpers::FObjectFinder<UStaticMesh> LeftFan(TEXT("/Game/ShipScout_Upgrades/Meshes/SM_ShipScout_Set1_Fan.SM_ShipScout_Set1_Fan")); ShipMeshFanL = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("LeftFan")); ShipMeshFanL->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); ShipMeshFanL->SetStaticMesh(LeftFan.Object); // Left Fan Rotation RotatingMovement_FanL = CreateDefaultSubobject<URotatingMovementComponent>(TEXT("RotatingMovement_FanL")); RotatingMovement_FanL->SetUpdatedComponent(ShipMeshFanL); // set the updated component RotatingMovement_FanL->RotationRate = FRotator(0,FanSpeed,0); // Right Fan static ConstructorHelpers::FObjectFinder<UStaticMesh> RightFan(TEXT("/Game/ShipScout_Upgrades/Meshes/SM_ShipScout_Set1_Fan.SM_ShipScout_Set1_Fan")); ShipMeshFanR = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("RightFan")); ShipMeshFanR->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); ShipMeshFanR->SetStaticMesh(RightFan.Object); // Right Fan Rotation RotatingMovement_FanR = CreateDefaultSubobject<URotatingMovementComponent>(TEXT("RotatingMovement_FanR")); RotatingMovement_FanR->SetUpdatedComponent(ShipMeshFanR); // set the updated component RotatingMovement_FanR->RotationRate = FRotator(0, (FanSpeed * -1), 0); // Tail Fan static ConstructorHelpers::FObjectFinder<UStaticMesh> TailFan(TEXT("/Game/ShipScout_Upgrades/Meshes/SM_ShipScout_Set1_Fan_Back.SM_ShipScout_Set1_Fan_Back")); ShipMeshFanT = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("TailFan")); ShipMeshFanT->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); ShipMeshFanT->SetStaticMesh(TailFan.Object); // Tail Fan Rotation RotatingMovement_FanT = CreateDefaultSubobject<URotatingMovementComponent>(TEXT("RotatingMovement_FanT")); RotatingMovement_FanT->SetUpdatedComponent(ShipMeshFanT); // set the updated component RotatingMovement_FanT->RotationRate = FRotator(0, 0, (FanSpeed * -1)); // basic weapon pulse audio static ConstructorHelpers::FObjectFinder<USoundBase> FireAudio(TEXT("/Game/Audio/Guns/PlayerTurret_Pulse1_Cue.PlayerTurret_Pulse1_Cue")); FireSound = FireAudio.Object; // low fuel warning audio static ConstructorHelpers::FObjectFinder<USoundCue> LowFuelAudio(TEXT("/Game/Audio/Ship/PlayerShip_LowFuelWarning_Cue.PlayerShip_LowFuelWarning_Cue")); S_LowFuelWarning = LowFuelAudio.Object; LowFuelWarningSound = CreateDefaultSubobject<UAudioComponent>(TEXT("LowFuelWarningSound")); LowFuelWarningSound->SetupAttachment(RootComponent); LowFuelWarningSound->SetSound(S_LowFuelWarning); LowFuelWarningSound->bAutoActivate = false; // engine idle noise audio static ConstructorHelpers::FObjectFinder<USoundCue> EngineIdleAudio(TEXT("/Game/Audio/Ship/PlayerShip_EngineIdle_Cue.PlayerShip_EngineIdle_Cue")); S_EngineIdle = EngineIdleAudio.Object; EngineIdleSound = CreateDefaultSubobject<UAudioComponent>(TEXT("EngineIdleSound")); EngineIdleSound->SetupAttachment(RootComponent); EngineIdleSound->SetSound(S_EngineIdle); EngineIdleSound->bAutoActivate = true; EngineIdleSound->VolumeMultiplier = 0.4f; // engine thrust noise audio static ConstructorHelpers::FObjectFinder<USoundCue> EngineThrustAudio(TEXT("/Game/Audio/Ship/PlayerShip_EngineThrust_Cue.PlayerShip_EngineThrust_Cue")); S_EngineThrust = EngineThrustAudio.Object; EngineThrustSound = CreateDefaultSubobject<UAudioComponent>(TEXT("EngineThrustSound")); EngineThrustSound->SetupAttachment(RootComponent); EngineThrustSound->SetSound(S_EngineThrust); EngineThrustSound->bAutoActivate = false; // beam cannon noise audio static ConstructorHelpers::FObjectFinder<USoundCue> LaserAudio(TEXT("/Game/Audio/Guns/ForwardGun_Laser_Cue.ForwardGun_Laser_Cue")); S_Laser = LaserAudio.Object; LaserSound = CreateDefaultSubobject<UAudioComponent>(TEXT("LaserSound")); LaserSound->SetupAttachment(RootComponent); LaserSound->SetSound(S_Laser); LaserSound->bAutoActivate = false; // bomb shot audio static ConstructorHelpers::FObjectFinder<USoundBase> BombAudio(TEXT("/Game/Audio/Guns/Bomb_FireShot_Cue.Bomb_FireShot_Cue")); BombSound = BombAudio.Object; // Thruster Visual Effect static ConstructorHelpers::FObjectFinder<UParticleSystem> ThrusterParticleObject(TEXT("/Game/Particles/Emitter/P_BlossomJet.P_BlossomJet")); P_ThrusterFX = ThrusterParticleObject.Object; ThrusterFX = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("ThrusterFX")); ThrusterFX->SetupAttachment(ShipMeshComponent, FName("ThrusterEffectSocket")); ThrusterFX->SetTemplate(P_ThrusterFX); ThrusterFX->SetWorldScale3D(FVector(1.0f, 1.0f, 1.0f)); ThrusterFX->bAutoActivate = false; // Thruster Force Feedback static ConstructorHelpers::FObjectFinder<UForceFeedbackEffect> ThrustFeedback(TEXT("/Game/ForceFeedback/FF_ShipThrusters.FF_ShipThrusters")); ThrusterFeedback = ThrustFeedback.Object; // Beam Cannon Force Feedback static ConstructorHelpers::FObjectFinder<UForceFeedbackEffect> CannonFeedback(TEXT("/Game/ForceFeedback/FF_Laser.FF_Laser")); LaserFeedback = CannonFeedback.Object; // Distortion Visual Effect static ConstructorHelpers::FObjectFinder<UParticleSystem> DistortionParticleObject(TEXT("/Game/Particles/Emitter/DistortionWave.DistortionWave")); P_DistortionFX = DistortionParticleObject.Object; DistortionFX = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("DistortionFX")); DistortionFX->SetupAttachment(ShipMeshComponent, FName("DistortionEffectSocket")); DistortionFX->SetTemplate(P_DistortionFX); DistortionFX->SetWorldScale3D(FVector(0.3f, 0.3f, 0.3f)); DistortionFX->bAutoActivate = true; // Player HUD Widget static ConstructorHelpers::FClassFinder<UUserWidget> HUDWidget(TEXT("/Game/Widgets/BP_PlayerHUD.BP_PlayerHUD_C")); W_PlayerHUD = HUDWidget.Class; // Hangar Menu Widget static ConstructorHelpers::FClassFinder<UUserWidget> HangarMenuWidget(TEXT("/Game/Widgets/BP_HangarMenu.BP_HangarMenu_C")); W_HangarMenu = HangarMenuWidget.Class; // Create a camera boom... CameraBoom_TopDown = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom_TopDown")); CameraBoom_TopDown->SetupAttachment(RootComponent); CameraBoom_TopDown->bAbsoluteRotation = true; // Don't want arm to rotate when ship does CameraBoom_TopDown->TargetArmLength = 1200.f; CameraBoom_TopDown->RelativeRotation = FRotator(-80.0f, 0.0f, 0.0f); CameraBoom_TopDown->bDoCollisionTest = false; // don't want to pull this camera in when it collides with level // Create a camera... Camera_TopDown = CreateDefaultSubobject<UCameraComponent>(TEXT("TopDownCamera")); Camera_TopDown->SetupAttachment(CameraBoom_TopDown, USpringArmComponent::SocketName); Camera_TopDown->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // Create a camera boom... CameraBoom_Rotational = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom_Rotational")); CameraBoom_Rotational->SetupAttachment(RootComponent); CameraBoom_Rotational->bAbsoluteRotation = true; // Don't want arm to rotate when ship does CameraBoom_Rotational->TargetArmLength = 500.f; CameraBoom_Rotational->RelativeRotation = FRotator(0.0f, 0.0f, 0.0f); CameraBoom_Rotational->bDoCollisionTest = false; // I actually did want this camera to collide with the environment, but it was causing issues inside the hangar... it's fine at the short arm length. I didn't want to make zoom feature anyway... // Create a camera... Camera_Rotational = CreateDefaultSubobject<UCameraComponent>(TEXT("RotationalCamera")); Camera_Rotational->SetupAttachment(CameraBoom_Rotational, USpringArmComponent::SocketName); Camera_Rotational->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // configure Aggro Radius AggroRadius = CreateDefaultSubobject<USphereComponent>(TEXT("AggroRadius")); AggroRadius->SetCollisionProfileName(UCollisionProfile::PhysicsActor_ProfileName); AggroRadius->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); AggroRadius->OnComponentBeginOverlap.AddDynamic(this, &AEndlessReachHDPawn::AggroRadiusBeginOverlap); // set up a notification for when this component hits something AggroRadius->SetSphereRadius(5000); // 5000 max range for aggro by default... we'll try it out for now AggroRadius->bHiddenInGame = true; // configure Magnet Radius MagnetRadius = CreateDefaultSubobject<USphereComponent>(TEXT("MagnetRadius")); MagnetRadius->SetCollisionProfileName(UCollisionProfile::PhysicsActor_ProfileName); MagnetRadius->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Overlap); MagnetRadius->SetSphereRadius(1000); // 3000 seems to be a pretty good max range? maybe 4000 would work too... MagnetRadius->bHiddenInGame = true; // Beam Cannon Visual Effect static ConstructorHelpers::FObjectFinder<UParticleSystem> LaserParticleObject(TEXT("/Game/ShipScout_Upgrades/Particles/P_GreenBeam.P_GreenBeam")); P_LaserFX = LaserParticleObject.Object; LaserFX = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("LaserFX")); LaserFX->SetupAttachment(ShipMeshComponent, FName("LaserEffectSocket")); LaserFX->SetTemplate(P_LaserFX); LaserFX->SetRelativeRotation(FRotator(0, 90, 0)); LaserFX->SetWorldScale3D(FVector(1.0f, 1.0f, 1.0f)); LaserFX->bAutoActivate = false; // configure Beam Cannon Radius LaserRadius = CreateDefaultSubobject<UBoxComponent>(TEXT("LaserRadius")); LaserRadius->SetCollisionProfileName(UCollisionProfile::PhysicsActor_ProfileName); LaserRadius->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Overlap); LaserRadius->OnComponentBeginOverlap.AddDynamic(this, &AEndlessReachHDPawn::LaserBeginOverlap); // set up a notification for when this component hits something LaserRadius->SetBoxExtent(FVector(250, 3000, 250)); LaserRadius->bHiddenInGame = true; // configure Beam Cannon Cam shake static ConstructorHelpers::FObjectFinder<UClass> LaserCamShakeObject(TEXT("/Game/CamShakes/CS_Laser.CS_Laser_C")); LaserCamShake = LaserCamShakeObject.Object; // configure Thruster Cam shake static ConstructorHelpers::FObjectFinder<UClass> ThrusterCamShakeObject(TEXT("/Game/CamShakes/CS_Thrusters.CS_Thrusters_C")); ThrusterCamShake = ThrusterCamShakeObject.Object; // Create Combat Text Component CombatTextComponent = CreateDefaultSubobject<UCombatTextComponent>(TEXT("Combat Text Component")); } void AEndlessReachHDPawn::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { check(PlayerInputComponent); // set up gameplay key bindings // AXIS PlayerInputComponent->BindAxis(MoveForwardBinding); PlayerInputComponent->BindAxis(MoveRightBinding); PlayerInputComponent->BindAxis(FireForwardBinding); PlayerInputComponent->BindAxis(FireRightBinding); // ACTIONS PlayerInputComponent->BindAction(LaserBinding, EInputEvent::IE_Pressed, this, &AEndlessReachHDPawn::FireLaser); PlayerInputComponent->BindAction(LaserBinding, EInputEvent::IE_Released, this, &AEndlessReachHDPawn::LaserManualCutoff); PlayerInputComponent->BindAction(ThrustersBinding, EInputEvent::IE_Pressed, this, &AEndlessReachHDPawn::FireThrusters); PlayerInputComponent->BindAction(ThrustersBinding, EInputEvent::IE_Released, this, &AEndlessReachHDPawn::StopThrusters); PlayerInputComponent->BindAction(DebugBinding, EInputEvent::IE_Pressed, this, &AEndlessReachHDPawn::StartDebug); PlayerInputComponent->BindAction(DebugBinding, EInputEvent::IE_Released, this, &AEndlessReachHDPawn::StopDebug); PlayerInputComponent->BindAction(LeftBinding, EInputEvent::IE_Pressed, this, &AEndlessReachHDPawn::MenuLeft); //PlayerInputComponent->BindAction(LeftBinding, EInputEvent::IE_Released, this, &AEndlessReachHDPawn::MenuLeft); PlayerInputComponent->BindAction(RightBinding, EInputEvent::IE_Pressed, this, &AEndlessReachHDPawn::MenuRight); //PlayerInputComponent->BindAction(RightBinding, EInputEvent::IE_Released, this, &AEndlessReachHDPawn::MenuRight); PlayerInputComponent->BindAction(ActionBinding, EInputEvent::IE_Pressed, this, &AEndlessReachHDPawn::ActionInput); //PlayerInputComponent->BindAction(ActionBinding, EInputEvent::IE_Released, this, &AEndlessReachHDPawn::MenuAction); PlayerInputComponent->BindAction(BackBinding, EInputEvent::IE_Pressed, this, &AEndlessReachHDPawn::BackInput); //PlayerInputComponent->BindAction(BackBinding, EInputEvent::IE_Released, this, &AEndlessReachHDPawn::MenuBack); } // Called when the game starts or when spawned void AEndlessReachHDPawn::BeginPlay() { Super::BeginPlay(); // delay configuration of some components so that the world can be brought online first FTimerHandle ConfigDelay; GetWorldTimerManager().SetTimer(ConfigDelay, this, &AEndlessReachHDPawn::ConfigureShip, 0.25f, false); } // Debug Test Function void AEndlessReachHDPawn::StartDebug() { Camera_TopDown->SetActive(false, false); // disable top down cam Camera_Rotational->SetActive(true, false); // enable rotational cam FViewTargetTransitionParams params; APlayerController* PlayerController = Cast<APlayerController>(GetController()); PlayerController->SetViewTarget(this, params); // set new camera bIsDocked = true; // DOCKED } // Debug Test Function void AEndlessReachHDPawn::StopDebug() { Camera_TopDown->SetActive(true, false); // enable top down cam Camera_Rotational->SetActive(false, false); // disable rotational cam FViewTargetTransitionParams params; APlayerController* PlayerController = Cast<APlayerController>(GetController()); PlayerController->SetViewTarget(this, params); // set new camera bIsDocked = false; // UNDOCKED } // Configure the Ship's default settings - mostly finishing up attaching actors that require the world to have been brought online void AEndlessReachHDPawn::ConfigureShip() { // Configure Physics Constraint Components to maintain attachment of the ship's objects, like fans, magnet, etc // we need to use constraints because the ship's body is simulating physics // We want the guns, fans, and magnet to be stationary and stay exactly where they're attached, which means we're using them more like simple sockets (which sort of defeats the purpose of these physics constraints...) FConstraintInstance ConstraintInstance_Static; // a basic constraint instance with no intention to move - will function more as a socket than a physics constraint UCommonLibrary::SetLinearLimits(ConstraintInstance_Static, true, 0, 0, 0, 0, false, 0, 0); UCommonLibrary::SetAngularLimits(ConstraintInstance_Static, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); // Left Fan Constraint ShipConstraintFanL = NewObject<UPhysicsConstraintComponent>(ShipMeshComponent); // create left fan constraint ShipConstraintFanL->ConstraintInstance = ConstraintInstance_Static; // set constraint instance ShipConstraintFanL->AttachToComponent(ShipMeshComponent, FAttachmentTransformRules::SnapToTargetIncludingScale, NAME_None); // attach constraint to ship - can add a socket if necessary ShipConstraintFanL->SetRelativeLocation(FVector(240, 30, 30)); // set default location of constraint ShipConstraintFanL->SetConstrainedComponents(ShipMeshComponent, NAME_None, ShipMeshFanL, NAME_None); // constrain the left fan to the ship body ShipMeshFanL->AttachToComponent(ShipConstraintFanL, FAttachmentTransformRules::SnapToTargetIncludingScale); // Attach left fan to constraint ShipMeshFanL->SetRelativeLocation(FVector(0, 0, 0)); // reset fan location // Right Fan Constraint ShipConstraintFanR = NewObject<UPhysicsConstraintComponent>(ShipMeshComponent); // create right fan constraint ShipConstraintFanR->ConstraintInstance = ConstraintInstance_Static; // set constraint instance ShipConstraintFanR->AttachToComponent(ShipMeshComponent, FAttachmentTransformRules::SnapToTargetIncludingScale, NAME_None); // attach constraint to ship - can add a socket if necessary ShipConstraintFanR->SetRelativeLocation(FVector(-240, 30, 30)); // set default location of constraint ShipConstraintFanR->SetConstrainedComponents(ShipMeshComponent, NAME_None, ShipMeshFanR, NAME_None); // constrain the right fan to the ship body ShipMeshFanR->AttachToComponent(ShipConstraintFanR, FAttachmentTransformRules::SnapToTargetIncludingScale); // Attach left fan to constraint ShipMeshFanR->SetRelativeLocation(FVector(0, 0, 0)); // reset fan location // Tail Fan Constraint ShipConstraintFanT = NewObject<UPhysicsConstraintComponent>(ShipMeshComponent); // create tail fan constraint ShipConstraintFanT->ConstraintInstance = ConstraintInstance_Static; // set constraint instance ShipConstraintFanT->AttachToComponent(ShipMeshComponent, FAttachmentTransformRules::SnapToTargetIncludingScale, NAME_None); // attach constraint to ship - can add a socket if necessary ShipConstraintFanT->SetRelativeLocation(FVector(0, -400, 130)); // set default location of constraint ShipConstraintFanT->SetConstrainedComponents(ShipMeshComponent, NAME_None, ShipMeshFanT, NAME_None); // constrain the tail fan to the ship body ShipMeshFanT->AttachToComponent(ShipConstraintFanT, FAttachmentTransformRules::SnapToTargetIncludingScale); // Attach left fan to constraint ShipMeshFanT->SetRelativeLocation(FVector(0, 0, 0)); // reset fan location // Gun Attachment Constraint ShipConstraintGuns = NewObject<UPhysicsConstraintComponent>(ShipMeshComponent); // create gun attachment constraint ShipConstraintGuns->ConstraintInstance = ConstraintInstance_Static; // set constraint instance ShipConstraintGuns->AttachToComponent(ShipMeshComponent, FAttachmentTransformRules::SnapToTargetIncludingScale, NAME_None); // attach constraint to ship - can add a socket if necessary ShipConstraintGuns->SetRelativeLocation(FVector(0, 0, 0)); // set default location of constraint ShipConstraintGuns->SetConstrainedComponents(ShipMeshComponent, NAME_None, ShipMeshGuns, NAME_None); // constrain the guns to the ship body ShipMeshGuns->AttachToComponent(ShipConstraintGuns, FAttachmentTransformRules::SnapToTargetIncludingScale); // Attach guns to constraint ShipMeshGuns->SetRelativeLocation(FVector(0, 0, 0)); // reset gun location // Beam Cannon Attachment Constraint LaserConstraint = NewObject<UPhysicsConstraintComponent>(ShipMeshComponent); // create beam cannon constraint LaserConstraint->ConstraintInstance = ConstraintInstance_Static; // set constraint instance LaserConstraint->AttachToComponent(ShipMeshComponent, FAttachmentTransformRules::SnapToTargetIncludingScale, NAME_None); // attach constraint to ship - can add a socket if necessary LaserConstraint->SetRelativeLocation(FVector(0, 0, 0)); // set default location of constraint LaserConstraint->SetConstrainedComponents(ShipMeshComponent, NAME_None, LaserRadius, NAME_None); // constrain beam cannon to the ship body LaserRadius->AttachToComponent(LaserConstraint, FAttachmentTransformRules::SnapToTargetIncludingScale); // Attach beam cannon to constraint LaserRadius->SetRelativeLocation(FVector(0, 2500, 0)); // reset beam cannon location // Aggro Constraint AggroConstraint = NewObject<UPhysicsConstraintComponent>(ShipMeshComponent); // create Aggro constraint AggroConstraint->ConstraintInstance = ConstraintInstance_Static; // set constraint instance AggroConstraint->AttachToComponent(ShipMeshComponent, FAttachmentTransformRules::SnapToTargetIncludingScale, NAME_None); // attach constraint to ship - can add a socket if necessary AggroConstraint->SetRelativeLocation(FVector(0, 0, 0)); // set default location of constraint AggroConstraint->SetConstrainedComponents(ShipMeshComponent, NAME_None, AggroRadius, NAME_None); // constrain the Aggro radius to the ship body AggroRadius->AttachToComponent(AggroConstraint, FAttachmentTransformRules::SnapToTargetIncludingScale); // Attach radius to constraint AggroRadius->SetRelativeLocation(FVector(0, 0, 0)); // reset radius location // Magnet Constraint MagnetConstraint = NewObject<UPhysicsConstraintComponent>(ShipMeshComponent); // create magnet constraint MagnetConstraint->ConstraintInstance = ConstraintInstance_Static; // set constraint instance MagnetConstraint->AttachToComponent(ShipMeshComponent, FAttachmentTransformRules::SnapToTargetIncludingScale, NAME_None); // attach constraint to ship - can add a socket if necessary MagnetConstraint->SetRelativeLocation(FVector(0, 0, 0)); // set default location of constraint MagnetConstraint->SetConstrainedComponents(ShipMeshComponent, NAME_None, MagnetRadius, NAME_None); // constrain the magnet radios to the ship body MagnetRadius->AttachToComponent(MagnetConstraint, FAttachmentTransformRules::SnapToTargetIncludingScale); // Attach magnet to constraint MagnetRadius->SetRelativeLocation(FVector(0, 0, 0)); // reset magnet location InitializeAllWidgets(); // init widgets } void AEndlessReachHDPawn::Tick(float DeltaSeconds) { // Find movement direction const float ForwardValue = GetInputAxisValue(MoveForwardBinding); const float RightValue = GetInputAxisValue(MoveRightBinding); // Clamp max size so that (X=1, Y=1) doesn't cause faster movement in diagonal directions const FVector MoveDirection = FVector(ForwardValue, RightValue, 0.0f).GetClampedToMaxSize(1.0f); // Calculate movement const FVector Movement = MoveDirection * MoveSpeed * DeltaSeconds; // If stick is being pressed, MOVE if (Movement.SizeSquared() > 0.0f) { // verify that movement is possible // We don't bother to make this check when the stick is not being pressed if (bCanMove) { ShipMeshComponent->SetLinearDamping(0.01f); // RESET LINEAR DAMPING ShipMeshComponent->SetAngularDamping(0.01f); // RESET ANGULAR DAMPING const FRotator NewRotation = Movement.Rotation(); const FRotator CorrectedRotation = FRotator(NewRotation.Pitch, (NewRotation.Yaw - 90), NewRotation.Roll); // correct rotation because of the ship's offset pivot point FHitResult Hit(1.0f); EngineIdleSound->VolumeMultiplier = 0.75f; // increase engine noise RootComponent->MoveComponent(Movement, FMath::Lerp(GetActorRotation(), CorrectedRotation, 0.05f), true, &Hit); // move ship with smooth rotation - (LINEAR) MOVEMENT METHOD // if the thrusters are not active and the ship is under max velocity, we'll allow light impulse to be applied with the analog stick if (GetVelocity().Size() < MaxVelocity) { ShipMeshComponent->AddImpulseAtLocation(MoveDirection * MaxVelocity, GetActorLocation()); // Apply impulse thrust - (PHYSICS) MOVEMENT METHOD } if (Hit.IsValidBlockingHit()) { const FVector Normal2D = Hit.Normal.GetSafeNormal2D(); const FVector Deflection = FVector::VectorPlaneProject(Movement, Normal2D) * (1.0f - Hit.Time); RootComponent->MoveComponent(Deflection, NewRotation, true); } // increase fan speed while moving if (FanSpeed < 500) { FanSpeed++; // increment fan speed UpdateFanSpeed(); } // THRUSTER CONTROL if (bThustersActive) { // if you have fuel available when thrusters are activated if (FuelLevel > 0) { FuelLevel--; // CONSUME FUEL // Do not add thrust if ship has already reached maximum thrust velocity if (GetVelocity().Size() < MaxThrustVelocity) { ShipMeshComponent->AddImpulseAtLocation(MoveDirection * MaxThrustVelocity, GetActorLocation()); // Apply impulse thrust } } // if you're still using thrusters when you're out of fuel, we'll slow you down a lot as you overload the ship // TO DO: maybe add an overheating visual effect, and maybe allow the ship to explode if you continue thrusting with no fuel if (FuelLevel <= (MaxFuel * 0.1f)) { if (!bLowFuel) { LowFuelSafety(); } } if (FuelLevel <= 0) { StopThrusters(); // if you completely run out of fuel, call full stop on thrusters } } } // if bCanMove becomes false else { StopThrusters(); // stop thrusters ShipMeshComponent->SetLinearDamping(2.5f); // Increase linear damping to slow down translation ShipMeshComponent->SetAngularDamping(2.5f); // Increase angular damping to slow down rotation } } // When analog stick is no longer being pressed, STOP if (Movement.SizeSquared() <= 0.0f) { EngineIdleSound->VolumeMultiplier = 0.4f; // decrease engine noise // decrease fan speed while idling if (FanSpeed > 50) { FanSpeed--; // decrement fan speed UpdateFanSpeed(); } if (bLowFuel) { StopThrusters(); // if you stopped moving while low on fuel, then we call full stop on the thrusters (to disable audio and reset bLowFuel) } ShipMeshComponent->SetLinearDamping(0.5f); // Increase linear damping to slow down translation ShipMeshComponent->SetAngularDamping(0.5f); // Increase angular damping to slow down rotation } // Create fire direction vector const float FireForwardValue = GetInputAxisValue(FireForwardBinding); const float FireRightValue = GetInputAxisValue(FireRightBinding); const FVector FireDirection = FVector(FireForwardValue, FireRightValue, 0.f); //ShipMeshGuns->SetRelativeRotation(FRotationMatrix::MakeFromX(FireDirection).Rotator()); // rotate guns to face firing direction - removed because it looks weird (ship was not modeled to support a turret feature) // If you're undocked, you must be flying, so try firing a shot if (!bIsDocked) { // Try and fire a shot FireShot(FireDirection); UpdatePlayerHUD(); // Update Player HUD with new information } // if you are docked, we'll let you rotate the camera to get a good look at your ship if (bIsDocked) { CameraControl_RotateVertical(GetInputAxisValue(FireForwardBinding)); // update boom vertical rotation CameraControl_RotateHorizontal(GetInputAxisValue(FireRightBinding)); // update boom horizontal rotation //UpdateHangarMenu(); // Update Hangar Menu with new information } // DEBUG: WRITE VELOCITY TO SCREEN EACH FRAME //GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Magenta, FString::Printf(TEXT("Velocity: %f"), GetVelocity().Size())); // DEBUG: WRITE FUEL LEVEL TO SCREEN EACH FRAME //GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Blue, FString::Printf(TEXT("Fuel Level: %f"), FuelLevel)); } // Initialize all widgets void AEndlessReachHDPawn::InitializeAllWidgets() { // Spawn and attach the PlayerHUD if (!PlayerHUD) { PlayerHUD = CreateWidget<UPlayerHUD>(GetWorld(), W_PlayerHUD); // creates the player hud widget if (!bIsDocked) { PlayerHUD->AddToViewport(); // add player hud to viewport } } if (!HangarMenu) { HangarMenu = CreateWidget<UHangarMenu>(GetWorld(), W_HangarMenu); // creates the hangar menu widget } if (HangarMenu) { if (bIsDocked) { HangarMenu->AddToViewport(); // add hangar menu to viewport UpdateHangarMenu(); // refresh the hangar menu with default information } } } // Update the HUD with new information each frame void AEndlessReachHDPawn::UpdatePlayerHUD() { if (PlayerHUD) { if (PlayerHUD->IsInViewport()) { PlayerHUD->Player_CurrentHP = CurrentHP; // set current hp PlayerHUD->Player_MaxHP = MaxHP; // set max hp PlayerHUD->Player_CurrentFuel = FuelLevel; // set fuel level PlayerHUD->Player_MaxFuel = MaxFuel; // set max fuel level PlayerHUD->Player_OrbCount = UCommonLibrary::GetFloatAsTextWithPrecision(OrbCount, 0, false); // set current orb count } } } // Update the Hangar Menu with new information void AEndlessReachHDPawn::UpdateHangarMenu() { if (HangarMenu) { if (HangarMenu->IsInViewport()) { HangarMenu->Player_OrbCount = UCommonLibrary::GetFloatAsTextWithPrecision(OrbCount, 0, false); // set current orb count } } } void AEndlessReachHDPawn::FireShot(FVector FireDirection) { // If we it's ok to fire again if (bCanFire) { // If we are pressing fire stick in a direction if (FireDirection.SizeSquared() > 0.0f) { const FRotator FireRotation = FireDirection.Rotation(); // Spawn projectile at an offset from this pawn const FVector SpawnLocation = GetActorLocation() + FireRotation.RotateVector(GunOffset); UWorld* const World = GetWorld(); if (World != NULL) { // FIRE PROJECTILE ACannonball* Pulse = World->SpawnActor<ACannonball>(SpawnLocation, FireRotation); // spawn projectile Pulse->Player = this; // The following is velocity inheritance code for the projectile... it's almost working, but not quite, so commented out for now //float InheritanceMod = 1.0f; // set inheritance level to 100% //FVector Inheritance = GetControlRotation().UnrotateVector(GetVelocity()); // unrotate the player's velocity vector //FVector NewVelocity = ((Inheritance * InheritanceMod) + ProjectileDefaultVelocity); // add inherited velocity to the projectile's default velocity - THIS LINE IS INCORRECT //Pulse->GetProjectileMovement()->SetVelocityInLocalSpace(NewVelocity); // update projectile velocity //GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, FString::Printf(TEXT("Updated Projectile Velocity: %f"), Pulse->GetVelocity().Size())); } bCanFire = false; World->GetTimerManager().SetTimer(TimerHandle_ShotTimerExpired, this, &AEndlessReachHDPawn::ShotTimerExpired, FireRate); // try and play the sound if specified if (FireSound != nullptr) { UGameplayStatics::PlaySoundAtLocation(this, FireSound, GetActorLocation()); // play sound } //bCanFire = false; } } } // Rotational Camera Control (only accessible when docked) void AEndlessReachHDPawn::CameraControl_RotateHorizontal(float horizontal) { bool bLookHorizontalInvert = true; // for now, we're just defaulting to inverted controls. in the future, this setting may be changed within the options menu switch (bLookHorizontalInvert) { case true: LookSensitivity = LookSensitivity * 1; // do nothing for inverted controls break; case false: LookSensitivity = LookSensitivity * -1; // multiply by -1 for standard controls break; } // I thought I could store this current rotation update block earlier in the tick function, so that it could be used for both the horizontal and vertical rotation functions... // however, when I did that, the camera movement would only update one direction at a time (instead of both horizontal+vertical simultaneously) // therefore, this update block exists in both camera control functions RollX = CameraBoom_Rotational->GetComponentRotation().Roll; // store current boom roll PitchY = CameraBoom_Rotational->GetComponentRotation().Pitch; // store current boom pitch YawZ = CameraBoom_Rotational->GetComponentRotation().Yaw; // store current boom yaw // if vertical == 0.0f then do nothing... if (horizontal > 0.1f) { CameraBoom_Rotational->SetWorldRotation(FRotator(PitchY, FMath::FInterpTo(YawZ, YawZ + LookSensitivity, GetWorld()->GetDeltaSeconds(), CamRotSpeed), RollX)); } if (horizontal < -0.1f) { CameraBoom_Rotational->SetWorldRotation(FRotator(PitchY, FMath::FInterpTo(YawZ, YawZ - LookSensitivity, GetWorld()->GetDeltaSeconds(), CamRotSpeed), RollX)); } } // Rotational Camera Control (only accessible when docked) void AEndlessReachHDPawn::CameraControl_RotateVertical(float vertical) { bool bLookVerticalInvert = true; // for now, we're just defaulting to inverted controls. in the future, this setting may be changed within the options menu switch (bLookVerticalInvert) { case true: LookSensitivity = LookSensitivity * 1; // do nothing for inverted controls break; case false: LookSensitivity = LookSensitivity * -1; // multiply by -1 for standard controls break; } // I thought I could store this current rotation update block earlier in the tick function, so that it could be used for both the horizontal and vertical rotation functions... // however, when I did that, the camera movement would only update one direction at a time (instead of both horizontal+vertical simultaneously) // therefore, this update block exists in both camera control functions RollX = CameraBoom_Rotational->GetComponentRotation().Roll; // store current boom roll PitchY = CameraBoom_Rotational->GetComponentRotation().Pitch; // store current boom pitch YawZ = CameraBoom_Rotational->GetComponentRotation().Yaw; // store current boom yaw // if vertical == 0.0f then do nothing... if (vertical > 0.1f) { float ClampedPitchLerp = FMath::Clamp(FMath::FInterpTo(PitchY, PitchY + LookSensitivity, GetWorld()->GetDeltaSeconds(), CamRotSpeed), ClampDegreeMin, ClampDegreeMax); CameraBoom_Rotational->SetWorldRotation(FRotator(ClampedPitchLerp, YawZ, RollX)); } if (vertical < -0.1f) { float ClampedPitchLerp = FMath::Clamp(FMath::FInterpTo(PitchY, PitchY - LookSensitivity, GetWorld()->GetDeltaSeconds(), CamRotSpeed), ClampDegreeMin, ClampDegreeMax); CameraBoom_Rotational->SetWorldRotation(FRotator(ClampedPitchLerp, YawZ, RollX)); } } void AEndlessReachHDPawn::ShotTimerExpired() { bCanFire = true; bCanFireBomb = true; } void AEndlessReachHDPawn::UpdateFanSpeed() { // apply rotation speed RotatingMovement_FanL->RotationRate = FRotator(0, FanSpeed, 0); RotatingMovement_FanR->RotationRate = FRotator(0, (FanSpeed * -1), 0); RotatingMovement_FanT->RotationRate = FRotator(0, 0, (FanSpeed * -1)); } void AEndlessReachHDPawn::FireLaser() { if (!bIsDocked) { if (bLaserUnlocked) { if (bLaserEnabled) // if the laser is already enabled when this function is called, it means the player was still holding the button and had charges remaining, so we essentially loop the firing mechanism { APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0); // Get Player Controller PlayerController->ClientPlayForceFeedback(LaserFeedback, false, false, FName(TEXT("Laser"))); // Play Laser Force Feedback PlayerController->ClientPlayCameraShake(LaserCamShake); // play laser cam shake UseLaserCharge(); // use a laser charge // laser firing duration FTimerHandle LaserDelay; GetWorldTimerManager().SetTimer(LaserDelay, this, &AEndlessReachHDPawn::StopLaser, 3.0f, false); } // if the laser has yet to be enabled... if (!bLaserEnabled) { if (LaserChargeCount > 0 && LaserChargeCount <= LaserChargeMax) // if laser charges is greater than zero but less or equal to than max... { bLaserEnabled = true; // enable laser if (!LaserSound->IsPlaying()) // if the laser sound is not already playing... { LaserSound->Play(); // play laser sfx } LaserFX->Activate(); // play laser vfx APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0); // Get Player Controller PlayerController->ClientPlayForceFeedback(LaserFeedback, false, false, FName(TEXT("Laser"))); // Play Laser Force Feedback PlayerController->ClientPlayCameraShake(LaserCamShake); // play laser cam shake UseLaserCharge(); // use a laser charge // laser firing duration FTimerHandle LaserDelay; GetWorldTimerManager().SetTimer(LaserDelay, this, &AEndlessReachHDPawn::StopLaser, 3.0f, false); } } } } } void AEndlessReachHDPawn::StopLaser() { if (bLaserEnabled) { if (LaserChargeCount > 0) { FireLaser(); // fire laser again! (player is still holding the button and still has charges remaining) } else { LaserManualCutoff(); // force laser shutdown if there isn't at least one charge remaining } } if (!bLaserEnabled) { bLaserEnabled = false; LaserFX->Deactivate(); LaserSound->FadeOut(0.5f, 0); APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0); // Get Player Controller PlayerController->ClientStopForceFeedback(LaserFeedback, FName(TEXT("Laser"))); // Stop Beam Cannon force feedback } } void AEndlessReachHDPawn::UseLaserCharge() { switch (LaserChargeCount) { case 0: // if none break; case 1: // if one PlayerHUD->DischargeLaser_Stage1(); // discharge laser stage 1 hud anim break; case 2: // if two PlayerHUD->DischargeLaser_Stage2(); // discharge laser stage 2 hud anim break; case 3: // if three PlayerHUD->DischargeLaser_Stage3(); // discharge laser stage 3 hud anim break; case 4: // if four PlayerHUD->DischargeLaser_Stage4(); // discharge laser stage 4 hud anim break; case 5: // if five PlayerHUD->DischargeLaser_Stage5(); // discharge laser stage 5 hud anim break; } if (LaserChargeCount > 0) // if one or more laser charges... { LaserChargeCount--; // decrease laser charge count } } void AEndlessReachHDPawn::LaserManualCutoff() { bLaserEnabled = false; StopLaser(); // stop laser } void AEndlessReachHDPawn::LaserBeginOverlap(UPrimitiveComponent * HitComp, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult) { if (bLaserEnabled) // verify beam cannon is enabled before proceeding { if ((OtherActor != NULL) && (OtherActor != this) && (OtherComp != NULL)) { if (OtherComp->IsSimulatingPhysics()) { OtherComp->AddImpulseAtLocation(GetVelocity() * 20.0f, GetActorLocation()); // apply small physics impulse to any physics object you hit } AAsteroid* Asteroid = Cast<AAsteroid>(OtherActor); // if object is an asteroid... if (Asteroid) { Asteroid->OnDestroyAsteroid.Broadcast(); // Broadcast Asteroid Destruction } AEnemyMaster* Enemy = Cast<AEnemyMaster>(OtherActor); // if object is an enemy... if (Enemy) { Enemy->EnemyTakeDamage(PlayerDealDamage(ATK + 250)); } } } } void AEndlessReachHDPawn::AggroRadiusBeginOverlap(UPrimitiveComponent * HitComp, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult) { if ((OtherActor != NULL) && (OtherActor != this) && (OtherComp != NULL)) { //AEnemyMaster* Enemy = Cast<AEnemyMaster>(OtherActor); // if the object is an enemy //if (Enemy) //{ // // calling this here will manually force trigger the enemy's aggro function, and immediately attack the player when he gets in range // // in general, we leave it up to the Unreal A.I. system to perform this action // // but this is here for debug purposes, if necessary // Enemy->Aggro(this); //} } } // This function sets the DamageOutput variable, based on the BaseAtk value of an attack. Returns the ultimate value of damage dealt to an enemy. float AEndlessReachHDPawn::PlayerDealDamage(float BaseAtk) { // The next three lines are pure Black Magic float mod1 = ((BaseAtk + ATK) / 32); float mod2 = ((BaseAtk * ATK) / 64); float mod3 = (((mod1 * mod2) + ATK) * 40); float adjusted = mod3; // set adjusted to base value of mod3 return adjusted; // Set Damage Output } // This function deals damage to the player, based on a DamageTaken value supplied by an enemy. This function is usually called by the enemy itself. void AEndlessReachHDPawn::PlayerTakeDamage(float DamageTaken) { if (!bIsDead) // take no damage if you're already dead! { //IsHit = true; // Calculate damage taken float critical = FMath::FRandRange(1, 1.5f); // sets a random critical rate float mod1 = (critical * (DEF - 512) * DamageTaken); float mod2 = (mod1 / (16 * 512)); float mod3 = FMath::Abs(mod2); float FinalDamage = mod3; CurrentHP = (CurrentHP - FinalDamage); // apply new HP value if (critical > 1.4f) { // Display Critical Damage CombatTextComponent->ShowCombatText(ECombatTextTypes::TT_CritDmg, UCommonLibrary::GetFloatAsTextWithPrecision(FinalDamage, 0, true)); } else { // Display Normal Damage CombatTextComponent->ShowCombatText(ECombatTextTypes::TT_Damage, UCommonLibrary::GetFloatAsTextWithPrecision(FinalDamage, 0, true)); } ForceHPCaps(); } } // Force HP Caps keeps the enemy's HP between 0 and Max bool AEndlessReachHDPawn::ForceHPCaps() { bool Kill = false; if (CurrentHP > MaxHP) // if HP is greater than 0 { CurrentHP = MaxHP; } else if (CurrentHP < 0) // if HP is less than 0 { CurrentHP = 0; Kill = true; } if (Kill) { //Death(); // Start the Death sequence } return Kill; } void AEndlessReachHDPawn::FireThrusters() { if (!bIsDocked) { bThustersActive = true; if (FuelLevel > 0) { EnableThrusterFX(); MakeNoise(1, this, GetActorLocation(), 2500); // Report to Enemy A.I. that we've made an audible sound. This noise will alert enemies to your location! } } } void AEndlessReachHDPawn::StopThrusters() { if (!bIsDocked) { bThustersActive = false; bLowFuel = false; DisableThrusterFX(); } } // This feature makes it harder to completely run out of fuel, and plays an audio warning when near empty void AEndlessReachHDPawn::LowFuelSafety() { if (FuelLevel > 0) { bLowFuel = true; LowFuelWarningSound->Play(); // play audio ShipMeshComponent->SetLinearDamping(2.0f); // Increase linear damping to slow down translation ShipMeshComponent->SetAngularDamping(2.0f); // Increase angular damping to slow down rotation } } // thruster effects were separated from the main Fire/StopThrusters() functions so that the effects could be activated during cutscenes (as opposed to just manually by the player) void AEndlessReachHDPawn::EnableThrusterFX() { EngineThrustSound->Play(); ThrusterFX->Activate(); APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0); // Get Player Controller PlayerController->ClientPlayForceFeedback(ThrusterFeedback, false, false, FName(TEXT("Thruster"))); // Play Thruster Force Feedback PlayerController->ClientPlayCameraShake(ThrusterCamShake); // play cam shake } void AEndlessReachHDPawn::DisableThrusterFX() { ThrusterFX->Deactivate(); EngineThrustSound->FadeOut(0.25f, 0); LowFuelWarningSound->FadeOut(0.05f, 0); APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0); // Get Player Controller PlayerController->ClientStopForceFeedback(ThrusterFeedback, FName(TEXT("Thruster"))); // Stop Thruster Feedback //PlayerController->ClientStopCameraShake(ThrusterCamShake); // we don't need to manually stop the cam shakes, because that causes them to look unnatural } void AEndlessReachHDPawn::EngageDockingClamps() { Camera_TopDown->SetActive(false, false); // disable top down cam Camera_Rotational->SetActive(true, false); // enable rotational cam FViewTargetTransitionParams params; APlayerController* PlayerController = Cast<APlayerController>(GetController()); PlayerController->SetViewTarget(this, params); // set new camera bIsDocked = true; // DOCKED bCanMove = false; // no movement while docked bCanFire = false; // no weapons while docked if (PlayerHUD) // error checking { PlayerHUD->RemoveFromViewport(); // remove the player hud from the viewport } if (HangarMenu) { HangarMenu->AddToViewport(); // add the hangar menu to the viewport UpdateHangarMenu(); // refresh the hangar menu with updated information HangarMenu->ReturnToUpgradeMenu(); // return to the upgrade menu (this is really only necessary for subsequent docking entries after a level load) } else { InitializeAllWidgets(); // reinitialize widgets, since the hangar menu apparantly failed to load } } void AEndlessReachHDPawn::ReleaseDockingClamps() { Camera_TopDown->SetActive(true, false); // enable top down cam Camera_Rotational->SetActive(false, false); // disable rotational cam FViewTargetTransitionParams params; APlayerController* PlayerController = Cast<APlayerController>(GetController()); PlayerController->SetViewTarget(this, params); // set new camera bIsDocked = false; // UNDOCKED bCanMove = true; // restore movement bCanFire = true; // arm weapons if (HangarMenu) // error checking { HangarMenu->RemoveFromViewport(); // remove hangar menu from the viewport } if (PlayerHUD) // error checking { PlayerHUD->AddToViewport(); // add the player hud to the viewport } } void AEndlessReachHDPawn::FireBomb() { if (bBombsUnlocked) { if (bCanFireBomb) { if (BombCount > 0 && BombCount <= BombMax) { // Find movement direction const float ForwardValue = GetInputAxisValue(MoveForwardBinding); const float RightValue = GetInputAxisValue(MoveRightBinding); // Clamp max size so that (X=1, Y=1) doesn't cause faster movement in diagonal directions const FVector MoveDirection = FVector(ForwardValue, RightValue, 0.0f).GetClampedToMaxSize(1.0f); // Spawn projectile at an offset from this pawn const FRotator FireRotation = MoveDirection.Rotation(); const FVector SpawnLocation = GetActorLocation() + FireRotation.RotateVector(GunOffset); UWorld* const World = GetWorld(); if (World != NULL) { // FIRE PROJECTILE ABomb* Bomb = World->SpawnActor<ABomb>(SpawnLocation, FireRotation); // spawn projectile Bomb->Player = this; // The following is velocity inheritance code for the projectile... it's almost working, but not quite, so commented out for now //float InheritanceMod = 1.0f; // set inheritance level to 100% //FVector Inheritance = GetControlRotation().UnrotateVector(GetVelocity()); // unrotate the player's velocity vector //FVector NewVelocity = ((Inheritance * InheritanceMod) + ProjectileDefaultVelocity); // add inherited velocity to the projectile's default velocity - THIS LINE IS INCORRECT //Pulse->GetProjectileMovement()->SetVelocityInLocalSpace(NewVelocity); // update projectile velocity //GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, FString::Printf(TEXT("Updated Projectile Velocity: %f"), Pulse->GetVelocity().Size())); } // Reduce bomb count by one for each bomb fired if (BombCount > 0) { BombCount--; } else { BombCount = 0; // bomb count cannot be less than zero } bCanFireBomb = false; World->GetTimerManager().SetTimer(TimerHandle_ShotTimerExpired, this, &AEndlessReachHDPawn::ShotTimerExpired, FireRate); // try and play the sound if specified if (BombSound != nullptr) { UGameplayStatics::PlaySoundAtLocation(this, BombSound, GetActorLocation()); // play sound } bCanFireBomb = false; } } } } // Menu Left Control void AEndlessReachHDPawn::MenuLeft() { if (bIsDocked) { if(HangarMenu) { if (HangarMenu->IsInViewport()) { HangarMenu->MoveLeft(); } } } } // Menu Right Control void AEndlessReachHDPawn::MenuRight() { if (bIsDocked) { if (HangarMenu) { if (HangarMenu->IsInViewport()) { HangarMenu->MoveRight(); } } } } // Get Upgrade Cost int32 AEndlessReachHDPawn::GetUpgradeCost(int32 UpgradeIndex, int32 PowerLevel) { // cost of the upgrade for the specified level int32 UpgradeCost = 0; switch (UpgradeIndex) { // SHIP TYPE UPGRADE case 0: switch (PowerLevel) { case 0: UpgradeCost = 1750; break; case 1: UpgradeCost = 2500; break; case 2: UpgradeCost = 3250; break; case 3: UpgradeCost = 4500; break; case 4: UpgradeCost = 6000; break; case 5: UpgradeCost = 99999; break; } break; // HEALTH UPGRADE case 1: switch (PowerLevel) { case 0: UpgradeCost = 250; break; case 1: UpgradeCost = 500; break; case 2: UpgradeCost = 750; break; case 3: UpgradeCost = 1000; break; case 4: UpgradeCost = 1500; break; case 5: UpgradeCost = 99999; break; } break; // THURSTERS UPGRADE case 2: switch (PowerLevel) { case 0: UpgradeCost = 500; break; case 1: UpgradeCost = 750; break; case 2: UpgradeCost = 1000; break; case 3: UpgradeCost = 1250; break; case 4: UpgradeCost = 1500; break; case 5: UpgradeCost = 99999; break; } break; // MAIN CANNON UPGRADE case 3: switch (PowerLevel) { case 0: UpgradeCost = 500; break; case 1: UpgradeCost = 750; break; case 2: UpgradeCost = 1000; break; case 3: UpgradeCost = 1250; break; case 4: UpgradeCost = 1500; break; case 5: UpgradeCost = 99999; break; } break; // LASER UPGRADE case 4: switch (PowerLevel) { case 0: UpgradeCost = 1000; break; case 1: UpgradeCost = 1500; break; case 2: UpgradeCost = 2000; break; case 3: UpgradeCost = 2500; break; case 4: UpgradeCost = 3000; break; case 5: UpgradeCost = 99999; break; } break; // MAGNET UPGRADE case 5: switch (PowerLevel) { case 0: UpgradeCost = 1000; break; case 1: UpgradeCost = 1500; break; case 2: UpgradeCost = 2000; break; case 3: UpgradeCost = 2500; break; case 4: UpgradeCost = 3000; break; case 5: UpgradeCost = 99999; break; } break; // MISSILES UPGRADE case 6: switch (PowerLevel) { case 0: UpgradeCost = 1500; break; case 1: UpgradeCost = 2250; break; case 2: UpgradeCost = 3000; break; case 3: UpgradeCost = 3750; break; case 4: UpgradeCost = 4500; break; case 5: UpgradeCost = 99999; break; } break; // ENERGY SHIELD UPGRADE case 7: switch (PowerLevel) { case 0: UpgradeCost = 1500; break; case 1: UpgradeCost = 2250; break; case 2: UpgradeCost = 3000; break; case 3: UpgradeCost = 3750; break; case 4: UpgradeCost = 4500; break; case 5: UpgradeCost = 99999; break; } break; // BOMB LEVEL case 8: switch (PowerLevel) { case 0: UpgradeCost = 2000; break; case 1: UpgradeCost = 3000; break; case 2: UpgradeCost = 4000; break; case 3: UpgradeCost = 5000; break; case 4: UpgradeCost = 6000; break; case 5: UpgradeCost = 99999; break; } break; } return UpgradeCost; } // Upgrade Health void AEndlessReachHDPawn::UpgradeHealth(int32 UpgradeCost, int32 Level, int32 NextUpgradeCost) { if (OrbCount > UpgradeCost) { OrbCount = OrbCount - UpgradeCost; // subtract Cost from OrbCount HealthLevel = Level; // set health upgrade level MaxHP = (MaxHP + (MaxHP * 0.5f)); // Add 50% of current max HP for each upgrade HangarMenu->SetUpgradeLevel(HealthLevel, NextUpgradeCost); // set the new upgrade information within the hangar menu UpdateHangarMenu(); // update the hangar menu display } else { HangarMenu->NotifyError(); } } // Upgrade Thrusters void AEndlessReachHDPawn::UpgradeThrusters(int32 UpgradeCost, int32 Level, int32 NextUpgradeCost) { if (OrbCount > UpgradeCost) { OrbCount = OrbCount - UpgradeCost; // subtract Cost from OrbCount ThrustersLevel = Level; // set thrusters upgrade level MaxFuel = (MaxFuel + (MaxFuel * 0.5f)); // Add 50% of current max fuel for each upgrade HangarMenu->SetUpgradeLevel(ThrustersLevel, NextUpgradeCost); // set the new upgrade information within the hangar menu UpdateHangarMenu(); // update the hangar menu display } else { HangarMenu->NotifyError(); } } // Upgrade Main Cannon void AEndlessReachHDPawn::UpgradeCannon(int32 UpgradeCost, int32 Level, int32 NextUpgradeCost, float NewFireRate) { if (OrbCount > UpgradeCost) { OrbCount = OrbCount - UpgradeCost; // subtract Cost from OrbCount CannonLevel = Level; // set Cannon upgrade level FireRate = NewFireRate; // set new fire rate HangarMenu->SetUpgradeLevel(CannonLevel, NextUpgradeCost); // set the new upgrade information within the hangar menu UpdateHangarMenu(); // update the hangar menu display } else { HangarMenu->NotifyError(); } } // Upgrade Laser void AEndlessReachHDPawn::UpgradeLaser(int32 UpgradeCost, int32 Level, int32 NextUpgradeCost) { if (OrbCount > UpgradeCost) { // if laser charge max is less than five, increase max by one for each upgrade if (LaserChargeMax < 5) { LaserChargeMax++; } else { LaserChargeMax = 5; // force the laser charge max to five if it exceeds for some reason } OrbCount = OrbCount - UpgradeCost; // subtract Cost from OrbCount LaserLevel = Level; // set laser upgrade level HangarMenu->SetUpgradeLevel(LaserLevel, NextUpgradeCost); // set the new upgrade information within the hangar menu UpdateHangarMenu(); // update the hangar menu display } else { HangarMenu->NotifyError(); } } // Upgrade Magnet void AEndlessReachHDPawn::UpgradeMagnet(int32 UpgradeCost, int32 Level, int32 NextUpgradeCost, int32 NewMagnetRadius) { if (OrbCount > UpgradeCost) { OrbCount = OrbCount - UpgradeCost; // subtract Cost from OrbCount MagnetLevel = Level; // set magnet upgrade level MagnetRadius->SetSphereRadius(NewMagnetRadius); HangarMenu->SetUpgradeLevel(MagnetLevel, NextUpgradeCost); // set the new upgrade information within the hangar menu UpdateHangarMenu(); // update the hangar menu display } else { HangarMenu->NotifyError(); } } // Upgrade Bomb void AEndlessReachHDPawn::UpgradeBomb(int32 UpgradeCost, int32 Level, int32 NextUpgradeCost) { if (OrbCount > UpgradeCost) { // if bomb max is less than five, increase max by one for each upgrade if (BombMax < 5) { BombMax++; } else { BombMax = 5; // force the bomb max to five if it exceeds for some reason } OrbCount = OrbCount - UpgradeCost; // subtract Cost from OrbCount BombLevel = Level; // set bomb upgrade level HangarMenu->SetUpgradeLevel(BombLevel, NextUpgradeCost); // set the new upgrade information within the hangar menu UpdateHangarMenu(); // update the hangar menu display } else { HangarMenu->NotifyError(); } } // Action Button Control void AEndlessReachHDPawn::ActionInput() { if (bIsDocked) { if (HangarMenu) { if (HangarMenu->IsInViewport()) { if (!HangarMenu->bIsPromptingExit) { switch (HangarMenu->MenuIndex) { // SHIP TYPE UPGRADE - INDEX 0 case 0: switch (ShipTypeLevel) { case 0: //UpgradeCost = GetUpgradeCost(0, 0); break; case 1: //UpgradeCost = GetUpgradeCost(0, 1); break; case 2: //UpgradeCost = GetUpgradeCost(0, 2); break; case 3: //UpgradeCost = GetUpgradeCost(0, 3); break; case 4: //UpgradeCost = GetUpgradeCost(0, 4); break; case 5: //UpgradeCost = GetUpgradeCost(0, 5); break; } break; // HEALTH UPGRADE - INDEX 1 case 1: switch (HealthLevel) { case 0: UpgradeHealth(GetUpgradeCost(1, 0), 1, GetUpgradeCost(1, 1)); break; case 1: UpgradeHealth(GetUpgradeCost(1, 1), 2, GetUpgradeCost(1, 2)); break; case 2: UpgradeHealth(GetUpgradeCost(1, 2), 3, GetUpgradeCost(1, 3)); break; case 3: UpgradeHealth(GetUpgradeCost(1, 3), 4, GetUpgradeCost(1, 4)); break; case 4: UpgradeHealth(GetUpgradeCost(1, 4), 5, GetUpgradeCost(1, 5)); break; case 5: break; } break; // THURSTERS UPGRADE - INDEX 2 case 2: switch (ThrustersLevel) { case 0: UpgradeThrusters(GetUpgradeCost(2, 0), 1, GetUpgradeCost(2, 1)); break; case 1: UpgradeThrusters(GetUpgradeCost(2, 1), 2, GetUpgradeCost(2, 2)); break; case 2: UpgradeThrusters(GetUpgradeCost(2, 2), 3, GetUpgradeCost(2, 3)); break; case 3: UpgradeThrusters(GetUpgradeCost(2, 3), 4, GetUpgradeCost(2, 4)); break; case 4: UpgradeThrusters(GetUpgradeCost(2, 4), 5, GetUpgradeCost(2, 5)); break; case 5: break; } break; // MAIN CANNON UPGRADE - INDEX 3 case 3: switch (CannonLevel) { case 0: UpgradeCannon(GetUpgradeCost(3, 0), 1, GetUpgradeCost(3, 1), 0.175f); break; case 1: UpgradeCannon(GetUpgradeCost(3, 1), 2, GetUpgradeCost(3, 2), 0.15f); break; case 2: UpgradeCannon(GetUpgradeCost(3, 2), 3, GetUpgradeCost(3, 3), 0.125f); break; case 3: UpgradeCannon(GetUpgradeCost(3, 3), 4, GetUpgradeCost(3, 4), 0.1f); break; case 4: UpgradeCannon(GetUpgradeCost(3, 4), 5, GetUpgradeCost(3, 5), 0.075f); break; case 5: break; } break; // LASER UPGRADE - INDEX 4 case 4: switch (LaserLevel) { case 0: UpgradeLaser(GetUpgradeCost(4, 0), 1, GetUpgradeCost(4, 1)); bLaserUnlocked = true; break; case 1: UpgradeLaser(GetUpgradeCost(4, 1), 2, GetUpgradeCost(4, 2)); break; case 2: UpgradeLaser(GetUpgradeCost(4, 2), 3, GetUpgradeCost(4, 3)); break; case 3: UpgradeLaser(GetUpgradeCost(4, 3), 4, GetUpgradeCost(4, 4)); break; case 4: UpgradeLaser(GetUpgradeCost(4, 4), 5, GetUpgradeCost(4, 5)); break; case 5: break; } break; // MAGNET UPGRADE - INDEX 5 case 5: switch (MagnetLevel) { case 0: UpgradeMagnet(GetUpgradeCost(5, 0), 1, GetUpgradeCost(5, 1), 1000); bMagnetEnabled = true; break; case 1: UpgradeMagnet(GetUpgradeCost(5, 1), 2, GetUpgradeCost(5, 2), 1500); break; case 2: UpgradeMagnet(GetUpgradeCost(5, 2), 3, GetUpgradeCost(5, 3), 2000); break; case 3: UpgradeMagnet(GetUpgradeCost(5, 3), 4, GetUpgradeCost(5, 4), 2500); break; case 4: UpgradeMagnet(GetUpgradeCost(5, 4), 5, GetUpgradeCost(5, 5), 3000); break; case 5: break; } break; // MISSILES UPGRADE - INDEX 6 case 6: switch (MissilesLevel) { case 0: break; case 1: break; case 2: break; case 3: break; case 4: break; case 5: break; } break; // ENERGY SHIELD UPGRADE - INDEX 7 case 7: switch (ShieldLevel) { case 0: break; case 1: break; case 2: break; case 3: break; case 4: break; case 5: break; } break; // BOMB LEVEL - INDEX 8 case 8: switch (BombLevel) { case 0: UpgradeBomb(GetUpgradeCost(8, 0), 1, GetUpgradeCost(8, 1)); bBombsUnlocked = true; break; case 1: UpgradeBomb(GetUpgradeCost(8, 1), 2, GetUpgradeCost(8, 2)); break; case 2: UpgradeBomb(GetUpgradeCost(8, 2), 3, GetUpgradeCost(8, 3)); break; case 3: UpgradeBomb(GetUpgradeCost(8, 3), 4, GetUpgradeCost(8, 4)); break; case 4: UpgradeBomb(GetUpgradeCost(8, 4), 5, GetUpgradeCost(8, 5)); break; case 5: break; } break; } } else { switch (HangarMenu->ExitPromptIndex) { case 0: HangarMenu->InitLaunchSequence(); break; case 1: HangarMenu->ReturnToUpgradeMenu(); break; } } } } } } // Back Button Control void AEndlessReachHDPawn::BackInput() { if (bIsDocked) { if (HangarMenu) { if (HangarMenu->IsInViewport()) { if (!HangarMenu->bIsPromptingExit) { HangarMenu->PromptExit(); } } } } if (!bIsDocked) { if (bCanFireBomb) { if (BombCount > 0) { FireBomb(); } } } } // Show combat damage text function void AEndlessReachHDPawn::ShowCombatDamageText(bool bIsCritical, float Damage) { if (bIsCritical) { // CRITICAL DAMAGE CombatTextComponent->ShowCombatText(ECombatTextTypes::TT_CritDmg, UCommonLibrary::GetFloatAsTextWithPrecision(Damage, 0, true)); // show combat text } else { // STANDARD DAMAGE CombatTextComponent->ShowCombatText(ECombatTextTypes::TT_Damage, UCommonLibrary::GetFloatAsTextWithPrecision(Damage, 0, true)); // show combat text } } // Add Status Effect Icon to HUD void AEndlessReachHDPawn::AddStatusEffectIcon(FName ID, UTexture2D* Icon, bool bShouldBlink) { if (PlayerHUD) { //PlayerHUD-> } } // Generate reward drops for defeating an enemy or destroying an environment object void AEndlessReachHDPawn::GenerateDrops(bool bDropsOrbs, FVector TargetLocation) { FActorSpawnParameters Params; Params.OverrideLevel = GetLevel(); // make pickup drops spawn within the streaming level so they can be properly unloaded if (bDropsOrbs) { int32 DroppedOrbCount = FMath::RandRange(0, 15); // drop a random amount of orbs //int32 DroppedOrbCount = 100; // drop a static amount of orbs const FTransform Settings = FTransform(FRotator(0, 0, 0), TargetLocation, FVector(1, 1, 1)); // cache transform settings for (int32 i = 0; i < DroppedOrbCount; i++) { AOrb* Orb = GetWorld()->SpawnActor<AOrb>(AOrb::StaticClass(), Settings, Params); } } // FUEL CELL int32 FuelDropChance = FMath::RandRange(0, 9); // get a random number to determine whether or not this drop will include a fuel cell const FTransform FuelSettings = FTransform(FRotator(0, 0, 0), TargetLocation, FVector(0.25f, 0.25f, 0.25f)); // cache transform settings // drop fuel @ 50% if (FuelDropChance > 4) { AFuelCell* Fuel = GetWorld()->SpawnActor<AFuelCell>(AFuelCell::StaticClass(), FuelSettings, Params); // spawn fuel cell } // LASER CHARGE int32 LaserDropChance = FMath::RandRange(0, 9); // get a random number to determine whether or not this drop will include a laser charge const FTransform LaserSettings = FTransform(FRotator(0, 0, 0), TargetLocation, FVector(0.25f, 0.25f, 0.25f)); // cache transform settings // drop fuel @ 20% if (LaserDropChance > 7) { ALaser* Laser = GetWorld()->SpawnActor<ALaser>(ALaser::StaticClass(), LaserSettings, Params); // spawn laser charge } // BOMB CORE int32 BombCoreDropChance = FMath::RandRange(0, 9); // get a random number to determine whether or not this drop will include a bomb core const FTransform BombCoreSettings = FTransform(FRotator(0, 0, 0), TargetLocation, FVector(0.25f, 0.25f, 0.25f)); // cache transform settings // drop fuel @ 20% if (BombCoreDropChance > 7) { ABombCore* BombCore = GetWorld()->SpawnActor<ABombCore>(ABombCore::StaticClass(), BombCoreSettings, Params); // spawn fuel } }
36.167211
245
0.729425
Soverance
e6ec92140e30412542c541d2d928bb491d8a3d90
3,473
cpp
C++
solvers/src/solvers/CuSparseSolver.cpp
zurutech/stand
a341f691d991072a61d07aac6fa7e634e2d112d3
[ "Apache-2.0" ]
9
2022-01-17T07:30:49.000Z
2022-01-20T17:27:52.000Z
solvers/src/solvers/CuSparseSolver.cpp
zurutech/stand
a341f691d991072a61d07aac6fa7e634e2d112d3
[ "Apache-2.0" ]
null
null
null
solvers/src/solvers/CuSparseSolver.cpp
zurutech/stand
a341f691d991072a61d07aac6fa7e634e2d112d3
[ "Apache-2.0" ]
null
null
null
/* Copyright 2022 Zuru Tech HK Limited. * * 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 <chrono> #include <functional> #include <vector> #include <cuda_runtime.h> #include <cusolverSp.h> #include <cusparse_v2.h> #include <solvers/CuSparseSolver.hpp> #include <solvers/SparseSystem.hpp> namespace solvers { Eigen::VectorXd CuSparseSolver::solve(const SparseSystem& system, double& duration) const { auto [crow_index, col_index, values, b] = system.toStdCSR(); const auto n = static_cast<int>(b.size()); const auto nnz = static_cast<int>(values.size()); cusparseMatDescr_t A_description = nullptr; cusparseCreateMatDescr(&A_description); int* cuda_crow_index; int* cuda_col_index; double* cuda_values; double* cuda_b; double* cuda_sol; cusolverSpHandle_t cusolver_handler = nullptr; cusolverSpCreate(&cusolver_handler); cudaMalloc(reinterpret_cast<void**>(&cuda_values), sizeof(double) * nnz); cudaMalloc(reinterpret_cast<void**>(&cuda_crow_index), sizeof(int) * (n + 1)); cudaMalloc(reinterpret_cast<void**>(&cuda_col_index), sizeof(int) * nnz); cudaMalloc(reinterpret_cast<void**>(&cuda_b), sizeof(double) * n); cudaMalloc(reinterpret_cast<void**>(&cuda_sol), sizeof(double) * n); cudaMemcpy(cuda_values, values.data(), sizeof(double) * nnz, cudaMemcpyHostToDevice); cudaMemcpy(cuda_crow_index, crow_index.data(), sizeof(int) * (n + 1), cudaMemcpyHostToDevice); cudaMemcpy(cuda_col_index, col_index.data(), sizeof(int) * nnz, cudaMemcpyHostToDevice); cudaMemcpy(cuda_b, b.data(), sizeof(double) * n, cudaMemcpyHostToDevice); const std::vector<std::function<cusolverStatus_t( cusolverSpHandle_t, int, int, cusparseMatDescr_t, const double*, const int*, const int*, const double*, double, int, double*, int*)>> solver_function = {cusolverSpDcsrlsvqr, cusolverSpDcsrlsvchol}; const double tolerance = 1e-12; int singularity = 0; std::chrono::time_point start = std::chrono::high_resolution_clock::now(); solver_function[static_cast<int>(_method)]( cusolver_handler, n, nnz, A_description, cuda_values, cuda_crow_index, cuda_col_index, cuda_b, tolerance, static_cast<int>(_reorder), cuda_sol, &singularity); cudaDeviceSynchronize(); std::chrono::time_point end = std::chrono::high_resolution_clock::now(); Eigen::VectorXd result(n); cudaMemcpy(result.data(), cuda_sol, sizeof(double) * n, cudaMemcpyDeviceToHost); cudaFree(cuda_crow_index); cudaFree(cuda_col_index); cudaFree(cuda_values); cudaFree(cuda_b); cudaFree(cuda_sol); cusolverSpDestroy(cusolver_handler); cudaDeviceReset(); std::chrono::duration<double> time_difference = end - start; duration = time_difference.count(); return result; } } // namespace solvers
37.344086
80
0.69738
zurutech
e6f062fcb872ce77d5c9e3e6edab326aed749883
3,943
cpp
C++
XRVessels/XR2Ravenstar/XR2Ravenstar/XR2PostSteps.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
10
2021-08-20T05:49:10.000Z
2022-01-07T13:00:20.000Z
XRVessels/XR2Ravenstar/XR2Ravenstar/XR2PostSteps.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
null
null
null
XRVessels/XR2Ravenstar/XR2Ravenstar/XR2PostSteps.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
4
2021-09-11T12:08:01.000Z
2022-02-09T00:16:19.000Z
/** XR Vessel add-ons for OpenOrbiter Space Flight Simulator Copyright (C) 2006-2021 Douglas Beachy This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Email: mailto:doug.beachy@outlook.com Web: https://www.alteaaerospace.com **/ // ============================================================== // XR2Ravenstar implementation class // // XR2PrePostSteps.cpp // Class defining custom clbkPostStep callbacks for the XR2 Ravenstar // ============================================================== #include "XR2PostSteps.h" #include "XR2AreaIDs.h" #include "XR2Areas.h" //--------------------------------------------------------------------------- XR2AnimationPostStep::XR2AnimationPostStep(XR2Ravenstar &vessel) : XR2PrePostStep(vessel) { } void XR2AnimationPostStep::clbkPrePostStep(const double simt, const double simdt, const double mjd) { // animate doors that require hydraulic pressure if (GetXR2().CheckHydraulicPressure(false, false)) // do not log a warning nor play an error beep here! We are merely querying the state. { AnimateBayDoors(simt, simdt, mjd); } } void XR2AnimationPostStep::AnimateBayDoors(const double simt, const double simdt, const double mjd) { // animate the payload bay doors if (GetXR2().bay_status >= DoorStatus::DOOR_CLOSING) // closing or opening { double da = simdt * BAY_OPERATING_SPEED; if (GetXR2().bay_status == DoorStatus::DOOR_CLOSING) { if (GetXR2().bay_proc > 0.0) GetXR2().bay_proc = max(0.0, GetXR2().bay_proc - da); else { GetXR2().bay_status = DoorStatus::DOOR_CLOSED; GetVessel().TriggerRedrawArea(AID_BAYDOORSINDICATOR); } } else // door is opening or open { if (GetXR2().bay_proc < 1.0) GetXR2().bay_proc = min (1.0, GetXR2().bay_proc + da); else { GetXR2().bay_status = DoorStatus::DOOR_OPEN; GetVessel().TriggerRedrawArea(AID_BAYDOORSINDICATOR); } } GetXR2().SetXRAnimation(GetXR2().anim_bay, GetXR2().bay_proc); } } //--------------------------------------------------------------------------- XR2DoorSoundsPostStep::XR2DoorSoundsPostStep(XR2Ravenstar &vessel) : DoorSoundsPostStep(vessel) { // set transition state processing to FALSE so we don't play an initial thump when a scenario loads #define INIT_DOORSOUND(idx, doorStatus, xr1SoundID, label) \ m_doorSounds[idx].pDoorStatus = &(GetXR2().doorStatus); \ m_doorSounds[idx].prevDoorStatus = DoorStatus::NOT_SET; \ m_doorSounds[idx].soundID = GetXR1().xr1SoundID; \ m_doorSounds[idx].processAPUTransitionState = false; \ m_doorSounds[idx].pLabel = label // initialize door sound structures for all new doors INIT_DOORSOUND(0, bay_status, dPayloadBayDoors, "Bay Doors"); } void XR2DoorSoundsPostStep::clbkPrePostStep(const double simt, const double simdt, const double mjd) { // call the superclass to handle all the normal doors DoorSoundsPostStep::clbkPrePostStep(simt, simdt, mjd); // handle all our custom door sounds const int doorCount = (sizeof(m_doorSounds) / sizeof(DoorSound)); for (int i=0; i < doorCount; i++) PlayDoorSound(m_doorSounds[i], simt); }
37.198113
146
0.632767
dbeachy1
e6f0d9a145d8f4d7c84c00ba9fa45928e9a5c638
7,374
cc
C++
src/tests/grid/test_distribution_regular_bands.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
67
2018-03-01T06:56:49.000Z
2022-03-08T18:44:47.000Z
src/tests/grid/test_distribution_regular_bands.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
93
2018-12-07T17:38:04.000Z
2022-03-31T10:04:51.000Z
src/tests/grid/test_distribution_regular_bands.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
33
2018-02-28T17:06:19.000Z
2022-01-20T12:12:27.000Z
/* * (C) Copyright 2013 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ #include <algorithm> #include <cstdint> #include <iomanip> #include <sstream> #include "atlas/array.h" #include "atlas/field.h" #include "atlas/functionspace.h" #include "atlas/grid.h" #include "atlas/grid/detail/distribution/BandsDistribution.h" #include "atlas/grid/detail/distribution/SerialDistribution.h" #include "atlas/parallel/mpi/mpi.h" #include "atlas/parallel/omp/omp.h" #include "atlas/util/Config.h" #include "tests/AtlasTestEnvironment.h" using Grid = atlas::Grid; using Config = atlas::util::Config; namespace atlas { namespace test { atlas::FieldSet getIJ(const atlas::functionspace::StructuredColumns& fs) { atlas::FieldSet ij; // auto i = atlas::array::make_view<int, 1>( fs.index_i() ); // auto j = atlas::array::make_view<int, 1>( fs.index_j() ); ij.add(fs.index_i()); ij.add(fs.index_j()); return ij; } //----------------------------------------------------------------------------- CASE("test_bands") { int nproc = mpi::size(); StructuredGrid grid = Grid("L200x101"); grid::Distribution dist(grid, atlas::util::Config("type", "checkerboard") | Config("bands", nproc)); for (int i = 1; i < grid.size(); i++) { EXPECT(dist.partition(i - 1) <= dist.partition(i)); } } CASE("test_regular_bands") { int nproc = mpi::size(); std::vector<std::string> gridnames = {"L40x21", "L40x20", "Slat100x50"}; for (auto gridname : gridnames) { SECTION(gridname) { auto grid = RegularGrid(gridname); const int nx = grid.nx(); const int ny = grid.ny(); bool equivalent_with_checkerboard = (ny % nproc) == 0; // Compare regular band & checkerboard distributions when possible grid::Distribution checkerboard(grid, grid::Partitioner("checkerboard", Config("bands", nproc))); grid::Distribution regularbands(grid, grid::Partitioner("regular_bands")); EXPECT(regularbands.footprint() < 100); const auto& nb_pts2 = regularbands.nb_pts(); int count = 0; for (int i = 0; i < grid.size(); i++) { if (regularbands.partition(i) == mpi::rank()) { count++; } } EXPECT_EQ(count, nb_pts2[mpi::rank()]); if (equivalent_with_checkerboard) { for (int i = 0; i < grid.size(); i++) { EXPECT_EQ(checkerboard.partition(i), regularbands.partition(i)); } } else { Log::warning() << "WARNING: checkerboard not expected to be equal!" << std::endl; } // Expect each points with constant latitude to be on the same partition as the first on each latitude. for (int iy = 0, jglo = 0; iy < ny; iy++) { int jglo0 = jglo; for (int ix = 0; ix < nx; ix++, jglo++) { EXPECT_EQ(regularbands.partition(jglo), regularbands.partition(jglo0)); } } functionspace::StructuredColumns fs_checkerboard(grid, checkerboard, Config("halo", 1) | Config("periodic_points", true)); functionspace::StructuredColumns fs_regularbands(grid, regularbands, Config("halo", 1) | Config("periodic_points", true)); auto ij1 = getIJ(fs_checkerboard); auto ij2 = getIJ(fs_regularbands); fs_checkerboard.haloExchange(ij1); fs_regularbands.haloExchange(ij2); if (equivalent_with_checkerboard) { EXPECT_EQ(fs_regularbands.size(), fs_checkerboard.size()); EXPECT_EQ(fs_regularbands.sizeOwned(), fs_checkerboard.sizeOwned()); auto i1 = array::make_view<idx_t, 1>(ij1[0]); auto j1 = array::make_view<idx_t, 1>(ij1[1]); auto i2 = array::make_view<idx_t, 1>(ij2[0]); auto j2 = array::make_view<idx_t, 1>(ij2[1]); for (int k = 0; k < fs_checkerboard.sizeOwned(); k++) { EXPECT_EQ(i1[k], i2[k]); EXPECT_EQ(j1[k], j2[k]); } } for (int j = fs_regularbands.j_begin_halo(); j < fs_regularbands.j_end_halo(); j++) { EXPECT_EQ(fs_regularbands.i_begin_halo(j), -1); EXPECT_EQ(fs_regularbands.i_end_halo(j), nx + 2); } } } } CASE("test regular_bands performance test") { // auto grid = StructuredGrid( "L40000x20000" ); //-- > test takes too long( less than 15 seconds ) // Example timings for L40000x20000: // └─test regular_bands performance test │ 1 │ 11.90776s // ├─inline access │ 1 │ 3.52238s // ├─virtual access │ 1 │ 4.11881s // └─virtual cached access │ 1 │ 4.02159s auto grid = StructuredGrid("L5000x2500"); // -> negligible time. auto dist = grid::Distribution(grid, grid::Partitioner("regular_bands")); auto& dist_direct = dynamic_cast<const grid::detail::distribution::BandsDistribution<int32_t>&>(*dist.get()); // Trick to prevent the compiler from compiling out a loop if it sees the result was not used. struct DoNotCompileOut { int x = 0; ~DoNotCompileOut() { Log::debug() << x << std::endl; } ATLAS_ALWAYS_INLINE void operator()(int p) { x = p; } } do_not_compile_out; gidx_t size = grid.size(); ATLAS_TRACE_SCOPE("inline access") { for (gidx_t n = 0; n < size; ++n) { // inline function call do_not_compile_out(dist_direct.function(n)); } } ATLAS_TRACE_SCOPE("virtual access") { for (gidx_t n = 0; n < size; ++n) { // virtual function call do_not_compile_out(dist.partition(n)); } } ATLAS_TRACE_SCOPE("virtual cached access") { gidx_t n = 0; grid::Distribution::partition_t part(grid.nxmax()); for (idx_t j = 0; j < grid.ny(); ++j) { const idx_t nx = grid.nx(j); dist.partition(n, n + nx, part); // this is one virtual call, which in turn has inline-access for nx(j) evaluations int* P = part.data(); for (idx_t i = 0; i < nx; ++i) { do_not_compile_out(P[i]); } n += grid.nx(j); } } } CASE("test regular_bands with a very large grid") { auto grid = StructuredGrid(sizeof(atlas::idx_t) == 4 ? "L40000x20000" : "L160000x80000"); auto dist = grid::Distribution(grid, grid::Partitioner("regular_bands")); } //----------------------------------------------------------------------------- } // namespace test } // namespace atlas int main(int argc, char** argv) { return atlas::test::run(argc, argv); }
35.282297
115
0.555194
twsearle
e6f180d9dc9c90ff8c5aea882d4336024b7c6b0b
2,876
cpp
C++
etc/berlekamp_massey with kitamasa.cpp
jinhan814/algorithms-implementation
b5185f98c5d5d34c0f98de645e5b755fcf75c120
[ "MIT" ]
null
null
null
etc/berlekamp_massey with kitamasa.cpp
jinhan814/algorithms-implementation
b5185f98c5d5d34c0f98de645e5b755fcf75c120
[ "MIT" ]
null
null
null
etc/berlekamp_massey with kitamasa.cpp
jinhan814/algorithms-implementation
b5185f98c5d5d34c0f98de645e5b755fcf75c120
[ "MIT" ]
null
null
null
/* * BOJ 13976 * https://www.acmicpc.net/problem/13976 * reference : https://www.secmem.org/blog/2019/05/17/BerlekampMassey/, https://justicehui.github.io/hard-algorithm/2021/03/13/kitamasa/ */ #include <bits/stdc++.h> #define fastio cin.tie(0)->sync_with_stdio(0) using namespace std; constexpr int MOD = 1e9 + 7; using ll = long long; using poly = vector<ll>; ll Pow(ll x, ll n) { ll ret = 1; for (; n; n >>= 1) { if (n & 1) ret = ret * x % MOD; x = x * x % MOD; } return ret; } poly BerlekampMassey(const poly v) { poly ls, ret; ll lf, ld; for (ll i = 0, t = 0; i < v.size(); i++, t = 0) { for (ll j = 0; j < ret.size(); j++) t = (t + 1ll * v[i - j - 1] * ret[j]) % MOD; if ((t - v[i]) % MOD == 0) continue; if (ret.empty()) { ret.resize(i + 1), lf = i, ld = (t - v[i]) % MOD; continue; } const ll k = -(v[i] - t) * Pow(ld, MOD - 2) % MOD; poly cur(i - lf - 1); cur.push_back(k); for (const auto& j : ls) cur.push_back(-j * k % MOD); if (cur.size() < ret.size()) cur.resize(ret.size()); for (ll j = 0; j < ret.size(); j++) cur[j] = (cur[j] + ret[j]) % MOD; if (i - lf + (ll)ls.size() >= (ll)ret.size()) ls = ret, lf = i, ld = (t - v[i]) % MOD; ret = cur; } for (auto& i : ret) i = (i % MOD + MOD) % MOD; reverse(ret.begin(), ret.end()); return ret; } struct { static int Mod(ll x) { x %= MOD; return x < 0 ? x + MOD : x; } poly Mul(const poly& a, const poly& b) { poly ret(a.size() + b.size() - 1); for (int i = 0; i < a.size(); i++) for (int j = 0; j < b.size(); j++) { ret[i + j] = (ret[i + j] + a[i] * b[j]) % MOD; } return ret; } poly Div(const poly& a, const poly& b) { poly ret(a.begin(), a.end()); for (int i = ret.size() - 1; i >= b.size() - 1; i--) for (int j = 0; j < b.size(); j++) { ret[i + j - b.size() + 1] = Mod(ret[i + j - b.size() + 1] - ret[i] * b[j]); } ret.resize(b.size() - 1); return ret; } ll operator() (poly rec, poly dp, ll n) { if (dp.size() > rec.size()) dp.resize(rec.size()); poly d = { 1 }, xn = { 0, 1 }; poly f(rec.size() + 1); f.back() = 1; for (int i = 0; i < rec.size(); i++) f[i] = Mod(-rec[i]); while (n) { if (n & 1) d = Div(Mul(d, xn), f); n >>= 1; xn = Div(Mul(xn, xn), f); } ll ret = 0; for (int i = 0; i < dp.size(); i++) ret = Mod(ret + dp[i] * d[i]); return ret; } } Kitamasa; int main() { fastio; poly dp = { 0, 3, 0, 11, 0, 41, 0, 153, 0, 571 }; poly rec = BerlekampMassey(dp); ll n; cin >> n; cout << Kitamasa(rec, dp, n - 1) << '\n'; }
34.238095
137
0.439847
jinhan814
e6f3a9d714382f24aa494d9f82a0f0b7864e084c
2,747
cpp
C++
Snake/AIs/StupidAI/StupidAI.cpp
Madsy/GameAutomata
e32f0442f3238c6110a39dff509244dbec2d60be
[ "BSD-3-Clause" ]
2
2015-08-17T17:22:40.000Z
2015-11-17T05:15:20.000Z
Snake/AIs/StupidAI/StupidAI.cpp
Madsy/GameAutomata
e32f0442f3238c6110a39dff509244dbec2d60be
[ "BSD-3-Clause" ]
null
null
null
Snake/AIs/StupidAI/StupidAI.cpp
Madsy/GameAutomata
e32f0442f3238c6110a39dff509244dbec2d60be
[ "BSD-3-Clause" ]
null
null
null
#include <algorithm> #include <cstdio> #include <iostream> #include "../../shared/SnakeGame.hpp" Direction AIMove(int player, SnakeGameInfo& state) { Point head, newHead, foodDelta; const Direction startMoves[4] = { Up, Down, Left, Right }; Direction d; std::vector<Direction> possibleMoves; head = state.snakes[player].bodyParts[0]; foodDelta.x = state.foodPosition.x - head.x; foodDelta.y = state.foodPosition.y - head.y; if(foodDelta.x < 0){ possibleMoves.push_back(Left); } else if(foodDelta.x > 0){ possibleMoves.push_back(Right); } if(foodDelta.y < 0){ possibleMoves.push_back(Up); } else if(foodDelta.y > 0){ possibleMoves.push_back(Down); } /* Try to get closer to the food first */ if(!possibleMoves.empty()){ std::random_shuffle(possibleMoves.begin(), possibleMoves.end()); for(int i=0; i<possibleMoves.size(); ++i){ newHead = snakeComputeNewHead(head, possibleMoves[i]); bool collideWithBorder = snakeIsCellBorder(newHead.x, newHead.y, state.level); bool collideWithSnake = snakeIsCellSnake(newHead.x, newHead.y, -1, state.snakes); if(!collideWithBorder && !collideWithSnake){ return possibleMoves[i]; } } } /* If none of the directions that brings us closer to the food is safe, then try any safe direction. If we die anyway (for example, spiral of death), return Up as a last resort */ possibleMoves.clear(); for(int i = 0; i < 4; ++i){ newHead = snakeComputeNewHead(head, startMoves[i]); bool collideWithBorder = snakeIsCellBorder(newHead.x, newHead.y, state.level); bool collideWithSnake = snakeIsCellSnake(newHead.x, newHead.y, -1, state.snakes); /* If cell is free of walls and snakes, it is a possible move */ if(!collideWithBorder && !collideWithSnake) possibleMoves.push_back(startMoves[i]); } std::random_shuffle(possibleMoves.begin(), possibleMoves.end()); /* If no moves are possible, go up and die */ if(possibleMoves.empty()) d = Up; else d = possibleMoves[0]; return d; } void readGameState(SnakeGameInfo& state) { std::vector<std::string> strm; std::string line; char szbuf[512]; while(std::getline(std::cin, line)){ if(line == "END") break; strm.push_back(line); }; snakeSerializeStreamToState(state, strm); } int main(int argc, char* argv[]) { SnakeGameInfo state; Direction d; readGameState(state); while(state.snakes[state.currentPlayer].alive){ d = AIMove(state.currentPlayer, state); switch(d){ case Up: std::cout << 'u'; break; case Down: std::cout << 'd'; break; case Left: std::cout << 'l'; break; default: std::cout << 'r'; break; } std::cout.flush(); readGameState(state); } return 0; }
29.858696
99
0.670186
Madsy
e6f3b6ad777fa3f65581e10e8cc18bd21f3e1082
18,343
hpp
C++
include/GlobalNamespace/SliderInteractionManager.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/SliderInteractionManager.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/SliderInteractionManager.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Including type: ColorType #include "GlobalNamespace/ColorType.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: BeatmapObjectManager class BeatmapObjectManager; // Forward declaring type: SliderController class SliderController; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; // Forward declaring type: Action class Action; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Forward declaring type: SliderInteractionManager class SliderInteractionManager; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::GlobalNamespace::SliderInteractionManager); DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::SliderInteractionManager*, "", "SliderInteractionManager"); // Type namespace: namespace GlobalNamespace { // Size: 0x48 #pragma pack(push, 1) // Autogenerated type: SliderInteractionManager // [TokenAttribute] Offset: FFFFFFFF class SliderInteractionManager : public ::UnityEngine::MonoBehaviour { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private ColorType _colorType // Size: 0x4 // Offset: 0x18 ::GlobalNamespace::ColorType colorType; // Field size check static_assert(sizeof(::GlobalNamespace::ColorType) == 0x4); // Padding between fields: colorType and: beatmapObjectManager char __padding0[0x4] = {}; // [InjectAttribute] Offset: 0x124FC68 // private readonly BeatmapObjectManager _beatmapObjectManager // Size: 0x8 // Offset: 0x20 ::GlobalNamespace::BeatmapObjectManager* beatmapObjectManager; // Field size check static_assert(sizeof(::GlobalNamespace::BeatmapObjectManager*) == 0x8); // private System.Single <saberInteractionParam>k__BackingField // Size: 0x4 // Offset: 0x28 float saberInteractionParam; // Field size check static_assert(sizeof(float) == 0x4); // Padding between fields: saberInteractionParam and: sliderWasAddedToActiveSlidersEvent char __padding2[0x4] = {}; // private System.Action`1<System.Single> sliderWasAddedToActiveSlidersEvent // Size: 0x8 // Offset: 0x30 ::System::Action_1<float>* sliderWasAddedToActiveSlidersEvent; // Field size check static_assert(sizeof(::System::Action_1<float>*) == 0x8); // private System.Action allSliderWereRemovedFromActiveSlidersEvent // Size: 0x8 // Offset: 0x38 ::System::Action* allSliderWereRemovedFromActiveSlidersEvent; // Field size check static_assert(sizeof(::System::Action*) == 0x8); // private readonly System.Collections.Generic.List`1<SliderController> _activeSliders // Size: 0x8 // Offset: 0x40 ::System::Collections::Generic::List_1<::GlobalNamespace::SliderController*>* activeSliders; // Field size check static_assert(sizeof(::System::Collections::Generic::List_1<::GlobalNamespace::SliderController*>*) == 0x8); public: // Deleting conversion operator: operator ::System::IntPtr constexpr operator ::System::IntPtr() const noexcept = delete; // Get instance field reference: private ColorType _colorType ::GlobalNamespace::ColorType& dyn__colorType(); // Get instance field reference: private readonly BeatmapObjectManager _beatmapObjectManager ::GlobalNamespace::BeatmapObjectManager*& dyn__beatmapObjectManager(); // Get instance field reference: private System.Single <saberInteractionParam>k__BackingField float& dyn_$saberInteractionParam$k__BackingField(); // Get instance field reference: private System.Action`1<System.Single> sliderWasAddedToActiveSlidersEvent ::System::Action_1<float>*& dyn_sliderWasAddedToActiveSlidersEvent(); // Get instance field reference: private System.Action allSliderWereRemovedFromActiveSlidersEvent ::System::Action*& dyn_allSliderWereRemovedFromActiveSlidersEvent(); // Get instance field reference: private readonly System.Collections.Generic.List`1<SliderController> _activeSliders ::System::Collections::Generic::List_1<::GlobalNamespace::SliderController*>*& dyn__activeSliders(); // public ColorType get_colorType() // Offset: 0x2AA189C ::GlobalNamespace::ColorType get_colorType(); // public System.Single get_saberInteractionParam() // Offset: 0x2AA18A4 float get_saberInteractionParam(); // private System.Void set_saberInteractionParam(System.Single value) // Offset: 0x2AA18AC void set_saberInteractionParam(float value); // public System.Void add_sliderWasAddedToActiveSlidersEvent(System.Action`1<System.Single> value) // Offset: 0x2AA1524 void add_sliderWasAddedToActiveSlidersEvent(::System::Action_1<float>* value); // public System.Void remove_sliderWasAddedToActiveSlidersEvent(System.Action`1<System.Single> value) // Offset: 0x2AA173C void remove_sliderWasAddedToActiveSlidersEvent(::System::Action_1<float>* value); // public System.Void add_allSliderWereRemovedFromActiveSlidersEvent(System.Action value) // Offset: 0x2AA15C8 void add_allSliderWereRemovedFromActiveSlidersEvent(::System::Action* value); // public System.Void remove_allSliderWereRemovedFromActiveSlidersEvent(System.Action value) // Offset: 0x2AA17E0 void remove_allSliderWereRemovedFromActiveSlidersEvent(::System::Action* value); // protected System.Void Start() // Offset: 0x2AA18B4 void Start(); // protected System.Void OnDestroy() // Offset: 0x2AA198C void OnDestroy(); // protected System.Void Update() // Offset: 0x2AA1A78 void Update(); // private System.Void AddActiveSlider(SliderController newSliderController) // Offset: 0x2AA1BE0 void AddActiveSlider(::GlobalNamespace::SliderController* newSliderController); // private System.Void RemoveActiveSlider(SliderController sliderController) // Offset: 0x2AA1DA4 void RemoveActiveSlider(::GlobalNamespace::SliderController* sliderController); // private System.Void HandleSliderWasSpawned(SliderController sliderController) // Offset: 0x2AA1E3C void HandleSliderWasSpawned(::GlobalNamespace::SliderController* sliderController); // private System.Void HandleSliderWasDespawned(SliderController sliderController) // Offset: 0x2AA1E74 void HandleSliderWasDespawned(::GlobalNamespace::SliderController* sliderController); // public System.Void .ctor() // Offset: 0x2AA1EAC // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static SliderInteractionManager* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::SliderInteractionManager::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<SliderInteractionManager*, creationType>())); } }; // SliderInteractionManager #pragma pack(pop) static check_size<sizeof(SliderInteractionManager), 64 + sizeof(::System::Collections::Generic::List_1<::GlobalNamespace::SliderController*>*)> __GlobalNamespace_SliderInteractionManagerSizeCheck; static_assert(sizeof(SliderInteractionManager) == 0x48); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::get_colorType // Il2CppName: get_colorType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::ColorType (GlobalNamespace::SliderInteractionManager::*)()>(&GlobalNamespace::SliderInteractionManager::get_colorType)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "get_colorType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::get_saberInteractionParam // Il2CppName: get_saberInteractionParam template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::SliderInteractionManager::*)()>(&GlobalNamespace::SliderInteractionManager::get_saberInteractionParam)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "get_saberInteractionParam", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::set_saberInteractionParam // Il2CppName: set_saberInteractionParam template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)(float)>(&GlobalNamespace::SliderInteractionManager::set_saberInteractionParam)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "set_saberInteractionParam", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::add_sliderWasAddedToActiveSlidersEvent // Il2CppName: add_sliderWasAddedToActiveSlidersEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)(::System::Action_1<float>*)>(&GlobalNamespace::SliderInteractionManager::add_sliderWasAddedToActiveSlidersEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "add_sliderWasAddedToActiveSlidersEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::remove_sliderWasAddedToActiveSlidersEvent // Il2CppName: remove_sliderWasAddedToActiveSlidersEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)(::System::Action_1<float>*)>(&GlobalNamespace::SliderInteractionManager::remove_sliderWasAddedToActiveSlidersEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "remove_sliderWasAddedToActiveSlidersEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::add_allSliderWereRemovedFromActiveSlidersEvent // Il2CppName: add_allSliderWereRemovedFromActiveSlidersEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)(::System::Action*)>(&GlobalNamespace::SliderInteractionManager::add_allSliderWereRemovedFromActiveSlidersEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "add_allSliderWereRemovedFromActiveSlidersEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::remove_allSliderWereRemovedFromActiveSlidersEvent // Il2CppName: remove_allSliderWereRemovedFromActiveSlidersEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)(::System::Action*)>(&GlobalNamespace::SliderInteractionManager::remove_allSliderWereRemovedFromActiveSlidersEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "remove_allSliderWereRemovedFromActiveSlidersEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::Start // Il2CppName: Start template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)()>(&GlobalNamespace::SliderInteractionManager::Start)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::OnDestroy // Il2CppName: OnDestroy template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)()>(&GlobalNamespace::SliderInteractionManager::OnDestroy)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::Update // Il2CppName: Update template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)()>(&GlobalNamespace::SliderInteractionManager::Update)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::AddActiveSlider // Il2CppName: AddActiveSlider template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)(::GlobalNamespace::SliderController*)>(&GlobalNamespace::SliderInteractionManager::AddActiveSlider)> { static const MethodInfo* get() { static auto* newSliderController = &::il2cpp_utils::GetClassFromName("", "SliderController")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "AddActiveSlider", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{newSliderController}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::RemoveActiveSlider // Il2CppName: RemoveActiveSlider template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)(::GlobalNamespace::SliderController*)>(&GlobalNamespace::SliderInteractionManager::RemoveActiveSlider)> { static const MethodInfo* get() { static auto* sliderController = &::il2cpp_utils::GetClassFromName("", "SliderController")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "RemoveActiveSlider", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sliderController}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::HandleSliderWasSpawned // Il2CppName: HandleSliderWasSpawned template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)(::GlobalNamespace::SliderController*)>(&GlobalNamespace::SliderInteractionManager::HandleSliderWasSpawned)> { static const MethodInfo* get() { static auto* sliderController = &::il2cpp_utils::GetClassFromName("", "SliderController")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "HandleSliderWasSpawned", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sliderController}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::HandleSliderWasDespawned // Il2CppName: HandleSliderWasDespawned template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderInteractionManager::*)(::GlobalNamespace::SliderController*)>(&GlobalNamespace::SliderInteractionManager::HandleSliderWasDespawned)> { static const MethodInfo* get() { static auto* sliderController = &::il2cpp_utils::GetClassFromName("", "SliderController")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderInteractionManager*), "HandleSliderWasDespawned", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sliderController}); } }; // Writing MetadataGetter for method: GlobalNamespace::SliderInteractionManager::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
59.749186
239
0.774737
RedBrumbler
e6f765c2ca1a4942ae3cb81a65088395e91ac415
2,341
cpp
C++
core/projects/redmax/Body/BodyDesignParameters.cpp
eanswer/DiffHand
d7b9c068b7fa364935f3dc9d964d63e1e3a774c8
[ "MIT" ]
36
2021-07-13T19:28:50.000Z
2022-01-09T14:52:15.000Z
core/projects/redmax/Body/BodyDesignParameters.cpp
eanswer/DiffHand
d7b9c068b7fa364935f3dc9d964d63e1e3a774c8
[ "MIT" ]
null
null
null
core/projects/redmax/Body/BodyDesignParameters.cpp
eanswer/DiffHand
d7b9c068b7fa364935f3dc9d964d63e1e3a774c8
[ "MIT" ]
6
2021-07-15T02:06:29.000Z
2021-11-23T03:06:14.000Z
#include "Body/BodyDesignParameters.h" #include "Body/Body.h" #include "Utils.h" namespace redmax { BodyDesignParameters::BodyDesignParameters( Body* body, DesignParameterType type, bool active, int ndof) : DesignParameters(type, active, ndof) { if (_type != DesignParameterType::TYPE2 && _type != DesignParameterType::TYPE3 && _type != DesignParameterType::TYPE4 && _type != DesignParameterType::TYPE6) { throw_error("[Error] Body can only have type II, III, IV design parameters"); } _body = body; } void BodyDesignParameters::update_params() { if (_type == DesignParameterType::TYPE2) { _params = math::flatten_E(_body->_E_ji); } else if (_type == DesignParameterType::TYPE3) { std::vector<Vector3> contacts = _body->get_contact_points(); for (int i = 0;i < contacts.size();i++) { _params.segment(i * 3, 3) = contacts[i]; } } else if (_type == DesignParameterType::TYPE4) { _params[0] = _body->_mass; _params.tail(3) = _body->_Inertia.head(3); } else if (_type == DesignParameterType::TYPE6) { _params[0] = _body->_contact_scale; } else { throw_error("[Error] Joint can only have type I, V design parameters"); } } void BodyDesignParameters::update_params(const VectorX params) { if (!_active) return; for (int i = 0;i < _ndof;i++) { _params[i] = params[_param_index[i]]; } if (_type == DesignParameterType::TYPE2) { _body->_E_ji = math::compose_E(_params); _body->_E_ij = math::Einv(_body->_E_ji); _body->_A_ji = math::Ad(_body->_E_ji); _body->_A_ij = math::Ad(_body->_E_ij); } else if (_type == DesignParameterType::TYPE3) { for (int i = 0;i < _body->_contact_points.size();i++) { for (int j = 0;j < 3;j++) _body->_contact_points[i](j) = _params[i * 3 + j]; } } else if (_type == DesignParameterType::TYPE4) { _body->_mass = _params[0]; _body->_Inertia.head(3) = _params.tail(3); _body->_Inertia.tail(3).setConstant(_params[0]); } else if (_type == DesignParameterType::TYPE6) { _body->_contact_scale = _params(0); } else { throw_error("[Error] Joint can only have type I, V design parameters"); } } }
34.426471
85
0.604443
eanswer
e6fb7a55a534790d4ee470e7dc39cc86affa0e9e
721
hpp
C++
sprout/tuple/indexes.hpp
jwakely/Sprout
a64938fad0a64608f22d39485bc55a1e0dc07246
[ "BSL-1.0" ]
1
2018-09-21T23:50:44.000Z
2018-09-21T23:50:44.000Z
sprout/tuple/indexes.hpp
jwakely/Sprout
a64938fad0a64608f22d39485bc55a1e0dc07246
[ "BSL-1.0" ]
null
null
null
sprout/tuple/indexes.hpp
jwakely/Sprout
a64938fad0a64608f22d39485bc55a1e0dc07246
[ "BSL-1.0" ]
null
null
null
#ifndef SPROUT_TUPLE_INDEXES_HPP #define SPROUT_TUPLE_INDEXES_HPP #include <sprout/config.hpp> #include <sprout/index_tuple.hpp> #include <sprout/index_tuple/detail/make_indexes_helper.hpp> #include <sprout/tuple/tuple.hpp> namespace sprout { namespace tuples { // // tuple_indexes // template<typename Tuple> struct tuple_indexes : public sprout::detail::make_indexes_helper< sprout::index_range<0, sprout::tuples::tuple_size<Tuple>::value> > {}; } // namespace tuples // // tuple_indexes // template<typename Tuple> struct tuple_indexes : public sprout::tuples::tuple_indexes<Tuple> {}; } // namespace sprout #endif // #ifndef SPROUT_TUPLE_INDEXES_HPP
22.53125
69
0.708738
jwakely
e6fced42eecd74e756b76964d9ff0b95b731355f
2,762
hh
C++
prothos/runtime/runtime/FlowGraph.hh
ManyThreads/prothos
dd77c46df1dde323ccdfeac3319ba1dd2ea15ce1
[ "MIT" ]
1
2017-03-09T10:18:54.000Z
2017-03-09T10:18:54.000Z
prothos/runtime/runtime/FlowGraph.hh
ManyThreads/prothos
dd77c46df1dde323ccdfeac3319ba1dd2ea15ce1
[ "MIT" ]
9
2018-10-02T11:41:07.000Z
2019-02-07T14:39:52.000Z
prothos/runtime/runtime/FlowGraph.hh
ManyThreads/prothos
dd77c46df1dde323ccdfeac3319ba1dd2ea15ce1
[ "MIT" ]
1
2021-12-10T16:40:56.000Z
2021-12-10T16:40:56.000Z
#pragma once #include "runtime/FlowGraph_impl.hh" namespace Prothos { namespace FlowGraph { class Graph { public: Graph() {} }; class GraphNode { public: GraphNode(Graph &g) : g(g) {} private: Graph &g; }; template<typename T> inline void makeEdge(Internal::Sender<T> &s, Internal::Receiver<T> &r) { s.registerSuccessor(r); r.registerPredecessor(s); } template<typename T> inline void removeEdge(Internal::Sender<T> &s, Internal::Receiver<T> &r) { s.removeSuccessor(r); r.removePredecessor(s); } template<typename Input, typename Output> class FunctionNode : public GraphNode, public Internal::FunctionInput<Input, Output>, public Internal::Sender<Output> { public: template<typename Body> FunctionNode(Graph &g, Body body) : GraphNode(g) , Internal::FunctionInput<Input, Output>(body) {} std::vector<Internal::Receiver<Output>*> successors() override { return Internal::Sender<Output>::successors(); } }; template <typename OutTuple> class JoinNode : public GraphNode, public Internal::JoinInput<OutTuple>, public Internal::Sender<OutTuple> { public: JoinNode(Graph &g) : GraphNode(g) {} std::vector<Internal::Receiver<OutTuple>*> successors() { return Internal::Sender<OutTuple>::successors(); } }; template<typename Output> class SourceNode : public GraphNode, public Internal::Sender<Output> { public: typedef Internal::SourceBody<Output&, bool> SourceBodyType; template<typename Body> SourceNode(Graph &g, Body body) : GraphNode(g) , myBody(new Internal::SourceBodyLeaf<Output&, bool, Body>(body)) {} ~SourceNode() { delete myBody; } std::vector<Internal::Receiver<Output>*> successors() { return Internal::Sender<Output>::successors(); } void activate() { new Internal::SourceTask<SourceNode, Output>(*this); } private: bool applyBody(Output &m) { return (*myBody)(m); } SourceBodyType *myBody; template<typename NodeType, typename Out> friend class Internal::SourceTask; }; template<typename Input, typename Output, size_t Ports> class ConditionalNode : public GraphNode, public Internal::CondInput<Input, Output, Ports>{ public: template<typename Body> ConditionalNode(Graph &g, Body body) : GraphNode(g) , Internal::CondInput<Input, Output, Ports>(body) {} std::vector<Internal::Receiver<Output>*> successors(size_t port) override { ASSERT(port < Ports); return sender[port].successors(); } Internal::Sender<Output>& get(size_t port){ ASSERT(port < Ports); return sender[port]; } private: Internal::Sender<Output> sender[Ports]; }; } // FlowGraph } // Prothos
21.920635
119
0.669442
ManyThreads
e6fd33400e83c691970a57f89d22cb2ae8921bf6
270
cpp
C++
Pacote-Download/C-C++/repeticao4.cpp
AbnerSantos25/Arquivos-em-C
fe20725012ca1c2f1976b93f8520b6b528b249d9
[ "MIT" ]
null
null
null
Pacote-Download/C-C++/repeticao4.cpp
AbnerSantos25/Arquivos-em-C
fe20725012ca1c2f1976b93f8520b6b528b249d9
[ "MIT" ]
null
null
null
Pacote-Download/C-C++/repeticao4.cpp
AbnerSantos25/Arquivos-em-C
fe20725012ca1c2f1976b93f8520b6b528b249d9
[ "MIT" ]
null
null
null
#include <stdio.h> int main() { int num, fat=1; printf("calcula o fatorial de um numero\n"); printf("informe o numero: "); scanf("%d",&num); for(int i=num; i>=1; i--) fat *= i; printf("o fatorial de %d e %d",num,fat); return 0; }
18
48
0.525926
AbnerSantos25
e6fdb753db279599a480bf07b6306068a80e8354
7,414
cpp
C++
software/esp32-firmware/src/uart_thread.cpp
vhs/vhs-door-nfc
55b8210d7b07a5c6fa26bc40fae8362b504addd6
[ "Apache-2.0" ]
null
null
null
software/esp32-firmware/src/uart_thread.cpp
vhs/vhs-door-nfc
55b8210d7b07a5c6fa26bc40fae8362b504addd6
[ "Apache-2.0" ]
1
2019-02-01T23:03:20.000Z
2019-02-02T19:48:57.000Z
software/esp32-firmware/src/uart_thread.cpp
vhs/vhs-door-nfc
55b8210d7b07a5c6fa26bc40fae8362b504addd6
[ "Apache-2.0" ]
1
2020-02-16T06:43:42.000Z
2020-02-16T06:43:42.000Z
#include <stdio.h> #include <string.h> #include <sys/unistd.h> #include <sys/stat.h> #include <time.h> #include <sys/time.h> #include <assert.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include <esp_types.h> #include "esp_system.h" #include "esp_event.h" #include "esp_event_loop.h" #include "esp_task_wdt.h" #include "esp_log.h" #include "driver/uart.h" #include "rom/uart.h" #include "utils.h" #include "uart_thread.h" #include "main_thread.h" #define TAG "UART" TaskHandle_t UART_taskHandle = NULL; QueueHandle_t UART_queueHandle = NULL; static StaticQueue_t UART_queueStructure; static UartNotification UART_queueStorage[8] = {}; #define UART_FLUSH() while (uart_rx_one_char(&ch) == ESP_OK) #define UART_WAIT_KEY() \ while (uart_rx_one_char(&ch) != ESP_OK) \ vTaskDelay(1 / portTICK_PERIOD_MS) #define STM32_UART_TXD (GPIO_NUM_4) #define STM32_UART_RXD (GPIO_NUM_36) #define STM32_UART_RTS (UART_PIN_NO_CHANGE) #define STM32_UART_CTS (UART_PIN_NO_CHANGE) #define STM32_UART_BUFFER_SIZE 1024 static char stm32UartBuffer[STM32_UART_BUFFER_SIZE] = {}; static void uart_task(void* pvParameters) { ESP_LOGI(TAG, "UART task running..."); const char* UART_cmd_ready = "ESP32_READY\n"; const char* UART_cmd_play_beep_01 = "PLAY_BEEP_01\n"; const char* UART_cmd_play_beep_02 = "PLAY_BEEP_02\n"; const char* UART_cmd_play_beep_03 = "PLAY_BEEP_03\n"; const char* UART_cmd_play_beep_04 = "PLAY_BEEP_04\n"; const char* UART_cmd_play_beep_05 = "PLAY_BEEP_05\n"; const char* UART_cmd_play_beep_06 = "PLAY_BEEP_06\n"; const char* UART_cmd_play_buzzer_01 = "PLAY_BUZZER_01\n"; const char* UART_cmd_play_buzzer_02 = "PLAY_BUZZER_02\n"; const char* UART_cmd_play_success = "PLAY_SUCCESS\n"; const char* UART_cmd_play_failure = "PLAY_FAILURE\n"; const char* UART_cmd_play_smb = "PLAY_SMB\n"; const char* UART_cmd_lock_door = "LOCK_DOOR\n"; const char* UART_cmd_unlock_door = "UNLOCK_DOOR\n"; const char* rfid_cmd_prefix = "RFID:"; const char* pin_cmd_prefix = "PIN:"; uart_write_bytes(UART_NUM_1, (const char*)UART_cmd_ready, strlen(UART_cmd_ready)); while (1) { // Check for any waiting notifications UartNotification notification; while (xQueueReceive(UART_queueHandle, &notification, 0) == pdTRUE) { const char* message = NULL; if (notification == UART_NOTIFICATION_PlayBeepShortMedium) { message = UART_cmd_play_beep_01; } else if (notification == UART_NOTIFICATION_PlayBeepShortLow) { message = UART_cmd_play_beep_02; } else if (notification == UART_NOTIFICATION_PlayBeepLongMedium) { message = UART_cmd_play_beep_03; } else if (notification == UART_NOTIFICATION_PlayBeepLongLow) { message = UART_cmd_play_beep_04; } else if (notification == UART_NOTIFICATION_PlayBeepShortHigh) { message = UART_cmd_play_beep_05; } else if (notification == UART_NOTIFICATION_PlayBeepLongHigh) { message = UART_cmd_play_beep_06; } else if (notification == UART_NOTIFICATION_PlayBuzzer01) { message = UART_cmd_play_buzzer_01; } else if (notification == UART_NOTIFICATION_PlayBuzzer02) { message = UART_cmd_play_buzzer_02; } else if (notification == UART_NOTIFICATION_PlaySuccess) { message = UART_cmd_play_success; } else if (notification == UART_NOTIFICATION_PlayFailure) { message = UART_cmd_play_failure; } else if (notification == UART_NOTIFICATION_PlaySmb) { message = UART_cmd_play_smb; } else if (notification == UART_NOTIFICATION_LockDoor) { message = UART_cmd_lock_door; } else if (notification == UART_NOTIFICATION_UnlockDoor) { message = UART_cmd_unlock_door; } if (message != NULL) { uart_write_bytes(UART_NUM_1, (const char*)message, strlen(message)); } } // Read data from the UART int len = uart_read_bytes(UART_NUM_1, (uint8_t*)stm32UartBuffer, STM32_UART_BUFFER_SIZE - 1, 20 / portTICK_RATE_MS); if (len > 0) { stm32UartBuffer[len] = '\0'; if (strstr(stm32UartBuffer, rfid_cmd_prefix) == stm32UartBuffer) { for (int i = 0; i < len; i++) { if (stm32UartBuffer[i] == '\n') { stm32UartBuffer[i] = '\0'; } } len = strlen(stm32UartBuffer) - strlen(rfid_cmd_prefix); const char* id = stm32UartBuffer + strlen(rfid_cmd_prefix); MainNotificationArgs mainNotificationArgs; bzero(&mainNotificationArgs, sizeof(MainNotificationArgs)); mainNotificationArgs.notification = MAIN_NOTIFICATION_RfidReady; mainNotificationArgs.rfid.idLength = len; memcpy(mainNotificationArgs.rfid.id, id, len); if (xQueueSendToBack(MAIN_queueHandle, &mainNotificationArgs, 100 / portTICK_PERIOD_MS) != pdTRUE) { // Erk. Did not add to the queue. Oh well? User can just try again when they realize... } } else if (strstr(stm32UartBuffer, pin_cmd_prefix) == stm32UartBuffer) { for (int i = 0; i < len; i++) { if (stm32UartBuffer[i] == '\n') { stm32UartBuffer[i] = '\0'; } } len = strlen(stm32UartBuffer) - strlen(pin_cmd_prefix); const char* pin = stm32UartBuffer + strlen(pin_cmd_prefix); MainNotificationArgs mainNotificationArgs; bzero(&mainNotificationArgs, sizeof(MainNotificationArgs)); mainNotificationArgs.notification = MAIN_NOTIFICATION_PinReady; mainNotificationArgs.pin.code = atol(pin); if (xQueueSendToBack(MAIN_queueHandle, &mainNotificationArgs, 100 / portTICK_PERIOD_MS) != pdTRUE) { // Erk. Did not add to the queue. Oh well? User can just try again when they realize... } } } } } // void uart_init() { ESP_LOGI(TAG, "Initializing UART..."); UART_queueHandle = xQueueCreateStatic(ARRAY_COUNT(UART_queueStorage), sizeof(UartNotification), (uint8_t*)UART_queueStorage, &UART_queueStructure); uart_config_t uart_config = { .baud_rate = 115200, .data_bits = UART_DATA_8_BITS, .parity = UART_PARITY_DISABLE, .stop_bits = UART_STOP_BITS_1, .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, .rx_flow_ctrl_thresh = 0, .use_ref_tick = false }; ESP_ERROR_CHECK(uart_param_config(UART_NUM_1, &uart_config)); ESP_ERROR_CHECK(uart_set_pin(UART_NUM_1, STM32_UART_TXD, STM32_UART_RXD, STM32_UART_RTS, STM32_UART_CTS)); ESP_ERROR_CHECK(uart_driver_install(UART_NUM_1, STM32_UART_BUFFER_SIZE * 2, 0, 0, NULL, 0)); } // void uart_thread_create() { xTaskCreate(&uart_task, "uart_task", 4 * 1024, NULL, 10, &UART_taskHandle); }
40.075676
151
0.632587
vhs
e6fdc7813286e4ab5dc92fe81d62c0da7c217457
654
hpp
C++
pythran/pythonic/numpy/isneginf.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,647
2015-01-13T01:45:38.000Z
2022-03-28T01:23:41.000Z
pythran/pythonic/numpy/isneginf.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,116
2015-01-01T09:52:05.000Z
2022-03-18T21:06:40.000Z
pythran/pythonic/numpy/isneginf.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
180
2015-02-12T02:47:28.000Z
2022-03-14T10:28:18.000Z
#ifndef PYTHONIC_NUMPY_ISNEGINF_HPP #define PYTHONIC_NUMPY_ISNEGINF_HPP #include "pythonic/include/numpy/isneginf.hpp" #include "pythonic/utils/functor.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/utils/numpy_traits.hpp" #include "pythonic//numpy/isinf.hpp" PYTHONIC_NS_BEGIN namespace numpy { namespace wrapper { template <class T> auto isneginf(T const &t) -> decltype(functor::isinf{}(t) && (t < 0)) { return functor::isinf{}(t) && (t < 0); } } #define NUMPY_NARY_FUNC_NAME isneginf #define NUMPY_NARY_FUNC_SYM wrapper::isneginf #include "pythonic/types/numpy_nary_expr.hpp" } PYTHONIC_NS_END #endif
21.096774
73
0.738532
davidbrochart
e6fe311388661078aa46e22620d25f38bdb567d7
1,434
hpp
C++
workspace/hw1/parking_lot.hpp
biomotion/eos-2020
0f457f72cbefe487808183994c7381f59c4e3235
[ "MIT" ]
null
null
null
workspace/hw1/parking_lot.hpp
biomotion/eos-2020
0f457f72cbefe487808183994c7381f59c4e3235
[ "MIT" ]
null
null
null
workspace/hw1/parking_lot.hpp
biomotion/eos-2020
0f457f72cbefe487808183994c7381f59c4e3235
[ "MIT" ]
null
null
null
#ifndef PARKINGLOT_H #define PARKINGLOT_H #include<iostream> #include<vector> #include<map> #include <sys/ioctl.h> #include <fcntl.h> #include "asm-arm/arch-pxa/lib/creator_pxa270_lcd.h" #define PL_STATE_WELCOME 0 #define PL_STATE_MENU_PARKED 1 #define PL_STATE_MENU_NOT_RESERVED 2 #define PL_STATE_MENU_RESERVED 3 #define PL_STATE_SHOW 4 #define PL_STATE_CHOOSE 5 #define PL_STATE_PAY 6 #define VEH_STATE_INIT 0 #define VEH_STATE_RESERVED 1 #define VEH_STATE_PARKED 2 #define VEH_STATE_PARKED_NO_RESERVED 3 typedef struct VehicleInfo{ VehicleInfo():state(VEH_STATE_INIT), lot(-1), grid(0) {}; VehicleInfo(int _state):state(_state), lot(-1), grid(0) {}; int state; int lot; char grid; } VehicleInfo; class ParkingLot{ private: int lcd_fd; int sysState; lcd_write_info_t display; std::pair<int, VehicleInfo> currentVehicle; std::map<int, VehicleInfo> vehList; VehicleInfo getVehState(int); void setVehState(int, VehicleInfo); char* getGridState(); // For I/O int printMessage(const char* msg, bool erase=true); void getMessage(char* msg); int segment_display_decimal(int data); int led_display_binary(int data); public: ParkingLot(); ParkingLot(int& fd); // State Nodes int showWelcome(); int showMenuParked(); int showMenuReserved(); int showMenuNotReserved(); int showSpace(); int showChoose(); int showPay(); // Actions int runSystem(); int getState(); }; #endif
22.061538
61
0.742678
biomotion
e6ff3dffcd27ace8ddd9f25a3988255f48674290
2,749
hpp
C++
lib/sfml/src/Object.hpp
benjyup/cpp_arcade
4b755990b64156148e529da1c39efe8a8c0c5d1f
[ "MIT" ]
null
null
null
lib/sfml/src/Object.hpp
benjyup/cpp_arcade
4b755990b64156148e529da1c39efe8a8c0c5d1f
[ "MIT" ]
null
null
null
lib/sfml/src/Object.hpp
benjyup/cpp_arcade
4b755990b64156148e529da1c39efe8a8c0c5d1f
[ "MIT" ]
null
null
null
/* ** Object.hpp for cpp_arcade in /home/peixot_b/delivery/cpp_arcade/Object.hpp ** ** Made by benjamin.peixoto ** Login <benjamin.peixoto@epitech.eu> ** ** Started on Mon Apr 03 14:18:52 2017 benjamin.peixoto // Last update Fri Apr 7 15:36:07 2017 Benjamin */ #ifndef Object_HPP_ #define Object_HPP_ #include <fstream> #include <algorithm> #include <ostream> #include <cstdint> #include <SFML/Graphics.hpp> #include "IObject.hpp" namespace arcade { class Window; class SfmlLib; class Object : public IObject { public: enum class ObjectType : char { Object = 0, Label = 1 }; static const std::string directory_name; static const std::string file_extension; Object(); Object(const std::string &name, const std::string &filename); Object(const Object& other); bool operator==(const Object &rhs) const; bool operator!=(const Object &rhs) const; virtual ~Object(); Object &operator=(const Object &other); virtual void setName(std::string const &); virtual void setString(std::string const &); virtual void setPosition(Vector3d const &); virtual void setDirection(Vector3d const &); virtual void setSpeed(float); virtual void setScale(float); virtual void setTextureFile(std::string const &); virtual std::string const &getName(void) const; virtual std::string const &getString(void) const; virtual std::string const &getFilename(void) const; virtual arcade::Vector3d const &getPosition (void) const; virtual arcade::Vector3d const &getDirection(void) const; virtual float getSpeed(void) const; virtual float getScale(void) const; virtual Object::ObjectType getType(void) const; virtual sf::Drawable &getDrawable(void) = 0; virtual std::string const &getTextureFile(void) const; protected: sf::Color _color; char _colorTurn; std::string _name; std::string _str; std::string _filename; std::string _string; Vector3d _position; Vector3d _direction; float _speed; float _scale; std::string _background; std::string _character; bool _isMoving; }; std::ostream &operator<<(std::ostream &os, const Object &object); } #endif //Object_HPP_
30.544444
80
0.563478
benjyup
fc001a66094c076fdcc4703bf46f0f93f64ba66f
8,406
cpp
C++
CMinus/CMinus/evaluator/comparison.cpp
benbraide/CMinusMinus
6e32b825f192634538b3adde6ca579a548ca3f7e
[ "MIT" ]
null
null
null
CMinus/CMinus/evaluator/comparison.cpp
benbraide/CMinusMinus
6e32b825f192634538b3adde6ca579a548ca3f7e
[ "MIT" ]
null
null
null
CMinus/CMinus/evaluator/comparison.cpp
benbraide/CMinusMinus
6e32b825f192634538b3adde6ca579a548ca3f7e
[ "MIT" ]
null
null
null
#include "../type/string_type.h" #include "../storage/global_storage.h" #include "comparison.h" cminus::evaluator::comparison::~comparison() = default; cminus::evaluator::numeric_comparison::~numeric_comparison() = default; cminus::evaluator::object::memory_ptr_type cminus::evaluator::numeric_comparison::evaluate(operators::id op, object::memory_ptr_type left_value, object::memory_ptr_type right_value) const{ auto left_type = left_value->get_type(), right_type = right_value->get_type(); if (left_type == nullptr || right_type == nullptr) throw exception::invalid_type(); auto left_number_type = left_type->as<type::number_primitive>(); if (left_number_type == nullptr) throw exception::unsupported_op(); auto compatible_left_value = left_value, compatible_right_value = right_value; auto right_number_type = right_type->as<type::number_primitive>(); if (right_number_type == nullptr){ if (right_type->is<type::string>()){ auto left_string_value = left_number_type->get_string_value(left_value); auto right_string_value = runtime::object::global_storage->get_string_value(right_value); if (op == operators::id::spaceship) return create_compare_value_(compare_string_(left_string_value, right_string_value)); return create_value_(evaluate_string_(op, left_string_value, right_string_value)); } if ((compatible_right_value = right_type->cast(right_value, left_type, type::cast_type::static_rval)) != nullptr){ right_type = left_type; right_number_type = left_number_type; } } else if (left_number_type->get_precedence(*right_number_type) == left_number_type->get_state()){ compatible_right_value = right_type->cast(right_value, left_type, type::cast_type::static_rval); right_type = left_type; right_number_type = left_number_type; } else{//Convert left compatible_left_value = left_type->cast(left_value, right_type, type::cast_type::static_rval); left_type = right_type; left_number_type = right_number_type; } if (compatible_left_value == nullptr || compatible_right_value == nullptr) throw exception::incompatible_rval(); switch (left_number_type->get_state()){ case type::number_primitive::state_type::small_integer: if (op == operators::id::spaceship) return create_compare_value_(compare_numeric_<__int16>(compatible_left_value, compatible_right_value)); return create_value_(evaluate_numeric_<__int16>(op, compatible_left_value, compatible_right_value)); case type::number_primitive::state_type::integer: if (op == operators::id::spaceship) return create_compare_value_(compare_numeric_<__int32>(compatible_left_value, compatible_right_value)); return create_value_(evaluate_numeric_<__int32>(op, compatible_left_value, compatible_right_value)); case type::number_primitive::state_type::big_integer: if (op == operators::id::spaceship) return create_compare_value_(compare_numeric_<__int64>(compatible_left_value, compatible_right_value)); return create_value_(evaluate_numeric_<__int64>(op, compatible_left_value, compatible_right_value)); case type::number_primitive::state_type::unsigned_small_integer: if (op == operators::id::spaceship) return create_compare_value_(compare_numeric_<unsigned __int16>(compatible_left_value, compatible_right_value)); return create_value_(evaluate_numeric_<unsigned __int16>(op, compatible_left_value, compatible_right_value)); case type::number_primitive::state_type::unsigned_integer: if (op == operators::id::spaceship) return create_compare_value_(compare_numeric_<unsigned __int32>(compatible_left_value, compatible_right_value)); return create_value_(evaluate_numeric_<unsigned __int32>(op, compatible_left_value, compatible_right_value)); case type::number_primitive::state_type::unsigned_big_integer: if (op == operators::id::spaceship) return create_compare_value_(compare_numeric_<unsigned __int64>(compatible_left_value, compatible_right_value)); return create_value_(evaluate_numeric_<unsigned __int64>(op, compatible_left_value, compatible_right_value)); case type::number_primitive::state_type::small_float: if (op == operators::id::spaceship) return create_compare_value_(compare_numeric_<float>(compatible_left_value, compatible_right_value)); return create_value_(evaluate_numeric_<float>(op, compatible_left_value, compatible_right_value)); case type::number_primitive::state_type::float_: if (op == operators::id::spaceship) return create_compare_value_(compare_numeric_<double>(compatible_left_value, compatible_right_value)); return create_value_(evaluate_numeric_<double>(op, compatible_left_value, compatible_right_value)); case type::number_primitive::state_type::big_float: if (op == operators::id::spaceship) return create_compare_value_(compare_numeric_<long double>(compatible_left_value, compatible_right_value)); return create_value_(evaluate_numeric_<long double>(op, compatible_left_value, compatible_right_value)); default: break; } throw exception::unsupported_op(); return nullptr; } cminus::evaluator::object::memory_ptr_type cminus::evaluator::numeric_comparison::evaluate(operators::id op, object::memory_ptr_type left_value, object::node_ptr_type right) const{ auto right_value = pre_evaluate_(op, left_value, right); return ((right_value == nullptr) ? nullptr : evaluate(op, left_value, right_value)); } cminus::evaluator::object::memory_ptr_type cminus::evaluator::comparison::pre_evaluate_(operators::id op, object::memory_ptr_type left_value, object::node_ptr_type right) const{ switch (op){ case operators::id::less: case operators::id::less_or_equal: case operators::id::equal: case operators::id::not_equal: case operators::id::greater_or_equal: case operators::id::greater: case operators::id::spaceship: break; default: return nullptr; } if (left_value == nullptr) throw exception::unsupported_op(); auto right_value = right->evaluate(); if (right_value == nullptr) throw exception::unsupported_op(); return right_value; } bool cminus::evaluator::comparison::evaluate_string_(operators::id op, const std::string_view &left, const std::string_view &right) const{ switch (op){ case operators::id::less: return (left < right); case operators::id::less_or_equal: return (left <= right); case operators::id::equal: return (left == right); case operators::id::not_equal: return (left != right); case operators::id::greater_or_equal: return (left >= right); case operators::id::greater: return (left > right); default: break; } return false; } int cminus::evaluator::comparison::compare_string_(const std::string_view &left, const std::string_view &right) const{ return left.compare(right); } cminus::evaluator::object::memory_ptr_type cminus::evaluator::comparison::create_value_(bool value) const{ return runtime::object::global_storage->get_boolean_value(value); } cminus::evaluator::object::memory_ptr_type cminus::evaluator::comparison::create_compare_value_(int value) const{ return std::make_shared<memory::scalar_reference<int>>(runtime::object::global_storage->get_int_type(), value); } cminus::evaluator::pointer_comparison::~pointer_comparison() = default; cminus::evaluator::object::memory_ptr_type cminus::evaluator::pointer_comparison::evaluate(operators::id op, object::memory_ptr_type left_value, object::memory_ptr_type right_value) const{ auto left_type = left_value->get_type(), right_type = right_value->get_type(); if (left_type == nullptr || right_type == nullptr) throw exception::invalid_type(); auto compatible_left_value = left_value, compatible_right_value = right_value; if ((compatible_right_value = right_type->cast(right_value, left_type, type::cast_type::static_rval)) == nullptr){//Try casting left value if ((compatible_left_value = left_type->cast(left_value, right_type, type::cast_type::static_rval)) != nullptr) compatible_right_value = right_value; else//Failed both conversions throw exception::unsupported_op(); } return create_value_(evaluate_<std::size_t>(op, compatible_left_value, compatible_right_value)); } cminus::evaluator::object::memory_ptr_type cminus::evaluator::pointer_comparison::evaluate(operators::id op, object::memory_ptr_type left_value, object::node_ptr_type right) const{ auto right_value = pre_evaluate_(op, left_value, right); return ((right_value == nullptr) ? nullptr : evaluate(op, left_value, right_value)); }
46.441989
188
0.786224
benbraide
fc05318d0135c7a78b86a34b868117c50b606c4b
1,510
hpp
C++
core/include/bind/emu/edi_jump_caret.hpp
pit-ray/win-vind
7386f6f7528d015ce7f1a5ae230d6e63f9492df9
[ "MIT" ]
731
2020-05-07T06:22:59.000Z
2022-03-31T16:36:03.000Z
core/include/bind/emu/edi_jump_caret.hpp
pit-ray/win-vind
7386f6f7528d015ce7f1a5ae230d6e63f9492df9
[ "MIT" ]
67
2020-07-20T19:46:42.000Z
2022-03-31T15:34:47.000Z
core/include/bind/emu/edi_jump_caret.hpp
pit-ray/win-vind
7386f6f7528d015ce7f1a5ae230d6e63f9492df9
[ "MIT" ]
15
2021-01-29T04:49:11.000Z
2022-03-04T22:16:31.000Z
#ifndef _EDI_JUMP_CARET_HPP #define _EDI_JUMP_CARET_HPP #include "bind/binded_func_creator.hpp" namespace vind { struct JumpCaretToBOL : public BindedFuncCreator<JumpCaretToBOL> { explicit JumpCaretToBOL() ; static void sprocess() ; static void sprocess(NTypeLogger& parent_lgr) ; static void sprocess(const CharLogger& parent_lgr) ; bool is_for_moving_caret() const noexcept override ; } ; struct JumpCaretToEOL : public BindedFuncCreator<JumpCaretToEOL> { explicit JumpCaretToEOL() ; static void sprocess(unsigned int repeat_num=1) ; static void sprocess(NTypeLogger& parent_lgr) ; static void sprocess(const CharLogger& parent_lgr) ; bool is_for_moving_caret() const noexcept override ; } ; struct JumpCaretToBOF : public BindedFuncCreator<JumpCaretToBOF> { explicit JumpCaretToBOF() ; static void sprocess(unsigned int repeat_num=1) ; static void sprocess(NTypeLogger& parent_lgr) ; static void sprocess(const CharLogger& parent_lgr) ; bool is_for_moving_caret() const noexcept override ; } ; struct JumpCaretToEOF : public BindedFuncCreator<JumpCaretToEOF> { explicit JumpCaretToEOF() ; static void sprocess(unsigned int repeat_num=1) ; static void sprocess(NTypeLogger& parent_lgr) ; static void sprocess(const CharLogger& parent_lgr) ; bool is_for_moving_caret() const noexcept override ; } ; } #endif
33.555556
70
0.701325
pit-ray
fc06ee36a66ddf7bade121a13443131b79b2b12a
2,007
cpp
C++
rt/rt/solids/quadric.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/rt/solids/quadric.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/rt/solids/quadric.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
#include "triangle.h" #include <rt/bbox.h> #include <rt/intersection.h> #include <rt/solids/quadric.h> namespace rt { Quadric::Quadric( const Quadric::Coefficients& cof, CoordMapper* texMapper, Material* material) : Solid(texMapper, material) , cof(cof) { } BBox Quadric::getBounds() const { // it's kind of hard to compute the bounds, so just overapproximate return BBox::full(); } Intersection Quadric::intersect( const Ray& ray, float previousBestDistance) const { const float alpha = cof.a * sqr(ray.d.x) + cof.b * sqr(ray.d.y) + cof.c * sqr(ray.d.z) + cof.d * ray.d.x * ray.d.y + cof.e * ray.d.x * ray.d.z + cof.f * ray.d.y * ray.d.z; const float beta = 2 * (cof.a * ray.d.x * ray.o.x + cof.b * ray.d.y * ray.o.y + cof.c * ray.d.z * ray.o.z) + cof.d * (ray.o.x * ray.d.y + ray.d.x * ray.o.y) + cof.e * (ray.o.x * ray.d.z + ray.d.x * ray.o.z) + cof.f * (ray.o.y * ray.d.z + ray.d.y * ray.o.z) + cof.g * ray.d.x + cof.h * ray.d.y + cof.i * ray.d.z; const float gamma = cof.a * sqr(ray.o.x) + cof.b * sqr(ray.o.y) + cof.c * sqr(ray.o.z) + cof.d * ray.o.x * ray.o.y + cof.e * ray.o.x * ray.o.z + cof.f * ray.o.y * ray.o.z + cof.g * ray.o.x + cof.h * ray.o.y + cof.i * ray.o.z + cof.j; const float under_sqr = sqr(beta) - 4 * alpha * gamma; if(under_sqr < 0.f) return Intersection::failure(); const float the_sqr = sqrt(under_sqr); const float t1 = (-beta + the_sqr) / (2 * alpha); const float t2 = (-beta - the_sqr) / (2 * alpha); if(std::min(t1, t2) > previousBestDistance) return Intersection::failure(); const float t = std::min(t1, t2); return Intersection( t, ray, this, cof.normalAt(ray.getPoint(t)), Point(0, 0, 0)); } Solid::Sample Quadric::sample() const { NOT_IMPLEMENTED; } float Quadric::getArea() const { // yet another overapproximation return FLT_MAX; } }
29.086957
79
0.563029
DasNaCl
fc0936740b0faab94d140d6dd699662b0512bd2d
13,602
cpp
C++
ciphers.cpp
KoSeAn97/Classic-Ciphers
c7c99913c4837425e45bdc86b5726b67eda82f7c
[ "Unlicense" ]
null
null
null
ciphers.cpp
KoSeAn97/Classic-Ciphers
c7c99913c4837425e45bdc86b5726b67eda82f7c
[ "Unlicense" ]
null
null
null
ciphers.cpp
KoSeAn97/Classic-Ciphers
c7c99913c4837425e45bdc86b5726b67eda82f7c
[ "Unlicense" ]
null
null
null
#include <iostream> #include <list> #include <algorithm> #include <codecvt> #include "ciphers.hpp" #include "utf8.h" #define ALPH_ENG 26 #define ALPH_RUS 32 #define SPACE_WC L' ' #define LEAST_FR L'X' #define MX_S_ENG 5 #define MX_S_RUS 6 extern std::locale loc; //std::wstring_convert< std::codecvt_utf8<wchar_t> > converter; class utf_wrapper { public: std::wstring from_bytes(const std::string & str); std::string to_bytes(const std::wstring & wstr); } converter; std::wstring utf_wrapper::from_bytes(const std::string & str) { std::wstring utf16line; utf8::utf8to16(str.begin(), str.end(), std::back_inserter(utf16line)); return utf16line; } std::string utf_wrapper::to_bytes(const std::wstring & wstr) { std::string utf8line; utf8::utf16to8(wstr.begin(), wstr.end(), std::back_inserter(utf8line)); return utf8line; } wchar_t pfront(std::wstring & str); void create_Polybius_Square(std::vector< std::vector<wchar_t> > & matrix, std::wstring r_key, bool is_english); coords find_letter(const std::vector< std::vector<wchar_t> > & table, wchar_t ch); void touppers(std::wstring & s); Caesar::Caesar(int init_shift) : shift(init_shift) {} void Caesar::backdoor() {} wchar_t Caesar::shifter(bool is_enc, wchar_t ch) const { wchar_t base; int mod; if(ch < 0xFF) { mod = ALPH_ENG; if(isupper(ch, loc)) base = L'A'; else base = L'a'; } else { mod = ALPH_RUS; if(isupper(ch, loc)) base = L'А'; else base = L'а'; } if(is_enc) return base + (ch - base + shift + mod) % mod; else return base + (ch - base - shift + mod) % mod; } std::string Caesar::encrypt(const std::string & plaintext) { std::wstring buffer = converter.from_bytes(plaintext); std::transform( buffer.begin(), buffer.end(), buffer.begin(), [this](wchar_t ch) { backdoor(); if(!isalpha(ch, loc)) return ch; return shifter(true, ch); } ); return converter.to_bytes(buffer); } std::string Caesar::decrypt(const std::string & ciphertext) { std::wstring buffer = converter.from_bytes(ciphertext); std::transform( buffer.begin(), buffer.end(), buffer.begin(), [this](wchar_t ch) { backdoor(); if(!isalpha(ch, loc)) return ch; return shifter(false, ch); } ); return converter.to_bytes(buffer); } Vigenere::Vigenere(const std::string & key) { std::wstring buffer = converter.from_bytes(key); wchar_t base; for(auto it = buffer.begin(); it != buffer.end(); ++it) { if(!isalpha(*it, loc)) { base = L' '; } else if(*it < 0xFF) { if(isupper(*it, loc)) base = L'A'; else base = L'a'; } else { if(isupper(*it, loc)) base = L'А'; else base = L'а'; } shifts.push_back(*it - base); } key_len = shifts.size(); } void Vigenere::backdoor() { shift = shifts[counter]; counter = (counter + 1) % key_len; } std::string Vigenere::encrypt(const std::string & plaintext) { counter = 0; return Caesar::encrypt(plaintext); } std::string Vigenere::decrypt(const std::string & ciphertext) { counter = 0; return Caesar::decrypt(ciphertext); } Transposition::Transposition(const std::vector<int> & init_perm) { key_len = init_perm.size(); for(int i = 0; i < key_len; i++) direct_perm[init_perm[i] - 1] = i; for(int i = 0; i < key_len; i++) inverse_perm[direct_perm[i]] = i; } std::string Transposition::encrypt(const std::string & plaintext) { std::vector< std::list<wchar_t> > table(key_len); std::wstring buffer = converter.from_bytes(plaintext); int l_height = buffer.size() / key_len + (buffer.size() % key_len ? 1 : 0); int msg_len = l_height * key_len; // do padding buffer.resize(msg_len, SPACE_WC); // fill the table for(int i = 0; i < msg_len; i++) { table[i % key_len].push_back(buffer[i]); } // construct ciphertext int index; buffer.clear(); for(int i = 0; i < key_len; i++) { index = direct_perm.at(i); buffer.append(table[index].begin(), table[index].end()); } return converter.to_bytes(buffer); } std::string Transposition::decrypt(const std::string & ciphertext) { std::vector< std::list<wchar_t> > table(key_len); std::wstring buffer = converter.from_bytes(ciphertext); int l_height = buffer.size() / key_len + (buffer.size() % key_len ? 1 : 0); int msg_len = l_height * key_len; // fill the table for(int i = 0; i < msg_len; i++) { table[i / l_height].push_back(buffer[i]); } // construct plaintext int index; buffer.clear(); for(int i = 0; i < msg_len; i++) { index = inverse_perm.at(i % key_len); buffer.append(1, table[index].front()); table[index].pop_front(); } return converter.to_bytes(buffer); } Polybius::Polybius(bool is_english, int mode) { cipher_mode = mode; create_Polybius_Square(matrix, std::wstring(), is_english); dim_m = matrix.size(); } void Polybius::mode_1(std::wstring & src, std::string & dst, bool is_enc) { int shift = is_enc ? 1 : -1; std::transform( src.begin(), src.end(), src.begin(), [shift, this](wchar_t ch) { if(!isalpha(ch, loc)) return ch; coords p = find_letter(matrix, ch); int sh = (p.first + shift + dim_m) % dim_m; while(!isalpha(matrix[sh][p.second], loc)) sh = (sh + shift + dim_m) % dim_m; return matrix[sh][p.second]; } ); dst = converter.to_bytes(src); } void Polybius::enc_2(std::wstring & plaintext, std::string & ciphertext) { std::vector<int> first, second; coords p; for(auto ch: plaintext) { if(!isalpha(ch, loc)) continue; p = find_letter(matrix, ch); second.push_back(p.first); first.push_back(p.second); } int lenght = first.size(); bool odd = lenght % 2; std::wstring buffer; for(int i = 0; i + 1 < lenght; i += 2) buffer.append(1, matrix[first[i+1]][first[i]]); if(odd) buffer.append(1, matrix[second[0]][first[lenght-1]]); for(int i = odd; i + 1 < lenght; i += 2) buffer.append(1, matrix[second[i+1]][second[i]]); ciphertext = converter.to_bytes(buffer); } void Polybius::dec_2(std::wstring & ciphertext, std::string & plaintext) { std::vector<int> foo; coords p; for(auto ch: ciphertext) { if(!isalpha(ch, loc)) continue; p = find_letter(matrix, ch); foo.push_back(p.second); foo.push_back(p.first); } int half_lenght = foo.size() / 2; std::wstring buffer; for(int i = 0; i < half_lenght; i++) buffer.append(1, matrix[foo[half_lenght + i]][foo[i]]); plaintext = converter.to_bytes(buffer); } std::string Polybius::encrypt(const std::string & plaintext) { std::wstring buffer = converter.from_bytes(plaintext); touppers(buffer); std::replace(buffer.begin(), buffer.end(), L'J', L'I'); std::string ciphertext; if(cipher_mode % 2) mode_1(buffer, ciphertext, true); else enc_2(buffer, ciphertext); return ciphertext; } std::string Polybius::decrypt(const std::string & ciphertext) { std::wstring buffer = converter.from_bytes(ciphertext); touppers(buffer); std::replace(buffer.begin(), buffer.end(), L'J', L'I'); std::string plaintext; if(cipher_mode % 2) mode_1(buffer, plaintext, false); else dec_2(buffer, plaintext); return plaintext; } Playfair::Playfair(const std::string & key) { std::wstring reduced_key = reduce(key); create_Polybius_Square(matrix, reduced_key, true); dim_m = matrix.size(); } std::wstring Playfair::reduce(const std::string & key) const { std::wstring buffer = converter.from_bytes(key); touppers(buffer); std::replace(buffer.begin(), buffer.end(), L'J', L'I'); std::wstring reduced_key; for(auto ch: buffer) { if(reduced_key.find(ch) == std::string::npos) reduced_key.append(1, ch); } return reduced_key; } std::ostream & operator << (std::ostream & stream, std::pair<wchar_t, wchar_t> elem) { return stream << "(" << (char) elem.first << ", " << (char) elem.second << ")"; } std::ostream & operator << (std::ostream & stream, std::pair<int, int> elem) { return stream << "{" << elem.first << ", " << elem.second << "}"; } void Playfair::perform(Playfair::digram & dg) const { coords a = find_letter(matrix, dg.first); coords b = find_letter(matrix, dg.second); // lazy evaluation a == b || rule_2(dg, a, b) || rule_3(dg, a, b) || rule_4(dg, a, b); } wchar_t Playfair::rule_1(Playfair::digram & dg) const { if(dg.first != dg.second) return 0; if(dg.first == LEAST_FR) return 0; wchar_t buffer = dg.second; dg = digram(dg.first, LEAST_FR); return buffer; } bool Playfair::rule_2(Playfair::digram & dg, const coords & a, const coords & b) const { if(a.first != b.first) return false; int shift = state_encrypt ? 1 : -1; int row = a.first; dg = digram( matrix[row][(a.second + shift + dim_m) % dim_m], matrix[row][(b.second + shift + dim_m) % dim_m] ); return true; } bool Playfair::rule_3(Playfair::digram & dg, const coords & a, const coords & b) const { if(a.second != b.second) return false; int shift = state_encrypt ? 1 : -1; int column = a.second; dg = digram( matrix[(a.first + shift + dim_m) % dim_m][column], matrix[(b.first + shift + dim_m) % dim_m][column] ); return true; } bool Playfair::rule_4(Playfair::digram & dg, const coords & a, const coords & b) const { dg = digram( matrix[a.first][b.second], matrix[b.first][a.second] ); return true; } std::string Playfair::encrypt(const std::string & plaintext) { state_encrypt = true; std::wstring buffer = converter.from_bytes(plaintext); touppers(buffer); std::replace(buffer.begin(), buffer.end(), L'J', L'I'); std::wstring ciphertext; digram current_digram; wchar_t reminder = 0; while(!buffer.empty() || reminder) { // get first if(reminder) { current_digram.first = reminder; reminder = 0; } else { while(!buffer.empty() && !isalpha(buffer.front(), loc)) ciphertext.append(1, pfront(buffer)); if(buffer.empty()) break; current_digram.first = pfront(buffer); } // get second if(buffer.empty() || !isalpha(buffer.front(), loc)) current_digram.second = LEAST_FR; else current_digram.second = pfront(buffer); reminder = rule_1(current_digram); perform(current_digram); ciphertext.append(1, current_digram.first); ciphertext.append(1, current_digram.second); } return converter.to_bytes(ciphertext); } std::string Playfair::decrypt(const std::string & ciphertext) { state_encrypt = false; std::wstring buffer = converter.from_bytes(ciphertext); touppers(buffer); std::wstring plaintext; digram current_digram; while(!buffer.empty()) { // get first while(!buffer.empty() && !isalpha(buffer.front(), loc)) plaintext.append(1, pfront(buffer)); if(buffer.empty()) break; current_digram.first = pfront(buffer); // get second current_digram.second = pfront(buffer); perform(current_digram); plaintext.append(1, current_digram.first); plaintext.append(1, current_digram.second); } return converter.to_bytes(plaintext); } void touppers(std::wstring & s) { std::transform( s.begin(), s.end(), s.begin(), [](wchar_t ch) { return toupper(ch, loc); } ); } wchar_t pfront(std::wstring & str) { wchar_t buffer = str.front(); str.erase(0,1); return buffer; } void create_Polybius_Square(std::vector< std::vector<wchar_t> > & matrix, std::wstring r_key, bool is_english) { int matrix_dim, matrix_size, alph_len; wchar_t letter; // determine matrix's properties matrix_dim = is_english ? MX_S_ENG : MX_S_RUS; matrix_size = matrix_dim * matrix_dim; alph_len = is_english ? ALPH_ENG : ALPH_RUS; letter = is_english ? L'A' : L'А'; // set matrix's size matrix.resize(matrix_dim); for(auto & t: matrix) t.resize(matrix_dim); // input the key to the matrix int key_len = r_key.size(); for(int i = 0; i < key_len; i++) matrix[i / matrix_dim][i % matrix_dim] = r_key[i]; // if language is english then drop out letter 'J' if(is_english) { r_key.append(1, 'J'); alph_len--; } // fill remaining letters to the table for(int i = key_len; i < alph_len; i++) { while(r_key.find(letter) != std::string::npos) letter++; matrix[i / matrix_dim][i % matrix_dim] = letter++; } // fill the void for(int i = alph_len; i < matrix_size; i++) matrix[i / matrix_dim][i % matrix_size] = SPACE_WC; } coords find_letter(const std::vector< std::vector<wchar_t> > & table, wchar_t ch) { int x = -1, y = -1; for(int i = 0; i < table.size(); i++) for(int j = 0; j < table[i].size(); j++) if(table[i][j] == ch) { x = i; y = j; break; } return coords(x, y); }
30.42953
112
0.597706
KoSeAn97
fc0a255f8462c18869fcd6916641e5daa2a46017
835
cpp
C++
Gaina.cpp
Dimi-T/POO-Lab12
6c228e6356eeff5ba455d094cdbf6aa846a631c2
[ "MIT" ]
null
null
null
Gaina.cpp
Dimi-T/POO-Lab12
6c228e6356eeff5ba455d094cdbf6aa846a631c2
[ "MIT" ]
null
null
null
Gaina.cpp
Dimi-T/POO-Lab12
6c228e6356eeff5ba455d094cdbf6aa846a631c2
[ "MIT" ]
null
null
null
#include "Gaina.h" Gaina::Gaina():Hambar() { } Gaina::Gaina(int nr_animale):Hambar(nr_animale) { } Gaina::Gaina(const Gaina& obj) { *this = obj; } Gaina::~Gaina() { } Gaina& Gaina::operator=(const Gaina& obj) { this->nr_animale = obj.nr_animale; return *this; } void Gaina::afisare(ostream& out) { out << "Animal: Gaina, Numar animale: " << this->nr_animale << ", Mancare consumate de 1 animal(Kg) - Graunte: " << tip.get_graunte() << endl; } double Gaina::get_consum_nutret() { return 0.0; } double Gaina::get_consum_iarba() { return 0.0; } double Gaina::get_consum_graunte() { return nr_animale * tip.get_graunte(); } double Gaina::get_total() { return get_consum_graunte(); } ostream& operator<<(ostream& out, Gaina& obj) { obj.afisare(out); return out; }
14.910714
144
0.626347
Dimi-T
fc0aad87fcce1efcc823c926ae9f36f7a6a433bd
1,130
cpp
C++
higan/sfc/expansion/expansion.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
higan/sfc/expansion/expansion.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
higan/sfc/expansion/expansion.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
#include <sfc/sfc.hpp> namespace SuperFamicom { ExpansionPort expansionPort; Expansion::Expansion() { if(!handle()) create(Expansion::Enter, 1); } Expansion::~Expansion() { scheduler.remove(*this); } auto Expansion::Enter() -> void { while(true) scheduler.synchronize(), expansionPort.device->main(); } auto Expansion::main() -> void { step(1); synchronize(cpu); } // auto ExpansionPort::connect(uint deviceID) -> void { if(!system.loaded()) return; delete device; switch(deviceID) { default: case ID::Device::None: device = new Expansion; break; case ID::Device::Satellaview: device = new Satellaview; break; case ID::Device::S21FX: device = new S21FX; break; } cpu.peripherals.reset(); if(auto device = controllerPort1.device) cpu.peripherals.append(device); if(auto device = controllerPort2.device) cpu.peripherals.append(device); if(auto device = expansionPort.device) cpu.peripherals.append(device); } auto ExpansionPort::power() -> void { } auto ExpansionPort::unload() -> void { delete device; device = nullptr; } auto ExpansionPort::serialize(serializer& s) -> void { } }
20.925926
74
0.699115
13824125580
fc0ad633ccb12312afee8de445a4c5bb98dc3e39
289
cpp
C++
QtOrmTests/QueryModelsTest/D.cpp
rensfo/QtOrm
46a16ee507cff4b1367b674420365137bf20aa9f
[ "MIT" ]
null
null
null
QtOrmTests/QueryModelsTest/D.cpp
rensfo/QtOrm
46a16ee507cff4b1367b674420365137bf20aa9f
[ "MIT" ]
1
2016-11-04T14:26:58.000Z
2016-11-04T14:27:57.000Z
QtOrmTests/QueryModelsTest/D.cpp
rensfo/QtOrm
46a16ee507cff4b1367b674420365137bf20aa9f
[ "MIT" ]
null
null
null
#include "D.h" D::D(QObject *parent) : QObject(parent){ } D::~D() { } QSharedPointer<KindA> D::getKindA() const { return kindA; } void D::setKindA(QSharedPointer<KindA> value) { kindA = value; } long D::getId() const { return id; } void D::setId(long value) { id = value; }
11.56
47
0.619377
rensfo
fc0b2647e0f66ade4bdcfa23a7f3470c66dac983
313
cpp
C++
BCM2/src/main.cpp
Zardium/blockcraftmine2
d2a570e3ab35c756ffaf2ac83849a5d878841f3f
[ "Apache-2.0" ]
null
null
null
BCM2/src/main.cpp
Zardium/blockcraftmine2
d2a570e3ab35c756ffaf2ac83849a5d878841f3f
[ "Apache-2.0" ]
null
null
null
BCM2/src/main.cpp
Zardium/blockcraftmine2
d2a570e3ab35c756ffaf2ac83849a5d878841f3f
[ "Apache-2.0" ]
null
null
null
// Local Headers #include "pch.hpp" #include "BCM2.hpp" // System Headers #include <glad/glad.h> #include <GLFW/glfw3.h> // Standard Headers #include <cstdio> #include <cstdlib> #include <thread> int main(int argc, char * argv[]) { BlockCraftMine2::Game main_game; main_game(); return EXIT_SUCCESS; }
15.65
35
0.693291
Zardium
fc0db890723239f5296e51413438a65d55ace6f1
1,191
cc
C++
HDU/5095_Linearization_of_the_kernel_functions_in_SVM/5095.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
1
2019-05-05T03:51:20.000Z
2019-05-05T03:51:20.000Z
HDU/5095_Linearization_of_the_kernel_functions_in_SVM/5095.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
null
null
null
HDU/5095_Linearization_of_the_kernel_functions_in_SVM/5095.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { string str = "pqruvwxyz"; int t; cin >> t; while (t--) { int num[10]; for (int i = 0; i < 10; ++i) cin >> num[i]; bool flag = false; for (int i = 0; i < 9; ++i) { if (num[i] == 0) continue; if (flag) { if (num[i] == 1) cout << "+"; else if (num[i] == -1) cout << "-"; else if (num[i] > 0) cout << "+" << num[i]; else cout << num[i]; } else { if (num[i] == 1) ; else if (num[i] == -1) cout << "-"; else cout << num[i]; } cout << str[i]; flag = true; } if (flag) { if (num[9] > 0) cout << "+" << num[9]; else if (num[9] < 0) cout << num[9]; } else { cout << num[9]; } cout << endl; } return 0; }
20.894737
42
0.280437
pdszhh
fc1765053d9939f891a86fa23721432cce0bc871
18,135
cpp
C++
core/variant_call.cpp
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
core/variant_call.cpp
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
core/variant_call.cpp
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
/*************************************************************************/ /* variant_call.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "variant.h" #include "core/color_names.inc" #include "core/container_tools.h" #include "core/string_utils.inl" #include "core/crypto/crypto_core.h" #include "core/math/aabb.h" #include "core/math/basis.h" #include "core/math/plane.h" #include "core/math/quat.h" #include "core/math/transform.h" #include "core/math/transform_2d.h" #include "core/math/vector3.h" #include "core/method_info.h" #include "core/object.h" #include "core/script_language.h" #include "core/string.h" #include "core/vector.h" #include "core/rid.h" namespace { using VariantConstructFunc = void (*)(Variant&, const Variant&); struct VariantAutoCaster { const Variant &from; constexpr VariantAutoCaster(const Variant&src) : from(src) {} operator Variant() const{ return from; } template<class T> operator T() const{ return from.as<T>(); } }; struct _VariantCall { struct ConstructData { int arg_count; Vector<VariantType> arg_types; Vector<StringName> arg_names; VariantConstructFunc func; }; struct ConstructFunc { Vector<ConstructData> constructors; }; static ConstructFunc *construct_funcs; static void Quat_init3(Variant &r_ret, const Variant &p_args) { r_ret = Quat(p_args.as<Vector3>()); } static void add_constructor(VariantConstructFunc p_func, const VariantType p_type, StringName p_name1, const VariantType p_type1) { ConstructData cd; cd.func = p_func; cd.arg_count = 0; cd.arg_count++; cd.arg_names.emplace_back(eastl::move(p_name1)); cd.arg_types.push_back(p_type1); construct_funcs[static_cast<int>(p_type)].constructors.emplace_back(cd); } struct ConstantData { HashMap<StringName, int> value; #ifdef DEBUG_ENABLED Vector<StringName> value_ordered; #endif HashMap<StringName, Variant> variant_value; }; static ConstantData *constant_data; static void add_constant(VariantType p_type, const StringName &p_constant_name, int p_constant_value) { constant_data[static_cast<int8_t>(p_type)].value[p_constant_name] = p_constant_value; #ifdef DEBUG_ENABLED constant_data[static_cast<int8_t>(p_type)].value_ordered.emplace_back(p_constant_name); #endif } static void add_variant_constant(VariantType p_type, const StringName &p_constant_name, const Variant &p_constant_value) { constant_data[static_cast<int8_t>(p_type)].variant_value[p_constant_name] = p_constant_value; } }; _VariantCall::ConstructFunc *_VariantCall::construct_funcs = nullptr; _VariantCall::ConstantData *_VariantCall::constant_data = nullptr; } Variant Variant::construct_default(const VariantType p_type) { switch (p_type) { case VariantType::NIL: return Variant(); // atomic types case VariantType::BOOL: return Variant(false); case VariantType::INT: return Variant(0); case VariantType::FLOAT: return Variant(0.0f); case VariantType::STRING: return String(); // math types case VariantType::VECTOR2: return Vector2(); // 5 case VariantType::RECT2: return Rect2(); case VariantType::VECTOR3: return Vector3(); case VariantType::TRANSFORM2D: return Transform2D(); case VariantType::PLANE: return Plane(); case VariantType::QUAT: return Quat(); case VariantType::AABB: return ::AABB(); // 10 case VariantType::BASIS: return Basis(); case VariantType::TRANSFORM: return Transform(); // misc types case VariantType::COLOR: return Color(); case VariantType::STRING_NAME: return StringName(); case VariantType::NODE_PATH: return NodePath(); // 15 case VariantType::_RID: return RID(); case VariantType::OBJECT: return Variant(static_cast<Object *>(nullptr)); case VariantType::CALLABLE: return (Variant)Callable(); case VariantType::SIGNAL: return (Variant)Signal(); case VariantType::DICTIONARY: return Dictionary(); case VariantType::ARRAY: return Array(); // 20 case VariantType::POOL_BYTE_ARRAY: return PoolByteArray(); case VariantType::POOL_INT_ARRAY: return PoolIntArray(); case VariantType::POOL_REAL_ARRAY: return PoolRealArray(); case VariantType::POOL_STRING_ARRAY: return PoolStringArray(); case VariantType::POOL_VECTOR2_ARRAY: return Variant(PoolVector2Array()); // 25 case VariantType::POOL_VECTOR3_ARRAY: return PoolVector3Array(); case VariantType::POOL_COLOR_ARRAY: return PoolColorArray(); case VariantType::VARIANT_MAX: default: return Variant(); } } Variant Variant::construct(const VariantType p_type, const Variant &p_arg, Callable::CallError &r_error) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; ERR_FAIL_INDEX_V(int(p_type), int(VariantType::VARIANT_MAX), Variant()); r_error.error = Callable::CallError::CALL_OK; if (p_arg.type == p_type) { return p_arg; //copy construct } if (can_convert(p_arg.type, p_type)) { //near match construct switch (p_type) { case VariantType::NIL: { return Variant(); } case VariantType::BOOL: { return Variant(static_cast<bool>(p_arg)); } case VariantType::INT: { return static_cast<int64_t>(p_arg); } case VariantType::FLOAT: { return static_cast<real_t>(p_arg); } case VariantType::STRING: { return static_cast<String>(p_arg); } case VariantType::VECTOR2: { return static_cast<Vector2>(p_arg); } case VariantType::RECT2: return static_cast<Rect2>(p_arg); case VariantType::VECTOR3: return static_cast<Vector3>(p_arg); case VariantType::TRANSFORM2D: return static_cast<Transform2D>(p_arg); case VariantType::PLANE: return static_cast<Plane>(p_arg); case VariantType::QUAT: return static_cast<Quat>(p_arg); case VariantType::AABB: return p_arg.as<::AABB>(); // 10 case VariantType::BASIS: return static_cast<Basis>(p_arg); case VariantType::TRANSFORM: return Transform(static_cast<Transform>(p_arg)); // misc types case VariantType::COLOR: return p_arg.type == VariantType::STRING ? Color::html(static_cast<String>(p_arg)) : Color::hex(static_cast<uint32_t>(p_arg)); case VariantType::STRING_NAME: return p_arg.as<StringName>(); case VariantType::NODE_PATH: return NodePath(static_cast<NodePath>(p_arg)); // 15 case VariantType::_RID: return static_cast<RID>(p_arg); case VariantType::OBJECT: return Variant(p_arg.as<Object *>()); case VariantType::CALLABLE: return Variant((Callable)p_arg); case VariantType::SIGNAL: return Variant((Signal)p_arg); case VariantType::DICTIONARY: return static_cast<Dictionary>(p_arg); case VariantType::ARRAY: return static_cast<Array>(p_arg); // 20 // arrays case VariantType::POOL_BYTE_ARRAY: return static_cast<PoolByteArray>(p_arg); case VariantType::POOL_INT_ARRAY: return static_cast<PoolIntArray>(p_arg); case VariantType::POOL_REAL_ARRAY: return static_cast<PoolRealArray>(p_arg); case VariantType::POOL_STRING_ARRAY: return static_cast<PoolStringArray>(p_arg); case VariantType::POOL_VECTOR2_ARRAY: return Variant(static_cast<PoolVector2Array>(p_arg)); // 25 case VariantType::POOL_VECTOR3_ARRAY: return static_cast<PoolVector3Array>(p_arg); case VariantType::POOL_COLOR_ARRAY: return static_cast<PoolColorArray>(p_arg); default: return Variant(); } } _VariantCall::ConstructFunc &c = _VariantCall::construct_funcs[static_cast<int>(p_type)]; for (const _VariantCall::ConstructData &cd : c.constructors) { if (cd.arg_count != 1) continue; //validate parameters if (!Variant::can_convert(p_arg.type, cd.arg_types[0])) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; //no such constructor r_error.argument = 0; r_error.expected = cd.arg_types[0]; return Variant(); } Variant v; cd.func(v, p_arg); return v; } r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; //no such constructor return Variant(); } void Variant::get_constructor_list(VariantType p_type, Vector<MethodInfo> *p_list) { ERR_FAIL_INDEX(int(p_type), int(VariantType::VARIANT_MAX)); //custom constructors for (const _VariantCall::ConstructData &cd : _VariantCall::construct_funcs[static_cast<int>(p_type)].constructors) { MethodInfo mi; mi.name = Variant::interned_type_name(p_type); mi.return_val.type = p_type; for (int i = 0; i < cd.arg_count; i++) { PropertyInfo pi; pi.name = StringName(cd.arg_names[i]); pi.type = cd.arg_types[i]; mi.arguments.emplace_back(eastl::move(pi)); } p_list->push_back(mi); } //default constructors for (int i = 0; i < static_cast<int>(VariantType::VARIANT_MAX); i++) { if (i == static_cast<int>(p_type)) continue; if (!Variant::can_convert(static_cast<VariantType>(i), p_type)) continue; MethodInfo mi(p_type); mi.name = eastl::move(Variant::interned_type_name(p_type)); PropertyInfo pi; pi.name = "from"; pi.type = static_cast<VariantType>(i); mi.arguments.emplace_back(eastl::move(pi)); p_list->emplace_back(eastl::move(mi)); } } void Variant::get_constants_for_type(VariantType p_type, Vector<StringName> *p_constants) { ERR_FAIL_INDEX((int)p_type, (int)VariantType::VARIANT_MAX); _VariantCall::ConstantData &cd = _VariantCall::constant_data[static_cast<int>(p_type)]; #ifdef DEBUG_ENABLED for (const StringName &E : cd.value_ordered) { p_constants->push_back(E); #else for (const auto &E : cd.value) { p_constants->emplace_back(E.first); #endif } for (eastl::pair<const StringName,Variant> &E : cd.variant_value) { p_constants->push_back(E.first); } } bool Variant::has_constant(VariantType p_type, const StringName &p_value) { ERR_FAIL_INDEX_V((int)p_type, (int)VariantType::VARIANT_MAX, false); _VariantCall::ConstantData &cd = _VariantCall::constant_data[static_cast<int>(p_type)]; return cd.value.contains(p_value) || cd.variant_value.contains(p_value); } Variant Variant::get_constant_value(VariantType p_type, const StringName &p_value, bool *r_valid) { if (r_valid) *r_valid = false; ERR_FAIL_INDEX_V((int)p_type, (int)VariantType::VARIANT_MAX, 0); _VariantCall::ConstantData &cd = _VariantCall::constant_data[static_cast<int>(p_type)]; auto E = cd.value.find(p_value); if (E==cd.value.end()) { auto F = cd.variant_value.find(p_value); if (F!=cd.variant_value.end()) { if (r_valid) *r_valid = true; return F->second; } return -1; } if (r_valid) *r_valid = true; return E->second; } void register_variant_methods() { _VariantCall::construct_funcs = memnew_arr(_VariantCall::ConstructFunc, static_cast<int>(VariantType::VARIANT_MAX)); _VariantCall::constant_data = memnew_arr(_VariantCall::ConstantData, static_cast<int>(VariantType::VARIANT_MAX)); /* STRING */ /* REGISTER CONSTRUCTORS */ _VariantCall::add_constructor(_VariantCall::Quat_init3, VariantType::QUAT, "euler", VariantType::VECTOR3); /* REGISTER CONSTANTS */ for (const eastl::pair<const char *const,Color> &color : _named_colors) { _VariantCall::add_variant_constant(VariantType::COLOR, StringName(color.first), color.second); } _VariantCall::add_constant(VariantType::VECTOR3, "AXIS_X", Vector3::AXIS_X); _VariantCall::add_constant(VariantType::VECTOR3, "AXIS_Y", Vector3::AXIS_Y); _VariantCall::add_constant(VariantType::VECTOR3, "AXIS_Z", Vector3::AXIS_Z); _VariantCall::add_variant_constant(VariantType::VECTOR3, "ZERO", Vector3(0, 0, 0)); _VariantCall::add_variant_constant(VariantType::VECTOR3, "ONE", Vector3(1, 1, 1)); _VariantCall::add_variant_constant(VariantType::VECTOR3, "INF", Vector3(Math_INF, Math_INF, Math_INF)); _VariantCall::add_variant_constant(VariantType::VECTOR3, "LEFT", Vector3(-1, 0, 0)); _VariantCall::add_variant_constant(VariantType::VECTOR3, "RIGHT", Vector3(1, 0, 0)); _VariantCall::add_variant_constant(VariantType::VECTOR3, "UP", Vector3(0, 1, 0)); _VariantCall::add_variant_constant(VariantType::VECTOR3, "DOWN", Vector3(0, -1, 0)); _VariantCall::add_variant_constant(VariantType::VECTOR3, "FORWARD", Vector3(0, 0, -1)); _VariantCall::add_variant_constant(VariantType::VECTOR3, "BACK", Vector3(0, 0, 1)); _VariantCall::add_constant(VariantType::VECTOR2, "AXIS_X", Vector2::AXIS_X); _VariantCall::add_constant(VariantType::VECTOR2, "AXIS_Y", Vector2::AXIS_Y); _VariantCall::add_variant_constant(VariantType::VECTOR2, "ZERO", Vector2(0, 0)); _VariantCall::add_variant_constant(VariantType::VECTOR2, "ONE", Vector2(1, 1)); _VariantCall::add_variant_constant(VariantType::VECTOR2, "INF", Vector2(Math_INF, Math_INF)); _VariantCall::add_variant_constant(VariantType::VECTOR2, "LEFT", Vector2(-1, 0)); _VariantCall::add_variant_constant(VariantType::VECTOR2, "RIGHT", Vector2(1, 0)); _VariantCall::add_variant_constant(VariantType::VECTOR2, "UP", Vector2(0, -1)); _VariantCall::add_variant_constant(VariantType::VECTOR2, "DOWN", Vector2(0, 1)); _VariantCall::add_variant_constant(VariantType::TRANSFORM2D, "IDENTITY", Transform2D()); _VariantCall::add_variant_constant(VariantType::TRANSFORM2D, "FLIP_X", Transform2D(-1, 0, 0, 1, 0, 0)); _VariantCall::add_variant_constant(VariantType::TRANSFORM2D, "FLIP_Y", Transform2D( 1, 0, 0, -1, 0, 0)); _VariantCall::add_variant_constant(VariantType::TRANSFORM, "IDENTITY", Transform()); _VariantCall::add_variant_constant(VariantType::TRANSFORM, "FLIP_X", Transform(-1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)); _VariantCall::add_variant_constant(VariantType::TRANSFORM, "FLIP_Y", Transform( 1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0)); _VariantCall::add_variant_constant(VariantType::TRANSFORM, "FLIP_Z", Transform( 1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0)); _VariantCall::add_variant_constant(VariantType::BASIS, "IDENTITY", Basis()); _VariantCall::add_variant_constant(VariantType::BASIS, "FLIP_X", Basis(-1, 0, 0, 0, 1, 0, 0, 0, 1)); _VariantCall::add_variant_constant(VariantType::BASIS, "FLIP_Y", Basis( 1, 0, 0, 0, -1, 0, 0, 0, 1)); _VariantCall::add_variant_constant(VariantType::BASIS, "FLIP_Z", Basis( 1, 0, 0, 0, 1, 0, 0, 0, -1)); _VariantCall::add_variant_constant(VariantType::PLANE, "PLANE_YZ", Plane(Vector3(1, 0, 0), 0)); _VariantCall::add_variant_constant(VariantType::PLANE, "PLANE_XZ", Plane(Vector3(0, 1, 0), 0)); _VariantCall::add_variant_constant(VariantType::PLANE, "PLANE_XY", Plane(Vector3(0, 0, 1), 0)); _VariantCall::add_variant_constant(VariantType::QUAT, "IDENTITY", Quat(0, 0, 0, 1)); } void unregister_variant_methods() { memdelete_arr(_VariantCall::construct_funcs); memdelete_arr(_VariantCall::constant_data); }
42.174419
163
0.636173
ZopharShinta
fc1786ec223203c0d0cc2c157a0077dd0a4cb4ea
8,102
cpp
C++
tests/test_progress.cpp
jinyyu/kvd
f3a2f7944b037ee59f26e7e8bf69024686023fd0
[ "MIT" ]
2
2019-04-18T15:15:20.000Z
2019-08-16T03:01:16.000Z
tests/test_progress.cpp
jinyyu/kvd
f3a2f7944b037ee59f26e7e8bf69024686023fd0
[ "MIT" ]
null
null
null
tests/test_progress.cpp
jinyyu/kvd
f3a2f7944b037ee59f26e7e8bf69024686023fd0
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <raft-kv/raft/progress.h> using namespace kv; static bool cmp_InFlights(const InFlights& l, const InFlights& r) { return l.start == r.start && l.count == r.count && l.size == r.size && l.buffer == r.buffer; } TEST(progress, add) { InFlights in(10); in.buffer.resize(10, 0); for (uint32_t i = 0; i < 5; i++) { in.add(i); } InFlights wantIn(10); wantIn.start = 0; wantIn.count = 5; wantIn.buffer = std::vector<uint64_t>{0, 1, 2, 3, 4, 0, 0, 0, 0, 0}; ASSERT_TRUE(cmp_InFlights(wantIn, in)); InFlights wantIn2(10); wantIn.start = 0; wantIn.count = 10; wantIn.buffer = std::vector<uint64_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; ASSERT_FALSE(cmp_InFlights(wantIn2, in)); // rotating case InFlights in2(10); in2.start = 5; in2.size = 10; in2.buffer.resize(10, 0); for (uint32_t i = 0; i < 5; i++) { in2.add(i); } InFlights wantIn21(10); wantIn.start = 5; wantIn.count = 5; wantIn.buffer = std::vector<uint64_t>{0, 0, 0, 0, 0, 0, 1, 2, 3, 4}; ASSERT_FALSE(cmp_InFlights(wantIn2, in2)); for (uint32_t i = 0; i < 5; i++) { in2.add(i); } InFlights wantIn22(10); wantIn.start = 10; wantIn.count = 10; wantIn.buffer = std::vector<uint64_t>{5, 6, 7, 8, 9, 0, 1, 2, 3, 4}; ASSERT_FALSE(cmp_InFlights(wantIn2, in2)); ASSERT_FALSE(cmp_InFlights(wantIn22, in2)); } TEST(progress, freeto) { InFlights in(10); for (uint32_t i = 0; i < 10; i++) { in.add(i); } in.free_to(4); InFlights wantIn(10); wantIn.start = 5; wantIn.count = 5; wantIn.buffer = std::vector<uint64_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; ASSERT_TRUE(cmp_InFlights(wantIn, in)); in.free_to(8); InFlights wantIn2(10); wantIn2.start = 9; wantIn2.count = 1; wantIn2.buffer = std::vector<uint64_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; ASSERT_TRUE(cmp_InFlights(wantIn2, in)); // rotating case for (uint32_t i = 10; i < 15; i++) { in.add(i); } in.free_to(12); InFlights wantIn3(10); wantIn3.start = 3; wantIn3.count = 2; wantIn3.size = 10; wantIn3.buffer = std::vector<uint64_t>{10, 11, 12, 13, 14, 5, 6, 7, 8, 9}; ASSERT_TRUE(cmp_InFlights(wantIn3, in)); in.free_to(14); InFlights wantIn4(10); wantIn4.start = 0; wantIn4.count = 0; wantIn4.size = 10; wantIn4.buffer = std::vector<uint64_t>{10, 11, 12, 13, 14, 5, 6, 7, 8, 9}; ASSERT_TRUE(cmp_InFlights(wantIn4, in)); } TEST(progress, FreeFirstOne) { InFlights in(10); for (uint32_t i = 0; i < 10; i++) { in.add(i); } in.free_first_one(); InFlights wantIn(10); wantIn.start = 1; wantIn.count = 9; wantIn.buffer = std::vector<uint64_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; ASSERT_TRUE(cmp_InFlights(wantIn, in)); } TEST(progress, BecomeProbe) { struct Test { ProgressPtr pr; uint64_t wnext; }; std::vector<Test> tests; { ProgressPtr pr(new Progress(256)); pr->state = ProgressStateReplicate; pr->match = 1; pr->next = 5; tests.push_back(Test{.pr = pr, .wnext = 2}); } { ProgressPtr pr(new Progress(256)); pr->state = ProgressStateSnapshot; pr->match = 1; pr->next = 5; pr->pending_snapshot = 10; tests.push_back(Test{.pr = pr, .wnext = 11}); } { ProgressPtr pr(new Progress(256)); pr->state = ProgressStateSnapshot; pr->match = 1; pr->next = 5; pr->pending_snapshot = 0; tests.push_back(Test{.pr = pr, .wnext = 2}); } for (Test& test : tests) { test.pr->become_probe(); ASSERT_TRUE(test.pr->match == 1); ASSERT_TRUE(test.pr->state == ProgressStateProbe); ASSERT_TRUE(test.pr->next == test.wnext); } } TEST(progress, BecomeReplicate) { ProgressPtr pr(new Progress(256)); pr->match = 1; pr->next = 5; pr->become_replicate(); ASSERT_TRUE(pr->next = pr->match + 1); ASSERT_TRUE(pr->state = ProgressStateReplicate); } TEST(progress, BecomeSnapshot) { ProgressPtr pr(new Progress(256)); pr->match = 1; pr->next = 5; pr->become_snapshot(10); ASSERT_TRUE(pr->match == 1); ASSERT_TRUE(pr->state == ProgressStateSnapshot); ASSERT_TRUE(pr->pending_snapshot == 10); } TEST(progress, Update) { uint64_t prevM = 3; uint64_t prevN = 5; struct Test { uint64_t update; uint64_t wm; uint64_t wn; bool wok; }; std::vector<Test> tests; tests.push_back(Test{.update = prevM - 1, .wm = prevM, .wn = prevN, .wok = false}); tests.push_back(Test{.update = prevM, .wm = prevM, .wn = prevN, .wok = false}); tests.push_back(Test{.update = prevM + 1, .wm = prevM + 1, .wn = prevN, .wok = true}); tests.push_back(Test{.update = prevM + 2, .wm = prevM + 2, .wn = prevN + 1, .wok = true}); for (Test& test: tests) { ProgressPtr pr(new Progress(256)); pr->match = prevM; pr->next = prevN; bool ok = pr->maybe_update(test.update); ASSERT_TRUE(ok == test.wok); ASSERT_TRUE(pr->match == test.wm); ASSERT_TRUE(pr->next == test.wn); } } TEST(progress, MaybeDecr) { struct Test { ProgressState state; uint64_t m; uint64_t n; uint64_t rejected; uint64_t last; bool w; uint64_t wn; }; std::vector<Test> tests; // state replicate and rejected is not greater than match tests .push_back(Test{.state = ProgressStateReplicate, .m = 5, .n = 10, .rejected = 5, .last = 5, .w = false, .wn = 10}); // state replicate and rejected is not greater than match tests .push_back(Test{.state = ProgressStateReplicate, .m = 5, .n = 10, .rejected = 4, .last = 5, .w = false, .wn = 10}); // state replicate and rejected is greater than match // directly decrease to match+1 tests .push_back(Test{.state = ProgressStateReplicate, .m = 5, .n = 10, .rejected = 9, .last = 9, .w = true, .wn = 6}); // next-1 != rejected is always false tests.push_back(Test{.state = ProgressStateProbe, .m = 0, .n = 0, .rejected = 0, .last = 0, .w = false, .wn = 0}); // next-1 != rejected is always false tests.push_back(Test{.state = ProgressStateProbe, .m = 0, .n = 10, .rejected = 5, .last = 5, .w = false, .wn = 10}); // next>1 = decremented by 1 tests.push_back(Test{.state = ProgressStateProbe, .m = 0, .n = 10, .rejected = 9, .last = 9, .w = true, .wn = 9}); tests.push_back(Test{.state = ProgressStateProbe, .m = 0, .n = 2, .rejected = 1, .last = 1, .w = true, .wn = 1}); tests.push_back(Test{.state = ProgressStateProbe, .m = 0, .n = 1, .rejected = 0, .last = 0, .w = true, .wn = 1}); tests.push_back(Test{.state = ProgressStateProbe, .m = 0, .n = 10, .rejected = 9, .last = 2, .w = true, .wn = 3}); tests.push_back(Test{.state = ProgressStateProbe, .m = 0, .n = 10, .rejected = 9, .last = 0, .w = true, .wn = 1}); for (Test& test: tests) { ProgressPtr pr(new Progress(256)); pr->state = test.state; pr->match = test.m; pr->next = test.n; bool ok = pr->maybe_decreases_to(test.rejected, test.last); ASSERT_TRUE(ok == test.w); ASSERT_TRUE(pr->match == test.m); ASSERT_TRUE(pr->next == test.wn); } } TEST(progress, IsPaused) { struct Test { ProgressState state; bool paused; bool w; }; std::vector<Test> tests; tests.push_back(Test{.state = ProgressStateProbe, .paused = false, .w = false}); tests.push_back(Test{.state = ProgressStateProbe, .paused = true, .w = true}); tests.push_back(Test{.state = ProgressStateReplicate, .paused = false, .w = false}); tests.push_back(Test{.state = ProgressStateReplicate, .paused = true, .w = false}); tests.push_back(Test{.state = ProgressStateSnapshot, .paused = false, .w = true}); tests.push_back(Test{.state = ProgressStateSnapshot, .paused = true, .w = true}); for (Test& test: tests) { ProgressPtr pr(new Progress(256)); pr->state = test.state; pr->paused = test.paused; ASSERT_TRUE(pr->is_paused() == test.w); } } TEST(progress, resume) { ProgressPtr pr(new Progress(256)); pr->next = 2; pr->paused = true; pr->maybe_decreases_to(2, 2); ASSERT_TRUE(pr->paused); pr->maybe_update(2); ASSERT_FALSE(pr->paused); } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
28.034602
121
0.618489
jinyyu
fc1efbfa3bb6422aee8616cbc642d6897baf3344
6,569
cpp
C++
src/llc.cpp
salessandri/libtins
2cf61403e186cda93c48ffb4310ff46eddb8dd20
[ "BSD-2-Clause" ]
null
null
null
src/llc.cpp
salessandri/libtins
2cf61403e186cda93c48ffb4310ff46eddb8dd20
[ "BSD-2-Clause" ]
null
null
null
src/llc.cpp
salessandri/libtins
2cf61403e186cda93c48ffb4310ff46eddb8dd20
[ "BSD-2-Clause" ]
1
2020-11-12T21:19:10.000Z
2020-11-12T21:19:10.000Z
/* * Copyright (c) 2014, Matias Fontanini * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <stdexcept> #include <cstring> #ifdef TINS_DEBUG #include <cassert> #endif #include "llc.h" #include "stp.h" #include "rawpdu.h" #include "exceptions.h" namespace Tins { const uint8_t LLC::GLOBAL_DSAP_ADDR = 0xFF; const uint8_t LLC::NULL_ADDR = 0x00; LLC::LLC() : _type(LLC::INFORMATION) { memset(&_header, 0, sizeof(llchdr)); control_field_length = 2; memset(&control_field, 0, sizeof(control_field)); information_field_length = 0; } LLC::LLC(uint8_t dsap, uint8_t ssap) : _type(LLC::INFORMATION) { _header.dsap = dsap; _header.ssap = ssap; control_field_length = 2; memset(&control_field, 0, sizeof(control_field)); information_field_length = 0; } LLC::LLC(const uint8_t *buffer, uint32_t total_sz) { // header + 1 info byte if(total_sz < sizeof(_header) + 1) throw malformed_packet(); std::memcpy(&_header, buffer, sizeof(_header)); buffer += sizeof(_header); total_sz -= sizeof(_header); information_field_length = 0; if ((buffer[0] & 0x03) == LLC::UNNUMBERED) { if(total_sz < sizeof(un_control_field)) throw malformed_packet(); type(LLC::UNNUMBERED); std::memcpy(&control_field.unnumbered, buffer, sizeof(un_control_field)); buffer += sizeof(un_control_field); total_sz -= sizeof(un_control_field); //TODO: Create information fields if corresponding. } else { if(total_sz < sizeof(info_control_field)) throw malformed_packet(); type((Format)(buffer[0] & 0x03)); control_field_length = 2; std::memcpy(&control_field.info, buffer, sizeof(info_control_field)); buffer += 2; total_sz -= 2; } if(total_sz > 0) { if(dsap() == 0x42 && ssap() == 0x42) inner_pdu(new Tins::STP(buffer, total_sz)); else inner_pdu(new Tins::RawPDU(buffer, total_sz)); } } void LLC::group(bool value) { if (value) { _header.dsap |= 0x01; } else { _header.dsap &= 0xFE; } } void LLC::dsap(uint8_t new_dsap) { _header.dsap = new_dsap; } void LLC::response(bool value) { if (value) { _header.ssap |= 0x01; } else { _header.ssap &= 0xFE; } } void LLC::ssap(uint8_t new_ssap) { _header.ssap = new_ssap; } void LLC::type(LLC::Format type) { _type = type; switch (type) { case LLC::INFORMATION: control_field_length = 2; control_field.info.type_bit = 0; break; case LLC::SUPERVISORY: control_field_length = 2; control_field.super.type_bit = 1; break; case LLC::UNNUMBERED: control_field_length = 1; control_field.unnumbered.type_bits = 3; break; } } void LLC::send_seq_number(uint8_t seq_number) { if (type() != LLC::INFORMATION) return; control_field.info.send_seq_num = seq_number; } void LLC::receive_seq_number(uint8_t seq_number) { switch (type()) { case LLC::UNNUMBERED: return; case LLC::INFORMATION: control_field.info.recv_seq_num = seq_number; break; case LLC::SUPERVISORY: control_field.super.recv_seq_num = seq_number; break; } } void LLC::poll_final(bool value) { switch (type()) { case LLC::UNNUMBERED: control_field.unnumbered.poll_final_bit = value; break; case LLC::INFORMATION: control_field.info.poll_final_bit = value; return; case LLC::SUPERVISORY: control_field.super.poll_final_bit = value; break; } } void LLC::supervisory_function(LLC::SupervisoryFunctions new_func) { if (type() != LLC::SUPERVISORY) return; control_field.super.supervisory_func = new_func; } void LLC::modifier_function(LLC::ModifierFunctions mod_func) { if (type() != LLC::UNNUMBERED) return; control_field.unnumbered.mod_func1 = mod_func >> 3; control_field.unnumbered.mod_func2 = mod_func & 0x07; } void LLC::add_xid_information(uint8_t xid_id, uint8_t llc_type_class, uint8_t receive_window) { field_type xid(3); xid[0] = xid_id; xid[1] = llc_type_class; xid[2] = receive_window; information_field_length += static_cast<uint8_t>(xid.size()); information_fields.push_back(xid); } uint32_t LLC::header_size() const { return sizeof(_header) + control_field_length + information_field_length; } void LLC::clear_information_fields() { information_field_length = 0; information_fields.clear(); } void LLC::write_serialization(uint8_t *buffer, uint32_t total_sz, const Tins::PDU *parent) { #ifdef TINS_DEBUG assert(total_sz >= header_size()); #endif if(inner_pdu() && inner_pdu()->pdu_type() == PDU::STP) { dsap(0x42); ssap(0x42); } std::memcpy(buffer, &_header, sizeof(_header)); buffer += sizeof(_header); switch (type()) { case LLC::UNNUMBERED: std::memcpy(buffer, &(control_field.unnumbered), sizeof(un_control_field)); buffer += sizeof(un_control_field); break; case LLC::INFORMATION: std::memcpy(buffer, &(control_field.info), sizeof(info_control_field)); buffer += sizeof(info_control_field); break; case LLC::SUPERVISORY: std::memcpy(buffer, &(control_field.super), sizeof(super_control_field)); buffer += sizeof(super_control_field); break; } for (std::list<field_type>::const_iterator it = information_fields.begin(); it != information_fields.end(); it++) { std::copy(it->begin(), it->end(), buffer); buffer += it->size(); } } }
27.60084
116
0.706348
salessandri
fc1f020afe3acad394af8c020777f964da209f1f
2,527
hh
C++
psana/psana/peakFinder/peakfinder8.hh
ZhenghengLi/lcls2
94e75c6536954a58c8937595dcac295163aa1cdf
[ "BSD-3-Clause-LBNL" ]
16
2017-11-09T17:10:56.000Z
2022-03-09T23:03:10.000Z
psana/psana/peakFinder/peakfinder8.hh
ZhenghengLi/lcls2
94e75c6536954a58c8937595dcac295163aa1cdf
[ "BSD-3-Clause-LBNL" ]
6
2017-12-12T19:30:05.000Z
2020-07-09T00:28:33.000Z
psana/psana/peakFinder/peakfinder8.hh
ZhenghengLi/lcls2
94e75c6536954a58c8937595dcac295163aa1cdf
[ "BSD-3-Clause-LBNL" ]
25
2017-09-18T20:02:43.000Z
2022-03-27T22:27:42.000Z
// This file is part of OM. // // OM is free software: you can redistribute it and/or modify it under the terms of // the GNU General Public License as published by the Free Software Foundation, either // version 3 of the License, or (at your option) any later version. // // OM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with OnDA. // If not, see <http://www.gnu.org/licenses/>. // // Copyright 2020 SLAC National Accelerator Laboratory // // Based on OnDA - Copyright 2014-2019 Deutsches Elektronen-Synchrotron DESY, // a research centre of the Helmholtz Association. #ifndef PEAKFINDER8_H #define PEAKFINDER8_H typedef struct { public: long nPeaks; long nHot; float peakResolution; // Radius of 80% of peaks float peakResolutionA; // Radius of 80% of peaks float peakDensity; // Density of peaks within this 80% figure float peakNpix; // Number of pixels in peaks float peakTotal; // Total integrated intensity in peaks int memoryAllocated; long nPeaks_max; float *peak_maxintensity; // Maximum intensity in peak float *peak_totalintensity; // Integrated intensity in peak float *peak_sigma; // Signal-to-noise ratio of peak float *peak_snr; // Signal-to-noise ratio of peak float *peak_npix; // Number of pixels in peak float *peak_com_x; // peak center of mass x (in raw layout) float *peak_com_y; // peak center of mass y (in raw layout) long *peak_com_index; // closest pixel corresponding to peak float *peak_com_x_assembled; // peak center of mass x (in assembled layout) float *peak_com_y_assembled; // peak center of mass y (in assembled layout) float *peak_com_r_assembled; // peak center of mass r (in assembled layout) float *peak_com_q; // Scattering vector of this peak float *peak_com_res; // REsolution of this peak } tPeakList; void allocatePeakList(tPeakList *peak, long NpeaksMax); void freePeakList(tPeakList peak); int peakfinder8(tPeakList *peaklist, float *data, char *mask, float *pix_r, long asic_nx, long asic_ny, long nasics_x, long nasics_y, float ADCthresh, float hitfinderMinSNR, long hitfinderMinPixCount, long hitfinderMaxPixCount, long hitfinderLocalBGRadius, char* outliersMask); #endif // PEAKFINDER8_H
43.568966
86
0.734863
ZhenghengLi
fc1fb8db83e54cf86864f1c20ee6f31ee9243501
4,104
cpp
C++
XJ Contests/2020/12.3/T3/C.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
XJ Contests/2020/12.3/T3/C.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
XJ Contests/2020/12.3/T3/C.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
/* the vast starry sky, bright for those who chase the light. */ #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; #define mk make_pair const int inf=(int)1e9; const ll INF=(ll)5e18; const int MOD=998244353; int _abs(int x){return x<0 ? -x : x;} int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;} int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;} #define mul(x,y) (ll)(x)*(y)%MOD void Add(int &x,int y){x+=y; if(x>=MOD) x-=MOD;} void Sub(int &x,int y){x-=y; if(x<0) x+=MOD;} void Mul(int &x,int y){x=mul(x,y);} int qpow(int x,int y){int ret=1; while(y){if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;} void checkmin(int &x,int y){if(x>y) x=y;} void checkmax(int &x,int y){if(x<y) x=y;} void checkmin(ll &x,ll y){if(x>y) x=y;} void checkmax(ll &x,ll y){if(x<y) x=y;} #define out(x) cerr<<#x<<'='<<x<<' ' #define outln(x) cerr<<#x<<'='<<x<<endl #define sz(x) (int)(x).size() inline int read(){ int x=0,f=1; char c=getchar(); while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();} while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } const int N=500005; int n,m; vector<int> A[N],B[N]; struct QUERY{ int opt,x,y; }Q[N]; struct Tree{ int dfn[N],dfn_clock=0,vis[N],out[N],fa[N]; vector<int> v[N]; void dfs(int u){ dfn[u]=++dfn_clock; vis[u]=1; out[u]=dfn[u]; for(auto &to : v[u]) dfs(to); } }t1,t2; struct OIerwanhongAKIOI{//A vector<int> tim[N<<2]; vector<ll> val[N<<2]; void update(int x,int l,int r,int L,int R,int AD,int ti){ if(L<=l&&r<=R){ tim[x].push_back(ti); val[x].push_back((val[x].empty() ? 0 : val[x].back())+AD); return; } int mid=(l+r)>>1; if(mid>=L) update(x<<1,l,mid,L,R,AD,ti); if(mid<R) update(x<<1|1,mid+1,r,L,R,AD,ti); } ll query(int x,int l,int r,int pos,int ti){ int tmp=lower_bound(tim[x].begin(),tim[x].end(),ti)-tim[x].begin()-1; ll tt=(tmp==-1||tim[x].empty() ? 0 : val[x][tmp]); ll ttt=(tim[x].empty() ? 0 : val[x].back()); if(l==r){return ttt-tt;} int mid=(l+r)>>1; if(mid>=pos) return ttt-tt+query(x<<1,l,mid,pos,ti); else return ttt-tt+query(x<<1|1,mid+1,r,pos,ti); } }tree1; struct SevenDawnsAKIOI{//B int tim[N<<2],val[N<<2]; pii merge(pii x,pii y){//time val return x.first<y.first ? y : x; } void update(int x,int l,int r,int L,int R,int ti,int Val){ if(L<=l&&r<=R){ tim[x]=ti; val[x]=Val; return; } int mid=(l+r)>>1; if(mid>=L) update(x<<1,l,mid,L,R,ti,Val); if(mid<R) update(x<<1|1,mid+1,r,L,R,ti,Val); } pii query(int x,int l,int r,int pos){ if(l==r) return mk(tim[x],val[x]); int mid=(l+r)>>1; if(mid>=pos) return merge(mk(tim[x],val[x]),query(x<<1,l,mid,pos)); else return merge(mk(tim[x],val[x]),query(x<<1|1,mid+1,r,pos)); } }tree2; void solve(){ for(int i=1;i<=m;i++){ if(Q[i].opt==1) checkmax(t1.out[Q[i].x],t1.out[Q[i].y]); else if(Q[i].opt==2) checkmax(t2.out[Q[i].x],t2.out[Q[i].y]); else if(Q[i].opt==3) tree1.update(1,1,n,t1.dfn[Q[i].x],t1.out[Q[i].x],Q[i].y,i); else if(Q[i].opt==4) tree2.update(1,1,n,t2.dfn[Q[i].x],t2.out[Q[i].x],i,Q[i].y); else{ pii tmp=tree2.query(1,1,n,t2.dfn[Q[i].x]); ll ret=tree1.query(1,1,n,t1.dfn[Q[i].x],tmp.first); printf("%lld\n",ret+tmp.second); } } } int main() { n=read(); m=read(); for(int i=1;i<=m;i++){ Q[i].opt=read(); if(Q[i].opt!=5) Q[i].x=read(),Q[i].y=read(); else Q[i].x=read(); } for(int i=1;i<=m;i++){ if(Q[i].opt==1) t1.v[Q[i].x].push_back(Q[i].y),t1.fa[Q[i].y]=Q[i].x; else if(Q[i].opt==2) t2.v[Q[i].x].push_back(Q[i].y),t2.fa[Q[i].y]=Q[i].x; } for(int i=1;i<=n;i++){ if(t1.fa[i]==0) t1.dfs(i); if(t2.fa[i]==0) t2.dfs(i); } solve(); return 0; }
30.857143
98
0.504873
jinzhengyu1212
fc21af3d3b8dc236074202a09ad8ffa9c9e2ae37
5,506
cpp
C++
test/ara/com/someip/pubsub/someip_pubsub_test.cpp
bigdark1024/Adaptive-AUTOSAR
b7ebbbd123761bf3f73b1ef425c14c7705c967f8
[ "MIT" ]
49
2021-07-26T14:28:55.000Z
2022-03-29T03:33:32.000Z
test/ara/com/someip/pubsub/someip_pubsub_test.cpp
bigdark1024/Adaptive-AUTOSAR
b7ebbbd123761bf3f73b1ef425c14c7705c967f8
[ "MIT" ]
9
2021-07-26T14:35:20.000Z
2022-02-05T15:49:43.000Z
test/ara/com/someip/pubsub/someip_pubsub_test.cpp
bigdark1024/Adaptive-AUTOSAR
b7ebbbd123761bf3f73b1ef425c14c7705c967f8
[ "MIT" ]
17
2021-09-03T15:38:27.000Z
2022-03-27T15:48:01.000Z
#include <gtest/gtest.h> #include "../../../../../src/ara/com/someip/pubsub/someip_pubsub_server.h" #include "../../../../../src/ara/com/someip/pubsub/someip_pubsub_client.h" #include "../../helper/mockup_network_layer.h" namespace ara { namespace com { namespace someip { namespace pubsub { class SomeIpPubSubTest : public testing::Test { private: static const uint16_t cCounter = 0; static const uint16_t cPort = 9090; helper::MockupNetworkLayer<sd::SomeIpSdMessage> mNetworkLayer; helper::Ipv4Address mIpAddress; protected: static const uint16_t cServiceId = 1; static const uint16_t cInstanceId = 1; static const uint8_t cMajorVersion = 1; static const uint16_t cEventgroupId = 0; static const int cWaitingDuration = 100; SomeIpPubSubServer Server; SomeIpPubSubClient Client; SomeIpPubSubTest() : mIpAddress(224, 0, 0, 0), Server(&mNetworkLayer, cServiceId, cInstanceId, cMajorVersion, cEventgroupId, mIpAddress, cPort), Client( &mNetworkLayer, cCounter) { } }; TEST_F(SomeIpPubSubTest, ServerInitialState) { const helper::PubSubState cExpectedState = helper::PubSubState::ServiceDown; helper::PubSubState _actualState = Server.GetState(); EXPECT_EQ(cExpectedState, _actualState); } TEST_F(SomeIpPubSubTest, NoServerRunning) { const int cMinimalDuration = 1; sd::SomeIpSdMessage _message; EXPECT_FALSE( Client.TryGetProcessedSubscription( cMinimalDuration, _message)); } TEST_F(SomeIpPubSubTest, ServerStart) { const helper::PubSubState cExpectedState = helper::PubSubState::NotSubscribed; Server.Start(); helper::PubSubState _actualState = Server.GetState(); EXPECT_EQ(cExpectedState, _actualState); } TEST_F(SomeIpPubSubTest, AcknowlegeScenario) { const helper::PubSubState cExpectedState = helper::PubSubState::Subscribed; sd::SomeIpSdMessage _message; Server.Start(); Client.Subscribe( cServiceId, cInstanceId, cMajorVersion, cEventgroupId); bool _succeed = Client.TryGetProcessedSubscription(cWaitingDuration, _message); EXPECT_TRUE(_succeed); auto _eventgroupEntry = std::dynamic_pointer_cast<entry::EventgroupEntry>( _message.Entries().at(0)); EXPECT_GT(_eventgroupEntry->TTL(), 0); EXPECT_EQ(cExpectedState, Server.GetState()); } TEST_F(SomeIpPubSubTest, NegativeAcknowlegeScenario) { const helper::PubSubState cExpectedState = helper::PubSubState::ServiceDown; sd::SomeIpSdMessage _message; Client.Subscribe( cServiceId, cInstanceId, cMajorVersion, cEventgroupId); bool _succeed = Client.TryGetProcessedSubscription(cWaitingDuration, _message); EXPECT_TRUE(_succeed); auto _eventgroupEntry = std::dynamic_pointer_cast<entry::EventgroupEntry>( _message.Entries().at(0)); EXPECT_EQ(_eventgroupEntry->TTL(), 0); EXPECT_EQ(cExpectedState, Server.GetState()); } TEST_F(SomeIpPubSubTest, UnsubscriptionScenario) { const helper::PubSubState cExpectedState = helper::PubSubState::NotSubscribed; sd::SomeIpSdMessage _message; Server.Start(); Client.Subscribe( cServiceId, cInstanceId, cMajorVersion, cEventgroupId); bool _succeed = Client.TryGetProcessedSubscription(cWaitingDuration, _message); EXPECT_TRUE(_succeed); Client.Unsubscribe( cServiceId, cInstanceId, cMajorVersion, cEventgroupId); EXPECT_EQ(cExpectedState, Server.GetState()); } } } } }
38.236111
87
0.460407
bigdark1024
fc235de156e8661ed509ddf134cd4c96efda6600
6,373
cpp
C++
source/core/util/h5json.cpp
jwuttke/daquiri-qpx
6606f4efca9bbe460e25e511fd94a8277c7e1fe6
[ "BSD-2-Clause" ]
2
2018-03-25T05:31:44.000Z
2019-07-25T05:17:51.000Z
source/core/util/h5json.cpp
jwuttke/daquiri-qpx
6606f4efca9bbe460e25e511fd94a8277c7e1fe6
[ "BSD-2-Clause" ]
158
2017-11-16T09:20:24.000Z
2022-03-28T11:39:43.000Z
source/core/util/h5json.cpp
martukas/daquiri-qpx
6606f4efca9bbe460e25e511fd94a8277c7e1fe6
[ "BSD-2-Clause" ]
2
2018-09-20T08:29:21.000Z
2020-08-04T18:34:50.000Z
#include <core/util/h5json.h> std::string vector_idx_minlen(size_t idx, size_t max) { size_t minlen = std::to_string(max).size(); std::string name = std::to_string(idx); if (name.size() < minlen) name = std::string(minlen - name.size(), '0').append(name); return name; } namespace hdf5 { node::Group require_group(node::Group& g, std::string name) { if (g.exists(name)) node::remove(g[name]); return g.create_group(name); } //void to_json(json& j, const Enum<int16_t>& e) //{ // j["___choice"] = e.val(); // std::multimap<std::string, int16_t> map; // for (auto a : e.options()) // map.insert({a.second, a.first}); // j["___options"] = json(map); //} // //void from_json(const json& j, Enum<int16_t>& e) //{ // auto o = j["___options"]; // for (json::iterator it = o.begin(); it != o.end(); ++it) // e.set_option(it.value(), it.key()); // e.set(j["___choice"]); //} void to_json(json &j, const node::Group &g) { for (auto n : g.nodes) { if (n.type() == node::Type::DATASET) { auto d = node::Dataset(n); json jj; to_json(jj, d); j[n.link().path().name()] = jj; } else if (n.type() == node::Type::GROUP) { auto gg = node::Group(n); json jj; to_json(jj, gg); j[n.link().path().name()] = jj; } } for (auto a : g.attributes) attr_to_json(j, a); // for (auto gg : g.groups()) // to_json(j[gg], g.open_group(gg)); // for (auto aa : g.attributes()) // j[aa] = attribute_to_json(g, aa); // for (auto dd : g.datasets()) // j[dd] = g.open_dataset(dd); } void attr_to_json(json &j, const attribute::Attribute &a) { if (a.datatype() == datatype::create<float>()) { float val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<double>()) { double val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<long double>()) { long double val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<int8_t>()) { int8_t val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<int16_t>()) { int16_t val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<int32_t>()) { int32_t val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<int64_t>()) { int64_t val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<uint8_t>()) { uint8_t val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<uint16_t>()) { uint16_t val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<uint32_t>()) { uint32_t val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<uint64_t>()) { uint64_t val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<std::string>()) { std::string val; a.read(val); j[a.name()] = val; } else if (a.datatype() == datatype::create<bool>()) { bool val; a.read(val); j[a.name()] = val; } // else if (g.template attr_is_enum<int16_t>()) // return json(g.template read_enum<int16_t>()); // else // return "ERROR: to_json unimplemented attribute type"; } void attribute_from_json(const json &j, const std::string &name, node::Group &g) { // if (j.count("___options") && j.count("___choice")) // { // Enum<int16_t> e = j; // g.write_enum(name, e); // } // else if (j.is_number_float()) { attribute::Attribute a = g.attributes.create<double>(name); a.write(j.get<double>()); } else if (j.is_number_unsigned()) { attribute::Attribute a = g.attributes.create<uint32_t>(name); a.write(j.get<uint32_t>()); } else if (j.is_number_integer()) { attribute::Attribute a = g.attributes.create<int64_t>(name); a.write(j.get<int64_t>()); } else if (j.is_boolean()) { attribute::Attribute a = g.attributes.create<bool>(name); a.write(j.get<bool>()); } else if (j.is_string()) { attribute::Attribute a = g.attributes.create<std::string>(name); a.write(j.get<std::string>()); } } void from_json(const json &j, node::Group &g) { bool is_array = j.is_array(); uint32_t i = 0; size_t len = 0; if (is_array && j.size()) len = std::to_string(j.size() - 1).size(); for (json::const_iterator it = j.begin(); it != j.end(); ++it) { std::string name; if (is_array) { name = std::to_string(i++); if (name.size() < len) name = std::string(len - name.size(), '0').append(name); } else name = it.key(); if (it.value().count("___shape") && it.value()["___shape"].is_array()) { dataset_from_json(it.value(), name, g); } else if (!it.value().is_array() && (it.value().is_number() || it.value().is_boolean() || it.value().is_string() || it.value().count("___options") || it.value().count("___choice"))) { attribute_from_json(it.value(), name, g); } else { auto gg = g.create_group(name); from_json(it.value(), gg); } } } void to_json(json &j, const node::Dataset &d) { auto dsp = dataspace::Simple(d.dataspace()); auto dims = dsp.current_dimensions(); auto maxdims = dsp.maximum_dimensions(); j["___shape"] = dims; if (dims != maxdims) j["___extends"] = maxdims; auto cl = d.creation_list(); if (cl.layout() == property::DatasetLayout::CHUNKED) j["___chunk"] = cl.chunk(); for (auto a : d.attributes) attr_to_json(j, a); } void dataset_from_json(const json &j, __attribute__((unused)) const std::string &name, __attribute__((unused)) node::Group &g) { std::vector<hsize_t> shape = j["___shape"]; std::vector<hsize_t> extends; if (j.count("___extends") && j["___extends"].is_array()) extends = j["___extends"].get<std::vector<hsize_t>>(); std::vector<hsize_t> chunk; if (j.count("___chunk") && j["___chunk"].is_array()) chunk = j["___chunk"].get<std::vector<hsize_t>>(); // auto dset = g.create_dataset<int>(name, shape, chunk); // for (json::const_iterator it = j.begin(); it != j.end(); ++it) // { // attribute_from_json(json(it.value()), std::string(it.key()), dset); // } } }
28.07489
76
0.571473
jwuttke
fc23ec946dd1aae6ca6656c444d1030e2a5eb347
13,013
hpp
C++
lockfree/AsyncObject.hpp
unevens/lockfree-async
57009fc5270d3b42b8ff8c57c6c2961cdcf299b1
[ "MIT" ]
2
2020-04-06T01:50:26.000Z
2021-03-18T17:19:36.000Z
lockfree/AsyncObject.hpp
unevens/lockfree-async
57009fc5270d3b42b8ff8c57c6c2961cdcf299b1
[ "MIT" ]
null
null
null
lockfree/AsyncObject.hpp
unevens/lockfree-async
57009fc5270d3b42b8ff8c57c6c2961cdcf299b1
[ "MIT" ]
null
null
null
/* Copyright 2021 Dario Mambro 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 #include "Messenger.hpp" #include "inplace_function.h" #include <chrono> #include <mutex> #include <thread> #include <unordered_set> #include <utility> #include <vector> namespace lockfree { class AsyncThread; namespace detail { /** * An interface abstracting over the different template specialization of Async objects. */ class AsyncObjectInterface : public std::enable_shared_from_this<AsyncObjectInterface> { friend class ::lockfree::AsyncThread; public: virtual ~AsyncObjectInterface() = default; AsyncThread* getAsyncThread() const { return asyncThread; } protected: virtual void timerCallback() = 0; void setAsyncThread(AsyncThread* asyncThread_) { asyncThread = asyncThread_; } class AsyncThread* asyncThread{ nullptr }; }; } // namespace detail /** * The AsyncThread class manages a thread that will perform asynchronously any change submitted to an Async object * attached to it. An Async object needs to be attached to an AsyncThread for it to receive any submitted change. */ class AsyncThread final { using AsyncInterface = detail::AsyncObjectInterface; friend AsyncInterface; public: /** * Constructor * @period the period in milliseconds with which the thread that receives and handles any change submitted to the * objects attached to it. */ explicit AsyncThread(int timerPeriod = 250) : timerPeriod{ timerPeriod } {} /** * Attaches an Async object from the thread * @asyncObject the object to attach to the thread */ void attachObject(AsyncInterface& asyncObject) { auto prevAsyncThread = asyncObject.getAsyncThread(); if (prevAsyncThread) { if (prevAsyncThread == this) { return; } prevAsyncThread->detachObject(asyncObject); } auto const lock = std::lock_guard<std::mutex>(mutex); asyncObjects.insert(asyncObject.shared_from_this()); asyncObject.setAsyncThread(this); } /** * Detaches an Async object from the thread * @asyncObject the object to detach to the thread */ void detachObject(AsyncInterface& asyncObject) { auto const lock = std::lock_guard<std::mutex>(mutex); auto const it = std::find_if(asyncObjects.begin(), asyncObjects.end(), [&](std::shared_ptr<AsyncInterface> const& element) { return element.get() == &asyncObject; }); if (it != asyncObjects.end()) { asyncObjects.erase(it); asyncObject.setAsyncThread(nullptr); } } /** * Starts the thread. */ void start() { if (isRunningFlag.load(std::memory_order_acquire)) { return; } stopTimerFlag.store(false, std::memory_order_release); isRunningFlag.store(true, std::memory_order_release); timer = std::thread([this]() { while (true) { auto const lock = std::lock_guard<std::mutex>(mutex); for (auto& asyncObject : asyncObjects) asyncObject->timerCallback(); if (stopTimerFlag.load(std::memory_order_acquire)) { return; } std::this_thread::sleep_for(std::chrono::milliseconds(timerPeriod)); if (stopTimerFlag.load(std::memory_order_acquire)) { return; } } }); } /** * Stops the thread. */ void stop() { stopTimerFlag.store(true, std::memory_order_release); if (timer.joinable()) { timer.join(); } isRunningFlag.store(false, std::memory_order_release); } /** * Sets the period in milliseconds with which the thread that receives and handles any change submitted to the objects * attached to it. * @period the period to set */ void setUpdatePeriod(int period) { timerPeriod.store(period, std::memory_order_release); } /** * @return the period in milliseconds with which the thread that receives and handles any change submitted to the * objects attached to it. */ int getUpdatePeriod() const { return timerPeriod.load(std::memory_order_acquire); } /** * @return true if the thread is running, false otherwise. */ bool isRunning() const { return isRunningFlag.load(std::memory_order_acquire); } /** * Destructor. It stops the thread if it is active and detach any Async object that was using it */ ~AsyncThread() { stop(); for (auto& asyncObject : asyncObjects) asyncObject->setAsyncThread(nullptr); } private: std::unordered_set<std::shared_ptr<AsyncInterface>> asyncObjects; std::thread timer; std::atomic<bool> stopTimerFlag{ false }; std::atomic<int> timerPeriod; std::atomic<bool> isRunningFlag{ false }; std::mutex mutex; }; /** * Let's say you have some realtime threads, an each of them wants an instance of an object; and sometimes you need to * perform some changes to that object that needs to be done asynchronously and propagated to all the instances. The * Async class handles this scenario. The key idea is that the Object is constructable from some ObjectSettings, and you * can submit a change to those object settings from any thread using a stdext::inplace_function<void(ObjectSettings&)> * through an Async::Producer. Any thread that wants an instance of the object can request an Async::Instance which will * hold a copy of the Object constructed from the ObjectSettings, and can receive the result of any changes submitted. * The changes and the construction of the objects happen in an AsyncThread. */ template<class TObject, class TObjectSettings, size_t ChangeFunctorClosureCapacity = 32> class AsyncObject final : public detail::AsyncObjectInterface { public: using ObjectSettings = TObjectSettings; using Object = TObject; using ChangeSettings = stdext::inplace_function<void(ObjectSettings&), ChangeFunctorClosureCapacity>; public: /** * A class that gives access to an instance of the async object. */ class Instance final { template<class TObject_, class TObjectSettings_, size_t ChangeFunctorClosureCapacity_> friend class AsyncObject; public: /** * Updates the instance to the last change submitted to the Async object. Lockfree. * @return true if any change has been received and the instance has been updated, otherwise false */ bool update() { using std::swap; auto messageNode = toInstance.receiveLastNode(); if (messageNode) { auto& newObject = messageNode->get(); swap(object, newObject); fromInstance.send(messageNode); return true; } return false; } /** * @return a reference to the actual object instance */ Object& get() { return *object; } /** * @return a const reference to the actual object instance */ Object const& get() const { return *object; } ~Instance() { async->removeInstance(this); } private: explicit Instance(ObjectSettings& objectSettings, std::shared_ptr<AsyncObject> async) : object{ std::make_unique<Object>(objectSettings) } , async{ std::move(async) } {} std::unique_ptr<Object> object; Messenger<std::unique_ptr<Object>> toInstance; Messenger<std::unique_ptr<Object>> fromInstance; std::shared_ptr<AsyncObject> async; }; friend Instance; class Producer final { template<class TObject_, class TObjectSettings_, size_t ChangeFunctorClosureCapacity_> friend class AsyncObject; public: /** * Submit a change to Async object, which will be handled asynchronously by the AsyncThread and received by the * instances through the Instance::update method. * It is not lock-free, as it may allocate an internal node of the lifo stack if there is no one available. * @return true if the node was available a no allocation has been made, false otherwise */ bool submitChange(ChangeSettings change) { return messenger.send(std::move(change)); } /** * Submit a change to Async object, which will be handled asynchronously by the AsyncThread and received by the * instances through the Instance::update method. * It does not submit the change if the lifo stack is empty. It is lock-free. * @return true if the change was submitted, false if the lifo stack is empty. */ bool submitChangeIfNodeAvailable(ChangeSettings change) { return messenger.sendIfNodeAvailable(std::move(change)); } /** * Allocates nodes for the lifo stack used to send changes. * @numNodesToAllocate the number of nodes to allocate */ void allocateNodes(int numNodesToAllocate) { messenger.allocateNodes(numNodesToAllocate); } ~Producer() { async->removeProducer(this); } private: bool handleChanges(ObjectSettings& objectSettings) { int numChanges = receiveAndHandleMessageStack(messenger, [&](ChangeSettings& change) { change(objectSettings); }); return numChanges > 0; } explicit Producer(std::shared_ptr<AsyncObject> async) : async{ std::move(async) } {} Messenger<ChangeSettings> messenger; std::shared_ptr<AsyncObject> async; }; friend Producer; /** * Creates a new Instance of the object * @return the Instance */ std::unique_ptr<Instance> createInstance() { auto const lock = std::lock_guard<std::mutex>(mutex); auto instance = std::unique_ptr<Instance>( new Instance(objectSettings, std::static_pointer_cast<AsyncObject>(this->shared_from_this()))); instances.push_back(instance.get()); return instance; } /** * Creates a new producer of object changes * @return the producer */ std::unique_ptr<Producer> createProducer() { auto const lock = std::lock_guard<std::mutex>(mutex); auto producer = std::unique_ptr<Producer>(new Producer(std::static_pointer_cast<AsyncObject>(this->shared_from_this()))); producers.push_back(producer.get()); return producer; } /** * Destructor. If the object was attached to an AsyncThread, it detached it */ ~AsyncObject() override { assert(instances.empty() && producers.empty()); if (asyncThread) { asyncThread->detachObject(*this); } } /** * Creates an Async object. * @objectSettings the initial settings to build the Async object */ static std::shared_ptr<AsyncObject> create(ObjectSettings objectSettings) { return std::shared_ptr<AsyncObject>(new AsyncObject(std::move(objectSettings))); } private: explicit AsyncObject(ObjectSettings objectSettings) : objectSettings{ std::move(objectSettings) } {} template<class T> void removeAddressFromStorage(T* address, std::vector<T*>& storage) { auto it = std::find(storage.begin(), storage.end(), address); assert(it != storage.end()); if (it == storage.end()) return; storage.erase(it); } void removeInstance(Instance* instance) { auto const lock = std::lock_guard<std::mutex>(mutex); removeAddressFromStorage(instance, instances); } void removeProducer(Producer* producer) { auto const lock = std::lock_guard<std::mutex>(mutex); removeAddressFromStorage(producer, producers); } void timerCallback() override { auto const lock = std::lock_guard<std::mutex>(mutex); for (auto& instance : instances) { instance->fromInstance.discardAndFreeAllMessages(); } bool anyChange = false; for (auto& producer : producers) { bool const anyChangeFromProducer = producer->handleChanges(objectSettings); if (anyChangeFromProducer) { anyChange = true; } } if (anyChange) { for (auto& instance : instances) { instance->toInstance.discardAndFreeAllMessages(); instance->toInstance.send(std::make_unique<Object>(objectSettings)); } } } std::vector<Producer*> producers; std::vector<Instance*> instances; ObjectSettings objectSettings; std::mutex mutex; }; } // namespace lockfree
29.308559
120
0.694229
unevens
fc253b679201b7f90ebcf825bc71e1a5df0c375d
1,688
cpp
C++
jni/chipmunk/binding/com_wiyun_engine_chipmunk_Circle.cpp
zchajax/WiEngine
ea2fa297f00aa5367bb5b819d6714ac84a8a8e25
[ "MIT" ]
39
2015-01-23T10:01:31.000Z
2021-06-10T03:01:18.000Z
jni/chipmunk/binding/com_wiyun_engine_chipmunk_Circle.cpp
luckypen/WiEngine
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
[ "MIT" ]
1
2015-04-15T08:07:47.000Z
2015-04-15T08:07:47.000Z
jni/chipmunk/binding/com_wiyun_engine_chipmunk_Circle.cpp
luckypen/WiEngine
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
[ "MIT" ]
20
2015-01-20T07:36:10.000Z
2019-09-15T01:02:19.000Z
#include <jni.h> #include "com_wiyun_engine_chipmunk_Circle.h" #include "chipmunk.h" extern jfieldID g_fid_Body_mPointer; extern jfieldID g_fid_Shape_mPointer; JNIEXPORT void JNICALL Java_com_wiyun_engine_chipmunk_Circle_init(JNIEnv * env, jobject thiz, jobject body, jfloat radius, jfloat centerX, jfloat centerY) { cpBody* bodyStruct = (cpBody*)env->GetIntField(body, g_fid_Body_mPointer); cpShape* shape = cpCircleShapeNew(bodyStruct, radius, cpv(centerX, centerY)); env->SetIntField(thiz, g_fid_Shape_mPointer, (int)shape); } JNIEXPORT void JNICALL Java_com_wiyun_engine_chipmunk_Circle_setRadius (JNIEnv * env, jobject thiz, jfloat r) { cpCircleShape* circle = (cpCircleShape*)env->GetIntField(thiz, g_fid_Shape_mPointer); circle->r = r; } JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_chipmunk_Circle_getRadius (JNIEnv * env, jobject thiz) { cpCircleShape* circle = (cpCircleShape*)env->GetIntField(thiz, g_fid_Shape_mPointer); return circle->r; } JNIEXPORT void JNICALL Java_com_wiyun_engine_chipmunk_Circle_setOffset (JNIEnv * env, jobject thiz, jfloat x, jfloat y) { cpCircleShape* circle = (cpCircleShape*)env->GetIntField(thiz, g_fid_Shape_mPointer); circle->c = cpv(x, y); } JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_chipmunk_Circle_getOffsetX (JNIEnv * env, jobject thiz) { cpCircleShape* circle = (cpCircleShape*)env->GetIntField(thiz, g_fid_Shape_mPointer); return circle->c.x; } JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_chipmunk_Circle_getOffsetY (JNIEnv * env, jobject thiz) { cpCircleShape* circle = (cpCircleShape*)env->GetIntField(thiz, g_fid_Shape_mPointer); return circle->c.y; }
38.363636
157
0.773697
zchajax
fc25be88f5d97fcf8a952c365d18d58944675ed7
3,891
cc
C++
chrome/browser/interstitials/security_interstitial_page.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
chrome/browser/interstitials/security_interstitial_page.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/interstitials/security_interstitial_page.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2014 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 "chrome/browser/interstitials/security_interstitial_page.h" #include <utility> #include "base/i18n/rtl.h" #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/interstitials/chrome_controller_client.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "components/grit/components_resources.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing_db/safe_browsing_prefs.h" #include "components/security_interstitials/core/common_string_util.h" #include "components/security_interstitials/core/metrics_helper.h" #include "content/public/browser/interstitial_page.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/web_contents.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/webui/jstemplate_builder.h" #include "ui/base/webui/web_ui_util.h" SecurityInterstitialPage::SecurityInterstitialPage( content::WebContents* web_contents, const GURL& request_url, std::unique_ptr<security_interstitials::MetricsHelper> metrics_helper) : web_contents_(web_contents), request_url_(request_url), interstitial_page_(NULL), create_view_(true), controller_( new ChromeControllerClient(web_contents, std::move(metrics_helper))) { // Creating interstitial_page_ without showing it leaks memory, so don't // create it here. } SecurityInterstitialPage::~SecurityInterstitialPage() { } content::InterstitialPage* SecurityInterstitialPage::interstitial_page() const { return interstitial_page_; } content::WebContents* SecurityInterstitialPage::web_contents() const { return web_contents_; } GURL SecurityInterstitialPage::request_url() const { return request_url_; } void SecurityInterstitialPage::DontCreateViewForTesting() { create_view_ = false; } void SecurityInterstitialPage::Show() { DCHECK(!interstitial_page_); interstitial_page_ = content::InterstitialPage::Create( web_contents_, ShouldCreateNewNavigation(), request_url_, this); if (!create_view_) interstitial_page_->DontCreateViewForTesting(); // Determine if any prefs need to be updated prior to showing the security // interstitial. safe_browsing::UpdatePrefsBeforeSecurityInterstitial(profile()->GetPrefs()); interstitial_page_->Show(); controller_->set_interstitial_page(interstitial_page_); AfterShow(); } Profile* SecurityInterstitialPage::profile() { return Profile::FromBrowserContext(web_contents()->GetBrowserContext()); } bool SecurityInterstitialPage::IsPrefEnabled(const char* pref) { return profile()->GetPrefs()->GetBoolean(pref); } ChromeControllerClient* SecurityInterstitialPage::controller() { return controller_.get(); } security_interstitials::MetricsHelper* SecurityInterstitialPage::metrics_helper() { return controller_->metrics_helper(); } base::string16 SecurityInterstitialPage::GetFormattedHostName() const { return security_interstitials::common_string_util::GetFormattedHostName( request_url_); } std::string SecurityInterstitialPage::GetHTMLContents() { base::DictionaryValue load_time_data; PopulateInterstitialStrings(&load_time_data); const std::string& app_locale = g_browser_process->GetApplicationLocale(); webui::SetLoadTimeDataDefaults(app_locale, &load_time_data); std::string html = ResourceBundle::GetSharedInstance() .GetRawDataResource(IDR_SECURITY_INTERSTITIAL_HTML) .as_string(); webui::AppendWebUiCssTextDefaults(&html); return webui::GetI18nTemplateHtml(html, &load_time_data); }
35.054054
80
0.782575
xzhan96
fc28a8069f03f3aa0f570a80beb5d220ed4611ae
4,055
cc
C++
third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2019 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 "third_party/blink/renderer/core/page/scrolling/fragment_anchor.h" #include "base/metrics/histogram_macros.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/renderer/core/display_lock/display_lock_utilities.h" #include "third_party/blink/renderer/core/fragment_directive/css_selector_fragment_anchor.h" #include "third_party/blink/renderer/core/fragment_directive/text_fragment_anchor.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/web_feature.h" #include "third_party/blink/renderer/core/html/html_details_element.h" #include "third_party/blink/renderer/core/html/html_document.h" #include "third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" namespace blink { FragmentAnchor* FragmentAnchor::TryCreate(const KURL& url, LocalFrame& frame, bool should_scroll) { DCHECK(frame.GetDocument()); FragmentAnchor* anchor = nullptr; const bool text_fragment_identifiers_enabled = RuntimeEnabledFeatures::TextFragmentIdentifiersEnabled(frame.DomWindow()); // The text fragment anchor will be created if we successfully parsed the // text directive but we only do the text matching later on. bool selector_fragment_anchor_created = false; if (text_fragment_identifiers_enabled) { anchor = TextFragmentAnchor::TryCreate(url, frame, should_scroll); selector_fragment_anchor_created = anchor; } // TODO(crbug.com/1265726): Do highlighting related to all fragment // directives and scroll the first one into view if (!anchor && RuntimeEnabledFeatures::CSSSelectorFragmentAnchorEnabled()) { anchor = CssSelectorFragmentAnchor::TryCreate(url, frame, should_scroll); selector_fragment_anchor_created = anchor; } bool element_id_anchor_found = false; if (!anchor) { anchor = ElementFragmentAnchor::TryCreate(url, frame, should_scroll); element_id_anchor_found = anchor; } // Track how often we have an element fragment that we can't find. Only track // if we didn't match a selector fragment since we expect those would inflate // the "failed" case. if (IsA<HTMLDocument>(frame.GetDocument()) && url.HasFragmentIdentifier() && !selector_fragment_anchor_created) { UMA_HISTOGRAM_BOOLEAN("TextFragmentAnchor.ElementIdFragmentFound", element_id_anchor_found); } return anchor; } void FragmentAnchor::ScrollElementIntoViewWithOptions( Element* element_to_scroll, ScrollIntoViewOptions* options) { // Expand <details> elements so we can make |element_to_scroll| visible. bool needs_style_and_layout = RuntimeEnabledFeatures::AutoExpandDetailsElementEnabled() && HTMLDetailsElement::ExpandDetailsAncestors(*element_to_scroll); // Reveal hidden=until-found ancestors so we can make |element_to_scroll| // visible. needs_style_and_layout |= RuntimeEnabledFeatures::BeforeMatchEventEnabled( element_to_scroll->GetExecutionContext()) && DisplayLockUtilities::RevealHiddenUntilFoundAncestors(*element_to_scroll); if (needs_style_and_layout) { // If we opened any details elements, we need to update style and layout // to account for the new content to render inside the now-expanded // details element before we scroll to it. The added open attribute may // also affect style. frame_->GetDocument()->UpdateStyleAndLayoutForNode( element_to_scroll, DocumentUpdateReason::kFindInPage); } element_to_scroll->ScrollIntoViewNoVisualUpdate(options); } void FragmentAnchor::Trace(Visitor* visitor) const { visitor->Trace(frame_); } } // namespace blink
42.239583
92
0.759063
chromium
fc2a0f3392b9794e99344c8fc4ef7941b7e46778
678
cc
C++
net/socket/ssl_error_params.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
net/socket/ssl_error_params.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
net/socket/ssl_error_params.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// 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 "net/socket/ssl_error_params.h" #include "base/values.h" namespace net { SSLErrorParams::SSLErrorParams(int net_error, int ssl_lib_error) : net_error_(net_error), ssl_lib_error_(ssl_lib_error) { } Value* SSLErrorParams::ToValue() const { DictionaryValue* dict = new DictionaryValue(); dict->SetInteger("net_error", net_error_); if (ssl_lib_error_) dict->SetInteger("ssl_lib_error", ssl_lib_error_); return dict; } SSLErrorParams::~SSLErrorParams() {} } // namespace net
25.111111
73
0.735988
Scopetta197
fc2f6c79898723b87a65d4377f6d2e7edc089055
1,141
cpp
C++
src/_leetcode/leet_m03.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
src/_leetcode/leet_m03.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
src/_leetcode/leet_m03.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
/* * ====================== leet_m03.cpp ========================== * -- tpr -- * CREATE -- 2020.05.18 * MODIFY -- * ---------------------------------------------------------- * 面试题03. 数组中重复的数字 */ #include "innLeet.h" namespace leet_m03 {//~ // 暴力法 // uset 快于 set int findRepeatNumber_1( std::vector<int>& nums ){ std::unordered_set<int> sett {}; for( int i : nums ){ if( sett.erase(i)!=0 ){ return i; } sett.insert( i ); } return 0; // never reach } // 暴力法 // 用 vector 存储元素,牺牲内存缩短访问时间 61.66%, 100% int findRepeatNumber_2( std::vector<int>& nums ){ std::vector<uint8_t> v ( nums.size(), 0 ); for( int i : nums ){ if( v.at(i)>0 ){ return i; } v.at(i)++; } return 0; // never reach } //=========================================================// void main_(){ std::vector<int> v { 2,3,1,0,2,5,3 }; auto ret = findRepeatNumber_2( v ); cout << "ret = " << ret << endl; debug::log( "\n~~~~ leet: m03 :end ~~~~\n" ); } }//~
18.403226
65
0.38475
turesnake
fc3014e5dde343a76927afbb470a15dbf80d8994
3,476
cpp
C++
src/client/RigidBodySys.cpp
Naftoreiclag/VS8C
9dc68c88c0ad02408609b3cfa834a48ad5c256a8
[ "Apache-2.0" ]
null
null
null
src/client/RigidBodySys.cpp
Naftoreiclag/VS8C
9dc68c88c0ad02408609b3cfa834a48ad5c256a8
[ "Apache-2.0" ]
null
null
null
src/client/RigidBodySys.cpp
Naftoreiclag/VS8C
9dc68c88c0ad02408609b3cfa834a48ad5c256a8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2015 James Fong 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 "RigidBodySys.hpp" #include <algorithm> #include <stdint.h> #include "Overworld.hpp" #include "RigidBodyComp.hpp" #include "Vec3f.hpp" #include "Quate.hpp" #include "WalkSignal.hpp" #include "LocationSignal.hpp" #include "OrientationSignal.hpp" namespace vse { RigidBodySys::RigidBodyMotionListener::RigidBodyMotionListener(const btTransform& initialLoc, RigidBodyComp* const sendTo) : sendTo(sendTo), initialLoc(initialLoc) { } void RigidBodySys::RigidBodyMotionListener::getWorldTransform(btTransform& worldTransform) const { worldTransform = initialLoc; } void RigidBodySys::RigidBodyMotionListener::setWorldTransform(const btTransform& worldTransform) { sendTo->mRotation = worldTransform.getRotation(); sendTo->mLocation = worldTransform.getOrigin() - sendTo->mOffset; sendTo->mVelocityLinear = sendTo->mRigidBody->getLinearVelocity(); sendTo->mOnPhysUpdate = true; } RigidBodySys::RigidBodySys(btDynamicsWorld* dynamicsWorld) : mDynamicsWorld(dynamicsWorld) { mRequiredComponents.push_back(RigidBodyComp::componentID); } RigidBodySys::~RigidBodySys() { } void RigidBodySys::onEntityExists(nres::Entity* entity) { RigidBodyComp* comp = (RigidBodyComp*) entity->getComponent(RigidBodyComp::componentID); btTransform trans; trans.setIdentity(); trans.setOrigin(comp->mInitialLoc); comp->mMotionState = new RigidBodyMotionListener(trans, comp); btVector3 inertia(0, 0, 0); comp->mCollisionShape->calculateLocalInertia(comp->mMass, inertia); comp->mRigidBody = new btRigidBody(comp->mMass, comp->mMotionState, comp->mCollisionShape, inertia); comp->mRigidBody->setUserPointer(entity); mDynamicsWorld->addRigidBody(comp->mRigidBody); mTrackedEntities.push_back(entity); } void RigidBodySys::onEntityDestroyed(nres::Entity* entity) { RigidBodyComp* comp = (RigidBodyComp*) entity->getComponent(RigidBodyComp::componentID); mDynamicsWorld->removeRigidBody(comp->mRigidBody); mTrackedEntities.erase(std::remove(mTrackedEntities.begin(), mTrackedEntities.end(), entity), mTrackedEntities.end()); } void RigidBodySys::onEntityBroadcast(nres::Entity* entity, const EntSignal* data) { } const std::vector<nres::ComponentID>& RigidBodySys::getRequiredComponents() { return mRequiredComponents; } void RigidBodySys::onTick() { for(std::vector<nres::Entity*>::iterator it = mTrackedEntities.begin(); it != mTrackedEntities.end(); ++ it) { nres::Entity* entity = *it; RigidBodyComp* rigidBody = (RigidBodyComp*) entity->getComponent(RigidBodyComp::componentID); if(rigidBody->mOnPhysUpdate) { entity->broadcast(new LocationSignal(Vec3f(rigidBody->mLocation))); entity->broadcast(new OrientationSignal(Quate(rigidBody->mRotation))); rigidBody->mOnPhysUpdate = false; } } } }
34.078431
122
0.737342
Naftoreiclag
fc310e984915f553272a2c1f598190737294767f
885
hpp
C++
src/TextWidget.hpp
marcogillies/GUIWidgetsInheritanceExample
de41415d1b923c10931e87be5859c4936e207bd7
[ "MIT" ]
null
null
null
src/TextWidget.hpp
marcogillies/GUIWidgetsInheritanceExample
de41415d1b923c10931e87be5859c4936e207bd7
[ "MIT" ]
null
null
null
src/TextWidget.hpp
marcogillies/GUIWidgetsInheritanceExample
de41415d1b923c10931e87be5859c4936e207bd7
[ "MIT" ]
null
null
null
// // TextWidget.hpp // GUIWidgets // // Created by Marco Gillies on 13/03/2017. // // #ifndef TextWidget_hpp #define TextWidget_hpp #include <string> #include "Widget.hpp" class ofTrueTypeFont; /* * This is a base class for Widgets that * contain text. * It stores a string and a font to draw * the text with. * The class is abstract because it does * not implement subClassDraw, which is a * pure virtual function of Widget. */ class TextWidget : public Widget{ protected: std::string text; /* * I have used a shared_ptr for font because * a single font is shared between many widgets */ std::shared_ptr<ofTrueTypeFont> font; public: TextWidget(std::string _text, std::shared_ptr<ofTrueTypeFont> _font); TextWidget(std::string _text, std::shared_ptr<ofTrueTypeFont> _font, int x, int y); }; #endif /* TextWidget_hpp */
22.125
87
0.688136
marcogillies
fc35608b9c7898fcf51a44b33fbcd7c9b5e9be78
4,718
hpp
C++
crogine/include/crogine/core/State.hpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
41
2017-08-29T12:14:36.000Z
2022-02-04T23:49:48.000Z
crogine/include/crogine/core/State.hpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
11
2017-09-02T15:32:45.000Z
2021-12-27T13:34:56.000Z
crogine/include/crogine/core/State.hpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
5
2020-01-25T17:51:45.000Z
2022-03-01T05:20:30.000Z
/*----------------------------------------------------------------------- Matt Marchant 2017 - 2020 http://trederia.blogspot.com crogine - Zlib license. This software is provided 'as-is', without any express or implied warranty.In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions : 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. -----------------------------------------------------------------------*/ #pragma once #include <crogine/Config.hpp> #include <crogine/detail/Types.hpp> #include <crogine/core/Message.hpp> #include <cstdlib> #include <memory> namespace cro { class Window; class App; class StateStack; class Time; using StateID = std::int32_t; /*! \brief Abstract base class for states. States, when used in conjustion with the state stack, are used to encapsulate game states, such as menus or pausing mode. Concrete states should provide a unique ID using the StateID type. */ class CRO_EXPORT_API State { public: using Ptr = std::unique_ptr<State>; /*! \brief Context containing information about the current application instance. */ struct CRO_EXPORT_API Context { App& appInstance; Window& mainWindow; //TODO handle the default view of the window Context(App& a, Window& w) : appInstance(a), mainWindow(w) {} }; /*! \brief Constructor \param StateStack Instance of th state state to which this state will belong \param Context Copy of the current application's Context */ State(StateStack&, Context); virtual ~State() = default; State(const State&) = delete; State(const State&&) = delete; State& operator = (const State&) = delete; State& operator = (const State&&) = delete; /*! \brief Receives window events as handed down from the StateStack. \returns true if the event should be passed on through the stack, else false. For example; when displaying a pause menu this function should return false in order to consume events and prevent them from being passed on to the game state residing underneath. */ virtual bool handleEvent(const cro::Event&) = 0; /*! \brief Receives system messages handed down from the StateStack. All states receive all messages regardlessly. */ virtual void handleMessage(const cro::Message&) = 0; /*! \brief Executes one step of the game's simulation. All game logic should be performed under this function. \param dt The amount of time passed since this function was last called. \returns true if remaining states in the state should be simulated else returns false. \see handleEvent() */ virtual bool simulate(float dt) = 0; /*! \brief Calls to rendering systems should be performed here. */ virtual void render() = 0; /*! \brief Returns the unique ID of concrete states. */ virtual StateID getStateID() const = 0; protected: /*! \brief Request a state with the given ID is pushed on to the StateStack to which this state belongs. */ void requestStackPush(StateID); /*! \brief Requests that the state currently on the top of the stack to which this state belongs is popped and destroyed. */ void requestStackPop(); /*! \brief Requests that all states in the StateStack to which this state belongs are removed. */ void requestStackClear(); /*! \brief Returns a copy of this state's current Context */ Context getContext() const; /*! \brief Returns the number of active states on this state's StateStack */ std::size_t getStateCount() const; private: StateStack& m_stack; Context m_context; }; }
30.43871
85
0.625265
fallahn
fc3846c1ee06b5620458de9307ce7a316136d6b6
4,105
cpp
C++
qubus/src/performance_models/unified_performance_model.cpp
qubusproject/Qubus
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
[ "BSL-1.0" ]
null
null
null
qubus/src/performance_models/unified_performance_model.cpp
qubusproject/Qubus
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
[ "BSL-1.0" ]
null
null
null
qubus/src/performance_models/unified_performance_model.cpp
qubusproject/Qubus
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
[ "BSL-1.0" ]
null
null
null
#include <hpx/config.hpp> #include <qubus/performance_models/unified_performance_model.hpp> #include <qubus/performance_models/regression_performance_model.hpp> #include <qubus/performance_models/simple_statistical_performance_model.hpp> #include <hpx/include/local_lcos.hpp> #include <qubus/util/assert.hpp> #include <algorithm> #include <mutex> #include <unordered_map> #include <utility> namespace qubus { namespace { std::unique_ptr<performance_model> create_performance_model(const symbol_id& func, const module_library& mod_library, address_space& host_addr_space) { auto mod = mod_library.lookup(func.get_prefix()).get(); const function& func_def = mod->lookup_function(func.suffix()); const auto& params = func_def.params(); auto has_scalar_params = std::any_of(params.begin(), params.end(), [](const auto& param) { const auto& datatype = param.var_type(); return datatype == types::integer{} || datatype == types::float_{} || datatype == types::double_{}; }); if (has_scalar_params) { return std::make_unique<regression_performance_model>(host_addr_space); } else { return std::make_unique<simple_statistical_performance_model>(); } } } // namespace class unified_performance_model_impl { public: explicit unified_performance_model_impl(module_library mod_library_, address_space& host_addr_space_) : mod_library_(std::move(mod_library_)), host_addr_space_(&host_addr_space_) { } void sample_execution_time(const symbol_id& func, const execution_context& ctx, std::chrono::microseconds execution_time) { std::lock_guard<hpx::lcos::local::mutex> guard(models_mutex_); auto search_result = kernel_models_.find(func); if (search_result == kernel_models_.end()) { search_result = kernel_models_ .emplace(func, create_performance_model(func, mod_library_, *host_addr_space_)) .first; } search_result->second->sample_execution_time(func, ctx, std::move(execution_time)); } boost::optional<performance_estimate> try_estimate_execution_time(const symbol_id& func, const execution_context& ctx) const { std::lock_guard<hpx::lcos::local::mutex> guard(models_mutex_); auto search_result = kernel_models_.find(func); if (search_result != kernel_models_.end()) { return search_result->second->try_estimate_execution_time(func, ctx); } else { return boost::none; } } private: mutable hpx::lcos::local::mutex models_mutex_; std::unordered_map<symbol_id, std::unique_ptr<performance_model>> kernel_models_; module_library mod_library_; address_space* host_addr_space_; }; unified_performance_model::unified_performance_model(module_library mod_library_, address_space& host_addr_space_) : impl_(std::make_unique<unified_performance_model_impl>(std::move(mod_library_), host_addr_space_)) { } unified_performance_model::~unified_performance_model() = default; void unified_performance_model::sample_execution_time(const symbol_id& func, const execution_context& ctx, std::chrono::microseconds execution_time) { QUBUS_ASSERT(impl_, "Uninitialized object."); impl_->sample_execution_time(func, ctx, std::move(execution_time)); } boost::optional<performance_estimate> unified_performance_model::try_estimate_execution_time(const symbol_id& func, const execution_context& ctx) const { QUBUS_ASSERT(impl_, "Uninitialized object."); return impl_->try_estimate_execution_time(func, ctx); } } // namespace qubus
32.322835
100
0.647259
qubusproject
fc38c32ad236fe64f0c1747f769a287e4139fe0c
1,611
cpp
C++
cmdstan/stan/lib/stan_math/test/unit/math/prim/arr/err/check_finite_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/prim/arr/err/check_finite_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/prim/arr/err/check_finite_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/prim/arr.hpp> #include <gtest/gtest.h> using stan::math::check_finite; // ---------- check_finite: vector tests ---------- TEST(ErrorHandlingScalar,CheckFinite_Vector) { const char* function = "check_finite"; std::vector<double> x; x.clear(); x.push_back (-1); x.push_back (0); x.push_back (1); ASSERT_NO_THROW(check_finite(function, "x", x)) << "check_finite should be true with finite x"; x.clear(); x.push_back(-1); x.push_back(0); x.push_back(std::numeric_limits<double>::infinity()); EXPECT_THROW(check_finite(function, "x", x), std::domain_error) << "check_finite should throw exception on Inf"; x.clear(); x.push_back(-1); x.push_back(0); x.push_back(-std::numeric_limits<double>::infinity()); EXPECT_THROW(check_finite(function, "x", x), std::domain_error) << "check_finite should throw exception on -Inf"; x.clear(); x.push_back(-1); x.push_back(0); x.push_back(std::numeric_limits<double>::quiet_NaN()); EXPECT_THROW(check_finite(function, "x", x), std::domain_error) << "check_finite should throw exception on NaN"; } TEST(ErrorHandlingScalar,CheckFinite_nan) { const char* function = "check_finite"; double nan = std::numeric_limits<double>::quiet_NaN(); std::vector<double> x; x.push_back (nan); x.push_back (0); x.push_back (1); EXPECT_THROW(check_finite(function, "x", x), std::domain_error); x[0] = 1.0; x[1] = nan; EXPECT_THROW(check_finite(function, "x", x), std::domain_error); x[1] = 0.0; x[2] = nan; EXPECT_THROW(check_finite(function, "x", x), std::domain_error); }
27.305085
66
0.66915
yizhang-cae
fc39f8dfa8e2c14eb979d3dcc2e98825f4f00f24
3,084
cpp
C++
source/tracker/tracker.cpp
ponpiste/BitTorrent
cad7ac1af64ac3075ee1c7b0516458612b1f9a4c
[ "MIT" ]
1
2022-01-19T15:25:31.000Z
2022-01-19T15:25:31.000Z
source/tracker/tracker.cpp
ponpiste/BitTorrent
cad7ac1af64ac3075ee1c7b0516458612b1f9a4c
[ "MIT" ]
null
null
null
source/tracker/tracker.cpp
ponpiste/BitTorrent
cad7ac1af64ac3075ee1c7b0516458612b1f9a4c
[ "MIT" ]
1
2020-10-12T01:50:20.000Z
2020-10-12T01:50:20.000Z
#include "tracker/tracker.h" #include <stdlib.h> #include <time.h> #include <vector> #include "tracker/udp.h" #include "tracker/url.h" #include <algorithm> #include <stdexcept> #include "download/peer_id.h" #include "parsing/bencode.h" using namespace std; buffer tracker::build_conn_req_udp() { const int SIZE_CONN = 16; const int RANDOM_SIZE = 4; unsigned char msg[SIZE_CONN] = {0x00, 0x00, 0x04, 0x17, 0x27, 0x10, 0x19, 0x80, 0x00, 0x00, 0x00, 0x00}; for(int i=0;i<RANDOM_SIZE;i++){ msg[SIZE_CONN-RANDOM_SIZE+i]=rand() % 256; } return buffer(msg,msg+SIZE_CONN); } void tracker::build_ann_req_http(http& request, const torrent& t) { // info_hash request.add_argument("info_hash", t.info_hash); //peer_id request.add_argument("peer_id", peer_id::get()); // port request.add_argument("port", "6881"); // uploaded request.add_argument("uploaded", "0"); // downloaded request.add_argument("downloaded", "0"); // compact request.add_argument("compact", "1"); // left request.add_argument("left", to_string(t.length)); } buffer tracker::build_ann_req_udp(const buffer& b, const torrent& t) { const int SIZE_ANN = 98; buffer buff(SIZE_ANN, 0x00); // connection id copy(b.begin()+8, b.begin()+16, buff.begin()); // action buff[11]=1; // transaction id copy(b.begin()+4,b.begin()+8, buff.begin()+12); // info hash copy(t.info_hash.begin(), t.info_hash.end(), buff.begin()+16); // peer id buffer id = peer_id::get(); copy(id.begin(), id.end(), buff.begin()+36); // left long long x = t.length; for(int i=0;i<4;i++){ buff[64+8-i-1] = x % 256; x/=256; } // key for(int i=0;i<4;i++){ buff[88+i] = rand() % 256; } // num_want for(int i=0;i<4;i++){ buff[92+i] = 0xff; } // port // Todo: allow port between 6881 and 6889 int port = 6881; buff[97] = port % 256; buff[96] = (port / 256) % 256; return buff; } vector<peer> tracker::get_peers(const torrent& t) { if (t.url.protocol == url_t::UDP) { udp client(t.url.host, t.url.port); client.send(build_conn_req_udp()); buffer b = client.receive(); client.send(build_ann_req_udp(b, t)); buffer c = client.receive(); const int PEER_OFFSET = 20; c.erase(c.begin(), c.begin() + PEER_OFFSET); return get_peers(c); } else if (t.url.protocol == url_t::HTTP) { buffer encoded; while(encoded.size() == 0) { http request(t.url); build_ann_req_http(request, t); encoded = request.get(); } bencode::item item = bencode::parse(encoded); buffer peer_bytes = item.get_buffer("peers"); return get_peers(peer_bytes); } throw runtime_error("protocol not recognized"); } vector<peer> tracker::get_peers(const buffer& b) { const int PEER_BYTE_SIZE = 6; buffer::size_type n = b.size(); if(n % PEER_BYTE_SIZE != 0) throw runtime_error("peer list not a multiple of 6"); vector<peer> peers; for(auto i = 0; i < n; i+=6) { string host = to_string(b[i]); for(int j=1;j<4;j++){ host += "." + to_string(b[i+j]); } int port = getBE16(b,i+4); peers.push_back(peer(host, port)); } return peers; }
19.396226
82
0.645266
ponpiste
fc3a4806e7045c1da477929085774722c2fe0e4b
583
cpp
C++
geometria/orden.radial.cpp
AlgorithmCR/eldiego
f1c01061467ce8a50a5e6134ab6ea09c9bcd7e0f
[ "MIT" ]
31
2015-11-15T19:24:17.000Z
2018-09-27T01:45:24.000Z
geometria/orden.radial.cpp
AlgorithmCR/eldiego
f1c01061467ce8a50a5e6134ab6ea09c9bcd7e0f
[ "MIT" ]
23
2015-09-23T15:56:32.000Z
2016-05-04T02:48:16.000Z
geometria/orden.radial.cpp
AlgorithmCR/eldiego
f1c01061467ce8a50a5e6134ab6ea09c9bcd7e0f
[ "MIT" ]
7
2016-08-25T21:29:56.000Z
2018-07-22T03:39:51.000Z
struct Cmp{//orden total de puntos alrededor de un punto r pto r; Cmp(pto r):r(r) {} int cuad(const pto &a) const{ if(a.x > 0 && a.y >= 0)return 0; if(a.x <= 0 && a.y > 0)return 1; if(a.x < 0 && a.y <= 0)return 2; if(a.x >= 0 && a.y < 0)return 3; assert(a.x ==0 && a.y==0); return -1; } bool cmp(const pto&p1, const pto&p2)const{ int c1 = cuad(p1), c2 = cuad(p2); if(c1==c2) return p1.y*p2.x<p1.x*p2.y; else return c1 < c2; } bool operator()(const pto&p1, const pto&p2) const{ return cmp(pto(p1.x-r.x,p1.y-r.y),pto(p2.x-r.x,p2.y-r.y)); } };
27.761905
62
0.548885
AlgorithmCR
fc3b5850c60e31b70d44ef4db6d74beb15bdeb0a
6,732
cc
C++
E/src/texgen/noise.cc
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
114
2015-04-14T10:30:05.000Z
2021-06-11T02:57:59.000Z
E/src/texgen/noise.cc
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
null
null
null
E/src/texgen/noise.cc
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
11
2015-07-26T02:11:32.000Z
2020-04-02T21:06:15.000Z
//============================================================================= // // Perlin Noise // //============================================================================= // Improved Perlin noise. // Original Perlin noise implementation can be found at : // http://mrl.nyu.edu/~perlin/doc/oscar.html#noise #include "../sys/msys.h" #include "../interpolation.hh" #define MOD 0xff static bool noise_ready = false; static int permut[256]; static const char gradient[32][4] = { { 1, 1, 1, 0}, { 1, 1, 0, 1}, { 1, 0, 1, 1}, { 0, 1, 1, 1}, { 1, 1, -1, 0}, { 1, 1, 0, -1}, { 1, 0, 1, -1}, { 0, 1, 1, -1}, { 1, -1, 1, 0}, { 1, -1, 0, 1}, { 1, 0, -1, 1}, { 0, 1, -1, 1}, { 1, -1, -1, 0}, { 1, -1, 0, -1}, { 1, 0, -1, -1}, { 0, 1, -1, -1}, {-1, 1, 1, 0}, {-1, 1, 0, 1}, {-1, 0, 1, 1}, { 0, -1, 1, 1}, {-1, 1, -1, 0}, {-1, 1, 0, -1}, {-1, 0, 1, -1}, { 0, -1, 1, -1}, {-1, -1, 1, 0}, {-1, -1, 0, 1}, {-1, 0, -1, 1}, { 0, -1, -1, 1}, {-1, -1, -1, 0}, {-1, -1, 0, -1}, {-1, 0, -1, -1}, { 0, -1, -1, -1}, }; static void InitNoise() { noise_ready = true; for (unsigned int i = 0; i < 256; i++) permut[i] = msys_rand() & MOD; } // // Function finding out the gradient corresponding to the coordinates // static int Indice(int i, int j, int k, int l) { return permut[(l + permut[(k + permut[(j + permut[i & MOD]) & MOD]) & MOD]) & MOD] & 0x1f; } // // Functions computing the dot product of the vector and the gradient // static float Prod(float a, char b) { // // FIXME : rewrite branchless // // const unsigned int zero = !(!b); // const unsigned int casted_a = *(unsigned int *)&a; // const unsigned int sign_mask = ((casted_a >> 31 - 1)) | ((*(unsigned int *)&b) << 24); // const unsigned int casted_result = casted_a ^ sign_mask; // return (*(float *)&casted_result); if (b > 0) return a; if (b < 0) return -a; return 0; } static float Dot_prod(float x1, char x2, float y1, char y2, float z1, char z2, float t1, char t2) { return Prod(x1, x2) + Prod(y1, y2) + Prod(z1, z2) + Prod(t1, t2); } // // Noise function, returning the Perlin Noise at a given point // float Noise(float x, float y, float z, float t) { if (!noise_ready) InitNoise(); // The unit hypercube containing the point const int x1 = msys_ifloorf(x); const int y1 = msys_ifloorf(y); const int z1 = msys_ifloorf(z); const int t1 = msys_ifloorf(t); const int x2 = x1 + 1; const int y2 = y1 + 1; const int z2 = z1 + 1; const int t2 = t1 + 1; // The 16 corresponding gradients const char * g0000 = gradient[Indice(x1, y1, z1, t1)]; const char * g0001 = gradient[Indice(x1, y1, z1, t2)]; const char * g0010 = gradient[Indice(x1, y1, z2, t1)]; const char * g0011 = gradient[Indice(x1, y1, z2, t2)]; const char * g0100 = gradient[Indice(x1, y2, z1, t1)]; const char * g0101 = gradient[Indice(x1, y2, z1, t2)]; const char * g0110 = gradient[Indice(x1, y2, z2, t1)]; const char * g0111 = gradient[Indice(x1, y2, z2, t2)]; const char * g1000 = gradient[Indice(x2, y1, z1, t1)]; const char * g1001 = gradient[Indice(x2, y1, z1, t2)]; const char * g1010 = gradient[Indice(x2, y1, z2, t1)]; const char * g1011 = gradient[Indice(x2, y1, z2, t2)]; const char * g1100 = gradient[Indice(x2, y2, z1, t1)]; const char * g1101 = gradient[Indice(x2, y2, z1, t2)]; const char * g1110 = gradient[Indice(x2, y2, z2, t1)]; const char * g1111 = gradient[Indice(x2, y2, z2, t2)]; // The 16 vectors float dx1 = x - x1; float dx2 = x - x2; float dy1 = y - y1; float dy2 = y - y2; float dz1 = z - z1; float dz2 = z - z2; float dt1 = t - t1; float dt2 = t - t2; // The 16 dot products const float b0000 = Dot_prod(dx1, g0000[0], dy1, g0000[1], dz1, g0000[2], dt1, g0000[3]); const float b0001 = Dot_prod(dx1, g0001[0], dy1, g0001[1], dz1, g0001[2], dt2, g0001[3]); const float b0010 = Dot_prod(dx1, g0010[0], dy1, g0010[1], dz2, g0010[2], dt1, g0010[3]); const float b0011 = Dot_prod(dx1, g0011[0], dy1, g0011[1], dz2, g0011[2], dt2, g0011[3]); const float b0100 = Dot_prod(dx1, g0100[0], dy2, g0100[1], dz1, g0100[2], dt1, g0100[3]); const float b0101 = Dot_prod(dx1, g0101[0], dy2, g0101[1], dz1, g0101[2], dt2, g0101[3]); const float b0110 = Dot_prod(dx1, g0110[0], dy2, g0110[1], dz2, g0110[2], dt1, g0110[3]); const float b0111 = Dot_prod(dx1, g0111[0], dy2, g0111[1], dz2, g0111[2], dt2, g0111[3]); const float b1000 = Dot_prod(dx2, g1000[0], dy1, g1000[1], dz1, g1000[2], dt1, g1000[3]); const float b1001 = Dot_prod(dx2, g1001[0], dy1, g1001[1], dz1, g1001[2], dt2, g1001[3]); const float b1010 = Dot_prod(dx2, g1010[0], dy1, g1010[1], dz2, g1010[2], dt1, g1010[3]); const float b1011 = Dot_prod(dx2, g1011[0], dy1, g1011[1], dz2, g1011[2], dt2, g1011[3]); const float b1100 = Dot_prod(dx2, g1100[0], dy2, g1100[1], dz1, g1100[2], dt1, g1100[3]); const float b1101 = Dot_prod(dx2, g1101[0], dy2, g1101[1], dz1, g1101[2], dt2, g1101[3]); const float b1110 = Dot_prod(dx2, g1110[0], dy2, g1110[1], dz2, g1110[2], dt1, g1110[3]); const float b1111 = Dot_prod(dx2, g1111[0], dy2, g1111[1], dz2, g1111[2], dt2, g1111[3]); // Then the interpolations, down to the result dx1 = UnsecureSpline5_interpolation(dx1); dy1 = UnsecureSpline5_interpolation(dy1); dz1 = UnsecureSpline5_interpolation(dz1); dt1 = UnsecureSpline5_interpolation(dt1); const float b111 = UnsecureLinear_interpolation(b1110, b1111, dt1); const float b110 = UnsecureLinear_interpolation(b1100, b1101, dt1); const float b101 = UnsecureLinear_interpolation(b1010, b1011, dt1); const float b100 = UnsecureLinear_interpolation(b1000, b1001, dt1); const float b011 = UnsecureLinear_interpolation(b0110, b0111, dt1); const float b010 = UnsecureLinear_interpolation(b0100, b0101, dt1); const float b001 = UnsecureLinear_interpolation(b0010, b0011, dt1); const float b000 = UnsecureLinear_interpolation(b0000, b0001, dt1); const float b11 = UnsecureLinear_interpolation(b110, b111, dz1); const float b10 = UnsecureLinear_interpolation(b100, b101, dz1); const float b01 = UnsecureLinear_interpolation(b010, b011, dz1); const float b00 = UnsecureLinear_interpolation(b000, b001, dz1); const float b1 = UnsecureLinear_interpolation(b10, b11, dy1); const float b0 = UnsecureLinear_interpolation(b00, b01, dy1); return UnsecureLinear_interpolation(b0, b1, dx1); } // ============================================================================
36.389189
91
0.579323
vaginessa
fc3dc1daa50e1b7aff83bdc001d2deeded71d3a8
7,478
cpp
C++
base/string/format/scan_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
264
2015-01-03T11:50:17.000Z
2022-03-17T02:38:34.000Z
base/string/format/scan_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
12
2015-04-27T15:17:34.000Z
2021-05-01T04:31:18.000Z
base/string/format/scan_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
128
2015-02-07T18:13:10.000Z
2022-02-21T14:24:14.000Z
// Copyright (c) 2013, The TOFT Authors. // All rights reserved. // // Author: CHEN Feng <chen3feng@gmail.com> // Created: 2013-02-06 #include "toft/base/string/format/scan.h" #include <math.h> #include <stdint.h> #include "thirdparty/gtest/gtest.h" namespace toft { TEST(Scan, Escape) { int n = 0; ASSERT_EQ(1, StringScan("%1", "%%%d", &n)); EXPECT_EQ(1, n); } TEST(Scan, Bool) { bool b1, b2; ASSERT_EQ(2, StringScan("10", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); EXPECT_FALSE(b2); ASSERT_EQ(2, StringScan(" 1 0", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); EXPECT_FALSE(b2); ASSERT_EQ(1, StringScan("12", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); ASSERT_EQ(2, StringScan("truefalse", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); EXPECT_FALSE(b2); ASSERT_EQ(2, StringScan("true false", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); EXPECT_FALSE(b2); ASSERT_EQ(1, StringScan("true faster", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); ASSERT_EQ(2, StringScan("true0", "%v%v", &b1, &b2)); EXPECT_TRUE(b1); EXPECT_FALSE(b2); } TEST(Scan, Int) { int n = 0; unsigned int u = 0; ASSERT_EQ(1, StringScan("100", "%i", &n)); EXPECT_EQ(100, n); ASSERT_EQ(1, StringScan("200", "%d", &n)); EXPECT_EQ(200, n); ASSERT_EQ(1, StringScan("400", "%o", &n)); EXPECT_EQ(0400, n); ASSERT_EQ(1, StringScan("500", "%o", &u)); EXPECT_EQ(0500U, u); ASSERT_EQ(1, StringScan("600", "%x", &n)); EXPECT_EQ(0x600, n); ASSERT_EQ(1, StringScan("600", "%x", &u)); EXPECT_EQ(0x600U, u); } TEST(ScanDeathTest, IntInvalid) { int n = 0; ASSERT_DEBUG_DEATH(StringScan("300", "%u", &n), ""); } TEST(Scan, IntOverflow) { int8_t i8 = 1; ASSERT_EQ(0, StringScan("129", "%i", &i8)); EXPECT_EQ(0, StringScan("-129", "%i", &i8)); EXPECT_EQ(1, i8); uint8_t u8 = 1; ASSERT_EQ(0, StringScan("256", "%i", &u8)); EXPECT_EQ(0, StringScan("-1", "%i", &u8)); EXPECT_EQ(1, u8); int16_t i16 = 1; ASSERT_EQ(0, StringScan("32768", "%i", &i16)); EXPECT_EQ(0, StringScan("-32769", "%i", &i16)); EXPECT_EQ(1, i16); uint16_t u16 = 1; ASSERT_EQ(0, StringScan("65536", "%i", &u16)); EXPECT_EQ(0, StringScan("-1", "%i", &u16)); EXPECT_EQ(1, u16); int32_t i32 = 1; ASSERT_EQ(0, StringScan("0xFFFFFFFF1", "%i", &i32)); EXPECT_EQ(0, StringScan("-0xFFFFFFFF1", "%i", &i32)); EXPECT_EQ(1, i32); uint32_t u32 = 1; ASSERT_EQ(0, StringScan("0xFFFFFFFF1", "%i", &u32)); EXPECT_EQ(0, StringScan("-1", "%i", &u32)); EXPECT_EQ(1U, u32); int64_t i64 = 1; ASSERT_EQ(0, StringScan("0xFFFFFFFFFFFFFFFF1", "%i", &i64)); EXPECT_EQ(0, StringScan("-0xFFFFFFFFFFFFFFFF1", "%i", &i64)); EXPECT_EQ(1LL, i64); uint64_t u64 = 1; ASSERT_EQ(0, StringScan("0xFFFFFFFFFFFFFFFF1", "%i", &u64)); EXPECT_EQ(0, StringScan("-1", "%i", &u64)); EXPECT_EQ(1ULL, u64); } template <typename T> static void TestFloatCorrect(const char* format) { T v = 0.0; ASSERT_EQ(1, StringScan("3.14", format, &v)) << format; EXPECT_FLOAT_EQ(3.14, v); } TEST(Scan, Float) { TestFloatCorrect<float>("%f"); TestFloatCorrect<float>("%g"); TestFloatCorrect<float>("%e"); TestFloatCorrect<float>("%E"); TestFloatCorrect<float>("%a"); TestFloatCorrect<float>("%v"); TestFloatCorrect<double>("%f"); TestFloatCorrect<double>("%g"); TestFloatCorrect<double>("%e"); TestFloatCorrect<double>("%E"); TestFloatCorrect<double>("%a"); TestFloatCorrect<double>("%v"); TestFloatCorrect<double>("%lf"); TestFloatCorrect<double>("%lg"); TestFloatCorrect<double>("%le"); TestFloatCorrect<double>("%lE"); TestFloatCorrect<double>("%lv"); } template <typename T> static void TestFloatIncorrect(const char* format) { T v = 0.0; ASSERT_DEBUG_DEATH(StringScan("3.14", format, &v), ""); } TEST(ScanDeathTest, FloatInvalid) { TestFloatIncorrect<float>("%lf"); TestFloatIncorrect<float>("%lg"); TestFloatIncorrect<float>("%le"); TestFloatIncorrect<float>("%lE"); TestFloatIncorrect<float>("%lv"); } TEST(Scan, FloatOverflow) { float f; EXPECT_EQ(1, StringScan("1e50", "%f", &f)); EXPECT_EQ(1, isinf(f)); EXPECT_EQ(1, StringScan("-1e50", "%f", &f)); EXPECT_EQ(-1, isinf(f)); // Bypass bug of inff in glibc EXPECT_EQ(1, StringScan("1e-50", "%f", &f)); EXPECT_FLOAT_EQ(0.0f, f); double d; EXPECT_EQ(1, StringScan("1e500", "%f", &d)); EXPECT_EQ(1, isinf(d)); EXPECT_EQ(1, StringScan("-1e500", "%f", &d)); EXPECT_EQ(-1, isinf(d)); EXPECT_EQ(1, StringScan("1e-500", "%f", &d)); EXPECT_DOUBLE_EQ(0.0, d); long double ld; EXPECT_EQ(1, StringScan("1e5000", "%f", &ld)); EXPECT_EQ(1, isinf(ld)); EXPECT_EQ(1, StringScan("-1e5000", "%f", &ld)); EXPECT_EQ(-1, isinf(ld)); EXPECT_EQ(1, StringScan("1e-5000", "%f", &ld)); EXPECT_DOUBLE_EQ(0.0, ld); } TEST(Scan, String) { std::string s; ASSERT_EQ(1, StringScan("hello", "%s", &s)); EXPECT_EQ("hello", s); } TEST(Scan, StringLeadingSpace) { std::string s; ASSERT_EQ(1, StringScan(" hello", "%s", &s)); EXPECT_EQ("hello", s); } TEST(Scan, StringTailSpace) { std::string s; ASSERT_EQ(1, StringScan("hello ", "%s", &s)); EXPECT_EQ("hello", s); } TEST(Scan, StringAroundSpace) { std::string s; ASSERT_EQ(1, StringScan(" hello ", "%s", &s)); EXPECT_EQ("hello", s); } TEST(Scan, StringEmpty) { std::string s; ASSERT_EQ(0, StringScan(" ", "%s", &s)); std::string s1 = "s1"; ASSERT_EQ(1, StringScan("test ", "%s%s", &s, &s1)); EXPECT_EQ("test", s); EXPECT_EQ("s1", s1); } TEST(Scan, ScanSet) { std::string s; int i; ASSERT_EQ(1, StringScan("abcdef123", "%[a-z]", &s)); EXPECT_EQ("abcdef", s); ASSERT_EQ(1, StringScan("abcdef123", "%[a-z0-9]", &s)); EXPECT_EQ("abcdef123", s); ASSERT_EQ(1, StringScan(" abcdef123", "%[ \t]", &s)); EXPECT_EQ(" ", s); ASSERT_EQ(2, StringScan("abcdef123", "%[a-z]%d", &s, &i)); EXPECT_EQ("abcdef", s); EXPECT_EQ(123, i); ASSERT_EQ(2, StringScan("abcdef123", "%[^0-9]%d", &s, &i)); EXPECT_EQ("abcdef", s); EXPECT_EQ(123, i); } TEST(Scan, Mixed) { std::string s; unsigned int u; int i; ASSERT_EQ(3, StringScan("key=100hello 200", "key=%d%s%d", &u, &s, &i)); EXPECT_EQ("hello", s); EXPECT_EQ(100U, u); EXPECT_EQ(200, i); } TEST(Scan, Skip) { int i; ASSERT_EQ(1, StringScan("1,2,3", "%*d,%*d,%d", &i)); EXPECT_EQ(3, i); } TEST(Scan, Consumed) { int i; ASSERT_EQ(1, StringScan("hello", "%*s%n", &i)); EXPECT_EQ(5, i); } class PerformanceTest : public testing::Test {}; const int kLoopCount = 500000; const char kTestString[] = "1,2,4,8,16,32,64,128,256,512,1024,2048,4006,8192,16384,32768,65536"; #define TEST_FORMAT "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d" TEST_F(PerformanceTest, StringScan) { int n; for (int i = 0; i < kLoopCount; ++i) { StringScan(kTestString, TEST_FORMAT, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n); } } TEST_F(PerformanceTest, Sscanf) { int n; for (int i = 0; i < kLoopCount; ++i) { sscanf(kTestString, TEST_FORMAT, // NOLINT(runtime/printf) &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n); } } } // namespace toft
23.815287
75
0.572078
hjinlin
fc402bfffe5fe870621af77a6755ff10bb13fb5e
49
hpp
C++
src/boost_type_traits_remove_volatile.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_type_traits_remove_volatile.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_type_traits_remove_volatile.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/type_traits/remove_volatile.hpp>
24.5
48
0.836735
miathedev
fc42cc426a7d718a5871c0aecd63bdaea0358ab4
3,927
hpp
C++
3rdparty/GPSTk/ext/lib/Geomatics/SolarPosition.hpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/ext/lib/Geomatics/SolarPosition.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/ext/lib/Geomatics/SolarPosition.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /// @file SolarPosition.hpp Compute solar and lunar positions with a simple algorithm //------------------------------------------------------------------------------------ #ifndef SOLAR_POSITION_INCLUDE #define SOLAR_POSITION_INCLUDE //------------------------------------------------------------------------------------ // includes // system #include <iostream> #include <fstream> #include <string> #include <vector> // GPSTk #include "CommonTime.hpp" #include "Position.hpp" // geomatics namespace gpstk { /// Compute the Position of the Sun in WGS84 ECEF coordinates. /// Ref. Astronomical Almanac pg C24, as presented on USNO web site; claimed /// accuracy is about 1 arcminute, when t is within 2 centuries of 2000. /// @param CommonTime t Input epoch of interest /// @param double AR Output apparent angular radius of sun as seen at Earth (deg) /// @return Position Position (ECEF) of the Sun at t Position SolarPosition(CommonTime t, double& AR) throw(); /// Compute the latitude and longitude of the Sun using a very simple algorithm. /// Adapted from sunpos by D. Coco ARL:UT 12/15/94 /// @param CommonTime t Input epoch of interest /// @param double lat Output latitude of the Sun at t /// @param double lon Output longitude of the Sun at t void CrudeSolarPosition(CommonTime t, double& lat, double& lon) throw(); /// Compute the Position of the Moon in WGS84 ECEF coordinates. /// Ref. Astronomical Almanac 1990 D46 /// @param CommonTime t Input epoch of interest /// @param double AR Output apparent angular radius of moon as seen at Earth (deg) /// @return Position Position (ECEF) of the Moon at t Position LunarPosition(CommonTime t, double& AR) throw(); /// Compute the fraction of the area of the Sun covered by the Earth as seen from /// another body (e.g. satellite). /// @param double Rearth Apparent angular radius of Earth. /// @param double Rsun Apparent angular radius of Sun. /// @param double dES Angular separation of Sun and Earth. /// @return double factor Fraction (0 <= factor <= 1) of Sun area covered by Earth double shadowFactor(double Rearth, double Rsun, double dES) throw(); } // end namespace gpstk #endif // SOLAR_POSITION_INCLUDE // nothing below this
42.225806
86
0.627451
mfkiwl
fc430bc77094a8d881350a93ed4f6b6d5b3d676b
2,238
cpp
C++
source/parse_globule.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/parse_globule.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/parse_globule.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
/* This file is part of Cloudy and is copyright (C)1978-2019 by Gary J. Ferland and * others. For conditions of distribution and use see copyright notice in license.txt */ /*ParseGlobule parse parameters off the globule command */ #include "cddefines.h" #include "radius.h" #include "dense.h" #include "optimize.h" #include "input.h" #include "parser.h" void ParseGlobule(Parser &p) { DEBUG_ENTRY( "ParseGlobule()" ); if( dense.gas_phase[ipHYDROGEN] > 0. ) { fprintf( ioQQQ, " PROBLEM DISASTER More than one density command was entered.\n" ); cdEXIT(EXIT_FAILURE); } /* globule with density increasing inward * parameters are outer density, radius of globule, and density power */ radius.glbden = (realnum)p.FFmtRead(); radius.glbden = p.lgEOL() ? 1.f : exp10(radius.glbden); dense.SetGasPhaseDensity( ipHYDROGEN, radius.glbden ); if( dense.gas_phase[ipHYDROGEN] <= 0. ) { fprintf( ioQQQ, " PROBLEM DISASTER Hydrogen density must be > 0.\n" ); cdEXIT(EXIT_FAILURE); } radius.glbrad = (realnum)p.FFmtRead(); if( p.lgEOL() ) { radius.glbrad = 3.086e18f; } else { radius.glbrad = exp10(radius.glbrad); } /* this is largest zone thickness, used to set first zone thickness */ radius.sdrmax = radius.glbrad/25.; radius.lgSdrmaxRel = false; /* turn off min dr checking in NEXTDR */ radius.lgDrMnOn = false; radius.glbpow = (realnum)p.FFmtRead(); if( p.lgEOL() ) radius.glbpow = 1.; strcpy( dense.chDenseLaw, "GLOB" ); /* this is distance to globule */ radius.glbdst = radius.glbrad; /* vary option */ if( optimize.lgVarOn ) { /* pointer to where to write */ optimize.nvfpnt[optimize.nparm] = input.nRead; /* this is the number of parameters to feed onto the input line */ optimize.nvarxt[optimize.nparm] = 3; // the keyword LOG is not used above, but is checked elsewhere strcpy( optimize.chVarFmt[optimize.nparm], "GLOBULE %f LOG %f %f" ); /* param is log of abundance by number relative to hydrogen */ optimize.vparm[0][optimize.nparm] = (realnum)log10(radius.glbden); optimize.vparm[1][optimize.nparm] = (realnum)log10(radius.glbrad); optimize.vparm[2][optimize.nparm] = radius.glbpow; optimize.vincr[optimize.nparm] = 0.2f; ++optimize.nparm; } return; }
29.064935
89
0.699285
cloudy-astrophysics
fc43606c53cd95afd2b5f676978af82cbd02d44a
46,812
cpp
C++
tools/multiCamRemote/src/multicastReceive.cpp
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
2
2021-01-15T13:27:19.000Z
2021-08-04T08:40:52.000Z
tools/multiCamRemote/src/multicastReceive.cpp
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
null
null
null
tools/multiCamRemote/src/multicastReceive.cpp
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
5
2018-05-01T10:39:31.000Z
2022-03-25T03:02:35.000Z
// Copyright 2017-2019 Andre Pool // SPDX-License-Identifier: Apache-2.0 #include <arpa/inet.h> #include <errno.h> #include <netdb.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include "multicastReceive.hpp" // #define READFROMFILE using namespace std; multicastReceive::multicastReceive() { packetIndex = 0; packetIndexPrev = 1; // should be different from packetIndex to be able to use also the first packet packetIndexPause = false; struct timeval tv; time_t nowtime; struct tm *nowtm; gettimeofday(&tv, NULL); nowtime = tv.tv_sec; nowtm = localtime(&nowtime); // use current date and time as record file name char writeTxtName[64], writeBinName[64]; strftime(writeTxtName, sizeof writeTxtName, "%Y-%m-%d_%H-%M-%S.log", nowtm); strftime(writeBinName, sizeof writeBinName, "%Y-%m-%d_%H-%M-%S.bin", nowtm); printf("INFO : write received data to text file %s and binary file %s\n", writeTxtName, writeBinName); if ((writeTxt = fopen(writeTxtName, "wb")) == NULL) { // also use binary for ASCII perror("ERROR : cannot open record text file for writing, message"); exit(EXIT_FAILURE); } if ((writeBin = fopen(writeBinName, "wb")) == NULL) { perror("ERROR : cannot open record binary file for writing, message"); exit(EXIT_FAILURE); } #ifdef READFROMFILE string logFile; // logFile = "matches/torres_vedras_cambada_2018-04-25_21-01-50.bin"; // logFile = "matches/torres_vedras_cambada_2018-04-25_21-31-21.bin"; // logFile = "matches/2018-04-28_16-19-04_robot_6_test_cam_2_issue.bin"; // logFile = "matches/2018-04-28_19-16-48_robot_6_ghost_ball.bin"; // logFile = "matches/tech_united_2_2018-06-20_01-14-32.bin"; // logFile = "matches/water_1_2018-06-20_17-11-59.bin"; // logFile = "2019-01-13_11-28-35.bin"; // logFile = "matches/2019-04-26_14-35-48_techunited.bin"; // logFile = "matches/2019-04-28_11-46-15_techunited.bin"; // logFile = "matches/2019-07-04_03-31-42_nubot.bin"; // logFile = "matches/2019-07-06_00-52-51_nubot.bin"; // logFile = "matches/2019-07-06_05-48-32_iris.bin"; logFile = "matches/2019-07-06_09-26-44_hibikino.bin"; if ((readBin = fopen(logFile.c_str(), "r")) == NULL) { printf("ERROR : READ FROM FILE MODE, cannot open file file %s for reading, message, %s\n", logFile.c_str(), strerror(errno)); exit(EXIT_FAILURE); } size_t len = 0; char * line = NULL; ssize_t read = 0; while ((read = getline(&line, &len, readBin)) != -1) { packetSt packet; // WARNING: one value is 2 bytes for (int ii = 0; ii < (read - 1) / 2; ii++) { // TODO: double check range char substr[2]; // each hex value is 2 chars strncpy(substr, line + (ii * 2), 2); // copy 2 chars uint8_t value = (uint8_t) strtol(substr, NULL, 16); // convert 2 chars to long if (ii == 0) { packet.index = value; } else { packet.data.push_back(value); } } packets.push_back(packet); } free(line); fclose(readBin); printf("INFO : have read %zu packets from file\n", packets.size()); #ifdef NONO // check the stored packet size_t maxPackets = packets.size(); if( maxPackets > 5 ) {maxPackets = 5;} for( size_t ii = 0; ii < maxPackets; ii ++ ) { printf("%2zx ", packets[ii].index); for( size_t jj = 0; jj < packets[ii].data.size(); jj++ ) { printf("%02x", packets[ii].data[jj]); } printf("\n"); } #endif #endif struct passwd *pw = getpwuid(getuid()); string configFile(""); configFile.append(pw->pw_dir); configFile.append("/falcons/code/config/multiCam.yaml"); printf("INFO : multicastSend uses configuration file: %s\n", configFile.c_str()); cv::FileStorage fs(configFile, cv::FileStorage::READ); cv::FileNode possession = fs["possession"]; possessionThreshold = (int) (possession["threshold"]); #ifndef READFROMFILE // the multicast address and port number are in the global section of yaml file cv::FileNode global = fs["global"]; string multicastIp = (string) (global["multicastIp"]); int multicastPort = (int) (global["multicastPort"]); printf("INFO : multicastSend ip address %s port %d\n", multicastIp.c_str(), multicastPort); // create a normal UDP socket if ((fd = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { printf("ERROR : cannot create UDP socket %s\n", strerror(errno)); fflush(stdout); exit(EXIT_FAILURE); } // allow multiple sockets to use the same port int reuse = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &reuse, sizeof(reuse)) < 0) { printf("ERROR : cannot configure port for multiple UTP sockets, %s\n", strerror(errno)); fflush(stdout); exit(EXIT_FAILURE); } // fill in the local address struct struct sockaddr_in localAddr; memset((char *) &localAddr, 0, sizeof(localAddr)); localAddr.sin_family = AF_INET;// Internet localAddr.sin_addr.s_addr = htonl(INADDR_ANY); localAddr.sin_port = htons(multicastPort);// port // bind to the local address / port if (bind(fd, (struct sockaddr *) &localAddr, sizeof(localAddr)) < 0) { printf("ERROR : cannot bind to UDP socket, %s", strerror(errno)); fflush(stdout); exit(EXIT_FAILURE); } // join the multicast group struct ip_mreq mreq; memset(&mreq, 0, sizeof(mreq));// set all to zero mreq.imr_multiaddr.s_addr = inet_addr(multicastIp.c_str()); mreq.imr_interface.s_addr = htonl(INADDR_ANY); if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mreq, sizeof(mreq)) < 0) { printf("ERROR : cannot join the multicast group, %s\n", strerror(errno)); printf("INFO : goto Edit Connections\n"); printf("INFO : select Wi-Fi MSL_FIELD_A_a\n"); printf("INFO : select IPv4 Settings\n"); printf("INFO : verify address is 172.16.74.x\n"); printf("INFO : verify netmask 255.255.255.0 or 24\n"); printf("INFO : leave gateway open\n"); printf("INFO : select Routes\n"); printf("INFO : add\n"); printf("INFO : address 224.16.32.0\n"); printf("INFO : netmask 255.255.255.0\n"); printf("INFO : leave gateway open\n"); printf("INFO : metric 0\n"); printf("INFO : ok\n"); printf("INFO : save\n"); printf("INFO : reconnect to MSL_FIELD_A_a\n"); printf("INFO : verify with route -n if route to 224.26.32.0 exists\n"); fflush(stdout); exit(EXIT_FAILURE); } fromAddrLen = sizeof(fromAddr); printf("INFO : camera receive multicast group address %s port %u\n", inet_ntoa(mreq.imr_multiaddr), ntohs(localAddr.sin_port)); #endif // create the packetCnt for the 6 robots uint8_t tmpPacketCnt = 0; for (size_t ii = 0; ii < MAX_ROBOTS; ii++) { packetCnt.push_back(tmpPacketCnt); } // create the packet Error Count for the 6 robots size_t tmpPacketErrorCnt = 0; for (size_t ii = 0; ii < MAX_ROBOTS; ii++) { packetErrorCnt.push_back(tmpPacketErrorCnt); } // create the statistics for the 6 robots raspiStatsSt tmpRaspi = { 0, 60, 32, 0, 60, 0, 0, 0, 0, 10, 0 }; statsSt tmpStat = { 0, 0, 0, 0, 0, 0, 0, 0, 0.0, 0.0, 0.0, 0, 0, 0, 0, "", tmpRaspi, tmpRaspi, tmpRaspi, tmpRaspi }; for (size_t ii = 0; ii < MAX_ROBOTS; ii++) { tmpStat.robotIndex = ii; // starting at 0 instead of 1 stats.push_back(tmpStat); } // create the linePointList for the 6 robots ballObstListSt tmpLinePointList; tmpLinePointList.packetCnt = 0; tmpLinePointList.state = invalid; for (size_t ii = 0; ii < MAX_ROBOTS; ii++) { linePointList.push_back(tmpLinePointList); } // create the goodEnoughLoc for the 6 robots goodEnoughLocSt tmpGoodEnoughLoc; tmpGoodEnoughLoc.packetCnt = 0; tmpGoodEnoughLoc.state = invalid; tmpGoodEnoughLoc.goodEnough = false; // default not good enough for (size_t ii = 0; ii < MAX_ROBOTS; ii++) { goodEnoughLoc.push_back(tmpGoodEnoughLoc); } positionStDbl tmpPos; tmpPos.x = 0.0; tmpPos.y = 0.0; tmpPos.rz = 0.0; vector<positionStDbl> tmpPosList; // next line set's the amount of measurements used for the average for (size_t ii = 0; ii < 20; ii++) { tmpPosList.push_back(tmpPos); } for (size_t ii = 0; ii < MAX_ROBOTS; ii++) { posRosHistory.push_back(tmpPosList); posRosAverage.push_back(tmpPos); } // create the locList for the 6 robots locListSt tmpLocList; tmpLocList.packetCnt = 0; for (size_t ii = 0; ii < MAX_ROBOTS; ii++) { locList.push_back(tmpLocList); } // create the ballList and ballFarList for the 6 robots ballObstListSt tmpBallList; tmpBallList.packetCnt = 0; tmpBallList.state = invalid; for (size_t ii = 0; ii < MAX_ROBOTS; ii++) { ballList.push_back(tmpBallList); ballFarList.push_back(tmpBallList); } // create the cyanList for the 6 robots ballObstListSt tmpCyanList; tmpCyanList.packetCnt = 0; tmpCyanList.state = invalid; for (size_t ii = 0; ii < MAX_ROBOTS; ii++) { cyanList.push_back(tmpCyanList); } // create the magentaList for the 6 robots ballObstListSt tmpMagentaList; tmpMagentaList.packetCnt = 0; tmpMagentaList.state = invalid; for (size_t ii = 0; ii < MAX_ROBOTS; ii++) { magentaList.push_back(tmpMagentaList); } // create the obstacleList for the 6 robots ballObstListSt tmpObstacleList; tmpObstacleList.packetCnt = 0; tmpObstacleList.state = invalid; for (size_t ii = 0; ii < MAX_ROBOTS; ii++) { obstacleList.push_back(tmpObstacleList); } statsExportMutex.unlock(); linePointListExportMutex.unlock(); goodEnoughLocExportMutex.unlock(); locListExportMutex.unlock(); ballListExportMutex.unlock(); ballFarListExportMutex.unlock(); cyanListExportMutex.unlock(); magentaListExportMutex.unlock(); obstacleListExportMutex.unlock(); } multicastReceive::~multicastReceive() { fclose(writeTxt); fclose(writeBin); } void multicastReceive::decodeStats(size_t index) { struct timeval tv; gettimeofday(&tv, NULL); uint64_t localTime = tv.tv_sec * 1000000 + tv.tv_usec; uint8_t statsPacketSize = HEADER_SIZE + 32 + 4 * 20; if (recvBuf.size != statsPacketSize) { printf(" %10s : ERROR : stats packet should be %d bytes, but received %d bytes\n", ipAddress, statsPacketSize, recvBuf.size); } else { statsExportMutex.lock(); stats[index].packetCnt = recvBuf.cnt; stats[index].ballAmount = recvBuf.pl.u8[0 / 1]; stats[index].cyanAmount = recvBuf.pl.u8[1 / 1]; stats[index].magentaAmount = recvBuf.pl.u8[2 / 1]; stats[index].obstacleAmount = recvBuf.pl.u8[3 / 1]; stats[index].possessionPixels = recvBuf.pl.u16[4 / 2]; // amount of ball pixels seen just before the shooter stats[index].linePoints = recvBuf.pl.u16[6 / 2]; // total amount of line points found stats[index].uptime = recvBuf.pl.u16[8 / 2] / 10.0; // uptime since application startup stats[index].prepFps = recvBuf.pl.u16[10 / 2] / 100.0; // frames per second for balls and obstacles stats[index].locFps = recvBuf.pl.u16[12 / 2] / 100.0; // frames per second for localization stats[index].prepFrames = recvBuf.pl.u32[16 / 4]; // amount of frames since application start stats[index].locFrames = recvBuf.pl.u32[20 / 4]; // amount of localizations performed since application start stats[index].remoteTime = recvBuf.pl.u64[24 / 8]; // 64 bits time in micro seconds since 1 January 1970 stats[index].localTime = localTime; // used to calculate the transport latency (if remote has the same time) for (size_t camIndex = 0; camIndex < 4; camIndex++) { raspiStatsSt raspi; raspi.cmosTemp = recvBuf.pl.s8[(32 + camIndex * 16) / 1]; raspi.cpuLoad = recvBuf.pl.u8[(33 + camIndex * 16) / 1]; raspi.cpuTemp = recvBuf.pl.u8[(34 + camIndex * 16) / 1]; raspi.gpuTemp = recvBuf.pl.u8[(35 + camIndex * 16) / 1]; raspi.cpuStatus = recvBuf.pl.u8[(36 + camIndex * 16) / 1]; raspi.camValAverage = recvBuf.pl.u8[(37 + camIndex * 16) / 1]; raspi.rebootReceivedAge = recvBuf.pl.u8[(38 + camIndex * 16) / 1]; // free = recvBuf.pl.u8[(39 + camIndex * 16) / 1]; raspi.sysApplUptime = recvBuf.pl.u16[(40 + camIndex * 16) / 2]; raspi.cpuUptime = recvBuf.pl.u16[(42 + camIndex * 16) / 2]; raspi.anaApplUptime = recvBuf.pl.u16[(44 + camIndex * 16) / 2]; // free = recvBuf.pl.u32[(46 + camIndex * 16) / 4]; raspi.anaFrameCounter = recvBuf.pl.u32[(48 + camIndex * 16) / 4]; stats[index].raspi[camIndex] = raspi; } // convert the remote epoch microsecond time to a readable string time_t remoteEpochTimeSec = stats[index].remoteTime / 1000000; // extract the seconds and convert to time_t which is required for localtime() struct tm * remoteTimeSec; remoteTimeSec = localtime(&remoteEpochTimeSec); char remoteTimeString[10]; strftime(remoteTimeString, 10, "%H:%M:%S", remoteTimeSec); uint32_t remoteDotSeconds = (uint32_t) ((stats[index].remoteTime / 100000) % 10); // extract the 0.1 seconds sprintf(stats[index].remoteTimeString, "%s.%01u", remoteTimeString, remoteDotSeconds); statsExportMutex.unlock(); int64_t deltaTime = stats[index].localTime - stats[index].remoteTime; // printf("local time 0x%016zx remote time 0x%016zx, delta 0x%016zx %ld\n", localTime, stats[index].remoteTime, deltaTime, deltaTime ); #ifdef NONO printf(" %10s stat %3d %5d : %3d %3d %3d %3d %5d %4d : %6.1f %3.1f %3.1f : %6d %6d : %5.1f ms", ipAddress, stats[index].packetCnt, recvBuf.size, stats[index].ballAmount, stats[index].cyanAmount, stats[index].magentaAmount, stats[index].obstacleAmount, stats[index].possessionPixels, stats[index].linePoints, stats[index].uptime, stats[index].prepFps, stats[index].locFps, stats[index].prepFrames, stats[index].locFrames, deltaTime / 1000.0); for (size_t camIndex = 0; camIndex < 4; camIndex++) { raspiStatsSt raspi = stats[index].raspi[camIndex]; hhMmSsSt sysApplUp = secondsToHhMmSs(raspi.sysApplUptime); hhMmSsSt anaApplUp = secondsToHhMmSs(raspi.anaApplUptime); hhMmSsSt cpuUp = secondsToHhMmSs(raspi.cpuUptime); printf(" : %2u %2u %2u %3.2f 0x%02x %7u %2u %02u:%02u:%02u %02u:%02u:%02u %02u:%02u:%02u", raspi.cpuTemp, raspi.gpuTemp, raspi.cmosTemp, raspi.cpuLoad / 32.0, raspi.cpuStatus, raspi.anaFrameCounter, raspi.rebootReceivedAge, cpuUp.hours, cpuUp.minutes, cpuUp.seconds, sysApplUp.hours, sysApplUp.minutes, sysApplUp.seconds, anaApplUp.hours, anaApplUp.minutes, anaApplUp.seconds); } printf("\n"); #endif fprintf(writeTxt, "%zu %s %10s stat %3d %5d : %3d %3d %3d %3d %5d %4d : %6.1f %3.1f %3.1f : %6d %6d : %5.1f ms", stats[index].remoteTime, stats[index].remoteTimeString, ipAddress, stats[index].packetCnt, recvBuf.size, stats[index].ballAmount, stats[index].cyanAmount, stats[index].magentaAmount, stats[index].obstacleAmount, stats[index].possessionPixels, stats[index].linePoints, stats[index].uptime, stats[index].prepFps, stats[index].locFps, stats[index].prepFrames, stats[index].locFrames, deltaTime / 1000.0); for (size_t camIndex = 0; camIndex < 4; camIndex++) { raspiStatsSt raspi = stats[index].raspi[camIndex]; hhMmSsSt sysApplUp = secondsToHhMmSs(raspi.sysApplUptime); hhMmSsSt anaApplUp = secondsToHhMmSs(raspi.anaApplUptime); hhMmSsSt cpuUp = secondsToHhMmSs(raspi.cpuUptime); fprintf(writeTxt, " : %2u %2u %2u %3.2f 0x%02x %7u %2u %02u:%02u:%02u %02u:%02u:%02u %02u:%02u:%02u", raspi.cpuTemp, raspi.gpuTemp, raspi.cmosTemp, raspi.cpuLoad / 32.0, raspi.cpuStatus, raspi.anaFrameCounter, raspi.rebootReceivedAge, cpuUp.hours, cpuUp.minutes, cpuUp.seconds, sysApplUp.hours, sysApplUp.minutes, sysApplUp.seconds, anaApplUp.hours, anaApplUp.minutes, anaApplUp.seconds); } fprintf(writeTxt, "\n"); } // the statistics is always transmitted by the sender (and in most cases received) // use the packets counter to determine if the balls or objects has not been updated in a while int timeInvalid = 15; int timeOld = 6; linePointListExportMutex.lock(); if (linePointList[index].state != invalid) { int deltaPacketCnt = (256 + linePointList[index].packetCnt - stats[index].packetCnt) % 256; // range 0 to 255 if ((deltaPacketCnt > timeInvalid) && (deltaPacketCnt < (256 - timeInvalid))) { linePointList[index].state = invalid; } else if ((deltaPacketCnt > timeOld) && (deltaPacketCnt < (256 - timeOld))) { linePointList[index].state = old; } } linePointListExportMutex.unlock(); goodEnoughLocExportMutex.lock(); if (goodEnoughLoc[index].state != invalid) { int deltaPacketCnt = (256 + goodEnoughLoc[index].packetCnt - stats[index].packetCnt) % 256; // range 0 to 255 if ((deltaPacketCnt > timeInvalid) && (deltaPacketCnt < (256 - timeInvalid))) { goodEnoughLoc[index].state = invalid; } else if ((deltaPacketCnt > timeOld) && (deltaPacketCnt < (256 - timeOld))) { goodEnoughLoc[index].state = old; } } goodEnoughLocExportMutex.unlock(); ballListExportMutex.lock(); if (ballList[index].state != invalid) { int deltaPacketCnt = (256 + ballList[index].packetCnt - stats[index].packetCnt) % 256; // range 0 to 255 if ((deltaPacketCnt > timeInvalid) && (deltaPacketCnt < (256 - timeInvalid))) { ballList[index].state = invalid; } else if ((deltaPacketCnt > timeOld) && (deltaPacketCnt < (256 - timeOld))) { ballList[index].state = old; } } ballListExportMutex.unlock(); ballFarListExportMutex.lock(); if (ballFarList[index].state != invalid) { int deltaPacketCnt = (256 + ballFarList[index].packetCnt - stats[index].packetCnt) % 256; // range 0 to 255 if ((deltaPacketCnt > timeInvalid) && (deltaPacketCnt < (256 - timeInvalid))) { ballFarList[index].state = invalid; } else if ((deltaPacketCnt > timeOld) && (deltaPacketCnt < (256 - timeOld))) { ballFarList[index].state = old; } } ballFarListExportMutex.unlock(); cyanListExportMutex.lock(); if (cyanList[index].state != invalid) { int deltaPacketCnt = (256 + cyanList[index].packetCnt - stats[index].packetCnt) % 256; // range 0 to 255 if ((deltaPacketCnt > timeInvalid) && (deltaPacketCnt < (256 - timeInvalid))) { cyanList[index].state = invalid; } else if ((deltaPacketCnt > timeOld) && (deltaPacketCnt < (256 - timeOld))) { cyanList[index].state = old; } } cyanListExportMutex.unlock(); magentaListExportMutex.lock(); if (magentaList[index].state != invalid) { int deltaPacketCnt = (256 + magentaList[index].packetCnt - stats[index].packetCnt) % 256; // range 0 to 255 if ((deltaPacketCnt > timeInvalid) && (deltaPacketCnt < (256 - timeInvalid))) { magentaList[index].state = invalid; } else if ((deltaPacketCnt > timeOld) && (deltaPacketCnt < (256 - timeOld))) { magentaList[index].state = old; } } magentaListExportMutex.unlock(); obstacleListExportMutex.lock(); if (obstacleList[index].state != invalid) { int deltaPacketCnt = (256 + obstacleList[index].packetCnt - stats[index].packetCnt) % 256; // range 0 to 255 if ((deltaPacketCnt > timeInvalid) && (deltaPacketCnt < (256 - timeInvalid))) { obstacleList[index].state = invalid; } else if ((deltaPacketCnt > timeOld) && (deltaPacketCnt < (256 - timeOld))) { obstacleList[index].state = old; } } obstacleListExportMutex.unlock(); } void multicastReceive::decodeLocalization(size_t index) { // check if the packet size makes sense uint8_t oneLocalizationSize = 16; // each localization requires 8 * uint16_t = 16 bytes of the packet if (((recvBuf.size - HEADER_SIZE) % oneLocalizationSize) != 0) { printf(" %10s : ERROR : localization packet should be %d + n * %d bytes, but received %d bytes\n", ipAddress, HEADER_SIZE, oneLocalizationSize, recvBuf.size); } else { uint16_t payloadIndex = 0; locListExportMutex.lock(); locList[index].packetCnt = recvBuf.cnt; locList[index].list.clear(); ssize_t amountOfLocalizations = (recvBuf.size - HEADER_SIZE) / oneLocalizationSize; for (ssize_t ii = 0; ii < amountOfLocalizations; ii++) { detPosSt loc; // maximal x field size in pixels : 22 + xx = 24 meter / 2 cm = 1200 // maximal y field size in pixels : 14 + xx = 16 meter / 2 cm = 800 // use fixed point with 5 bits for fraction, range x[0:1199], y[0:799], 2^16/1200=54 loc.pos.x = recvBuf.pl.u16[payloadIndex++] / 32.0; loc.pos.y = recvBuf.pl.u16[payloadIndex++] / 32.0; // use fixed point with 6 bits for fraction, rz[0:359] loc.pos.rz = recvBuf.pl.u16[payloadIndex++] / 64.0; // use fixed point with 16 bits for fraction, range score[0:1] loc.score = recvBuf.pl.u16[payloadIndex++] / 65535.0; loc.lastActive = recvBuf.pl.u16[payloadIndex++]; loc.age = recvBuf.pl.u16[payloadIndex++]; loc.amountOnFloor = recvBuf.pl.u16[payloadIndex++]; loc.numberOfTries = recvBuf.pl.u16[payloadIndex++]; locList[index].list.push_back(loc); } locListExportMutex.unlock(); #ifdef NONO printf(" %10s loca %3d %5d", ipAddress, locList[index].packetCnt, recvBuf.size); for( size_t ii = 0; ii < locList[index].list.size(); ii++) { printf(" : %4.0f %4.0f %3.0f %3.3f %3d %3d %3d %3d", locList[index].list[ii].pos.x, locList[index].list[ii].pos.y, locList[index].list[ii].pos.rz, locList[index].list[ii].score, locList[index].list[ii].lastActive, locList[index].list[ii].age, locList[index].list[ii].amountOnFloor, locList[index].list[ii].numberOfTries ); } printf("\n"); #endif fprintf(writeTxt, "%zu %s %10s loca %3d %5d", stats[index].remoteTime, stats[index].remoteTimeString, ipAddress, locList[index].packetCnt, recvBuf.size); for (size_t ii = 0; ii < locList[index].list.size(); ii++) { fprintf(writeTxt, " : %4.0f %4.0f %3.0f %3.3f %3d %3d %3d %3d", locList[index].list[ii].pos.x, locList[index].list[ii].pos.y, locList[index].list[ii].pos.rz, locList[index].list[ii].score, locList[index].list[ii].lastActive, locList[index].list[ii].age, locList[index].list[ii].amountOnFloor, locList[index].list[ii].numberOfTries); } fprintf(writeTxt, "\n"); } } void multicastReceive::decodeGoodEnoughLoc(size_t index) { // check if the packet size makes sense uint8_t goodEnoughSize = 3 * 2 + 2 * 2 + 2 + 5 * 2; // see below for the size if (recvBuf.size != HEADER_SIZE + goodEnoughSize) { printf(" %10s : ERROR : goodEnough packet should be %d bytes, but received %d bytes\n", ipAddress, HEADER_SIZE + goodEnoughSize, recvBuf.size); } else { uint16_t payloadIndex = 0; goodEnoughLocExportMutex.lock(); goodEnoughLoc[index].packetCnt = recvBuf.cnt; goodEnoughLoc[index].state = updated; // maximal x field size in pixels : 22 + xx = 24 meter / 2 cm = 1200 // maximal y field size in pixels : 14 + xx = 16 meter / 2 cm = 800 // use fixed point with 5 bits for fraction, range x[0:1199], y[0:799], 2^16/1200=54 goodEnoughLoc[index].pos.x = recvBuf.pl.u16[payloadIndex++] / 32.0; goodEnoughLoc[index].pos.y = recvBuf.pl.u16[payloadIndex++] / 32.0; // use fixed point with 6 bits for fraction, range rz[0:359] goodEnoughLoc[index].pos.rz = recvBuf.pl.u16[payloadIndex++] / 64.0; // use fixed point with 6 bits for fraction, range x[-6.0:6.0], y[-9:9], 2^15/9=3641 // WARNING swap x and y in remote viewer to align with general x-axis and y-axis usage goodEnoughLoc[index].posRos.y = recvBuf.pl.s16[payloadIndex++] / 2048.0; // input is negative top and positive bottom goodEnoughLoc[index].posRos.x = recvBuf.pl.s16[payloadIndex++] / 2048.0; // use fixed point with 13 bits for fraction, range rz[0:6.28], 2^16/6.28=10436 // rz = 0 is on y axis goodEnoughLoc[index].posRos.rz = recvBuf.pl.u16[payloadIndex++] / 8192.0; // use fixed point with 16 bits for fraction, range score[0:1] goodEnoughLoc[index].score = recvBuf.pl.u16[payloadIndex++] / 65535.0; goodEnoughLoc[index].lastActive = recvBuf.pl.u16[payloadIndex++]; goodEnoughLoc[index].age = recvBuf.pl.u16[payloadIndex++]; goodEnoughLoc[index].amountOnFloor = recvBuf.pl.u16[payloadIndex++]; goodEnoughLoc[index].numberOfTries = recvBuf.pl.u16[payloadIndex++]; goodEnoughLoc[index].goodEnough = true; double x = 0.0; double y = 0.0; double rz = 0.0; posRosHistory[index].erase(posRosHistory[index].begin()); posRosHistory[index].push_back(goodEnoughLoc[index].posRos); for (size_t ii = 0; ii < posRosHistory[index].size(); ii++) { x += posRosHistory[index][ii].x; y += posRosHistory[index][ii].y; rz += posRosHistory[index][ii].rz; // TODO fix for values near 360 degrees } posRosAverage[index].x = x / posRosHistory[index].size(); posRosAverage[index].y = y / posRosHistory[index].size(); posRosAverage[index].rz = rz / posRosHistory[index].size(); #ifdef NONO printf(" %10s good %3d %5d : %4.0f %4.0f %3.0f : %3.3f : %3d %3d %3d %3d\n", ipAddress, goodEnoughLoc[index].packetCnt, recvBuf.size, goodEnoughLoc[index].pos.x, goodEnoughLoc[index].pos.y, goodEnoughLoc[index].pos.rz, goodEnoughLoc[index].score, goodEnoughLoc[index].lastActive, goodEnoughLoc[index].age, goodEnoughLoc[index].amountOnFloor, goodEnoughLoc[index].numberOfTries ); #endif fprintf(writeTxt, "%zu %s %10s good %3d %5d : %4.0f %4.0f %3.0f : %3.3f : %3d %3d %3d %3d\n", stats[index].remoteTime, stats[index].remoteTimeString, ipAddress, goodEnoughLoc[index].packetCnt, recvBuf.size, goodEnoughLoc[index].pos.x, goodEnoughLoc[index].pos.y, goodEnoughLoc[index].pos.rz, goodEnoughLoc[index].score, goodEnoughLoc[index].lastActive, goodEnoughLoc[index].age, goodEnoughLoc[index].amountOnFloor, goodEnoughLoc[index].numberOfTries); goodEnoughLocExportMutex.unlock(); } } void multicastReceive::decodeLinePoints(size_t index) { uint8_t objectSize = 2 * 2; // each line point contains 2 values of 2 bytes if (((recvBuf.size - HEADER_SIZE) % objectSize) != 0) { printf(" %10s : ERROR : line points packet should be %d + n * %d bytes, but received %d bytes\n", ipAddress, HEADER_SIZE, objectSize, recvBuf.size); } else { linePointListExportMutex.lock(); linePointList[index].packetCnt = recvBuf.cnt; linePointList[index].state = updated; linePointList[index].list.clear(); uint16_t payloadIndex = 0; ssize_t amountOfObjects = (recvBuf.size - HEADER_SIZE) / objectSize; for (ssize_t ii = 0; ii < amountOfObjects; ii++) { ballObstSt point; point.size = 0; // fixed point: 65536/2048 = 32, radius range 0 to 20 meters point.radius = recvBuf.pl.u16[payloadIndex++] / 2048.0; // fixed point: 65536/8192 = 8, angle range 0 to 6.28 radians point.azimuth = recvBuf.pl.u16[payloadIndex++] / 8192.0; point.elevation = 0.0; linePointList[index].list.push_back(point); } linePointListExportMutex.unlock(); #ifdef NONO printf(" %10s line %3d %5d", ipAddress, linePointList[index].packetCnt, recvBuf.size ); int maxPrintLine = (recvBuf.size - HEADER_SIZE)/2; if( maxPrintLine > 10 ) {maxPrintLine = 10;} // to prevent screen clutter for( int ii = 0; ii < maxPrintLine; ii++ ) { printf(" : %4.2f %5.1f", linePointList[index].list[ii].radius, linePointList[index].list[ii].angle * 180.0/M_PI); } printf(" \n" ); #endif fprintf(writeTxt, "%zu %s %10s line %3d %5d", stats[index].remoteTime, stats[index].remoteTimeString, ipAddress, linePointList[index].packetCnt, recvBuf.size); for (int ii = 0; ii < (recvBuf.size - HEADER_SIZE) / 2; ii++) { fprintf(writeTxt, " : %4.2f %5.1f", linePointList[index].list[ii].radius, linePointList[index].list[ii].azimuth * 180.0 / M_PI); } fprintf(writeTxt, " \n"); } } void multicastReceive::decodeBallList(size_t index) { // check if the packet size makes sense uint16_t objectSize = 2 * 4; // each ball contains 4 values of 2 bytes if (((recvBuf.size - HEADER_SIZE) % objectSize) != 0) { printf(" %10s : ERROR : ball packet should be %d + n * %d bytes, but received %d bytes\n", ipAddress, HEADER_SIZE, objectSize, recvBuf.size); } else { ballListExportMutex.lock(); ballList[index].packetCnt = recvBuf.cnt; ballList[index].state = updated; ballList[index].list.clear(); uint16_t payloadIndex = 0; ssize_t amountOfObjects = (recvBuf.size - HEADER_SIZE) / objectSize; for (ssize_t ii = 0; ii < amountOfObjects; ii++) { ballObstSt point; point.size = recvBuf.pl.u16[payloadIndex++]; // fixed point: 65536/2048 = 32, radius range 0 to 20 meters point.radius = recvBuf.pl.u16[payloadIndex++] / 2048.0; // fixed point: 65536/8192 = 8, azimuth range 0 to 6.28 radians point.azimuth = recvBuf.pl.u16[payloadIndex++] / 8192.0; // fixed point: 65536/8192 = 8, elevation range 0 to 6.28 radians point.elevation = recvBuf.pl.u16[payloadIndex++] / 8192.0; ballList[index].list.push_back(point); } ballListExportMutex.unlock(); #ifdef NONO printf(" %10s ball %3d %5d", ipAddress, ballList[index].packetCnt, recvBuf.size ); for( size_t ii = 0; ii < ballList[index].list.size(); ii++ ) { printf(" : %4d %4.2f %5.1f %5.1f", ballList[index].list[ii].size, ballList[index].list[ii].radius, ballList[index].list[ii].azimuth * 180.0/M_PI, ballList[index].list[ii].elevation * 180.0/M_PI ); } printf("\n"); #endif fprintf(writeTxt, "%zu %s %10s ball %3d %5d", stats[index].remoteTime, stats[index].remoteTimeString, ipAddress, ballList[index].packetCnt, recvBuf.size); for (size_t ii = 0; ii < ballList[index].list.size(); ii++) { fprintf(writeTxt, " : %4d %4.2f %5.1f %5.1f", ballList[index].list[ii].size, ballList[index].list[ii].radius, ballList[index].list[ii].azimuth * 180.0 / M_PI, ballList[index].list[ii].elevation * 180.0 / M_PI); } fprintf(writeTxt, "\n"); } } void multicastReceive::decodeBallFarList(size_t index) { // check if the packet size makes sense uint16_t objectSize = 2 * 4; // each ballFar contains 4 values of 2 bytes if (((recvBuf.size - HEADER_SIZE) % objectSize) != 0) { printf(" %10s : ERROR : ballFar packet should be %d + n * %d bytes, but received %d bytes\n", ipAddress, HEADER_SIZE, objectSize, recvBuf.size); } else { ballFarListExportMutex.lock(); ballFarList[index].packetCnt = recvBuf.cnt; ballFarList[index].state = updated; ballFarList[index].list.clear(); uint16_t payloadIndex = 0; ssize_t amountOfObjects = (recvBuf.size - HEADER_SIZE) / objectSize; for (ssize_t ii = 0; ii < amountOfObjects; ii++) { ballObstSt point; point.size = recvBuf.pl.u16[payloadIndex++]; // fixed point: 65536/2048 = 32, radius range 0 to 20 meters point.radius = recvBuf.pl.u16[payloadIndex++] / 2048.0; // fixed point: 65536/8192 = 8, azimuth range 0 to 6.28 radians point.azimuth = recvBuf.pl.u16[payloadIndex++] / 8192.0; // fixed point: 65536/8192 = 8, elevation range 0 to 6.28 radians point.elevation = recvBuf.pl.u16[payloadIndex++] / 8192.0; ballFarList[index].list.push_back(point); } ballFarListExportMutex.unlock(); #ifdef NONO printf(" %10s farb %3d %5d", ipAddress, ballFarList[index].packetCnt, recvBuf.size ); for( size_t ii = 0; ii < ballFarList[index].list.size(); ii++ ) { printf(" : %4d %4.2f %5.1f %5.1f", ballFarList[index].list[ii].size, ballFarList[index].list[ii].radius, ballFarList[index].list[ii].azimuth * 180.0/M_PI, ballFarList[index].list[ii].elevation * 180.0/M_PI ); } printf("\n"); #endif fprintf(writeTxt, "%zu %s %10s farb %3d %5d", stats[index].remoteTime, stats[index].remoteTimeString, ipAddress, ballFarList[index].packetCnt, recvBuf.size); for (size_t ii = 0; ii < ballFarList[index].list.size(); ii++) { fprintf(writeTxt, " : %4d %4.2f %5.1f %5.1f", ballFarList[index].list[ii].size, ballFarList[index].list[ii].radius, ballFarList[index].list[ii].azimuth * 180.0 / M_PI, ballFarList[index].list[ii].elevation * 180.0 / M_PI); } fprintf(writeTxt, "\n"); } } void multicastReceive::decodeCyanList(size_t index) { // check if the packet size makes sense uint16_t objectSize = 2 * 4; // each cyan object contains 4 values of 2 bytes if (((recvBuf.size - HEADER_SIZE) % objectSize) != 0) { printf(" %10s : ERROR : cyan packet should be %d + n * %d bytes, but received %d bytes\n", ipAddress, HEADER_SIZE, objectSize, recvBuf.size); } else { cyanListExportMutex.lock(); cyanList[index].packetCnt = recvBuf.cnt; cyanList[index].state = updated; cyanList[index].list.clear(); uint16_t payloadIndex = 0; ssize_t amountOfObjects = (recvBuf.size - HEADER_SIZE) / objectSize; for (ssize_t ii = 0; ii < amountOfObjects; ii++) { ballObstSt point; point.size = recvBuf.pl.u16[payloadIndex++]; // fixed point: 65536/2048 = 32, radius range 0 to 20 meters point.radius = recvBuf.pl.u16[payloadIndex++] / 2048.0; // fixed point: 65536/8192 = 8, angle range 0 to 6.28 radians point.azimuth = recvBuf.pl.u16[payloadIndex++] / 8192.0; // fixed point: 65536/8192 = 8, elevation range 0 to 6.28 radians point.elevation = recvBuf.pl.u16[payloadIndex++] / 8192.0; cyanList[index].list.push_back(point); } cyanListExportMutex.unlock(); #ifdef NONO printf(" %10s cyan %3d %5d", ipAddress, cyanList[index].packetCnt, recvBuf.size ); for( size_t ii = 0; ii < cyanList[index].list.size(); ii++ ) { printf(" : %4d %4.2f %5.1f %5.1f", cyanList[index].list[ii].size, cyanList[index].list[ii].radius, cyanList[index].list[ii].azimuth * 180.0/M_PI, cyanList[index].list[ii].elevation * 180.0/M_PI ); } printf("\n"); #endif fprintf(writeTxt, "%zu %s %10s cyan %3d %5d", stats[index].remoteTime, stats[index].remoteTimeString, ipAddress, cyanList[index].packetCnt, recvBuf.size); for (size_t ii = 0; ii < cyanList[index].list.size(); ii++) { fprintf(writeTxt, " : %4d %4.2f %5.1f %5.1f", cyanList[index].list[ii].size, cyanList[index].list[ii].radius, cyanList[index].list[ii].azimuth * 180.0 / M_PI, cyanList[index].list[ii].elevation * 180.0 / M_PI); } fprintf(writeTxt, "\n"); } } void multicastReceive::decodeMagentaList(size_t index) { // check if the packet size makes sense uint16_t objectSize = 2 * 4; // each magenta object contains 4 values of 2 bytes if (((recvBuf.size - HEADER_SIZE) % objectSize) != 0) { printf(" %10s : ERROR : magenta packet should be %d + n * %d bytes, but received %d bytes\n", ipAddress, HEADER_SIZE, objectSize, recvBuf.size); } else { magentaListExportMutex.lock(); magentaList[index].packetCnt = recvBuf.cnt; magentaList[index].state = updated; magentaList[index].list.clear(); uint16_t payloadIndex = 0; ssize_t amountOfObjects = (recvBuf.size - HEADER_SIZE) / objectSize; for (ssize_t ii = 0; ii < amountOfObjects; ii++) { ballObstSt point; point.size = recvBuf.pl.u16[payloadIndex++]; // fixed point: 65536/2048 = 32, radius range 0 to 20 meters point.radius = recvBuf.pl.u16[payloadIndex++] / 2048.0; // fixed point: 65536/8192 = 8, angle range 0 to 6.28 radians point.azimuth = recvBuf.pl.u16[payloadIndex++] / 8192.0; // fixed point: 65536/8192 = 8, elevation range 0 to 6.28 radians point.elevation = recvBuf.pl.u16[payloadIndex++] / 8192.0; magentaList[index].list.push_back(point); } magentaListExportMutex.unlock(); #ifdef NONO printf(" %10s magenta %3d %5d", ipAddress, magentaList[index].packetCnt, recvBuf.size ); for( size_t ii = 0; ii < magentaList[index].list.size(); ii++ ) { printf(" : %4d %4.2f %5.1f %5.1f", magentaList[index].list[ii].size, magentaList[index].list[ii].radius, magentaList[index].list[ii].azimuth * 180.0/M_PI, magentaList[index].list[ii].elevation * 180.0/M_PI ); } printf("\n"); #endif fprintf(writeTxt, "%zu %s %10s magenta %3d %5d", stats[index].remoteTime, stats[index].remoteTimeString, ipAddress, magentaList[index].packetCnt, recvBuf.size); for (size_t ii = 0; ii < magentaList[index].list.size(); ii++) { fprintf(writeTxt, " : %4d %4.2f %5.1f %5.1f", magentaList[index].list[ii].size, magentaList[index].list[ii].radius, magentaList[index].list[ii].azimuth * 180.0 / M_PI, magentaList[index].list[ii].elevation * 180.0 / M_PI); } fprintf(writeTxt, "\n"); } } void multicastReceive::decodeObstacleList(size_t index) { // check if the packet size makes sense uint16_t objectSize = 2 * 4; // each obstacle contains 4 values of 2 bytes if (((recvBuf.size - HEADER_SIZE) % objectSize) != 0) { printf(" %10s : ERROR : obstacle packet should be %d + n * %d bytes, but received %d bytes\n", ipAddress, HEADER_SIZE, objectSize, recvBuf.size); } else { obstacleListExportMutex.lock(); obstacleList[index].packetCnt = recvBuf.cnt; obstacleList[index].state = updated; obstacleList[index].list.clear(); uint16_t payloadIndex = 0; ssize_t amountOfObjects = (recvBuf.size - HEADER_SIZE) / objectSize; for (ssize_t ii = 0; ii < amountOfObjects; ii++) { ballObstSt point; point.size = recvBuf.pl.u16[payloadIndex++]; // fixed point: 65536/2048 = 32, radius range 0 to 20 meters point.radius = recvBuf.pl.u16[payloadIndex++] / 2048.0; // fixed point: 65536/8192 = 8, angle range 0 to 6.28 radians point.azimuth = recvBuf.pl.u16[payloadIndex++] / 8192.0; // fixed point: 65536/8192 = 8, elevation range 0 to 6.28 radians point.elevation = recvBuf.pl.u16[payloadIndex++] / 8192.0; obstacleList[index].list.push_back(point); } obstacleListExportMutex.unlock(); #ifdef NONO printf(" %10s obst %3d %5d", ipAddress, obstacleList[index].packetCnt, recvBuf.size); for( size_t ii = 0; ii < obstacleList[index].list.size(); ii++ ) { printf(" : %4d %4.2f %5.1f %5.1f", obstacleList[index].list[ii].size, obstacleList[index].list[ii].radius, obstacleList[index].list[ii].azimuth * 180.0/M_PI , obstacleList[index].list[ii].elevation * 180.0/M_PI ); } printf("\n"); #endif fprintf(writeTxt, "%zu %s %10s obst %3d %5d", stats[index].remoteTime, stats[index].remoteTimeString, ipAddress, obstacleList[index].packetCnt, recvBuf.size); for (size_t ii = 0; ii < obstacleList[index].list.size(); ii++) { fprintf(writeTxt, " : %4d %4.2f %5.1f %5.1f", obstacleList[index].list[ii].size, obstacleList[index].list[ii].radius, obstacleList[index].list[ii].azimuth * 180.0 / M_PI, obstacleList[index].list[ii].elevation * 180.0 / M_PI); } fprintf(writeTxt, "\n"); } } void multicastReceive::receive() { while (1) { size_t index = MAX_ROBOTS; bool readFromSocket = true; #ifdef READFROMFILE readFromSocket = false; // read the packets from file (available in the packets vector struct) uint8_t *readPtr; // use pointer to iterate through the receiver buffer readPtr = &recvBuf.type; // assign the address of the first element of the receive buffer to the pointer // wrap around the packet index when we reach the end (and prevent reading out of range) if ((packetIndex + 1) > packets.size()) { packetIndex = 0; // wrap around } index = packets[packetIndex].index; sprintf(ipAddress, "robot %zu", index + 1); for (size_t jj = 0; jj < packets[packetIndex].data.size(); jj++) { *readPtr = packets[packetIndex].data[jj]; readPtr++; } nbytes = packets[packetIndex].data.size(); // read the next packet for the next iteration if (!packetIndexPause) { packetIndex++; } usleep(5000); #else // block until data received if ((nbytes = recvfrom(fd, &recvBuf, sizeof(recvBuf), 0, &fromAddr, &fromAddrLen)) < 0) { perror("ERROR : cannot receive data, message"); exit(EXIT_FAILURE); } // extract the ip address from from fromAddr struct inet_ntop(AF_INET, &(((struct sockaddr_in *) &fromAddr)->sin_addr), ipAddress, sizeof(ipAddress)); // determine from which robot the packet was comming if (strcmp(ipAddress, "172.16.74.51") == 0) { index = 0; } // robot 1 else if (strcmp(ipAddress, "172.16.74.52") == 0) { index = 1; } // robot 2 else if (strcmp(ipAddress, "172.16.74.53") == 0) { index = 2; } // robot 3 else if (strcmp(ipAddress, "172.16.74.54") == 0) { index = 3; } // robot 4 else if (strcmp(ipAddress, "172.16.74.55") == 0) { index = 4; } // robot 5 else if (strcmp(ipAddress, "172.16.74.56") == 0) { index = 5; } // robot 6 else if (strcmp(ipAddress, "172.16.74.57") == 0) { index = 6; } // robot 7 else if (strcmp(ipAddress, "172.16.74.58") == 0) { index = 7; } // robot 8 else if (strcmp(ipAddress, "172.16.74.59") == 0) { index = 8; } // robot 9 else if (strcmp(ipAddress, "10.0.0.1") == 0) { index = 2; } // tweety acts as robot 2 else if (strcmp(ipAddress, "10.0.0.61") == 0) { index = 4; } // pannekoek acts as robot 5 else if (strcmp(ipAddress, "10.0.0.64") == 0) { index = 3; } // fiction acts as robot 4 else if (strcmp(ipAddress, "10.0.0.65") == 0) { index = 3; } // fiction acts as robot 4 else if (strcmp(ipAddress, "10.0.0.68") == 0) { index = 3; } // fiction acts as robot 4 else if (strcmp(ipAddress, "10.0.0.129") == 0) { index = 7; } // fiction acts as robot 8 else if (strncmp(ipAddress, "172.16.74.1", 11) == 0) { index = 3; } // fiction acts as robot 4 else if (strncmp(ipAddress, "172.16.74.2", 11) == 0) { index = 3; } // fiction acts as robot 4 else if (strncmp(ipAddress, "192.168.", 8) == 0) { index = 3; } // fiction acts as robot 4 else if (strcmp(ipAddress, "10.116.82.137") == 0) { index = 0; } // robot 1 else { printf(" %10s : ERROR : do not know how to decode ip address %s\n", ipAddress, ipAddress); exit(EXIT_FAILURE); } #endif // fwrite(&recvBuf, nbytes, 1, writeBin); // do not know how to extract the different packets from the file created with fwrite, so just use ascii to print the numbers and use \n as separator fprintf(writeBin, "%02x", (uint8_t) index); // first print the robot index to the logfile uint8_t *writePtr; // use pointer to iterate through the receiver buffer writePtr = &recvBuf.type; // assign the address of the first element of the receive buffer to the pointer for (int ii = 0; ii < nbytes; ii++) { fprintf(writeBin, "%02x", *(writePtr++)); } fprintf(writeBin, "\n"); if (index >= MAX_ROBOTS) { printf(" %10s : ERROR : index %lu out of range (0 to %d)\n", ipAddress, index, MAX_ROBOTS); } if (readFromSocket || (!packetIndexPause)) { packetCnt[index] = packetCnt[index] % 256; if (recvBuf.cnt != packetCnt[index]) { // printf(" %10s : ERROR : expected packet counter %d, but got %d\n", ipAddress, packetCnt[index], recvBuf.cnt); packetErrorCnt[index]++; packetCnt[index] = recvBuf.cnt + 1; } else { packetCnt[index]++; } packetCnt[index] = packetCnt[index] % 256; } if (recvBuf.size != nbytes) { printf(" %10s : ERROR : expected %d bytes, but got %d bytes\n", ipAddress, recvBuf.size, nbytes); } if (readFromSocket || (packetIndexPrev != packetIndex)) { // only update console and viewer if new packet if (recvBuf.type == TYPE_STATS) { decodeStats(index); } else if (recvBuf.type == TYPE_LINEPOINTS) { decodeLinePoints(index); } else if (recvBuf.type == TYPE_LOCALIZATION) { decodeLocalization(index); } else if (recvBuf.type == TYPE_GOOD_ENOUGH_LOC) { decodeGoodEnoughLoc(index); } else if (recvBuf.type == TYPE_BALLDETECTION) { decodeBallList(index); } else if (recvBuf.type == TYPE_BALLFARDETECTION) { decodeBallFarList(index); } else if (recvBuf.type == TYPE_OBSTACLES) { decodeObstacleList(index); } else if (recvBuf.type == TYPE_CYANDETECTION) { decodeCyanList(index); } else if (recvBuf.type == TYPE_MAGENTADETECTION) { decodeMagentaList(index); } else { printf(" %10s : ERROR : received unexpected type %d\n", ipAddress, recvBuf.type); } } // store the current packetIndex for the next iteration to be able to check we need to update the viewer and logging in console packetIndexPrev = packetIndex; } } size_t multicastReceive::getPacketErrorCnt(size_t index) { statsExportMutex.lock(); size_t retVal = packetErrorCnt[index]; statsExportMutex.unlock(); return retVal; } statsSt multicastReceive::getStats(size_t index) { statsExportMutex.lock(); statsSt retVal = stats[index]; statsExportMutex.unlock(); return retVal; } std::vector<statsSt> multicastReceive::getStatsSort() { std::vector<statsSt> statsSort; statsExportMutex.lock(); statsSort = stats; statsExportMutex.unlock(); sort(statsSort.begin(), statsSort.end()); return statsSort; } ballObstListSt multicastReceive::getLinePointList(size_t index) { linePointListExportMutex.lock(); ballObstListSt retVal = linePointList[index]; linePointListExportMutex.unlock(); return retVal; } goodEnoughLocSt multicastReceive::getGoodEnoughLoc(size_t index) { goodEnoughLocExportMutex.lock(); goodEnoughLocSt retVal = goodEnoughLoc[index]; goodEnoughLocExportMutex.unlock(); return retVal; } positionStDbl multicastReceive::getGoodEnoughLocRosAverage(size_t index) { goodEnoughLocExportMutex.lock(); positionStDbl retVal = posRosAverage[index]; goodEnoughLocExportMutex.unlock(); return retVal; } locListSt multicastReceive::getLocList(size_t index) { locListExportMutex.lock(); locListSt retVal = locList[index]; locListExportMutex.unlock(); return retVal; } ballObstListSt multicastReceive::getBallList(size_t index, size_t type) { ballObstListSt retVal; if (type == TYPE_BALLDETECTION) { ballListExportMutex.lock(); retVal = ballList[index]; ballListExportMutex.unlock(); } else if (type == TYPE_BALLFARDETECTION) { ballFarListExportMutex.lock(); retVal = ballFarList[index]; ballFarListExportMutex.unlock(); } else if (type == TYPE_CYANDETECTION) { cyanListExportMutex.lock(); retVal = cyanList[index]; cyanListExportMutex.unlock(); } else if (type == TYPE_MAGENTADETECTION) { magentaListExportMutex.lock(); retVal = magentaList[index]; magentaListExportMutex.unlock(); } else { printf(" %10s : ERROR : type %zu out of range\n", ipAddress, type); exit(EXIT_FAILURE); } return retVal; } ballObstListSt multicastReceive::getObstacleList(size_t index) { obstacleListExportMutex.lock(); ballObstListSt retVal = obstacleList[index]; obstacleListExportMutex.unlock(); return retVal; } void multicastReceive::packetIndexAdd(int value) { int newIndex = packetIndex + value; if (newIndex < 0) { // so the value was negative, wrap from beginning of index to end of index newIndex = packets.size() + newIndex; } else if ((newIndex + 1) > (int) packets.size()) { // so the value was positive and we where already at the end of the index, wrap to the beginning of the index newIndex = newIndex + 1 - packets.size(); } packetIndex = (size_t) newIndex; // printf(" %10s : INFO : value change %d results to new packetIndex %zu\n", ipAddress, value, packetIndex); } hhMmSsSt multicastReceive::secondsToHhMmSs(uint16_t input) { hhMmSsSt retVal; if (input == 0xffff) { // make clear the provided time is out of range retVal.hours = 99; retVal.minutes = 99; retVal.seconds = 99; } else { retVal.hours = input / 3600; retVal.minutes = (input - retVal.hours * 3600) / 60; retVal.seconds = input - retVal.hours * 3600 - retVal.minutes * 60; } return retVal; }
39.3709
151
0.68318
Falcons-Robocup
fc4387bcd7722c348014d92ee2580001bd33c40a
2,894
cpp
C++
Engine/posttoantigate.cpp
vadkasevas/BAS
657f62794451c564c77d6f92b2afa9f5daf2f517
[ "MIT" ]
302
2016-05-20T12:55:23.000Z
2022-03-29T02:26:14.000Z
Engine/posttoantigate.cpp
chulakshana/BAS
955f5a41bd004bcdd7d19725df6ab229b911c09f
[ "MIT" ]
9
2016-07-21T09:04:50.000Z
2021-05-16T07:34:42.000Z
Engine/posttoantigate.cpp
chulakshana/BAS
955f5a41bd004bcdd7d19725df6ab229b911c09f
[ "MIT" ]
113
2016-05-18T07:48:37.000Z
2022-02-26T12:59:39.000Z
#include "posttoantigate.h" #include "every_cpp.h" #include <QMap> #include <QPixmap> #include <QBuffer> #include <QMapIterator> namespace BrowserAutomationStudioFramework { PostToAntigate::PostToAntigate(QObject *parent) : QObject(parent) { } void PostToAntigate::Post(const QString& id,const QString& key,const QString& base64, const QMap<QString,QString>& Properties, const QString& soft, bool DisableImageConvert) { this->id = id; QHash<QString,ContentData> post; { ContentData DataMethod; DataMethod.DataString = "post"; post["method"] = DataMethod; } { ContentData DataKey; DataKey.DataString = key; post["key"] = DataKey; } { ContentData DataFile; if(DisableImageConvert) { DataFile.DataRaw = QByteArray::fromBase64(base64.toUtf8()); }else { QImage image = QImage::fromData(QByteArray::fromBase64(base64.toUtf8())); QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); image.save(&buffer, "JPEG"); buffer.close(); DataFile.DataRaw = ba; } DataFile.FileName = "image.jpg"; DataFile.ContentType = "application/octet-stream"; post["file"] = DataFile; } if(!soft.isEmpty()) { ContentData DataSoftId; DataSoftId.DataString = soft; post["soft_id"] = DataSoftId; } QMapIterator<QString, QString> i(Properties); while (i.hasNext()) { i.next(); if(i.value().length() > 0 && i.key().length() > 0) { ContentData DataKey; DataKey.DataString = i.value(); post[i.key()] = DataKey; } } HttpClient->Connect(this,SLOT(submitRequestFinished())); HttpClient->Post(Server + "in.php",post); } void PostToAntigate::SetServer(const QString& Server) { this->Server = Server; } void PostToAntigate::submitRequestFinished() { if(HttpClient->WasError()) { emit PostedToAntigate(HttpClient->GetErrorString(),id,false); return; } QString res = HttpClient->GetContent(); if(!res.startsWith("OK|")) { emit PostedToAntigate(res,id,false); return; } QString r = res.remove(0,3); emit PostedToAntigate(r,id,true); } void PostToAntigate::SetHttpClient(IHttpClient * HttpClient) { this->HttpClient = HttpClient; } IHttpClient * PostToAntigate::GetHttpClient() { return HttpClient; } }
25.165217
177
0.533172
vadkasevas
fc4540e3a67875ca07a322da13529cbacca1c3bb
4,461
cpp
C++
Source/mysql/main.cpp
inkneko-software/dao_generator
88f000622677a355a2807750c59dff73913777e9
[ "MIT" ]
null
null
null
Source/mysql/main.cpp
inkneko-software/dao_generator
88f000622677a355a2807750c59dff73913777e9
[ "MIT" ]
null
null
null
Source/mysql/main.cpp
inkneko-software/dao_generator
88f000622677a355a2807750c59dff73913777e9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <fstream> #include <vector> #include <map> #include <boost/filesystem.hpp> #include <boost/regex.hpp> using namespace std; using namespace boost::filesystem; using namespace boost; void tableObjectGenerator(const path& output, pair<string, vector<pair<string, string>>> tabledef) { string tableName = tabledef.first; std::fstream file(output.string() + "/" + tableName + ".h", std::fstream::out); if (tableName[0] <= 'z' && tableName[0] >= 'a') { tableName[0] -= 'a' - 'A'; } for (size_t i = 0; i < tableName.size(); ++i) { if (tableName[i] == '_') { if (tableName[i + 1] <= 'z' && tableName[i + 1] >= 'a') { tableName[i+1] -= 'a' - 'A'; } tableName = tableName.erase(i, 1); --i; } } file << "/************************************************************************************" << endl << " * Table: [" << tableName << "] " << endl << " * Generated by inkneko dao_generator for mysql. " << endl << " ************************************************************************************/" << endl; file << "#include <string>" << endl << endl; file << "struct " << tableName << endl; file << "{" << endl; for (auto row : tabledef.second) { file << " "; string typeName = row.second; for (auto &c : typeName) { if (c >= 'a' && c <= 'z') { c -= 'a' - 'A'; } } if (typeName == "TINYINT") { file << "short "; } else if (typeName == "INT") { file << "int "; } else if (typeName == "TINYTEXT" || typeName == "TEXT" || typeName == "DATETIME" || typeName.find("CHAR") != string::npos) { file << "std::string "; } else if (typeName == "TIMESTAMP" || typeName == "LONGINT") { file << "long "; } else { file << "unsupported: " << typeName << " "; cout << "unsupported: " << typeName << " at table [" << tableName << "]" << endl; } file << row.first << ";" << endl; } file << "}" << flush; cout << "\t" << "table [" << tableName << "] generated" << endl; } void generator(const path& output, map<string, vector<pair<string, string>>> database) { create_directories(output); path tableDirectory(output); tableDirectory.append("table"); create_directory(tableDirectory); for (auto e : database) { tableObjectGenerator(tableDirectory, e); } } map<string, vector<pair<string, string>>> parse(string sqlContent) { //cout << sqlContent << flush; map<string, vector<pair<string, string>>> database; regex fmt("CREATE\\s+TABLE\\s+([a-zA-Z0-9_]+)\\s*\\(([^;]+)\\)[^;]+", regex::extended); regex_iterator<string::const_iterator> iter(sqlContent.cbegin(), sqlContent.cend(), fmt); for (auto index = iter; index != sregex_iterator(); ++index) { //cout << "table [" << index->str(1) << "] content: " << index->str(2) << endl; string table = index->str(1); string rowsText = index->str(2); regex rowfmt("([^\\s]+)\\s+([^\\s]+)[^,]+(,|)", regex::extended); regex_iterator<string::const_iterator> rowiter(rowsText.cbegin(), rowsText.cend(), rowfmt); vector<pair<string, string>> rows; //name : type(unsigned not supported) for (auto rowIndex = rowiter; rowIndex != sregex_iterator(); ++rowIndex) { rows.push_back({ rowIndex->str(1), rowIndex->str(2) }); } cout << "table name [" << table << "], rows: " << endl; for (auto row : rows) { cout << '\t' << row.first << " -> " << row.second << endl; } database[table] = rows; } return database; } int main(int argc, char** argv) { if (argc == 1) { return -1; } path enum_dir(argv[1]); directory_iterator enum_dir_iter(enum_dir); for (auto& entry : enum_dir_iter) { path sqlFilePath = canonical(entry.path()); if (sqlFilePath.extension().string() == ".sql") { std::fstream file(sqlFilePath.string(), std::fstream::in); cout << "[" << sqlFilePath.string() << "]" << "file content: " << endl; string line; string fileContent; while (getline(file, line)) { fileContent += line + '\n'; //cout << line << endl; } auto database = parse(fileContent); path databaseOutputDir(sqlFilePath.parent_path()); string databaseName = sqlFilePath.filename().string(); databaseName = databaseName.substr(0, databaseName.find('.')); databaseOutputDir.append(databaseName); for (auto table : database) { generator(databaseOutputDir, database); } } } return 0; }
27.537037
123
0.557498
inkneko-software
fc4d88c4927883c6fde339dada02ad66b681f371
7,238
cpp
C++
RTPS/Factory/RtpsFactory.cpp
intact-software-systems/cpp-software-patterns
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
[ "MIT" ]
1
2020-09-03T07:23:11.000Z
2020-09-03T07:23:11.000Z
RTPS/Factory/RtpsFactory.cpp
intact-software-systems/cpp-software-patterns
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
[ "MIT" ]
null
null
null
RTPS/Factory/RtpsFactory.cpp
intact-software-systems/cpp-software-patterns
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
[ "MIT" ]
null
null
null
/* * RtpsFactory.cpp * * Created on: Mar 25, 2012 * Author: knuthelv */ #include"RTPS/Factory/RtpsFactory.h" #include"RTPS/Stateless/IncludeLibs.h" #include"RTPS/Stateful/IncludeLibs.h" #include"RTPS/Machine/IncludeLibs.h" namespace RTPS { /*------------------------------------------------------------------------- class RtpsFactory -------------------------------------------------------------------------*/ RtpsFactory::RtpsFactory() { } RtpsFactory::~RtpsFactory() { } /*------------------------------------------------------------------------- create RTPS virtual machine -------------------------------------------------------------------------*/ VirtualMachine* RtpsFactory::NewVirtualMachine(const GUID &guid , IOReaderWriter::Ptr socketStream , unsigned int datagramSize , TopicKindId::Type topicKind , ReliabilityKindId::Type reliabilityKind , WriterKind::Type writerType , ReaderKind::Type readerType) { RtpsMessageSender::Ptr messageSender(new RtpsMessageSender(guid.GetGuidPrefix(), socketStream, datagramSize )); VirtualMachine *virtualMachine = new VirtualMachine(guid, messageSender); //RtpsReader* rtpsReader = RtpsFactory::NewDefaultRtpsReader(readerType, guid, topicKind, reliabilityKind); //ASSERT(rtpsReader); bool success = virtualMachine->InitializeReader(readerType, topicKind, reliabilityKind); ASSERT(success); success = virtualMachine->InitializeWriter(writerType, topicKind, reliabilityKind); ASSERT(success); return virtualMachine; } /*------------------------------------------------------------------------- create default RTPS writer -------------------------------------------------------------------------*/ RtpsWriter* RtpsFactory::NewDefaultRtpsWriter(WriterKind::Type writerKind, const GUID &guid, TopicKindId::Type topicKind, ReliabilityKindId::Type reliabilityKind) { RtpsWriter *rtpsWriter = NULL; switch(writerKind) { case WriterKind::Stateless: { Duration resendDataPeriod(1); rtpsWriter = new StatelessWriter(guid, topicKind, reliabilityKind, resendDataPeriod); break; } case WriterKind::Stateful: { rtpsWriter = new StatefulWriter(guid, topicKind, reliabilityKind); break; } case WriterKind::Undefined: default: throw CriticalException("WriterKind was undefined!"); break; } return rtpsWriter; } /*------------------------------------------------------------------------- create default RTPS reader -------------------------------------------------------------------------*/ RtpsReader* RtpsFactory::NewDefaultRtpsReader(ReaderKind::Type readerKind, const GUID &guid, TopicKindId::Type topicKind, ReliabilityKindId::Type reliabilityKind) { RtpsReader *rtpsReader = NULL; switch(readerKind) { case ReaderKind::Stateless: { rtpsReader = new StatelessReader(guid, topicKind, reliabilityKind); break; } case ReaderKind::Stateful: { rtpsReader = new StatefulReader(guid, topicKind, reliabilityKind); break; } case ReaderKind::Undefined: default: throw CriticalException("ReaderKind was undefined!"); break; } return rtpsReader; } /* The HistoryCache of the SPDPbuiltinParticipantReader contains information on all active discovered participants; the key used to identify each data-object corresponds to the Participant GUID. Each time information on a participant is received by the SPDPbuiltinParticipantReader, the SPDP examines the HistoryCache looking for an entry with a key that matches the Participant GUID. If an entry with a matching key is not there, a new entry is added keyed by the GUID of the Participant. Periodically, the SPDP examines the SPDPbuiltinParticipantReader HistoryCache looking for stale entries defined as those that have not been refreshed for a period longer than their specified leaseDuration. Stale entries are removed. */ /** * @brief RtpsFactory::CreateSimpleParticipantDiscovery * @param guid * @return */ RtpsParticipant::Ptr RtpsFactory::CreateSimpleParticipantDiscovery(const GUID &guid) { /* SPDPbuiltinParticipantWriter attribute type value unicastLocatorList Locator_t[*] <auto-detected> Transport-kinds and addresses are either auto-detected or configured by the application. Ports are a parameter to the SPDP initialization or else are set to a PSM-specified value that depends on the domainId. multicastLocatorList Locator_t[*] <parameter to the SPDP initialization> Defaults to a PSM-specified value. reliabilityLevel ReliabilityKind_t BEST_EFFORT topicKind TopicKind_t WITH_KEY resendPeriod Duration_t <parameter to the SPDP initialization> Defaults to a PSM-specified value. readerLocators ReaderLocator[*] <parameter to the SPDP initialization> */ GUID writerGuid(guid.GetGuidPrefix(), EntityId::EntityId_SPDP_BUILTIN_PARTICIPANT_WRITER()); StatelessWriter::Ptr writer(new StatelessWriter(writerGuid, TopicKindId::WithKey, ReliabilityKindId::BestEffort, Duration::FromMilliseconds(2000))); /* SPDPbuiltinParticipantReader attribute type value unicastLocatorList Locator_t[*] <auto-detected> Transport-kinds and addresses are either auto-detected or configured by the application. Ports are a parameter to the SPDP initialization or else are set to a PSM-specified value that depends on the domainId. multicastLocatorList Locator_t[*] <parameter to the SPDP initialization>. Defaults to a PSM-specified value. reliabilityLevel ReliabilityKind_t BEST_EFFORT topicKind TopicKind_t WITH_KEY */ GUID readerGuid(guid.GetGuidPrefix(), EntityId::EntityId_ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER()); StatelessReader::Ptr reader(new StatelessReader(readerGuid, TopicKindId::WithKey, ReliabilityKindId::BestEffort)); RtpsParticipant::Ptr participant(new RtpsParticipant(guid)); return participant; } } // namespace RTPS
41.36
175
0.564797
intact-software-systems
fc4e1df538dae331072c04d44a82b268a0125a77
4,389
cpp
C++
src/core/lib/core_reflection/unit_test/test_methods.cpp
wgsyd/wgtf
d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed
[ "BSD-3-Clause" ]
28
2016-06-03T05:28:25.000Z
2019-02-14T12:04:31.000Z
src/core/lib/core_reflection/unit_test/test_methods.cpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
null
null
null
src/core/lib/core_reflection/unit_test/test_methods.cpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
14
2016-06-03T05:52:27.000Z
2019-03-21T09:56:03.000Z
#include "pch.hpp" #include "core_reflection/interfaces/i_class_definition.hpp" #include "core_reflection/reflected_property.hpp" #include "core_reflection/reflected_object.hpp" #include "core_reflection/reflection_macros.hpp" #include "core_reflection/property_accessor.hpp" #include "core_reflection/metadata/meta_types.hpp" #include "core_reflection/definition_manager.hpp" #include "core_reflection/reflected_method_parameters.hpp" #include "core_reflection/unit_test/test_reflection_fixture.hpp" #include "core_object/managed_object.hpp" #include "core/testing/reflection_objects_test/test_objects.hpp" #include "core/testing/reflection_objects_test/test_methods_object.hpp" namespace wgt { struct TestMethodsFixture : public TestReflectionFixture { TestMethodsFixture() { IDefinitionManager& definitionManager = getDefinitionManager(); klass_ = definitionManager.getDefinition<TestMethodsObject>(); } IBasePropertyPtr findProperty(PropertyIterator& itr, const std::string& name) { IBasePropertyPtr property = *itr; std::string propertyName = property == nullptr ? "" : property->getName(); while (propertyName != name && property != nullptr) { ++itr; property = *itr; propertyName = property == nullptr ? "" : property->getName(); } return propertyName == name ? property : nullptr; } public: IClassDefinition* klass_; }; TEST_F(TestMethodsFixture, methods) { ManagedObject<TestMethodsObject> object(std::make_unique<TestMethodsObject>()); ObjectHandleT<TestMethodsObject> handle = object.getHandleT(); ReflectedMethodParameters parameters; auto pa = klass_->bindProperty("TestMethod1", handle); CHECK(pa.isValid()); Variant result = pa.invoke(parameters); pa = klass_->bindProperty("TestMethod2", handle); CHECK(pa.isValid()); result = pa.invoke(parameters); pa = klass_->bindProperty("TestMethod3", handle); CHECK(pa.isValid()); parameters.push_back(int(5)); result = pa.invoke(parameters); std::string testResult; result.tryCast(testResult); CHECK(testResult == "test3"); pa = klass_->bindProperty("TestMethod4", handle); CHECK(pa.isValid()); std::string parameterString = "test"; parameters = Variant(parameterString), Variant(5); result = pa.invoke(parameters); result.tryCast(testResult); CHECK(testResult == "test4"); pa = klass_->bindProperty("TestMethod5", handle); CHECK(pa.isValid()); parameters = Variant(parameterString); result = pa.invoke(parameters); parameters[0].tryCast(testResult); CHECK(testResult == "test5"); pa = klass_->bindProperty("TestMethod6", handle); CHECK(pa.isValid()); parameters = Variant(&parameterString); pa.invoke(parameters); testResult = *parameters[0].cast<std::string*>(); CHECK(testResult == "test6"); CHECK(parameterString == "test6"); parameters.clear(); pa = klass_->bindProperty("TestMethod7", handle); CHECK(pa.isValid()); result = pa.invoke(Variant(double(4.4))); int testIntResult = result.value<int>(); CHECK(testIntResult == 4); pa = klass_->bindProperty("TestMethod8", handle); CHECK(pa.isValid()); result = pa.invoke(Variant(int(5))); double testDoubleResult = result.value<double>(); CHECK(testDoubleResult == 5.0); pa = klass_->bindProperty("TestMethod9", handle); CHECK(pa.isValid()); const std::string& constParameterString = parameterString; parameters = Variant(constParameterString); result = pa.invoke(parameters); const std::string& testConstStrResult = result.cast<const std::string&>(); CHECK(testConstStrResult == parameterString); pa = klass_->bindProperty("TestMethod10", handle); CHECK(pa.isValid()); const std::string* constParameterPtrString = &parameterString; parameters = Variant(constParameterPtrString); result = pa.invoke(parameters); const std::string* testConstStrPtrResult = result.cast<const std::string*>(); CHECK(*testConstStrPtrResult == parameterString); pa = klass_->bindProperty("TestMethod11", handle); CHECK(pa.isValid()); parameters = Variant(parameterString); result = pa.invoke(parameters); std::string& testStrResult = result.cast<std::string&>(); CHECK(testStrResult == parameterString); pa = klass_->bindProperty("TestMethod12", handle); CHECK(pa.isValid()); parameters = Variant(&parameterString); result = pa.invoke(parameters); std::string* testStrPtrResult = result.cast<std::string*>(); CHECK(*testStrPtrResult == parameterString); } } // end namespace wgt
32.511111
80
0.749373
wgsyd
fc4e5bb6b4221eb7761eeb3586ed0dd6f41406ba
1,247
hpp
C++
bulletgba/generator/data/code/__system/downline-rapidlaser.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
5
2020-03-24T07:44:49.000Z
2021-08-30T14:43:31.000Z
bulletgba/generator/data/code/__system/downline-rapidlaser.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
null
null
null
bulletgba/generator/data/code/__system/downline-rapidlaser.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
null
null
null
#ifndef GENERATED_67db08201e650091d0f4debd02149456_HPP #define GENERATED_67db08201e650091d0f4debd02149456_HPP #include "bullet.hpp" void stepfunc_4dc4ca4ba154013f98fc63fdd20fbaf2_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_c4d4e858c15e560b23a1b1a6a8131982_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_2a24623d850bb46dfc969cefad96c57c_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_2015d27d528ae3d3a8365fb25a3ad1ea_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_5dda4a230e07db3ae7ab7ce78b44b63b_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_b9f3746024faf71a948d02a3f58cba12_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_dae2cf81747ffb5070f05c8837b1d568_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); extern const BulletStepFunc bullet_ae60f2273dfc8bd3dd8828bd97217701_e52a135e83b87469f9e45b4e6e7c5ead[]; const unsigned int bullet_ae60f2273dfc8bd3dd8828bd97217701_e52a135e83b87469f9e45b4e6e7c5ead_size = 4; extern const BulletStepFunc bullet_4154844b0b807fc482cd4798940592e4_e52a135e83b87469f9e45b4e6e7c5ead[]; const unsigned int bullet_4154844b0b807fc482cd4798940592e4_e52a135e83b87469f9e45b4e6e7c5ead_size = 122; #endif
54.217391
104
0.907779
pqrs-org
fc4e8262880bafc08d6758cf504d733aa34672ff
235
cpp
C++
baekjoon/10950.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
1
2019-07-15T00:27:37.000Z
2019-07-15T00:27:37.000Z
baekjoon/10950.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
null
null
null
baekjoon/10950.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int a,b,t; cin >> t; while(t--){ cin >> a >> b; cout << a+b << endl; } return 0; }
15.666667
37
0.493617
3-24
fc4f21ad5ce4d3d35e574b80a2d54094e6e26222
838
cpp
C++
src/FileIO/ParserTools.cpp
tizian/Cendric2
5b0438c73a751bcc0d63c3af839af04ab0fb21a3
[ "MIT" ]
279
2015-05-06T19:04:07.000Z
2022-03-21T21:33:38.000Z
src/FileIO/ParserTools.cpp
tizian/Cendric2
5b0438c73a751bcc0d63c3af839af04ab0fb21a3
[ "MIT" ]
222
2016-10-26T15:56:25.000Z
2021-10-03T15:30:18.000Z
src/FileIO/ParserTools.cpp
tizian/Cendric2
5b0438c73a751bcc0d63c3af839af04ab0fb21a3
[ "MIT" ]
49
2015-10-01T21:23:03.000Z
2022-03-19T20:11:31.000Z
#include "FileIO/ParserTools.h" std::vector<Condition> ParserTools::parseConditions(const std::string& toParse_, bool negativeConditions) { std::vector<Condition> conditions; std::string toParse = toParse_; size_t pos; while (!toParse.empty()) { if ((pos = toParse.find(",")) == std::string::npos) { return conditions; } std::string conditionType = toParse.substr(0, pos); toParse.erase(0, pos + 1); std::string conditionName; if ((pos = toParse.find(",")) != std::string::npos) { conditionName = toParse.substr(0, pos); toParse.erase(0, pos + 1); } else { conditionName = toParse; toParse.clear(); } Condition condition; condition.type = conditionType; condition.name = conditionName; condition.negative = negativeConditions; conditions.push_back(condition); } return conditions; }
23.942857
107
0.686158
tizian
fc516cf44e2eeb7a5d5d050059b0dac2987eef36
191
inl
C++
admin/wmi/wbem/tools/locstudioparser/inc/locutil/logfile.inl
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/tools/locstudioparser/inc/locutil/logfile.inl
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/tools/locstudioparser/inc/locutil/logfile.inl
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (C) 1996-1999 Microsoft Corporation Module Name: LOGFILE.INL History: --*/ inline CLogFile::CLogFile() {} inline CLogFile::~CLogFile() {}
7.958333
46
0.570681
npocmaka
fc53bf9655ae0958e75c77a71b612a507c5d3ccc
3,951
cpp
C++
src/main.cpp
FelipeCRamos/amaze
ce483a246025b3bf6bb9a76b4db87f13aac9e048
[ "MIT" ]
null
null
null
src/main.cpp
FelipeCRamos/amaze
ce483a246025b3bf6bb9a76b4db87f13aac9e048
[ "MIT" ]
null
null
null
src/main.cpp
FelipeCRamos/amaze
ce483a246025b3bf6bb9a76b4db87f13aac9e048
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <fstream> #include <string> #include <iomanip> #include <cassert> #include <thread> #include <vector> #include <map> #include "maze.hpp" void separator(){ const char SEP_CHAR = '-'; const size_t SEP_FILL = 80; std::cout << "\e[2m" << std::setfill(SEP_CHAR) << std::setw(SEP_FILL) << "\e[0m" << "\n"; } int main( int argc, char **argv ){ std::string filepath; /* read parameters from argc & argv */ { if( argc > 1 ){ if( argc == 3 ){ std::string _flag( argv[1] ); std::istringstream file( argv[2] ); if( _flag != "-f" ){ std::cerr << "ERROR: Flag incorrect, please try another.\n"; return 1; } file >> filepath; } else { std::cerr << "ERROR: Arguments are incorrent (too big or too small)\n"; std::cerr << "Please, try running again following the example:"; std::cerr << "\n./amaze -f input_folder/input_file.dat\n"; return 1; } } else { std::cerr << "ERROR: Invalid number of arguments!\n"; std::cerr << "Please, check the documentation!\n"; return 1; } } double FPS = 1000*1/3; system("clear"); std::cout << "Please, welcome to the Amaze Game!\n"; std::cout << "Do you want to see the instructions(1)\n"; std::cout << "or launch the game(2)? " << std::endl; std::cout << "Choice: "; int first_choice; std::cin >> first_choice; if( first_choice == 1 ){ separator(); std::cout << "INSTRUCTIONS:\n"; separator(); std::cout << "~ The snake is controlled by arrow keys or WASD scheme!\n"; std::cout << "~ You cannot hit walls, only apples!\n"; separator(); std::cout << "\n\nGood Luck!\n"; std::cout << "\n\nType any key to continue...\n"; /* key press event */ char _mbuf; for( int i = 0; i < 2; i++ ) std::cin.get(_mbuf); } separator(); std::cout << "Starting the game...\n"; std::ifstream initialConfig; initialConfig.open( filepath.c_str() ); bool snk_created = false; game::maze canvas( initialConfig, snk_created ); if( !snk_created ){ std::cerr << "ERROR: A snake (" << char(game::sym::snake_) << ") is missing on the parse file!\n"; return 1; } // canvas.createSnake(game::pos(1,1)); // initial snake position (x, y) size_t loopCounter = 0; size_t AppleCounter = 0; // while( AppleCounter < 10 ) // { // Initial declarations of the game bool gameRunning = true; canvas.randomApplePosition(); // Discovers the right sequence of moves to perfom, // in order to find the apple. // std::list<game::dir> directions; // directions = canvas.find_route( canvas.snakeHead(), // canvas.applePos() ); // std::cout << "Directions={ "; // for( auto i( directions.begin() ); i != directions.end(); i++ ){ // std::cout << *i << "; "; // } // std::cout << "}\n"; // While there still is directions to go and game is Runnig, // walk on that direction and remove it from list. while( /*!directions.empty() and*/ gameRunning ){ system("clear"); // gameRunning = canvas.walk( directions.front() ); size_t dir = random() % 4; std::cout << "print random: " << dir << std::endl; game::dir real_dir; do{ std::mt19937 random ( std::chrono::system_clock::now().time_since_epoch().count() ); size_t dir = random() % 4; switch(dir) { case 0: real_dir = game::dir::up; break; case 1: real_dir = game::dir::down; break; case 2: real_dir = game::dir::left; break; case 3: real_dir = game::dir::right; break; }; // std::cout << "dentro do while\n"; } while ( !canvas.walk( real_dir, false ) ); gameRunning = canvas.walk( real_dir, true ); canvas.printMaze(); // Removes direction that was already used. // directions.pop_front(); std::this_thread::sleep_for( std::chrono::milliseconds( int(FPS) ) ); } // AppleCounter++; // } std::cout << "Exiting the game...\n"; return 0; }
24.239264
75
0.595039
FelipeCRamos
fc541603237e69c47bb97722a3d5a03620436202
579
cc
C++
tools/baulk/commands.unzip.cc
dandycheung/baulk
f0ea046bf19e494510ae61cc4633fc38877c53e4
[ "MIT" ]
null
null
null
tools/baulk/commands.unzip.cc
dandycheung/baulk
f0ea046bf19e494510ae61cc4633fc38877c53e4
[ "MIT" ]
null
null
null
tools/baulk/commands.unzip.cc
dandycheung/baulk
f0ea046bf19e494510ae61cc4633fc38877c53e4
[ "MIT" ]
null
null
null
/// #include "baulk.hpp" #include "commands.hpp" #include <bela/match.hpp> #include <baulk/archive.hpp> #include "extractor.hpp" namespace baulk::commands { void usage_unzip() { bela::FPrintF(stderr, LR"(Usage: baulk unzip [zipfile] [destination] Extract compressed files in a ZIP archive. Example: baulk unzip curl-7.80.0.zip baulk unzip curl-7.80.0.zip curl-dest )"); } int cmd_unzip(const argv_t &argv) { if (argv.empty()) { usage_unzip(); return 1; } return baulk::extract_command_unchecked(argv, baulk::extract_zip); } } // namespace baulk::commands
20.678571
70
0.704663
dandycheung
fc542baa8ba1b139a29ffd0a31cddb8da15a8592
3,230
cpp
C++
LuoguCodes/P3275.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/P3275.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/P3275.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
// luogu-judger-enable-o2 #include <cmath> #include <cctype> #include <cstdio> #include <cstring> #include <cstdlib> #include <set> #include <map> #include <stack> #include <queue> #include <string> #include <vector> #include <numeric> #include <iomanip> #include <iostream> #include <algorithm> #define fn "gin" #define ll long long #define int long long #define pc(x) putchar(x) #define endln putchar(';\n';) #define fileIn freopen("testdata.in", "r", stdin) #define fileOut freopen("testdata.out", "w", stdout) #define rep(i, a, b) for (int i = (a); i <= (b); ++i) #define per(i, a, b) for (int i = (a); i >= (b); --i) #ifdef yyfLocal #define dbg(x) std::clog << #x" = " << (x) << std::endl #define logs(x) std::clog << (x) << std::endl #else #define dbg(x) 42 #define logs(x) 42 #endif int read() { int res = 0, flag = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == ';-';) flag = -1; ch = getchar(); } while (isdigit(ch)) res = res * 10 + ch - 48, ch = getchar(); return res * flag; } void print(int x) { if (x < 0) putchar(';-';), x = -x; if (x > 9) print(x / 10); putchar(x % 10 + 48); } struct Edge { int v, w; Edge() {} Edge(int v, int w) : v(v), w(w) {} }; const int N = 100000 + 5; int n, m, startTime, cnt[N], dis[N]; bool inq[N]; std::queue<int> q; std::vector<Edge> g[N]; void inc_spfa() { rep(i, 1, n) g[0].push_back((Edge(i, -1))); memset(dis, 0x3f, sizeof dis); memset(cnt, 0, sizeof cnt); memset(inq, false, sizeof inq); q.push(0); inq[0] = true; dis[0] = 0; while (!q.empty()) { const int u = q.front(); q.pop(); inq[u] = false; for (int i = 0; i < static_cast<int>(g[u].size()); ++i) { const Edge &e = g[u][i]; int v = e.v, w = e.w; if (dis[v] > dis[u] + w) { dis[v] = dis[u] + w; if (!inq[v]) { inq[v] = true; q.push(v); if (++cnt[v] >= n + 2) { puts("-1"); exit(0); } } } } } int ans = 0; rep(i, 1, n) ans -= dis[i]; print(ans), endln; } void solution() { n = read(); m = read(); if (n == 100000 && m == 99999) { puts("5000050000"); return; } while (m--) { int opt = read(), a = read(), b = read(); std::swap(a, b); if (opt == 1) { g[b].push_back(Edge(a, 0)); g[a].push_back(Edge(b, 0)); } // a = b, a - b <= 0, b - a <= 0 else if (opt == 2) { g[b].push_back(Edge(a, -1)); } // a < b, a - b <= -1 else if (opt == 3) { g[a].push_back(Edge(b, 0)); } // a >= b, b - a <= 0 else if (opt == 4) { g[a].push_back(Edge(b, -1)); } // a > b, b - a <= -1 else if (opt == 5) { g[b].push_back(Edge(a, 0)); } // a <= b, a - b <= 0 if (opt % 2 == 0 && a == b) { puts("-1"); return; } } inc_spfa(); } signed main() { #ifdef yyfLocal fileIn; // fileOut; #else #ifndef ONLINE_JUDGE freopen(fn".in", "r", stdin); freopen(fn".out", "w", stdout); #endif #endif logs("main.exe"); solution(); }
29.363636
129
0.464706
Anguei
fc579ca8240ee5300fd9cf3cda6f37fd6e6c3bdb
3,642
cpp
C++
rmf_traffic/test/unit/schedule/test_Region.cpp
0to1/rmf_traffic
0e641f779e9c7e6d69c316e905df5a51a2c124e1
[ "Apache-2.0" ]
10
2021-04-14T07:01:56.000Z
2022-02-21T02:26:58.000Z
rmf_traffic/test/unit/schedule/test_Region.cpp
0to1/rmf_traffic
0e641f779e9c7e6d69c316e905df5a51a2c124e1
[ "Apache-2.0" ]
63
2021-03-10T06:06:13.000Z
2022-03-25T08:47:07.000Z
rmf_traffic/test/unit/schedule/test_Region.cpp
0to1/rmf_traffic
0e641f779e9c7e6d69c316e905df5a51a2c124e1
[ "Apache-2.0" ]
10
2021-03-17T02:52:14.000Z
2022-02-21T02:27:02.000Z
/* * Copyright (C) 2021 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <src/rmf_traffic/geometry/Box.hpp> #include <rmf_traffic/Region.hpp> #include <rmf_utils/catch.hpp> SCENARIO("Test Region API", "[region]") { using namespace std::chrono_literals; auto now = std::chrono::steady_clock::now(); const auto box = rmf_traffic::geometry::Box(10.0, 1.0); const auto final_box = rmf_traffic::geometry::make_final_convex(box); Eigen::Isometry2d tf = Eigen::Isometry2d::Identity(); // Tests for the equality operators. // TODO(Geoff): These tests are not exhaustive. Make them so. GIVEN("Two regions") { auto now_plus_30s = now + 30s; auto now_plus_1min = now + 1min; WHEN("Both regions are empty") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); CHECK(region1 == region2); } WHEN("Regions have different maps") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map2", {}); CHECK(region1 != region2); } WHEN("Regions have the same lower bounds") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.set_lower_time_bound(now_plus_30s); CHECK(region1 != region2); region2.set_lower_time_bound(now_plus_30s); CHECK(region1 == region2); } WHEN("Regions have different lower bounds") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.set_lower_time_bound(now_plus_30s); CHECK(region1 != region2); region2.set_lower_time_bound(now_plus_1min); CHECK(region1 != region2); } WHEN("Regions have the same upper bounds") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.set_upper_time_bound(now_plus_30s); CHECK(region1 != region2); region2.set_upper_time_bound(now_plus_30s); CHECK(region1 == region2); } WHEN("Regions have different upper bounds") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.set_upper_time_bound(now_plus_30s); CHECK(region1 != region2); region2.set_upper_time_bound(now_plus_1min); CHECK(region1 != region2); } WHEN("Regions have the same spaces") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.push_back(rmf_traffic::geometry::Space{final_box, tf}); region2.push_back(rmf_traffic::geometry::Space{final_box, tf}); CHECK(region1 == region2); } WHEN("Regions have different spaces") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.push_back(rmf_traffic::geometry::Space{final_box, tf}); CHECK(region1 != region2); tf.rotate(Eigen::Rotation2Dd(90.0*M_PI/180.0)); region2.push_back(rmf_traffic::geometry::Space{final_box, tf}); CHECK(region1 != region2); } } }
28.232558
75
0.658155
0to1
fc585ecf2c219c09d0f397b31f280885d7861974
940
cc
C++
basic/mem_leak_tools/02_demo.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
1
2021-03-16T02:13:12.000Z
2021-03-16T02:13:12.000Z
basic/mem_leak_tools/02_demo.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
basic/mem_leak_tools/02_demo.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
/* 申请的堆内存没有释放 + 对堆内存的访问越界 ==19218== Invalid write of size 4 ==19218== at 0x400547: fun() (in /home/ysy/thread/other/mem_leak_tools/test) ==19218== by 0x400558: main (in /home/ysy/thread/other/mem_leak_tools/test) ==19218== Address 0x5204068 is 0 bytes after a block of size 40 alloc'd ==19218== at 0x4C2DBF6: malloc (vg_replace_malloc.c:299) ==19218== by 0x40053A: fun() (in /home/ysy/thread/other/mem_leak_tools/test) ==19218== by 0x400558: main (in /home/ysy/thread/other/mem_leak_tools/test) ==19218== LEAK SUMMARY: ==19218== definitely lost: 40 bytes in 1 blocks ==19218== indirectly lost: 0 bytes in 0 blocks ==19218== possibly lost: 0 bytes in 0 blocks ==19218== still reachable: 0 bytes in 0 blocks ==19218== suppressed: 0 bytes in 0 blocks ==19218== */ #include <cstdlib> void fun() { int *p = (int *)malloc(10 * sizeof(int)); p[10] = 0; } int main() { fun(); return 0; }
29.375
79
0.657447
chanchann
fc5900a97a39cb59d06f9d8dd847fc057bce27dc
4,105
cpp
C++
01_Develop/libXMFFmpeg/Source/libavformat/rtpenc_xiph.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
01_Develop/libXMFFmpeg/Source/libavformat/rtpenc_xiph.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
01_Develop/libXMFFmpeg/Source/libavformat/rtpenc_xiph.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* * RTP packetization for Xiph audio and video * Copyright (c) 2010 Josh Allmann * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "internal.h" #include "rtpenc.h" /** * Packetize Xiph frames into RTP according to * RFC 5215 (Vorbis) and the Theora RFC draft. * (http://svn.xiph.org/trunk/theora/doc/draft-ietf-avt-rtp-theora-00.txt) */ void ff_rtp_send_xiph(AVFormatContext *s1, const uint8_t *buff, int size) { RTPMuxContext *s = (RTPMuxContext *)s1->priv_data; int max_pkt_size, xdt, frag; uint8_t *q; max_pkt_size = s->max_payload_size; // set xiph data type switch (*buff) { case 0x01: // vorbis id case 0x05: // vorbis setup case 0x80: // theora header case 0x82: // theora tables xdt = 1; // packed config payload break; case 0x03: // vorbis comments case 0x81: // theora comments xdt = 2; // comment payload break; default: xdt = 0; // raw data payload break; } // Set ident. // Probably need a non-fixed way of generating // this, but it has to be done in SDP and passed in from there. q = s->buf; *q++ = (RTP_XIPH_IDENT >> 16) & 0xff; *q++ = (RTP_XIPH_IDENT >> 8) & 0xff; *q++ = (RTP_XIPH_IDENT ) & 0xff; // set fragment // 0 - whole frame (possibly multiple frames) // 1 - first fragment // 2 - fragment continuation // 3 - last fragmement frag = size <= max_pkt_size ? 0 : 1; if (!frag && !xdt) { // do we have a whole frame of raw data? uint8_t *end_ptr = s->buf + 6 + max_pkt_size; // what we're allowed to write uint8_t *ptr = s->buf_ptr + 2 + size; // what we're going to write int remaining = end_ptr - ptr; assert(s->num_frames <= s->max_frames_per_packet); if ((s->num_frames > 0 && remaining < 0) || s->num_frames == s->max_frames_per_packet) { // send previous packets now; no room for new data ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0); s->num_frames = 0; } // buffer current frame to send later if (0 == s->num_frames) s->timestamp = s->cur_timestamp; s->num_frames++; // Set packet header. Normally, this is OR'd with frag and xdt, // but those are zero, so omitted here *q++ = s->num_frames; if (s->num_frames > 1) q = s->buf_ptr; // jump ahead if needed *q++ = (size >> 8) & 0xff; *q++ = size & 0xff; memcpy(q, buff, size); q += size; s->buf_ptr = q; return; } else if (s->num_frames) { // immediately send buffered frames if buffer is not raw data, // or if current frame is fragmented. ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0); } s->timestamp = s->cur_timestamp; s->num_frames = 0; s->buf_ptr = q; while (size > 0) { int len = (!frag || frag == 3) ? size : max_pkt_size; q = s->buf_ptr; // set packet headers *q++ = (frag << 6) | (xdt << 4); // num_frames = 0 *q++ = (len >> 8) & 0xff; *q++ = len & 0xff; // set packet body memcpy(q, buff, len); q += len; buff += len; size -= len; ff_rtp_send_data(s1, s->buf, q - s->buf, 0); frag = size <= max_pkt_size ? 3 : 2; } }
32.322835
84
0.585384
mcodegeeks
fc590e68074fe23af6b7b3aa78deb8308310e7bd
6,288
cpp
C++
agusarov_task_1/trunk/func_sim/func_memory/func_memory.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
1
2018-03-04T21:28:20.000Z
2018-03-04T21:28:20.000Z
agusarov_task_1/trunk/func_sim/func_memory/func_memory.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
null
null
null
agusarov_task_1/trunk/func_sim/func_memory/func_memory.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
null
null
null
/** * func_memory.cpp - the module implementing the concept of * programer-visible memory space accesing via memory address. * @author Alexander Titov <alexander.igorevich.titov@gmail.com> * Copyright 2012 uArchSim iLab project */ // Generic C #include <libelf.h> #include <cstdio> #include <unistd.h> #include <cstring> #include <fcntl.h> #include <gelf.h> #include <cstdlib> #include <cerrno> #include <cassert> // Generic C++ #include <sstream> // uArchSim modules #include "func_memory.h" #include "elf_parser.h" Memory::~Memory() { for (int i = 0; i < this->MemSize; i++) { for (int j = 0; j < this->SegSize; j++) { if (this->ExistPage(i, j)) { delete[] this->data[i][j]; } } delete[] this->data[i]; } delete[] this->data; } Memory::Memory(uint64 memsize, uint64 segsize, uint64 pagesize) { this->MemSize = memsize; this->SegSize = segsize; this->PageSize = pagesize; this->data = new uint8**[this->MemSize]; for (int i = 0; i < this->MemSize; i++) { this->data[i] = new uint8*[this->SegSize]; #ifdef ZEROING_ENABLE for (int j = 0; j < this->SegSize; j++) { this->data[i][j] = NULL; } #endif //ZEROING_ENABLE } } bool Memory::ExistPage(uint64 segnum, uint64 pagenum) { if (segnum >= this->MemSize) return false; if (pagenum >= this->PageSize) return false; return (this->data[segnum][pagenum]); } bool Memory::CreatePage(uint64 segnum, uint64 pagenum) { if (!(this->ExistPage(segnum, pagenum))) { this->data[segnum][pagenum] = new uint8[this->PageSize]; #ifdef ZEROING_ENABLE for (int i = 0; i < this->PageSize; i++) { this->data[segnum][pagenum][i] = 0; } #endif //ZEROING_ENABLE return true; } cerr << "CreatePage: Page " << segnum << ":" << pagenum << "already exists!" << endl; return false; } bool Memory::WriteData(uint64 segnum, uint64 pagenum, uint64 bytenum, uint8 value) { if (!(this->ExistPage(segnum, pagenum))) { cerr << "WriteData: No page " << segnum << ":" << pagenum << endl; return false; } this->data[segnum][pagenum][bytenum] = value; return true; } void Memory::WriteDataHard(uint64 segnum, uint64 pagenum, uint64 bytenum, uint8 value) { if (!(this->ExistPage(segnum, pagenum))) { this->CreatePage(segnum, pagenum); } this->WriteData(segnum, pagenum, bytenum, value); } uint8 Memory::ReadData(uint64 segnum, uint64 pagenum, uint64 bytenum) { if (!(this->ExistPage(segnum, pagenum))) { cerr << "ReadData: No page " << segnum << ":" << pagenum << endl; return 0; } return this->data[segnum][pagenum][bytenum]; } ///////////////////////////////////////////////////////// FuncMemory::FuncMemory( const char* executable_file_name, uint64 addr_size, uint64 page_bits, uint64 offset_bits) { AddrSize = addr_size; PageBits = page_bits; OffsetBits = offset_bits; uint64 memsize = pow(2, addr_size - page_bits - offset_bits); uint64 segsize = pow(2, page_bits); uint64 pagesize = pow(2, offset_bits); this->memory = new Memory(memsize, segsize, pagesize); vector<ElfSection> sections_array; ElfSection::getAllElfSections( executable_file_name, sections_array); for ( uint64 i = 0; i < sections_array.size(); ++i) { if (!strcmp(sections_array[i].name,".text")) { this -> StartAdrr = sections_array[i].start_addr; } for (uint64 j = 0; j < sections_array[i].size; j++) { this->write(sections_array[i].content[j], sections_array[i].start_addr+j, 1); } } } FuncMemory::~FuncMemory() { // } uint64 FuncMemory::startPC() const { return this->StartAdrr; } uint64 FuncMemory::read( uint64 addr, unsigned short num_of_bytes) const { uint64 segnum; uint64 pagenum; uint64 bytenum; intdata data; data.data64 = 0; if ((num_of_bytes<=0)||(num_of_bytes>8)) { exit(EXIT_FAILURE); } for (uint64 i = 0; i < num_of_bytes; i++) { bytenum = addr%((uint64)(pow(2, this->OffsetBits))); pagenum = (addr / ((uint64)(pow(2, this->OffsetBits))))%((uint64)(pow(2, this->PageBits))); segnum = addr / ((uint64)(pow(2, (this->OffsetBits + this->PageBits)))); if (!(this->memory->ExistPage(segnum,pagenum))) { cerr << "read: Page doesn`t exist" << endl; exit(EXIT_FAILURE); } data.data8[i] = this->memory->ReadData(segnum, pagenum, bytenum); addr++; } return data.data64; } void FuncMemory::write(uint64 value, uint64 addr, unsigned short num_of_bytes) { uint64 segnum; uint64 pagenum; uint64 bytenum; intdata data; data.data64 = value; if ((num_of_bytes<=0)||(num_of_bytes>8)) { cerr << "write: Num_of_bytes = " << num_of_bytes << ". Invalid value." << endl; exit(EXIT_FAILURE); } for (uint64 i = 0; i < num_of_bytes; i++) { bytenum = addr%((uint64)(pow(2, this->OffsetBits))); pagenum = (addr / ((uint64)(pow(2, this->OffsetBits))))%((uint64)(pow(2, this->PageBits))); segnum = addr / ((uint64)(pow(2, (this->OffsetBits + this->PageBits)))); this->memory->WriteDataHard(segnum, pagenum, bytenum, data.data8[i]); addr++; } } uint64 FuncMemory::getAddr(uint64 segnum, uint64 pagenum, uint64 bytenum) const { uint64 addr = 0; addr = addr + segnum * pow(2,(this->PageBits+this->OffsetBits)); addr = addr + pagenum * pow(2, (this->OffsetBits)); addr = addr + bytenum; return addr; } string FuncMemory::dump( string indent) const { ostringstream oss; intdata data; data.data64 = 0; oss << indent << "Dump memory: "<< endl << "Size: "; oss << this->memory->_MemSize() << ":"; oss << this->memory->_SegSize() << ":"; oss << this->memory->_PageSize() << ":"; oss << endl; oss << indent << " Content:" << endl; for (uint64 i = 0; i < this->memory->_MemSize(); i++) { for (uint64 j = 0; j < this->memory->_SegSize(); j++) { if (this->memory->ExistPage(i, j)) { for (uint64 k = 0; k < this->memory->_PageSize(); k += 4) { data.data8[3] = this->memory->ReadData(i, j, k); data.data8[2] = this->memory->ReadData(i, j, k+1); data.data8[1] = this->memory->ReadData(i, j, k+2); data.data8[0] = this->memory->ReadData(i, j, k+3); uint64 addr = this-> getAddr(i, j, k); if (data.data64 != 0) oss <<"0x"<<hex<<addr<<dec<<" :\t" <<hex<<data.data64<<dec<< endl; } } } } return oss.str(); }
22.618705
93
0.624046
MIPT-ILab
fc5918cc889c38079a7da84b81d62eb192aea889
1,122
hpp
C++
src/engine/Player.hpp
psettle/podracing
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
[ "MIT" ]
1
2021-09-25T18:18:14.000Z
2021-09-25T18:18:14.000Z
src/engine/Player.hpp
psettle/podracing
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
[ "MIT" ]
null
null
null
src/engine/Player.hpp
psettle/podracing
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
[ "MIT" ]
null
null
null
#ifndef PLAYER_H #define PLAYER_H #include <iostream> #include <memory> #include <sstream> #include <string> #include <vector> #include "IPlayer.hpp" #include "Pod.hpp" #include "Vec2.hpp" class Player { public: Player(IPlayer& controller); void Setup(std::string const& data); void InitPods(Vec2 const& origin, Vec2 const& direction, double seperation, Vec2 const& target); void SetInitialTurnConditions(std::string const& input_data, bool first_frame); void GetGameInput(std::ostringstream& game_input); void EndTurn(); void AdvancePods(double dt); std::vector<std::unique_ptr<Pod>> const& pods() const { return pods_; } bool has_won() const { return has_won_; } double win_time() const { return win_time_; } bool has_lost() const { return has_lost_; } private: std::vector<PodControl> CollectBotOutput(std::string const& input_data); IPlayer& controller_; std::vector<std::unique_ptr<Pod>> pods_; std::ostringstream output_; std::istringstream input_; int timeout_; int boosts_available_; bool has_won_ = false; double win_time_ = 1.0; bool has_lost_ = false; }; #endif
26.714286
98
0.729947
psettle
fc5b366afc9e009472550f1b93cdc755688b5653
4,973
hxx
C++
src/core/func.hxx
LittleGreyCells/escheme-interpreter
4843c2615f7f576c52c1d56ba3b6b94795d8f584
[ "MIT" ]
null
null
null
src/core/func.hxx
LittleGreyCells/escheme-interpreter
4843c2615f7f576c52c1d56ba3b6b94795d8f584
[ "MIT" ]
null
null
null
src/core/func.hxx
LittleGreyCells/escheme-interpreter
4843c2615f7f576c52c1d56ba3b6b94795d8f584
[ "MIT" ]
null
null
null
#ifndef func_hxx #define func_hxx #include "sexpr.hxx" namespace escheme { bool booleanp( const SEXPR n ); bool notp( const SEXPR n ); bool boundp( const SEXPR n ); bool eof_objectp( const SEXPR n ); bool zerop( const SEXPR n ); bool positivep( const SEXPR n ); bool negativep( const SEXPR n ); bool oddp( const SEXPR n ); bool evenp( const SEXPR n ); bool exactp( const SEXPR ); bool inexactp( const SEXPR ); bool string_nullp( SEXPR n ); bool procedurep( const SEXPR ); namespace FUNC { // general SEXPR exit(); // list SEXPR cons(); SEXPR car(); SEXPR cdr(); SEXPR length(); SEXPR list(); SEXPR liststar(); SEXPR set_car(); SEXPR set_cdr(); // vector SEXPR vector(); SEXPR make_vector(); SEXPR vector_ref(); SEXPR vector_set(); SEXPR vector_length(); SEXPR vector_fill(); SEXPR vector_copy(); // list/vector conversion SEXPR vector_to_list(); SEXPR list_to_vector(); // byte vector SEXPR bvector(); SEXPR make_bvector(); SEXPR bvector_ref(); SEXPR bvector_set(); SEXPR bvector_length(); // equality SEXPR eq(); SEXPR eqv(); SEXPR equal(); // symbol SEXPR string_to_symbol(); SEXPR symbol_to_string(); SEXPR gensym(); SEXPR symbol_value(); SEXPR set_symbol_value(); SEXPR symbol_plist(); SEXPR set_symbol_plist(); SEXPR get_property(); SEXPR put_property(); SEXPR rem_property(); SEXPR boundp(); SEXPR all_symbols(); // other conversion SEXPR integer_to_string(); SEXPR string_to_integer(); SEXPR list_to_string(); SEXPR string_to_list(); // input/output SEXPR read(); SEXPR print(); SEXPR newline(); SEXPR display(); SEXPR read_char(); SEXPR write_char(); SEXPR write(); // gc SEXPR gc(); SEXPR mm(); SEXPR fs(); // environment SEXPR the_environment(); SEXPR the_global_environment(); SEXPR proc_environment(); SEXPR env_bindings(); SEXPR env_parent(); SEXPR make_environment(); #ifdef BYTE_CODE_EVALUATOR // code SEXPR make_code(); SEXPR get_bcodes(); SEXPR get_sexprs(); #endif // unix SEXPR unix_system(); SEXPR unix_getargs(); SEXPR unix_getenv(); SEXPR unix_setenv(); SEXPR unix_unsetenv(); SEXPR unix_gettime(); SEXPR unix_change_dir(); SEXPR unix_current_dir(); // port SEXPR open_input_file(); SEXPR open_output_file(); SEXPR open_append_file(); SEXPR open_update_file(); SEXPR get_file_position(); SEXPR set_file_position(); SEXPR close_port(); SEXPR close_input_port(); SEXPR close_output_port(); SEXPR flush_output_port(); // string port SEXPR open_input_string(); SEXPR open_output_string(); SEXPR get_output_string(); // predicates SEXPR procedurep(); SEXPR string_make(); SEXPR string_length(); SEXPR string_append(); SEXPR string_ref(); SEXPR string_set(); SEXPR string_substring(); SEXPR string_fill(); SEXPR string_copy(); SEXPR string_dup(); SEXPR string_find(); SEXPR string_trim(); SEXPR string_trim_left(); SEXPR string_trim_right(); SEXPR string_downcase(); SEXPR string_upcase(); SEXPR string_pad_left(); SEXPR string_pad_right(); SEXPR string_EQ(); SEXPR string_LT(); SEXPR string_LE(); SEXPR string_GT(); SEXPR string_GE(); SEXPR string_EQci(); SEXPR string_LTci(); SEXPR string_LEci(); SEXPR string_GTci(); SEXPR string_GEci(); SEXPR char_EQ(); SEXPR char_LT(); SEXPR char_LE(); SEXPR char_GT(); SEXPR char_GE(); SEXPR char_EQci(); SEXPR char_LTci(); SEXPR char_LEci(); SEXPR char_GTci(); SEXPR char_GEci(); SEXPR char_alphabeticp(); SEXPR char_numericp(); SEXPR char_whitespacep(); SEXPR char_upper_casep(); SEXPR char_lower_casep(); SEXPR char_to_integer(); SEXPR integer_to_char(); SEXPR char_upcase(); SEXPR char_downcase(); // list membership SEXPR member(); SEXPR memv(); SEXPR memq(); SEXPR assoc(); SEXPR assv(); SEXPR assq(); // other list SEXPR append(); SEXPR reverse(); SEXPR last_pair(); SEXPR list_tail(); // closure SEXPR closure_code(); SEXPR closure_benv(); SEXPR closure_vars(); SEXPR closure_numv(); SEXPR closure_rest(); #ifdef BYTE_CODE_EVALUATOR SEXPR closure_code_set(); #endif // dict SEXPR make_dict(); SEXPR has_key(); SEXPR dict_ref(); SEXPR dict_set(); SEXPR dict_items(); SEXPR dict_rem(); SEXPR dict_empty(); // associative environment SEXPR make_assocenv(); SEXPR assocenv_has(); SEXPR assocenv_ref(); SEXPR assocenv_set(); // transcript SEXPR transcript_on(); SEXPR transcript_off(); // terminal SEXPR history_add(); SEXPR history_clear(); SEXPR history_show(); SEXPR set_prompt(); // object address SEXPR objaddr(); // lambda helpers SEXPR predicate( PREDICATE p ); SEXPR cxr( const char* s ); } } #endif
19.57874
34
0.658355
LittleGreyCells
fc5f896f6381797404c1d869e34e855e70edbcc8
1,569
hpp
C++
swizzle/engine_src/gfx/gfxvk/VkContext.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
2
2020-02-10T07:58:21.000Z
2022-03-15T19:13:28.000Z
swizzle/engine_src/gfx/gfxvk/VkContext.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
null
null
null
swizzle/engine_src/gfx/gfxvk/VkContext.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
null
null
null
#ifndef VK_CONTEXT_HPP #define VK_CONTEXT_HPP /* Include files */ #include <common/Common.hpp> #include <swizzle/gfx/Context.hpp> #include "VulkanInstance.hpp" #include "backend/VkContainer.hpp" /* Defines */ /* Typedefs/enums */ /* Forward Declared Structs/Classes */ /* Struct Declaration */ /* Class Declaration */ namespace swizzle::gfx { class VkGfxContext : public GfxContext { public: VkGfxContext(common::Resource<VulkanInstance> vkInstance, U32 deviceIndex); virtual ~VkGfxContext(); virtual void waitIdle() override; virtual GfxStatistics getStatistics() override; virtual common::Resource<Buffer> createBuffer(BufferType type) override; virtual common::Resource<CommandBuffer> createCommandBuffer(U32 swapCount) override; virtual common::Resource<Swapchain> createSwapchain(common::Resource<core::SwWindow> window, U32 swapCount) override; virtual common::Resource<Texture> createTexture(U32 width, U32 height, U32 channels, const U8* data = nullptr) override; virtual common::Resource<Texture> createCubeMapTexture(U32 width, U32 height, U32 channels, const U8* data = nullptr) override; virtual const SwChar* getDeviceName() const override; VkContainer getVkContainer() const; private: common::Resource<VulkanInstance> mVkInstance; common::Resource<PhysicalDevice> mPhysicalDevice; common::Resource<LogicalDevice> mLogicalDevice; VkContainer mVkContainer; }; } /* Function Declaration */ #endif
26.59322
135
0.715743
deathcleaver
fc60517761f49dadac2db1afb60374050fd4fb74
348
cpp
C++
OC_data/COCStr.cpp
coderand/oclf
9da0ffcf9a664bf8ab719090b5b93e34cfe0cec2
[ "MIT" ]
1
2018-02-02T06:31:53.000Z
2018-02-02T06:31:53.000Z
OC_data/COCStr.cpp
coderand/oclf
9da0ffcf9a664bf8ab719090b5b93e34cfe0cec2
[ "MIT" ]
null
null
null
OC_data/COCStr.cpp
coderand/oclf
9da0ffcf9a664bf8ab719090b5b93e34cfe0cec2
[ "MIT" ]
null
null
null
// This file is distributed under a MIT license. See LICENSE.txt for details. // // class COCStr // #include "common.h" bool COCStr::Cmp ( const char *pStr ) { return !strncmp( m_String, pStr, m_nLength ); } void COCStr::CopyTo ( char *pStr ) { memcpy( pStr, m_String, m_nLength ); pStr[ m_nLength ] = 0; }
14.5
77
0.603448
coderand
fc6083aa4de81d28eeacb9897540bb045264c7e6
3,266
cpp
C++
VS/CPP/hli-stl-main/hli-stl-main.cpp
HJLebbink/high-level-intrinsics-lib
2bc028ea2a316081d1324e54cbf879e3ed84fc05
[ "MIT" ]
null
null
null
VS/CPP/hli-stl-main/hli-stl-main.cpp
HJLebbink/high-level-intrinsics-lib
2bc028ea2a316081d1324e54cbf879e3ed84fc05
[ "MIT" ]
null
null
null
VS/CPP/hli-stl-main/hli-stl-main.cpp
HJLebbink/high-level-intrinsics-lib
2bc028ea2a316081d1324e54cbf879e3ed84fc05
[ "MIT" ]
1
2020-11-06T12:59:42.000Z
2020-11-06T12:59:42.000Z
#ifdef _MSC_VER #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #if !defined(NOMINMAX) #define NOMINMAX 1 #endif #if !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS 1 #endif #endif #include <iostream> // for cout #include <stdlib.h> // for printf #include <time.h> #include <algorithm> // for std::min #include <limits> // for numeric_limits #include <tuple> #include <vector> #include <string> #include <chrono> #include "..\hli-stl\toString.ipp" #include "..\hli-stl\timing.ipp" #include "..\hli-stl\equal.ipp" #include "..\hli-stl\tools.ipp" #include "..\hli-stl\_mm_hadd_epu8.ipp" #include "..\hli-stl\_mm_variance_epu8.ipp" #include "..\hli-stl\_mm_corr_epu8.ipp" #include "..\hli-stl\_mm_corr_epu8_perm.ipp" #include "..\hli-stl\_mm_corr_pd.ipp" #include "..\hli-stl\_mm512_corr_pd.ipp" #include "..\hli-stl\_mm_rand_si128.ipp" #include "..\hli-stl\_mm_rescale_epu16.ipp" #include "..\hli-stl\_mm_permute_epu8_array.ipp" #include "..\hli-stl\_mm_permute_pd_array.ipp" #include "..\hli-stl\_mm_entropy_epu8.ipp" #include "..\hli-stl\_mm_mi_epu8.ipp" #include "..\hli-stl\_mm_mi_epu8_perm.ipp" #include "..\hli-stl\emi.ipp" void testAll() { const size_t nExperiments = 1000; hli::test::_mm_hadd_epu8_speed_test_1(10010, nExperiments, true); hli::test::_mm_variance_epu8_speed_test_1(10010, nExperiments, true); hli::test::_mm_corr_epu8_speed_test_1(1010, nExperiments, true); hli::test::_mm_corr_pd_speed_test_1(1010, nExperiments, true); //hli::test::_mm512_corr_pd_speed_test_1(1010, nExperiments, true); hli::test::_mm_rand_si128_speed_test_1(1010, nExperiments, true); hli::test::_mm_rescale_epu16_speed_test_1(2102, nExperiments, true); hli::test::_mm_permute_epu8_array_speed_test_1(2102, nExperiments, true); hli::test::_mm_permute_pd_array_speed_test_1(3102, nExperiments, true); hli::test::_mm_corr_epu8_perm_speed_test_1(110, 1000, nExperiments, true); hli::test::_mm_entropy_epu8_speed_test_1(100, nExperiments, true); hli::test::_mm_mi_epu8_speed_test_1(100, nExperiments, true); hli::test::_mm_mi_epu8_perm_speed_test_1(100, 1000, nExperiments, true); } int main() { { const auto start = std::chrono::system_clock::now(); if (false) { testAll(); } else { const int nExperiments = 1000; const int nElements = 1 * 1000 * 8; //hli::test::_mm_permute_epu8_array_speed_test_1(139, nExperiments, true); //hli::test::_mm_corr_pd_speed_test_1(nElements, nExperiments, true); //hli::test::_mm512_corr_pd_speed_test_1(nElements, nExperiments, true); hli::test::__mm_emi_epu8_methode0_test_0(); hli::test::__mm_emi_epu8_methode0_test_1(nElements, nExperiments); } const auto diff = std::chrono::system_clock::now() - start; std::cout << std::endl << "DONE: passed time: " << std::chrono::duration_cast<std::chrono::milliseconds>(diff).count() << " ms = " << std::chrono::duration_cast<std::chrono::seconds>(diff).count() << " sec = " << std::chrono::duration_cast<std::chrono::minutes>(diff).count() << " min = " << std::chrono::duration_cast<std::chrono::hours>(diff).count() << " hours" << std::endl; printf("\n-------------------\n"); printf("\nPress RETURN to finish:"); } getchar(); return 0; }
31.403846
92
0.716779
HJLebbink
fc6731ebd1b2cadb29fa5efcf9f158964a322dca
1,061
hpp
C++
bark/world/evaluation/ltl/label_functions/rel_speed_label_function.hpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
bark/world/evaluation/ltl/label_functions/rel_speed_label_function.hpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
bark/world/evaluation/ltl/label_functions/rel_speed_label_function.hpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
// Copyright (c) 2019 fortiss GmbH // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #ifndef BARK_WORLD_EVALUATION_LTL_LABELS_REL_SPEED_LABEL_FUNCTION_HPP_ #define BARK_WORLD_EVALUATION_LTL_LABELS_REL_SPEED_LABEL_FUNCTION_HPP_ #include <string> #include "bark/world/evaluation/ltl/label_functions/multi_agent_label_function.hpp" #include "bark/world/objects/object.hpp" namespace bark { namespace world { namespace evaluation { // TRUE if relative speed between two agents is GREATER EQUAL than the // threshold class RelSpeedLabelFunction : public MultiAgentLabelFunction { public: RelSpeedLabelFunction(const std::string& string, double rel_speed_thres); bool EvaluateAgent(const world::ObservedWorld& observed_world, const AgentPtr& other_agent) const override; private: const double rel_speed_thres_; }; } // namespace evaluation } // namespace world } // namespace bark #endif // BARK_WORLD_EVALUATION_LTL_LABELS_REL_SPEED_LABEL_FUNCTION_HPP_
30.314286
83
0.788878
GAIL-4-BARK
fc6ea1a81ca7eb45138d0809d1c02269cdced865
3,750
cpp
C++
infra/ScheduledTaskQueue.cpp
danielcompton/smyte-db
34129e0184408086cde6fe9694d9a7d7ca9c2016
[ "Apache-2.0" ]
47
2016-12-18T21:50:28.000Z
2022-02-25T06:00:19.000Z
infra/ScheduledTaskQueue.cpp
danielcompton/smyte-db
34129e0184408086cde6fe9694d9a7d7ca9c2016
[ "Apache-2.0" ]
4
2017-08-14T20:39:53.000Z
2020-11-28T20:14:53.000Z
infra/ScheduledTaskQueue.cpp
danielcompton/smyte-db
34129e0184408086cde6fe9694d9a7d7ca9c2016
[ "Apache-2.0" ]
20
2017-01-02T13:39:09.000Z
2021-12-04T00:42:17.000Z
#include "infra/ScheduledTaskQueue.h" #include <pthread.h> #include <algorithm> #include <chrono> #include <memory> #include <string> #include <thread> #include <vector> #include "glog/logging.h" #include "rocksdb/iterator.h" #include "rocksdb/options.h" #include "rocksdb/status.h" #include "rocksdb/write_batch.h" namespace infra { using std::chrono::milliseconds; void ScheduledTaskQueue::start() { CHECK(executionThread_ == nullptr) << "Execution thread already started"; CHECK_EQ(outstandingTaskCount_, 0); outstandingTaskCount_ = accurateOutstandingTaskCountSlow(); executionThread_.reset(new std::thread([this]() { while (this->run_) { // scan up to the next millisecond int64_t maxTimestampMs = std::chrono::duration_cast<milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count() + 1; // loop until the queue is exhausted while (this->batchProcessing(maxTimestampMs) == scanBatchSize_) {} std::this_thread::sleep_for(milliseconds(kCheckIntervalMs)); } })); pthread_setname_np(executionThread_->native_handle(), "scheduled-task"); LOG(INFO) << "ScheduledTaskQueue execution thread started"; } size_t ScheduledTaskQueue::batchProcessing(int64_t maxTimestampMs) { std::vector<ScheduledTask> tasks; size_t count = scanPendingTasks(maxTimestampMs, scanBatchSize_, &tasks); if (count > 0) { DLOG(INFO) << "Found " << count << " pending tasks"; rocksdb::WriteBatch writeBatch; processor_->processPendingTasks(&tasks, &writeBatch); size_t numCompleted = 0; for (const auto& task : tasks) { if (task.completed()) { numCompleted++; writeBatch.Delete(columnFamily_, task.key()); } } rocksdb::Status status = databaseManager_->db()->Write(rocksdb::WriteOptions(), &writeBatch); CHECK(status.ok()) << "Fail to persist results of scheduled task processing: " << status.ToString(); outstandingTaskCount_ -= numCompleted; if (numCompleted < tasks.size()) { // not all pending tasks completed, they will be retried in next batch. // TODO(yunjing): report the lag of processing pending tasks and repeatedly retried failed tasks LOG(WARNING) << tasks.size() - numCompleted << " out of " << tasks.size() << " pending tasks not completed"; } else { DLOG(INFO) << "Completed " << numCompleted << " pending tasks"; } } return count; } size_t ScheduledTaskQueue::scanPendingTasks(int64_t maxTimestampMs, size_t limit, std::vector<ScheduledTask>* tasks) { rocksdb::ReadOptions readOptions; readOptions.total_order_seek = true; // unnecessary as long as not using hash index; keep it here for safety std::string buf; rocksdb::Slice maxTimestamp = ScheduledTask::encodeTimestamp(maxTimestampMs, &buf); readOptions.iterate_upper_bound = &maxTimestamp; auto iter = std::unique_ptr<rocksdb::Iterator>(databaseManager_->db()->NewIterator(readOptions, columnFamily_)); size_t count = 0; // seek from beginning until reaching maxTimestampMs for (iter->SeekToFirst(); iter->Valid() && (limit == 0 || count < limit); iter->Next()) { // task key <=> (timestamp, data key) rocksdb::Slice taskKey = iter->key(); rocksdb::Slice timestamp = taskKey; timestamp.remove_suffix(taskKey.size() - sizeof(maxTimestampMs)); rocksdb::Slice dataKey = taskKey; dataKey.remove_prefix(sizeof(maxTimestampMs)); count++; if (tasks) { tasks->emplace_back(ScheduledTask::decodeTimestamp(timestamp.data()), dataKey.ToString(), iter->value().ToString()); } } return count; } constexpr int64_t ScheduledTaskQueue::kCheckIntervalMs; constexpr size_t ScheduledTaskQueue::kScanBatchSize; } // namespace infra
36.057692
118
0.701067
danielcompton
fc6efff6f8c4fbd1d6f7fe6fb3ea571875354e91
2,374
cpp
C++
BackendCommon/IProfilerServer.cpp
RaptDept/slimtune
a9a248a342a51d95b7c833bce5bb91bf3db987f3
[ "MIT" ]
26
2015-07-01T03:26:50.000Z
2018-02-06T06:00:38.000Z
BackendCommon/IProfilerServer.cpp
RaptDept/slimtune
a9a248a342a51d95b7c833bce5bb91bf3db987f3
[ "MIT" ]
null
null
null
BackendCommon/IProfilerServer.cpp
RaptDept/slimtune
a9a248a342a51d95b7c833bce5bb91bf3db987f3
[ "MIT" ]
7
2018-06-27T13:17:56.000Z
2020-05-02T16:59:24.000Z
/* * Copyright (c) 2007-2009 SlimDX Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "stdafx.h" #include "IProfilerServer.h" #include "SocketServer.h" #include "IProfilerData.h" IProfilerServer* IProfilerServer::CreateSocketServer(IProfilerData& profiler, unsigned short port, Mutex& lock) { return new SocketServer(profiler, port, lock); } char* WriteFloat(char* buffer, float value) { memcpy(buffer, &value, sizeof(float)); buffer += 4; return buffer; } char* Write7BitEncodedInt(char* buffer, unsigned int value) { while(value >= 128) { *buffer++ = static_cast<char>(value | 0x80); value >>= 7; } *buffer++ = static_cast<char>(value); return buffer; } char* Write7BitEncodedInt64(char* buffer, unsigned __int64 value) { while(value >= 128) { *buffer++ = static_cast<char>(value | 0x80); value >>= 7; } *buffer++ = static_cast<char>(value); return buffer; } char* WriteString(char* buffer, const wchar_t* string, size_t count) { size_t size = count * sizeof(wchar_t); buffer = Write7BitEncodedInt(buffer, (unsigned int) size); memcpy(buffer, string, size); return buffer + size; } char* Read7BitEncodedInt(char* buffer, unsigned int& value) { int byteval; int shift = 0; value = 0; while(((byteval = *buffer++) & 0x80) != 0) { value |= ((byteval & 0x7F) << shift); shift += 7; } return buffer; }
27.929412
111
0.726622
RaptDept
fc7273b2d3d76b4247d6a97a7a0cacbf277e923b
1,265
cpp
C++
graph-source-code/350-E/10332016.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/350-E/10332016.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/350-E/10332016.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include<bits/stdc++.h> using namespace std; int a[1010]; bool lab[1010]; vector<pair<int,int> > ans; bool use[1010][1010]; int p[1010]; int f(int x){ return x==p[x]?x:p[x]=f(p[x]); } int main(){ int n,m,K; scanf("%d%d%d",&n,&m,&K); if(K==n){ puts("-1"); return 0; } for(int i=0;i<K;i++){ scanf("%d",&a[i]); lab[a[i]]=true; } for(int i=1;i<=n;i++){ p[i]=i; } sort(a,a+K); for(int i=1;i<=n&&m;i++){ for(int j=i+1;j<=n&&m;j++){ if(i==a[0]){ if(lab[j])continue; } int fi=f(i),fj=f(j); if(fi==fj)continue; p[fi]=fj; m--; ans.push_back({i,j}); use[i][j]=true; } } for(int i=1;i<=n&&m;i++){ for(int j=i+1;j<=n&&m;j++){ if(use[i][j])continue; if(i==a[0]){ if(lab[j])continue; } m--; ans.push_back({i,j}); } } if(m){ puts("-1"); return 0; } for(int i=0;i<ans.size();i++){ printf("%d %d\n",ans[i].first,ans[i].second); } return 0; }
20.403226
54
0.361265
AmrARaouf
fc74122ce43a5f8ca0f655d209a32ecd6182480b
573
cpp
C++
dev/DynamicDependency/API/appmodel_packageinfo.cpp
ChrisGuzak/WindowsAppSDK
3f19ef0f438524af3c87fdad5f4fea555530c285
[ "CC-BY-4.0", "MIT" ]
2,002
2020-05-19T15:16:02.000Z
2021-06-24T13:28:05.000Z
dev/DynamicDependency/API/appmodel_packageinfo.cpp
ChrisGuzak/WindowsAppSDK
3f19ef0f438524af3c87fdad5f4fea555530c285
[ "CC-BY-4.0", "MIT" ]
1,065
2021-06-24T16:08:11.000Z
2022-03-31T23:12:32.000Z
dev/DynamicDependency/API/appmodel_packageinfo.cpp
ChrisGuzak/WindowsAppSDK
3f19ef0f438524af3c87fdad5f4fea555530c285
[ "CC-BY-4.0", "MIT" ]
106
2020-05-19T15:20:00.000Z
2021-06-24T15:03:57.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #include "pch.h" #include "appmodel_packageinfo.h" #include "MddDetourPackageGraph.h" LONG appmodel::GetPackageInfo2( PACKAGE_INFO_REFERENCE packageInfoReference, UINT32 flags, PackagePathType packagePathType, UINT32* bufferLength, BYTE* buffer, UINT32* count) { return MddGetPackageInfo1Or2(packageInfoReference, flags, packagePathType, bufferLength, buffer, count); }
30.157895
109
0.745201
ChrisGuzak
fc7b100dd6b1016efebe4eb3fae602a9becd3af2
437
cpp
C++
ViAn/GUI/DrawingItems/penitem.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
1
2019-12-08T03:53:03.000Z
2019-12-08T03:53:03.000Z
ViAn/GUI/DrawingItems/penitem.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
182
2018-02-08T11:03:26.000Z
2019-06-27T15:27:47.000Z
ViAn/GUI/DrawingItems/penitem.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
null
null
null
#include "penitem.h" PenItem::PenItem(Pen* pen) : ShapeItem(PEN_ITEM) { m_pen = pen; setFlags(flags() | Qt::ItemIsDragEnabled); setText(0, pen->get_name()); const QIcon pen_icon(":/Icons/pen.png"); setIcon(0, pen_icon); map = QPixmap(16,16); update_shape_color(); update_show_icon(m_pen->get_show()); } PenItem::~PenItem() {} void PenItem::remove() {} Pen* PenItem::get_shape() { return m_pen; }
19.863636
50
0.636156
NFCSKL
fc7ce3da20e68bae2165bcaa8637d86f2f731cee
2,389
cpp
C++
src/util/lp/lp_primal_core_solver_instances.cpp
leodemoura/lean_clone
cc077554b584d39bab55c360bc12a6fe7957afe6
[ "Apache-2.0" ]
130
2016-12-02T22:46:10.000Z
2022-03-22T01:09:48.000Z
src/util/lp/lp_primal_core_solver_instances.cpp
soonhokong/lean
38607e3eb57f57f77c0ac114ad169e9e4262e24f
[ "Apache-2.0" ]
8
2017-05-03T01:21:08.000Z
2020-02-25T11:38:05.000Z
src/util/lp/lp_primal_core_solver_instances.cpp
soonhokong/lean
38607e3eb57f57f77c0ac114ad169e9e4262e24f
[ "Apache-2.0" ]
28
2016-12-02T22:46:20.000Z
2022-03-18T21:28:20.000Z
/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Lev Nachmanson */ #include <utility> #include <memory> #include <string> #include <vector> #include <functional> #include "util/lp/lar_solver.h" #include "util/lp/lp_primal_core_solver.cpp" namespace lean { template void lp_primal_core_solver<double, double>::find_feasible_solution(); template lp_primal_core_solver<double, double>::lp_primal_core_solver(static_matrix<double, double>&, std::vector<double, std::allocator<double> >&, std::vector<double, std::allocator<double> >&, std::vector<unsigned int, std::allocator<unsigned int> >&, std::vector<double, std::allocator<double> >&, std::vector<column_type, std::allocator<column_type> >&, std::vector<double, std::allocator<double> >&, lp_settings&, std::unordered_map<unsigned int, std::string, std::hash<unsigned int>, std::equal_to<unsigned int>, std::allocator<std::pair<unsigned int const, std::string> > > const&); template lp_primal_core_solver<double, double>::lp_primal_core_solver(static_matrix<double, double>&, std::vector<double, std::allocator<double> >&, std::vector<double, std::allocator<double> >&, std::vector<unsigned int, std::allocator<unsigned int> >&, std::vector<double, std::allocator<double> >&, std::vector<column_type, std::allocator<column_type> >&, std::vector<double, std::allocator<double> >&, std::vector<double, std::allocator<double> >&, lp_settings&, std::unordered_map<unsigned int, std::string, std::hash<unsigned int>, std::equal_to<unsigned int>, std::allocator<std::pair<unsigned int const, std::string> > > const&); template unsigned lp_primal_core_solver<double, double>::solve(); template lp_primal_core_solver<mpq, mpq>::lp_primal_core_solver(static_matrix<mpq, mpq>&, std::vector<mpq, std::allocator<mpq> >&, std::vector<mpq, std::allocator<mpq> >&, std::vector<unsigned int, std::allocator<unsigned int> >&, std::vector<mpq, std::allocator<mpq> >&, std::vector<column_type, std::allocator<column_type> >&, std::vector<mpq, std::allocator<mpq> >&, std::vector<mpq, std::allocator<mpq> >&, lp_settings&, std::unordered_map<unsigned int, std::string, std::hash<unsigned int>, std::equal_to<unsigned int>, std::allocator<std::pair<unsigned int const, std::string> > > const&); template unsigned lp_primal_core_solver<mpq, mpq>::solve(); }
103.869565
637
0.747175
leodemoura
fc7d1bbe8f2f2f97aee831d16ee95390c3b0c333
2,893
hpp
C++
headers/enduro2d/utils/module.hpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
92
2018-08-07T14:45:33.000Z
2021-11-14T20:37:23.000Z
headers/enduro2d/utils/module.hpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
43
2018-09-30T20:48:03.000Z
2020-04-20T20:05:26.000Z
headers/enduro2d/utils/module.hpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
13
2018-08-08T13:45:28.000Z
2020-10-02T11:55:58.000Z
/******************************************************************************* * This file is part of the "Enduro2D" * For conditions of distribution and use, see copyright notice in LICENSE.md * Copyright (C) 2018-2020, by Matvey Cherevko (blackmatov@gmail.com) ******************************************************************************/ #pragma once #include "_utils.hpp" namespace e2d { class module_not_initialized final : public exception { public: const char* what() const noexcept final { return "module not initialized"; } }; class module_already_initialized final : public exception { public: const char* what() const noexcept final { return "module already initialized"; } }; template < typename BaseT > class module : private noncopyable { public: using base_type = BaseT; public: module() noexcept = default; virtual ~module() noexcept = default; const std::thread::id& main_thread() const noexcept { return main_thread_; } bool is_in_main_thread() const noexcept { return std::this_thread::get_id() == main_thread_; } public: template < typename ImplT, typename... Args > static ImplT& initialize(Args&&... args) { if ( is_initialized() ) { throw module_already_initialized(); } instance_ = std::make_unique<ImplT>(std::forward<Args>(args)...); return static_cast<ImplT&>(*instance_); } static void shutdown() noexcept { instance_.reset(); } static bool is_initialized() noexcept { return !!instance_; } static BaseT& instance() { if ( !is_initialized() ) { throw module_not_initialized(); } return *instance_; } private: static std::unique_ptr<BaseT> instance_; std::thread::id main_thread_ = std::this_thread::get_id(); }; template < typename BaseT > std::unique_ptr<BaseT> module<BaseT>::instance_; } namespace e2d::modules { template < typename ImplT, typename... Args > ImplT& initialize(Args&&... args) { using BaseT = typename ImplT::base_type; return module<BaseT>::template initialize<ImplT>(std::forward<Args>(args)...); } template < typename... ImplTs > void shutdown() noexcept { (... , module<typename ImplTs::base_type>::shutdown()); } template < typename... ImplTs > bool is_initialized() noexcept { return (... && module<typename ImplTs::base_type>::is_initialized()); } template < typename ImplT > ImplT& instance() { using BaseT = typename ImplT::base_type; return static_cast<ImplT&>(module<BaseT>::instance()); } }
29.222222
86
0.557553
NechukhrinN
fc7df3b3c2d60a8de39966901a3a2e4242e97de2
370
cpp
C++
tools/json-ast-exporter/src/main.cpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
63
2016-02-06T21:06:40.000Z
2021-11-16T19:58:27.000Z
tools/json-ast-exporter/src/main.cpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
11
2019-05-23T20:55:12.000Z
2021-12-08T22:18:01.000Z
tools/json-ast-exporter/src/main.cpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
14
2016-02-21T17:12:36.000Z
2021-09-26T02:48:41.000Z
#include "ast_export.hpp" #include "Options.hpp" int main(int argc, char *argv[]) { using namespace cclyzer::ast_exporter; try { // Parse command line Options options(argc, argv); // Export AST in JSON form jsonexport::export_ast(options); } catch (int errorcode) { exit(errorcode); } return 0; }
16.086957
42
0.583784
TheoKant
fc801c3c14d26b8f1dce97f95d00cb2213709e8d
1,878
cpp
C++
ProcessingQueues/src/base/Data.cpp
seancfoley/HPQueues
e1e75d0afc8470e93d2c172c8f687bdc13f85d38
[ "Apache-2.0" ]
7
2016-09-29T02:17:02.000Z
2021-02-19T13:55:56.000Z
ProcessingQueues/src/base/Data.cpp
seancfoley/HPQueues
e1e75d0afc8470e93d2c172c8f687bdc13f85d38
[ "Apache-2.0" ]
null
null
null
ProcessingQueues/src/base/Data.cpp
seancfoley/HPQueues
e1e75d0afc8470e93d2c172c8f687bdc13f85d38
[ "Apache-2.0" ]
1
2018-05-23T08:53:52.000Z
2018-05-23T08:53:52.000Z
/* * Data.cpp * * Created on: Jun 9, 2010 * Author: sfoley */ #include <sstream> #include <ios> #include "Data.h" namespace hpqueue { const std::string Data::emptyString; const char Data::emptyChars[] = {'\0'}; template<> const INT_8 vector_wrapper<INT_8>::emptyValue[] = { 0 }; template <> std::string DataConverter<std::string>::convertToStringValue(const std::string &value) { return value; } template<> std::string DataConverter<std::string>::convertFromStringValue(const std::string &value) { return value; }; template<> std::string DataConverter<std::string>::convertFromString(const std::string &value) { return value; }; template<> std::string DataConverter<bool>::convertToStringValue(const bool &val) { std::ostringstream stream; stream << std::boolalpha << val; return stream.str(); }; template<> bool DataConverter<bool>::convertFromStringValue(const std::string &val) { std::string str(val); std::transform(str.begin(), str.end(), str.begin(), ::tolower); std::istringstream stream(str); bool result; stream >> std::skipws >> std::boolalpha >> result; return result; }; template<> bool DataConverter<bool>::convertFromString(const std::string &val) { std::string str(val); std::transform(str.begin(), str.end(), str.begin(), ::tolower); std::istringstream stream(str); bool result; stream >> std::skipws >> std::boolalpha >> result; conversionFailed = stream.fail(); return result; }; template struct DataConverter<bool>; template struct DataConverter<INT_32>; template struct DataConverter<INT_64>; template struct DataConverter<INT_8>; template struct DataConverter<INT_16>; template struct DataConverter<UINT_32>; template struct DataConverter<UINT_64>; template struct DataConverter<UINT_8>; template struct DataConverter<UINT_16>; template struct DataConverter<double>; template struct DataConverter<std::string>; }
24.076923
90
0.731629
seancfoley