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
109
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
48.5k
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
feea6d93c4b2a76f63baa3b9912ccd3b26ae96b2
15,495
cpp
C++
WebArborEmail/NSQuotedPrintable.cpp
klanglie/WebArborEmail
71459e76f6d67b66b5856f093d260d9d4ae245a7
[ "Apache-2.0" ]
null
null
null
WebArborEmail/NSQuotedPrintable.cpp
klanglie/WebArborEmail
71459e76f6d67b66b5856f093d260d9d4ae245a7
[ "Apache-2.0" ]
null
null
null
WebArborEmail/NSQuotedPrintable.cpp
klanglie/WebArborEmail
71459e76f6d67b66b5856f093d260d9d4ae245a7
[ "Apache-2.0" ]
null
null
null
// NSQuotedPrintable.cpp // v2.0.1.72 2005/11/30 // Updated 10/5/2005 // (c) 2003 - 2005 Langlie Systems, Inc. www.langliesystems.com // All rights reserved. // You may not re-use this code without permission from Langlie Systems, Inc. #include "stdafx.h" #include "NSQuotedPrintable.h" // http://rfc-2045.rfclist.net/rfc-2045-23.htm using namespace WEBARBOR_EMAIL_COMPONENTS; const char crLf[3] = { 13, 10, 0 }; ////--------------------------------------------------------------------------- //#include<iostream> // for debugging purposes only! //using std::cout; //#include<fstream> //// write to a file //void writeFile( string &output, const char * file_path ) //{ // ofstream outClientFile( file_path, ios::out ); // // if ( !outClientFile ){ //// cerr << "File could not be opened" << endl; // exit(1); // } // // outClientFile << output << endl; // // outClientFile.close(); //} ////--------------------------------------------------------------------------- // NSQuotedPrintable destructor // Make sure to delete all global pointers that have been allocated NSQuotedPrintable::NSQuotedPrintable() { } // NSQuotedPrintable constructor. Note that this class must be // constructed in the following manner only: NSQuotedPrintable::NSQuotedPrintable( const string& inVar ) : sQPVar( inVar ) { } // NSQuotedPrintable destructor // Make sure to delete all global pointers that have been allocated NSQuotedPrintable::~NSQuotedPrintable() { } // This function starts the whole quoted-printable decoding engine. // The input is passed into the class constructor and is copied // The resulting output, passed in byref by the variable sQPVar // Hopefully now the message will now be fully qp decoded and looking // like how the author intended it to look. string & NSQuotedPrintable::DecodeQP(bool bHtml) { char * chQP = NULL; char * chQPOut = NULL; try{ if( sQPVar.length() > 0 ) { RemoveQPLineBreaks(); //writeFile(sQPVar, "RemoveQPLineBreaks.txt"); ChangeHttpVar( true ); //writeFile(sQPVar, "_ChangeHttpVar_True.txt"); chQP = c_string( sQPVar ); chQPOut = new char[ strlen(chQP) + 1 ]; chQPOut[ strlen(chQP) ] = '\0'; DecodeQuotedPrintable( chQP, chQPOut ); sQPVar = chQPOut; delete [] chQPOut; delete [] chQP; //writeFile(sQPVar, "_DecodeQuotedPrintable.txt"); if( bHtml == true ){ size_t iFind1 = sQPVar.find("<html"); if( iFind1 != string::npos && iFind1 != 0 ){ sQPVar = sQPVar.substr( iFind1 ); RTrimCrLfSpace(sQPVar); } else{ size_t iFind2 = sQPVar.find("<HTML"); if( iFind2 != string::npos && iFind2 != 0 ){ sQPVar = sQPVar.substr( iFind2 ); RTrimCrLfSpace(sQPVar); } } } ChangeHttpVar( false ); //writeFile(sQPVar, "_ChangeHttpVar_False.txt"); // 4/15/2005. In response to: The Rush Backstage Club message if( sQPVar.find("’") != string::npos ){ chQP = c_string( sQPVar ); strreplace(chQP, "’", "'"); sQPVar = chQP; delete [] chQP; } } return sQPVar; } catch( MiscError ){ delete [] chQP; delete [] chQPOut; throw; } catch(...){ delete [] chQP; delete [] chQPOut; throw MiscError("NSQuotedPrintable::DecodeQP has encountered an unknown error", 9352); } } // RemoveQPLineBreaks is used to remove the equals sign from the // end of a line of text and concatonate the following line to the first line. // The input is searched by line breaks and each line represents // a token that is either appended to with a line break or has an equals // sign which means that the following line is appended to it the previous line. inline void NSQuotedPrintable::RemoveQPLineBreaks() { string sLine; string sbTemp = ""; register size_t iLen, iPos; try{ register string::size_type lastPos = sQPVar.find_first_not_of("\n", 0); // Find first "non-delimiter". register string::size_type pos = sQPVar.find_first_of("\n", lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token sLine = sQPVar.substr(lastPos, pos - lastPos - 1); iLen = sLine.length(); if( iLen == 0 ){ sbTemp.append( crLf ); } else{ // Each line should be 78 chars long or less, but some implementations encode their messages improperly! if ( iLen > 2 && sLine.at(0) == '.' && sLine.at(1) == '.' ) { sLine = sLine.substr(1); iLen -= 1; } if( sLine.at( (iLen - 1) ) == '=' ){ iPos = sLine.find("=0A="); if( iPos != string::npos && iPos == (iLen - 4) ){ sLine.erase( (iLen - 4), 4 ); sbTemp.append( sLine ); sbTemp.append( crLf ); } else{ sLine.erase( (iLen - 1), 1 ); sbTemp.append( sLine ); } } else{ sbTemp.append( sLine ); sbTemp.append( crLf ); } } // Skip delimiters. Note the "not_of" lastPos = sQPVar.find_first_not_of("\n", pos); // Find next "non-delimiter" pos = sQPVar.find_first_of("\n", lastPos); } sQPVar = sbTemp; } catch( MiscError ){ throw; } catch(...){ throw MiscError("NSQuotedPrintable::RemoveQPLineBreaks has encountered an unknown error", 2646); } } // ChangeHttpVar will change the equals sign in an input string's http:// links // in a message to the ascii character 1 or vice versa. This is done so that the QP engine // does not decode a token that it finds in a link that it shouldn't be decoding. // There are however a few commonly found QP symbols in a link that do need converting. // These special cases if found are removed using the strreplace function. Thses special // characters include but might not be limited to =3D(=), =2E(.), and =22(\). inline void NSQuotedPrintable::ChangeHttpVar( bool bStart ) { if( sQPVar.find("http://") == string::npos ){ return; } else if( bStart == false && sQPVar.find_first_of(5) == string::npos ){ return; } string sbTemp = ""; string sLine; char *str = 0; register basic_string <char>::size_type idxStart, idxFind, iLength; register basic_string <char>::size_type idxSpace, idxQuote, idxBracket, idxQP20; register bool bStartQuote; register bool bFind = false; register const char * c4 = "="; try{ register string::size_type lastPos = sQPVar.find_first_not_of("\n", 0); // Find first "non-delimiter". register string::size_type pos = sQPVar.find_first_of("\n", lastPos); while ( string::npos != pos || string::npos != lastPos ) { // Found a token sLine = sQPVar.substr(lastPos, pos - lastPos - 1); idxStart = 0; idxFind = sLine.find_first_of( 'h', idxStart ); while( idxFind != string::npos ){ iLength = 0; if( sLine.find_first_of( 't', idxFind + 1 ) == idxFind + 1 && sLine.find_first_of( 't', idxFind + 2 ) == idxFind + 2 && sLine.find_first_of( 'p', idxFind + 3 ) == idxFind + 3 && sLine.find_first_of( ':', idxFind + 4 ) == idxFind + 4 && sLine.find_first_of( '/', idxFind + 5 ) == idxFind + 5 && sLine.find_first_of( '/', idxFind + 6 ) == idxFind + 6 && sLine.find_first_of( c4, idxFind + 7 ) != string::npos ) { if( idxFind > 0 ){ if( sLine.at(idxFind-1) == '"'){ bStartQuote = true; } else{ bStartQuote = false; } } else{ bStartQuote = false; } idxSpace = sLine.find_first_of( 32, idxFind ); idxQuote = sLine.find_first_of( '"', idxFind ); idxBracket = sLine.find_first_of( '>', idxFind ); if( idxSpace != string::npos ){ if( idxQuote != string::npos && idxQuote < idxSpace && bStartQuote ){ iLength = idxQuote - idxFind; } else if( ( idxBracket != string::npos && idxBracket < idxSpace ) ){ iLength = idxBracket - idxFind; } else{ idxQP20 = FindQPCharsInString(sLine, idxFind, '2', '0'); if( idxQP20 != string::npos && idxQP20 < idxSpace ){ iLength = idxQP20 - idxFind; } else{ iLength = idxSpace - idxFind; // This is the default case with a space! } } } else{ if( idxQuote != string::npos && bStartQuote ){ iLength = idxQuote - idxFind; } else if( idxBracket != string::npos ){ iLength = idxBracket - idxFind; } else{ idxQP20 = FindQPCharsInString(sLine, idxFind, '2', '0'); if( idxQP20 != string::npos ){ iLength = idxQP20 - idxFind; } else{ iLength = sLine.length() - idxFind; // This is the default case with no space! } } } if ( iLength > 0 ){ // Change all equals signs to a smily face character. str = new char[ iLength + 1 ]; str[ iLength ] = 0; strcpy( str, sLine.substr( idxFind, iLength ).c_str() ); if( bStart == true ){ register basic_string <char>::size_type i, j, k, iLen; iLen = strlen(str) - 2; for( i = 0; i < iLen; i++ ){ if( *( str + i ) == '=' ){ j = i + 1; k = i + 2; if( !isdigit(*( str + j )) && !isalpha(*( str + k )) ){ if( (idxQuote == string::npos) && *( str + j ) == '2' && *( str + k ) == '2' ){ // do nothing } else{ *( str + i ) = 5; bFind = true; } } } } } else{ char c3[2] = { 5, 0}; if( strreplace( str, c3, c4 ) > 0 ) bFind = true; } if( bFind == true ){ sLine.erase( idxFind, iLength ); sLine.insert( idxFind, str, iLength ); bFind = false; } delete [] str; } } if( iLength == 0 ){ idxStart = idxFind + 1; } else{ idxStart = idxFind + iLength; } idxFind = sLine.find_first_of( 'h', idxStart ); } sbTemp.append( sLine ); sbTemp.append( crLf ); // Skip delimiters. Note the "not_of" lastPos = sQPVar.find_first_not_of("\n", pos); // Find next "non-delimiter" pos = sQPVar.find_first_of("\n", lastPos); } sQPVar = sbTemp; } catch( MiscError ){ delete [] str; throw; } catch(...){ delete [] str; throw MiscError("NSQuotedPrintable::ChangeHttpVar has encountered an unknown error", 3728); } } void NSQuotedPrintable::DecodeQuotedPrintable( char * chQPIn, char * chQPOut ){ register basic_string <char>::size_type i, j, k, iLen, iSkip, iCount, iPos; iLen = strlen(chQPIn); iSkip = 2; iCount = 0; iPos = 0; try{ for( i = 0; i < iLen; i++ ){ if( *( chQPIn + i ) == '=' && (i < iLen - 2) ){ j = i + 1; k = i + 2; if( ( *( chQPIn + j ) >= 48 && *( chQPIn + j ) <= 57 || *( chQPIn + j ) >= 65 && *( chQPIn + j ) <= 70 || *( chQPIn + j ) >= 97 && *( chQPIn + j ) <= 102 ) && ( *( chQPIn + k ) >= 48 && *( chQPIn + k ) <= 57 || *( chQPIn + k ) >= 65 && *( chQPIn + k ) <= 70 || *( chQPIn + k ) >= 97 && *( chQPIn + k ) <= 102 ) ){ //=B9 equals an apostrophe and can look funny in NSPOP. if( *( chQPIn + j ) == 66 && *( chQPIn + k ) == 57 ){ chQPOut[iPos++] = '\''; } else{ chQPOut[iPos++] = static_cast<char>(HexToChar( ( chQPIn + j ), ( chQPIn + k ) )); } iCount += 2; iSkip = 0; } else if( iSkip < 2 ){ ++iSkip; } else{ chQPOut[iPos++] = *( chQPIn + i ); } } else if( iSkip < 2 ){ ++iSkip; } else{ chQPOut[iPos++] = *( chQPIn + i ); } } if( iCount > 0 ){ chQPOut[ iLen - iCount ] = '\0'; } } catch( MiscError ){ throw; } catch(...){ throw MiscError("NSQuotedPrintable::DecodeQuotedPrintable has encountered an unknown error", 39482); } } // This function returns an ascii integer representing // the decoded character from the two chars that are passed in. // See RFC's on Quoted-Printable for detail. inline int NSQuotedPrintable::HexToChar( char *chLeft, char *chRight) { register char chTemp; register int iResult, iTotal; for( short i = 1; i < 3; i++ ) { if( i == 1 ){ chTemp = *chRight; } else{ chTemp = *chLeft; } switch(chTemp){ case '0': iResult = 0; break; case '1': iResult = 1; break; case '2': iResult = 2; break; case '3': iResult = 3; break; case '4': iResult = 4; break; case '5': iResult = 5; break; case '6': iResult = 6; break; case '7': iResult = 7; break; case '8': iResult = 8; break; case '9': iResult = 9; break; case 'a': case 'A': iResult = 10; break; case 'b': case 'B': iResult = 11; break; case 'c': case 'C': iResult = 12; break; case 'd': case 'D': iResult = 13; break; case 'e': case 'E': iResult = 14; break; case 'f': case 'F': iResult = 15; break; } if( i == 1 ){ iTotal = iResult; } else{ iTotal += ( iResult * 16 ); } } return iTotal; } inline size_t NSQuotedPrintable::FindQPCharsInString( string& sIn, size_t iBeginPos, const char & c1, const char & c2) { basic_string <char>::iterator str_Iter; str_Iter = sIn.begin(); size_t i = 0; size_t idxEnd = string::npos; while( str_Iter != sIn.end()) { if( i > iBeginPos){ if( *str_Iter == '=' && *(str_Iter + 1) == c1 && *(str_Iter + 2) == c2){ idxEnd = i; break; } } str_Iter++; i++; } return idxEnd; } void NSQuotedPrintable::DecodeQP(const char *input_file_name) { char * a = 0; try{ // This code is for binary attachments only! Not text/html // They must be dealt with using the other way. a = c_string( sQPVar ); DecodeBinaryAttachment( input_file_name, a ); delete [] a; } catch( MiscError ){ delete [] a; throw; } catch(...){ delete [] a; throw MiscError("NSQuotedPrintable::DecodeQP(2) has encountered an unknown error", 26413); } } inline void NSQuotedPrintable::DecodeBinaryAttachment( const char *file_name, const char *input ){ register enum state{ NONE, EQUALS, QUOTED_PRINTABLE } Status; Status = NONE; register char c_qp1 = 0; register char c = 0; //register const char crLf[3] = { 13, 10, 0 } ; ofstream fout; try{ fout.open( file_name, ios_base::binary ); if( !fout.is_open() ){ throw MiscError( "NSQuotedPrintable::DecodeBinaryAttachment was unable to open an output file", 20693 ); ////cerr << "Error: could not poen file" << endl; ////exit(1); } while(*input){ c = *input; switch(c){ case '=': Status = EQUALS; break; case 13: // carriage return if( Status != EQUALS ){ fout << crLf; } break; case 10: // line feed Status = NONE; break; default: if( Status == EQUALS && IsQPChar(&c) == true ){ c_qp1 = c; Status = QUOTED_PRINTABLE; } else if( Status == QUOTED_PRINTABLE && IsQPChar(&c) == true ){ fout << static_cast<unsigned char>(HexToChar(&c_qp1, &c)); Status = NONE; } else if(Status == NONE){ fout << c; } break; } input++; } fout.close(); } catch( MiscError ){ throw; } catch(...){ throw MiscError("NSQuotedPrintable::DecodeBinaryAttachment has encountered an unknown error", 20694); } } inline bool NSQuotedPrintable::IsQPChar(char *c){ if( (*c >= 48 && *c <= 57) || (*c >= 65 && *c <= 70) ){ return true; } else{ return false; } }
22.853982
119
0.566183
klanglie
feee31d87e36fd843eb33de4339f330046427253
2,822
cpp
C++
src/util/ResourceUsage.cpp
kunisura/algorithms2012
49867c897fbca7d2b21f602428ea1a67a79f4a75
[ "MIT" ]
2
2016-08-17T01:49:36.000Z
2019-02-27T13:07:04.000Z
src/util/ResourceUsage.cpp
kunisura/algorithms2012
49867c897fbca7d2b21f602428ea1a67a79f4a75
[ "MIT" ]
null
null
null
src/util/ResourceUsage.cpp
kunisura/algorithms2012
49867c897fbca7d2b21f602428ea1a67a79f4a75
[ "MIT" ]
1
2021-05-14T00:16:52.000Z
2021-05-14T00:16:52.000Z
/* * CPU Resource Usage * Hiroaki Iwashita <iwashita@erato.ist.hokudai.ac.jp> * Copyright (c) 2011 Japan Science and Technology Agency * $Id: ResourceUsage.cpp 9 2011-11-16 06:38:04Z iwashita $ */ #include "ResourceUsage.hpp" #include <cctype> #include <algorithm> #include <fstream> #include <iomanip> #include <string> #include <sstream> #include <sys/time.h> #include <sys/resource.h> using std::string; using std::ifstream; using std::istringstream; using std::ostream; using std::ios; using std::ios_base; using std::setprecision; using std::max; ResourceUsage::ResourceUsage() { update(); } ResourceUsage::ResourceUsage(double utime, double stime, long maxrss) : utime(utime), stime(stime), maxrss(maxrss) { } namespace { long readMemoryStatus(string key) { ifstream ifs("/proc/self/status"); string buf; while (ifs.good()) { getline(ifs, buf); if (buf.compare(0, key.length(), key) == 0) { istringstream iss(buf.substr(key.length())); double size; string unit; iss >> size >> unit; switch (tolower(unit[0])) { case 'b': size *= 1e-3; break; case 'm': size *= 1e+3; break; case 'g': size *= 1e+6; break; case 't': size *= 1e+9; break; } return long(size); } } return 0; } } ResourceUsage& ResourceUsage::update() { struct rusage s; getrusage(RUSAGE_SELF, &s); utime = s.ru_utime.tv_sec + s.ru_utime.tv_usec * 1e-6; stime = s.ru_stime.tv_sec + s.ru_stime.tv_usec * 1e-6; maxrss = s.ru_maxrss; if (maxrss == 0) maxrss = readMemoryStatus("VmHWM:"); return *this; } ResourceUsage ResourceUsage::operator+(ResourceUsage const& u) const { return ResourceUsage(utime + u.utime, stime + u.stime, max(maxrss, u.maxrss)); } ResourceUsage& ResourceUsage::operator+=(ResourceUsage const& u) { utime += u.utime; stime += u.stime; if (maxrss < u.maxrss) maxrss = u.maxrss; return *this; } ResourceUsage ResourceUsage::operator-(ResourceUsage const& u) const { return ResourceUsage(utime - u.utime, stime - u.stime, max(maxrss, u.maxrss)); } ResourceUsage& ResourceUsage::operator-=(ResourceUsage const& u) { utime -= u.utime; stime -= u.stime; if (maxrss < u.maxrss) maxrss = u.maxrss; return *this; } ostream& operator<<(ostream& os, ResourceUsage const& u) { ios_base::fmtflags backup = os.flags(ios::fixed); os << setprecision(2) << u.utime << "s + "; os << setprecision(2) << u.stime << "s, "; os << setprecision(0) << u.maxrss / 1024.0 << "MB"; os.flags(backup); return os; }
24.754386
71
0.589298
kunisura
feeee202d47083c0356065ddbfaddbc7c3c54976
5,289
cpp
C++
Source/SoundEngine/CListener.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
3
2019-04-12T15:22:53.000Z
2022-01-05T02:59:56.000Z
Source/SoundEngine/CListener.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
null
null
null
Source/SoundEngine/CListener.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
2
2019-04-10T22:46:21.000Z
2020-05-27T16:21:37.000Z
#include "SoundEngineException.h" #include "CListener.h" #include "OgreNode.h" template<> Sound::CListener* Ogre::Singleton<Sound::CListener>::msSingleton = 0; namespace Sound { CListener* CListener::Listener = nullptr; CListener* CListener::Instance() { if(Listener == nullptr) Listener = new CListener(); return Listener; } CListener::CListener() : m_Gain(1.0), m_Position(Vector3::ZERO), m_Direction(Vector3::NEGATIVE_UNIT_Z), m_Velocity(Vector3::ZERO), m_Up(Vector3::UNIT_Y), m_DerivedPosition(Vector3::ZERO), m_DerivedDirection(Vector3::NEGATIVE_UNIT_Z) { mParentNode = nullptr; m_LocalTransformDirty = false; InitListener(); } CListener::CListener(const String& name) : Ogre::MovableObject(name), m_Gain(1.0), m_Position(Vector3::ZERO), m_Direction(Vector3::NEGATIVE_UNIT_Z), m_Velocity(Vector3::ZERO), m_Up(Vector3::UNIT_Y), m_DerivedPosition(Vector3::ZERO), m_DerivedDirection(Vector3::NEGATIVE_UNIT_Z) { mParentNode = nullptr; InitListener(); } CListener::~CListener() { } void CListener::SetGain(f32 gain) { m_Gain = gain; alListenerf(AL_GAIN, m_Gain); CheckError(alGetError(), "Failed to Set Gain"); } void CListener::SetPosition(f32 x, f32 y, f32 z) { m_Position.x = x; m_Position.y = y; m_Position.z = z; m_LocalTransformDirty = true; } void CListener::SetPosition(const Vector3& vec) { m_Position = vec; m_LocalTransformDirty = true; } void CListener::SetDirection(f32 x, f32 y, f32 z) { m_Direction.x = x; m_Direction.y = y; m_Direction.z = z; m_LocalTransformDirty = true; } void CListener::SetDirection(const Vector3& vec) { m_Direction = vec; m_LocalTransformDirty = true; } void CListener::SetVelocity(f32 x, f32 y, f32 z) { m_Velocity.x = x; m_Velocity.y = y; m_Velocity.z = z; alListener3f(AL_VELOCITY, m_Velocity.x, m_Velocity.y, m_Velocity.z); CheckError(alGetError(), "Failed to Set Velocity"); } void CListener::SetVelocity(const Vector3& vec) { SetVelocity(vec.x, vec.y, vec.z); } const Vector3& CListener::GetDerivedPosition(void) const { Update(); return m_DerivedPosition; } const Vector3& CListener::GetDerivedDirection(void) const { Update(); return m_DerivedDirection; } void CListener::InitListener() { mOrientation[0]= m_Direction.x; // Forward.x mOrientation[1]= m_Direction.y; // Forward.y mOrientation[2]= m_Direction.z; // Forward.z mOrientation[3]= m_Up.x; // Up.x mOrientation[4]= m_Up.y; // Up.y mOrientation[5]= m_Up.z; // Up.z alListener3f(AL_POSITION, m_Position.x, m_Position.y, m_Position.z); CheckError(alGetError(), "Failed to Set Position"); alListenerfv(AL_ORIENTATION, mOrientation); CheckError(alGetError(), "Failed to Set Orientation"); alListenerf (AL_GAIN, 1.0f); CheckError(alGetError(), "Failed to Set Gain"); alListener3f(AL_VELOCITY, 0.0f, 0.0f, 0.0f); CheckError(alGetError(), "Failed to Set Velocity"); } void CListener::Update() const { if (mParentNode) { if (!(mParentNode->_getDerivedOrientation() == m_LastParentOrientation && mParentNode->_getDerivedPosition() == m_LastParentPosition) || m_LocalTransformDirty) { // Ok, we're out of date with SceneNode we're attached to m_LastParentOrientation = mParentNode->_getDerivedOrientation(); m_LastParentPosition = mParentNode->_getDerivedPosition(); m_DerivedDirection = m_LastParentOrientation * m_Direction; m_DerivedPosition = (m_LastParentOrientation * m_Position) + m_LastParentPosition; } } else { m_DerivedPosition = m_Position; m_DerivedDirection = m_Direction; } m_LocalTransformDirty = false; } void CListener::UpdateListener() { Update(); if(mParentNode) { m_Position = m_LastParentPosition; m_Direction = m_LastParentOrientation.zAxis(); m_Up = m_LastParentOrientation.yAxis(); } alListener3f(AL_POSITION, m_Position.x, m_Position.y, m_Position.z); CheckError(alGetError(), "Failed to Set Position"); mOrientation[0]= -m_Direction.x; // Forward.x mOrientation[1]= -m_Direction.y; // Forward.y mOrientation[2]= -m_Direction.z; // Forward.z mOrientation[3]= m_Up.x; // Up.x mOrientation[4]= m_Up.y; // Up.y mOrientation[5]= m_Up.z; // Up.z alListenerfv(AL_ORIENTATION, mOrientation); CheckError(alGetError(), "Failed to Set Orientation"); } const String& CListener::getMovableType() const { return ListenerFactory::FACTORY_TYPE_NAME; } const Ogre::AxisAlignedBox& CListener::getBoundingBox() const { // Null, Sounds are not visible static Ogre::AxisAlignedBox box; return box; } void CListener::_updateRenderQueue(Ogre::RenderQueue* queue) { // Do Nothing } void CListener::_notifyAttached(Ogre::Node* parent, bool isTagPoint) { mParentNode = parent; } String ListenerFactory::FACTORY_TYPE_NAME = "OgreAL_Listener"; const String& ListenerFactory::getType(void) const { return FACTORY_TYPE_NAME; } Ogre::MovableObject* ListenerFactory::createInstanceImpl(const String& name, const Ogre::NameValuePairList* params) { CListener *listener = CListener::Instance(); if(listener) return listener; else return new CListener(name); } void ListenerFactory::destroyInstance(Ogre::MovableObject* obj) { delete obj; } }
22.995652
116
0.7128
shanefarris
fef0683d7df839c8e0a4b51377a60a644beede39
11,401
cpp
C++
src/util/gdal_timesnap.cpp
umr-dbs/mapping-core
1651e1c1bc887214d9f525536f6bdf79a8c464de
[ "MIT" ]
null
null
null
src/util/gdal_timesnap.cpp
umr-dbs/mapping-core
1651e1c1bc887214d9f525536f6bdf79a8c464de
[ "MIT" ]
10
2018-03-02T13:58:32.000Z
2020-06-05T11:12:42.000Z
src/util/gdal_timesnap.cpp
umr-dbs/mapping-core
1651e1c1bc887214d9f525536f6bdf79a8c464de
[ "MIT" ]
3
2018-02-26T14:01:43.000Z
2019-12-09T10:03:17.000Z
#include "gdal_timesnap.h" #include <boost/filesystem.hpp> #include "util/concat.h" #include "util/log.h" constexpr int MAX_FILE_NAME_LENGTH = 255; const std::map<std::string, TimeUnit> GDALTimesnap::string_to_TimeUnit = { {"Second", TimeUnit::Second}, {"Minute", TimeUnit::Minute}, {"Hour", TimeUnit::Hour}, {"Day", TimeUnit::Day}, {"Month", TimeUnit::Month}, {"Year", TimeUnit::Year} }; TimeUnit GDALTimesnap::createTimeUnit(std::string value) { return string_to_TimeUnit.at(value); } // snaps the wanted time to a interval timestamp from the startTime ptime GDALTimesnap::snapToInterval(TimeUnit snapUnit, int intervalValue, ptime start, ptime wanted){ switch (snapUnit) { case TimeUnit::Year: { int diff = wanted.date().year() - start.date().year(); diff = (diff / intervalValue) * intervalValue; boost::gregorian::date snapped(start.date()); snapped += boost::gregorian::years(diff); return ptime(snapped, start.time_of_day()); } case TimeUnit::Month: { int months = (wanted.date().year() - start.date().year())*12 + wanted.date().month() - start.date().month(); months = (months / intervalValue) * intervalValue; boost::gregorian::date snapped(start.date()); snapped += boost::gregorian::months(months); return ptime(snapped, start.time_of_day()); } case TimeUnit::Day: { long days = (wanted.date() - start.date()).days(); days = (days / intervalValue) * intervalValue; boost::gregorian::date snapped(start.date()); snapped += boost::gregorian::days(days); return ptime(snapped, start.time_of_day()); } case TimeUnit::Hour: { long hours = (wanted.date() - start.date()).days() * 24; hours += wanted.time_of_day().hours() - start.time_of_day().hours(); hours = (hours / intervalValue) * intervalValue; long days = hours / 24; hours = hours - days * 24; boost::gregorian::date snapped(start.date()); snapped += boost::gregorian::days(days); return ptime(snapped, start.time_of_day() + boost::posix_time::hours(hours)); } case TimeUnit::Minute: { long minutes = (wanted.date() - start.date()).days() * 24 * 60; minutes += wanted.time_of_day().hours() * 60 - start.time_of_day().hours() * 60; minutes += wanted.time_of_day().minutes() - start.time_of_day().minutes(); minutes = (minutes / intervalValue) * intervalValue; long hours = minutes / 60; minutes = minutes - hours * 60; long days = hours / 24; hours = hours - days * 24; boost::gregorian::date snapped(start.date()); snapped += boost::gregorian::days(days); return ptime(snapped, start.time_of_day() + boost::posix_time::hours(hours) + boost::posix_time::minutes(minutes)); } case TimeUnit::Second: { long seconds = (wanted.date() - start.date()).days() * 24 * 60 * 60; seconds += wanted.time_of_day().hours() * 60 * 60 - start.time_of_day().hours() * 60 * 60; seconds += wanted.time_of_day().minutes() * 60 - start.time_of_day().minutes() * 60; seconds += wanted.time_of_day().seconds() - start.time_of_day().seconds(); seconds = (seconds / intervalValue) * intervalValue; long minutes = seconds / 60; seconds = seconds - minutes * 60; long hours = minutes / 60; minutes = minutes - hours * 60; long days = hours / 24; hours = hours - days * 24; boost::gregorian::date snapped(start.date()); snapped += boost::gregorian::days(days); return ptime(snapped, start.time_of_day() + boost::posix_time::hours(hours) + boost::posix_time::minutes(minutes) +boost::posix_time::seconds(seconds) ); } } } // calculates the filename for queried time by snapping the wanted time to the // nearest smaller timestamp that exists for the dataset // TODO: move general parameter parsing to a more appropriate function GDALTimesnap::GDALDataLoadingInfo GDALTimesnap::getDataLoadingInfo(Json::Value datasetJson, int channel, const TemporalReference &tref) { // get parameters Json::Value channelJson = datasetJson["channels"][channel]; // get parameters std::string time_format = channelJson.get("time_format", datasetJson.get("time_format", "")).asString(); std::string time_start = channelJson.get("time_start", datasetJson.get("time_start", "")).asString(); std::string time_end = channelJson.get("time_end", datasetJson.get("time_end", "")).asString(); std::string path = channelJson.get("path", datasetJson.get("path", "")).asString(); std::string fileName = channelJson.get("file_name", datasetJson.get("file_name", "")).asString(); Log::debug( concat("getDataLoadingInfo: time_format: ", time_format, ", time_start: ", time_start, ", time_end: ", time_end, ", path: ", path, ", fileName: ", fileName ) ); channel = channelJson.get("channel", channel).asInt(); // resolve time auto timeParser = TimeParser::create(TimeParser::Format::ISO); double time_start_mapping; double time_end_mapping; if(time_start.empty()) { time_start_mapping = tref.beginning_of_time(); } else { time_start_mapping = timeParser->parse(time_start); } if(time_end.empty()) { time_end_mapping = tref.end_of_time(); } else { time_end_mapping = timeParser->parse(time_end); } double wantedTimeUnix = tref.t1; //check if requested time is in range of dataset timestamps //a dataset only has start not end time. if wantedtime is past the last file of dataset, it can simply not be loaded. if(wantedTimeUnix < time_start_mapping || wantedTimeUnix > time_end_mapping) { throw NoRasterForGivenTimeException( "Requested time is not in range of dataset", MappingExceptionType::PERMANENT ); } if(datasetJson.isMember("time_interval") || channelJson.isMember("time_interval")) { Json::Value timeInterval = channelJson.get("time_interval", datasetJson.get("time_interval", Json::Value(Json::objectValue))); TimeUnit intervalUnit = GDALTimesnap::createTimeUnit(timeInterval.get("unit", "Month").asString()); int intervalValue = timeInterval.get("value", 1).asInt(); // doesn't work on older boost versions because seconds precision is limit to 32bit // ptime start = from_time_t(static_cast<time_t>(time_start_mapping)); // ptime wanted = from_time_t(static_cast<time_t>(wantedTimeUnix)); ptime start = ptime(boost::gregorian::date(1970,1,1)) + milliseconds(static_cast<long>(time_start_mapping * 1000)); ptime wanted = ptime(boost::gregorian::date(1970,1,1)) + milliseconds(static_cast<long>(wantedTimeUnix * 1000)); //snap the time to the given interval ptime snappedTimeStart = GDALTimesnap::snapToInterval(intervalUnit, intervalValue, start, wanted); // snap end to the next interval ptime snappedTimeEnd(snappedTimeStart); switch (intervalUnit) { case TimeUnit::Year: snappedTimeEnd += boost::gregorian::years(intervalValue); break; case TimeUnit::Month: snappedTimeEnd += boost::gregorian::months(intervalValue); break; case TimeUnit::Day: snappedTimeEnd += boost::gregorian::days(intervalValue); break; case TimeUnit::Hour: snappedTimeEnd += boost::posix_time::hours(intervalValue); break; case TimeUnit::Minute: snappedTimeEnd += boost::posix_time::minutes(intervalValue); break; case TimeUnit::Second: snappedTimeEnd += boost::posix_time::seconds(intervalValue); break; } time_start_mapping = boost::posix_time::to_time_t(snappedTimeStart); time_end_mapping = boost::posix_time::to_time_t(snappedTimeEnd); // format date to determine file auto snappedTimeT = static_cast<time_t>(time_start_mapping); tm snappedTimeTm = {}; gmtime_r(&snappedTimeT, &snappedTimeTm); char date[MAX_FILE_NAME_LENGTH] = {0}; strftime(date, sizeof(date), time_format.c_str(), &snappedTimeTm); std::string snappedTimeString(date); std::string placeholder = "%%%TIME_STRING%%%"; size_t placeholderPos = fileName.find(placeholder); fileName = fileName.replace(placeholderPos, placeholder.length(), snappedTimeString); Log::debug(concat("getDataLoadingInfo: resulting time fileName: ", fileName.c_str())); } else if ( datasetJson.isMember("channel_start_time_list") && datasetJson["channel_start_time_list"].isArray() ) { Log::debug(concat("getDataLoadingInfo: using channels as time")); auto time_channel = 0; const auto channel_time_strings = datasetJson.get("channel_start_time_list", Json::Value(Json::ValueType::arrayValue)); for (const auto &time_string : channel_time_strings) { auto const channel_time = timeParser->parse(time_string.asString()); if (wantedTimeUnix >= channel_time) { time_channel += 1; } else { break; } } if (time_channel <= 0) { throw NoRasterForGivenTimeException( "No channel corresponds to the requested time", MappingExceptionType::PERMANENT ); } Log::debug(concat("getDataLoadingInfo: setting channel to: ", time_channel, " (was: ", channel,") for time: ", wantedTimeUnix)); channel = time_channel; } // other GDAL parameters Unit unit = Unit::unknown(); if (channelJson.isMember("unit")) { unit = Unit(channelJson["unit"]); } double nodata = NAN; if (channelJson.isMember("nodata")) { nodata = channelJson["nodata"].asDouble(); } auto coords = channelJson.get("coords", datasetJson["coords"]); CrsId crsId = CrsId::from_srs_string(coords.get("crs", "").asString()); boost::filesystem::path file_path(path); file_path /= fileName; std::string dataset_file_path = file_path.string(); Log::debug(concat("getDataLoadingInfo: file_path: ", file_path)); // Handle NetCDF subdatasets if (channelJson.isMember("netcdf_subdataset") || datasetJson.isMember("netcdf_subdataset")) { std::string netcdf_subdataset = channelJson.get("netcdf_subdataset", datasetJson.get("netcdf_subdataset", "")).asString(); dataset_file_path = concat("NETCDF:", dataset_file_path, ":", netcdf_subdataset); Log::debug(concat("getDataLoadingInfo: found NETCDF subdataset: ", netcdf_subdataset, ". Resulting path: ", dataset_file_path)); } return GDALDataLoadingInfo(dataset_file_path, channel, TemporalReference(TIMETYPE_UNIX, time_start_mapping, time_end_mapping), crsId, nodata, unit); }
40.429078
136
0.626787
umr-dbs
fef390320457c133f4fe32d56a61a07ae6a4be61
1,356
cpp
C++
lib/VM/JSDate.cpp
calebmackdavenport/hermes
13fc688865ee9bf8a41b7cef93f613853401f453
[ "MIT" ]
2
2022-02-21T00:02:22.000Z
2022-02-21T00:02:28.000Z
lib/VM/JSDate.cpp
calebmackdavenport/hermes
13fc688865ee9bf8a41b7cef93f613853401f453
[ "MIT" ]
null
null
null
lib/VM/JSDate.cpp
calebmackdavenport/hermes
13fc688865ee9bf8a41b7cef93f613853401f453
[ "MIT" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "hermes/VM/JSDate.h" #include "hermes/VM/BuildMetadata.h" #include "hermes/VM/Runtime-inline.h" namespace hermes { namespace vm { //===----------------------------------------------------------------------===// // class JSDate const ObjectVTable JSDate::vt{ VTable(CellKind::JSDateKind, cellSize<JSDate>()), JSDate::_getOwnIndexedRangeImpl, JSDate::_haveOwnIndexedImpl, JSDate::_getOwnIndexedPropertyFlagsImpl, JSDate::_getOwnIndexedImpl, JSDate::_setOwnIndexedImpl, JSDate::_deleteOwnIndexedImpl, JSDate::_checkAllOwnIndexedImpl, }; void JSDateBuildMeta(const GCCell *cell, Metadata::Builder &mb) { mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<JSDate>()); JSObjectBuildMeta(cell, mb); mb.setVTable(&JSDate::vt); } PseudoHandle<JSDate> JSDate::create(Runtime &runtime, double value, Handle<JSObject> parentHandle) { auto *cell = runtime.makeAFixed<JSDate>( runtime, value, parentHandle, runtime.getHiddenClassForPrototype( *parentHandle, numOverlapSlots<JSDate>())); return JSObjectInit::initToPseudoHandle(runtime, cell); } } // namespace vm } // namespace hermes
27.673469
80
0.688053
calebmackdavenport
fef42d0a42330c36969b90dd899141f108aeb0b9
9,120
hpp
C++
NWNXLib/API/Constants/Animation.hpp
summonFox/unified
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
[ "MIT" ]
111
2018-01-16T18:49:19.000Z
2022-03-13T12:33:54.000Z
NWNXLib/API/Constants/Animation.hpp
summonFox/unified
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
[ "MIT" ]
636
2018-01-17T10:05:31.000Z
2022-03-28T20:06:03.000Z
NWNXLib/API/Constants/Animation.hpp
summonFox/unified
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
[ "MIT" ]
110
2018-01-16T19:05:54.000Z
2022-03-28T03:44:16.000Z
#pragma once #include <cstdint> namespace NWNXLib::API::Constants { namespace Animation { enum TYPE { Pause = 0, Ready = 1, Walking = 2, WalkingBackwards = 3, Running = 4, KnockdownFront = 5, DeadFront = 6, KnockdownButt = 7, DeadButt = 8, Attack = 9, Throw = 10, Dodge = 11, Parry = 12, Shield = 13, Damage = 14, Conjure1 = 15, Conjure2 = 16, Cast1 = 17, Cast2 = 18, Cast3 = 19, Cast4 = 20, Open = 21, Closed = 22, Spasm = 23, CombatStepFront = 24, CombatStepBack = 25, CombatStepLeft = 26, CombatStepRight = 27, Taunt = 28, OverlayGreeting = 29, OverlayListen = 30, Meditate = 32, Worship = 33, OverlaySalute = 34, Bow = 35, Sitting = 36, Steal = 37, OverlayTalkNormal = 38, OverlayTalkPleading = 39, OverlayTalkForceful = 40, OverlayTalkLaugh = 41, CombatStepDummy = 42, AttackDummy = 43, VictoryFighter = 44, VictoryMage = 45, VictoryThief = 46, SitCrossLegs = 47, LookFar = 48, CombatStepDummyFB = 49, Opened1 = 50, Opened2 = 51, Pause2 = 52, HeadTurnLeft = 53, HeadTurnRight = 54, PauseScratchHead = 55, PauseBored = 56, PauseTired = 57, PauseDrunk = 58, GetLow = 59, GetMid = 60, Cast5 = 61, Flown = 62, Arrived = 63, OverlayDrink = 70, OverlayRead = 71, Destroyed = 72, PlaceableActivated = 73, PlaceableDeactivated = 74, PlaceableOpened = 75, PlaceableClosed = 76, DamageStab = 77, WalkingLeft = 78, WalkingRight = 79, TurnOnSpotRight = 80, TurnOnSpotLeft = 81, CombatTurnRight = 82, CombatTurnLeft = 83, WalkingForwardLeft = 84, WalkingForwardRight = 85, RunningForwardLeft = 86, RunningForwardRight = 87, DialogNoAnim = 88, FakeAttack = 89, FakeDodgeSide = 90, FakeDodgeDuck = 91, Whirlwind = 92, SpasmLooping = 93, Flown2 = 94, Arrived2 = 95, CastCreature = 96, Custom1 = 97, Custom2 = 98, DamageLeft = 99, DamageRight = 100, Custom3 = 101, Custom4 = 102, Custom5 = 103, Custom6 = 104, Custom7 = 105, Custom8 = 106, Custom9 = 107, Custom10 = 108, Custom11 = 109, Custom12 = 110, Custom13 = 111, Custom14 = 112, Custom15 = 113, Custom16 = 114, Custom17 = 115, Custom18 = 116, Custom19 = 117, Custom20 = 118, Mount1 = 119, Dismount1 = 120, }; constexpr int32_t MIN = 0; constexpr int32_t MAX = 120; static_assert(MAX == Dismount1); constexpr const char* ToString(const unsigned value) { constexpr const char* TYPE_STRINGS[] = { "Pause", "Ready", "Walking ", "Walking Backwards", "Running", "Knockdown Front", "Dead Front", "Knockdown Butt", "Dead Butt", "Attack", "Throw", "Dodge", "Parry", "Shield", "Damage", "Conjure 1", "Conjure 2", "Cast 1", "Cast 2", "Cast 3", "Cast 4", "Open", "Closed", "Spasm", "Combat Step Front", "Combat Step Back", "Combat Step Left", "Combat Step Right", "Taunt", "Overlay Greeting", "Overlay Listen", "Meditate", "Worship", "Overlay Salute", "Bow", "Sitting", "Steal", "Overlay Talk Normal", "Overlay Talk Pleading", "Overlay Talk Forceful", "Overlay Talk Laugh", "Combat Step Dummy", "Attack Dummy", "Victory Fighter", "Victory Mage", "Victory Thief", "Sit Cross Legs", "Look Far", "Combat Step DummyFB", "Opened 1", "Opened 2", "Pause 2", "Head Turn Left", "Head Turn Right", "Pause ScratchHead", "Pause Bored", "Pause Tired", "Pause Drunk", "Get Low", "Get Mid", "Cast 5", "Flown", "Arrived", "Overlay Drink", "Overlay Read", "Destroyed", "Placeable Activated", "Placeable Deactivated", "Placeable Opened", "Placeable Closed", "Damage Stab", "Walking Left", "Walking Right", "Turn On Spot Right", "Turn On Spot Left", "Combat Turn Right", "Combat Turn Left", "Walking Forward Left", "Walking Forward Right", "Running Forward Left", "Running Forward Right", "Dialog No Animation", "Fake Attack", "Fake Dodge Side", "Fake Dodge Duck", "Whirlwind", "Spasm Looping", "Flown 2", "Arrived 2", "Cast Creature", "Custom 1", "Custom 2", "Damage Left", "Damage Right", "Custom 3", "Custom 4", "Custom 5", "Custom 6", "Custom 7", "Custom 8", "Custom 9", "Custom 10", "Custom 11", "Custom 12", "Custom 13", "Custom 14", "Custom 15", "Custom 16", "Custom 17", "Custom 18", "Custom 19", "Custom 20", "Mount 1", "Dismount 1", }; return (value > MAX) ? "(invalid)" : TYPE_STRINGS[value]; } } }
35.625
65
0.304715
summonFox
67972f21b5fbc149b3213a382ff8c6a7294ff1da
1,169
cpp
C++
apal_cxx/src/polynomial.cpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
null
null
null
apal_cxx/src/polynomial.cpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
15
2019-05-23T07:18:19.000Z
2019-12-17T08:01:10.000Z
apal_cxx/src/polynomial.cpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
null
null
null
#include "polynomial.hpp" #include <stdexcept> #include <sstream> using namespace std; void Polynomial::add_term(double new_coeff, const PolynomialTerm &new_term){ if (new_term.get_dim() != dim){ stringstream ss; ss << "Dimension of new term does not match the dimension "; ss << "of the polynomial. Polynomial dimension: " << dim; ss << " dimension of new term " << new_term.get_dim(); throw invalid_argument(ss.str()); } terms.push_back(new_term); coeff.push_back(new_coeff); } double Polynomial::evaluate(double x[]) const{ double value = 0.0; for (unsigned int i=0;i<terms.size();i++){ value += coeff[i]*terms[i].evaluate(x); } return value; } double Polynomial::deriv(double x[], unsigned int crd) const{ double value = 0.0; for (unsigned int i=0;i<terms.size();i++){ value += coeff[i]*terms[i].deriv(x, crd); } return value; } ostream& operator <<(ostream& out, const Polynomial &instance){ for (unsigned int i=0;i<instance.coeff.size();i++){ out << "Coeff: " << instance.coeff[i] << " " << instance.terms[i] << "\n"; } return out; }
28.512195
82
0.615911
davidkleiven
67988e2cc2901f7e9b1432355d9600b480b06670
4,026
hpp
C++
discovery/l496g/l496gSystem.hpp
shangaoren/bsp
ea05ebee7d897f793587da1c2d0940a9aefcc13d
[ "MIT" ]
1
2018-11-28T08:56:55.000Z
2018-11-28T08:56:55.000Z
discovery/l496g/l496gSystem.hpp
shangaoren/bsp
ea05ebee7d897f793587da1c2d0940a9aefcc13d
[ "MIT" ]
null
null
null
discovery/l496g/l496gSystem.hpp
shangaoren/bsp
ea05ebee7d897f793587da1c2d0940a9aefcc13d
[ "MIT" ]
null
null
null
/*MIT License Copyright (c) 2018 Florian GERARD 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. Except as contained in this notice, the name of Florian GERARD shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Florian GERARD */ #ifdef STM32L496xx #pragma once #include <cstdint> #include "../../../yggdrasil/interfaces/ISystem.hpp" #include "../../../yggdrasil/kernel/Processor.hpp" namespace bsp { namespace discovery { namespace l496g { class System : public interface::ISystem { public : //initialise clock of the board, maximum speed using internal oscillator bool initSystemClock(void) override { //prevent to initialise system a second time if(s_initialised) return false; else s_initialised = true; uint32_t timeout = 100; FLASH->ACR = ((FLASH->ACR & ~(FLASH_ACR_LATENCY_Msk)) | (FLASH_ACR_LATENCY_4WS)); if((FLASH->ACR & FLASH_ACR_LATENCY_Msk) != FLASH_ACR_LATENCY_4WS) return false; PWR->CR1 = ((PWR->CR1 & ~(PWR_CR1_VOS)) | (PWR_CR1_VOS_1)); RCC->CR |= RCC_CR_HSION; timeout = 100; while((RCC->CR & RCC_CR_HSIRDY) != RCC_CR_HSIRDY) { timeout -= 1; if(timeout == 0) return false; } RCC->ICSCR = ((RCC->ICSCR & ~(RCC_ICSCR_HSITRIM)) | (64 << RCC_ICSCR_HSITRIM_Pos)); RCC->CRRCR |= RCC_CRRCR_HSI48ON; timeout = 100; while((RCC->CRRCR & RCC_CRRCR_HSI48RDY) != RCC_CRRCR_HSI48RDY) { timeout -= 1; if(timeout == 0) return false; } RCC->PLLCFGR = ((RCC->PLLCFGR & ~(RCC_PLLCFGR_PLLM | RCC_PLLCFGR_PLLN | RCC_PLLCFGR_PLLSRC | RCC_PLLCFGR_PLLR)) | (RCC_PLLCFGR_PLLSRC_HSI | 20 << RCC_PLLCFGR_PLLN_Pos | RCC_PLLCFGR_PLLR_0)); RCC->PLLCFGR |= RCC_PLLCFGR_PLLREN; RCC->CR |= RCC_CR_PLLON; timeout = 100; while(((RCC->CR & RCC_CR_PLLRDY) != RCC_CR_PLLRDY)) { timeout -= 1; if(timeout == 0) return false; } RCC->CFGR = ((RCC->CFGR & ~(RCC_CFGR_SW)) | (RCC_CFGR_SW_PLL)); timeout -= 100; while(((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL)) { timeout -= 1; if(timeout == 0) return false; } RCC->CFGR = ((RCC->CFGR & ~(RCC_CFGR_HPRE)) | (RCC_CFGR_HPRE_DIV1)); RCC->CFGR = ((RCC->CFGR & ~(RCC_CFGR_PPRE1)) | (RCC_CFGR_PPRE1_DIV1)); RCC->CFGR = ((RCC->CFGR & ~(RCC_CFGR_PPRE2)) | (RCC_CFGR_PPRE2_DIV1)); s_systemCoreClock = 80000000; s_peripheralClock1 = 80000000; s_peripheralClock2 = 80000000; return true; } uint32_t getSystemCoreFrequency() override { return s_systemCoreClock; } uint32_t getPeripheralClock1Frequency() override { return s_peripheralClock1; } uint32_t getPeripheralClock2Frequency() override { return s_peripheralClock2; } static System& instance() { return s_instance; } private: static uint32_t s_systemCoreClock; static uint32_t s_peripheralClock1; static uint32_t s_peripheralClock2; static System s_instance; static bool s_initialised; }; } /* namespace l496g */ } /* namespace discovery */ } /* namespace boards */ #endif /* STM32L496xx */
26.142857
113
0.722305
shangaoren
67a4b7dee66e749e390364275703a894eee4b281
9,494
cpp
C++
src/modules/processes/ImageIntegration/ImageIntegrationProcess.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
src/modules/processes/ImageIntegration/ImageIntegrationProcess.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
src/modules/processes/ImageIntegration/ImageIntegrationProcess.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 2.4.9 // ---------------------------------------------------------------------------- // Standard ImageIntegration Process Module Version 1.2.33 // ---------------------------------------------------------------------------- // ImageIntegrationProcess.cpp - Released 2021-04-09T19:41:48Z // ---------------------------------------------------------------------------- // This file is part of the standard ImageIntegration PixInsight module. // // Copyright (c) 2003-2021 Pleiades Astrophoto S.L. All Rights Reserved. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (https://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS 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 PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) 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 "ImageIntegrationInstance.h" #include "ImageIntegrationInterface.h" #include "ImageIntegrationParameters.h" #include "ImageIntegrationProcess.h" namespace pcl { // ---------------------------------------------------------------------------- ImageIntegrationProcess* TheImageIntegrationProcess = nullptr; // ---------------------------------------------------------------------------- ImageIntegrationProcess::ImageIntegrationProcess() { TheImageIntegrationProcess = this; new IIImages( this ); new IIImageEnabled( TheIIImagesParameter ); new IIImagePath( TheIIImagesParameter ); new IIDrizzlePath( TheIIImagesParameter ); new IILocalNormalizationDataPath( TheIIImagesParameter ); new IIInputHints( this ); new IICombination( this ); new IIWeightMode( this ); new IIWeightKeyword( this ); new IIWeightScale( this ); new IIAdaptiveGridSize( this ); new IIAdaptiveNoScale( this ); new IIIgnoreNoiseKeywords( this ); new IINormalization( this ); new IIRejection( this ); new IIRejectionNormalization( this ); new IIMinMaxLow( this ); new IIMinMaxHigh( this ); new IIPercentileLow( this ); new IIPercentileHigh( this ); new IISigmaLow( this ); new IISigmaHigh( this ); new IIWinsorizationCutoff( this ); new IILinearFitLow( this ); new IILinearFitHigh( this ); new IIESDOutliersFraction( this ); new IIESDAlpha( this ); new IIESDLowRelaxation( this ); new IICCDGain( this ); new IICCDReadNoise( this ); new IICCDScaleNoise( this ); new IIClipLow( this ); new IIClipHigh( this ); new IIRangeClipLow( this ); new IIRangeLow( this ); new IIRangeClipHigh( this ); new IIRangeHigh( this ); new IIMapRangeRejection( this ); new IIReportRangeRejection( this ); new IILargeScaleClipLow( this ); new IILargeScaleClipLowProtectedLayers( this ); new IILargeScaleClipLowGrowth( this ); new IILargeScaleClipHigh( this ); new IILargeScaleClipHighProtectedLayers( this ); new IILargeScaleClipHighGrowth( this ); new IIGenerate64BitResult( this ); new IIGenerateRejectionMaps( this ); new IIGenerateIntegratedImage( this ); new IIGenerateDrizzleData( this ); new IIClosePreviousImages( this ); new IIBufferSize( this ); new IIStackSize( this ); new IIAutoMemorySize( this ); new IIAutoMemoryLimit( this ); new IIUseROI( this ); new IIROIX0( this ); new IIROIY0( this ); new IIROIX1( this ); new IIROIY1( this ); new IIUseCache( this ); new IIEvaluateNoise( this ); new IIMRSMinDataFraction( this ); new IISubtractPedestals( this ); new IITruncateOnOutOfRange( this ); new IINoGUIMessages( this ); new IIShowImages( this ); new IIUseFileThreads( this ); new IIFileThreadOverload( this ); new IIUseBufferThreads( this ); new IIMaxBufferThreads( this ); new IIIntegrationImageId( this ); new IILowRejectionMapImageId( this ); new IIHighRejectionMapImageId( this ); new IISlopeMapImageId( this ); new IINumberOfChannels( this ); new IINumberOfPixels( this ); new IITotalPixels( this ); new IIOutputRangeLow( this ); new IIOutputRangeHigh( this ); new IITotalRejectedLowRK( this ); new IITotalRejectedLowG( this ); new IITotalRejectedLowB( this ); new IITotalRejectedHighRK( this ); new IITotalRejectedHighG( this ); new IITotalRejectedHighB( this ); new IIFinalNoiseEstimateRK( this ); new IIFinalNoiseEstimateG( this ); new IIFinalNoiseEstimateB( this ); new IIFinalScaleEstimateRK( this ); new IIFinalScaleEstimateG( this ); new IIFinalScaleEstimateB( this ); new IIFinalLocationEstimateRK( this ); new IIFinalLocationEstimateG( this ); new IIFinalLocationEstimateB( this ); new IIReferenceNoiseReductionRK( this ); new IIReferenceNoiseReductionG( this ); new IIReferenceNoiseReductionB( this ); new IIMedianNoiseReductionRK( this ); new IIMedianNoiseReductionG( this ); new IIMedianNoiseReductionB( this ); new IIReferenceSNRIncrementRK( this ); new IIReferenceSNRIncrementG( this ); new IIReferenceSNRIncrementB( this ); new IIAverageSNRIncrementRK( this ); new IIAverageSNRIncrementG( this ); new IIAverageSNRIncrementB( this ); new IIImageData( this ); new IIImageWeightRK( TheIIImageDataParameter ); new IIImageWeightG( TheIIImageDataParameter ); new IIImageWeightB( TheIIImageDataParameter ); new IIImageRejectedLowRK( TheIIImageDataParameter ); new IIImageRejectedLowG( TheIIImageDataParameter ); new IIImageRejectedLowB( TheIIImageDataParameter ); new IIImageRejectedHighRK( TheIIImageDataParameter ); new IIImageRejectedHighG( TheIIImageDataParameter ); new IIImageRejectedHighB( TheIIImageDataParameter ); } // ---------------------------------------------------------------------------- IsoString ImageIntegrationProcess::Id() const { return "ImageIntegration"; } // ---------------------------------------------------------------------------- IsoString ImageIntegrationProcess::Category() const { return "ImageIntegration,Preprocessing"; } // ---------------------------------------------------------------------------- uint32 ImageIntegrationProcess::Version() const { return 0x100; } // ---------------------------------------------------------------------------- String ImageIntegrationProcess::Description() const { return ""; } // ---------------------------------------------------------------------------- String ImageIntegrationProcess::IconImageSVGFile() const { return "@module_icons_dir/ImageIntegration.svg"; } // ---------------------------------------------------------------------------- ProcessInterface* ImageIntegrationProcess::DefaultInterface() const { return TheImageIntegrationInterface; } // ------------------------------------------------------------------------- ProcessImplementation* ImageIntegrationProcess::Create() const { return new ImageIntegrationInstance( this ); } // ---------------------------------------------------------------------------- ProcessImplementation* ImageIntegrationProcess::Clone( const ProcessImplementation& p ) const { const ImageIntegrationInstance* instPtr = dynamic_cast<const ImageIntegrationInstance*>( &p ); return (instPtr != nullptr) ? new ImageIntegrationInstance( *instPtr ) : nullptr; } // ---------------------------------------------------------------------------- } // pcl // ---------------------------------------------------------------------------- // EOF ImageIntegrationProcess.cpp - Released 2021-04-09T19:41:48Z
37.231373
97
0.642616
fmeschia
67a5b1080e522ea75b6e93a684906914e5f895d3
1,242
hpp
C++
SDEngine/include/Graphics/OpenGL/GLTranslator.hpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
null
null
null
SDEngine/include/Graphics/OpenGL/GLTranslator.hpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
4
2021-12-10T05:01:49.000Z
2022-03-19T10:16:14.000Z
SDEngine/include/Graphics/OpenGL/GLTranslator.hpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
null
null
null
#ifndef SD_GL_TRANSLATOR_HPP #define SD_GL_TRANSLATOR_HPP #include <GL/glew.h> #include "Utility/Export.hpp" #include "Graphics/Graphics.hpp" namespace SD { GLenum SD_GRAPHICS_API Translate(BufferLayoutType data_type); GLenum SD_GRAPHICS_API Translate(MeshTopology mesh_type); GLenum SD_GRAPHICS_API Translate(PolygonMode mode); GLint SD_GRAPHICS_API Translate(BufferIOType io_type); GLenum SD_GRAPHICS_API Translate(DataFormat format); GLenum SD_GRAPHICS_API Translate(TextureType type, MultiSampleLevel msaa); GLint SD_GRAPHICS_API Translate(TextureWrap wrap); GLint SD_GRAPHICS_API Translate(TextureMagFilter filter); GLint SD_GRAPHICS_API Translate(TextureMinFilter filter, MipmapMode mode); GLenum SD_GRAPHICS_API Translate(Operation operation); GLenum SD_GRAPHICS_API Translate(Face face); GLenum SD_GRAPHICS_API Translate(BlitFilter filter); GLint SD_GRAPHICS_API Translate(BufferBitMask bit); GLenum SD_GRAPHICS_API Translate(DepthFunc depth_func); GLenum SD_GRAPHICS_API Translate(Access access); GLenum SD_GRAPHICS_API Translate(BarrierBit bit); GLenum SD_GRAPHICS_API GetFormatType(DataFormat format); GLenum SD_GRAPHICS_API GetDataType(DataFormat format); } // namespace SD #endif /* SD_GL_TRANSLATOR_HPP */
25.875
74
0.838164
xubury
67a6b7469c6b610e34cabd183d4f9635c40bc796
1,177
cpp
C++
src/events/MyIMUSample.cpp
LinuxDroneLab/MyDrone
33b8e9f15cebf79da0141e4d8aa5f4d57da73b3e
[ "Apache-2.0" ]
2
2021-05-31T09:46:39.000Z
2022-02-17T12:33:43.000Z
src/events/MyIMUSample.cpp
LinuxDroneLab/MyLinuxDrone
33b8e9f15cebf79da0141e4d8aa5f4d57da73b3e
[ "Apache-2.0" ]
17
2018-09-03T05:41:37.000Z
2018-11-15T07:48:20.000Z
src/events/MyIMUSample.cpp
LinuxDroneLab/MyLinuxDrone
33b8e9f15cebf79da0141e4d8aa5f4d57da73b3e
[ "Apache-2.0" ]
null
null
null
/* * MyIMUSample.cpp * * Created on: 17 dic 2015 * Author: andrea */ #include <commons/MyPriority.h> #include <events/MyIMUSample.h> MyIMUSample::MyIMUSample(boost::uuids::uuid origin, boost::math::quaternion<float> q, float yaw, float pitch, float roll, VectorFloat gravity, VectorInt16 accel, VectorInt16 linearAccel) : MyEvent(origin), q(q) { this->setPriority(MyPriority::IMU_SAMPLE_PRIORITY); this->yaw = yaw; this->pitch = pitch; this->roll = roll; this->gravity = gravity; this->accel = accel; this->linearAccel = linearAccel; } MyIMUSample::~MyIMUSample() { // TODO Auto-generated destructor stub } MyEvent::EventType MyIMUSample::getType() const { return MyEvent::EventType::IMUSample; } boost::math::quaternion<float> MyIMUSample::getQuaternion() const { return q; } float MyIMUSample::getYaw() const { return yaw; } float MyIMUSample::getPitch() const { return pitch; } float MyIMUSample::getRoll() const { return roll; } VectorFloat MyIMUSample::getGravity() const { return gravity; } VectorInt16 MyIMUSample::getAccel() const { return accel; } VectorInt16 MyIMUSample::getLinearAccel() const { return linearAccel; }
24.520833
212
0.720476
LinuxDroneLab
67af2745ed3bcb2e5bc1bf5c91c5421c2f4b90f2
2,201
cpp
C++
15/12.cpp
riuri/adventofcode
6e839972162f99a702359f94b275af0d717c7ea3
[ "MIT" ]
1
2021-12-05T16:31:50.000Z
2021-12-05T16:31:50.000Z
15/12.cpp
riuri/adventofcode
6e839972162f99a702359f94b275af0d717c7ea3
[ "MIT" ]
1
2021-12-05T18:27:26.000Z
2021-12-05T18:54:06.000Z
15/12.cpp
riuri/adventofcode
6e839972162f99a702359f94b275af0d717c7ea3
[ "MIT" ]
null
null
null
#include <iostream> #include <queue> #include <set> #include <string> #include <tuple> #include <vector> using namespace std; typedef pair<int, int> Location; bool valid(Location l, int size) { return l.first >= 0 && l.second >= 0 && l.first < size && l.second < size; } int astar(Location l, int size) { return 2 * size - l.first - l.second - 2; } Location neighbour(Location l, int i) { int v[] = {1, 0, -1, 0}; return {l.first + v[i], l.second + v[(i + 3) % 4]}; } typedef tuple<int, int, Location> GraphState; int astar(vector<vector<int>> risk) { Location end(risk.size() - 1, risk.size() - 1); priority_queue<GraphState, vector<GraphState>, greater<GraphState>> pq; set<Location> visited; pq.emplace(risk.size() * 2 - 2, 0, Location{0, 0}); while (!pq.empty()) { auto [_, cost, cur] = pq.top(); pq.pop(); if (visited.contains(cur)) { continue; } visited.insert(cur); if (cur == end) { return cost; } for (int i = 0; i < 4; ++i) { Location neigh = neighbour(cur, i); if (!valid(neigh, risk.size())) { continue; } if (visited.contains(neigh)) { continue; } int next_cost = cost + risk[neigh.first][neigh.second]; pq.emplace(astar(neigh, risk.size()) + next_cost, next_cost, neigh); } } return -1; } int main() { vector<vector<int>> risk, increased_risk; string cur; while (cin >> cur) { vector<int> row, increased_row; for (size_t i = 0; i < cur.size(); ++i) { row.push_back(cur[i] - '0'); } risk.push_back(row); increased_row = row; for (int i = 0; i < 4; ++i) { for (size_t j = 0; j < row.size(); ++j) { increased_row.push_back((row[j] + i) % 9 + 1); } } increased_risk.push_back(increased_row); } for (int i = 0; i < 4; ++i) { for (size_t j = 0; j < risk.size(); ++j) { vector<int> increased_row; for (size_t k = 0; k < increased_risk[j].size(); ++k) { increased_row.push_back((increased_risk[j][k] + i) % 9 + 1); } increased_risk.push_back(increased_row); } } cout << astar(risk) << endl; cout << astar(increased_risk) << endl; return 0; }
25.011364
77
0.567015
riuri
67b1f6621765e44dbd391fd1bae723a9755202d8
4,745
cpp
C++
tests/xrt/11_fp_mmult256/main.cpp
pranjalv-xilinx/XRT
34e2ac16e9368c887a271959d1bb5778913e6a1c
[ "Apache-2.0" ]
1
2020-09-24T09:43:25.000Z
2020-09-24T09:43:25.000Z
tests/xrt/11_fp_mmult256/main.cpp
pranjalv-xilinx/XRT
34e2ac16e9368c887a271959d1bb5778913e6a1c
[ "Apache-2.0" ]
4
2021-04-14T22:58:18.000Z
2021-04-18T07:04:11.000Z
tests/xrt/11_fp_mmult256/main.cpp
pranjalv-xilinx/XRT
34e2ac16e9368c887a271959d1bb5778913e6a1c
[ "Apache-2.0" ]
3
2021-03-12T00:39:52.000Z
2021-03-25T20:42:22.000Z
/** * Copyright (C) 2016-2020 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located 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 <iostream> #include <stdexcept> #include <string> #include <cstring> #include <ctime> #include <chrono> #include "experimental/xrt_device.h" #include "experimental/xrt_kernel.h" #include "experimental/xrt_bo.h" #ifdef _WIN32 # pragma warning ( disable : 4244 ) #endif static const int size = 256; int data_size = size*size; /** * Runs an OpenCL kernel which writes known 16 integers into a 64 byte * buffer. Does not use OpenCL runtime but directly exercises the HAL * driver API. */ static void usage() { std::cout << "usage: %s [options] -k <bitstream>\n\n"; std::cout << " -s <hal_driver>\n"; std::cout << " -k <bitstream>\n"; std::cout << " -d <index>\n"; std::cout << " -r Random input data.\n"; std::cout << " -v\n"; std::cout << " -h\n\n"; std::cout << "* Bitstream is required\n"; } static void run(xrt::device& device, const xrt::uuid& uuid, bool random, bool verbose) { auto mmult = xrt::kernel(device, uuid.get(), "mmult"); auto a = xrt::bo(device, 2*data_size*sizeof(float), mmult.group_id(0)); auto output = xrt::bo(device, data_size*sizeof(float), mmult.group_id(1)); auto a_mapped = a.map<float*>(); std::cout << "Populate the input and reference vectors.\n"; const int MY_MAX = 4096; float A[size][size], B[size][size], C[size*size]; std::srand(std::time(0)); for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { A[i][j] = random ? static_cast<float>(std::rand()) / (static_cast<float>(RAND_MAX/MY_MAX)):(float)(i+j); B[i][j] = random ? static_cast<float>(std::rand()) / (static_cast<float>(RAND_MAX/MY_MAX)):(float)(i+j); } } for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { C[i*size+j] = 0.0; for (int k = 0; k < size; ++k) { C[i*size+j] += A[i][k] * B[k][j]; } } } std::memcpy(a_mapped, A, data_size*sizeof(float)); std::memcpy(a_mapped + data_size, B, data_size*sizeof(float)); // Send the input data to the device memory std::cout << "Send the input data to the device memory.\n"; a.sync(XCL_BO_SYNC_BO_TO_DEVICE , 2*data_size*sizeof(float), 0); // Run kernel auto run = mmult(a, output, 1); run.wait(); //Get the output; std::cout << "Get the output data from the device" << std::endl; output.sync(XCL_BO_SYNC_BO_FROM_DEVICE, data_size*sizeof(float), 0); auto output_mapped = output.map<float*>(); // Validate FPGA results int err = 0; for (int i = 0; i < size * size; i++) { bool bShow = verbose; if (C[i] != output_mapped[i]) { bShow = true; // always show errors err++; } if (bShow) std::cout<< std::hex << i << " : " << std::fixed << C[i] << " vs " << output_mapped[i] << "\n"; } if (err) throw std::runtime_error("mismatch count = " + std::to_string(err)); } int run(int argc, char** argv) { if (argc < 3) { usage(); return 1; } std::string xclbin_fnm; bool verbose = false; unsigned int device_index = 0; bool random = false; std::vector<std::string> args(argv+1,argv+argc); std::string cur; for (auto& arg : args) { if (arg == "-h") { usage(); return 1; } else if (arg == "-v") { verbose = true; continue; } else if (cur == "-r") { random = true; continue; } if (arg[0] == '-') { cur = arg; continue; } if (cur == "-k") xclbin_fnm = arg; else if (cur == "-d") device_index = std::stoi(arg); else throw std::runtime_error("Unknown option value " + cur + " " + arg); } if (xclbin_fnm.empty()) throw std::runtime_error("FAILED_TEST\nNo xclbin specified"); auto device = xrt::device(device_index); auto uuid = device.load_xclbin(xclbin_fnm); run(device, uuid, random, verbose); return 0; } int main(int argc, char** argv) { try { auto ret = run(argc, argv); std::cout << "PASSED TEST\n"; return ret; } catch (std::exception const& e) { std::cout << "Exception: " << e.what() << "\n"; std::cout << "FAILED TEST\n"; return 1; } std::cout << "PASSED TEST\n"; return 0; }
25.510753
111
0.598946
pranjalv-xilinx
67b4025f7be4405802f041b3b7ff6d6a4b44ceed
292
hpp
C++
include/daqi/redis-client/redis_command.hpp
hl4/da4qi4
9dfb8902427d40b392977b4fd706048ce3ee8828
[ "Apache-2.0" ]
166
2019-04-15T03:19:31.000Z
2022-03-26T05:41:12.000Z
include/daqi/redis-client/redis_command.hpp
YangKefan/da4qi4
9dfb8902427d40b392977b4fd706048ce3ee8828
[ "Apache-2.0" ]
9
2019-07-18T06:09:59.000Z
2021-01-27T04:19:04.000Z
include/daqi/redis-client/redis_command.hpp
YangKefan/da4qi4
9dfb8902427d40b392977b4fd706048ce3ee8828
[ "Apache-2.0" ]
43
2019-07-03T05:41:57.000Z
2022-02-24T14:16:09.000Z
#ifndef DAQI_REDIS_COMMAND_HPP #define DAQI_REDIS_COMMAND_HPP #include <vector> #include <deque> #include "daqi/redis-client/redis_buffer.hpp" namespace da4qi4 { std::vector<char> MakeCommand(std::deque<RedisBuffer> const& items); } // namespace da4qi4 #endif // DAQI_REDIS_COMMAND_HPP
17.176471
68
0.780822
hl4
67b418311db0ecf4386a8cc75d5ddca7aced6f14
145
cpp
C++
ForEach/ForEach.cpp
renatoas77/CursoDeCMaisPlus
232efee2dba211dd9d001701aa5207f929934948
[ "MIT" ]
null
null
null
ForEach/ForEach.cpp
renatoas77/CursoDeCMaisPlus
232efee2dba211dd9d001701aa5207f929934948
[ "MIT" ]
null
null
null
ForEach/ForEach.cpp
renatoas77/CursoDeCMaisPlus
232efee2dba211dd9d001701aa5207f929934948
[ "MIT" ]
null
null
null
#include <iostream> int main() { for (auto Ano : { 1998,2011,2014,2017,2020 }) { std::cout << Ano << "\n"; } system("PAUSE"); return 0; }
13.181818
46
0.558621
renatoas77
67b804cdd61a2b6e2ce5c23eaed90b09e4e334e1
31,064
cpp
C++
src/WEDMap/WED_MapPane.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
src/WEDMap/WED_MapPane.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
src/WEDMap/WED_MapPane.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
/* * Copyright (c) 2007, Laminar Research. * * 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 "WED_MapPane.h" #include "WED_Archive.h" #include "WED_Menus.h" #include "GUI_ToolBar.h" #include "XESConstants.h" #include "IGIS.h" #include "ISelection.h" #include "WED_Thing.h" #include "WED_Map.h" #include "WED_MapBkgnd.h" #include "WED_ToolUtils.h" #include "WED_MarqueeTool.h" #include "WED_CreateBoxTool.h" #if AIRPORT_ROUTING #include "WED_CreateEdgeTool.h" #endif #include "WED_CreatePolygonTool.h" #include "WED_CreatePointTool.h" #include "WED_CreateLineTool.h" #include "WED_StructureLayer.h" #include "WED_ATCLayer.h" #include "WED_WorldMapLayer.h" #include "WED_PreviewLayer.h" #include "WED_DebugLayer.h" #include "WED_VertexTool.h" //#include "WED_TileServerLayer.h" #include "WED_TerraserverLayer.h" #include "GUI_Fonts.h" #include "GUI_Table.h" #include "GUI_TextTable.h" #include "WED_Colors.h" #include "GUI_Resources.h" #include "WED_ToolInfoAdapter.h" #include "WED_UIMeasurements.h" #include "WED_GroupCommands.h" #include "WED_LibraryListAdapter.h" #include "WED_LibraryMgr.h" #include "IDocPrefs.h" #include "WED_Orthophoto.h" #if WITHNWLINK #include "WED_Document.h" #include "WED_Server.h" #include "WED_NWInfoLayer.h" #endif char kToolKeys[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'b', 0, 'a', 'o', 'e', 'w', 'f', 'g', 'l', 'k', 'h', 't', 'r', 's', 'v', 'm' }; // A bit of a hack...zoom to selection sets the zoom so that the screen is filled with the sel. If the sel size is 0 in both // dimensions, our zoom is NaN, which is bad. But try telling that to users! // // So....IF the selected entity is a point AND it doesn't have an overloaded bounds that gives it some thickness, we apply this // extra padding (in meters) around it. The result is that we always zoom out enough to show 50 meters around point objects. // In practice this should be okay - you probably want to see SOME of what's happening, and padding a small distance around your // airport when you have perimeter objects isn't going to kill anything. We can tune the dimensions as desired. #define PAD_POINTS_FOR_ZOOM_MTR 50.0 static void GetExtentAll(Bbox2& box, IResolver * resolver) { box = Bbox2(); WED_Thing * wrl = WED_GetWorld(resolver); IGISEntity * ent = dynamic_cast<IGISEntity *>(wrl); if (ent) ent->GetBounds(gis_Geo,box); } static int accum_box(ISelectable * who, void * ref) { Bbox2 * total = (Bbox2 *) ref; IGISEntity * ent = dynamic_cast<IGISEntity *>(who); if (ent) { Bbox2 ent_box; ent->GetBounds(gis_Geo,ent_box); GISClass_t gc = ent->GetGISClass(); if(gc == gis_Point || gc == gis_Point_Bezier || gc == gis_Point_Heading) { if(ent_box.is_empty()) { double lat = ent_box.ymin(); double MTR_TO_DEG_LON = MTR_TO_DEG_LAT * cos(lat * DEG_TO_RAD); ent_box.expand(PAD_POINTS_FOR_ZOOM_MTR * MTR_TO_DEG_LON,PAD_POINTS_FOR_ZOOM_MTR * MTR_TO_DEG_LAT); } } if(!ent_box.is_null()) *total += ent_box; } return 0; } static void GetExtentSel(Bbox2& box, IResolver * resolver) { box = Bbox2(); ISelection * sel = WED_GetSelect(resolver); sel->IterateSelectionOr(accum_box,&box); } WED_MapPane::WED_MapPane(GUI_Commander * cmdr, double map_bounds[4], IResolver * resolver, WED_Archive * archive, WED_LibraryListAdapter * library) : mResolver(resolver) { this->SetBkgkndImage("gradient.png"); mMap = new WED_Map(resolver); // Visualization layers mLayers.push_back( new WED_MapBkgnd(mMap, mMap, resolver)); mLayers.push_back(mWorldMap = new WED_WorldMapLayer(mMap, mMap, resolver)); #if WANT_TERRASEVER mLayers.push_back(mTerraserver = new WED_TerraserverLayer(mMap, mMap, resolver)); #endif mLayers.push_back(mStructureLayer = new WED_StructureLayer(mMap, mMap, resolver)); mLayers.push_back(mATCLayer = new WED_ATCLayer(mMap, mMap, resolver)); mLayers.push_back(mPreview = new WED_PreviewLayer(mMap, mMap, resolver)); // mLayers.push_back(mTileserver = new WED_TileServerLayer(mMap, mMap, resolver)); mLayers.push_back( new WED_DebugLayer(mMap, mMap, resolver)); #if WITHNWLINK WED_NWLinkAdapter * nwlink = (dynamic_cast<WED_Document *>(resolver))->GetNWLink(); if(nwlink) { mLayers.push_back(mNWInfoLayer = new WED_NWInfoLayer(mMap, mMap, resolver,nwlink)); nwlink->AddListener(mNWInfoLayer); } #endif // TOOLS mTools.push_back( new WED_CreatePointTool("Truck Parking", mMap, mMap, resolver, archive, create_TruckParking)); mTools.push_back( new WED_CreatePointTool("Truck Destination", mMap, mMap, resolver, archive, create_TruckDestination)); mTools.push_back( new WED_CreateBoxTool("Exclusions",mMap, mMap, resolver, archive, create_Exclusion)); #if ROAD_EDITING mTools.push_back( new WED_CreateEdgeTool("Roads",mMap, mMap, resolver, archive, create_Road)); #else mTools.push_back( NULL); #endif mTools.push_back(mLinTool= new WED_CreatePolygonTool("Lines",mMap, mMap, resolver, archive, create_Line)); mTools.push_back(mPolTool= new WED_CreatePolygonTool("Polygons",mMap, mMap, resolver, archive, create_Polygon)); mTools.push_back(mFstTool= new WED_CreatePolygonTool("Forests",mMap, mMap, resolver, archive, create_Forest)); mTools.push_back(mStrTool= new WED_CreatePolygonTool("Strings",mMap, mMap, resolver, archive, create_String)); mTools.push_back(mObjTool= new WED_CreatePointTool("Objects",mMap, mMap, resolver, archive, create_Object)); mTools.push_back(mFacTool= new WED_CreatePolygonTool("Facades",mMap, mMap, resolver, archive, create_Facade)); mTools.push_back( new WED_CreatePolygonTool("Boundary",mMap, mMap, resolver, archive, create_Boundary)); #if AIRPORT_ROUTING mTools.push_back( new WED_CreateEdgeTool("Taxi Routes",mMap, mMap, resolver, archive, create_TaxiRoute)); #else mTools.push_back( NULL); #endif mTools.push_back( new WED_CreatePointTool("Tower Viewpoint", mMap, mMap, resolver, archive, create_TowerViewpoint)); mTools.push_back( new WED_CreatePointTool("Ramp Start", mMap, mMap, resolver, archive, create_RampStart)); mTools.push_back( new WED_CreatePointTool("Airport Beacon", mMap, mMap, resolver, archive, create_Beacon)); mTools.push_back( new WED_CreatePointTool("Windsock", mMap, mMap, resolver, archive, create_Windsock)); mTools.push_back( new WED_CreatePointTool("Light Fixture", mMap, mMap, resolver, archive, create_Lights)); mTools.push_back( new WED_CreatePointTool("Sign", mMap, mMap, resolver, archive, create_Sign)); mTools.push_back( new WED_CreatePolygonTool("Taxilines",mMap, mMap, resolver, archive, create_Marks)); mTools.push_back( new WED_CreatePolygonTool("Hole",mMap, mMap, resolver, archive, create_Hole)); mTools.push_back( new WED_CreatePointTool("Helipad", mMap, mMap, resolver, archive, create_Helipad)); mTools.push_back( new WED_CreatePolygonTool("Taxiway",mMap, mMap, resolver, archive, create_Taxi)); mTools.push_back( new WED_CreateLineTool("Runway", mMap, mMap, resolver, archive, create_Runway)); mTools.push_back( new WED_CreateLineTool("Sealane", mMap, mMap, resolver, archive, create_Sealane)); mTools.push_back( new WED_VertexTool("Vertex",mMap, mMap, resolver, 1)); mTools.push_back( new WED_MarqueeTool("Marquee",mMap, mMap, resolver)); mInfoAdapter = new WED_ToolInfoAdapter(GUI_GetImageResourceHeight("property_bar.png") / 2); mTextTable = new GUI_TextTable(cmdr,10,0); mTable = new GUI_Table(1); mTextTable->SetColors( WED_Color_RGBA(wed_Table_Gridlines), WED_Color_RGBA(wed_Table_Select), WED_Color_RGBA(wed_Table_Text), WED_Color_RGBA(wed_PropertyBar_Text), WED_Color_RGBA(wed_Table_Drag_Insert), WED_Color_RGBA(wed_Table_Drag_Into)); mTextTable->SetFont(font_UI_Small); mTable->SetGeometry(mInfoAdapter); mTable->SetContent(mTextTable); mTextTable->SetProvider(mInfoAdapter); // mTable->SetParent(this); // mTable->Show(); mTable->SizeShowAll(); mTextTable->SetParentTable(mTable); // mTable->SetSticky(1,0,1,1); // this->PackPane(mTable, gui_Pack_Top); mTextTable->AddListener(mTable); mTextTable->SetImage("property_bar.png", 2); mInfoAdapter->AddListener(mTable); mToolbar = new GUI_ToolBar(2,13,"map_tools.png"); mToolbar->SizeToBitmap(); mToolbar->Show(); mToolbar->SetParent(this); mToolbar->SetSticky(1,0,0,1); this->PackPane(mToolbar,gui_Pack_Left); mToolbar->SizeToBitmap(); mToolbar->AddListener(this); vector<string> tips; for (int n = 0; n < mTools.size(); ++n) { string tip(mTools[n] ? mTools[n]->GetToolName() : string()); if (kToolKeys[n]) { char buf[5] = { " [x]" }; buf[2] = toupper(kToolKeys[n]); tip += buf; } tips.push_back(tip); if(mTools[n] == NULL) mToolbar->DisableTool(n); } mToolbar->SetToolTips(tips); GUI_ScrollerPane * map_scroller = new GUI_ScrollerPane(1,1); map_scroller->SetParent(this); map_scroller->Show(); map_scroller->SetSticky(1,1,1,1); this->PackPane(map_scroller, gui_Pack_Center); mMap->SetParent(map_scroller); mMap->Show(); map_scroller->PositionInContentArea(mMap); map_scroller->SetContent(mMap); // mMap->SetMapVisibleBounds(map_bounds[0], map_bounds[1], map_bounds[2], map_bounds[3]); mMap->SetMapLogicalBounds(map_bounds[0], map_bounds[1], map_bounds[2], map_bounds[3]); mMap->ZoomShowAll(); for(vector<WED_MapLayer *>::iterator l = mLayers.begin(); l != mLayers.end(); ++l) mMap->AddLayer(*l); for(vector<WED_MapToolNew *>::iterator t = mTools.begin(); t != mTools.end(); ++t) if(*t) mMap->AddLayer(*t); mMap->SetTool(mTools[0]); mInfoAdapter->SetTool(mTools[0]); mToolbar->SetValue(mTools.size()-2); // This is a bit of a hack. The archive provides whole-doc "changed" messages at the minimum global times: // 1. On the commit of any operation. // 2. On the undo or redo of any operation. // So ... for lack of a better idea right now, we simply broker a connection between the source opf these // messages (secretly it's our document's GetArchive() member) and anyone who needs it (our map). archive->AddListener(mMap); // This is a band-aid. We don't restore the current tab in the tab hierarchy (as of WED 1.5) so we don't get a tab changed message. Instead we just // are always in the selection tab. So mostly that means the defaults for things like filters are fine, but for the ATC layer it needs to be off! mATCLayer->ToggleVisible(); } GUI_Pane * WED_MapPane::GetTopBar(void) { return mTable; } WED_MapPane::~WED_MapPane() { for(vector<WED_MapLayer *>::iterator l = mLayers.begin(); l != mLayers.end(); ++l) delete *l; for(vector<WED_MapToolNew *>::iterator t = mTools.begin(); t != mTools.end(); ++t) if(*t) delete *t; delete mTextTable; delete mInfoAdapter; } void WED_MapPane::SetResource(const string& r, int res_type) { switch(res_type) { case res_Object: mObjTool->SetResource(r); mToolbar->SetValue(distance(mTools.begin(),find(mTools.begin(),mTools.end(),mObjTool))); break; case res_Facade: mFacTool->SetResource(r); mToolbar->SetValue(distance(mTools.begin(),find(mTools.begin(),mTools.end(),mFacTool))); break; case res_Forest: mFstTool->SetResource(r); mToolbar->SetValue(distance(mTools.begin(),find(mTools.begin(),mTools.end(),mFstTool))); break; case res_String: mStrTool->SetResource(r); mToolbar->SetValue(distance(mTools.begin(),find(mTools.begin(),mTools.end(),mStrTool))); break; case res_Line: mLinTool->SetResource(r); mToolbar->SetValue(distance(mTools.begin(),find(mTools.begin(),mTools.end(),mLinTool))); break; case res_Polygon: mPolTool->SetResource(r); mToolbar->SetValue(distance(mTools.begin(),find(mTools.begin(),mTools.end(),mPolTool))); break; } } void WED_MapPane::ZoomShowAll(void) { // double l,b,r,t; // mMap->GetMapLogicalBounds(l,b,r,t); // mMap->SetAspectRatio(1.0 / cos((b+t) * 0.5 * DEG_TO_RAD)); mMap->ZoomShowAll(); } void WED_MapPane::ZoomShowSel(void) { Bbox2 box; GetExtentSel(box, mResolver); if(!box.is_empty() && !box.is_null()) mMap->ZoomShowArea(box.p1.x(),box.p1.y(),box.p2.x(),box.p2.y()); mMap->Refresh(); } int WED_MapPane::Map_KeyPress(uint32_t inKey, int inVK, GUI_KeyFlags inFlags) { if (mMap->HandleKeyPress(inKey, inVK, inFlags)) return 1; if ((inFlags & (gui_ShiftFlag | gui_OptionAltFlag | gui_ControlFlag)) == 0) for (int n = 0; n < sizeof(kToolKeys) / sizeof(kToolKeys[0]); ++n) if (kToolKeys[n]) if (kToolKeys[n]==inKey) { mToolbar->SetValue(n); return 1; } return 0; } int WED_MapPane::Map_HandleCommand(int command) { Bbox2 box; switch(command) { case wed_ImportOrtho: WED_MakeOrthos(mResolver, mMap); return 1; case wed_PickOverlay: WED_DoMakeNewOverlay(mResolver, mMap); return 1; case wed_ToggleWorldMap:mWorldMap->ToggleVisible(); return 1; // case wed_ToggleOverlay: if (mImageOverlay->CanShow()) { mImageOverlay->ToggleVisible(); return 1; } #if WANT_TERRASEVER case wed_ToggleTerraserver: mTerraserver->ToggleVisible(); return 1; #endif // case wed_ToggleTileserver: mTileserver->ToggleVis(); return 1; case wed_TogglePreview: mPreview->ToggleVisible(); return 1; case wed_Pavement0: mPreview->SetPavementTransparency(0.0f); return 1; case wed_Pavement25: mPreview->SetPavementTransparency(0.25f); return 1; case wed_Pavement50: mPreview->SetPavementTransparency(0.5f); return 1; case wed_Pavement75: mPreview->SetPavementTransparency(0.75f); return 1; case wed_Pavement100: mPreview->SetPavementTransparency(1.0f); return 1; case wed_ObjDensity1: mPreview->SetObjDensity(1); return 1; case wed_ObjDensity2: mPreview->SetObjDensity(2); return 1; case wed_ObjDensity3: mPreview->SetObjDensity(3); return 1; case wed_ObjDensity4: mPreview->SetObjDensity(4); return 1; case wed_ObjDensity5: mPreview->SetObjDensity(5); return 1; case wed_ObjDensity6: mPreview->SetObjDensity(6); return 1; case wed_ToggleLines: mStructureLayer->SetRealLinesShowing(!mStructureLayer->GetRealLinesShowing()); return 1; case wed_ToggleVertices:mStructureLayer->SetVerticesShowing(!mStructureLayer->GetVerticesShowing()); return 1; case wed_ZoomWorld: mMap->ZoomShowArea(-180,-90,180,90); mMap->Refresh(); return 1; case wed_ZoomAll: GetExtentAll(box, mResolver); mMap->ZoomShowArea(box.p1.x(),box.p1.y(),box.p2.x(),box.p2.y()); mMap->Refresh(); return 1; case wed_ZoomSelection: GetExtentSel(box, mResolver); mMap->ZoomShowArea(box.p1.x(),box.p1.y(),box.p2.x(),box.p2.y()); mMap->Refresh(); return 1; default: return 0; } } int WED_MapPane::Map_CanHandleCommand(int command, string& ioName, int& ioCheck) { Bbox2 box; switch(command) { case wed_PickOverlay: return 1; case wed_ToggleWorldMap:ioCheck = mWorldMap->IsVisible(); return 1; // case wed_ToggleOverlay: if (mImageOverlay->CanShow()) { ioCheck = mImageOverlay->IsVisible(); return 1; } break; #if WANT_TERRASEVER case wed_ToggleTerraserver: ioCheck = mTerraserver->IsVisible(); return 1; #endif // case wed_ToggleTileserver: ioCheck = mTileserver->IsVis(); return 1; case wed_TogglePreview: ioCheck = mPreview->IsVisible(); return 1; case wed_Pavement0: ioCheck = mPreview->GetPavementTransparency() == 0.0f; return 1; case wed_Pavement25: ioCheck = mPreview->GetPavementTransparency() == 0.25f; return 1; case wed_Pavement50: ioCheck = mPreview->GetPavementTransparency() == 0.5f; return 1; case wed_Pavement75: ioCheck = mPreview->GetPavementTransparency() == 0.75f; return 1; case wed_Pavement100: ioCheck = mPreview->GetPavementTransparency() == 1.0f; return 1; case wed_ObjDensity1: ioCheck = mPreview->GetObjDensity() == 1; return 1; case wed_ObjDensity2: ioCheck = mPreview->GetObjDensity() == 2; return 1; case wed_ObjDensity3: ioCheck = mPreview->GetObjDensity() == 3; return 1; case wed_ObjDensity4: ioCheck = mPreview->GetObjDensity() == 4; return 1; case wed_ObjDensity5: ioCheck = mPreview->GetObjDensity() == 5; return 1; case wed_ObjDensity6: ioCheck = mPreview->GetObjDensity() == 6; return 1; case wed_ToggleLines: ioCheck = mStructureLayer->GetRealLinesShowing(); return 1; case wed_ToggleVertices:ioCheck = mStructureLayer->GetVerticesShowing(); return 1; case wed_ZoomWorld: return 1; case wed_ZoomAll: GetExtentAll(box, mResolver); return !box.is_empty() && !box.is_null(); case wed_ZoomSelection: GetExtentSel(box, mResolver); return !box.is_empty() && !box.is_null(); default: return 0; } return 0; } void WED_MapPane::ReceiveMessage( GUI_Broadcaster * inSrc, intptr_t inMsg, intptr_t inParam) { if(inSrc == mToolbar) { int i = mToolbar->GetValue(); WED_MapToolNew * t = NULL; if (i >= 0 && i < mTools.size()) t = mTools[i]; mMap->SetTool(t); mInfoAdapter->SetTool(t); } else { SetTabFilterMode(inParam); } } void WED_MapPane::FromPrefs(IDocPrefs * prefs) { if ((mWorldMap->IsVisible() ? 1 : 0) != prefs->ReadIntPref("map/world_map_vis", mWorldMap->IsVisible() ? 1 : 0)) mWorldMap->ToggleVisible(); #if WANT_TERRASEVER if ((mTerraserver->IsVisible () ? 1 : 0) != prefs->ReadIntPref("map/terraserver_vis",mTerraserver->IsVisible() ? 1 : 0)) mTerraserver->ToggleVisible(); #endif if ((mPreview->IsVisible () ? 1 : 0) != prefs->ReadIntPref("map/preview_vis" ,mPreview->IsVisible() ? 1 : 0)) mPreview->ToggleVisible(); mPreview->SetPavementTransparency(prefs->ReadIntPref("map/pavement_alpha",mPreview->GetPavementTransparency()*4) * 0.25f); mPreview->SetObjDensity(prefs->ReadIntPref("map/obj_density",mPreview->GetObjDensity())); mStructureLayer->SetRealLinesShowing( prefs->ReadIntPref("map/real_lines_vis",mStructureLayer->GetRealLinesShowing() ? 1 : 0) != 0); mStructureLayer->SetVerticesShowing( prefs->ReadIntPref("map/vertices_vis", mStructureLayer->GetVerticesShowing() ? 1 : 0) != 0); double w,s,e,n; mMap->GetMapVisibleBounds(w,s,e,n); mMap->ZoomShowArea( prefs->ReadDoublePref("map/west" ,w), prefs->ReadDoublePref("map/south",s), prefs->ReadDoublePref("map/east", e), prefs->ReadDoublePref("map/north",n)); for (int t = 0; t < mTools.size(); ++t) if(mTools[t]) { int pc = mTools[t]->CountProperties(); for (int p = 0; p < pc; ++p) { PropertyInfo_t inf; PropertyVal_t val; mTools[t]->GetNthPropertyInfo(p,inf); string key = "map_"; key += mTools[t]->GetToolName(); key += "_"; key += inf.prop_name; string v; string::size_type s, e; v = prefs->ReadStringPref(key.c_str(),string()); if (!v.empty()) { val.prop_kind = inf.prop_kind; switch(inf.prop_kind) { case prop_Int: case prop_Bool: case prop_Enum: val.int_val = atoi(v.c_str()); break; case prop_Double: val.double_val = atoi(v.c_str()); break; case prop_String: case prop_FilePath: case prop_TaxiSign: val.string_val = v; break; case prop_EnumSet: s = 0; do { e = v.find(',',s); val.set_val.insert(atoi(v.c_str() + s)); if (e != v.npos) s = e + 1; } while (e != v.npos); break; } mTools[t]->SetNthProperty(p,val); } } } } void WED_MapPane::ToPrefs(IDocPrefs * prefs) { prefs->WriteIntPref("map/world_map_vis",mWorldMap->IsVisible() ? 1 : 0); #if WANT_TERRASEVER prefs->WriteIntPref("map/terraserver_vis",mTerraserver->IsVisible() ? 1 : 0); #endif prefs->WriteIntPref("map/preview_vis",mPreview->IsVisible() ? 1 : 0); prefs->WriteIntPref("map/pavement_alpha",mPreview->GetPavementTransparency()*4); prefs->WriteIntPref("map/obj_density",mPreview->GetObjDensity()); //prefs->WriteIntPref("map/atc_vis", mATCLayer->IsVisible() ? 1 : 0); prefs->WriteIntPref("map/real_lines_vis",mStructureLayer->GetRealLinesShowing() ? 1 : 0); prefs->WriteIntPref("map/vertices_vis",mStructureLayer->GetVerticesShowing() ? 1 : 0); double w,s,e,n; mMap->GetMapVisibleBounds(w,s,e,n); prefs->WriteDoublePref("map/west" ,w); prefs->WriteDoublePref("map/south",s); prefs->WriteDoublePref("map/east", e); prefs->WriteDoublePref("map/north",n); for (int t = 0; t < mTools.size(); ++t) if(mTools[t]) { int pc = mTools[t]->CountProperties(); for (int p = 0; p < pc; ++p) { PropertyInfo_t inf; PropertyVal_t val; mTools[t]->GetNthPropertyInfo(p,inf); mTools[t]->GetNthProperty(p,val); string key = "map_"; key += mTools[t]->GetToolName(); key += "_"; key += inf.prop_name; string v; char buf[256]; switch(val.prop_kind) { case prop_Int: case prop_Bool: case prop_Enum: sprintf(buf,"%d",val.int_val); v = buf; break; case prop_Double: sprintf(buf,"%lf",val.double_val); v = buf; break; case prop_String: case prop_FilePath: case prop_TaxiSign: v = val.string_val; break; case prop_EnumSet: for (set<int>::iterator it = val.set_val.begin(); it != val.set_val.end(); ++it) { if (!v.empty()) v += ","; sprintf(buf,"%d",*it); v += buf; } break; } prefs->WriteStringPref(key.c_str(),v); } } } //--Tab Modes---------------------------------------------------------------- #include "WED_AirportSign.h" #include "WED_AirportBeacon.h" #include "WED_AirportBoundary.h" #include "WED_AirportChain.h" #include "WED_Ring.h" #include "WED_AirportNode.h" #include "WED_AirportSign.h" #include "WED_Helipad.h" #include "WED_KeyObjects.h" #include "WED_LightFixture.h" #include "WED_ObjPlacement.h" #include "WED_RampPosition.h" #include "WED_Root.h" #include "WED_Runway.h" #include "WED_RunwayNode.h" #include "WED_Sealane.h" #include "WED_Select.h" #include "WED_Taxiway.h" #include "WED_TowerViewpoint.h" #include "WED_Windsock.h" #include "WED_ATCFrequency.h" #include "WED_TextureNode.h" #include "WED_TextureBezierNode.h" #include "WED_OverlayImage.h" #include "WED_SimpleBoundaryNode.h" #include "WED_SimpleBezierBoundaryNode.h" #include "WED_LinePlacement.h" #include "WED_StringPlacement.h" #include "WED_ForestPlacement.h" #include "WED_FacadePlacement.h" #include "WED_PolygonPlacement.h" #include "WED_DrapedOrthophoto.h" #include "WED_ExclusionZone.h" #include "WED_ForestRing.h" #include "WED_FacadeRing.h" #include "WED_FacadeNode.h" #include "WED_TaxiRoute.h" #include "WED_TaxiRouteNode.h" #include "WED_ATCFlow.h" #include "WED_ATCTimeRule.h" #include "WED_ATCWindRule.h" #include "WED_ATCRunwayUse.h" #include "WED_RoadEdge.h" //Note: Replace WED_Airport or WED_Group with WED_GISComposite or it won't work when nested underneath const char * k_show_taxiline_chain = "WED_AirportChain/WED_GISComposite"; const char * k_show_taxiline_nodes = "WED_AirportNode/WED_AirportChain/WED_GISComposite"; const char * k_show_boundary_chain = "WED_AirportChain/WED_AirportBoundary"; const char * k_show_boundary_nodes = "WED_AirportNode/WED_AirportChain/WED_AirportBoundary"; void hide_all_persistents(vector<const char*>& hide_list) { //Commenting an item here makes it "white listed", aka always shown. //Most white listed items are vertex nodes, and //persistents that compose more concrete persistents. //If a pattern is here, it is hazy. Tread carefully, debug from the top-down or bottom-up. //Minimizing the size of the hide_list will likely speed things up for you. //See also WED_MapLayer::Is(Visible|Locked)Now and WED_MapLayer.cpp's ::matches_filter // -Ted 07/06/2016 hide_list.push_back(WED_AirportSign::sClass); hide_list.push_back(WED_AirportBeacon::sClass); hide_list.push_back(WED_AirportBoundary::sClass); hide_list.push_back(k_show_taxiline_chain); hide_list.push_back(k_show_taxiline_nodes); hide_list.push_back(k_show_boundary_chain); hide_list.push_back(k_show_boundary_nodes); //hide_list.push_back(WED_AirportChain::sClass); //hide_list.push_back(WED_Ring::sClass); //hide_list.push_back(WED_AirportNode::sClass); hide_list.push_back(WED_Helipad::sClass); hide_list.push_back(WED_KeyObjects::sClass); hide_list.push_back(WED_LightFixture::sClass); hide_list.push_back(WED_ObjPlacement::sClass); hide_list.push_back(WED_RampPosition::sClass); hide_list.push_back(WED_Root::sClass); hide_list.push_back(WED_Runway::sClass); //hide_list.push_back(WED_RunwayNode::sClass); hide_list.push_back(WED_Sealane::sClass); hide_list.push_back(WED_Select::sClass); hide_list.push_back(WED_Taxiway::sClass); hide_list.push_back(WED_TowerViewpoint::sClass); hide_list.push_back(WED_Windsock::sClass); hide_list.push_back(WED_ATCFrequency::sClass); //hide_list.push_back(WED_TextureNode::sClass); //hide_list.push_back(WED_TextureBezierNode::sClass); hide_list.push_back(WED_OverlayImage::sClass); //hide_list.push_back(WED_SimpleBoundaryNode::sClass); //hide_list.push_back(WED_SimpleBezierBoundaryNode::sClass); hide_list.push_back(WED_LinePlacement::sClass); hide_list.push_back(WED_StringPlacement::sClass); hide_list.push_back(WED_ForestPlacement::sClass); hide_list.push_back(WED_FacadePlacement::sClass); hide_list.push_back(WED_PolygonPlacement::sClass); hide_list.push_back(WED_DrapedOrthophoto::sClass); hide_list.push_back(WED_ExclusionZone::sClass); //hide_list.push_back(WED_ForestRing::sClass); //hide_list.push_back(WED_FacadeRing::sClass); //hide_list.push_back(WED_FacadeNode::sClass); hide_list.push_back(WED_TaxiRoute::sClass); hide_list.push_back(WED_TaxiRouteNode::sClass); hide_list.push_back(WED_ATCFlow::sClass); hide_list.push_back(WED_ATCTimeRule::sClass); hide_list.push_back(WED_ATCWindRule::sClass); hide_list.push_back(WED_ATCRunwayUse::sClass); #if ROAD_EDITING hide_list.push_back(WED_RoadEdge::sClass); #endif // ROAD_EDITING } void unhide_persistent(vector<const char*>& hide_list, const char* to_unhide) { for(vector<const char*>::iterator hide_itr = hide_list.begin(); hide_itr != hide_list.end(); ++hide_itr) { if(*hide_itr == to_unhide) { hide_list.erase(hide_itr); break; } } } void unhide_persistent(vector<const char*>& hide_list, const vector<const char*>& to_unhide) { for (vector<const char*>::const_iterator unhide_itr = to_unhide.begin(); unhide_itr != to_unhide.end(); ++unhide_itr) { for(vector<const char*>::iterator hide_itr = hide_list.begin(); hide_itr != hide_list.end(); ++hide_itr) { if(*unhide_itr == *hide_itr) { hide_list.erase(hide_itr); break; } } } } void WED_MapPane::SetTabFilterMode(int mode) { string title; vector<const char *> hide_list, lock_list; enum //Must be kept in sync with TabPane { tab_Selection, tab_Pavement, tab_ATC, tab_Lights, tab_3D, tab_Exclusions, tab_Texture }; hide_all_persistents(hide_list); mATCLayer->SetVisible(false); //Add to lock_list for Map Dead //unhide_persistent for Map Live //All else will be hidden if(mode == tab_Selection) { title = ""; hide_list.clear(); lock_list.clear(); } else if(mode == tab_Pavement) { title = "Pavement Mode"; unhide_persistent(hide_list, WED_DrapedOrthophoto::sClass); unhide_persistent(hide_list, WED_PolygonPlacement::sClass); unhide_persistent(hide_list, WED_Helipad::sClass); unhide_persistent(hide_list, WED_Runway::sClass); unhide_persistent(hide_list, WED_Taxiway::sClass); } else if(mode == tab_ATC) { title = "ATC Taxi + Flow Mode"; lock_list.push_back(WED_DrapedOrthophoto::sClass); lock_list.push_back(WED_FacadePlacement::sClass); lock_list.push_back(WED_ForestPlacement::sClass); lock_list.push_back(WED_ObjPlacement::sClass); lock_list.push_back(WED_PolygonPlacement::sClass); lock_list.push_back(WED_Runway::sClass); lock_list.push_back(WED_Taxiway::sClass); lock_list.push_back(k_show_taxiline_chain); mATCLayer->SetVisible(true); unhide_persistent(hide_list, lock_list); unhide_persistent(hide_list, WED_RampPosition::sClass); unhide_persistent(hide_list, WED_TaxiRoute::sClass); unhide_persistent(hide_list, WED_TaxiRouteNode::sClass); } else if(mode == tab_Lights) { title = "Lights and Markings"; lock_list.push_back(WED_DrapedOrthophoto::sClass); lock_list.push_back(WED_PolygonPlacement::sClass); lock_list.push_back(WED_Runway::sClass); lock_list.push_back(WED_Taxiway::sClass); unhide_persistent(hide_list, lock_list); unhide_persistent(hide_list, WED_LightFixture::sClass); unhide_persistent(hide_list, WED_LinePlacement::sClass); unhide_persistent(hide_list, WED_StringPlacement::sClass); unhide_persistent(hide_list, k_show_taxiline_chain); unhide_persistent(hide_list, k_show_taxiline_nodes); unhide_persistent(hide_list, WED_Windsock::sClass); } else if(mode == tab_3D) { title = "3D Objects Mode"; lock_list.push_back(WED_DrapedOrthophoto::sClass); lock_list.push_back(WED_PolygonPlacement::sClass); lock_list.push_back(WED_Runway::sClass); lock_list.push_back(WED_Taxiway::sClass); unhide_persistent(hide_list, lock_list); unhide_persistent(hide_list, WED_FacadePlacement::sClass); unhide_persistent(hide_list, WED_ForestPlacement::sClass); unhide_persistent(hide_list, WED_ObjPlacement::sClass); } else if(mode == tab_Exclusions) { title = "Exclusions and Boundaries"; lock_list.push_back(WED_DrapedOrthophoto::sClass); lock_list.push_back(WED_FacadePlacement::sClass); lock_list.push_back(WED_ForestPlacement::sClass); lock_list.push_back(WED_ObjPlacement::sClass); lock_list.push_back(WED_PolygonPlacement::sClass); lock_list.push_back(WED_Runway::sClass); lock_list.push_back(WED_Taxiway::sClass); unhide_persistent(hide_list, lock_list); unhide_persistent(hide_list, WED_ExclusionZone::sClass); unhide_persistent(hide_list, WED_AirportBoundary::sClass); unhide_persistent(hide_list, k_show_boundary_chain); unhide_persistent(hide_list, k_show_boundary_nodes); } else if(mode == tab_Texture) { title = "UV Texture Mode"; lock_list.push_back(WED_AirportSign::sClass); lock_list.push_back(WED_PolygonPlacement::sClass); lock_list.push_back(WED_Runway::sClass); lock_list.push_back(WED_Taxiway::sClass); unhide_persistent(hide_list, lock_list); unhide_persistent(hide_list, WED_DrapedOrthophoto::sClass); } mMap->SetFilter(title, hide_list, lock_list); } //---------------------------------------------------------------------------//
35.542334
169
0.732488
den-rain
67bb95e4ff351bc5d7671fa872ccc4fe11f26d51
6,755
cpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/audio_player_screen/Equalizer.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/audio_player_screen/Equalizer.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/audio_player_screen/Equalizer.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
/** ****************************************************************************** * This file is part of the TouchGFX 4.10.0 distribution. * * @attention * * Copyright (c) 2018 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ #include <gui/audio_player_screen/Equalizer.hpp> #include <BitmapDatabase.hpp> #include <texts/TextKeysAndLanguages.hpp> #include <touchgfx/Color.hpp> #include <math.h> #if defined(AUDIO_USE_SPIRIT_EQUALIZER) Equalizer::Equalizer() : onDrag(this, &Equalizer::drag), onStop(this, &Equalizer::stop), onLoudnessChanged(this, &Equalizer::loudnessChanged), callback(0) { background.setBitmap(Bitmap(BITMAP_EQUALIZER_BACKGROUND_ID)); add(background); EqualizerSlider* sliders[] = { &slider100Hz, &slider1kHz, &slider10kHz, &slider20kHz }; for (int i = 0; i < 4; i++) { EqualizerSlider* slider = sliders[i]; slider->setXY(49 + i * 139 + ((i > 1) ? i - 1 : 0), 97); slider->setBitmaps(Bitmap(BITMAP_EQUALIZER_BAR_UNFILL_ID), Bitmap(BITMAP_EQUALIZER_BAR_FILL_ID), Bitmap(BITMAP_LOUDNESS_KNOP_ID)); slider->setupVerticalSlider(19, 19, 0, 0, 302); slider->setValueRange(-12, 12); slider->setNewValueCallback(onDrag); slider->setStopValueCallback(onStop); add(*slider); } sliderValue.setBitmap(Bitmap(BITMAP_EQUALIZER_DB_VALUE_ID)); sliderValue.setVisible(false); add(sliderValue); sliderValueBuffer[0] = 0; sliderValueText.setPosition(0, 0, sliderValue.getWidth(), sliderValue.getHeight()); sliderValueText.setTypedText(TypedText(T_EQUALIZER_BAND_READOUT)); sliderValueText.setColor(Color::getColorFrom24BitRGB(29, 29, 35)); sliderValueText.setWildcard(sliderValueBuffer); sliderValueText.setVisible(false); add(sliderValueText); loudnessSlider.setXY(589, 178); loudnessSlider.setLoudnessChangedCallback(onLoudnessChanged); //loudnessSlider.setValue(0); //default value add(loudnessSlider); loudnessValueBuffer[0] = 0; loudnessValueText.setPosition(loudnessSlider.getX(), loudnessSlider.getY() + 55, loudnessSlider.getWidth(), 120); loudnessValueText.setTypedText(TypedText(T_EQUALIZER_LOUDNESS_READOUT)); loudnessValueText.setColor(Color::getColorFrom24BitRGB(1, 191, 255)); loudnessValueText.setWildcard(loudnessValueBuffer); add(loudnessValueText); setPosition(0, 0, background.getWidth(), background.getHeight()); //setTouchable(true); not good in combination with fingersize } void Equalizer::drag(const Slider& slider, int value) { const EqualizerSlider& equalizerSlider = (const EqualizerSlider&)slider; sliderValue.setVisible(true); sliderValue.moveTo(slider.getX() - 28, equalizerSlider.getIndicatorY() + 60); Unicode::snprintf(sliderValueBuffer, 5, "%d", value); //todo sliderValueText.setVisible(true); sliderValueText.moveTo(slider.getX() - 70, equalizerSlider.getIndicatorY() + 62); if (callback && callback->isValid()) { AudioPlayer::EqualizerSetting setting = AudioPlayer::_100HZ; if (&slider == &slider1kHz) { setting = AudioPlayer::_1KHZ; } else if (&slider == &slider10kHz) { setting = AudioPlayer::_10KHZ; } else if (&slider == &slider20kHz) { setting = AudioPlayer::_20KHZ; } callback->execute(setting, value); } } void Equalizer::stop(const Slider&, int) { sliderValue.setVisible(false); sliderValueText.setVisible(false); sliderValue.invalidate(); } void Equalizer::loudnessChanged(const unsigned int percentage) { Unicode::snprintfFloat(loudnessValueBuffer, 6, "%2.1f", (float)(percentage * 24.0f / 100.0f) - 12.0f); loudnessValueText.invalidate(); if (callback && callback->isValid()) { callback->execute(AudioPlayer::LOUDNESS, ((percentage * 24) / 100 - 12)); } } void Equalizer::setSettings(int16_t _100Hz, int16_t _1kHz, int16_t _10kHz, int16_t _20kHz, int16_t loudness) { /* Values are in db */ slider100Hz.setValue(_100Hz); slider1kHz.setValue(_1kHz); slider10kHz.setValue(_10kHz); slider20kHz.setValue(_20kHz); loudnessSlider.setValue(loudness); sliderValue.setVisible(false); sliderValueText.setVisible(false); } LoudnessSlider::LoudnessSlider() : callback(0), colorPainter(Color::getColorFrom24BitRGB(1, 191, 255)) { dot.setPosition(0, 0, 14, 14); dot.setCircle(7, 7, 7); dot.setLineWidth(0); dot.setPainter(colorPainter); add(dot); setPosition(0, 0, size, size); setTouchable(true); } void LoudnessSlider::handleClickEvent(const ClickEvent& evt) { update(evt.getX(), evt.getY()); } void LoudnessSlider::handleDragEvent(const DragEvent& evt) { update(evt.getNewX(), evt.getNewY()); } void LoudnessSlider::update(int16_t x, int16_t y) { int16_t vx = x - getWidth() / 2; int16_t vy = y - getHeight() / 2; int length; int angleInDegrees = CWRUtil::angle<int>(vx, vy, length); if (length < 30 || length > 130) { return; } //clamp angle if (angleInDegrees > maxAngle && angleInDegrees <= 180) { angleInDegrees = maxAngle; } if (angleInDegrees < 360 - maxAngle && angleInDegrees > 180) { angleInDegrees = 360 - maxAngle; } dot.moveTo((int16_t)(getWidth() / 2.0f * (1.0f + 0.8f * cosf((angleInDegrees - 90) * 3.141592f / 180.0f)) - dot.getWidth() / 2), (int16_t)(getHeight() / 2.0f * (1.0f + 0.8f * sinf((angleInDegrees - 90) * 3.141592f / 180.0f))) - dot.getHeight() / 2); if (callback && callback->isValid()) { int16_t percentage = (((angleInDegrees + maxAngle) % 360) * 100) / (2 * maxAngle); callback->execute(percentage); } } void LoudnessSlider::setValue(int16_t value) { assert(value <= 12 && value >= -12 && "value out of range"); //-12 to 12 int percentage = ((value + 12) * 100) / 24; int angleInDegrees = percentage * 2 * maxAngle / 100 - maxAngle; dot.moveTo((int16_t)(getWidth() / 2.0f * (1.0f + 0.8f * cosf((angleInDegrees - 90) * 3.141592f / 180.0f)) - dot.getWidth() / 2), (int16_t)(getHeight() / 2.0f * (1.0f + 0.8f * sinf((angleInDegrees - 90) * 3.141592f / 180.0f))) - dot.getHeight() / 2); if (callback && callback->isValid()) { callback->execute(percentage); } } #endif /* AUDIO_USE_SPIRIT_EQUALIZER */
32.320574
138
0.646632
ramkumarkoppu
67bbb6c2d67e1b47a7f919377fbddf9733a77fd2
4,565
cpp
C++
FireRender.Max.Plugin/parser/Synchronizer_RenderSettings.cpp
Vsevolod1983/RadeonProRenderMaxPlugin
d5393fd04e45dd2c77c8b17fac4e10b20df55285
[ "Apache-2.0" ]
6
2020-05-24T12:00:43.000Z
2021-07-13T06:22:49.000Z
FireRender.Max.Plugin/parser/Synchronizer_RenderSettings.cpp
Vsevolod1983/RadeonProRenderMaxPlugin
d5393fd04e45dd2c77c8b17fac4e10b20df55285
[ "Apache-2.0" ]
4
2020-09-17T17:05:38.000Z
2021-06-23T14:29:14.000Z
FireRender.Max.Plugin/parser/Synchronizer_RenderSettings.cpp
Vsevolod1983/RadeonProRenderMaxPlugin
d5393fd04e45dd2c77c8b17fac4e10b20df55285
[ "Apache-2.0" ]
8
2020-05-15T08:29:17.000Z
2021-07-14T08:38:07.000Z
/********************************************************************** Copyright 2020 Advanced Micro Devices, Inc 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 "Synchronizer.h" #include "plugin/ParamBlock.h" #include "plugin/TmManager.h" #include "plugin/CamManager.h" FIRERENDER_NAMESPACE_BEGIN void Synchronizer::UpdateRenderSettings(const std::vector<int> &changes) { auto context = mScope.GetContext(); for (auto pp : changes) { switch (pp) { case PARAM_MAX_RAY_DEPTH: { auto v = mParametersTracker.GetParam(pp); context.SetParameter(RPR_CONTEXT_MAX_RECURSION, v.mSimpleValue.int_val); } break; case PARAM_RENDER_MODE: { auto v = mParametersTracker.GetParam(pp); context.SetParameter(RPR_CONTEXT_RENDER_MODE, v.mSimpleValue.int_val); } break; case PARAM_IMAGE_FILTER: { auto v = mParametersTracker.GetParam(pp); context.SetParameter(RPR_CONTEXT_IMAGE_FILTER_TYPE, v.mSimpleValue.int_val); } break; case PARAM_USE_TEXTURE_COMPRESSION: { auto v = mParametersTracker.GetParam(pp); context.SetParameter(RPR_CONTEXT_TEXTURE_COMPRESSION, v.mSimpleValue.int_val); } break; case PARAM_IMAGE_FILTER_WIDTH: { auto v = mParametersTracker.GetParam(pp); context.SetParameter(RPR_CONTEXT_IMAGE_FILTER_BOX_RADIUS, v.mSimpleValue.float_val); context.SetParameter(RPR_CONTEXT_IMAGE_FILTER_GAUSSIAN_RADIUS, v.mSimpleValue.float_val); context.SetParameter(RPR_CONTEXT_IMAGE_FILTER_TRIANGLE_RADIUS, v.mSimpleValue.float_val); context.SetParameter(RPR_CONTEXT_IMAGE_FILTER_MITCHELL_RADIUS, v.mSimpleValue.float_val); context.SetParameter(RPR_CONTEXT_IMAGE_FILTER_LANCZOS_RADIUS, v.mSimpleValue.float_val); context.SetParameter(RPR_CONTEXT_IMAGE_FILTER_BLACKMANHARRIS_RADIUS, v.mSimpleValue.float_val); } break; case PARAM_USE_IRRADIANCE_CLAMP: { auto v = mParametersTracker.GetParam(pp); if (v.mSimpleValue.int_val) { float irradianceClamp = FLT_MAX; mBridge->GetPBlock()->GetValue(PARAM_IRRADIANCE_CLAMP, 0, irradianceClamp, Interval()); context.SetParameter(RPR_CONTEXT_RADIANCE_CLAMP, irradianceClamp); } else context.SetParameter(RPR_CONTEXT_RADIANCE_CLAMP, FLT_MAX); } break; case PARAM_IRRADIANCE_CLAMP: { BOOL useIrradianceClamp = FALSE; mBridge->GetPBlock()->GetValue(PARAM_USE_IRRADIANCE_CLAMP, 0, useIrradianceClamp, Interval()); if (useIrradianceClamp) { auto v = mParametersTracker.GetParam(pp); context.SetParameter(RPR_CONTEXT_RADIANCE_CLAMP, v.mSimpleValue.float_val); } } break; case PARAM_CONTEXT_ITERATIONS: { auto v = mParametersTracker.GetParam(pp); context.SetParameter(RPR_CONTEXT_ITERATIONS, v.mSimpleValue.int_val); } case PARAM_TIME_LIMIT: { auto v = mParametersTracker.GetParam(pp); mBridge->SetTimeLimit(v.mSimpleValue.int_val); } break; case PARAM_PASS_LIMIT: { auto v = mParametersTracker.GetParam(pp); mBridge->SetPassLimit(v.mSimpleValue.int_val); } break; case PARAM_RENDER_LIMIT: { auto v = mParametersTracker.GetParam(pp); mBridge->SetLimitType(v.mSimpleValue.int_val); } break; case PARAM_QUALITY_RAYCAST_EPSILON: { auto v = mParametersTracker.GetParam(pp); context.SetParameter(RPR_CONTEXT_RAY_CAST_EPISLON, v.mSimpleValue.float_val); } break; case PARAM_ADAPTIVE_NOISE_THRESHOLD: { auto v = mParametersTracker.GetParam(pp); context.SetParameter(RPR_CONTEXT_ADAPTIVE_SAMPLING_THRESHOLD, v.mSimpleValue.float_val); } break; case PARAM_ADAPTIVE_TILESIZE: { auto v = mParametersTracker.GetParam(pp); context.SetParameter(RPR_CONTEXT_ADAPTIVE_SAMPLING_TILE_SIZE, v.mSimpleValue.int_val); } break; case PARAM_SAMPLES_MIN: { auto v = mParametersTracker.GetParam(pp); context.SetParameter(RPR_CONTEXT_ADAPTIVE_SAMPLING_MIN_SPP, v.mSimpleValue.int_val); } break; } } } FIRERENDER_NAMESPACE_END
29.451613
99
0.725958
Vsevolod1983
67be5896142e95b56876cb46626c06046019d70e
5,805
cpp
C++
Source/API/Vulkan/FrameBufferVk.cpp
KawBuma/Buma3D
73b1c7a99c979492f072d4ead89f2d357d5e048a
[ "MIT" ]
5
2020-11-25T05:05:13.000Z
2022-02-09T09:35:21.000Z
Source/API/Vulkan/FrameBufferVk.cpp
KawBuma/Buma3D
73b1c7a99c979492f072d4ead89f2d357d5e048a
[ "MIT" ]
5
2020-11-11T09:52:59.000Z
2021-12-15T13:27:37.000Z
Source/API/Vulkan/FrameBufferVk.cpp
KawBuma/Buma3D
73b1c7a99c979492f072d4ead89f2d357d5e048a
[ "MIT" ]
null
null
null
#include "Buma3DPCH.h" #include "FramebufferVk.h" namespace buma3d { B3D_APIENTRY FramebufferVk::FramebufferVk() : ref_count { 1 } , name {} , device {} , desc {} , desc_data {} , vkdevice {} , inspfn {} , devpfn {} , framebuffer {} , render_area {} { } B3D_APIENTRY FramebufferVk::~FramebufferVk() { Uninit(); } BMRESULT B3D_APIENTRY FramebufferVk::Init(DeviceVk* _device, const FRAMEBUFFER_DESC& _desc) { (device = _device)->AddRef(); vkdevice = device->GetVkDevice(); inspfn = &device->GetInstancePFN(); devpfn = &device->GetDevicePFN(); CopyDesc(_desc); B3D_RET_IF_FAILED(CreateVkFramebuffer()); return BMRESULT_SUCCEED; } BMRESULT B3D_APIENTRY FramebufferVk::CreateVkFramebuffer() { VkFramebufferCreateInfo ci{ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; EXTENT3D s{}; util::DyArray<VkImageView> views{}; B3D_RET_IF_FAILED(PrepareFramebufferCreateInfo(s, ci, &views)); auto vkr = vkCreateFramebuffer(vkdevice, &ci, B3D_VK_ALLOC_CALLBACKS, &framebuffer); B3D_RET_IF_FAILED(VKR_TRACE_IF_FAILED(vkr)); return BMRESULT_SUCCEED; } BMRESULT B3D_APIENTRY FramebufferVk::PrepareFramebufferCreateInfo(EXTENT3D& _s, VkFramebufferCreateInfo& _ci, util::DyArray<VkImageView>* _views) { bool set = false; auto CheckSize = [&](const IView* _view) { auto type = _view->GetViewDesc().type; uint32_t layer = 0; if (type == VIEW_TYPE_RENDER_TARGET) layer = _view->As<RenderTargetViewVk>()->GetDesc().texture.subresource_range.array_size; else if (type == VIEW_TYPE_DEPTH_STENCIL) layer = _view->As<DepthStencilViewVk>()->GetDesc().texture.subresource_range.array_size; else return BMRESULT_FAILED_INVALID_PARAMETER; auto&& t = _view->GetResource()->GetDesc().texture; if (!set) { _s = { t.extent.width,t.extent.height,layer }; set = true; return BMRESULT_SUCCEED; } bool invalid = false; invalid |= _s.width != t.extent.width; invalid |= _s.height != t.extent.height; invalid |= _s.depth != layer; return invalid ? BMRESULT_FAILED_INVALID_PARAMETER : BMRESULT_SUCCEED; }; _ci.flags = 0; _ci.renderPass = desc.render_pass->As<RenderPassVk>()->GetVkRenderPass(); _views->resize((desc.num_attachments)); auto views_data = _views->data(); for (uint32_t i = 0; i < desc.num_attachments; i++) views_data[i] = desc.attachments[i]->As<RenderTargetViewVk>()->GetVkImageView(); _ci.attachmentCount = desc.num_attachments; _ci.pAttachments = views_data; // 全てのRTV/DSVのサイズが一致しているか確認。 for (uint32_t i = 0; i < desc.num_attachments; i++) B3D_RET_IF_FAILED(CheckSize(desc.attachments[i])); _ci.width = _s.width; _ci.height = _s.height; _ci.layers = _s.depth; render_area.offset.x = 0; render_area.offset.y = 0; render_area.extent.width = _s.width; render_area.extent.height = _s.height; return BMRESULT_SUCCEED; } void B3D_APIENTRY FramebufferVk::CopyDesc(const FRAMEBUFFER_DESC& _desc) { desc = _desc; desc_data.render_passvk = desc.render_pass->As<RenderPassVk>(); desc_data.attachments.resize(desc.num_attachments); auto attachments_data = desc_data.attachments.data(); for (uint32_t i = 0; i < desc.num_attachments; i++) (attachments_data[i] = desc.attachments[i])->AddRef(); desc.attachments = attachments_data; } void B3D_APIENTRY FramebufferVk::Uninit() { if (framebuffer) vkDestroyFramebuffer(vkdevice, framebuffer, B3D_VK_ALLOC_CALLBACKS); framebuffer = VK_NULL_HANDLE; desc = {}; desc_data.Uninit(); hlp::SafeRelease(device); vkdevice = VK_NULL_HANDLE; name.reset(); } BMRESULT B3D_APIENTRY FramebufferVk::Create(DeviceVk* _device, const FRAMEBUFFER_DESC& _desc, FramebufferVk** _dst) { util::Ptr<FramebufferVk> ptr; ptr.Attach(B3DCreateImplementationClass(FramebufferVk)); B3D_RET_IF_FAILED(ptr->Init(_device, _desc)); *_dst = ptr.Detach(); return BMRESULT_SUCCEED; } void B3D_APIENTRY FramebufferVk::AddRef() { ++ref_count; B3D_REFCOUNT_DEBUG(ref_count); } uint32_t B3D_APIENTRY FramebufferVk::Release() { B3D_REFCOUNT_DEBUG(ref_count - 1); auto count = --ref_count; if (count == 0) B3DDestroyImplementationClass(this); return count; } uint32_t B3D_APIENTRY FramebufferVk::GetRefCount() const { return ref_count; } const char* B3D_APIENTRY FramebufferVk::GetName() const { return name ? name->c_str() : nullptr; } BMRESULT B3D_APIENTRY FramebufferVk::SetName(const char* _name) { if (!util::IsEnabledDebug(this)) return BMRESULT_FAILED; if (framebuffer) B3D_RET_IF_FAILED(device->SetVkObjectName(framebuffer, _name)); if (name && !_name) name.reset(); else name = B3DMakeUniqueArgs(util::NameableObjStr, _name); return BMRESULT_SUCCEED; } IDevice* B3D_APIENTRY FramebufferVk::GetDevice() const { return device; } const VkAllocationCallbacks* B3D_APIENTRY FramebufferVk::GetVkAllocationCallbacks() const { return device->GetVkAllocationCallbacks(); } const InstancePFN& B3D_APIENTRY FramebufferVk::GetIsntancePFN() const { return *inspfn; } const DevicePFN& B3D_APIENTRY FramebufferVk::GetDevicePFN() const { return *devpfn; } const FRAMEBUFFER_DESC& B3D_APIENTRY FramebufferVk::GetDesc() const { return desc; } VkFramebuffer B3D_APIENTRY FramebufferVk::GetVkFramebuffer() const { return framebuffer; } const VkRect2D& B3D_APIENTRY FramebufferVk::GetRenderArea() const { return render_area; } }// namespace buma3d
24.087137
136
0.680276
KawBuma
67c05949960445fba00a15b56983d4aca3431dfe
5,077
hpp
C++
ionFinder/include/geometry.hpp
ajmaurais/ms2_annotator
103fa6bef497589005c7fd264a9b68355d4fc056
[ "MIT" ]
4
2021-09-14T03:03:49.000Z
2022-01-04T21:16:48.000Z
ionFinder/include/geometry.hpp
ajmaurais/ms2_annotator
103fa6bef497589005c7fd264a9b68355d4fc056
[ "MIT" ]
null
null
null
ionFinder/include/geometry.hpp
ajmaurais/ms2_annotator
103fa6bef497589005c7fd264a9b68355d4fc056
[ "MIT" ]
1
2021-06-04T00:11:33.000Z
2021-06-04T00:11:33.000Z
// // geometry.hpp // ionFinder // ----------------------------------------------------------------------------- // MIT License // Copyright 2020 Aaron Maurais // ----------------------------------------------------------------------------- // 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. // ----------------------------------------------------------------------------- // #ifndef geometry_hpp #define geometry_hpp #include <cmath> #include <iostream> namespace geometry{ class Point; class Line; class Rect; class Vector2D; std::string const NA_STR = "NA"; bool valueInRange(double, double, double); double dist(const Point&, const Point&); class Point{ friend double dist(const Point&, const Point&); friend class Vector2D; friend class Rect; protected: double x, y; public: Point(double _x, double _y){ x = _x; y = _y; } Point(){ x = 0; y = 0; } void operator = (const Point& cp){ x = cp.x; y = cp.y; } bool operator == (const Point& comp){ return (x == comp.x && y == comp.y); } void setPos(double _x, double _y){ x = _x; y = _y; } void move(const Vector2D&); double getX() const{ return x; } double getY() const{ return y; } }; class Rect : public Point{ protected: double width, height; public: Rect() : Point() { width = 0; height = 0; } Rect(double _x, double _y, double _width, double _height) : Point(_x, _y){ width = _width; height = _height; } ~Rect() {} bool intersects(const Rect&) const; bool operator == (const Rect& comp) const{ return (x == comp.x && y == comp.y && width == comp.width && height == comp.height); } double getWidth() const{ return width; } double getHeight() const{ return height; } Point getTLC() const{ Point ret; ret.x = (x - width/2); ret.y = (y + height/2); return ret; } Point getBRC() const{ Point ret; ret.x = (x + width/2); ret.y = (y - height/2); return ret; } }; class Vector2D{ private: double v, h; public: Vector2D(){ v = 0; h = 0; } Vector2D(double _v, double _h){ v = _v; h = _h; } Vector2D(const Point& p1, const Point& p2){ h = p2.x - p1.x; v = p2.y - p1.y; } ~Vector2D() {} void operator += (const Vector2D& add){ v += add.v; h += add.h; } void operator /= (double div){ v /= div; h /= div; } double getMagnitude() const{ return dist(Point(0, 0), Point(h, v)); } double getDirrection() const{ return atan(v/h); } double getH() const{ return h; } double getV() const{ return v; } }; class Line{ public: Point beg; Point end; Line() { beg = Point(0, 0); end = Point(0, 0); } Line(double begX, double begY, double endX, double endY){ beg = Point(begX, begY); end = Point(endX, endY); } Line(const Point& _beg, const Vector2D& mov){ beg = _beg; end = Point(beg.getX() + mov.getH(), end.getY() + mov.getV()); } ~Line() {} double length() const{ return dist(beg, end); } }; class DataLabel{ private: std::string label; bool includeLabel; bool includeArrow; Point dataPoint; public: Line arrow; Rect labelLoc; Vector2D movement; bool forceLabel; size_t overlapNum; DataLabel(){ label = NA_STR; arrow = Line(); labelLoc = Rect(); movement = Vector2D(); forceLabel = false; includeLabel = false; includeArrow = false; } void setIncludeLabel(bool boo){ includeLabel = boo; } void setLabel(std::string str){ label = str; } std::string getLabel() const{ return label; } bool getIncludeLabel() const{ return includeLabel; } bool getIncludeArrow() const{ return includeArrow; } bool operator > (const DataLabel& comp) const{ return overlapNum > comp.overlapNum; } bool operator < (const DataLabel& comp) const{ return overlapNum < comp.overlapNum; } bool operator == (const DataLabel& comp) const{ return labelLoc == comp.labelLoc; } }; } #endif /* geometry_h */
21.331933
80
0.602915
ajmaurais
67c320d021e4ed2d0d29930809c53e303fcff1df
2,837
cc
C++
renderer/gl/camera.cc
rrobbyflya330/House3D
258d155ba4d6c7399ed463de73bb1f1fae52979f
[ "Apache-2.0" ]
1,163
2017-12-07T17:45:44.000Z
2022-03-29T13:34:42.000Z
renderer/gl/camera.cc
rrobbyflya330/House3D
258d155ba4d6c7399ed463de73bb1f1fae52979f
[ "Apache-2.0" ]
55
2018-01-11T20:01:48.000Z
2021-03-10T08:41:01.000Z
renderer/gl/camera.cc
harunpehlivan/House3D
dea99540cf8edde41820718863429c58d9189b3f
[ "Apache-2.0" ]
181
2017-12-07T18:25:31.000Z
2022-03-25T12:51:43.000Z
// Copyright 2017-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. //File: camera.cc #include <functional> #include "camera.hh" #include "gl/glfw++.hh" #include "lib/debugutils.hh" namespace { constexpr int NR_KEYS = 1024; } namespace render { void Camera::shift(Camera::Movement dir, float dist) { if (dir == FORWARD) pos += front * dist; if (dir == BACKWARD) pos -= front * dist; if (dir == LEFT) pos -= right * dist; if (dir == RIGHT) pos += right * dist; if (dir == UP) pos += up * dist; if (dir == DOWN) pos -= up * dist; } void Camera::turn(float dyaw, float dpitch) { yaw += dyaw; pitch += dpitch; pitch = glm::clamp(pitch, -89.f, 89.f); updateDirection(); } CameraController::CameraController(GLFWwindow& window, Camera& cam): window_{window}, cam_(cam), keys_(NR_KEYS) { using namespace std::placeholders; glfwSetKeyCallback(&window, std::bind( &CameraController::keyCallback, this, _1, _2, _3, _4)); glfwSetInputMode(&window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPosCallback(&window, std::bind( &CameraController::mouseCallback, this, _1, _2)); last_time_ = timer_.duration(); } void CameraController::keyCallback(int key, int /* scancode */, int action, int /* mode*/) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(&window_, GL_TRUE); if (key >= 0 && key < NR_KEYS) { if (action == GLFW_PRESS) keys_[key] = true; else if (action == GLFW_RELEASE) keys_[key] = false; } } void CameraController::mouseCallback(double x, double y) { if (!mouse_init_) { mouse_ = glm::vec2(x, y); mouse_init_ = true; return; } auto old = mouse_; mouse_ = glm::dvec2(x, y); auto offset = mouse_ - old; offset = offset * mouse_speed_; offset.y = -offset.y; // mouse y coordinate and 3D y coordinate are opposite cam_.turn(offset.x, offset.y); } void CameraController::moveCamera() { float now = timer_.duration(); float delta = now - last_time_; last_time_ = now; float dist = key_speed_ * delta; if (keys_[GLFW_KEY_W]) cam_.shift(Camera::Movement::FORWARD, dist); if (keys_[GLFW_KEY_S]) cam_.shift(Camera::Movement::BACKWARD, dist); if (keys_[GLFW_KEY_A]) cam_.shift(Camera::Movement::LEFT, dist); if (keys_[GLFW_KEY_D]) cam_.shift(Camera::Movement::RIGHT, dist); if (keys_[GLFW_KEY_UP]) cam_.shift(Camera::Movement::UP, dist); if (keys_[GLFW_KEY_DOWN]) cam_.shift(Camera::Movement::DOWN, dist); if (keys_[GLFW_KEY_LEFT]) cam_.shift(Camera::Movement::LEFT, dist); if (keys_[GLFW_KEY_RIGHT]) cam_.shift(Camera::Movement::RIGHT, dist); } } // namespace render
26.514019
92
0.657032
rrobbyflya330
67c75eed412594454536114180a4cf37094d5590
1,018
cpp
C++
static-loop-unrollers/loop_unroller_examples.cpp
ammarhusain/cpp-sandbox
ff69ebfe55020b33ddc418928080b86f84d7539f
[ "MIT" ]
null
null
null
static-loop-unrollers/loop_unroller_examples.cpp
ammarhusain/cpp-sandbox
ff69ebfe55020b33ddc418928080b86f84d7539f
[ "MIT" ]
null
null
null
static-loop-unrollers/loop_unroller_examples.cpp
ammarhusain/cpp-sandbox
ff69ebfe55020b33ddc418928080b86f84d7539f
[ "MIT" ]
null
null
null
// Copyright (C) 2016 Ammar Husain. All Rights Reserved. #include <iostream> // std::cout #include <string> #include "loop_unroller.h" struct MyFunc { template<typename I> void operator()(I, int val) { std::cout << "Functor " << I::value*val << std::endl; } }; int main(int argc, char** argv) { // Using functor. loop_unroller::ForLoopGreaterThan<10, 1>(MyFunc{}, 5); // Using lambda expressions : thanks to c++14! loop_unroller::ForLoopLessThanEqualTo<1, 20>([](auto a){ using INT_CONSTANT=decltype(a); std::cout << "Lambda " << INT_CONSTANT::value << std::endl;}); // Using generic API: prints powers of 2 from [1,6// 4]. loop_unroller::ForLoop(loop_unroller::LoopParams<1, 64, 2, std::less_equal<int>, std::multiplies<int>>(), [](auto idx, std::string str){ using I=decltype(idx); std::cout << str << I::value << std::endl; }, "Power of 2: "); }
32.83871
82
0.562868
ammarhusain
67c7c50f736884e02f036cea6cc81c8692d85a01
8,471
cpp
C++
wxWidgets/src/gtk/glcanvas.cpp
VonaInc/lokl
83fbaa9c73d3112490edd042da812ceeb3cc9e53
[ "MIT" ]
86
2015-08-06T11:30:01.000Z
2022-02-28T04:50:22.000Z
wxWidgets/src/gtk/glcanvas.cpp
VonaInc/lokl
83fbaa9c73d3112490edd042da812ceeb3cc9e53
[ "MIT" ]
6
2016-01-04T19:36:22.000Z
2021-08-08T02:43:48.000Z
wxWidgets/src/gtk/glcanvas.cpp
VonaInc/lokl
83fbaa9c73d3112490edd042da812ceeb3cc9e53
[ "MIT" ]
22
2015-11-04T04:04:54.000Z
2022-02-28T04:50:24.000Z
///////////////////////////////////////////////////////////////////////////// // Name: src/gtk/glcanvas.cpp // Purpose: wxGLCanvas, for using OpenGL/Mesa with wxWidgets and GTK // Author: Robert Roebling // Modified by: // Created: 17/08/98 // Copyright: (c) Robert Roebling // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #if wxUSE_GLCANVAS #include "wx/glcanvas.h" #include "wx/gtk/private/wrapgtk.h" #include <gdk/gdkx.h> #ifdef __WXGTK3__ extern "C" { static gboolean draw(GtkWidget* widget, cairo_t* cr, wxGLCanvas* win) { GtkAllocation a; gtk_widget_get_allocation(widget, &a); if (a.width > win->m_size.x || a.height > win->m_size.y) { // GLX buffers are apparently not reliably updated to the new size // before the paint event occurs, resulting in newly exposed window // areas sometimes not being painted at the end of a drag resize. gdk_display_sync(gtk_widget_get_display(widget)); } win->m_size.Set(a.width, a.height); win->GTKSendPaintEvents(cr); return false; } } #endif // __WXGTK3__ //----------------------------------------------------------------------------- // emission hook for "parent-set" //----------------------------------------------------------------------------- extern "C" { static gboolean parent_set_hook(GSignalInvocationHint*, guint, const GValue* param_values, void* data) { wxGLCanvas* win = (wxGLCanvas*)data; if (g_value_peek_pointer(&param_values[0]) == win->m_wxwindow) { const XVisualInfo* xvi = static_cast<XVisualInfo*>(win->GetXVisualInfo()); GdkVisual* visual = gtk_widget_get_visual(win->m_wxwindow); if (GDK_VISUAL_XVISUAL(visual)->visualid != xvi->visualid) { GdkScreen* screen = gtk_widget_get_screen(win->m_wxwindow); visual = gdk_x11_screen_lookup_visual(screen, xvi->visualid); #ifdef __WXGTK3__ gtk_widget_set_visual(win->m_wxwindow, visual); #else GdkColormap* colormap = gdk_colormap_new(visual, false); gtk_widget_set_colormap(win->m_wxwindow, colormap); g_object_unref(colormap); #endif } // remove hook return false; } return true; } } //--------------------------------------------------------------------------- // wxGlCanvas //--------------------------------------------------------------------------- wxIMPLEMENT_CLASS(wxGLCanvas, wxWindow); wxGLCanvas::wxGLCanvas(wxWindow *parent, const wxGLAttributes& dispAttrs, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name, const wxPalette& palette) #if WXWIN_COMPATIBILITY_2_8 : m_createImplicitContext(false) #endif { Create(parent, dispAttrs, id, pos, size, style, name, palette); } wxGLCanvas::wxGLCanvas(wxWindow *parent, wxWindowID id, const int *attribList, const wxPoint& pos, const wxSize& size, long style, const wxString& name, const wxPalette& palette) #if WXWIN_COMPATIBILITY_2_8 : m_createImplicitContext(false) #endif { Create(parent, id, pos, size, style, name, attribList, palette); } #if WXWIN_COMPATIBILITY_2_8 wxGLCanvas::wxGLCanvas(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name, const int *attribList, const wxPalette& palette) : m_createImplicitContext(true) { m_sharedContext = NULL; m_sharedContextOf = NULL; Create(parent, id, pos, size, style, name, attribList, palette); } wxGLCanvas::wxGLCanvas(wxWindow *parent, const wxGLContext *shared, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name, const int *attribList, const wxPalette& palette) : m_createImplicitContext(true) { m_sharedContext = const_cast<wxGLContext *>(shared); Create(parent, id, pos, size, style, name, attribList, palette); } wxGLCanvas::wxGLCanvas(wxWindow *parent, const wxGLCanvas *shared, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name, const int *attribList, const wxPalette& palette ) : m_createImplicitContext(true) { m_sharedContext = NULL; m_sharedContextOf = const_cast<wxGLCanvas *>(shared); Create(parent, id, pos, size, style, name, attribList, palette); } #endif // WXWIN_COMPATIBILITY_2_8 static bool IsAvailable() { #ifdef GDK_WINDOWING_X11 if ( !GDK_IS_X11_DISPLAY(gdk_display_get_default()) ) #endif { wxSafeShowMessage(_("Fatal Error"), _("wxGLCanvas is only supported on X11 currently. You may be able to\nwork around this by setting environment variable GDK_BACKEND=x11 before starting\nyour program.")); return false; } return true; } bool wxGLCanvas::Create(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name, const int *attribList, const wxPalette& palette) { if ( !IsAvailable() ) return false; // Separate 'GLXFBConfig/XVisual' attributes. // Also store context attributes for wxGLContext ctor wxGLAttributes dispAttrs; if ( ! ParseAttribList(attribList, dispAttrs, &m_GLCTXAttrs) ) return false; return Create(parent, dispAttrs, id, pos, size, style, name, palette); } bool wxGLCanvas::Create(wxWindow *parent, const wxGLAttributes& dispAttrs, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name, const wxPalette& palette) { if ( !IsAvailable() ) return false; #if wxUSE_PALETTE wxASSERT_MSG( !palette.IsOk(), wxT("palettes not supported") ); #endif // wxUSE_PALETTE wxUnusedVar(palette); // Unused when wxDEBUG_LEVEL==0 m_nativeSizeEvent = true; #ifdef __WXGTK3__ m_noExpose = true; m_backgroundStyle = wxBG_STYLE_PAINT; #endif if ( !InitVisual(dispAttrs) ) return false; // watch for the "parent-set" signal on m_wxwindow so we can set colormap // before m_wxwindow is realized (which will occur before // wxWindow::Create() returns if parent is already visible) unsigned sig_id = g_signal_lookup("parent-set", GTK_TYPE_WIDGET); g_signal_add_emission_hook(sig_id, 0, parent_set_hook, this, NULL); wxWindow::Create( parent, id, pos, size, style, name ); #ifdef __WXGTK3__ g_signal_connect(m_wxwindow, "draw", G_CALLBACK(draw), this); #endif gtk_widget_set_double_buffered(m_wxwindow, false); return true; } bool wxGLCanvas::SetBackgroundStyle(wxBackgroundStyle /* style */) { return false; } unsigned long wxGLCanvas::GetXWindow() const { GdkWindow* window = GTKGetDrawingWindow(); return window ? GDK_WINDOW_XID(window) : 0; } void wxGLCanvas::GTKHandleRealized() { BaseType::GTKHandleRealized(); #if WXWIN_COMPATIBILITY_2_8 GTKInitImplicitContext(); #endif SendSizeEvent(); } #if WXWIN_COMPATIBILITY_2_8 void wxGLCanvas::GTKInitImplicitContext() { if ( !m_glContext && m_createImplicitContext ) { wxGLContext *share = m_sharedContext; if ( !share && m_sharedContextOf ) share = m_sharedContextOf->m_glContext; m_glContext = new wxGLContext(this, share); } } #endif // WXWIN_COMPATIBILITY_2_8 #endif // wxUSE_GLCANVAS
30.803636
214
0.574312
VonaInc
67c8d513a51971b65d602738bc44fddf11f21cf2
1,062
hpp
C++
src/nudb/extras/beast/include/beast/http/resume_context.hpp
gyas-kk/JBcoin
b2cdc126d4db4f2913dac34ad3ba83c4e1543ce6
[ "BSL-1.0" ]
2
2020-03-03T12:46:29.000Z
2020-11-14T09:52:14.000Z
include/beast/http/resume_context.hpp
somayeghahari/beast
999e2fa0318b5982736d3ea01a418770ea802671
[ "BSL-1.0" ]
1
2016-06-22T17:13:44.000Z
2016-06-22T17:13:44.000Z
include/beast/http/resume_context.hpp
somayeghahari/beast
999e2fa0318b5982736d3ea01a418770ea802671
[ "BSL-1.0" ]
1
2019-03-25T01:54:42.000Z
2019-03-25T01:54:42.000Z
// // Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BEAST_HTTP_RESUME_CONTEXT_HPP #define BEAST_HTTP_RESUME_CONTEXT_HPP #include <functional> namespace beast { namespace http { /** A functor that resumes a write operation. An rvalue reference to an object of this type is provided by the write implementation to the `writer` associated with the body of a message being sent. If it is desired that the `writer` suspend the write operation (for example, to wait until data is ready), it can take ownership of the resume context using a move. Then, it returns `boost::indeterminate` to indicate that the write operation should suspend. Later, the calling code invokes the resume function and the write operation continues from where it left off. */ using resume_context = std::function<void(void)>; } // http } // beast #endif
30.342857
79
0.742938
gyas-kk
67d0d7db9c33a916b76be22c9042cb36aec32ccd
1,549
cpp
C++
gtasa_render_hook_rt/gta3_geometry_proxy.cpp
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
gtasa_render_hook_rt/gta3_geometry_proxy.cpp
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
gtasa_render_hook_rt/gta3_geometry_proxy.cpp
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
#include "gta3_geometry_proxy.h" RpGeometryRw35::~RpGeometryRw35() {} void *RpGeometryRw35::GetResEntry() { return static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->repEntry; } RwResEntry *&RpGeometryRw35::GetResEntryRef() { return static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->repEntry; } int32_t RpGeometryRw35::GetVertexCount() { return static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->numVertices; } uint32_t RpGeometryRw35::GetFlags() { return static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->flags; } RpMeshHeader *RpGeometryRw35::GetMeshHeader() { return static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->mesh; } int32_t RpGeometryRw35::GetMorphTargetCount() { return static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->numMorphTargets; } RpMorphTarget *RpGeometryRw35::GetMorphTarget( uint32_t id ) { return &static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->morphTarget[id]; } RwTexCoords *RpGeometryRw35::GetTexCoordSetPtr( uint32_t id ) { return static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->texCoords[id]; } RwRGBA *RpGeometryRw35::GetVertexColorPtr() { return static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->preLitLum; } void RpGeometryRw35::Unlock() { static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->lockedSinceLastInst = 0; } int32_t RpGeometryRw35::GetTriangleCount() { return static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->numTriangles; } RpTriangle *RpGeometryRw35::GetTrianglePtr() { return static_cast<RpGeometryGTA3 *>( m_pGeometryImpl )->triangles; }
24.203125
78
0.759199
HermanLederer
67d19e236cd3a1005d743daed6995749a2a55fa5
6,328
cpp
C++
src/util/HSet.cpp
chrhansk/HiGHS
311aa8571925ed23c952687569dbe7207e542e0a
[ "MIT" ]
null
null
null
src/util/HSet.cpp
chrhansk/HiGHS
311aa8571925ed23c952687569dbe7207e542e0a
[ "MIT" ]
null
null
null
src/util/HSet.cpp
chrhansk/HiGHS
311aa8571925ed23c952687569dbe7207e542e0a
[ "MIT" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the HiGHS linear optimization suite */ /* */ /* Written and engineered 2008-2022 at the University of Edinburgh */ /* */ /* Available as open-source under the MIT License */ /* */ /* Authors: Julian Hall, Ivet Galabova, Leona Gottwald and Michael */ /* Feldmeier */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file util/HSet.cpp * @brief */ #include "util/HSet.h" #include <cassert> bool HSet::setup(const HighsInt size, const HighsInt max_entry, const bool output_flag, FILE* log_file, const bool debug, const bool allow_assert) { setup_ = false; if (size <= 0) return false; if (max_entry < min_entry) return false; max_entry_ = max_entry; debug_ = debug; allow_assert_ = allow_assert; output_flag_ = output_flag; log_file_ = log_file; entry_.resize(size); pointer_.assign(max_entry_ + 1, no_pointer); count_ = 0; setup_ = true; return true; } void HSet::clear() { if (!setup_) setup(1, 0); pointer_.assign(max_entry_ + 1, no_pointer); count_ = 0; if (debug_) debug(); } bool HSet::add(const HighsInt entry) { if (entry < min_entry) return false; if (!setup_) setup(1, entry); if (entry > max_entry_) { // Entry exceeds what's allowable so far so can't be in the list pointer_.resize(entry + 1); for (HighsInt ix = max_entry_ + 1; ix < entry; ix++) pointer_[ix] = no_pointer; max_entry_ = entry; } else if (pointer_[entry] > no_pointer) { // Duplicate if (debug_) debug(); return false; } // New entry HighsInt size = entry_.size(); if (count_ == size) { size++; entry_.resize(size); } pointer_[entry] = count_; entry_[count_++] = entry; if (debug_) debug(); return true; } bool HSet::remove(const HighsInt entry) { if (!setup_) { setup(1, 0); if (debug_) debug(); return false; } if (entry < min_entry) return false; if (entry > max_entry_) return false; HighsInt pointer = pointer_[entry]; if (pointer == no_pointer) return false; pointer_[entry] = no_pointer; if (pointer < count_ - 1) { HighsInt last_entry = entry_[count_ - 1]; entry_[pointer] = last_entry; pointer_[last_entry] = pointer; } count_--; if (debug_) debug(); return true; } bool HSet::in(const HighsInt entry) const { if (entry < min_entry) return false; if (entry > max_entry_) return false; return pointer_[entry] != no_pointer; } bool HSet::debug() const { if (!setup_) { if (output_flag_) fprintf(log_file_, "HSet: ERROR setup_ not called\n"); if (allow_assert_) assert(setup_); return false; } bool max_entry_ok = max_entry_ >= min_entry; if (!max_entry_ok) { if (output_flag_) { fprintf(log_file_, "HSet: ERROR max_entry_ = %" HIGHSINT_FORMAT " < %" HIGHSINT_FORMAT "\n", max_entry_, min_entry); print(); } if (allow_assert_) assert(max_entry_ok); return false; } HighsInt size = entry_.size(); bool size_count_ok = size >= count_; if (!size_count_ok) { if (output_flag_) { fprintf(log_file_, "HSet: ERROR entry_.size() = %" HIGHSINT_FORMAT " is less than count_ = %" HIGHSINT_FORMAT "\n", size, count_); print(); } if (allow_assert_) assert(size_count_ok); return false; } // Check pointer_ is consistent with count_ and entry_ HighsInt count = 0; for (HighsInt ix = 0; ix <= max_entry_; ix++) { HighsInt pointer = pointer_[ix]; if (pointer == no_pointer) continue; bool pointer_ok = pointer >= 0 && pointer < count_; if (!pointer_ok) { if (output_flag_) { fprintf(log_file_, "HSet: ERROR pointer_[%" HIGHSINT_FORMAT "] = %" HIGHSINT_FORMAT " is not in [0, %" HIGHSINT_FORMAT "]\n", ix, pointer, count_); print(); } if (allow_assert_) assert(pointer_ok); return false; } count++; HighsInt entry = entry_[pointer]; bool entry_ok = entry == ix; if (!entry_ok) { if (output_flag_) { fprintf(log_file_, "HSet: ERROR entry_[%" HIGHSINT_FORMAT "] is %" HIGHSINT_FORMAT ", not %" HIGHSINT_FORMAT "\n", pointer, entry, ix); print(); } if (allow_assert_) assert(entry_ok); return false; } } bool count_ok = count == count_; if (!count_ok) { if (output_flag_) { fprintf(log_file_, "HSet: ERROR pointer_ has %" HIGHSINT_FORMAT " pointers, not %" HIGHSINT_FORMAT "\n", count, count_); print(); } if (allow_assert_) assert(count_ok); return false; } return true; } void HSet::print() const { if (!setup_) return; if (log_file_ == NULL) return; HighsInt size = entry_.size(); fprintf(log_file_, "\nSet(%" HIGHSINT_FORMAT ", %" HIGHSINT_FORMAT "):\n", size, max_entry_); fprintf(log_file_, "Pointers: Pointers|"); for (HighsInt ix = 0; ix <= max_entry_; ix++) { if (pointer_[ix] != no_pointer) fprintf(log_file_, " %4" HIGHSINT_FORMAT "", pointer_[ix]); } fprintf(log_file_, "\n"); fprintf(log_file_, " Entries |"); for (HighsInt ix = 0; ix <= max_entry_; ix++) { if (pointer_[ix] != no_pointer) fprintf(log_file_, " %4" HIGHSINT_FORMAT "", ix); } fprintf(log_file_, "\n"); fprintf(log_file_, "Entries: Indices |"); for (HighsInt ix = 0; ix < count_; ix++) fprintf(log_file_, " %4" HIGHSINT_FORMAT "", ix); fprintf(log_file_, "\n"); fprintf(log_file_, " Entries |"); for (HighsInt ix = 0; ix < count_; ix++) fprintf(log_file_, " %4" HIGHSINT_FORMAT "", entry_[ix]); fprintf(log_file_, "\n"); }
31.172414
80
0.545038
chrhansk
67d259930c44851e0083f1c3db196db3d70f9814
44,540
cpp
C++
code/cheonsa/cheonsa_reflection_types.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
code/cheonsa/cheonsa_reflection_types.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
code/cheonsa/cheonsa_reflection_types.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
#include "cheonsa_reflection_types.h" #include "cheonsa_reflection_property.h" #include "cheonsa_reflection_object.h" #include "cheonsa_reflection_class.h" #include "cheonsa__ops.h" #include <cassert> namespace cheonsa { reflection_value_container_c::reflection_value_container_c() : uint64{} , string8() , string16() { } reflection_value_container_c & reflection_value_container_c::operator = ( reflection_value_container_c const & other ) { for ( sint32_c i = 0; i < 4; i++ ) { uint64[ i ] = other.uint64[ i ]; } string8 = other.string8; string16 = other.string16; return *this; } reflection_property_value_changed_information_c::reflection_property_value_changed_information_c() : reflection_object( nullptr ) , reflection_property( nullptr ) , before_value() , after_value() { } reflection_property_value_changed_information_c::reflection_property_value_changed_information_c( reflection_property_value_changed_information_c const & other ) : reflection_object( other.reflection_object ) , reflection_property( other.reflection_property ) , before_value( other.before_value ) , after_value( other.after_value ) { } reflection_property_value_changed_information_c & reflection_property_value_changed_information_c::operator = ( reflection_property_value_changed_information_c const & other ) { reflection_object = other.reflection_object; reflection_property = other.reflection_property; before_value = other.before_value; after_value = other.after_value; return *this; } boolean_c reflection_get_object_property_value( reflection_object_c * object, reflection_property_c const * property, reflection_value_container_c & value ) { assert( object && property ); assert( object->_reflection_class == property->_reflection_class ); if ( property->_type == data_type_e_string8 ) { assert( property->_accessors._value_getter ); return property->_accessors._value_getter( object, &value.string8, property->_type, property->_type_count ); } else if ( property->_type == data_type_e_string16 ) { assert( property->_accessors._value_getter ); return property->_accessors._value_getter( object, &value.string16, property->_type, property->_type_count ); } else if ( property->_type >= data_type_e_uint8 && property->_type <= data_type_e_float64 ) { assert( property->_accessors._value_getter ); return property->_accessors._value_getter( object, &value, property->_type, property->_type_count ); } return false; } boolean_c reflection_set_object_property_value( reflection_object_c * object, reflection_property_c const * property, reflection_value_container_c const & value ) { assert( object && property ); assert( object->_reflection_class == property->_reflection_class ); assert( property->_type >= data_type_e_string8 && property->_type <= data_type_e_float64 ); assert( property->_accessors._value_setter ); if ( property->_type == data_type_e_string8 ) { return property->_accessors._value_setter( object, &value.string8, property->_type, property->_type_count ); } else if ( property->_type == data_type_e_string16 ) { return property->_accessors._value_setter( object, &value.string16, property->_type, property->_type_count ); } else { return property->_accessors._value_setter( object, &value, property->_type, property->_type_count ); } } string16_c reflection_convert_value_to_string16( reflection_property_c const * property, reflection_value_container_c const & property_value, sint32_c property_value_element_index ) { assert( property ); //reflection_value_container_c value_b; //reflection_value_container_c & value = value_a ? *value_a : value_b; string8_c value_as_string8; string16_c value_as_string16; if ( property->_view == data_view_e_color ) { vector64x4_c value_as_color( 1.0, 1.0, 1.0, 1.0 ); if ( property->_type == data_type_e_uint32 ) { assert( property->_type_count == 1 ); if ( property_value_element_index == 0 ) { ops::convert_uint8_to_string8( static_cast< uint8_c >( property_value.uint32[ 0 ] >> 24 ), value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 1 ) { ops::convert_uint8_to_string8( static_cast< uint8_c >( property_value.uint32[ 0 ] >> 16 ), value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 2 ) { ops::convert_uint8_to_string8( static_cast< uint8_c >( property_value.uint32[ 0 ] >> 8 ), value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 3 ) { ops::convert_uint8_to_string8( static_cast< uint8_c >( property_value.uint32[ 0 ] ), value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } //else if ( property_value_element_index == -1 ) //{ // assert( property_value_element_index == 0 || property_value_element_index == -1 ); // value_as_color.a = static_cast< float64_c >( ( property_value.uint32[ 0 ] >> 24 ) & 0x000000FF ) / 255.0; // value_as_color.b = static_cast< float64_c >( ( property_value.uint32[ 0 ] >> 16 ) & 0x000000FF ) / 255.0; // value_as_color.c = static_cast< float64_c >( ( property_value.uint32[ 0 ] >> 8 ) & 0x000000FF ) / 255.0; // value_as_color.d = static_cast< float64_c >( ( property_value.uint32[ 0 ] ) & 0x000000FF ) / 255.0; // value_as_string8 = "#"; // string8_c hex; // ops::convert_rgba_to_hexadecimal_string8( value_as_color, hex ); // value_as_string8 += hex; // value_as_string16 = value_as_string8; // return value_as_string16; //} else { assert( false ); } } else if ( property->_type == data_type_e_uint8 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); if ( property_value_element_index == 0 ) { ops::convert_uint8_to_string8( property_value.uint8[ 0 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 1 ) { ops::convert_uint8_to_string8( property_value.uint8[ 1 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 2 ) { ops::convert_uint8_to_string8( property_value.uint8[ 2 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 3 ) { ops::convert_uint8_to_string8( property_value.uint8[ 3 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } //else if ( property_value_element_index == -1 ) //{ // value_as_color.a = static_cast< float64_c >( property_value.uint8[ 0 ] ) / 255.0; // value_as_color.b = static_cast< float64_c >( property_value.uint8[ 1 ] ) / 255.0; // value_as_color.c = static_cast< float64_c >( property_value.uint8[ 2 ] ) / 255.0; // value_as_string8 = "#"; // string8_c hex; // if ( property->_type_count == 4 ) // { // value_as_color.d = static_cast< float64_c >( property_value.uint8[ 3 ] ) / 255.0; // ops::convert_rgba_to_hexadecimal_string8( value_as_color, hex ); // } // else // { // ops::convert_rgb_to_hexadecimal_string8( vector64x3_c( value_as_color.as_array() ), hex ); // } // value_as_string8 += hex; // value_as_string16 = value_as_string8; // return value_as_string16; //} assert( false ); } else if ( property->_type == data_type_e_uint16 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); if ( property_value_element_index == 0 ) { ops::convert_float64_to_string8( static_cast< float64_c >( property_value.uint16[ 0 ] ) / 65535.0, value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 1 ) { ops::convert_float64_to_string8( static_cast< float64_c >( property_value.uint16[ 1 ] ) / 65535.0, value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 2 ) { ops::convert_float64_to_string8( static_cast< float64_c >( property_value.uint16[ 2 ] ) / 65535.0, value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 3 ) { assert( property->_type_count == 4 ); ops::convert_float64_to_string8( static_cast< float64_c >( property_value.uint16[ 3 ] ) / 65535.0, value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } //else if ( property_value_element_index == -1 ) //{ // value_as_color.a = static_cast< float64_c >( property_value.uint16[ 0 ] ) / 65535.0; // value_as_color.b = static_cast< float64_c >( property_value.uint16[ 1 ] ) / 65535.0; // value_as_color.c = static_cast< float64_c >( property_value.uint16[ 2 ] ) / 65535.0; // if ( property->_type_count == 4 ) // { // value_as_color.d = static_cast< float64_c >( property_value.uint16[ 3 ] ) / 65535.0; // } //} else { assert( false ); } } else if ( property->_type == data_type_e_float32 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); if ( property_value_element_index == 0 ) { ops::convert_float32_to_string8( property_value.float32[ 0 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 1 ) { ops::convert_float32_to_string8( property_value.float32[ 1 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 2 ) { ops::convert_float32_to_string8( property_value.float32[ 2 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 3 ) { assert( property->_type_count == 4 ); ops::convert_float32_to_string8( property_value.float32[ 3 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } //else if ( property_value_element_index == -1 ) //{ // value_as_color.a = static_cast< float64_c >( property_value.float32[ 0 ] ); // value_as_color.b = static_cast< float64_c >( property_value.float32[ 1 ] ); // value_as_color.c = static_cast< float64_c >( property_value.float32[ 2 ] ); // if ( property->_type_count == 4 ) // { // value_as_color.d = static_cast< float64_c >( property_value.float32[ 0 ] ); // } //} else { assert( false ); } } else if ( property->_type == data_type_e_float64 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); if ( property_value_element_index == 0 ) { ops::convert_float64_to_string8( property_value.float64[ 0 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 1 ) { ops::convert_float64_to_string8( property_value.float64[ 1 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 2 ) { ops::convert_float64_to_string8( property_value.float64[ 2 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } else if ( property_value_element_index == 3 ) { assert( property->_type_count == 4 ); ops::convert_float64_to_string8( property_value.float64[ 3 ], value_as_string8 ); value_as_string16 = value_as_string8; return value_as_string16; } //else if ( property_value_element_index == -1 ) //{ // value_as_color.a = property_value.float64[ 0 ]; // value_as_color.b = property_value.float64[ 1 ]; // value_as_color.c = property_value.float64[ 2 ]; // if ( property->_type_count == 4 ) // { // value_as_color.d = property_value.float64[ 3 ]; // } //} else { assert( false ); } } else { assert( false ); } if ( property->_type_count == 3 ) { ops::convert_float64xn_to_string8( core_list_c< float64_c >( core_list_mode_e_static, value_as_color.as_array(), 3 ), value_as_string8 ); } else if ( property->_type_count == 4 ) { ops::convert_float64xn_to_string8( core_list_c< float64_c >( core_list_mode_e_static, value_as_color.as_array(), 4 ), value_as_string8 ); } else { assert( false ); } value_as_string16 = value_as_string8; return value_as_string16; } else if ( property->_view == data_view_e_euler_angles ) { vector32x3_c value_as_euler_angles; if ( property->_type == data_type_e_float32 ) { if ( property->_type_count == 3 ) { value_as_euler_angles.a = property_value.float32[ 0 ]; value_as_euler_angles.b = property_value.float32[ 1 ]; value_as_euler_angles.c = property_value.float32[ 2 ]; } else if ( property->_type_count == 4 ) { quaternion32_c value_as_quaternion; value_as_quaternion.a = property_value.float32[ 0 ]; value_as_quaternion.b = property_value.float32[ 1 ]; value_as_quaternion.c = property_value.float32[ 2 ]; value_as_quaternion.d = property_value.float32[ 3 ]; value_as_euler_angles = ops::euler_angles_from_rotation_quaternion32( quaternion32_c( property_value.float32 ) ); } else { assert( false ); } } else if ( property->_type == data_type_e_float64 ) { if ( property->_type_count == 3 ) { value_as_euler_angles.a = static_cast< float32_c >( property_value.float64[ 0 ] ); value_as_euler_angles.b = static_cast< float32_c >( property_value.float64[ 1 ] ); value_as_euler_angles.c = static_cast< float32_c >( property_value.float64[ 2 ] ); } else if ( property->_type_count == 4 ) { quaternion32_c value_as_quaternion; value_as_quaternion.a = static_cast< float32_c >( property_value.float64[ 0 ] ); value_as_quaternion.b = static_cast< float32_c >( property_value.float64[ 1 ] ); value_as_quaternion.c = static_cast< float32_c >( property_value.float64[ 2 ] ); value_as_quaternion.d = static_cast< float32_c >( property_value.float64[ 3 ] ); value_as_euler_angles = ops::euler_angles_from_rotation_quaternion32( value_as_quaternion ); } else { assert( false ); } } else { assert( false ); } if ( property_value_element_index == 0 ) { ops::convert_float32_to_string8( value_as_euler_angles.a, value_as_string8 ); } else if ( property_value_element_index == 1 ) { ops::convert_float32_to_string8( value_as_euler_angles.b, value_as_string8 ); } else if ( property_value_element_index == 2 ) { ops::convert_float32_to_string8( value_as_euler_angles.c, value_as_string8 ); } //else if ( property_value_element_index == -1 ) //{ // ops::convert_float32xn_to_string8( core_list_c< float32_c >( core_list_mode_e_static, value_as_euler_angles.as_array(), 3 ), value_as_string8 ); //} else { assert( false ); } value_as_string16 = value_as_string8; return value_as_string16; } else { assert( property_value_element_index == 0 ); if ( property->_type == data_type_e_string8 ) { assert( property->_type_count == 1 ); value_as_string16 = property_value.string8; } else if ( property->_type == data_type_e_string16 ) { assert( property->_type_count == 1 ); value_as_string16 = property_value.string16; } else if ( property->_type == data_type_e_uint8 ) { ops::convert_uint8xn_to_string8( core_list_c< uint8_c >( core_list_mode_e_static, property_value.uint8, property->_type_count ), value_as_string8 ); value_as_string16 = value_as_string8; } else if ( property->_type == data_type_e_sint8 ) { ops::convert_sint8xn_to_string8( core_list_c< sint8_c >( core_list_mode_e_static, property_value.sint8, property->_type_count ), value_as_string8 ); value_as_string16 = value_as_string8; } else if ( property->_type == data_type_e_uint16 ) { ops::convert_uint16xn_to_string8( core_list_c< uint16_c >( core_list_mode_e_static, property_value.uint16, property->_type_count ), value_as_string8 ); value_as_string16 = value_as_string8; } else if ( property->_type == data_type_e_sint16 ) { ops::convert_sint16xn_to_string8( core_list_c< sint16_c >( core_list_mode_e_static, property_value.sint16, property->_type_count ), value_as_string8 ); value_as_string16 = value_as_string8; } else if ( property->_type == data_type_e_uint32 ) { ops::convert_uint32xn_to_string8( core_list_c< uint32_c >( core_list_mode_e_static, property_value.uint32, property->_type_count ), value_as_string8 ); } else if ( property->_type == data_type_e_sint32 ) { ops::convert_sint32xn_to_string8( core_list_c< sint32_c >( core_list_mode_e_static, property_value.sint32, property->_type_count ), value_as_string8 ); value_as_string16 = value_as_string8; } else if ( property->_type == data_type_e_uint64 ) { ops::convert_uint64xn_to_string8( core_list_c< uint64_c >( core_list_mode_e_static, property_value.uint64, property->_type_count ), value_as_string8 ); value_as_string16 = value_as_string8; } else if ( property->_type == data_type_e_sint64 ) { ops::convert_sint64xn_to_string8( core_list_c< sint64_c >( core_list_mode_e_static, property_value.sint64, property->_type_count ), value_as_string8 ); value_as_string16 = value_as_string8; } else if ( property->_type == data_type_e_float32 ) { ops::convert_float32xn_to_string8( core_list_c< float32_c >( core_list_mode_e_static, property_value.float32, property->_type_count ), value_as_string8 ); value_as_string16 = value_as_string8; } else if ( property->_type == data_type_e_float64 ) { ops::convert_float64xn_to_string8( core_list_c< float64_c >( core_list_mode_e_static, property_value.float64, property->_type_count ), value_as_string8 ); value_as_string16 = value_as_string8; } else { assert( false ); } } return value_as_string16; } boolean_c reflection_convert_string16_to_value( reflection_property_c const * property, reflection_value_container_c & property_value, sint32_c property_value_element_index, string16_c const & property_value_as_string16 ) { assert( property ); string8_c value_as_string8; value_as_string8 = property_value_as_string16; value_as_string8 = ops::string8_trim( value_as_string8 ); if ( property->_view == data_view_e_color ) { /* if ( property_value_element_index == -1 ) { // string value holds all elements. vector64x4_c value_as_color; if ( !ops::convert_string8_to_rgba( value_as_string8, value_as_color ) ) { return false; } if ( property->_type == data_type_e_uint32 ) { assert( property->_type_count == 1 ); property_value.uint32[ 0 ] = ( static_cast< uint32_c >( ops::math_saturate( value_as_color.a ) * 255.0 ) << 24 ) | ( static_cast< uint32_c >( ops::math_saturate( value_as_color.b ) * 255.0 ) << 16 ) | ( static_cast< uint32_c >( ops::math_saturate( value_as_color.c ) * 255.0 ) << 8 ) | ( static_cast< uint32_c >( ops::math_saturate( value_as_color.d ) * 255.0 ) ); } else if ( property->_type == data_type_e_uint8 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); property_value.uint8[ 0 ] = static_cast< uint8_c >( ops::math_saturate( value_as_color.a ) * 255 ); property_value.uint8[ 1 ] = static_cast< uint8_c >( ops::math_saturate( value_as_color.b ) * 255 ); property_value.uint8[ 2 ] = static_cast< uint8_c >( ops::math_saturate( value_as_color.c ) * 255 ); property_value.uint8[ 3 ] = static_cast< uint8_c >( ops::math_saturate( value_as_color.d ) * 255 ); // this element may not be used but it's okay to set it anyway. } else if ( property->_type == data_type_e_uint16 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); property_value.uint16[ 0 ] = static_cast< uint16_c >( ops::math_saturate( value_as_color.a ) * 65535.0 ); property_value.uint16[ 1 ] = static_cast< uint16_c >( ops::math_saturate( value_as_color.b ) * 65535.0 ); property_value.uint16[ 2 ] = static_cast< uint16_c >( ops::math_saturate( value_as_color.c ) * 65535.0 ); property_value.uint16[ 3 ] = static_cast< uint16_c >( ops::math_saturate( value_as_color.d ) * 65535.0 ); // this element may not be used but it's okay to set it anyway. } else if ( property->_type == data_type_e_float32 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); property_value.float32[ 0 ] = static_cast< float32_c >( value_as_color.a ); property_value.float32[ 1 ] = static_cast< float32_c >( value_as_color.b ); property_value.float32[ 2 ] = static_cast< float32_c >( value_as_color.c ); property_value.float32[ 3 ] = static_cast< float32_c >( value_as_color.d ); // this element may not be used but it's okay to set it anyway. } else if ( property->_type == data_type_e_float64 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); property_value.float64[ 0 ] = value_as_color.a; property_value.float64[ 1 ] = value_as_color.b; property_value.float64[ 2 ] = value_as_color.c; property_value.float64[ 3 ] = value_as_color.d; // this element may not be used but it's okay to set it anyway. } else { assert( false ); } } else */ { // string value holds one element. if ( property->_type == data_type_e_uint32 ) { assert( property->_type_count == 1 ); assert( property_value_element_index >= 0 && property_value_element_index <= 3 ); uint8_c value_as_uint8 = 0; if ( !ops::convert_string8_to_uint8( value_as_string8, value_as_uint8 ) ) { return false; } property_value.uint32[ 0 ] &= 0x000000FF << ( property_value_element_index * 8 ); property_value.uint32[ 0 ] |= static_cast< uint32_c >( value_as_uint8 ) << ( property_value_element_index * 8 ); return true; } else if ( property->_type == data_type_e_uint8 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); assert( property_value_element_index >= 0 && property_value_element_index < property->_type_count ); uint8_c value_as_uint8 = 0; if ( !ops::convert_string8_to_uint8( value_as_string8, value_as_uint8 ) ) { return false; } property_value.uint8[ property_value_element_index ] = value_as_uint8; return true; } else if ( property->_type == data_type_e_uint16 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); assert( property_value_element_index >= 0 && property_value_element_index < property->_type_count ); uint16_c value_as_uint16 = 0; if ( !ops::convert_string8_to_uint16( value_as_string8, value_as_uint16 ) ) { return false; } property_value.uint16[ property_value_element_index ] = value_as_uint16; return true; } else if ( property->_type == data_type_e_float32 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); assert( property_value_element_index >= 0 && property_value_element_index < property->_type_count ); float32_c value_as_float32 = 0.0f; if ( !ops::convert_string8_to_float32( value_as_string8, value_as_float32 ) ) { return false; } property_value.float32[ property_value_element_index ] = value_as_float32; return true; } else if ( property->_type == data_type_e_float64 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); assert( property_value_element_index >= 0 && property_value_element_index < property->_type_count ); float64_c value_as_float64 = 0.0; if ( !ops::convert_string8_to_float64( value_as_string8, value_as_float64 ) ) { return false; } property_value.float64[ property_value_element_index ] = value_as_float64; return true; } else { assert( false ); } } } else if ( property->_view == data_view_e_euler_angles ) { /* if ( property_value_element_index == -1 ) { // string value holds all elements. vector32x3_c value_as_euler_angles; if ( !ops::convert_string8_to_float32xn( value_as_string8, core_list_c< float32_c >( core_list_mode_e_static, value_as_euler_angles.as_array(), 3 ) ) ) { return false; } if ( property->_type == data_type_e_float32 ) { if ( property->_type_count == 3 ) { property_value.float32[ 0 ] = value_as_euler_angles.a; property_value.float32[ 1 ] = value_as_euler_angles.b; property_value.float32[ 2 ] = value_as_euler_angles.c; } else if ( property->_type_count == 4 ) { quaternion32_c value_as_quaternion = ops::rotation_quaternion32_from_euler_angles( vector32x3_c( value_as_euler_angles ) ); property_value.float32[ 0 ] = value_as_quaternion.a; property_value.float32[ 1 ] = value_as_quaternion.b; property_value.float32[ 2 ] = value_as_quaternion.c; property_value.float32[ 3 ] = value_as_quaternion.d; } else { assert( false ); } } else if ( property->_type == data_type_e_float64 ) { if ( property->_type_count == 3 ) { property_value.float64[ 0 ] = static_cast< float64_c >( value_as_euler_angles.a ); property_value.float64[ 1 ] = static_cast< float64_c >( value_as_euler_angles.b ); property_value.float64[ 2 ] = static_cast< float64_c >( value_as_euler_angles.c ); } else if ( property->_type_count == 4 ) { quaternion32_c quaternion = ops::rotation_quaternion32_from_euler_angles( vector32x3_c( value_as_euler_angles ) ); property_value.float64[ 0 ] = static_cast< float64_c >( quaternion.a ); property_value.float64[ 1 ] = static_cast< float64_c >( quaternion.b ); property_value.float64[ 2 ] = static_cast< float64_c >( quaternion.c ); property_value.float64[ 3 ] = static_cast< float64_c >( quaternion.d ); } else { assert( false ); } } else { assert( false ); } } else */ { // string value holds one element. float64_c value_as_float64 = 0.0f; if ( !ops::convert_string8_to_float64( value_as_string8, value_as_float64 ) ) { return false; } // get current value as euler angles, because we have to set all the element values at once even though we only want to modify a single element. vector64x3_c value_as_euler_angles; if ( property->_type_count == 3 ) { // current value is already formatted as euler angles. if ( property->_type == data_type_e_float32 ) { value_as_euler_angles.a = static_cast< float64_c >( property_value.float32[ 0 ] ); value_as_euler_angles.b = static_cast< float64_c >( property_value.float32[ 1 ] ); value_as_euler_angles.c = static_cast< float64_c >( property_value.float32[ 2 ] ); } else if ( property->_type == data_type_e_float64 ) { value_as_euler_angles.a = property_value.float64[ 0 ]; value_as_euler_angles.b = property_value.float64[ 1 ]; value_as_euler_angles.c = property_value.float64[ 2 ]; } else { assert( false ); } } else if ( property->_type_count == 4 ) { // current value is formatted as quaternion, convert it to euler angles. quaternion32_c quaternion; if ( property->_type == data_type_e_float32 ) { quaternion.a = property_value.float32[ 0 ]; quaternion.b = property_value.float32[ 1 ]; quaternion.c = property_value.float32[ 2 ]; quaternion.d = property_value.float32[ 3 ]; } else if ( property->_type == data_type_e_float64 ) { quaternion.a = static_cast< float32_c >( property_value.float64[ 0 ] ); quaternion.b = static_cast< float32_c >( property_value.float64[ 1 ] ); quaternion.c = static_cast< float32_c >( property_value.float64[ 2 ] ); quaternion.d = static_cast< float32_c >( property_value.float64[ 3 ] ); } else { assert( false ); } value_as_euler_angles = vector64x3_c( ops::euler_angles_from_rotation_quaternion32( quaternion ) ); } // modify the single element value. value_as_euler_angles.get_element_at_index( property_value_element_index ) = value_as_float64; // convert the euler angles back to whatever the property format is. if ( property->_type_count == 3 ) { // current value is already formatted as euler angles. if ( property->_type == data_type_e_float32 ) { property_value.float32[ 0 ] = static_cast< float32_c >( value_as_euler_angles.a ); property_value.float32[ 1 ] = static_cast< float32_c >( value_as_euler_angles.b ); property_value.float32[ 2 ] = static_cast< float32_c >( value_as_euler_angles.c ); } else if ( property->_type == data_type_e_float64 ) { property_value.float64[ 0 ] = value_as_euler_angles.a; property_value.float64[ 1 ] = value_as_euler_angles.b; property_value.float64[ 2 ] = value_as_euler_angles.c; } else { assert( false ); } } else if ( property->_type_count == 4 ) { // current value is formatted as quaternion, so we have to convert. quaternion32_c value_as_quaternion = ops::rotation_quaternion32_from_euler_angles( vector32x3_c( value_as_euler_angles ) ); if ( property->_type == data_type_e_float32 ) { property_value.float32[ 0 ] = value_as_quaternion.a; property_value.float32[ 1 ] = value_as_quaternion.b; property_value.float32[ 2 ] = value_as_quaternion.c; property_value.float32[ 3 ] = value_as_quaternion.d; } else if ( property->_type == data_type_e_float64 ) { property_value.float64[ 0 ] = static_cast< float64_c >( value_as_quaternion.a ); property_value.float64[ 1 ] = static_cast< float64_c >( value_as_quaternion.b ); property_value.float64[ 2 ] = static_cast< float64_c >( value_as_quaternion.c ); property_value.float64[ 3 ] = static_cast< float64_c >( value_as_quaternion.d ); } else { assert( false ); } } return true; } } else { assert( property_value_element_index == 0 ); if ( property->_type == data_type_e_string8 ) { property_value.string8 = property_value_as_string16; } else if ( property->_type == data_type_e_string16 ) { property_value.string16 = property_value_as_string16; } else if ( property->_type == data_type_e_uint8 ) { if ( !ops::convert_string8_to_uint8xn( value_as_string8, core_list_c< uint8_c >( core_list_mode_e_static, property_value.uint8, property->_type_count ) ) ) { return false; } } else if ( property->_type == data_type_e_sint8 ) { if ( !ops::convert_string8_to_sint8xn( value_as_string8, core_list_c< sint8_c >( core_list_mode_e_static, property_value.sint8, property->_type_count ) ) ) { return false; } } else if ( property->_type == data_type_e_uint16 ) { if ( !ops::convert_string8_to_uint16xn( value_as_string8, core_list_c< uint16_c >( core_list_mode_e_static, property_value.uint16, property->_type_count ) ) ) { return false; } } else if ( property->_type == data_type_e_sint16 ) { if ( !ops::convert_string8_to_sint16xn( value_as_string8, core_list_c< sint16_c >( core_list_mode_e_static, property_value.sint16, property->_type_count ) ) ) { return false; } } else if ( property->_type == data_type_e_uint32 ) { if ( !ops::convert_string8_to_uint32xn( value_as_string8, core_list_c< uint32_c >( core_list_mode_e_static, property_value.uint32, property->_type_count ) ) ) { return false; } } else if ( property->_type == data_type_e_sint32 ) { if ( !ops::convert_string8_to_sint32xn( value_as_string8, core_list_c< sint32_c >( core_list_mode_e_static, property_value.sint32, property->_type_count ) ) ) { return false; } } else if ( property->_type == data_type_e_uint64 ) { if ( !ops::convert_string8_to_uint64xn( value_as_string8, core_list_c< uint64_c >( core_list_mode_e_static, property_value.uint64, property->_type_count ) ) ) { return false; } } else if ( property->_type == data_type_e_sint64 ) { if ( !ops::convert_string8_to_sint64xn( value_as_string8, core_list_c< sint64_c >( core_list_mode_e_static, property_value.sint64, property->_type_count ) ) ) { return false; } } else if ( property->_type == data_type_e_float32 ) { if ( !ops::convert_string8_to_float32xn( value_as_string8, core_list_c< float32_c >( core_list_mode_e_static, property_value.float32, property->_type_count ) ) ) { return false; } } else if ( property->_type == data_type_e_float64 ) { if ( !ops::convert_string8_to_float64xn( value_as_string8, core_list_c< float64_c >( core_list_mode_e_static, property_value.float64, property->_type_count ) ) ) { return false; } } else { assert( false ); } } return true; } vector64x4_c reflection_convert_value_to_color( reflection_property_c const * property, reflection_value_container_c const & value ) { assert( property ); assert( property->_view == data_view_e_color ); vector64x4_c value_as_color; value_as_color.d = 1.0; if ( property->_type == data_type_e_uint32 ) { assert( property->_type_count == 1 ); value_as_color.a = static_cast< float64_c >( ( value.uint32[ 0 ] >> 24 ) & 0x000000FF ) / 255.0; value_as_color.b = static_cast< float64_c >( ( value.uint32[ 0 ] >> 16 ) & 0x000000FF ) / 255.0; value_as_color.c = static_cast< float64_c >( ( value.uint32[ 0 ] >> 8 ) & 0x000000FF ) / 255.0; value_as_color.d = static_cast< float64_c >( ( value.uint32[ 0 ] ) & 0x000000FF ) / 255.0; } else if ( property->_type == data_type_e_uint8 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); value_as_color.a = static_cast< float64_c >( value.uint8[ 0 ] ) / 255.0; value_as_color.b = static_cast< float64_c >( value.uint8[ 1 ] ) / 255.0; value_as_color.c = static_cast< float64_c >( value.uint8[ 2 ] ) / 255.0; if ( property->_type_count == 4 ) { value_as_color.d = static_cast< float64_c >( value.uint8[ 3 ] ) / 255.0; } } else if ( property->_type == data_type_e_uint16 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); value_as_color.a = static_cast< float64_c >( value.uint16[ 0 ] ) / 65535.0; value_as_color.b = static_cast< float64_c >( value.uint16[ 1 ] ) / 65535.0; value_as_color.c = static_cast< float64_c >( value.uint16[ 2 ] ) / 65535.0; if ( property->_type_count == 4 ) { value_as_color.d = static_cast< float64_c >( value.uint16[ 3 ] ) / 65535.0; } } else if ( property->_type == data_type_e_float32 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); value_as_color.a = static_cast< float64_c >( value.float32[ 0 ] ); value_as_color.b = static_cast< float64_c >( value.float32[ 1 ] ); value_as_color.c = static_cast< float64_c >( value.float32[ 2 ] ); if ( property->_type_count == 4 ) { value_as_color.d = static_cast< float64_c >( value.float32[ 3 ] ); } } else if ( property->_type == data_type_e_float64 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); value_as_color.a = value.float64[ 0 ]; value_as_color.b = value.float64[ 1 ]; value_as_color.c = value.float64[ 2 ]; if ( property->_type_count == 4 ) { value_as_color.d = value.float64[ 3 ]; } } else { assert( false ); } return value_as_color; } void_c reflection_convert_color_to_value( reflection_property_c const * property, reflection_value_container_c & value, vector64x4_c const & value_as_color ) { assert( property ); assert( property->_view == data_view_e_color ); if ( property->_type == data_type_e_uint32 ) { assert( property->_type_count == 1 ); value.uint32[ 0 ] = ( static_cast< uint32_c >( ops::math_saturate( value_as_color.a ) * 255.0 ) << 24 ) | ( static_cast< uint32_c >( ops::math_saturate( value_as_color.b ) * 255.0 ) << 16 ) | ( static_cast< uint32_c >( ops::math_saturate( value_as_color.c ) * 255.0 ) << 8 ) | ( static_cast< uint32_c >( ops::math_saturate( value_as_color.d ) * 255.0 ) ); } else if ( property->_type == data_type_e_uint8 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); value.uint8[ 0 ] = static_cast< uint8_c >( ops::math_saturate( value_as_color.a ) * 255 ); value.uint8[ 1 ] = static_cast< uint8_c >( ops::math_saturate( value_as_color.b ) * 255 ); value.uint8[ 2 ] = static_cast< uint8_c >( ops::math_saturate( value_as_color.c ) * 255 ); value.uint8[ 3 ] = static_cast< uint8_c >( ops::math_saturate( value_as_color.d ) * 255 ); // this element may not be used but it's okay to set it anyway. } else if ( property->_type == data_type_e_uint16 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); value.uint16[ 0 ] = static_cast< uint16_c >( ops::math_saturate( value_as_color.a ) * 65535.0 ); value.uint16[ 1 ] = static_cast< uint16_c >( ops::math_saturate( value_as_color.b ) * 65535.0 ); value.uint16[ 2 ] = static_cast< uint16_c >( ops::math_saturate( value_as_color.c ) * 65535.0 ); value.uint16[ 3 ] = static_cast< uint16_c >( ops::math_saturate( value_as_color.d ) * 65535.0 ); // this element may not be used but it's okay to set it anyway. } else if ( property->_type == data_type_e_float32 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); value.float32[ 0 ] = static_cast< float32_c >( value_as_color.a ); value.float32[ 1 ] = static_cast< float32_c >( value_as_color.b ); value.float32[ 2 ] = static_cast< float32_c >( value_as_color.c ); value.float32[ 3 ] = static_cast< float32_c >( value_as_color.d ); } else if ( property->_type == data_type_e_float64 ) { assert( property->_type_count == 3 || property->_type_count == 4 ); value.float64[ 0 ] = value_as_color.a; value.float64[ 1 ] = value_as_color.b; value.float64[ 2 ] = value_as_color.c; value.float64[ 3 ] = value_as_color.d; } else { assert( false ); } } vector32x3_c reflection_convert_value_to_euler_angles( reflection_property_c const * property, reflection_value_container_c const & value ) { assert( property ); assert( property->_view == data_view_e_euler_angles ); vector32x3_c value_as_euler_angles; if ( property->_type == data_type_e_float32 ) { if ( property->_type_count == 3 ) { value_as_euler_angles.a = value.float32[ 0 ]; value_as_euler_angles.b = value.float32[ 1 ]; value_as_euler_angles.c = value.float32[ 2 ]; } else if ( property->_type_count == 4 ) { quaternion32_c value_as_quaternion; value_as_quaternion.a = value.float32[ 0 ]; value_as_quaternion.b = value.float32[ 1 ]; value_as_quaternion.c = value.float32[ 2 ]; value_as_quaternion.d = value.float32[ 3 ]; value_as_euler_angles = ops::euler_angles_from_rotation_quaternion32( value_as_quaternion ); } else { assert( false ); } } else if ( property->_type == data_type_e_float64 ) { if ( property->_type_count == 3 ) { value_as_euler_angles.a = static_cast< float32_c >( value.float64[ 0 ] ); value_as_euler_angles.b = static_cast< float32_c >( value.float64[ 1 ] ); value_as_euler_angles.c = static_cast< float32_c >( value.float64[ 2 ] ); } else if ( property->_type_count == 4 ) { quaternion32_c value_as_quaternion; value_as_quaternion.a = static_cast< float32_c >( value.float64[ 0 ] ); value_as_quaternion.b = static_cast< float32_c >( value.float64[ 1 ] ); value_as_quaternion.c = static_cast< float32_c >( value.float64[ 2 ] ); value_as_quaternion.d = static_cast< float32_c >( value.float64[ 3 ] ); value_as_euler_angles = ops::euler_angles_from_rotation_quaternion32( value_as_quaternion ); } else { assert( false ); } } else { assert( false ); } return value_as_euler_angles; } void_c reflection_convert_euler_angles_to_value( reflection_property_c const * property, reflection_value_container_c & value, vector32x3_c const & value_as_euler_angles ) { assert( property ); assert( property->_view == data_view_e_euler_angles ); if ( property->_type == data_type_e_float32 ) { if ( property->_type_count == 3 ) { value.float32[ 0 ] = value_as_euler_angles.a; value.float32[ 1 ] = value_as_euler_angles.b; value.float32[ 2 ] = value_as_euler_angles.c; } else if ( property->_type_count == 4 ) { quaternion32_c value_as_quaternion = ops::rotation_quaternion32_from_euler_angles( value_as_euler_angles ); value.float32[ 0 ] = value_as_quaternion.a; value.float32[ 1 ] = value_as_quaternion.b; value.float32[ 2 ] = value_as_quaternion.c; value.float32[ 3 ] = value_as_quaternion.d; } else { assert( false ); } } else if ( property->_type == data_type_e_float64 ) { if ( property->_type_count == 3 ) { value.float64[ 0 ] = static_cast< float64_c >( value_as_euler_angles.a ); value.float64[ 1 ] = static_cast< float64_c >( value_as_euler_angles.b ); value.float64[ 2 ] = static_cast< float64_c >( value_as_euler_angles.c ); } else if ( property->_type_count == 4 ) { quaternion32_c value_as_quaternion = ops::rotation_quaternion32_from_euler_angles( value_as_euler_angles ); value.float64[ 0 ] = static_cast< float64_c >( value_as_quaternion.a ); value.float64[ 1 ] = static_cast< float64_c >( value_as_quaternion.b ); value.float64[ 2 ] = static_cast< float64_c >( value_as_quaternion.c ); value.float64[ 3 ] = static_cast< float64_c >( value_as_quaternion.d ); } else { assert( false ); } } else { assert( false ); } } boolean_c reflection_compare_values( reflection_property_c const * property, reflection_value_container_c const & a, reflection_value_container_c const & b ) { assert( property ); assert( property->_type_count >= 1 && property->_type_count <= 4 ); if ( property->_type == data_type_e_uint8 || property->_type == data_type_e_sint8 ) { for ( sint32_c i = 0; i < property->_type_count; i++ ) { if ( a.uint8[ i ] != b.uint8[ i ] ) { return false; } } } else if ( property->_type == data_type_e_uint16 || property->_type == data_type_e_sint16 ) { for ( sint32_c i = 0; i < property->_type_count; i++ ) { if ( a.uint16[ i ] != b.uint16[ i ] ) { return false; } } } else if ( property->_type == data_type_e_uint32 || property->_type == data_type_e_sint32 || property->_type == data_type_e_float32 ) { for ( sint32_c i = 0; i < property->_type_count; i++ ) { if ( a.uint32[ i ] != b.uint32[ i ] ) { return false; } } } else if ( property->_type == data_type_e_uint64 || property->_type == data_type_e_sint64 || property->_type == data_type_e_float64 ) { for ( sint32_c i = 0; i < property->_type_count; i++ ) { if ( a.uint64[ i ] != b.uint64[ i ] ) { return false; } } } else if ( property->_type == data_type_e_string8 ) { assert( property->_type_count == 1 ); if ( a.string8 != b.string8 ) { return false; } } else if ( property->_type == data_type_e_string16 ) { assert( property->_type_count == 1 ); if ( a.string16 != b.string16 ) { return false; } } else { assert( false ); } return true; } }
37.87415
222
0.677818
Olaedaria
67d3371e362cceaf991e66b40c0eb657f575c035
12,020
cxx
C++
Modules/Registration/Common/test/itkMultiResolutionImageRegistrationMethodTest_2.cxx
rmukh/ITK
0fcfaf1288928a76c3ef2b3fcc8b6e53246bfbba
[ "Apache-2.0" ]
null
null
null
Modules/Registration/Common/test/itkMultiResolutionImageRegistrationMethodTest_2.cxx
rmukh/ITK
0fcfaf1288928a76c3ef2b3fcc8b6e53246bfbba
[ "Apache-2.0" ]
null
null
null
Modules/Registration/Common/test/itkMultiResolutionImageRegistrationMethodTest_2.cxx
rmukh/ITK
0fcfaf1288928a76c3ef2b3fcc8b6e53246bfbba
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright NumFOCUS * * 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 * * https://www.apache.org/licenses/LICENSE-2.0.txt * * 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 "itkQuaternionRigidTransform.h" #include "itkMutualInformationImageToImageMetric.h" #include "itkQuaternionRigidTransformGradientDescentOptimizer.h" #include "itkTextOutput.h" #include "itkSimpleMultiResolutionImageRegistrationUI.h" namespace { double F(itk::Vector<double, 3> & v); } /** * This program test one instantiation of the * itk::MultiResolutionImageRegistrationMethod class * * This file tests the combination of: * - MutualInformation * - QuaternionRigidTransform * - QuaternionRigidTransformGradientDescentOptimizer * - LinearInterpolateImageFunction * - RecursiveMultiResolutionPyramidImageFilter * * The test image pattern consists of a 3D gaussian in the middle * with some directional pattern on the outside. * One image is rotated and shifted relative to the other. * * Notes: * ===== * This example performs an rigid * registration between a 3D moving image and a 3D fixed image using * mutual information and a multi-resolution strategy. * * See notes for itkImageRegistrationMethodTest_14.cxx for more * detailed information on the algorithm. * * A simple user-interface, allows the user to define the number * of iteration and learning rate at each resolution level. * */ int itkMultiResolutionImageRegistrationMethodTest_2(int, char *[]) { itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer()); bool pass = true; constexpr unsigned int dimension = 3; unsigned int j; using PixelType = float; // Fixed Image Type using FixedImageType = itk::Image<PixelType, dimension>; // Moving Image Type using MovingImageType = itk::Image<PixelType, dimension>; // Transform Type using TransformType = itk::QuaternionRigidTransform<double>; // Optimizer Type using OptimizerType = itk::QuaternionRigidTransformGradientDescentOptimizer; // Metric Type using MetricType = itk::MutualInformationImageToImageMetric<FixedImageType, MovingImageType>; // Interpolation technique using InterpolatorType = itk::LinearInterpolateImageFunction<MovingImageType, double>; // Fixed Image Pyramid Type using FixedImagePyramidType = itk::RecursiveMultiResolutionPyramidImageFilter<FixedImageType, FixedImageType>; // Moving Image Pyramid Type using MovingImagePyramidType = itk::RecursiveMultiResolutionPyramidImageFilter<MovingImageType, MovingImageType>; // Registration Method using RegistrationType = itk::MultiResolutionImageRegistrationMethod<FixedImageType, MovingImageType>; auto metric = MetricType::New(); auto transform = TransformType::New(); auto optimizer = OptimizerType::New(); auto fixedImage = FixedImageType::New(); auto movingImage = MovingImageType::New(); auto interpolator = InterpolatorType::New(); auto fixedImagePyramid = FixedImagePyramidType::New(); auto movingImagePyramid = MovingImagePyramidType::New(); auto registration = RegistrationType::New(); /********************************************************* * Set up the two input images. * One image rotated (xy plane) and shifted with respect to the other. **********************************************************/ double displacement[dimension] = { 7, 3, 2 }; double angle = 10.0 / 180.0 * itk::Math::pi; FixedImageType::SizeType size = { { 100, 100, 40 } }; FixedImageType::IndexType index = { { 0, 0, 0 } }; FixedImageType::RegionType region; region.SetSize(size); region.SetIndex(index); fixedImage->SetLargestPossibleRegion(region); fixedImage->SetBufferedRegion(region); fixedImage->SetRequestedRegion(region); fixedImage->Allocate(); movingImage->SetLargestPossibleRegion(region); movingImage->SetBufferedRegion(region); movingImage->SetRequestedRegion(region); movingImage->Allocate(); using MovingImageIterator = itk::ImageRegionIterator<MovingImageType>; using FixedImageIterator = itk::ImageRegionIterator<FixedImageType>; itk::Point<double, dimension> center; for (j = 0; j < dimension; ++j) { center[j] = 0.5 * static_cast<double>(region.GetSize()[j]); } itk::Point<double, dimension> p; itk::Vector<double, dimension> d, d2; MovingImageIterator mIter(movingImage, region); FixedImageIterator fIter(fixedImage, region); while (!mIter.IsAtEnd()) { for (j = 0; j < dimension; ++j) { p[j] = mIter.GetIndex()[j]; } d = p - center; fIter.Set((PixelType)F(d)); d2[0] = d[0] * std::cos(angle) + d[1] * std::sin(angle) + displacement[0]; d2[1] = -d[0] * std::sin(angle) + d[1] * std::cos(angle) + displacement[1]; d2[2] = d[2] + displacement[2]; mIter.Set((PixelType)F(d2)); ++fIter; ++mIter; } // set the image origin to be center of the image double transCenter[dimension]; for (j = 0; j < dimension; ++j) { transCenter[j] = -0.5 * static_cast<double>(size[j]); } movingImage->SetOrigin(transCenter); fixedImage->SetOrigin(transCenter); /****************************************************************** * Set up the optimizer. ******************************************************************/ // set the translation scale using ScalesType = OptimizerType::ScalesType; ScalesType parametersScales(transform->GetNumberOfParameters()); parametersScales.Fill(1.0); for (j = 4; j < 7; ++j) { parametersScales[j] = 0.0001; } optimizer->SetScales(parametersScales); // need to maximize for mutual information optimizer->MaximizeOn(); /****************************************************************** * Set up the optimizer observer ******************************************************************/ /* using CommandIterationType = itk::CommandIterationUpdate< OptimizerType >; CommandIterationType::Pointer iterationCommand = CommandIterationType::New(); iterationCommand->SetOptimizer( optimizer ); */ /****************************************************************** * Set up the metric. ******************************************************************/ metric->SetMovingImageStandardDeviation(5.0); metric->SetFixedImageStandardDeviation(5.0); metric->SetNumberOfSpatialSamples(50); metric->ReinitializeSeed(121212); /****************************************************************** * Set up the registrator. ******************************************************************/ // connect up the components registration->SetMetric(metric); registration->SetOptimizer(optimizer); registration->SetTransform(transform); registration->SetFixedImage(fixedImage); registration->SetMovingImage(movingImage); registration->SetInterpolator(interpolator); registration->SetFixedImagePyramid(fixedImagePyramid); registration->SetMovingImagePyramid(movingImagePyramid); registration->SetFixedImageRegion(fixedImage->GetBufferedRegion()); // set initial parameters to identity RegistrationType::ParametersType initialParameters(transform->GetNumberOfParameters()); initialParameters.Fill(0.0); initialParameters[3] = 1.0; /****************************************************************** * Attach registration to a simple UI and run registration ******************************************************************/ SimpleMultiResolutionImageRegistrationUI2<RegistrationType> simpleUI(registration); unsigned short numberOfLevels = 3; itk::Array<unsigned int> niter(numberOfLevels); itk::Array<double> rates(numberOfLevels); niter[0] = 300; niter[1] = 300; niter[2] = 350; rates[0] = 1e-3; rates[1] = 5e-4; rates[2] = 1e-4; simpleUI.SetNumberOfIterations(niter); simpleUI.SetLearningRates(rates); try { registration->SetNumberOfLevels(numberOfLevels); registration->SetInitialTransformParameters(initialParameters); registration->Update(); } catch (const itk::ExceptionObject & e) { std::cout << "Registration failed" << std::endl; std::cout << "Reason " << e.GetDescription() << std::endl; return EXIT_FAILURE; } /*********************************************************** * Check the results ************************************************************/ RegistrationType::ParametersType solution = registration->GetLastTransformParameters(); std::cout << "Solution is: " << solution << std::endl; RegistrationType::ParametersType trueParameters(transform->GetNumberOfParameters()); trueParameters.Fill(0.0); trueParameters[2] = std::sin(angle / 2.0); trueParameters[3] = std::cos(angle / 2.0); trueParameters[4] = -1.0 * (displacement[0] * std::cos(angle) - displacement[1] * std::sin(angle)); trueParameters[5] = -1.0 * (displacement[0] * std::sin(angle) + displacement[1] * std::cos(angle)); trueParameters[6] = -1.0 * displacement[2]; std::cout << "True solution is: " << trueParameters << std::endl; for (j = 0; j < 4; ++j) { if (itk::Math::abs(solution[j] - trueParameters[j]) > 0.025) { pass = false; } } for (j = 4; j < 7; ++j) { if (itk::Math::abs(solution[j] - trueParameters[j]) > 1.0) { pass = false; } } if (!pass) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } /************************************************* * Check for parzen window exception **************************************************/ double oldValue = metric->GetMovingImageStandardDeviation(); metric->SetMovingImageStandardDeviation(0.005); try { pass = false; registration->Update(); } catch (const itk::ExceptionObject & err) { std::cout << "Caught expected ExceptionObject" << std::endl; std::cout << err << std::endl; pass = true; } if (!pass) { std::cout << "Should have caught an exception" << std::endl; std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } metric->SetMovingImageStandardDeviation(oldValue); /************************************************* * Check for mapped out of image error **************************************************/ solution[5] = 1000; registration->SetInitialTransformParameters(solution); try { pass = false; registration->Update(); } catch (const itk::ExceptionObject & err) { std::cout << "Caught expected ExceptionObject" << std::endl; std::cout << err << std::endl; pass = true; } if (!pass) { std::cout << "Should have caught an exception" << std::endl; std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; } namespace { /** * This function defines the test image pattern. * The pattern is a 3D gaussian in the middle * and some directional pattern on the outside. */ double F(itk::Vector<double, 3> & v) { double x = v[0]; double y = v[1]; double z = v[2]; constexpr double s = 50; double value = 200.0 * std::exp(-(x * x + y * y + z * z) / (s * s)); x -= 8; y += 3; z += 0; double r = std::sqrt(x * x + y * y + z * z); if (r > 35) { value = 2 * (itk::Math::abs(x) + 0.8 * itk::Math::abs(y) + 0.5 * itk::Math::abs(z)); } if (r < 4) { value = 400; } return value; } } // namespace
29.104116
115
0.613228
rmukh
67d3606c09323fc3d79d2122b15bbac6aafd012a
61
hh
C++
extern/polymesh/src/polymesh/impl/impl_iterators.hh
huzjkevin/portal_maze_zgl
efb32b1c3430f20638c1401095999ecb4d0af5aa
[ "MIT" ]
null
null
null
extern/polymesh/src/polymesh/impl/impl_iterators.hh
huzjkevin/portal_maze_zgl
efb32b1c3430f20638c1401095999ecb4d0af5aa
[ "MIT" ]
null
null
null
extern/polymesh/src/polymesh/impl/impl_iterators.hh
huzjkevin/portal_maze_zgl
efb32b1c3430f20638c1401095999ecb4d0af5aa
[ "MIT" ]
null
null
null
#pragma once #include "../Mesh.hh" namespace polymesh { }
6.777778
21
0.655738
huzjkevin
67d370745e7175c7ffb641e02eebf878d6ec6d96
378
cpp
C++
src/SSceneInitParameters.cpp
h2r0x/ZHM5Randomizer-1
8bf6a9676a88374cd82cd85fd3ada659cd08d63a
[ "MIT" ]
null
null
null
src/SSceneInitParameters.cpp
h2r0x/ZHM5Randomizer-1
8bf6a9676a88374cd82cd85fd3ada659cd08d63a
[ "MIT" ]
null
null
null
src/SSceneInitParameters.cpp
h2r0x/ZHM5Randomizer-1
8bf6a9676a88374cd82cd85fd3ada659cd08d63a
[ "MIT" ]
null
null
null
#include "SSceneInitParameters.h" void SSceneInitParameters::print() const { printf("\nSSceneInitParameter hash: 0x%I64X\n", std::hash<SSceneInitParameters>()(*this)); printf("\t%s\n", m_SceneResource.to_string().c_str()); for (int i = 0; i < m_aAdditionalBrickResources.size(); ++i) printf("\t\t%s\n", m_aAdditionalBrickResources[i].to_string().c_str()); }
37.8
75
0.690476
h2r0x
67d4cfab0dd43e4dd96bd4dbb941498408d1be45
460
cpp
C++
all_domains/data_structures/trees/tree_top_view.cpp
ejspeiro/HackerRank
2e489588e8d7102acb676cc49fe07ee83e4f66e9
[ "MIT" ]
null
null
null
all_domains/data_structures/trees/tree_top_view.cpp
ejspeiro/HackerRank
2e489588e8d7102acb676cc49fe07ee83e4f66e9
[ "MIT" ]
null
null
null
all_domains/data_structures/trees/tree_top_view.cpp
ejspeiro/HackerRank
2e489588e8d7102acb676cc49fe07ee83e4f66e9
[ "MIT" ]
null
null
null
/* struct node { int data; node* left; node* right; }; */ void go_left(node * root) { if (root != nullptr) { go_left(root->left); std::cout << root->data << ' '; } } void go_right(node * root) { if (root != nullptr) { std::cout << root->data << ' '; go_right(root->right); } } void top_view(node * root) { go_left(root->left); std::cout << root->data << ' '; go_right(root->right); }
14.83871
39
0.495652
ejspeiro
67d57c8377c9a6c23b04d503f172c4e980281680
12,941
cpp
C++
AIPDebug/External-Interface/UdpClient.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
AIPDebug/External-Interface/UdpClient.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
AIPDebug/External-Interface/UdpClient.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
#include "UdpClient.h" UdpClient::UdpClient(QObject *parent) : QUdpSocket(parent) { Status = "free"; Number = "----"; Reply_conut = 0; } void UdpClient::Init() { this->bind(6000); // QHostAddress::Broadcast, connect(this, SIGNAL(readyRead()), this, SLOT(ReadAll())); } void UdpClient::Quit() { this->close(); } void UdpClient::InitSettings() { qDebug() << QTime::currentTime().toString() << "Read UDP"; QSettings *set_Test_File = new QSettings(Sys_path, QSettings::IniFormat); set_Test_File->setIniCodec("GB18030"); Number = set_Test_File->value("Factory/text", "V-0.0.0").toString(); QSettings File_Types(Test_File_path, QSettings::IniFormat); File_Types.setIniCodec("UTF-8"); QStringList Type_list = File_Types.value("DateFile/currentfile").toStringList(); Types = Type_list.join(" "); qDebug() << QTime::currentTime().toString() << "Read UDP OK"; } void UdpClient::SaveSettings() { // } void UdpClient::ReadAll() { while (this->hasPendingDatagrams()) { QByteArray msg; msg.resize(this->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; this->readDatagram(msg.data(), msg.size(), &sender, &senderPort); QStringList n = QString(msg).split(" "); quint16 Command; Command = quint16(n.at(0).toInt()); n.removeFirst(); QByteArray Param; Param = n.join(" ").toUtf8(); sender_Record = sender; if (Command != 6030) { qDebug() << "Command-------------------->" << Command; } switch (Command) { case 3000: //查询在线主机 ---成功--- InitSettings(); TxMsg = "3001 "; TxMsg.append(Number); this->writeDatagram(TxMsg.toUtf8(), sender, 6000); break; case 3002: //修改主机编号 break; case 3004: //获取测试型号 ---成功--- InitSettings(); TxMsg = "3005 "; TxMsg.append(Types); this->writeDatagram(TxMsg.toUtf8(), sender, 6000); break; case 3006: //设置测试型号 ---成功--- if (!Param.isEmpty()) emit SendCommand(6000, CMD_Param, Param); break; case 3008: //启动左工位测试 ---成功--- emit SendCommand(6000, CMD_START, QString("%1 %2").arg(0x13).arg(0x03).toUtf8()); TxMsg = "3009 "; TxMsg.append(Number); this->writeDatagram(TxMsg.toUtf8(), sender, senderPort); break; case 3010: //停止测试 ---成功--- emit SendCommand(6000, CMD_STOP, QString("%1 %2").arg(0x13).arg(0x03).toUtf8()); TxMsg = "3011 "; TxMsg.append(Number); this->writeDatagram(TxMsg.toUtf8(), sender, senderPort); break; case 3012: //获取状态 ---成功--- emit SendCommand(6000, CMD_STATUSING, QString("").toUtf8()); break; case 3014: // TxMsg = "3015 "; // TxMsg.append(Items.join("\n")); // this->writeDatagram(TxMsg.toUtf8(), sender, senderPort); break; case 1666: qDebug() << "PC Asking"; emit SendCommand(6000, CMD_ICO, QString("").toUtf8()); break; case 2000: Reply_conut = 0; break; case 6000: // 获取警告 SendCommand(6000, CMD_WMessage, QString("").toUtf8()); break; case 6002: // qDebug() << "msg---init" << msg; SendCommand(6000, CMD_Init_Data, msg); break; case 6004: // 解析接收数据 Analy_XML_Data(n); break; case 6006: // 解析启动数据 emit SendCommand(6000, CMD_Start_Item, msg); break; case 6008: // 跳转测试界面 emit SendCommand(6000, CMD_Judge, QString("").toUtf8()); break; case 6010: //-添加型号 emit SendCommand(6000, CMD_Add_Model, msg); break; case 6012: //-删除型号 emit SendCommand(6000, CMD_Del_Model, msg); break; case 6016: emit SendCommand(6000, CMD_Oder_Model, QString("").toUtf8()); break; case 6018: emit SendCommand(6000, CMD_Updae_Model, msg); break; case 6020: emit SendCommand(6000, CMD_All_Start, msg); break; case 6022: emit SendCommand(6000, CMD_All_Stop, msg); break; case 6026: emit SendCommand(6000, CMD_Time, msg); break; case 6030: this->writeDatagram("0x31", sender_Record, 6000); break; case 6036: emit SendCommand(6000, CMD_IO_Put, msg); break; case 6038: emit SendCommand(6000, CMD_MAG_Sample, msg); break; case 6041: emit SendCommand(6000, CMD_IMP_Sample, msg); break; case 6046: emit SendCommand(6000, CMD_IMP_Finsh, msg); break; case 6050: emit SendCommand(6000, CMD_IMP_Ready, msg); break; case 6052: emit SendCommand(6000, CMD_Vacuum_IMP, msg); break; case 6056: emit SendCommand(6000, CMD_IMP_PL, msg); break; case 6058: emit SendCommand(6000, CMD_PIC, msg); break; case 6066: emit SendCommand(6000, CMD_9a, msg); break; case 6067: emit SendCommand(6000, CMD_Start_Auto, msg); break; case 6068: // emit SendCommand(6000, CMD_Vacuum_ACW, msg); break; case 6070: emit SendCommand(6000, CMD_Start_No, msg); break; case 6071: emit SendCommand(6000, CMD_Beep, msg); break; case 6072: emit SendCommand(6000, CMD_A1, msg); break; case 6073: emit SendCommand(6000, CMD_A2, msg); break; case 6078: emit SendCommand(6000, CMD_A3, msg); break; case 6081: // 清除状态 emit SendCommand(6000, CMD_A4, msg); break; default: this->writeDatagram("Error command", sender_Record, 6000); break; } } } void UdpClient::Analy_XML_Data(QStringList data) { if (data.at(0) == QString(tr("Conf"))) { SendCommand(6000, CMD_CONF_Data, QString("1").toUtf8()); } else if (data.at(0) == QString(tr("Sys"))) { SendCommand(6000, CMD_CONF_Data, QString("2").toUtf8()); } else if (data.at(0) == QString(tr("DCR"))) { SendCommand(6000, CMD_CONF_Data, QString("3").toUtf8()); } else if (data.at(0) == QString(tr("MAG"))) { SendCommand(6000, CMD_CONF_Data, QString("15").toUtf8()); } else if (data.at(0) == QString(tr("IR"))) { SendCommand(6000, CMD_CONF_Data, QString("4").toUtf8()); } else if (data.at(0) == QString(tr("ACW"))) { SendCommand(6000, CMD_CONF_Data, QString("5").toUtf8()); } else if (data.at(0) == QString(tr("IMP"))) { SendCommand(6000, CMD_CONF_Data, QString("6").toUtf8()); } else if (data.at(0) == QString(tr("IND"))) { SendCommand(6000, CMD_CONF_Data, QString("7").toUtf8()); } else if (data.at(0) == QString(tr("HALL"))) { SendCommand(6000, CMD_CONF_Data, QString("11").toUtf8()); } else if (data.at(0) == QString(tr("LOAD"))) { SendCommand(6000, CMD_CONF_Data, QString("12").toUtf8()); } else if (data.at(0) == QString(tr("NOLOAD"))) { SendCommand(6000, CMD_CONF_Data, QString("13").toUtf8()); } else if (data.at(0) == QString(tr("BEMF"))) { SendCommand(6000, CMD_CONF_Data, QString("14").toUtf8()); } else { qDebug() << "Error data--Analy_XML_Data" << data; } } void UdpClient::ReadMessage(quint16 addr, quint16 cmd, QByteArray msg) { // qDebug()<<"cmd"<<cmd<<"msg"<<msg; if (addr != 6000) return; switch (cmd) { case CMD_ITEM: Items.append(msg); break; case CMD_STATUS: Status = msg; if (Status == "free") { this->writeDatagram(Items.join("\n").toUtf8(), sender_Record, 6000); // QHostAddress::Broadcast Items.clear(); } else { // } break; case CMD_STATUSING: Status = msg; TxMsg = "3013 "; TxMsg.append(Status); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_Param: TxMsg = "3007 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_Login: this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_Reply: Reply_conut++; TxMsg = "2000 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); qDebug() << "Rleply_conut" << Reply_conut; if (Reply_conut > 30) { // >30s qDebug() << "Realy Fail"; } break; case CMD_WMessage: TxMsg = "6001 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_CONF_Data: TxMsg = "6005 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_Start_Item: TxMsg = "6007 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_Oder_Model: TxMsg = "6017 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_ad: TxMsg = "6015 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_73: TxMsg = "6019 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_75: TxMsg = "6021 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_76: TxMsg = "6032 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_77: TxMsg = "6033 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_IO_IN: TxMsg = "6037 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_81: TxMsg = "6039 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_82: TxMsg = "6040 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_85: TxMsg = "6042 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_86: TxMsg = "6043 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_87: TxMsg = "6035 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_V_State: TxMsg = "6053 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_92: TxMsg = "6055 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_96: TxMsg = "6059 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_97: TxMsg = "6060 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_98: TxMsg = "6061 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_Close_Pumb: TxMsg = "6062 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_Curtain: TxMsg = "6063 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_Action: TxMsg = "6064 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_A4: TxMsg = "6082 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; case CMD_B0: TxMsg = "6083 "; TxMsg.append(msg); this->writeDatagram(TxMsg.toUtf8(), sender_Record, 6000); break; default: break; } }
33.097187
95
0.540221
Bluce-Song
67d8f625c8645701bc6a482086d5da32d07fb4f1
1,427
cpp
C++
libs/data/tests/src/temporary.cpp
blagodarin/seir
fec45228d161dabb8bb4aaa23c64ea218b84e8fd
[ "Apache-2.0" ]
null
null
null
libs/data/tests/src/temporary.cpp
blagodarin/seir
fec45228d161dabb8bb4aaa23c64ea218b84e8fd
[ "Apache-2.0" ]
null
null
null
libs/data/tests/src/temporary.cpp
blagodarin/seir
fec45228d161dabb8bb4aaa23c64ea218b84e8fd
[ "Apache-2.0" ]
null
null
null
// This file is part of Seir. // Copyright (C) Sergei Blagodarin. // SPDX-License-Identifier: Apache-2.0 #include <seir_data/blob.hpp> #include <seir_data/temporary.hpp> #include <array> #include <cstring> #include <filesystem> #include <doctest/doctest.h> TEST_CASE("TemporaryFile") { auto writer = seir::TemporaryWriter::create(); REQUIRE(writer); REQUIRE(writer->size() == 0); const auto data = std::to_array<uint8_t>({ 1, 2, 3, 4, 5, 6, 7 }); CHECK(writer->reserve(2 * data.size())); REQUIRE(writer->write(data.data(), data.size())); REQUIRE(writer->write(data.data(), data.size())); CHECK(writer->flush()); // Should successfully do nothing. Unfortunately we're unable to check that it actually does nothing. auto file = seir::TemporaryWriter::commit(std::move(writer)); REQUIRE(file); MESSAGE("TemporaryFile: ", file->path()); CHECK_FALSE(writer); const std::filesystem::path path{ file->path() }; CHECK(std::filesystem::exists(path)); { const auto blob = seir::Blob::from(*file); REQUIRE(blob); REQUIRE(blob->size() == 2 * data.size()); CHECK_FALSE(std::memcmp(blob->data(), data.data(), data.size())); CHECK_FALSE(std::memcmp(static_cast<const std::byte*>(blob->data()) + data.size(), data.data(), data.size())); } file.reset(); CHECK_FALSE(std::filesystem::exists(path)); } TEST_CASE("TemporaryFile::commit({})") { CHECK_FALSE(static_cast<bool>(seir::TemporaryWriter::commit({}))); }
31.711111
126
0.686055
blagodarin
67d95c2233dec64e8de34eb16d103affaf60f42e
4,834
cpp
C++
lib/Target/X86/X86MacroFusion.cpp
vangthao95/llvm
7161a90f679d8d52ab57a3166361a7ebd1ba5459
[ "Apache-2.0" ]
115
2018-02-01T18:56:44.000Z
2022-03-21T13:23:00.000Z
FRProtector/lib/Target/X86/X86MacroFusion.cpp
whucs303/randomizationlib
07a1f495e1cf878ad9dd4c79b7ff1c6b48cff876
[ "MIT" ]
27
2018-09-17T17:49:49.000Z
2021-11-03T04:31:51.000Z
FRProtector/lib/Target/X86/X86MacroFusion.cpp
whucs303/randomizationlib
07a1f495e1cf878ad9dd4c79b7ff1c6b48cff876
[ "MIT" ]
55
2018-02-01T07:11:49.000Z
2022-03-04T01:20:23.000Z
//===- X86MacroFusion.cpp - X86 Macro Fusion ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file This file contains the X86 implementation of the DAG scheduling /// mutation to pair instructions back to back. // //===----------------------------------------------------------------------===// #include "X86MacroFusion.h" #include "X86Subtarget.h" #include "llvm/CodeGen/MacroFusion.h" #include "llvm/CodeGen/TargetInstrInfo.h" using namespace llvm; /// \brief Check if the instr pair, FirstMI and SecondMI, should be fused /// together. Given SecondMI, when FirstMI is unspecified, then check if /// SecondMI may be part of a fused pair at all. static bool shouldScheduleAdjacent(const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI, const MachineInstr *FirstMI, const MachineInstr &SecondMI) { const X86Subtarget &ST = static_cast<const X86Subtarget&>(TSI); // Check if this processor supports macro-fusion. if (!ST.hasMacroFusion()) return false; enum { FuseTest, FuseCmp, FuseInc } FuseKind; unsigned FirstOpcode = FirstMI ? FirstMI->getOpcode() : static_cast<unsigned>(X86::INSTRUCTION_LIST_END); unsigned SecondOpcode = SecondMI.getOpcode(); switch (SecondOpcode) { default: return false; case X86::JE_1: case X86::JNE_1: case X86::JL_1: case X86::JLE_1: case X86::JG_1: case X86::JGE_1: FuseKind = FuseInc; break; case X86::JB_1: case X86::JBE_1: case X86::JA_1: case X86::JAE_1: FuseKind = FuseCmp; break; case X86::JS_1: case X86::JNS_1: case X86::JP_1: case X86::JNP_1: case X86::JO_1: case X86::JNO_1: FuseKind = FuseTest; break; } switch (FirstOpcode) { default: return false; case X86::TEST8rr: case X86::TEST16rr: case X86::TEST32rr: case X86::TEST64rr: case X86::TEST8ri: case X86::TEST16ri: case X86::TEST32ri: case X86::TEST32i32: case X86::TEST64i32: case X86::TEST64ri32: case X86::TEST8mr: case X86::TEST16mr: case X86::TEST32mr: case X86::TEST64mr: case X86::TEST8ri_NOREX: case X86::AND16i16: case X86::AND16ri: case X86::AND16ri8: case X86::AND16rm: case X86::AND16rr: case X86::AND32i32: case X86::AND32ri: case X86::AND32ri8: case X86::AND32rm: case X86::AND32rr: case X86::AND64i32: case X86::AND64ri32: case X86::AND64ri8: case X86::AND64rm: case X86::AND64rr: case X86::AND8i8: case X86::AND8ri: case X86::AND8rm: case X86::AND8rr: return true; case X86::CMP16i16: case X86::CMP16ri: case X86::CMP16ri8: case X86::CMP16rm: case X86::CMP16rr: case X86::CMP32i32: case X86::CMP32ri: case X86::CMP32ri8: case X86::CMP32rm: case X86::CMP32rr: case X86::CMP64i32: case X86::CMP64ri32: case X86::CMP64ri8: case X86::CMP64rm: case X86::CMP64rr: case X86::CMP8i8: case X86::CMP8ri: case X86::CMP8rm: case X86::CMP8rr: case X86::ADD16i16: case X86::ADD16ri: case X86::ADD16ri8: case X86::ADD16ri8_DB: case X86::ADD16ri_DB: case X86::ADD16rm: case X86::ADD16rr: case X86::ADD16rr_DB: case X86::ADD32i32: case X86::ADD32ri: case X86::ADD32ri8: case X86::ADD32ri8_DB: case X86::ADD32ri_DB: case X86::ADD32rm: case X86::ADD32rr: case X86::ADD32rr_DB: case X86::ADD64i32: case X86::ADD64ri32: case X86::ADD64ri32_DB: case X86::ADD64ri8: case X86::ADD64ri8_DB: case X86::ADD64rm: case X86::ADD64rr: case X86::ADD64rr_DB: case X86::ADD8i8: case X86::ADD8mi: case X86::ADD8mr: case X86::ADD8ri: case X86::ADD8rm: case X86::ADD8rr: case X86::SUB16i16: case X86::SUB16ri: case X86::SUB16ri8: case X86::SUB16rm: case X86::SUB16rr: case X86::SUB32i32: case X86::SUB32ri: case X86::SUB32ri8: case X86::SUB32rm: case X86::SUB32rr: case X86::SUB64i32: case X86::SUB64ri32: case X86::SUB64ri8: case X86::SUB64rm: case X86::SUB64rr: case X86::SUB8i8: case X86::SUB8ri: case X86::SUB8rm: case X86::SUB8rr: return FuseKind == FuseCmp || FuseKind == FuseInc; case X86::INC16r: case X86::INC32r: case X86::INC64r: case X86::INC8r: case X86::DEC16r: case X86::DEC32r: case X86::DEC64r: case X86::DEC8r: return FuseKind == FuseInc; case X86::INSTRUCTION_LIST_END: return true; } } namespace llvm { std::unique_ptr<ScheduleDAGMutation> createX86MacroFusionDAGMutation () { return createBranchMacroFusionDAGMutation(shouldScheduleAdjacent); } } // end namespace llvm
24.049751
80
0.638602
vangthao95
67df737a8baa7b41644c5b87090a2893614f0dbd
965
cpp
C++
src/tools.cpp
tairaO/CarND-Unscented-Kalman-Filter-Project
cd7b489060ec9c55d72e25b49b5e0fd920d8fddb
[ "MIT" ]
null
null
null
src/tools.cpp
tairaO/CarND-Unscented-Kalman-Filter-Project
cd7b489060ec9c55d72e25b49b5e0fd920d8fddb
[ "MIT" ]
null
null
null
src/tools.cpp
tairaO/CarND-Unscented-Kalman-Filter-Project
cd7b489060ec9c55d72e25b49b5e0fd920d8fddb
[ "MIT" ]
null
null
null
#include <iostream> #include "tools.h" using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; Tools::Tools() {} Tools::~Tools() {} VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { /** TODO: * Calculate the RMSE here. */ VectorXd rmse_(4); rmse_ << 0, 0, 0, 0; unsigned int est_num_ = estimations.size(); if(est_num_ != ground_truth.size() || est_num_==0) { cout << "Invalid estimation or ground_truth data" << endl; return rmse_; } // accumulate residuals for(unsigned int i=0; i < est_num_; ++i) { // calculate squared error VectorXd residual_ = estimations[i] - ground_truth[i]; residual_ = residual_.array()*residual_.array(); rmse_ += residual_; } // calculate the mean rmse_ = rmse_/est_num_; // calculate the root rmse_ = rmse_.array().sqrt(); return rmse_; }
22.97619
69
0.615544
tairaO
67e04929fceb21cb6fc41cdd69e9c9700fd6add4
2,579
cc
C++
cc/json-export.cc
acorg/acmacs-tal
13da33bb8ed456ac1f968b8b86df295467ee5429
[ "MIT" ]
null
null
null
cc/json-export.cc
acorg/acmacs-tal
13da33bb8ed456ac1f968b8b86df295467ee5429
[ "MIT" ]
null
null
null
cc/json-export.cc
acorg/acmacs-tal
13da33bb8ed456ac1f968b8b86df295467ee5429
[ "MIT" ]
null
null
null
#include "acmacs-base/to-json.hh" #include "acmacs-base/date.hh" #include "acmacs-base/timeit.hh" #include "acmacs-tal/json-export.hh" #include "acmacs-tal/tree.hh" static to_json::object export_node(const acmacs::tal::v3::Node& node); // ---------------------------------------------------------------------- std::string acmacs::tal::v3::json_export(const Tree& tree, size_t indent) { // Timeit ti{"exporting tree to json"}; tree.cumulative_calculate(); auto json = to_json::object(to_json::key_val("_", fmt::format("-*- js-indent-level: {} -*-", indent)), to_json::key_val(" version", "phylogenetic-tree-v3"), to_json::key_val(" date", date::current_date_time())); json << to_json::key_val_if_not_empty("v", tree.virus_type()) << to_json::key_val_if_not_empty("l", tree.lineage()) << to_json::key_val("tree", export_node(tree)); return fmt::format(fmt::runtime(fmt::format("{{:{}}}", indent)), json); } // acmacs::tal::v3::json_export // ---------------------------------------------------------------------- to_json::object export_node(const acmacs::tal::v3::Node& node) { to_json::object result; if (node.is_leaf()) { result << to_json::key_val("n", *node.seq_id) << to_json::key_val_if_true("H", node.hidden) << to_json::key_val_if_not_empty("a", *node.aa_sequence) << to_json::key_val_if_not_empty("N", *node.nuc_sequence) << to_json::key_val_if_not_empty("d", node.date) << to_json::key_val_if_not_empty("C", node.continent) << to_json::key_val_if_not_empty("D", node.country); if (!node.hi_names.empty()) result << to_json::key_val("h", to_json::array(std::begin(node.hi_names), std::end(node.hi_names))); } if (!node.edge_length.is_zero()) result << to_json::key_val("l", to_json::raw(node.edge_length.as_string())); if (node.cumulative_edge_length >= acmacs::tal::v3::EdgeLength{0.0}) result << to_json::key_val("c", to_json::raw(node.cumulative_edge_length.as_string())); if (!node.subtree.empty()) { to_json::array subtree; for (const auto& sub_node : node.subtree) subtree << export_node(sub_node); result << to_json::key_val("t", std::move(subtree)); } return result; } // export_node // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
43.711864
112
0.563397
acorg
67ef50d239c6505631ee5bfd2ab7d70063c69ae7
1,327
cpp
C++
source/ktwgEngine/raycastcallbacks.cpp
JasonWyx/ktwgEngine
410ba799f7000895995b9f9fc59d738f293f8871
[ "MIT" ]
null
null
null
source/ktwgEngine/raycastcallbacks.cpp
JasonWyx/ktwgEngine
410ba799f7000895995b9f9fc59d738f293f8871
[ "MIT" ]
12
2019-09-15T07:48:18.000Z
2019-12-08T17:23:22.000Z
source/ktwgEngine/raycastcallbacks.cpp
JasonWyx/ktwgEngine
410ba799f7000895995b9f9fc59d738f293f8871
[ "MIT" ]
null
null
null
#include "raycastcallbacks.h" #include "boxcollider.h" #include "rigidbody.h" #include "broadphase.h" bool CastCallback::QueryTriggers(int32_t id) { void* data = broadPhase_->GetUserData(id); BoxCollider* collider = static_cast<BoxCollider*>(data); return collider->GetIsTrigger(); } float RayCastCallback::Query(RayCastInput input, int32_t id) { // Retrieve the collider bounded by the bounding volume void* data = broadPhase_->GetUserData(id); BoxCollider* collider = static_cast<BoxCollider*>(data); // Don't check inactive collider if (!collider->GetActive()) return input.m_MaxT; auto layerId = collider->GetRigidBody()->GetLayerId(); auto layerBit = 1 << layerId; // Early out for the ray cast check for this collider if their layer is not included in layermask if (!(layerBit & input.m_LayerMask)) return input.m_MaxT; // Perform raycast on the collider to test for intersection RayCastOutput out; auto hit = collider->RayCast(input, out); // If there's a hit, check if its the earliest based on time if (hit) { // Update the earlier intersection if (out.m_T < output_->m_T) *output_ = out; // Use this to clip our ray return output_->m_T; } // Return the maxt to continue our search for a better one if there are return input.m_MaxT; }
26.54
99
0.708365
JasonWyx
67efbb1a22aa931e8d772f21270f628b20b67f77
1,362
hpp
C++
include/shapes/bvh.hpp
voyagingmk/renderer
c2dfddb611b99691e67701a726c404baa1759abb
[ "MIT" ]
2
2018-03-18T09:14:58.000Z
2020-04-11T14:50:37.000Z
include/shapes/bvh.hpp
voyagingmk/renderer
c2dfddb611b99691e67701a726c404baa1759abb
[ "MIT" ]
null
null
null
include/shapes/bvh.hpp
voyagingmk/renderer
c2dfddb611b99691e67701a726c404baa1759abb
[ "MIT" ]
null
null
null
#ifndef RENDERER_BVH_HPP #define RENDERER_BVH_HPP #include "union.hpp" namespace renderer { class BVHNode { public: BVHNode(): left(nullptr), right(nullptr) {} void InitAsLeaf(Shape* s, const BBox &b) { shapes.push_back(s); bound = b; left = right = nullptr; } void InitAsLeaf(Shapes s, const BBox &b) { shapes.insert(shapes.end(), s.begin(), s.end()); bound = b; left = right = nullptr; } void InitAsInterior(Axis axis, BVHNode* l, BVHNode* r) { left = l; right = r; bound = Union(l->bound, r->bound); splitAxis = axis; } Shapes shapes; BBox bound; BVHNode* left; BVHNode* right; Axis splitAxis; }; class BVHShapeInfo { public: BVHShapeInfo(): idx(0) {} BVHShapeInfo(size_t i, const BBox& wb) : idx(i), bound(wb), centroid(.5f * bound.pMin + .5f * bound.pMax) {} size_t idx; BBox bound; Point3dF centroid; }; typedef std::vector<BVHShapeInfo> BVHShapeInfos; class BVHTree: public ShapeUnion { public: BVHTree(Shapes shapes): ShapeUnion(shapes) {} virtual void Init() override; virtual int Intersect(Ray&, IntersectResult*) override; private: BVHNode* recursiveBuild(BVHShapeInfos& shapeInfos, int start, int end); private: BVHNode* root; }; } #endif // RENDERER_BVH_HPP
19.457143
74
0.62188
voyagingmk
67f3144de87b4767e26a5709ec609d5f07794f60
427
cpp
C++
dvxplorer_ros_driver/src/driver_node.cpp
jixing96/rpg_dvs_ros
5acb00fb939b5c0e451629c13773cd938b2b1258
[ "MIT" ]
228
2015-03-02T10:08:35.000Z
2022-03-18T06:28:03.000Z
dvxplorer_ros_driver/src/driver_node.cpp
jixing96/rpg_dvs_ros
5acb00fb939b5c0e451629c13773cd938b2b1258
[ "MIT" ]
98
2015-12-03T10:59:03.000Z
2022-02-23T15:45:25.000Z
dvxplorer_ros_driver/src/driver_node.cpp
jixing96/rpg_dvs_ros
5acb00fb939b5c0e451629c13773cd938b2b1258
[ "MIT" ]
117
2015-03-02T07:11:09.000Z
2022-03-20T02:57:34.000Z
// This file is part of DVS-ROS - the RPG DVS ROS Package #include "dvxplorer_ros_driver/driver.h" #include <ros/ros.h> int main(int argc, char *argv[]) { ros::init(argc, argv, "dvxplorer_ros_driver"); ros::NodeHandle nh; ros::NodeHandle nh_private("~"); dvxplorer_ros_driver::DvxplorerRosDriver *driver = new dvxplorer_ros_driver::DvxplorerRosDriver(nh, nh_private); ros::spin(); driver->dataStop(); return 0; }
21.35
113
0.723653
jixing96
67f9e80f189200fd6d30edea1be57055978a3e8d
476
cc
C++
src/utils.cc
informave/dbwtl
fed8f84ac42949d906a34b6a5a1b61b3a7b74356
[ "BSD-3-Clause" ]
1
2018-04-20T08:44:05.000Z
2018-04-20T08:44:05.000Z
src/utils.cc
informave/dbwtl
fed8f84ac42949d906a34b6a5a1b61b3a7b74356
[ "BSD-3-Clause" ]
null
null
null
src/utils.cc
informave/dbwtl
fed8f84ac42949d906a34b6a5a1b61b3a7b74356
[ "BSD-3-Clause" ]
null
null
null
#include <sstream> #include <string> #include <stdexcept> #include "dbwtl/exceptions.hh" #include "utils.hh" DB_NAMESPACE_BEGIN namespace utils { void raise_bugcheck_exception(const char *cond, const char *what, int line, const char *file, const char *function) { std::stringstream ss; ss << ">>>INTERNAL BUGCHECK<<< Condition failed: " << cond << " at " << file << ":" << line << " {" << function << "}"; throw Exception(ss.str()); } } DB_NAMESPACE_END
14.875
120
0.653361
informave
67fe969ff0fbdf2ab7b63f3ecc116b0e19aecc94
3,446
cpp
C++
src/scrambling/DigitalXOR_2di.cpp
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
44
2018-01-09T19:56:29.000Z
2022-03-03T06:38:54.000Z
src/scrambling/DigitalXOR_2di.cpp
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
16
2018-01-29T18:01:42.000Z
2022-03-31T07:01:09.000Z
src/scrambling/DigitalXOR_2di.cpp
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
12
2018-03-14T00:24:14.000Z
2022-03-03T06:40:07.000Z
/* * Hélène Perrier helene.perrier@liris.cnrs.fr * and David Coeurjolly david.coeurjolly@liris.cnrs.fr * * Copyright (c) 2018 CNRS Université de Lyon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the UTK project. */ #include "ScramblingDigitalXOR.hpp" #include "../parameters/ParamParser_getopt.hpp" #include "../io/fileIO.hpp" #include <chrono> #include <algorithm> #include "runScrambler.hpp" using namespace utk; typedef int T; #define D 2 typedef Point<D, T> P; typedef ScramblingDigitalXOR S; int main(int argc, char** argv) { ParamParser_getopt parser; S scrambler; //PARSE PARAM initParserScrambler(&parser); //PARSING parser.parse(argc, argv); if(!dealParamParserScrambler(&parser)) return 0; PointsetWriter<D, T, P> writer; writer.open(param_output.c_str()); PointsetReader<D, T, P> reader; reader.open(param_input.c_str()); Pointset<D, T, P> pts; Pointset<D, T, P> pts_scrambled; while(reader.readPointset(pts)) { int xmin=11212346, ymin=121212, xmax=0,ymax=0; for(auto i = 0; i < pts.size(); ++i) { xmin = std::min(xmin, pts[i].pos()[0]); ymin = std::min(xmin, pts[i].pos()[1]); xmax = std::max(xmax, pts[i].pos()[0]); ymax = std::max(ymax, pts[i].pos()[1]); } pts.domain.pMin = {xmin, ymin}; pts.domain.pMax = {xmax, ymax}; //SAMPLE std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); if(!scrambler.scramble<D, T, P>(pts, pts_scrambled)) return 1; std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1); if(param_verbose) std::cout << std::fixed << std::setprecision(5) << "Scrambled " << pts.size() << " samples in " << time_span.count() << " secs" << std::endl; //WRITE writer.writePointset(pts_scrambled); } writer.close(); return 0; }
35.525773
144
0.716193
FrancoisGaits
db02dc23e57775f45898e4a86964ffd9747fb887
269
cpp
C++
L1-026/main.cpp
Heliovic/GPLT
7e8745e589a6b6594d4db24a2030f3b0e6efe38b
[ "MIT" ]
1
2019-03-14T05:35:16.000Z
2019-03-14T05:35:16.000Z
L1-026/main.cpp
Heliovic/GPLT
7e8745e589a6b6594d4db24a2030f3b0e6efe38b
[ "MIT" ]
null
null
null
L1-026/main.cpp
Heliovic/GPLT
7e8745e589a6b6594d4db24a2030f3b0e6efe38b
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> using namespace std; char str[] = "I Love GPLT"; int main() { int len = strlen(str); for (int i = 0; i < len; i++) { if (i != 0) printf("\n"); printf("%c", str[i]); } return 0; }
12.809524
33
0.460967
Heliovic
db040e0b009e52a6cfc9c9020074dd8e3a95526a
1,423
hh
C++
src/Utilities/integrateThroughMeshAlongSegment.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Utilities/integrateThroughMeshAlongSegment.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Utilities/integrateThroughMeshAlongSegment.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // integrateThroughMeshAlongSegment // // Return the result of integrating a quantity along a line segment. // The quantity here is assumed to be represented a values in a vector<Value>, // where the vector<Value> is the value of the quantity in a series of cartesian // cells whose box is defined by by xmin, xmax, and ncells. // // We actually pass in a vector<vector<Value> >, which is a progressively refined // (by factors of 2 in each dimesion) representation of the data. The idea is that // we use the finest level with a non-zero value for the value. // // Created by JMO, Wed Feb 3 16:03:46 PST 2010 //----------------------------------------------------------------------------// #ifndef __Spheral_integrateThroughMeshAlongSegment__ #define __Spheral_integrateThroughMeshAlongSegment__ #include <vector> namespace Spheral { template<typename Dimension, typename Value> Value integrateThroughMeshAlongSegment(const std::vector<std::vector<Value> >& values, const typename Dimension::Vector& xmin, const typename Dimension::Vector& xmax, const std::vector<unsigned>& ncells, const typename Dimension::Vector& s0, const typename Dimension::Vector& s1); } #endif
41.852941
83
0.601546
jmikeowen
db045b1287ade8aafdb7e4cbf38e23bb25fa6506
16,805
tpp
C++
src/hypro/datastructures/Halfspace.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
22
2016-10-05T12:19:01.000Z
2022-01-23T09:14:41.000Z
src/hypro/datastructures/Halfspace.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
23
2017-05-08T15:02:39.000Z
2021-11-03T16:43:39.000Z
src/hypro/datastructures/Halfspace.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
12
2017-06-07T23:51:09.000Z
2022-01-04T13:06:21.000Z
/** * Class that holds the implementation of a Halfspace. * @file Halfspace.tpp * * @author Stefan Schupp <stefan.schupp@cs.rwth-aachen.de> * * @since 2015-03-16 * @version 2015-03-16 */ #include "Halfspace.h" namespace hypro { template <typename Number> Halfspace<Number>::Halfspace( const Point<Number>& _vector, const Number& _off ) : mNormal( _vector.rawCoordinates() ) , mScalar( _off ) {} template <typename Number> Halfspace<Number>::Halfspace( std::initializer_list<Number> _coordinates, const Number& _off ) { mNormal = vector_t<Number>( _coordinates.size() ); unsigned pos = 0; for ( auto& coordinate : _coordinates ) { mNormal( pos ) = coordinate; ++pos; } mScalar = _off; } template <typename Number> template <typename Normal, typename Offset, enable_if<convertible<Normal, vector_t<Number>> && convertible<Offset, Number>>> Halfspace<Number>::Halfspace( Normal&& normal, Offset&& offset ) : mNormal( std::forward<Normal>( normal ) ) , mScalar( std::forward<Offset>( offset ) ) {} template <typename Number> Halfspace<Number>::Halfspace( const vector_t<Number>& _vec, const std::vector<vector_t<Number>>& _vectorSet ) { // here: Halfspace given in parameterform is converted to normalform // the normal vector of the Halfspace is computed by solving a system of // equations mNormal = computePlaneNormal( _vectorSet ); // the scalar is just the scalar product of the normal vector & a point in the // Halfspace mScalar = mNormal.dot( _vec ); } template <typename Number> Halfspace<Number>::Halfspace( const std::vector<Point<Number>>& points ) { assert( !points.empty() ); std::vector<vector_t<Number>> rawCoordinates; std::transform( points.begin(), points.end(), std::back_inserter( rawCoordinates ), []( const Point<Number>& refpoint ) { return refpoint.rawCoordinates(); } ); mNormal = Halfspace<Number>::computePlaneNormal( rawCoordinates ); mScalar = Halfspace<Number>::computePlaneOffset( mNormal, points[0] ); TRACE( "hypro.datastructures", "Constructed hsp from " << mNormal << " and " << mScalar ); } template <typename Number> Halfspace<Number>::Halfspace( const std::vector<vector_t<Number>>& points ) { assert( !points.empty() ); mNormal = Halfspace<Number>::computePlaneNormal( points ); mScalar = Halfspace<Number>::computePlaneOffset( mNormal, Point( points[0] ) ); } template <typename Number> unsigned Halfspace<Number>::dimension() const { return unsigned( mNormal.nonZeros() ); } template <typename Number> const vector_t<Number>& Halfspace<Number>::normal() const& { return mNormal; } template <typename Number> vector_t<Number>&& Halfspace<Number>::normal() && { return std::move( mNormal ); } template <typename Number> void Halfspace<Number>::setNormal( const vector_t<Number>& _normal ) { mNormal = _normal; } template <typename Number> Halfspace<Number>& Halfspace<Number>::invert() { mNormal = -mNormal; mScalar = -mScalar; return *this; } template <typename Number> Number Halfspace<Number>::offset() const& { return mScalar; } template <typename Number> Number&& Halfspace<Number>::offset() && { return std::move( mScalar ); } template <typename Number> void Halfspace<Number>::setOffset( Number _offset ) { mScalar = _offset; } template <typename Number> Number Halfspace<Number>::signedDistance( const vector_t<Number>& _point ) const { return ( _point.dot( mNormal ) - mScalar ); } template <typename Number> Number Halfspace<Number>::evaluate( const vector_t<Number>& _direction ) const { return ( _direction.dot( mNormal ) ); } template <typename Number> Point<Number> Halfspace<Number>::projectPointOnPlane( const Point<Number> point ) const { return Point<Number>( point.rawCoordinates() + ( ( mScalar - point.rawCoordinates().dot( mNormal ) ) / mNormal.dot( mNormal ) ) * mNormal ); } template <typename Number> bool Halfspace<Number>::intersection( Number& _result, const vector_t<Number>& _vector ) const { bool intersect = false; Number factor = 0; Number dotProduct = ( mNormal.dot( _vector ) ); if ( dotProduct != 0 ) { intersect = true; factor = mScalar / dotProduct; } _result = factor; // note: to get the intersection point -> _vector *= factor; return intersect; } template <typename Number> bool Halfspace<Number>::intersection( Number& _result, const Point<Number>& _vector ) const { return intersection( _result, _vector.rawCoordinates() ); } template <typename Number> Halfspace<Number> Halfspace<Number>::projectOn( const std::vector<unsigned>& dimensions ) const { if ( dimensions.empty() ) { return Halfspace<Number>(); } vector_t<Number> projectedNormal = hypro::projectOn( mNormal, dimensions ); return Halfspace<Number>( projectedNormal, mScalar ); } template <typename Number> Halfspace<Number> Halfspace<Number>::linearTransformation( const matrix_t<Number>& A ) const { Eigen::FullPivLU<matrix_t<Number>> lu( A ); // if A has full rank, we can simply retransform if ( lu.rank() == A.rows() ) { // Todo: Verify this. return Halfspace<Number>( mNormal.transpose() * A.inverse(), mScalar ); } else { // we cannot invert A - chose points on the plane surface and create new plane assert( false ); // TODO return Halfspace<Number>(); } } template <typename Number> Halfspace<Number> Halfspace<Number>::affineTransformation( const matrix_t<Number>& A, const vector_t<Number>& b ) const { Eigen::FullPivLU<matrix_t<Number>> lu( A ); // if A has full rank, we can simply retransform if ( lu.rank() == A.rows() ) { Number newOffset = mNormal.transpose() * A.inverse() * b; return Halfspace<Number>( mNormal.transpose() * A.inverse(), newOffset + mScalar ); } else { // we cannot invert A - chose points on the plane surface and create new plane assert( false ); // TODO return Halfspace<Number>(); } } template <typename Number> vector_t<Number> Halfspace<Number>::intersectionVector( const Halfspace<Number>& _rhs ) const { matrix_t<Number> A = matrix_t<Number>( 3, mNormal.rows() ); A.row( 0 ) = mNormal.transpose(); A.row( 1 ) = _rhs.normal().transpose(); A.row( 2 ) = vector_t<Number>::Ones( A.cols() ).transpose(); vector_t<Number> b = vector_t<Number>( 3 ); b << mScalar, _rhs.offset(), Number( 1 ); vector_t<Number> result = A.fullPivLu().solve( b ); // vector_t<Number> result = gauss( A, b ); return result; } template <typename Number> vector_t<Number> Halfspace<Number>::fastIntersect( const std::vector<Halfspace<Number>>& _planes ) { assert( _planes.size() == _planes.begin()->dimension() ); // TODO: Make function more general to cope with arbitrary input. matrix_t<Number> A( _planes.size(), _planes.begin()->dimension() ); vector_t<Number> b( _planes.size() ); std::size_t pos = 0; for ( auto planeIt = _planes.begin(); planeIt != _planes.end(); ++planeIt ) { A.row( pos ) = planeIt->normal().transpose(); b( pos ) = planeIt->offset(); ++pos; } Eigen::FullPivLU<matrix_t<Number>> lu_decomp( A ); if ( lu_decomp.rank() < A.rows() ) { // TODO: Cope with intersection plane. } vector_t<Number> res = lu_decomp.solve( b ); /* // check for infinity bool infty = false; for ( unsigned i = 0; i < res.rows(); ++i ) { if ( std::numeric_limits<Number>::infinity() == ( Number( res( i ) ) ) ) { //std::cout << ( Number( res( i ) ) ) << " is infty." << std::endl; infty = true; break; } } */ return res; } template <typename Number> vector_t<Number> Halfspace<Number>::saveIntersect( const std::vector<Halfspace<Number>>& _planes, Number threshold ) { assert( _planes.size() == _planes.begin()->dimension() ); // TODO: Make function more general to cope with arbitrary input. matrix_t<Number> A( _planes.size(), _planes.begin()->dimension() ); vector_t<Number> b( _planes.size() ); std::size_t pos = 0; for ( auto planeIt = _planes.begin(); planeIt != _planes.end(); ++planeIt ) { A.row( pos ) = planeIt->normal().transpose(); b( pos ) = planeIt->offset(); ++pos; } Eigen::FullPivLU<matrix_t<Number>> lu_decomp( A ); if ( lu_decomp.rank() < A.rows() ) { // TODO: Cope with intersection plane. } vector_t<Number> res = lu_decomp.solve( b ); std::vector<std::size_t> belowIndices; for ( std::size_t index = 0; index < _planes.size(); ++index ) { Number dist = _planes.at( index ).offset() - _planes.at( index ).normal().dot( res ); if ( dist > 0 ) { belowIndices.push_back( index ); } } Number eps = std::numeric_limits<Number>::epsilon(); std::size_t iterationCount = 0; while ( !belowIndices.empty() ) { // enlarge as long as point lies below one of the planes. if ( eps < threshold ) { eps = eps * 2; } else { eps += std::numeric_limits<Number>::epsilon(); } for ( std::size_t index = 0; index < _planes.size(); ++index ) { A.row( index ) = _planes.at( index ).normal().transpose(); // if(belowIndices.front() == index) { // std::cout << "Shift plane + " << eps << ", dist: "; b( index ) = _planes.at( index ).offset() + eps; // belowIndices.erase(belowIndices.begin()); //} else { // b(index) = _planes.at(index).offset(); //} } belowIndices.clear(); assert( belowIndices.empty() ); vector_t<Number> tmp = Eigen::FullPivLU<matrix_t<Number>>( A ).solve( b ); for ( std::size_t i = 0; i < _planes.size(); ++i ) { Number dist = _planes.at( i ).offset() - _planes.at( i ).normal().dot( tmp ); if ( dist > 0 ) { belowIndices.push_back( i ); } } ++iterationCount; if ( belowIndices.empty() ) { res = tmp; } } return res; } template <typename Number> bool Halfspace<Number>::contains( const vector_t<Number> _vector ) const { return satisfiesIneqation( mNormal, mScalar, _vector ); } template <typename Number> bool Halfspace<Number>::contains( const Point<Number> _vector ) const { return this->contains( _vector.rawCoordinates() ); } template <typename Number> bool Halfspace<Number>::contains( const std::vector<Point<Number>>& _points ) const { for ( const auto& point : _points ) { if ( !this->contains( point.rawCoordinates() ) ) { return false; } } return true; } template <typename Number> bool Halfspace<Number>::exactContains( vector_t<Number> const& point ) const { hypro::vector_t<mpq_class> normal = mNormal.template cast<mpq_class>(); hypro::vector_t<mpq_class> mpq_vertex = point.template cast<mpq_class>(); mpq_class offset = mScalar; return normal.dot( mpq_vertex ) - offset <= 0; } template <typename Number> bool Halfspace<Number>::holds( const vector_t<Number> _vector ) const { return ( _vector.dot( mNormal ) == mScalar ); } template <typename Number> vector_t<Number> Halfspace<Number>::computePlaneNormal( const std::vector<vector_t<Number>>& pointSet ) { assert( !pointSet.empty() ); // case: dimension-many vertices in the plane if ( pointSet.size() <= unsigned( pointSet.begin()->rows() ) ) { // method avoiding glpk and using Eigen instead (higher precision) Eigen::Index dim = pointSet.begin()->rows(); matrix_t<Number> constraints( pointSet.size(), dim + 1 ); for ( unsigned pos = 0; pos < pointSet.size(); ++pos ) { constraints.row( pos ).head( dim ) = pointSet.at( pos ).transpose(); constraints.row( pos )( dim ) = Number( 1 ); } TRACE( "hypro.datastructures", "computing kernel of " << constraints ); TRACE( "hypro.datastructures", "rows: " << constraints.rows() << ", cols: " << constraints.cols() ); matrix_t<Number> kernel = constraints.fullPivLu().kernel(); vector_t<Number> normal = kernel.col( 0 ).head( dim ); TRACE( "hypro.datastructures", "Computed kernel: " << kernel ); return normal; } else { /* * Setup LP with GLPK */ // TODO: Re-think this: apparently this only works, if all points lie exactly on the plane, in which case you // could have selected only the dim-first ones. glp_prob* normal; normal = glp_create_prob(); glp_set_obj_dir( normal, GLP_MAX ); // we have one row for each edge in our set glp_add_rows( normal, int( pointSet.size() ) ); // constraints of auxiliary variables (bounds for rows) for ( int i = 1; i <= int( pointSet.size() ); ++i ) { glp_set_row_bnds( normal, i, GLP_FX, 0.0, 0.0 ); } // each column corresponds to one dimension of a vector in our edgeSet // TODO consider p1 & p2 of different dimensions? (-> two edge sets) glp_add_cols( normal, int( pointSet.at( 0 ).rows() ) ); // coefficients of objective function: for ( int i = 1; i <= pointSet.at( 0 ).rows(); ++i ) { glp_set_obj_coef( normal, i, 1.0 ); } // constraints for structural variables for ( int i = 1; i <= pointSet.at( 0 ).rows(); ++i ) { glp_set_col_bnds( normal, i, GLP_DB, -1.0, 1.0 ); } // setup matrix coefficients std::size_t elements = ( pointSet.size() ) * ( std::size_t( pointSet.at( 0 ).rows() ) ); int* ia = new int[elements + 1]; int* ja = new int[elements + 1]; double* ar = new double[elements + 1]; int pos = 1; // to prevent bugs ia[0] = 0; ja[0] = 0; ar[0] = 0; for ( int i = 1; i <= int( pointSet.size() ); ++i ) { for ( int j = 1; j <= pointSet.at( 0 ).rows(); ++j ) { ia[pos] = i; ja[pos] = j; vector_t<Number> tmpVec = pointSet.at( i - 1 ); ar[pos] = carl::toDouble( tmpVec( j - 1 ) ); ++pos; } } assert( pos - 1 <= int( elements ) ); glp_load_matrix( normal, int( elements ), ia, ja, ar ); glp_simplex( normal, NULL ); glp_exact( normal, NULL ); vector_t<Number> result = vector_t<Number>( pointSet.at( 0 ).rows(), 1 ); // fill the result vector based on the optimal solution returned by the LP for ( unsigned i = 1; i <= pointSet.at( 0 ).rows(); ++i ) { result( i - 1 ) = carl::rationalize<Number>( glp_get_col_prim( normal, i ) ); } glp_delete_prob( normal ); delete[] ja; delete[] ia; delete[] ar; return result; } } template <typename Number> Number Halfspace<Number>::computePlaneOffset( const vector_t<Number>& normal, const Point<Number>& pointOnPlane ) { return normal.dot( pointOnPlane.rawCoordinates() ); } // Return mNormal as a matrix template <typename Number> matrix_t<Number> Halfspace<Number>::matrix() const { matrix_t<Number> mat = matrix_t<Number>::Zero( 1, mNormal.rows() ); mat.row( 0 ) = mNormal.transpose(); return mat; } // Return mScalar as a vector template <typename Number> vector_t<Number> Halfspace<Number>::vector() const { vector_t<Number> vec = vector_t<Number>::Zero( 1 ); vec( 0 ) = mScalar; return vec; } // A halfspace itself cannot be empty, except its normal is the zero vector and the scalar is smaller than 0 template <typename Number> bool Halfspace<Number>::empty() const { if ( mNormal != vector_t<Number>::Zero( mNormal.rows() ) && mScalar < 0 ) return true; return false; } template <typename Number> EvaluationResult<Number> Halfspace<Number>::evaluate( const vector_t<Number>& direction, bool /*useExact*/ ) const { assert( mNormal.rows() == direction.rows() ); std::pair<bool, Number> dependent = linearDependent( mNormal, direction ); if ( dependent.first ) { if ( dependent.second > 0 ) { // The vectors are dependent -> to find point on plane and to avoid squareroot computations, return vector // which contains zeroes except of the position with the first non-zero coeff, which is set to the stored // distance. vector_t<Number> pointOnPlane = vector_t<Number>::Zero( direction.rows() ); unsigned i = 0; while ( i < direction.rows() && direction( i ) == 0 ) { ++i; } pointOnPlane( i ) = mScalar; return EvaluationResult<Number>( mScalar, pointOnPlane, SOLUTION::FEAS ); } else { return EvaluationResult<Number>( 0, SOLUTION::INFTY ); } } return EvaluationResult<Number>( 0, SOLUTION::INFTY ); } template <typename Number> std::vector<EvaluationResult<Number>> Halfspace<Number>::multiEvaluate( const matrix_t<Number>& _directions, bool /*useExact*/ ) const { assert( _directions.cols() == this->dimension() ); std::vector<EvaluationResult<Number>> res; vector_t<Number> pointOnPlane = vector_t<Number>::Zero( dimension() ); assert( mNormal.nonZeros() != 0 ); unsigned nonZeroPos = 0; while ( mNormal( nonZeroPos ) == 0 ) { ++nonZeroPos; } pointOnPlane( nonZeroPos ) = mScalar; for ( unsigned index = 0; index < _directions.rows(); ++index ) { std::pair<bool, Number> dependent = linearDependent( vector_t<Number>( mNormal ), vector_t<Number>( _directions.row( index ) ) ); if ( dependent.first ) { if ( dependent.second > 0 ) { res.emplace_back( mScalar * dependent.second, pointOnPlane, SOLUTION::FEAS ); } else { res.emplace_back( 1, pointOnPlane, SOLUTION::INFTY ); } } else { res.emplace_back( 1, pointOnPlane, SOLUTION::INFTY ); } } assert( res.size() == std::size_t( _directions.rows() ) ); return res; } } // namespace hypro
32.442085
118
0.671824
hypro
db08847e831d840c41f5bec28dd020606888ce4b
801
hpp
C++
Jackal/Source/Core/Public/Core/Math/Color4.hpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
Jackal/Source/Core/Public/Core/Math/Color4.hpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
Jackal/Source/Core/Public/Core/Math/Color4.hpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Jackal Engine, MIT License. #pragma once #include "Core/Platform/Platform.hpp" #include "Core/Platform/JTypes.hpp" #include "Vector4.hpp" namespace jackal { // Color values marked with normalized values from [0.0f, 1.0f]. // These values are used to determine the color of some mesh object. struct Color { Color(uint8 r = 0, uint8 g = 0, uint8 b = 0, uint8 a = 0) : r(r), g(g), b(b), a(a) { } struct { uint8 r, g, b, a; }; }; // Standard color values. static Color RED = Color(255, 0, 0, 255); static Color GREEN = Color(0, 255, 0, 255); static Color BLUE = Color(0, 0, 255, 255); static Color BLACK = Color(0, 0, 0, 255); static Color WHITE = Color(255, 255, 255, 255); } // jackal
28.607143
68
0.589263
CheezBoiger
db090d2234185e2337bb31462e30be6295e76b59
22,708
cpp
C++
Lumos/src/Editor/Editor.cpp
adriengivry/Lumos
beab295c25639e2320be9f1b6f0c0e49a2412d5a
[ "MIT" ]
null
null
null
Lumos/src/Editor/Editor.cpp
adriengivry/Lumos
beab295c25639e2320be9f1b6f0c0e49a2412d5a
[ "MIT" ]
null
null
null
Lumos/src/Editor/Editor.cpp
adriengivry/Lumos
beab295c25639e2320be9f1b6f0c0e49a2412d5a
[ "MIT" ]
1
2020-04-17T13:40:49.000Z
2020-04-17T13:40:49.000Z
#include "lmpch.h" #include "Editor.h" #include "ImGUIConsoleSink.h" #include "SceneWindow.h" #include "ProfilerWindow.h" #include "ConsoleWindow.h" #include "HierarchyWindow.h" #include "InspectorWindow.h" #include "ApplicationInfoWindow.h" #include "GraphicsInfoWindow.h" #include "App/Application.h" #include "Core/OS/Input.h" #include "Core/Profiler.h" #include "App/Engine.h" #include "App/Scene.h" #include "App/SceneManager.h" #include "Events/ApplicationEvent.h" #include "ECS/Component/Components.h" #include "Physics/LumosPhysicsEngine/LumosPhysicsEngine.h" #include "Graphics/Layers/Layer3D.h" #include "Graphics/Sprite.h" #include "Graphics/Light.h" #include "Graphics/Camera/Camera.h" #include "Graphics/Layers/LayerStack.h" #include "Graphics/API/GraphicsContext.h" #include "Graphics/MeshFactory.h" #include "Graphics/Renderers/GridRenderer.h" #include "ImGui/ImGuiHelpers.h" #include <imgui/imgui_internal.h> #include <imgui/plugins/ImGuizmo.h> #include <imgui/plugins/ImGuiAl/button/imguial_button.h> #include <IconFontCppHeaders/IconsFontAwesome5.h> #ifdef LUMOS_PLATFORM_WINDOWS #include <imgui/plugins/ImFileBrowser.h> #endif static ImVec2 operator+(const ImVec2 &a, const ImVec2 &b) { return ImVec2(a.x + b.x, a.y + b.y); } static ImVec2 operator-(const ImVec2 &a, const ImVec2 &b) { return ImVec2(a.x - b.x, a.y - b.y); } namespace Lumos { Editor::Editor(Application* app, u32 width, u32 height) : m_Application(app), m_Selected(), m_FileBrowser(nullptr) { } Editor::~Editor() { #ifdef LUMOS_PLATFORM_WINDOWS lmdel m_FileBrowser; #endif } void Editor::OnInit() { const char *ini[] = { "editor.ini", "editor/editor.ini", "../editor/editor.ini" }; bool fileFound = false; for (int i = 0; i < IM_ARRAYSIZE(ini); ++i) { auto fexist = [](const char *f) -> bool { FILE *fp = fopen(f, "rb"); return fp ? (fclose(fp), 1) : 0; }; if (fexist(ini[i])) { ImGui::GetIO().IniFilename = ini[i]; fileFound = true; break; } } // if (!fileFound) // { // FileSystem::WriteFile("editor.ini", nullptr); // ImGui::GetIO().IniFilename = "editor.ini"; // } m_ComponentIconMap[typeid(Graphics::Light).hash_code()] = ICON_FA_LIGHTBULB; m_ComponentIconMap[typeid(CameraComponent).hash_code()] = ICON_FA_CAMERA; m_ComponentIconMap[typeid(SoundComponent).hash_code()] = ICON_FA_VOLUME_UP; m_ComponentIconMap[typeid(Graphics::Sprite).hash_code()] = ICON_FA_IMAGE; m_ComponentIconMap[typeid(Maths::Transform).hash_code()] = ICON_FA_VECTOR_SQUARE; m_ComponentIconMap[typeid(Physics2DComponent).hash_code()] = ICON_FA_SQUARE; m_ComponentIconMap[typeid(Physics3DComponent).hash_code()] = ICON_FA_CUBE; m_ComponentIconMap[typeid(MeshComponent).hash_code()] = ICON_FA_SHAPES; m_ComponentIconMap[typeid(MaterialComponent).hash_code()] = ICON_FA_PAINT_BRUSH; m_Windows.emplace_back(CreateRef<ConsoleWindow>()); m_Windows.emplace_back(CreateRef<SceneWindow>()); m_Windows.emplace_back(CreateRef<ProfilerWindow>()); m_Windows.back()->SetActive(false); m_Windows.emplace_back(CreateRef<InspectorWindow>()); m_Windows.emplace_back(CreateRef<HierarchyWindow>()); m_Windows.emplace_back(CreateRef<GraphicsInfoWindow>()); m_Windows.back()->SetActive(false); m_Windows.emplace_back(CreateRef<ApplicationInfoWindow>()); for (auto& window : m_Windows) window->SetEditor(this); m_ShowImGuiDemo = false; #ifdef LUMOS_PLATFORM_WINDOWS m_FileBrowser = lmnew ImGui::FileBrowser(ImGuiFileBrowserFlags_CreateNewDir | ImGuiFileBrowserFlags_EnterNewFilename | ImGuiFileBrowserFlags_NoModal); m_FileBrowser->SetTitle("Test File Browser"); m_FileBrowser->SetFileFilters({ ".sh" , ".h" }); m_FileBrowser->SetLabels(ICON_FA_FOLDER, ICON_FA_FILE, ICON_FA_FOLDER_OPEN); m_FileBrowser->Refresh(); #endif ImGuiHelpers::SetTheme(ImGuiHelpers::Dark); m_Selected = entt::null; } void Editor::OnImGui() { LUMOS_PROFILE_FUNC; DrawMenuBar(); BeginDockSpace(false); for (auto& window : m_Windows) { if (window->Active()) window->OnImGui(); } if(m_ShowImGuiDemo) ImGui::ShowDemoWindow(&m_ShowImGuiDemo); m_View2D = Application::Instance()->GetSceneManager()->GetCurrentScene()->GetCamera()->IsOrthographic(); if (m_ShowGrid) { if (m_3DGridLayer == nullptr) { m_3DGridLayer = new Layer3D(new Graphics::GridRenderer(u32(Application::Instance()->GetWindowSize().x), u32(Application::Instance()->GetWindowSize().y), true), "Grid"); Application::Instance()->PushLayerInternal(m_3DGridLayer, true, false); } } else if(m_3DGridLayer) { Application::Instance()->GetLayerStack()->PopOverlay(m_3DGridLayer); m_3DGridLayer = nullptr; } EndDockSpace(); } void Editor::DrawMenuBar() { if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Exit")) { Application::Instance()->SetAppState(AppState::Closing); } if(ImGui::MenuItem("Open File")) { #ifdef LUMOS_PLATFORM_WINDOWS if(ImGuiAl::Button("open file dialog", true)) m_FileBrowser->Open(); ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->Pos + ImVec2(viewport->Size.x * 0.5f, viewport->Size.y * 0.5f), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); m_FileBrowser->Display(); if(m_FileBrowser->HasSelected()) { std::cout << "Selected filename" << m_FileBrowser->GetSelected().string() << std::endl; m_FileBrowser->ClearSelected(); } #endif } if (ImGui::BeginMenu("Style")) { if (ImGui::MenuItem("Dark", "")) { ImGuiHelpers::SetTheme(ImGuiHelpers::Dark); } if (ImGui::MenuItem("Black", "")) { ImGuiHelpers::SetTheme(ImGuiHelpers::Black); } if (ImGui::MenuItem("Grey", "")) { ImGuiHelpers::SetTheme(ImGuiHelpers::Grey); } if (ImGui::MenuItem("Light", "")) { ImGuiHelpers::SetTheme(ImGuiHelpers::Light); } if (ImGui::MenuItem("Cherry", "")) { ImGuiHelpers::SetTheme(ImGuiHelpers::Cherry); } if (ImGui::MenuItem("Blue", "")) { ImGuiHelpers::SetTheme(ImGuiHelpers::Blue); } if (ImGui::MenuItem("Cinder", "")) { ImGuiHelpers::SetTheme(ImGuiHelpers::Cinder); } if (ImGui::MenuItem("Classic", "")) { ImGuiHelpers::SetTheme(ImGuiHelpers::Classic); } if (ImGui::MenuItem("ClassicDark", "")) {ImGuiHelpers::SetTheme(ImGuiHelpers::ClassicDark); } if (ImGui::MenuItem("ClassicLight", "")) { ImGuiHelpers::SetTheme(ImGuiHelpers::ClassicLight); } ImGui::EndMenu(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Edit")) { if (ImGui::MenuItem("Undo", "CTRL+Z")) {} if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item ImGui::Separator(); if (ImGui::MenuItem("Cut", "CTRL+X")) {} if (ImGui::MenuItem("Copy", "CTRL+C")) {} if (ImGui::MenuItem("Paste", "CTRL+V")) {} ImGui::EndMenu(); } if (ImGui::BeginMenu("Windows")) { for (auto& window : m_Windows) { if (ImGui::MenuItem(window->GetName().c_str(), "", &window->Active(), true)) { window->SetActive(true); } } if (ImGui::MenuItem("ImGui Demo", "", &m_ShowImGuiDemo, true)) { m_ShowImGuiDemo = true; } ImGui::EndMenu(); } if (ImGui::BeginMenu("Scenes")) { auto scenes = Application::Instance()->GetSceneManager()->GetSceneNames(); for(size_t i = 0; i < scenes.size(); i++) { auto name = scenes[i]; if (ImGui::MenuItem(name.c_str())) { Application::Instance()->GetSceneManager()->SwitchScene(name); } } ImGui::EndMenu(); } if (ImGui::BeginMenu("Entity")) { auto& registry = m_Application->GetSceneManager()->GetCurrentScene()->GetRegistry(); if (ImGui::MenuItem("CreateEmpty")) { registry.create(); } if (ImGui::MenuItem("Cube")) { auto entity = registry.create(); registry.assign<MeshComponent>(entity, Graphics::CreatePrimative(Graphics::PrimitiveType::Cube)); registry.assign<NameComponent>(entity, "Cube"); registry.assign<Maths::Transform>(entity); } if (ImGui::MenuItem("Sphere")) { auto entity = registry.create(); registry.assign<MeshComponent>(entity, Graphics::CreatePrimative(Graphics::PrimitiveType::Sphere)); registry.assign<NameComponent>(entity, "Sphere"); registry.assign<Maths::Transform>(entity); } if (ImGui::MenuItem("Pyramid")) { auto entity = registry.create(); registry.assign<MeshComponent>(entity, Graphics::CreatePrimative(Graphics::PrimitiveType::Pyramid)); registry.assign<NameComponent>(entity, "Pyramid"); registry.assign<Maths::Transform>(entity); } if (ImGui::MenuItem("Plane")) { auto entity = registry.create(); registry.assign<MeshComponent>(entity, Graphics::CreatePrimative(Graphics::PrimitiveType::Plane)); registry.assign<NameComponent>(entity, "Plane"); registry.assign<Maths::Transform>(entity); } if (ImGui::MenuItem("Cylinder")) { auto entity = registry.create(); registry.assign<MeshComponent>(entity, Graphics::CreatePrimative(Graphics::PrimitiveType::Cylinder)); registry.assign<NameComponent>(entity, "Cylinder"); registry.assign<Maths::Transform>(entity); } if (ImGui::MenuItem("Capsule")) { auto entity = registry.create(); registry.assign<MeshComponent>(entity, Graphics::CreatePrimative(Graphics::PrimitiveType::Capsule)); registry.assign<NameComponent>(entity, "Capsule"); registry.assign<Maths::Transform>(entity); } ImGui::EndMenu(); } ImGui::SameLine(ImGui::GetWindowContentRegionMax().x / 2.0f); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.1f, 0.2f, 0.7f, 0.0f)); bool selected; { selected = m_Application->GetEditorState() == EditorState::Play; if (selected) ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.28f, 0.56f, 0.9f, 1.0f)); if (ImGui::Button(ICON_FA_PLAY, ImVec2(19.0f, 19.0f))) m_Application->SetEditorState(EditorState::Play); ImGuiHelpers::Tooltip("Play"); if (selected) ImGui::PopStyleColor(); } ImGui::SameLine(); { selected = m_Application->GetEditorState() == EditorState::Paused; if (selected) ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.28f, 0.56f, 0.9f, 1.0f)); if (ImGui::Button(ICON_FA_PAUSE, ImVec2(19.0f, 19.0f))) m_Application->SetEditorState(EditorState::Paused); ImGuiHelpers::Tooltip("Pause"); if (selected) ImGui::PopStyleColor(); } ImGui::SameLine(); { selected = m_Application->GetEditorState() == EditorState::Next; if (selected) ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.28f, 0.56f, 0.9f, 1.0f)); if (ImGui::Button(ICON_FA_STEP_FORWARD, ImVec2(19.0f, 19.0f))) m_Application->SetEditorState(EditorState::Next); ImGuiHelpers::Tooltip("Next"); if (selected) ImGui::PopStyleColor(); } ImGui::PopStyleColor(); ImGui::EndMainMenuBar(); } } void Editor::OnImGuizmo() { if (m_Selected == entt::null || m_ImGuizmoOperation == 4) return; if (m_ShowGizmos) { Maths::Matrix4 view = Application::Instance()->GetSceneManager()->GetCurrentScene()->GetCamera()->GetViewMatrix(); Maths::Matrix4 proj = Application::Instance()->GetSceneManager()->GetCurrentScene()->GetCamera()->GetProjectionMatrix(); #ifdef LUMOS_RENDER_API_VULKAN if (Graphics::GraphicsContext::GetRenderAPI() == Graphics::RenderAPI::VULKAN) proj.m11_ *= -1.0f; #endif view = view.Transpose(); proj = proj.Transpose(); ImGuizmo::SetDrawlist(); ImGuizmo::SetOrthographic(Application::Instance()->GetSceneManager()->GetCurrentScene()->GetCamera()->IsOrthographic()); auto& registry = m_Application->GetSceneManager()->GetCurrentScene()->GetRegistry(); auto transform = registry.try_get<Maths::Transform>(m_Selected); if (transform != nullptr) { Maths::Matrix4 model = transform->GetWorldMatrix(); model = model.Transpose(); float snapAmount[3] = { m_SnapAmount , m_SnapAmount , m_SnapAmount }; float delta[16]; ImGuizmo::Manipulate(Maths::ValuePointer(view), Maths::ValuePointer(proj), static_cast<ImGuizmo::OPERATION>(m_ImGuizmoOperation), ImGuizmo::LOCAL, Maths::ValuePointer(model), delta, m_SnapQuizmo ? snapAmount : nullptr); if (ImGuizmo::IsUsing()) { if (static_cast<ImGuizmo::OPERATION>(m_ImGuizmoOperation) == ImGuizmo::OPERATION::SCALE) { auto mat = Maths::Matrix4(delta).Transpose(); transform->SetLocalScale(transform->GetLocalScale() * mat.Scale()); } else { auto mat = Maths::Matrix4(delta).Transpose() * transform->GetLocalMatrix(); transform->SetLocalTransform(mat); auto physics2DComponent = registry.try_get<Physics2DComponent>(m_Selected); if (physics2DComponent) { physics2DComponent->GetPhysicsObject()->SetPosition({ mat.Translation().x, mat.Translation().y }); } else { auto physics3DComponent = registry.try_get<Physics3DComponent>(m_Selected); if (physics3DComponent) { physics3DComponent->GetPhysicsObject()->SetPosition(mat.Translation()); physics3DComponent->GetPhysicsObject()->SetOrientation(mat.Rotation()); } } } } } } if (m_Selected != entt::null && m_ShowViewSelected) { auto& registry = m_Application->GetSceneManager()->GetCurrentScene()->GetRegistry(); auto camera = Application::Instance()->GetSceneManager()->GetCurrentScene()->GetCamera(); auto transform = registry.try_get<Maths::Transform>(m_Selected); #if 0 Maths::Matrix4 view = camera->GetViewMatrix(); float camDistance = transform ? (Application::Instance()->GetSceneManager()->GetCurrentScene()->GetCamera()->GetPosition() - transform->GetWorldMatrix().Translation()).Length() : 0.0f; auto window = ImGui::GetCurrentWindow(); auto size = 128.0f; auto windowPos = window->Pos; auto windowSize = window->Size; auto viewManipulatePos = ImVec2(windowPos.x + windowSize.x - size, size / 2.0f - 20.0f + windowPos.y); //view = Maths::Matrix4::Inverse(view); ImGuizmo::ViewManipulate(Maths::ValuePointer(view), camDistance, viewManipulatePos, ImVec2(size, size), 0x10101010); view = Maths::Matrix4::Inverse(view); auto quat = view.ToQuaternion(); auto euler = quat.ToEuler(); camera->SetPitch(euler.x); camera->SetYaw(euler.y); camera->SetPosition(view.Translation()); #else float pos[3] = { camera->GetPosition().x, camera->GetPosition().y, camera->GetPosition().z }; float rot[3] = { camera->GetPitch(), camera->GetYaw(), camera->GetRoll() }; float scale[3] = { 1.0f, 1.0f, 1.0f }; float view[16]; ImGuizmo::RecomposeMatrixFromComponents(pos, rot, scale, view); float camDistance = transform ? (Application::Instance()->GetSceneManager()->GetCurrentScene()->GetCamera()->GetPosition() - transform->GetWorldMatrix().Translation()).Length() : 0.0f; auto window = ImGui::GetCurrentWindow(); auto size = 128.0f; auto windowPos = window->Pos; auto windowSize = window->Size; auto viewManipulatePos = ImVec2(windowPos.x + windowSize.x - size, size / 2.0f - 20.0f + windowPos.y); ImGuizmo::ViewManipulate(view, camDistance, viewManipulatePos, ImVec2(size, size), 0x10101010); ImGuizmo::DecomposeMatrixToComponents(view, pos, rot, scale); camera->SetPitch(rot[0]); camera->SetYaw(rot[1]); camera->SetRoll(rot[2]); camera->SetPosition({ pos[0], pos[1], pos[2] }); #endif } } void Editor::BeginDockSpace(bool infoBar) { static bool p_open = true; static bool opt_fullscreen_persistant = true; static ImGuiDockNodeFlags opt_flags = ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton; bool opt_fullscreen = opt_fullscreen_persistant; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, // because it would be confusing to have two docking targets within each others. ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDocking; if (opt_fullscreen) { ImGuiViewport* viewport = ImGui::GetMainViewport(); auto pos = viewport->Pos; auto size = viewport->Size; bool menuBar = true; if (menuBar) { const float infoBarSize = 19.0f; pos.y += infoBarSize; size.y -= infoBarSize; } if (infoBar) { const float infoBarSize = 24.0f; pos.y += infoBarSize; size.y -= infoBarSize; } ImGui::SetNextWindowPos(pos); ImGui::SetNextWindowSize(size); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } // When using ImGuiDockNodeFlags_PassthruDockspace, DockSpace() will render our background and handle the pass-thru hole, so we ask Begin() to not render a background. if (opt_flags & ImGuiDockNodeFlags_DockSpace) window_flags |= ImGuiWindowFlags_NoBackground; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("MyDockspace", &p_open, window_flags); ImGui::PopStyleVar(); if (opt_fullscreen) ImGui::PopStyleVar(2); if (ImGui::DockBuilderGetNode(ImGui::GetID("MyDockspace")) == nullptr) { ImGuiID dockspace_id = ImGui::GetID("MyDockspace"); ImGui::DockBuilderRemoveNode(dockspace_id); ImGui::DockBuilderAddNode(dockspace_id); ImGui::DockBuilderSetNodeSize(dockspace_id, ImGui::GetIO().DisplaySize); ImGuiID dock_main_id = dockspace_id; ImGuiID dock_id_bottom = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Down, 0.2f, nullptr, &dock_main_id); ImGuiID dock_id_left = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Left, 0.2f, nullptr, &dock_main_id); ImGuiID dock_id_right = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Right, 0.3f, nullptr, &dock_main_id); ImGuiID dock_id_middle = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Right, 0.8f, nullptr, &dock_main_id); ImGui::DockBuilderDockWindow("###scene", dock_id_middle); ImGui::DockBuilderDockWindow("###inspector", dock_id_right); ImGui::DockBuilderDockWindow("###hierarchy", dock_id_left); ImGui::DockBuilderDockWindow("###console", dock_id_bottom); ImGui::DockBuilderDockWindow("###profiler", dock_id_bottom); ImGui::DockBuilderDockWindow("Dear ImGui Demo", dock_id_left); ImGui::DockBuilderDockWindow("GraphicsInfo", dock_id_left); ImGui::DockBuilderDockWindow("ApplicationInfo", dock_id_left); ImGui::DockBuilderFinish(dockspace_id); } // Dockspace ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGuiID dockspace_id = ImGui::GetID("MyDockspace"); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), opt_flags); } } void Editor::EndDockSpace() { ImGui::End(); } void Editor::OnNewScene(Scene * scene) { m_Selected = entt::null; m_CurrentSceneAspectRatio = 0.0f; for (auto window : m_Windows) { window->OnNewScene(scene); } } void Editor::Draw2DGrid(ImDrawList* drawList, const ImVec2& cameraPos, const ImVec2& windowPos, const ImVec2& canvasSize, const float factor, const float thickness) { static const auto graduation = 10; float GRID_SZ = canvasSize.y * 0.5f / factor; const ImVec2& offset = { canvasSize.x * 0.5f - cameraPos.x * GRID_SZ, canvasSize.y * 0.5f + cameraPos.y * GRID_SZ }; ImU32 GRID_COLOR = IM_COL32(200, 200, 200, 40); float gridThickness = 1.0f; const auto& gridColor = GRID_COLOR; auto smallGraduation = GRID_SZ / graduation; const auto& smallGridColor = IM_COL32(100, 100, 100, smallGraduation); for (float x = -GRID_SZ; x < canvasSize.x + GRID_SZ; x += GRID_SZ) { auto localX = floorf(x + fmodf(offset.x, GRID_SZ)); drawList->AddLine(ImVec2{ localX, 0.0f } + windowPos, ImVec2{ localX, canvasSize.y } +windowPos, gridColor, gridThickness); if (smallGraduation > 5.0f) { for (int i = 1; i < graduation; ++i) { const auto graduation = floorf(localX + smallGraduation * i); drawList->AddLine(ImVec2{ graduation, 0.0f } +windowPos, ImVec2{ graduation, canvasSize.y } +windowPos, smallGridColor, 1.0f); } } } for (float y = -GRID_SZ; y < canvasSize.y + GRID_SZ; y += GRID_SZ) { auto localY = floorf(y + fmodf(offset.y, GRID_SZ)); drawList->AddLine(ImVec2{ 0.0f, localY } +windowPos, ImVec2{ canvasSize.x, localY } +windowPos, gridColor, gridThickness); if (smallGraduation > 5.0f) { for (int i = 1; i < graduation; ++i) { const auto graduation = floorf(localY + smallGraduation * i); drawList->AddLine(ImVec2{ 0.0f, graduation } +windowPos, ImVec2{ canvasSize.x, graduation } +windowPos, smallGridColor,1.0f); } } } } void Editor::OnEvent(Event& e) { EventDispatcher dispatcher(e); dispatcher.Dispatch<WindowResizeEvent>(BIND_EVENT_FN(Editor::OnWindowResize)); m_Application->OnEvent(e); } void Editor::BindEventFunction() { m_Application->GetWindow()->SetEventCallback(BIND_EVENT_FN(Editor::OnEvent)); } bool Editor::OnWindowResize(WindowResizeEvent & e) { return false; } }
35.425897
223
0.650079
adriengivry
db0c6d297e5b90d0a04d3194fd39ea728e280457
257
cpp
C++
src/Vtk/Wrapper/quickVtkOBJReader.cpp
ruisebastiao/QVTK
6e9aee0d0fc691539dca3b825d0ffe6e7b30db09
[ "BSD-3-Clause" ]
1
2021-09-13T06:17:31.000Z
2021-09-13T06:17:31.000Z
src/Vtk/Wrapper/quickVtkOBJReader.cpp
ruisebastiao/QVTK
6e9aee0d0fc691539dca3b825d0ffe6e7b30db09
[ "BSD-3-Clause" ]
null
null
null
src/Vtk/Wrapper/quickVtkOBJReader.cpp
ruisebastiao/QVTK
6e9aee0d0fc691539dca3b825d0ffe6e7b30db09
[ "BSD-3-Clause" ]
null
null
null
#include "quickVtkOBJReader.hpp" namespace quick { namespace Vtk { //Qml::Register::Class<OBJReader> OBJReader::Register(true); OBJReader::OBJReader() : AbstractPolyDataReader(vtkSmartPointer<vtkOBJReader>::New()) { } } }
21.416667
95
0.657588
ruisebastiao
db105f84cd2d327a910161bbe6633b35459310d9
3,254
cpp
C++
libvast/test/system/type_registry.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
63
2016-04-22T01:50:03.000Z
2019-07-31T15:50:36.000Z
libvast/test/system/type_registry.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
216
2017-01-24T16:25:43.000Z
2019-08-01T19:37:00.000Z
libvast/test/system/type_registry.cpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
28
2016-05-19T13:09:19.000Z
2019-04-12T15:11:42.000Z
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2020 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #define SUITE type_registry #include "vast/system/type_registry.hpp" #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/expression.hpp" #include "vast/defaults.hpp" #include "vast/detail/notifying_stream_manager.hpp" #include "vast/detail/spawn_container_source.hpp" #include "vast/system/importer.hpp" #include "vast/table_slice.hpp" #include "vast/table_slice_builder_factory.hpp" #include "vast/test/fixtures/actor_system_and_events.hpp" #include "vast/test/test.hpp" #include "vast/type.hpp" #include <caf/stateful_actor.hpp> #include <caf/test/dsl.hpp> #include <filesystem> #include <stddef.h> using namespace vast; namespace { template <class... Ts> vast::table_slice make_data(const vast::type& layout, Ts&&... ts) { auto builder = factory<table_slice_builder>::make( defaults::import::table_slice_type, layout); REQUIRE(builder->add(std::forward<Ts>(ts)...)); return builder->finish(); } } // namespace struct fixture : fixtures::deterministic_actor_system_and_events { fixture() : fixtures::deterministic_actor_system_and_events( VAST_PP_STRINGIFY(SUITE)) { MESSAGE("spawning AUT"); aut = spawn_aut(); REQUIRE(aut); CHECK_EQUAL(state().data.size(), 0u); } ~fixture() { MESSAGE("shutting down AUT"); self->send_exit(aut, caf::exit_reason::user_shutdown); } using stateful_type_registry_actor_pointer = system::type_registry_actor::stateful_pointer<system::type_registry_state>; system::type_registry_actor spawn_aut() { auto handle = sys.spawn(system::type_registry, directory); sched.run(); return handle; } system::type_registry_state& state() { return caf::actor_cast<stateful_type_registry_actor_pointer>(aut)->state; } system::type_registry_actor aut; }; FIXTURE_SCOPE(type_registry_tests, fixture) TEST(taxonomies) { MESSAGE("setting a taxonomy"); auto c1 = concepts_map{{{"foo", {"", {"a.fo0", "b.foO", "x.foe"}, {}}}, {"bar", {"", {"a.b@r", "b.baR"}, {}}}}}; auto t1 = taxonomies{c1, models_map{}}; self->send(aut, atom::put_v, t1); run(); MESSAGE("collecting some types"); const vast::type la = vast::type{ "a", vast::record_type{ {"fo0", vast::string_type{}}, }, }; auto slices_a = std::vector{make_data(la, "bogus")}; const vast::type lx = vast::type{ "x", vast::record_type{ {"foe", vast::count_type{}}, }, }; auto slices_x = std::vector{make_data(lx, 1u)}; vast::detail::spawn_container_source(sys, std::move(slices_a), aut); vast::detail::spawn_container_source(sys, std::move(slices_x), aut); run(); MESSAGE("resolving an expression"); auto exp = unbox(to<expression>("foo == 1")); auto ref = unbox(to<expression>("x.foe == 1")); self->send(aut, atom::resolve_v, exp); run(); expression result; self->receive( [&](expression r) { result = r; }, error_handler()); CHECK_EQUAL(result, ref); } FIXTURE_SCOPE_END()
27.576271
81
0.665028
rdettai
db17a13385c670c9ad3a7a01b861c7cb1964b01b
1,627
cpp
C++
test/unit/io/detail/misc_test.cpp
joergi-w/seqan3
b757646eee3cddf1f2487db8f1c9f3576ee37391
[ "CC-BY-4.0", "CC0-1.0" ]
283
2017-03-14T23:43:33.000Z
2022-03-28T02:30:02.000Z
test/unit/io/detail/misc_test.cpp
joergi-w/seqan3
b757646eee3cddf1f2487db8f1c9f3576ee37391
[ "CC-BY-4.0", "CC0-1.0" ]
2,754
2017-03-21T18:39:02.000Z
2022-03-31T13:26:15.000Z
test/unit/io/detail/misc_test.cpp
joergi-w/seqan3
b757646eee3cddf1f2487db8f1c9f3576ee37391
[ "CC-BY-4.0", "CC0-1.0" ]
88
2017-03-20T12:43:42.000Z
2022-03-17T08:56:13.000Z
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2021, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2021, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #include <gtest/gtest.h> #include <string> #include <vector> #include <seqan3/io/detail/misc.hpp> struct dummy_file { struct format1 { static inline std::vector<std::string> file_extensions{ {"fa"}, {"fasta"}}; }; struct format2 { static inline std::vector<std::string> file_extensions{ {"sam"}, {"bam"}}; }; using valid_formats = seqan3::type_list<format1, format2>; }; TEST(misc, valid_file_extensions) { // get all extensions. auto all_extensions = seqan3::detail::valid_file_extensions<dummy_file::valid_formats>(); // define testing lambda auto cmp_lambda = [&all_extensions] (auto & source) { return std::find(all_extensions.begin(), all_extensions.end(), source); }; // Test format1 extensions for (std::string & ext : dummy_file::format1::file_extensions) EXPECT_NE(cmp_lambda(ext), all_extensions.end()); // Test format2 extensions for (std::string & ext : dummy_file::format2::file_extensions) EXPECT_NE(cmp_lambda(ext), all_extensions.end()); }
32.54
104
0.596804
joergi-w
db183f466958c48efaf00f8de05b9b59e255aca1
1,908
cpp
C++
trikControl/src/pwmCapture.cpp
thetoropov/trikRuntime
f236e441875ff4ab999803252f26075e089ae04c
[ "Apache-2.0" ]
17
2015-03-20T16:56:36.000Z
2019-07-24T08:13:23.000Z
trikControl/src/pwmCapture.cpp
thetoropov/trikRuntime
f236e441875ff4ab999803252f26075e089ae04c
[ "Apache-2.0" ]
276
2015-02-01T20:25:37.000Z
2022-03-25T13:18:14.000Z
trikControl/src/pwmCapture.cpp
IKhonakhbeeva/trikRuntime
b87c4c4eb50ad505e69964e594123e3b4138f17d
[ "Apache-2.0" ]
50
2015-01-03T13:56:26.000Z
2022-03-29T12:47:39.000Z
/* Copyright 2013 - 2015 Roman Kurbatov, Yurii Litvinov and CyberTech Labs Ltd. * * 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 "pwmCapture.h" #include <QtCore/QByteArray> #include <QtCore/QTextStream> #include <trikKernel/configurer.h> #include <trikHal/hardwareAbstractionInterface.h> #include <QsLog.h> using namespace trikControl; PwmCapture::PwmCapture(const QString &port, const trikKernel::Configurer &configurer , const trikHal::HardwareAbstractionInterface &hardwareAbstraction) : mFrequencyFile(hardwareAbstraction.createInputDeviceFile(configurer.attributeByPort(port, "frequencyFile"))) , mDutyFile(hardwareAbstraction.createInputDeviceFile(configurer.attributeByPort(port, "dutyFile"))) , mState("PWM Capture on " + port) { if (!mFrequencyFile->open()) { mState.fail(); } if (!mDutyFile->open()) { mState.fail(); } mState.ready(); } PwmCapture::~PwmCapture() { } PwmCapture::Status PwmCapture::status() const { return mState.status(); } QVector<int> PwmCapture::frequency() { if (!mState.isReady()) { return {}; } mFrequencyFile->reset(); QVector<int> data(3); char c = '\0'; mFrequencyFile->stream() >> data[0] >> c >> data[1] >> c >> data[2] >> c; return data; } int PwmCapture::duty() { if (!mState.isReady()) { return {}; } mDutyFile->reset(); int data = 0; char c = '\0'; mDutyFile->stream() >> data >> c; return data; }
24.461538
111
0.713312
thetoropov
db18c03fe1a98c74608cdf967afcc724d55a4777
5,031
cpp
C++
src/CatroModulo_CM-4.cpp
CardinalModules/catro-modulo
bf6f969c5f7fff6a419a54197fb4318671281ad5
[ "BSD-3-Clause" ]
17
2019-03-08T01:49:29.000Z
2020-07-07T00:30:03.000Z
src/CatroModulo_CM-4.cpp
CardinalModules/catro-modulo
bf6f969c5f7fff6a419a54197fb4318671281ad5
[ "BSD-3-Clause" ]
20
2019-03-08T11:56:32.000Z
2021-12-20T23:55:30.000Z
src/CatroModulo_CM-4.cpp
CardinalModules/catro-modulo
bf6f969c5f7fff6a419a54197fb4318671281ad5
[ "BSD-3-Clause" ]
3
2019-04-30T03:08:07.000Z
2022-02-25T20:01:33.000Z
#include "CatroModulo.hpp" //Catro-Module CM-4: vcClk struct CM4Module : Module { enum ParamIds { PARAM_BPM, PARAM_RST, PARAM_SNAP, NUM_PARAMS }; enum InputIds { INPUT_EXT, INPUT_BPM, INPUT_RST, NUM_INPUTS }; enum OutputIds { OUTPUT_BPM1, OUTPUT_BPM2, OUTPUT_D2, OUTPUT_X2, OUTPUT_CLKD2, OUTPUT_CLK, OUTPUT_CLKX2, OUTPUT_RST, NUM_OUTPUTS }; enum LightIds { NUM_LIGHTS }; float bpm_display = 0.0; //create objects CM_BpmClock bpmclock; bool isreset = false; CM4Module() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); configParam(CM4Module::PARAM_BPM, 0.0f, 5.0, 0.0f, "tempo", " BPM", 0.0f, 100.0f); configParam(CM4Module::PARAM_SNAP, 0.0f, 2.0f, 1.0f, "snap"); configParam(CM4Module::PARAM_RST, 0.0f, 1.0f, 0.0f, "reset"); //initialize objects } void process(const ProcessArgs &args) override; }; void CM4Module::process(const ProcessArgs &args) { if (params[PARAM_SNAP].getValue() == 0){ bpmclock.setbpm(int( (params[PARAM_BPM].getValue() * 100.0) * 100) / 100.0f ); }else if (params[PARAM_SNAP].getValue() == 1){ bpmclock.setbpm(int(params[PARAM_BPM].getValue() * 100.0)); }else if (params[PARAM_SNAP].getValue() == 2){ bpmclock.setbpm(int( (params[PARAM_BPM].getValue() * 100.0) * 0.2) * 5.0f ); } outputs[OUTPUT_RST].setVoltage((inputs[INPUT_RST].getVoltage() || params[PARAM_RST].getValue()) * 10.0); bpmclock.setReset(outputs[OUTPUT_RST].getVoltage()); //external clock if (inputs[INPUT_EXT].isConnected()){ float extcv = bpmclock.exttrack(inputs[INPUT_EXT].getVoltage(), args.sampleTime); //extcv = (extcv > 0) ? (1.0f / extcv) * (60000.0f / args.sampleRate ) : 0.0f;//* 1.211387038158690f : 0.0f; if (params[PARAM_SNAP].getValue() == 0){ bpmclock.addcv(bpmclock.bpmtocv(0.01) * roundf(extcv * 10000.0f)); }else if (params[PARAM_SNAP].getValue() == 1){ bpmclock.addcv(bpmclock.bpmtocv(1) * roundf(extcv * 100.0f)); }else if (params[PARAM_SNAP].getValue() == 2){ bpmclock.addcv(bpmclock.bpmtocv(5) * roundf(extcv * 20.0f)); } isreset = false; }else if (isreset == false){ bpmclock.extreset(true); isreset = true; } outputs[OUTPUT_BPM1].setVoltage(bpmclock.getcv()); //add bpm cv outputs[OUTPUT_BPM2].setVoltage(bpmclock.addcv((inputs[INPUT_BPM].isConnected()) ? inputs[INPUT_BPM].getVoltage() : 0.0f)); outputs[OUTPUT_D2].setVoltage(bpmclock.getcv() * 0.5); outputs[OUTPUT_X2].setVoltage(bpmclock.getcv() * 2.0); bpm_display = bpmclock.getbpm(); bpmclock.step(args.sampleTime); outputs[OUTPUT_CLK].setVoltage(bpmclock.track(1) * 10.0); outputs[OUTPUT_CLKD2].setVoltage(bpmclock.track(2) * 10.0); outputs[OUTPUT_CLKX2].setVoltage(bpmclock.track(0) * 10.0); } struct CM4ModuleWidget : ModuleWidget { CM4ModuleWidget(CM4Module *module) { setModule(module); setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/CM-4.svg"))); //addChild(createWidget<ScrewSilver>(Vec(30, 0))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 16, 0))); addChild(createWidget<ScrewSilver>(Vec(5, 365))); // addChild(createWidget<ScrewSilver>(Vec(box.size.x - 60, 365))); //UNIQUE ELEMENTS addParam(createParam<CM_Knob_huge_red_os>(Vec(3.6 , 56.0), module, CM4Module::PARAM_BPM)); addParam(createParam<CM_Switch_small_3>(Vec(7.0, 43.0), module, CM4Module::PARAM_SNAP)); addInput(createInput<CM_Input_ext>(Vec(0.0 , 126.3), module, CM4Module::INPUT_EXT)); addInput(createInput<CM_Input_bpm>(Vec(7.0 , 169.1), module, CM4Module::INPUT_BPM)); addOutput(createOutput<CM_Output_bpm>(Vec(44.4 , 126.3), module, CM4Module::OUTPUT_BPM1)); addOutput(createOutput<CM_Output_bpm>(Vec(44.4 , 169.1), module, CM4Module::OUTPUT_BPM2)); addOutput(createOutput<CM_Output_bpm>(Vec(7.0 , 212.0), module, CM4Module::OUTPUT_D2)); addOutput(createOutput<CM_Output_bpm>(Vec(44.4 , 212.0), module, CM4Module::OUTPUT_X2)); addOutput(createOutput<CM_Output_def>(Vec(26.1 , 293.9), module, CM4Module::OUTPUT_CLK)); addOutput(createOutput<CM_Output_def>(Vec(3.5 , 326.5), module, CM4Module::OUTPUT_CLKD2)); addOutput(createOutput<CM_Output_def>(Vec(48.1 , 326.5), module, CM4Module::OUTPUT_CLKX2)); addInput(createInput<CM_Input_small>(Vec(6.2 , 251.8), module, CM4Module::INPUT_RST)); addParam(createParam<CM_Button_small_red>(Vec(29.4 , 251.8), module, CM4Module::PARAM_RST)); addOutput(createOutput<CM_Output_small>(Vec(52.4 , 251.8), module, CM4Module::OUTPUT_RST)); if (module) { //LCD display NumDisplayWidget *display = new NumDisplayWidget(); display->box.pos = Vec(7.0, 21.0); display->box.size = Vec(61.1, 20.4); display->value = &module->bpm_display; addChild(display); } } }; // Specify the Module and ModuleWidget subclass, human-readable // author name for categorization per pluginInstance, module slug (should never // change), human-readable module name, and any number of tags // (found in `include/tags.hpp`) separated by commas. Model *modelCM4Module = createModel<CM4Module, CM4ModuleWidget>("CatroModulo_CM-4");
34.696552
124
0.709402
CardinalModules
db1e3ee29d3997579632ac9aad298dc405572803
99
cpp
C++
Core/GameManagers/ISimulationManager.cpp
gaspardpetit/INF740-GameEngine
075b6563204fb3d1cf7531599f30dd296c2c9239
[ "Apache-2.0" ]
null
null
null
Core/GameManagers/ISimulationManager.cpp
gaspardpetit/INF740-GameEngine
075b6563204fb3d1cf7531599f30dd296c2c9239
[ "Apache-2.0" ]
null
null
null
Core/GameManagers/ISimulationManager.cpp
gaspardpetit/INF740-GameEngine
075b6563204fb3d1cf7531599f30dd296c2c9239
[ "Apache-2.0" ]
1
2015-09-25T22:24:16.000Z
2015-09-25T22:24:16.000Z
#include "Precompiled.h" #include "ISimulationManager.h" namespace engine { } // namespace engine
14.142857
31
0.757576
gaspardpetit
db20a571e78c0be65bbd6a377a1b802a7e89ce98
922
cc
C++
test/client_bind_port_client.cc
wyhuo123/lib
be802f060a418e28d95d3a6d3b8b2812565e2123
[ "MIT" ]
null
null
null
test/client_bind_port_client.cc
wyhuo123/lib
be802f060a418e28d95d3a6d3b8b2812565e2123
[ "MIT" ]
null
null
null
test/client_bind_port_client.cc
wyhuo123/lib
be802f060a418e28d95d3a6d3b8b2812565e2123
[ "MIT" ]
null
null
null
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <linux/version.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <map> #include <arpa/inet.h> int main() { struct sockaddr_in saddr; memset(&saddr, 0, sizeof(struct sockaddr_in)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = inet_addr("127.0.0.1"); saddr.sin_port = htons(5546); int listenfd = 0; if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) > 0 && bind(listenfd, (struct sockaddr*)&saddr, sizeof(struct sockaddr_in)) == 0 && listen(listenfd, 8) == 0) { struct sockaddr_in rmt_addr; socklen_t len = sizeof(rmt_addr); int rmtfd = accept(listenfd, (struct sockaddr*)&rmt_addr, &len); if (rmtfd == -1) { // TODO return -1; } char buf[1024]; while (recv(rmtfd, buf, 1024, 0) > 0) { printf("%s\n", buf); } } return 0; }
21.44186
68
0.612798
wyhuo123
db212c534cad3a7617ae334681342df388e53a46
11,947
cpp
C++
src/dollar.cpp
natemc/qiss
5cbe3250b4879db6c444a3baec9b603f32f10ca5
[ "MIT" ]
1
2015-11-03T01:57:04.000Z
2015-11-03T01:57:04.000Z
src/dollar.cpp
natemc/qiss
5cbe3250b4879db6c444a3baec9b603f32f10ca5
[ "MIT" ]
null
null
null
src/dollar.cpp
natemc/qiss
5cbe3250b4879db6c444a3baec9b603f32f10ca5
[ "MIT" ]
1
2015-11-01T08:01:39.000Z
2015-11-01T08:01:39.000Z
#include <dollar.h> #include <algorithm> #include <cmath> #include <cstdio> #include <each.h> #include <flip.h> #include <o.h> #include <prim_parse.h> #include <sym.h> namespace { template <class X> using OT = ObjectTraits<X>; S c2s(C x) { const char s[] = { C::rep(x), '\0' }; return sym(s); } O cannot_cast(const char* to, O y) { L<C> s; s << "'type: cannot convert " << std::move(y) << " to " << to; throw lc2ex(s); } template <class TO, class FROM> L<TO> cast_vec(L<FROM> y) { L<TO> r(y.size()); std::transform(y.begin(), y.end(), r.begin(), [](FROM x){ return TO(typename TO::rep(typename FROM::rep(x))); }); return r; } template <class Derived, class Result> struct Caster { const Derived& This() const { return *static_cast<const Derived*>(this); } // TODO don't be so permissive? template <class Z> Result operator()(Z x) const { return Result(typename Result::rep(typename Z::rep(x))); } template <class Z> O operator()(L<Z> x) const { return each(This(), std::move(x)); } O operator()(UKV x) const { auto [k, v] = std::move(x).kv(); return UKV(std::move(k), This()(std::move(v))); } O operator()(L<O> x) const { if (!std::all_of(x.begin(), x.end(), [](const O& o){ return o.is_atom(); })) return each(This(), x); L<Result> r(x.size()); for (index_t i = 0; i < x.size(); ++i) { O& e = x[i]; switch (int(e.type())) { #define CASE(X) case -OT<X>::typei(): r[i] = This()(e.atom<X>()) CASE(B); CASE(C); CASE(D); CASE(F); CASE(I); CASE(J); CASE(S); CASE(T); CASE(X); default : throw Exception("nyi $ (cast)"); #undef CASE } } return O(std::move(r)); } O operator()(O x) const { #define CS(X) case OT<X>::typei() : return This()(L<X>(std::move(x))); \ case -OT<X>::typei(): return O(This()(x.atom<X>())) switch (int(x.type())) { CS(B); CS(C); CS(D); CS(F); CS(H); CS(I); CS(J); CS(S); CS(T); CS(X); case OT<O>::typei() : return each(This(), L<O>(std::move(x))); case '!': return This()(UKV(std::move(x))); case '+': return +This()(+std::move(x)); default : throw Exception("type ($ cast)"); } #undef CS } }; const struct CastToBool: Caster<CastToBool, B> { using Caster<CastToBool, B>::operator(); B operator()(C x) const { return B(B::rep(C::rep(x) != 0)); } B operator()(F x) const { return B(B::rep(F::rep(x) != 0)); } B operator()(J x) const { return B(B::rep(J::rep(x) != 0)); } B operator()(S x) const { return B(B::rep(S::rep(x) != 0)); } B operator()(X x) const { return B(B::rep(X::rep(x) != 0)); } template <class Z> B operator()(Z ) const { throw Exception("type (`bool$)"); } } cast_to_bool; const struct CastToChar: Caster<CastToChar, C> { using Caster<CastToChar, C>::operator(); C operator()(S x) const { if (x != S(0) && c_str(x)[1] == '\0') return C(c_str(x)[0]); throw Exception("type (can't cast sym to char)"); } } cast_to_char; const struct CastToDate: Caster<CastToDate, D> { using Caster<CastToDate, D>::operator(); } cast_to_date; const struct CastToFloat: Caster<CastToFloat, F> { using Caster<CastToFloat, F>::operator(); } cast_to_float; const struct CastToInt: Caster<CastToInt, I> { using Caster<CastToInt, I>::operator(); I operator()(B x) const { return I(B::rep(x)); } I operator()(F x) const { return I(I::rep(round(F::rep(x)))); } I operator()(J x) const { return I(I::rep(J::rep(x))); } I operator()(S ) const { throw Exception("type (can't cast sym to int)"); } } cast_to_int; const struct CastToLong: Caster<CastToLong, J> { using Caster<CastToLong, J>::operator(); J operator()(B x) const { return J(B::rep(x)); } J operator()(F x) const { return J(J::rep(round(F::rep(x)))); } J operator()(I x) const { return J(I::rep(x)); } J operator()(S ) const { throw Exception("type (can't cast sym to long)"); } } cast_to_long; const struct CastToSym: Caster<CastToSym, S> { using Caster<CastToSym, S>::operator(); S operator()(C x) const { return c2s(x); } O operator()(L<C> x) const { return O(parse_sym(std::move(x)).second); } template <class Z> S operator()(Z ) const { throw Exception("type (`$)"); } } cast_to_sym; const struct CastToByte: Caster<CastToByte, X> { using Caster<CastToByte, X>::operator(); } cast_to_byte; O cast(S to, O y) { const char* const s = c_str(to); if (!strcmp(s, "bool" )) return cast_to_bool (std::move(y)); if (!strcmp(s, "char" )) return cast_to_char (std::move(y)); if (!strcmp(s, "date" )) return cast_to_date (std::move(y)); if (!strcmp(s, "float")) return cast_to_float(std::move(y)); if (!strcmp(s, "int" )) return cast_to_int (std::move(y)); if (!strcmp(s, "long" )) return cast_to_long (std::move(y)); if (!strcmp(s, "" )) return cast_to_sym (std::move(y)); if (!strcmp(s, "byte" )) return cast_to_byte (std::move(y)); throw Exception("nyi: $"); } O cast(C to, O y) { switch (C::rep(to)) { case 'b': return cast_to_bool (std::move(y)); case 'c': return cast_to_char (std::move(y)); case 'f': return cast_to_float(std::move(y)); case 'j': return cast_to_long (std::move(y)); case 's': return cast_to_sym (std::move(y)); case 'x': return cast_to_byte (std::move(y)); default : throw Exception("nyi: $"); } } O cannot_parse(const char* to, const O y) { L<C> s; s << "'type: cannot parse " << y << " as " << to; throw lc2ex(s); } O parse(C to, O y); constexpr char digits[] = "0123456789abcdef"; bool all_digits(const C* first, const C* last) { while (first != last && isdigit(C::rep(*first))) ++first; return first == last; } J::rep from_digits(const C* first, const C* last) { J::rep r = 0; for (; first != last; ++first) r = r * 10 + C::rep(*first) - '0'; return r; } X::rep parse_digit(C c) { return X::rep(std::find(digits, std::end(digits), tolower(C::rep(c))) - digits); } bool parse_j(J::rep* j, const C* first, const C* last) { // TODO handle infinities, na assert(first != last); const C* p = first + (*first == C('-')); J::rep r = 0; J::rep prev = 0; for (; p != last && prev <= r; ++p) { if (!isdigit(C::rep(*p))) return false; prev = r; r = r * 10 + C::rep(*p) - '0'; } if (r < prev) return false; *j = *first != C('-')? r : -r; return true; } template <class P> struct Parser { O operator()(L<O> y) const { const auto isC = [](const O& o){ return o.type() == OT<C>::typet(); }; if (std::all_of(y.begin(), y.end(), isC)) { using Z = decltype(This()(C(' '))); L<Z> r(y.size()); std::transform(y.begin(), y.end(), r.begin(), [this](O x){ return Z(This()(L<C>(x))); }); return O(std::move(r)); } else { L<O> r; r.reserve(y.size()); std::transform(y.begin(), y.end(), std::back_inserter(r), *this); return O(std::move(r)); } } O operator()(O y) const { using Z = decltype(This()(C(' '))); switch (int(y.type())) { case -OT<C>::typei(): return O(This()(y.atom<C>())); case OT<C>::typei() : return O(This()(L<C>(std::move(y)))); case OT<O>::typei() : return (*this)(L<O>(std::move(y))); default : return cannot_parse(OT<Z>::name(), y); } } const P& This() const { return *static_cast<const P*>(this); } }; const struct BoolParser: Parser<BoolParser> { using Parser<BoolParser>::operator(); B operator()(C x) const { return (*this)(L<C>{x}); } B operator()(L<C> x) const { return parse_bool(std::move(x)).second; } } bool_parser; const struct ByteParser: Parser<ByteParser> { using Parser<ByteParser>::operator(); X operator()(C x) const { return (*this)(L<C>{x}); } X operator()(L<C> x) const { return parse_byte(std::move(x)).second; } } byte_parser; const struct CharParser: Parser<CharParser> { using Parser<CharParser>::operator(); C operator()(C x) const { return x; } C operator()(L<C> x) const { return parse_char(std::move(x)).second; } } char_parser; const struct DateParser: Parser<DateParser> { using Parser<DateParser>::operator(); D operator()(C ) const { return ND; } D operator()(L<C> x) const { return parse_date(std::move(x)).second; } } date_parser; const struct FloatParser: Parser<FloatParser> { using Parser<FloatParser>::operator(); F operator()(C ) const { return NF; } F operator()(L<C> x) const { return parse_float(std::move(x)).second; } } float_parser; const struct IntParser: Parser<IntParser> { using Parser<IntParser>::operator(); I operator()(C ) const { return NI; } I operator()(L<C> x) const { return parse_int(std::move(x)).second; } } int_parser; const struct LongParser: Parser<LongParser> { using Parser<LongParser>::operator(); J operator()(C ) const { return NJ; } J operator()(L<C> x) const { return parse_long(std::move(x)).second; } } long_parser; const struct SymParser: Parser<SymParser> { using Parser<SymParser>::operator(); S operator()(C x) const { return c2s(x); } S operator()(L<C> x) const { return parse_sym(std::move(x)).second; } } sym_parser; const struct TimeParser: Parser<TimeParser> { using Parser<TimeParser>::operator(); T operator()(C ) const { return NT; } T operator()(L<C> x) const { return parse_time(std::move(x)).second; } } time_parser; O parse(C to, O y) { switch (C::rep(to)) { case 'B': return bool_parser (std::move(y)); case 'C': return char_parser (std::move(y)); case 'D': return date_parser (std::move(y)); case 'F': return float_parser(std::move(y)); case 'I': return int_parser (std::move(y)); case 'J': return long_parser (std::move(y)); case 'S': return sym_parser (std::move(y)); case 'T': return time_parser (std::move(y)); case 'X': return byte_parser (std::move(y)); case '*': return y; default : throw Exception("nyi: $"); } } } // unnamed O dollar(O x, O y) { switch (int(x.type())) { case -OT<C>::typei(): { C cx(x.atom<C>()); if (C('a') <= cx && cx <= C('z')) return cast (cx, y); if (C('A') <= cx && cx <= C('Z')) return parse(cx, y); throw Exception("domain ($)"); } case OT<C>::typei(): { if (y.type() != OT<O>::typei()) throw Exception("'type ($)"); L<C> cx(std::move(x)); L<O> oy(std::move(y)); if (oy.size() < cx.size()) throw Exception("'length ($)"); return each(parse, std::move(cx), std::move(oy)); } case -OT<S>::typei(): return cast(x.atom<S>(), std::move(y)); default : throw Exception("nyi: $"); } }
37.687697
88
0.514271
natemc
db22a25e4b1c9a192e4b0ed79bcb061cdfef095c
4,842
cpp
C++
src/gl9_scene/player.cpp
ImMuffin/ppgso_koricansky_ambrus
156c136c54320c85576216e020e3124e96060d20
[ "MIT" ]
null
null
null
src/gl9_scene/player.cpp
ImMuffin/ppgso_koricansky_ambrus
156c136c54320c85576216e020e3124e96060d20
[ "MIT" ]
null
null
null
src/gl9_scene/player.cpp
ImMuffin/ppgso_koricansky_ambrus
156c136c54320c85576216e020e3124e96060d20
[ "MIT" ]
null
null
null
#include "player.h" #include "scene.h" #include <glm/gtx/euler_angles.hpp> #include <shaders/diffuse_vert_glsl.h> #include <shaders/diffuse_frag_glsl.h> #include <shaders/convolution_frag_glsl.h> #include <shaders/convolution_vert_glsl.h> #include <shaders/water_vert_glsl.h> #include <shaders/water_frag_glsl.h> #include <iostream> #include <fstream> // shared resources std::unique_ptr<ppgso::Mesh> Player::mesh; std::unique_ptr<ppgso::Texture> Player::texture; std::unique_ptr<ppgso::Shader> Player::shader; Player::Player() { // Scale the default model //scale *= 1; // Initialize static resources if needed if (!shader) shader = std::make_unique<ppgso::Shader>(water_vert_glsl, water_frag_glsl); if (!texture) texture = std::make_unique<ppgso::Texture>(ppgso::image::loadBMP("fish.bmp")); if (!mesh) mesh = std::make_unique<ppgso::Mesh>("fish.obj"); } bool Player::update(Scene &scene, float dt) { // calculate forward forward.x = sin(rotation.z)*sin(rotation.x); forward.y = cos(rotation.x); forward.z = sin(rotation.x)*cos(rotation.z); // Keyboard controls if(scene.keyboard[GLFW_KEY_LEFT]) { rotation.z += ppgso::PI/2.0f * dt; } else if(scene.keyboard[GLFW_KEY_RIGHT]) { rotation.z -= ppgso::PI/2.0f * dt; } speed.x = -(fabs(forward.x) * dt); speed.y = -(fabs(forward.y) * dt); speed.z = -(fabs(forward.z) * dt); if(scene.keyboard[GLFW_KEY_UP]) { position -= forward * dt;; } else if(scene.keyboard[GLFW_KEY_DOWN]) { position += forward * dt; } if(scene.keyboard[GLFW_KEY_PAGE_UP]) { rotation.x += ppgso::PI/2.0f * dt; } else if (scene.keyboard[GLFW_KEY_PAGE_DOWN]) { rotation.x -= ppgso::PI/2.0f * dt; } if (scene.keyboard[GLFW_KEY_B] && record == false) { if (!f.is_open()) f.open("../data/matrix.txt"); keyframeTime = 0; record = true; } if (scene.keyboard[GLFW_KEY_N] && record == true) { if (record) { record = false; f.close(); } } if ((scene.keyboard[GLFW_KEY_M]) && (playback == false)) { if (!p.is_open()) p.open("../data/matrix.txt"); keyframeTime = (((int) glfwGetTime()) * 2) + (( (int) (glfwGetTime() * 10)) % 10) / 5; playbackMovement(p); firstModel = modelMatrix; playbackMovement(p); secondModel = modelMatrix; modelMatrix = firstModel; playback = true; } if ((playback == false) && (playable == false)) { if (!p.is_open()) p.open("../data/friend.txt"); keyframeTime = (((int) glfwGetTime()) * 2) + (( (int) (glfwGetTime() * 10)) % 10) / 5; playbackMovement(p); firstModel = modelMatrix; playbackMovement(p); secondModel = modelMatrix; modelMatrix = firstModel; playback = true; } if (playback){ int halfSeconds = (((int) glfwGetTime()) * 2) + (( (int) (glfwGetTime() * 10)) % 10) / 5; if(halfSeconds > keyframeTime) { keyframeTime = halfSeconds; firstModel = secondModel; if (!playbackMovement(p)) { playback = false; p.close(); } secondModel = modelMatrix; modelMatrix = firstModel; } else { modelMatrix = firstModel + (secondModel - firstModel) * (( (float) ( (int) (glfwGetTime() * 100) % 50) * 2) / 100); } } else { generateModelMatrix(); } if (record) { int halfSeconds = (((int) glfwGetTime()) * 2) + (( (int) (glfwGetTime() * 10)) % 10) / 5; if(halfSeconds > keyframeTime) { keyframeTime = halfSeconds; recordMovement(f); } } if ((playback == false) && (playable == false)) { if (!p.is_open()) p.open("../data/friend.txt"); keyframeTime = (((int) glfwGetTime()) * 2) + (( (int) (glfwGetTime() * 10)) % 10) / 5; playbackMovement(p); firstModel = modelMatrix; playbackMovement(p); secondModel = modelMatrix; modelMatrix = firstModel; playback = true; } if (scene.keyboard[GLFW_KEY_U]) { cameraFocus = true; } if (scene.keyboard[GLFW_KEY_J]) { cameraFocus = false; } return true; } void Player::render(Scene &scene) { shader->use(); // Set up light shader->setUniform("LightDirection", scene.lightDirection); shader->setUniform("LightColor", scene.lightColor); // use camera shader->setUniform("ProjectionMatrix", scene.camera->projectionMatrix); shader->setUniform("ViewMatrix", scene.camera->viewMatrix); // render mesh shader->setUniform("ModelMatrix", modelMatrix); shader->setUniform("Texture", *texture); // shader->setUniform("Transparency",1.0f); shader->setUniform("TimeOffset", (glfwGetTime() * 2*3.14159 * .75)); //vodna animacia glDisable(GL_CULL_FACE); //ryba nemala plutvy mesh->render(); glEnable(GL_CULL_FACE); }
26.315217
124
0.610078
ImMuffin
db22e7e4ae821fac46e27d52278ba560b0d050d3
2,799
cpp
C++
Samples/Windows/View/ComboBox.cpp
Topsens/3DVision
a694cf36df3883a5e2d55173e02d865972b8dee2
[ "Apache-2.0" ]
2
2020-11-12T07:47:06.000Z
2020-11-12T11:49:07.000Z
Samples/Windows/View/ComboBox.cpp
Topsens/3DVision
a694cf36df3883a5e2d55173e02d865972b8dee2
[ "Apache-2.0" ]
null
null
null
Samples/Windows/View/ComboBox.cpp
Topsens/3DVision
a694cf36df3883a5e2d55173e02d865972b8dee2
[ "Apache-2.0" ]
null
null
null
#include "ComboBox.h" #include <CommCtrl.h> using namespace std; ComboBox ComboBox::Create(HWND parent, UINT id, DWORD type, HINSTANCE instance) { DialogItem di; if (parent) { DWORD style = WS_CHILD | WS_TABSTOP | WS_VSCROLL; if (ComboBox::Simple != type) { style |= WS_OVERLAPPED; } auto hwnd = CreateWindowExW(0, WC_COMBOBOXW, nullptr, type | style, 0, 0, 0, 0, parent, (HMENU)id, instance, nullptr); if (hwnd) { di = DialogItem(parent, hwnd, id); } } return (ComboBox&)di; } int ComboBox::Add(const wchar_t* item) { return (int)this->Send(CB_ADDSTRING, 0, (LPARAM)item); } int ComboBox::Add(const wstring& item) { return this->Add(item.c_str()); } int ComboBox::Insert(const wchar_t* item, int index) { return (int)this->Send(CB_INSERTSTRING, (WPARAM)index, (LPARAM)item); } int ComboBox::Insert(const wstring& item, int index) { return this->Insert(item.c_str(), index); } int ComboBox::Remove(int index) { return (int)this->Send(CB_DELETESTRING, (WPARAM)index); } int ComboBox::Count() const { return (int)this->Send(CB_GETCOUNT); } void ComboBox::Clear() { this->Send(CB_RESETCONTENT); } int ComboBox::FindExact(const wchar_t* item, int first) const { return (int)this->Send(CB_FINDSTRINGEXACT, (WPARAM)(first - 1), (LPARAM)item); } int ComboBox::FindExact(const wstring& item, int first) const { return this->FindExact(item.c_str(), first); } int ComboBox::FindBeginWith(const wchar_t* item, int first) const { return (int)this->Send(CB_FINDSTRING, (WPARAM)(first - 1), (LPARAM)item); } int ComboBox::FindBeginWith(const wstring& item, int first) const { return this->FindBeginWith(item.c_str(), first); } int ComboBox::TextLength(int index) const { return (int)this->Send(CB_GETLBTEXTLEN, (WPARAM)index); } bool ComboBox::GetText(int index, wstring& text) const { text.clear(); auto cnt = this->TextLength(index); if (CB_ERR == cnt) { return false; } text.resize(cnt + 1); if (CB_ERR == this->Send(CB_GETLBTEXT, (WPARAM)index, (LPARAM)&text[0])) { text.clear(); return false; } text.resize(cnt); return true; } int ComboBox::Selection() const { return (int)this->Send(CB_GETCURSEL); } bool ComboBox::Select(int index) const { if (index < 0 && index >= this->Count()) { return false; } return CB_ERR != this->Send(CB_SETCURSEL, (WPARAM)index); } void ComboBox::ClearSelection() const { this->Send(CB_SETCURSEL, (WPARAM)-1); } wstring ComboBox::Text() const { wstring text; auto index = this->Selection(); if (index >= 0) { this->GetText(index, text); } return text; }
19.851064
126
0.630225
Topsens
db2a7e98de7a3865cc822733aabc761ba4ba1313
622
cpp
C++
src/libs/html/examples/file_html.cpp
rnascunha/agro_daemon
061e9c3ad16b6cebed64a9554dff97481e28f26d
[ "MIT" ]
null
null
null
src/libs/html/examples/file_html.cpp
rnascunha/agro_daemon
061e9c3ad16b6cebed64a9554dff97481e28f26d
[ "MIT" ]
null
null
null
src/libs/html/examples/file_html.cpp
rnascunha/agro_daemon
061e9c3ad16b6cebed64a9554dff97481e28f26d
[ "MIT" ]
1
2022-01-13T19:06:32.000Z
2022-01-13T19:06:32.000Z
#include "html/fwriter.hpp" #include <iostream> #define FILE_NAME "file2.html" int main() { std::cout << "HTML File Test\n"; HTML::fwriter os(FILE_NAME); if(!os.is_open()) { std::cerr << "Error opening file\n"; return 1; } std::cout << "Opened file\n"; std::cout << "Writing to file...\n"; os.init() .hrow("col1", std::string{"col2"}, "col3") .column(1) .column(2.3) .column('a') .nl() .row(1, 2, 2.3) .row(5, 7, 9) .column("t\"es,te") .column("teste2") .column(HTML::io::break_line, 1, "teste3", HTML::io::break_line); std::cout << "Closing file...\n"; os.close(); return 0; }
15.948718
67
0.57717
rnascunha
db2b347db21242ae193d2383270e721ca82c6d85
2,388
cpp
C++
Engine/source/platformWin32/winProcessControl.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
2,113
2015-01-01T11:23:01.000Z
2022-03-28T04:51:46.000Z
Engine/source/platformWin32/winProcessControl.cpp
Ashry00/Torque3D
33e3e41c8b7eb41c743a589558bc21302207ef97
[ "MIT" ]
948
2015-01-02T01:50:00.000Z
2022-02-27T05:56:40.000Z
Engine/source/platformWin32/winProcessControl.cpp
Ashry00/Torque3D
33e3e41c8b7eb41c743a589558bc21302207ef97
[ "MIT" ]
944
2015-01-01T09:33:53.000Z
2022-03-15T22:23:03.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "platformWin32/platformWin32.h" #include "core/strings/stringFunctions.h" #include "core/util/journal/process.h" void Platform::postQuitMessage(const S32 in_quitVal) { if (!Platform::getWebDeployment()) Process::requestShutdown(); } void Platform::debugBreak() { DebugBreak(); } void Platform::forceShutdown(S32 returnValue) { // Don't do an ExitProcess here or you'll wreak havoc in a multithreaded // environment. exit( returnValue ); } void Platform::outputDebugString( const char *string, ... ) { // Expand string. char buffer[ 2048 ]; va_list args; va_start( args, string ); dVsprintf( buffer, sizeof( buffer ), string, args ); va_end( args ); // Append a newline to buffer. This is better than calling OutputDebugStringA // twice as in a multi-threaded environment, some other thread may output some // stuff in between the two calls. U32 length = strlen( buffer ); if( length == ( sizeof( buffer ) - 1 ) ) length --; buffer[ length ] = '\n'; buffer[ length + 1 ] = '\0'; OutputDebugStringA( buffer ); }
33.166667
81
0.667085
vbillet
db3114cf65972f68e1f4b03e480b1756a79bb763
13,657
cpp
C++
source/Vulkan/StreamBuffer.cpp
Wunkolo/vkblam
764ae91396716e54b0d2667f31b114915a2057e9
[ "MIT" ]
6
2022-01-04T23:01:27.000Z
2022-01-15T20:39:50.000Z
source/Vulkan/StreamBuffer.cpp
Wunkolo/vkblam
764ae91396716e54b0d2667f31b114915a2057e9
[ "MIT" ]
null
null
null
source/Vulkan/StreamBuffer.cpp
Wunkolo/vkblam
764ae91396716e54b0d2667f31b114915a2057e9
[ "MIT" ]
null
null
null
#include <Vulkan/StreamBuffer.hpp> #include "Common/Alignment.hpp" #include "Common/Format.hpp" #include <Vulkan/Debug.hpp> #include <Vulkan/Memory.hpp> #include <vulkan/vulkan_enums.hpp> namespace Vulkan { StreamBuffer::StreamBuffer( vk::Device Device, vk::PhysicalDevice PhysicalDevice, vk::Queue TransferQueue, std::uint8_t TransferQueueFamilyIndex, vk::DeviceSize BufferSize) : Device(Device), PhysicalDevice(PhysicalDevice), TransferQueue(TransferQueue), TransferQueueFamilyIndex(TransferQueueFamilyIndex), BufferSize(BufferSize), FlushTick(0), RingOffset(0) { //// Create Semaphore { vk::StructureChain<vk::SemaphoreCreateInfo, vk::SemaphoreTypeCreateInfo> FlushSemaphoreInfoChain = {}; auto& FlushSemaphoreInfo = FlushSemaphoreInfoChain.get<vk::SemaphoreCreateInfo>(); FlushSemaphoreInfo.flags = {}; auto& FlushSemaphoreTypeInfo = FlushSemaphoreInfoChain.get<vk::SemaphoreTypeCreateInfo>(); FlushSemaphoreTypeInfo.initialValue = 0; FlushSemaphoreTypeInfo.semaphoreType = vk::SemaphoreType::eTimeline; if( auto CreateResult = Device.createSemaphoreUnique(FlushSemaphoreInfoChain.get()); CreateResult.result == vk::Result::eSuccess ) { FlushSemaphore = std::move(CreateResult.value); } else { std::fprintf( stderr, "Error creating vertex buffer: %s\n", vk::to_string(CreateResult.result).c_str()); /// ??? should we exit the program } Vulkan::SetObjectName( Device, FlushSemaphore.get(), "Staging Ring Buffer Semaphore"); } //// Create buffer { vk::BufferCreateInfo RingBufferInfo; RingBufferInfo.size = BufferSize; RingBufferInfo.usage = vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst; if( auto CreateResult = Device.createBufferUnique(RingBufferInfo); CreateResult.result == vk::Result::eSuccess ) { RingBuffer = std::move(CreateResult.value); } else { std::fprintf( stderr, "Error creating vertex buffer: %s\n", vk::to_string(CreateResult.result).c_str()); /// ??? should we exit the program } Vulkan::SetObjectName( Device, RingBuffer.get(), "Staging Ring Buffer( %s )", Common::FormatByteCount(BufferSize).c_str()); } //// Allocate memory for staging ring buffer { const vk::MemoryRequirements RingBufferMemoryRequirements = Device.getBufferMemoryRequirements(RingBuffer.get()); vk::MemoryAllocateInfo RingBufferAllocInfo = {}; RingBufferAllocInfo.allocationSize = RingBufferMemoryRequirements.size; // Try to get some shared memory std::int32_t RingBufferHeapIndex = Vulkan::FindMemoryTypeIndex( PhysicalDevice, RingBufferMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eDeviceLocal); // If that failed, then just get some host memory if( RingBufferHeapIndex < 0 ) { RingBufferHeapIndex = Vulkan::FindMemoryTypeIndex( PhysicalDevice, RingBufferMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent); } RingBufferAllocInfo.memoryTypeIndex = RingBufferHeapIndex; if( auto AllocResult = Device.allocateMemoryUnique(RingBufferAllocInfo); AllocResult.result == vk::Result::eSuccess ) { RingBufferMemory = std::move(AllocResult.value); } else { std::fprintf( stderr, "Error allocating memory for staging buffer: %s\n", vk::to_string(AllocResult.result).c_str()); /// ??? should we exit the program } Vulkan::SetObjectName( Device, RingBufferMemory.get(), "Staging Ring Buffer Memory( %s )", Common::FormatByteCount(BufferSize).c_str()); if( auto BindResult = Device.bindBufferMemory( RingBuffer.get(), RingBufferMemory.get(), 0); BindResult == vk::Result::eSuccess ) { // Successfully binded memory to buffer } else { std::fprintf( stderr, "Error binding memory to staging ring buffer: %s\n", vk::to_string(BindResult).c_str()); /// ??? should we exit the program } } //// Map the device memory if( auto MapResult = Device.mapMemory(RingBufferMemory.get(), 0, BufferSize); MapResult.result == vk::Result::eSuccess ) { RingMemoryMapped = std::span<std::byte>( reinterpret_cast<std::byte*>(MapResult.value), BufferSize); } else { std::fprintf( stderr, "Error mapping staging ring buffer memory: %s\n", vk::to_string(MapResult.result).c_str()); /// ??? should we exit the program } //// Allocate command pool { vk::CommandPoolCreateInfo CommandPoolInfo; CommandPoolInfo.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer; CommandPoolInfo.queueFamilyIndex = TransferQueueFamilyIndex; if( auto CreateResult = Device.createCommandPoolUnique(CommandPoolInfo); CreateResult.result == vk::Result::eSuccess ) { CommandPool = std::move(CreateResult.value); } else { std::fprintf( stderr, "Error creating staging buffer command pool: %s\n", vk::to_string(CreateResult.result).c_str()); /// ??? should we exit the program } } } StreamBuffer::~StreamBuffer() { Device.unmapMemory(RingBufferMemory.get()); } std::uint64_t StreamBuffer::QueueBufferUpload( const std::span<const std::byte> Data, vk::Buffer Buffer, vk::DeviceSize Offset) { if( Data.empty() ) { return FlushTick; } if( Data.size_bytes() > BufferSize ) { std::fprintf( stderr, "Staging buffer overflow: %zu > %zu \n", Data.size_bytes(), BufferSize); } // Satisfy any alignment requirements here std::uint64_t CurRingOffset = RingOffset; if( (CurRingOffset + Data.size_bytes()) >= BufferSize ) { const std::uint64_t FlushTick = Flush(); // Blocking wait since we need to ensure that the staging buffer is // entirely free todo, attach timestamps to particular regions of the // ring buffer so that we can use parts of the buffer immediately when // it is ready vk::SemaphoreWaitInfo WaitInfo; WaitInfo.semaphoreCount = 1; WaitInfo.pSemaphores = &GetSemaphore(); WaitInfo.pValues = &FlushTick; if( auto WaitResult = Device.waitSemaphores(WaitInfo, ~0ULL); WaitResult != vk::Result::eSuccess ) { std::fprintf(stderr, "Error waiting on Stream buffer semaphore \n"); } // Satisfy any alignment requirements here CurRingOffset = RingOffset; } RingOffset = CurRingOffset + Data.size_bytes(); std::copy( Data.begin(), Data.end(), RingMemoryMapped.subspan(CurRingOffset).begin()); BufferCopies[Buffer].emplace_back( vk::BufferCopy{CurRingOffset, Offset, Data.size_bytes()}); return FlushTick; } std::uint64_t StreamBuffer::QueueImageUpload( const std::span<const std::byte> Data, vk::Image Image, vk::Offset3D Offset, vk::Extent3D Extent, vk::ImageSubresourceLayers SubresourceLayers, vk::ImageLayout DstLayout) { if( Data.empty() ) { return FlushTick; } if( Data.size_bytes() > BufferSize ) { std::fprintf( stderr, "Staging buffer overflow: %zu > %zu \n", Data.size_bytes(), BufferSize); } // Memory offset must at least match the alignment of the image format's // texel size. Here we just force it to handle the upper-bound alignment // as a temporary catch-all std::uint64_t CurRingOffset = Common::AlignUp(RingOffset, 16); if( (CurRingOffset + Data.size_bytes()) >= BufferSize ) { const std::uint64_t FlushTick = Flush(); // Blocking wait since we need to ensure that the staging buffer is // entirely free todo, attach timestamps to particular regions of the // ring buffer so that we can use parts of the buffer immediately when // it is ready vk::SemaphoreWaitInfo WaitInfo; WaitInfo.semaphoreCount = 1; WaitInfo.pSemaphores = &GetSemaphore(); WaitInfo.pValues = &FlushTick; if( Device.waitSemaphores(WaitInfo, ~0ULL) != vk::Result::eSuccess ) { std::fprintf(stderr, "Error waiting on Stream buffer semaphore \n"); } CurRingOffset = Common::AlignUp(RingOffset, 16); } RingOffset = CurRingOffset + Data.size_bytes(); std::copy( Data.begin(), Data.end(), RingMemoryMapped.subspan(CurRingOffset).begin()); ImageCopies[Image].emplace_back(vk::BufferImageCopy{ CurRingOffset, 0, 0, SubresourceLayers, Offset, Extent}); ImagePreBarrier.emplace_back(vk::ImageMemoryBarrier( vk::AccessFlagBits::eMemoryWrite, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, Image, vk::ImageSubresourceRange( SubresourceLayers.aspectMask, SubresourceLayers.mipLevel, 1, SubresourceLayers.baseArrayLayer, SubresourceLayers.layerCount))); ImagePostBarrier.emplace_back(vk::ImageMemoryBarrier( vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eMemoryRead, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, Image, vk::ImageSubresourceRange( SubresourceLayers.aspectMask, SubresourceLayers.mipLevel, 1, SubresourceLayers.baseArrayLayer, SubresourceLayers.layerCount))); return FlushTick; } std::uint64_t StreamBuffer::Flush() { if( RingOffset == 0 ) { return FlushTick; } // Any further pushes are going to be a part of the next tick const std::uint64_t PrevFlushTick = FlushTick++; vk::CommandBuffer FlushCommandBuffer = {}; // Get where the GPU is at in our submit-timeline std::uint64_t GpuFlushTick = 0; if( auto GetResult = Device.getSemaphoreCounterValue(FlushSemaphore.get()); GetResult.result == vk::Result::eSuccess ) { GpuFlushTick = GetResult.value; } else { std::fprintf( stderr, "Error getting timeline semaphore value: %s\n", vk::to_string(GetResult.result).c_str()); /// ??? should we exit the program } // Find a free command buffer for( std::size_t i = 0; i < CommandBuffers.size(); ++i ) { // This command context is free! recycle it if( CommandBufferTimeStamps[i] < GpuFlushTick ) { CommandBufferTimeStamps[i] = FlushTick; FlushCommandBuffer = CommandBuffers[i].get(); break; } } if( !FlushCommandBuffer ) { // No command buffer was free, we need to push a new one CommandBufferTimeStamps.push_back(FlushTick); vk::CommandBufferAllocateInfo CommandBufferInfo; CommandBufferInfo.commandPool = CommandPool.get(); CommandBufferInfo.commandBufferCount = 1; if( auto AllocateResult = Device.allocateCommandBuffersUnique(CommandBufferInfo); AllocateResult.result == vk::Result::eSuccess ) { FlushCommandBuffer = AllocateResult.value[0].get(); CommandBuffers.emplace_back(std::move(AllocateResult.value[0])); } else { std::fprintf( stderr, "Error allocating command buffer: %s\n", vk::to_string(AllocateResult.result).c_str()); /// ??? should we exit the program } } vk::CommandBufferBeginInfo BeginInfo; BeginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit; if( auto BeginResult = FlushCommandBuffer.begin(vk::CommandBufferBeginInfo{}); BeginResult != vk::Result::eSuccess ) { std::fprintf( stderr, "Error beginning command buffer: %s\n", vk::to_string(BeginResult).c_str()); } { Vulkan::DebugLabelScope DebugCopyScope( FlushCommandBuffer, {1.0, 1.0, 0.0, 1.0}, "Upload Buffers"); for( const auto& [CurBuffer, CurBufferCopies] : BufferCopies ) { FlushCommandBuffer.copyBuffer( RingBuffer.get(), CurBuffer, CurBufferCopies); } } { Vulkan::DebugLabelScope DebugCopyScope( FlushCommandBuffer, {1.0, 1.0, 0.0, 1.0}, "Upload Images"); FlushCommandBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags{}, {}, {}, ImagePreBarrier); for( const auto& [CurImage, CurImageCopies] : ImageCopies ) { FlushCommandBuffer.copyBufferToImage( RingBuffer.get(), CurImage, vk::ImageLayout::eTransferDstOptimal, CurImageCopies); } FlushCommandBuffer.pipelineBarrier( vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags{}, {}, {}, ImagePostBarrier); } if( auto EndResult = FlushCommandBuffer.end(); EndResult != vk::Result::eSuccess ) { std::fprintf( stderr, "Error ending command buffer: %s\n", vk::to_string(EndResult).c_str()); } vk::StructureChain<vk::SubmitInfo, vk::TimelineSemaphoreSubmitInfo> SubmitInfoChain = {}; auto& SubmitInfo = SubmitInfoChain.get<vk::SubmitInfo>(); SubmitInfo.commandBufferCount = 1; SubmitInfo.pCommandBuffers = &FlushCommandBuffer; SubmitInfo.waitSemaphoreCount = 1; SubmitInfo.pWaitSemaphores = &FlushSemaphore.get(); static const vk::PipelineStageFlags WaitStage = vk::PipelineStageFlagBits::eTransfer; SubmitInfo.pWaitDstStageMask = &WaitStage; SubmitInfo.signalSemaphoreCount = 1; SubmitInfo.pSignalSemaphores = &FlushSemaphore.get(); auto& SubmitTimelineInfo = SubmitInfoChain.get<vk::TimelineSemaphoreSubmitInfo>(); SubmitTimelineInfo.waitSemaphoreValueCount = 1; SubmitTimelineInfo.pWaitSemaphoreValues = &PrevFlushTick; SubmitTimelineInfo.signalSemaphoreValueCount = 1; SubmitTimelineInfo.pSignalSemaphoreValues = &FlushTick; if( auto SubmitResult = TransferQueue.submit(SubmitInfoChain.get()); SubmitResult != vk::Result::eSuccess ) { // Error submitting std::fprintf( stderr, "Error submitting streaming buffer flush: %s\n", vk::to_string(SubmitResult).c_str()); } RingOffset = 0; BufferCopies.clear(); ImageCopies.clear(); ImagePreBarrier.clear(); ImagePostBarrier.clear(); return FlushTick; } const vk::Semaphore& StreamBuffer::GetSemaphore() const { return FlushSemaphore.get(); } } // namespace Vulkan
29.884026
77
0.72666
Wunkolo
db327445502d383665e08e52727e5b129eea89c4
1,541
hpp
C++
visen/display_list.hpp
MrTAB/aabGameEngine
dc51c6e443bf087ca10e14e6884e4dfa6caef4a8
[ "MIT" ]
null
null
null
visen/display_list.hpp
MrTAB/aabGameEngine
dc51c6e443bf087ca10e14e6884e4dfa6caef4a8
[ "MIT" ]
null
null
null
visen/display_list.hpp
MrTAB/aabGameEngine
dc51c6e443bf087ca10e14e6884e4dfa6caef4a8
[ "MIT" ]
null
null
null
/** * * display_list.hpp * * A DisplayList can be used to "remember" what is rendered inbetween calls to * open() and close(). It can then be rendered after that point and will render * that which it remembered, but in an optimised fashion. * * Note that Display Lists are depricated in current OpenGL **/ #if !defined(AAB_VISEN_DISPLAY_LIST_CLASS) #define AAB_VISEN_DISPLAY_LIST_CLASS #include"../types/manager.hpp" namespace aab { namespace visen { class DisplayListClass : public aab::types::Manager <DisplayListClass> { public: typedef aab::types::Smart <DisplayListClass>::Ptr Ptr; void open (bool allowExecutionWhileAbsorbing);// std::domain_error, std::invalid_argument, std::logic_error, std::runtime_error void close (); private: unsigned int list; DisplayListClass (DisplayListClass &); // no copy protected: friend class DisplayAbsorber; friend class aab::types::Manager <DisplayListClass>::Deleter; friend Ptr makeDisplayList ();// std::domain_error, std::invalid_argument, std::logic_error, std::runtime_error explicit DisplayListClass ();// std::domain_error, std::invalid_argument, std::logic_error, std::runtime_error virtual ~DisplayListClass ();// throw (); public: void render () const; }; typedef DisplayListClass::Ptr DisplayList; DisplayList makeDisplayList ();// std::domain_error, std::invalid_argument, std::logic_error, std::runtime_error } // visen } // aab #endif // AAB_VISEN_DISPLAY_LIST_CLASS
25.262295
130
0.714471
MrTAB
db33a4a0db93f9032e045979f5380b41ec901ac6
210,028
cpp
C++
HotelSearchApp/Classes/Native/Il2CppCompilerCalculateTypeValues_20Table.cpp
skarian92/hotelSearch
0f6ef494f621452e511b5ee5aca0a50acf1e8fd6
[ "MIT" ]
null
null
null
HotelSearchApp/Classes/Native/Il2CppCompilerCalculateTypeValues_20Table.cpp
skarian92/hotelSearch
0f6ef494f621452e511b5ee5aca0a50acf1e8fd6
[ "MIT" ]
null
null
null
HotelSearchApp/Classes/Native/Il2CppCompilerCalculateTypeValues_20Table.cpp
skarian92/hotelSearch
0f6ef494f621452e511b5ee5aca0a50acf1e8fd6
[ "MIT" ]
null
null
null
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "class-internals.h" #include "codegen/il2cpp-codegen.h" #include "object-internals.h" // System.Byte[] struct ByteU5BU5D_t3397334013; // System.String struct String_t; // System.Char[] struct CharU5BU5D_t1328083999; // System.Void struct Void_t1841601450; // UnityEngine.Vector3[] struct Vector3U5BU5D_t1172311765; // System.UInt64[] struct UInt64U5BU5D_t1668688775; // System.Collections.Generic.List`1<UnityEngine.XR.iOS.UnityARVideoFormat> struct List_1_t4208419204; // UnityEngine.XR.iOS.VideoFormatEnumerator struct VideoFormatEnumerator_t1718260816; // System.Reflection.MethodInfo struct MethodInfo_t; // System.DelegateData struct DelegateData_t1572802995; // System.Single[] struct SingleU5BU5D_t577127397; // UnityEngine.XR.iOS.UnityARDirectionalLightEstimate struct UnityARDirectionalLightEstimate_t1689150542; // UnityEngine.Vector2[] struct Vector2U5BU5D_t686124026; // System.Int32[] struct Int32U5BU5D_t3030399641; // System.Int16[] struct Int16U5BU5D_t3104283263; // System.IAsyncResult struct IAsyncResult_t1999651008; // System.AsyncCallback struct AsyncCallback_t163412349; // UnityEngine.XR.iOS.ARPointCloud struct ARPointCloud_t2004641850; // System.Collections.Generic.Dictionary`2<System.String,System.Single> struct Dictionary_2_t3991289194; // UnityEngine.XR.iOS.ARFaceGeometry struct ARFaceGeometry_t2928150040; // UnityEngine.XR.iOS.ARFaceAnchor/DictionaryVisitorHandler struct DictionaryVisitorHandler_t245332630; #ifndef RUNTIMEOBJECT_H #define RUNTIMEOBJECT_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEOBJECT_H #ifndef VALUETYPE_T3507792607_H #define VALUETYPE_T3507792607_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ValueType struct ValueType_t3507792607 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t3507792607_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t3507792607_marshaled_com { }; #endif // VALUETYPE_T3507792607_H #ifndef SERIALIZABLEARWORLDMAP_T3518979552_H #define SERIALIZABLEARWORLDMAP_T3518979552_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.serializableARWorldMap struct serializableARWorldMap_t3518979552 : public RuntimeObject { public: // System.Byte[] UnityEngine.XR.iOS.serializableARWorldMap::arWorldMapData ByteU5BU5D_t3397334013* ___arWorldMapData_0; public: inline static int32_t get_offset_of_arWorldMapData_0() { return static_cast<int32_t>(offsetof(serializableARWorldMap_t3518979552, ___arWorldMapData_0)); } inline ByteU5BU5D_t3397334013* get_arWorldMapData_0() const { return ___arWorldMapData_0; } inline ByteU5BU5D_t3397334013** get_address_of_arWorldMapData_0() { return &___arWorldMapData_0; } inline void set_arWorldMapData_0(ByteU5BU5D_t3397334013* value) { ___arWorldMapData_0 = value; Il2CppCodeGenWriteBarrier((&___arWorldMapData_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SERIALIZABLEARWORLDMAP_T3518979552_H #ifndef SERIALIZABLEARREFERENCEOBJECT_T284449772_H #define SERIALIZABLEARREFERENCEOBJECT_T284449772_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.serializableARReferenceObject struct serializableARReferenceObject_t284449772 : public RuntimeObject { public: // System.Byte[] UnityEngine.XR.iOS.serializableARReferenceObject::arReferenceObjectData ByteU5BU5D_t3397334013* ___arReferenceObjectData_0; public: inline static int32_t get_offset_of_arReferenceObjectData_0() { return static_cast<int32_t>(offsetof(serializableARReferenceObject_t284449772, ___arReferenceObjectData_0)); } inline ByteU5BU5D_t3397334013* get_arReferenceObjectData_0() const { return ___arReferenceObjectData_0; } inline ByteU5BU5D_t3397334013** get_address_of_arReferenceObjectData_0() { return &___arReferenceObjectData_0; } inline void set_arReferenceObjectData_0(ByteU5BU5D_t3397334013* value) { ___arReferenceObjectData_0 = value; Il2CppCodeGenWriteBarrier((&___arReferenceObjectData_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SERIALIZABLEARREFERENCEOBJECT_T284449772_H #ifndef ARBLENDSHAPELOCATION_T3927368462_H #define ARBLENDSHAPELOCATION_T3927368462_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARBlendShapeLocation struct ARBlendShapeLocation_t3927368462 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARBLENDSHAPELOCATION_T3927368462_H #ifndef ARLIGHTESTIMATE_T3477821059_H #define ARLIGHTESTIMATE_T3477821059_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARLightEstimate struct ARLightEstimate_t3477821059 { public: // System.Single UnityEngine.XR.iOS.ARLightEstimate::ambientIntensity float ___ambientIntensity_0; public: inline static int32_t get_offset_of_ambientIntensity_0() { return static_cast<int32_t>(offsetof(ARLightEstimate_t3477821059, ___ambientIntensity_0)); } inline float get_ambientIntensity_0() const { return ___ambientIntensity_0; } inline float* get_address_of_ambientIntensity_0() { return &___ambientIntensity_0; } inline void set_ambientIntensity_0(float value) { ___ambientIntensity_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARLIGHTESTIMATE_T3477821059_H #ifndef VOID_T1841601450_H #define VOID_T1841601450_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void struct Void_t1841601450 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VOID_T1841601450_H #ifndef ENUM_T2459695545_H #define ENUM_T2459695545_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Enum struct Enum_t2459695545 : public ValueType_t3507792607 { public: public: }; struct Enum_t2459695545_StaticFields { public: // System.Char[] System.Enum::split_char CharU5BU5D_t1328083999* ___split_char_0; public: inline static int32_t get_offset_of_split_char_0() { return static_cast<int32_t>(offsetof(Enum_t2459695545_StaticFields, ___split_char_0)); } inline CharU5BU5D_t1328083999* get_split_char_0() const { return ___split_char_0; } inline CharU5BU5D_t1328083999** get_address_of_split_char_0() { return &___split_char_0; } inline void set_split_char_0(CharU5BU5D_t1328083999* value) { ___split_char_0 = value; Il2CppCodeGenWriteBarrier((&___split_char_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t2459695545_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t2459695545_marshaled_com { }; #endif // ENUM_T2459695545_H #ifndef INTPTR_T_H #define INTPTR_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTPTR_T_H #ifndef ARSIZE_T3911821096_H #define ARSIZE_T3911821096_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARSize struct ARSize_t3911821096 { public: // System.Double UnityEngine.XR.iOS.ARSize::width double ___width_0; // System.Double UnityEngine.XR.iOS.ARSize::height double ___height_1; public: inline static int32_t get_offset_of_width_0() { return static_cast<int32_t>(offsetof(ARSize_t3911821096, ___width_0)); } inline double get_width_0() const { return ___width_0; } inline double* get_address_of_width_0() { return &___width_0; } inline void set_width_0(double value) { ___width_0 = value; } inline static int32_t get_offset_of_height_1() { return static_cast<int32_t>(offsetof(ARSize_t3911821096, ___height_1)); } inline double get_height_1() const { return ___height_1; } inline double* get_address_of_height_1() { return &___height_1; } inline void set_height_1(double value) { ___height_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARSIZE_T3911821096_H #ifndef VECTOR4_T2243707581_H #define VECTOR4_T2243707581_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Vector4 struct Vector4_t2243707581 { public: // System.Single UnityEngine.Vector4::x float ___x_1; // System.Single UnityEngine.Vector4::y float ___y_2; // System.Single UnityEngine.Vector4::z float ___z_3; // System.Single UnityEngine.Vector4::w float ___w_4; public: inline static int32_t get_offset_of_x_1() { return static_cast<int32_t>(offsetof(Vector4_t2243707581, ___x_1)); } inline float get_x_1() const { return ___x_1; } inline float* get_address_of_x_1() { return &___x_1; } inline void set_x_1(float value) { ___x_1 = value; } inline static int32_t get_offset_of_y_2() { return static_cast<int32_t>(offsetof(Vector4_t2243707581, ___y_2)); } inline float get_y_2() const { return ___y_2; } inline float* get_address_of_y_2() { return &___y_2; } inline void set_y_2(float value) { ___y_2 = value; } inline static int32_t get_offset_of_z_3() { return static_cast<int32_t>(offsetof(Vector4_t2243707581, ___z_3)); } inline float get_z_3() const { return ___z_3; } inline float* get_address_of_z_3() { return &___z_3; } inline void set_z_3(float value) { ___z_3 = value; } inline static int32_t get_offset_of_w_4() { return static_cast<int32_t>(offsetof(Vector4_t2243707581, ___w_4)); } inline float get_w_4() const { return ___w_4; } inline float* get_address_of_w_4() { return &___w_4; } inline void set_w_4(float value) { ___w_4 = value; } }; struct Vector4_t2243707581_StaticFields { public: // UnityEngine.Vector4 UnityEngine.Vector4::zeroVector Vector4_t2243707581 ___zeroVector_5; // UnityEngine.Vector4 UnityEngine.Vector4::oneVector Vector4_t2243707581 ___oneVector_6; // UnityEngine.Vector4 UnityEngine.Vector4::positiveInfinityVector Vector4_t2243707581 ___positiveInfinityVector_7; // UnityEngine.Vector4 UnityEngine.Vector4::negativeInfinityVector Vector4_t2243707581 ___negativeInfinityVector_8; public: inline static int32_t get_offset_of_zeroVector_5() { return static_cast<int32_t>(offsetof(Vector4_t2243707581_StaticFields, ___zeroVector_5)); } inline Vector4_t2243707581 get_zeroVector_5() const { return ___zeroVector_5; } inline Vector4_t2243707581 * get_address_of_zeroVector_5() { return &___zeroVector_5; } inline void set_zeroVector_5(Vector4_t2243707581 value) { ___zeroVector_5 = value; } inline static int32_t get_offset_of_oneVector_6() { return static_cast<int32_t>(offsetof(Vector4_t2243707581_StaticFields, ___oneVector_6)); } inline Vector4_t2243707581 get_oneVector_6() const { return ___oneVector_6; } inline Vector4_t2243707581 * get_address_of_oneVector_6() { return &___oneVector_6; } inline void set_oneVector_6(Vector4_t2243707581 value) { ___oneVector_6 = value; } inline static int32_t get_offset_of_positiveInfinityVector_7() { return static_cast<int32_t>(offsetof(Vector4_t2243707581_StaticFields, ___positiveInfinityVector_7)); } inline Vector4_t2243707581 get_positiveInfinityVector_7() const { return ___positiveInfinityVector_7; } inline Vector4_t2243707581 * get_address_of_positiveInfinityVector_7() { return &___positiveInfinityVector_7; } inline void set_positiveInfinityVector_7(Vector4_t2243707581 value) { ___positiveInfinityVector_7 = value; } inline static int32_t get_offset_of_negativeInfinityVector_8() { return static_cast<int32_t>(offsetof(Vector4_t2243707581_StaticFields, ___negativeInfinityVector_8)); } inline Vector4_t2243707581 get_negativeInfinityVector_8() const { return ___negativeInfinityVector_8; } inline Vector4_t2243707581 * get_address_of_negativeInfinityVector_8() { return &___negativeInfinityVector_8; } inline void set_negativeInfinityVector_8(Vector4_t2243707581 value) { ___negativeInfinityVector_8 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VECTOR4_T2243707581_H #ifndef MATRIX4X4_T2933234003_H #define MATRIX4X4_T2933234003_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Matrix4x4 struct Matrix4x4_t2933234003 { public: // System.Single UnityEngine.Matrix4x4::m00 float ___m00_0; // System.Single UnityEngine.Matrix4x4::m10 float ___m10_1; // System.Single UnityEngine.Matrix4x4::m20 float ___m20_2; // System.Single UnityEngine.Matrix4x4::m30 float ___m30_3; // System.Single UnityEngine.Matrix4x4::m01 float ___m01_4; // System.Single UnityEngine.Matrix4x4::m11 float ___m11_5; // System.Single UnityEngine.Matrix4x4::m21 float ___m21_6; // System.Single UnityEngine.Matrix4x4::m31 float ___m31_7; // System.Single UnityEngine.Matrix4x4::m02 float ___m02_8; // System.Single UnityEngine.Matrix4x4::m12 float ___m12_9; // System.Single UnityEngine.Matrix4x4::m22 float ___m22_10; // System.Single UnityEngine.Matrix4x4::m32 float ___m32_11; // System.Single UnityEngine.Matrix4x4::m03 float ___m03_12; // System.Single UnityEngine.Matrix4x4::m13 float ___m13_13; // System.Single UnityEngine.Matrix4x4::m23 float ___m23_14; // System.Single UnityEngine.Matrix4x4::m33 float ___m33_15; public: inline static int32_t get_offset_of_m00_0() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m00_0)); } inline float get_m00_0() const { return ___m00_0; } inline float* get_address_of_m00_0() { return &___m00_0; } inline void set_m00_0(float value) { ___m00_0 = value; } inline static int32_t get_offset_of_m10_1() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m10_1)); } inline float get_m10_1() const { return ___m10_1; } inline float* get_address_of_m10_1() { return &___m10_1; } inline void set_m10_1(float value) { ___m10_1 = value; } inline static int32_t get_offset_of_m20_2() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m20_2)); } inline float get_m20_2() const { return ___m20_2; } inline float* get_address_of_m20_2() { return &___m20_2; } inline void set_m20_2(float value) { ___m20_2 = value; } inline static int32_t get_offset_of_m30_3() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m30_3)); } inline float get_m30_3() const { return ___m30_3; } inline float* get_address_of_m30_3() { return &___m30_3; } inline void set_m30_3(float value) { ___m30_3 = value; } inline static int32_t get_offset_of_m01_4() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m01_4)); } inline float get_m01_4() const { return ___m01_4; } inline float* get_address_of_m01_4() { return &___m01_4; } inline void set_m01_4(float value) { ___m01_4 = value; } inline static int32_t get_offset_of_m11_5() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m11_5)); } inline float get_m11_5() const { return ___m11_5; } inline float* get_address_of_m11_5() { return &___m11_5; } inline void set_m11_5(float value) { ___m11_5 = value; } inline static int32_t get_offset_of_m21_6() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m21_6)); } inline float get_m21_6() const { return ___m21_6; } inline float* get_address_of_m21_6() { return &___m21_6; } inline void set_m21_6(float value) { ___m21_6 = value; } inline static int32_t get_offset_of_m31_7() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m31_7)); } inline float get_m31_7() const { return ___m31_7; } inline float* get_address_of_m31_7() { return &___m31_7; } inline void set_m31_7(float value) { ___m31_7 = value; } inline static int32_t get_offset_of_m02_8() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m02_8)); } inline float get_m02_8() const { return ___m02_8; } inline float* get_address_of_m02_8() { return &___m02_8; } inline void set_m02_8(float value) { ___m02_8 = value; } inline static int32_t get_offset_of_m12_9() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m12_9)); } inline float get_m12_9() const { return ___m12_9; } inline float* get_address_of_m12_9() { return &___m12_9; } inline void set_m12_9(float value) { ___m12_9 = value; } inline static int32_t get_offset_of_m22_10() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m22_10)); } inline float get_m22_10() const { return ___m22_10; } inline float* get_address_of_m22_10() { return &___m22_10; } inline void set_m22_10(float value) { ___m22_10 = value; } inline static int32_t get_offset_of_m32_11() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m32_11)); } inline float get_m32_11() const { return ___m32_11; } inline float* get_address_of_m32_11() { return &___m32_11; } inline void set_m32_11(float value) { ___m32_11 = value; } inline static int32_t get_offset_of_m03_12() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m03_12)); } inline float get_m03_12() const { return ___m03_12; } inline float* get_address_of_m03_12() { return &___m03_12; } inline void set_m03_12(float value) { ___m03_12 = value; } inline static int32_t get_offset_of_m13_13() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m13_13)); } inline float get_m13_13() const { return ___m13_13; } inline float* get_address_of_m13_13() { return &___m13_13; } inline void set_m13_13(float value) { ___m13_13 = value; } inline static int32_t get_offset_of_m23_14() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m23_14)); } inline float get_m23_14() const { return ___m23_14; } inline float* get_address_of_m23_14() { return &___m23_14; } inline void set_m23_14(float value) { ___m23_14 = value; } inline static int32_t get_offset_of_m33_15() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003, ___m33_15)); } inline float get_m33_15() const { return ___m33_15; } inline float* get_address_of_m33_15() { return &___m33_15; } inline void set_m33_15(float value) { ___m33_15 = value; } }; struct Matrix4x4_t2933234003_StaticFields { public: // UnityEngine.Matrix4x4 UnityEngine.Matrix4x4::zeroMatrix Matrix4x4_t2933234003 ___zeroMatrix_16; // UnityEngine.Matrix4x4 UnityEngine.Matrix4x4::identityMatrix Matrix4x4_t2933234003 ___identityMatrix_17; public: inline static int32_t get_offset_of_zeroMatrix_16() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003_StaticFields, ___zeroMatrix_16)); } inline Matrix4x4_t2933234003 get_zeroMatrix_16() const { return ___zeroMatrix_16; } inline Matrix4x4_t2933234003 * get_address_of_zeroMatrix_16() { return &___zeroMatrix_16; } inline void set_zeroMatrix_16(Matrix4x4_t2933234003 value) { ___zeroMatrix_16 = value; } inline static int32_t get_offset_of_identityMatrix_17() { return static_cast<int32_t>(offsetof(Matrix4x4_t2933234003_StaticFields, ___identityMatrix_17)); } inline Matrix4x4_t2933234003 get_identityMatrix_17() const { return ___identityMatrix_17; } inline Matrix4x4_t2933234003 * get_address_of_identityMatrix_17() { return &___identityMatrix_17; } inline void set_identityMatrix_17(Matrix4x4_t2933234003 value) { ___identityMatrix_17 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MATRIX4X4_T2933234003_H #ifndef ARPOINT_T3436811567_H #define ARPOINT_T3436811567_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARPoint struct ARPoint_t3436811567 { public: // System.Double UnityEngine.XR.iOS.ARPoint::x double ___x_0; // System.Double UnityEngine.XR.iOS.ARPoint::y double ___y_1; public: inline static int32_t get_offset_of_x_0() { return static_cast<int32_t>(offsetof(ARPoint_t3436811567, ___x_0)); } inline double get_x_0() const { return ___x_0; } inline double* get_address_of_x_0() { return &___x_0; } inline void set_x_0(double value) { ___x_0 = value; } inline static int32_t get_offset_of_y_1() { return static_cast<int32_t>(offsetof(ARPoint_t3436811567, ___y_1)); } inline double get_y_1() const { return ___y_1; } inline double* get_address_of_y_1() { return &___y_1; } inline void set_y_1(double value) { ___y_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARPOINT_T3436811567_H #ifndef SINGLE_T2076509932_H #define SINGLE_T2076509932_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Single struct Single_t2076509932 { public: // System.Single System.Single::m_value float ___m_value_7; public: inline static int32_t get_offset_of_m_value_7() { return static_cast<int32_t>(offsetof(Single_t2076509932, ___m_value_7)); } inline float get_m_value_7() const { return ___m_value_7; } inline float* get_address_of_m_value_7() { return &___m_value_7; } inline void set_m_value_7(float value) { ___m_value_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SINGLE_T2076509932_H #ifndef VECTOR3_T2243707580_H #define VECTOR3_T2243707580_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Vector3 struct Vector3_t2243707580 { public: // System.Single UnityEngine.Vector3::x float ___x_1; // System.Single UnityEngine.Vector3::y float ___y_2; // System.Single UnityEngine.Vector3::z float ___z_3; public: inline static int32_t get_offset_of_x_1() { return static_cast<int32_t>(offsetof(Vector3_t2243707580, ___x_1)); } inline float get_x_1() const { return ___x_1; } inline float* get_address_of_x_1() { return &___x_1; } inline void set_x_1(float value) { ___x_1 = value; } inline static int32_t get_offset_of_y_2() { return static_cast<int32_t>(offsetof(Vector3_t2243707580, ___y_2)); } inline float get_y_2() const { return ___y_2; } inline float* get_address_of_y_2() { return &___y_2; } inline void set_y_2(float value) { ___y_2 = value; } inline static int32_t get_offset_of_z_3() { return static_cast<int32_t>(offsetof(Vector3_t2243707580, ___z_3)); } inline float get_z_3() const { return ___z_3; } inline float* get_address_of_z_3() { return &___z_3; } inline void set_z_3(float value) { ___z_3 = value; } }; struct Vector3_t2243707580_StaticFields { public: // UnityEngine.Vector3 UnityEngine.Vector3::zeroVector Vector3_t2243707580 ___zeroVector_4; // UnityEngine.Vector3 UnityEngine.Vector3::oneVector Vector3_t2243707580 ___oneVector_5; // UnityEngine.Vector3 UnityEngine.Vector3::upVector Vector3_t2243707580 ___upVector_6; // UnityEngine.Vector3 UnityEngine.Vector3::downVector Vector3_t2243707580 ___downVector_7; // UnityEngine.Vector3 UnityEngine.Vector3::leftVector Vector3_t2243707580 ___leftVector_8; // UnityEngine.Vector3 UnityEngine.Vector3::rightVector Vector3_t2243707580 ___rightVector_9; // UnityEngine.Vector3 UnityEngine.Vector3::forwardVector Vector3_t2243707580 ___forwardVector_10; // UnityEngine.Vector3 UnityEngine.Vector3::backVector Vector3_t2243707580 ___backVector_11; // UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector Vector3_t2243707580 ___positiveInfinityVector_12; // UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector Vector3_t2243707580 ___negativeInfinityVector_13; public: inline static int32_t get_offset_of_zeroVector_4() { return static_cast<int32_t>(offsetof(Vector3_t2243707580_StaticFields, ___zeroVector_4)); } inline Vector3_t2243707580 get_zeroVector_4() const { return ___zeroVector_4; } inline Vector3_t2243707580 * get_address_of_zeroVector_4() { return &___zeroVector_4; } inline void set_zeroVector_4(Vector3_t2243707580 value) { ___zeroVector_4 = value; } inline static int32_t get_offset_of_oneVector_5() { return static_cast<int32_t>(offsetof(Vector3_t2243707580_StaticFields, ___oneVector_5)); } inline Vector3_t2243707580 get_oneVector_5() const { return ___oneVector_5; } inline Vector3_t2243707580 * get_address_of_oneVector_5() { return &___oneVector_5; } inline void set_oneVector_5(Vector3_t2243707580 value) { ___oneVector_5 = value; } inline static int32_t get_offset_of_upVector_6() { return static_cast<int32_t>(offsetof(Vector3_t2243707580_StaticFields, ___upVector_6)); } inline Vector3_t2243707580 get_upVector_6() const { return ___upVector_6; } inline Vector3_t2243707580 * get_address_of_upVector_6() { return &___upVector_6; } inline void set_upVector_6(Vector3_t2243707580 value) { ___upVector_6 = value; } inline static int32_t get_offset_of_downVector_7() { return static_cast<int32_t>(offsetof(Vector3_t2243707580_StaticFields, ___downVector_7)); } inline Vector3_t2243707580 get_downVector_7() const { return ___downVector_7; } inline Vector3_t2243707580 * get_address_of_downVector_7() { return &___downVector_7; } inline void set_downVector_7(Vector3_t2243707580 value) { ___downVector_7 = value; } inline static int32_t get_offset_of_leftVector_8() { return static_cast<int32_t>(offsetof(Vector3_t2243707580_StaticFields, ___leftVector_8)); } inline Vector3_t2243707580 get_leftVector_8() const { return ___leftVector_8; } inline Vector3_t2243707580 * get_address_of_leftVector_8() { return &___leftVector_8; } inline void set_leftVector_8(Vector3_t2243707580 value) { ___leftVector_8 = value; } inline static int32_t get_offset_of_rightVector_9() { return static_cast<int32_t>(offsetof(Vector3_t2243707580_StaticFields, ___rightVector_9)); } inline Vector3_t2243707580 get_rightVector_9() const { return ___rightVector_9; } inline Vector3_t2243707580 * get_address_of_rightVector_9() { return &___rightVector_9; } inline void set_rightVector_9(Vector3_t2243707580 value) { ___rightVector_9 = value; } inline static int32_t get_offset_of_forwardVector_10() { return static_cast<int32_t>(offsetof(Vector3_t2243707580_StaticFields, ___forwardVector_10)); } inline Vector3_t2243707580 get_forwardVector_10() const { return ___forwardVector_10; } inline Vector3_t2243707580 * get_address_of_forwardVector_10() { return &___forwardVector_10; } inline void set_forwardVector_10(Vector3_t2243707580 value) { ___forwardVector_10 = value; } inline static int32_t get_offset_of_backVector_11() { return static_cast<int32_t>(offsetof(Vector3_t2243707580_StaticFields, ___backVector_11)); } inline Vector3_t2243707580 get_backVector_11() const { return ___backVector_11; } inline Vector3_t2243707580 * get_address_of_backVector_11() { return &___backVector_11; } inline void set_backVector_11(Vector3_t2243707580 value) { ___backVector_11 = value; } inline static int32_t get_offset_of_positiveInfinityVector_12() { return static_cast<int32_t>(offsetof(Vector3_t2243707580_StaticFields, ___positiveInfinityVector_12)); } inline Vector3_t2243707580 get_positiveInfinityVector_12() const { return ___positiveInfinityVector_12; } inline Vector3_t2243707580 * get_address_of_positiveInfinityVector_12() { return &___positiveInfinityVector_12; } inline void set_positiveInfinityVector_12(Vector3_t2243707580 value) { ___positiveInfinityVector_12 = value; } inline static int32_t get_offset_of_negativeInfinityVector_13() { return static_cast<int32_t>(offsetof(Vector3_t2243707580_StaticFields, ___negativeInfinityVector_13)); } inline Vector3_t2243707580 get_negativeInfinityVector_13() const { return ___negativeInfinityVector_13; } inline Vector3_t2243707580 * get_address_of_negativeInfinityVector_13() { return &___negativeInfinityVector_13; } inline void set_negativeInfinityVector_13(Vector3_t2243707580 value) { ___negativeInfinityVector_13 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VECTOR3_T2243707580_H #ifndef UNITYARLIGHTESTIMATE_T311267890_H #define UNITYARLIGHTESTIMATE_T311267890_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARLightEstimate struct UnityARLightEstimate_t311267890 { public: // System.Single UnityEngine.XR.iOS.UnityARLightEstimate::ambientIntensity float ___ambientIntensity_0; // System.Single UnityEngine.XR.iOS.UnityARLightEstimate::ambientColorTemperature float ___ambientColorTemperature_1; public: inline static int32_t get_offset_of_ambientIntensity_0() { return static_cast<int32_t>(offsetof(UnityARLightEstimate_t311267890, ___ambientIntensity_0)); } inline float get_ambientIntensity_0() const { return ___ambientIntensity_0; } inline float* get_address_of_ambientIntensity_0() { return &___ambientIntensity_0; } inline void set_ambientIntensity_0(float value) { ___ambientIntensity_0 = value; } inline static int32_t get_offset_of_ambientColorTemperature_1() { return static_cast<int32_t>(offsetof(UnityARLightEstimate_t311267890, ___ambientColorTemperature_1)); } inline float get_ambientColorTemperature_1() const { return ___ambientColorTemperature_1; } inline float* get_address_of_ambientColorTemperature_1() { return &___ambientColorTemperature_1; } inline void set_ambientColorTemperature_1(float value) { ___ambientColorTemperature_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARLIGHTESTIMATE_T311267890_H #ifndef ARRECT_T3555590363_H #define ARRECT_T3555590363_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARRect struct ARRect_t3555590363 { public: // UnityEngine.XR.iOS.ARPoint UnityEngine.XR.iOS.ARRect::origin ARPoint_t3436811567 ___origin_0; // UnityEngine.XR.iOS.ARSize UnityEngine.XR.iOS.ARRect::size ARSize_t3911821096 ___size_1; public: inline static int32_t get_offset_of_origin_0() { return static_cast<int32_t>(offsetof(ARRect_t3555590363, ___origin_0)); } inline ARPoint_t3436811567 get_origin_0() const { return ___origin_0; } inline ARPoint_t3436811567 * get_address_of_origin_0() { return &___origin_0; } inline void set_origin_0(ARPoint_t3436811567 value) { ___origin_0 = value; } inline static int32_t get_offset_of_size_1() { return static_cast<int32_t>(offsetof(ARRect_t3555590363, ___size_1)); } inline ARSize_t3911821096 get_size_1() const { return ___size_1; } inline ARSize_t3911821096 * get_address_of_size_1() { return &___size_1; } inline void set_size_1(ARSize_t3911821096 value) { ___size_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARRECT_T3555590363_H #ifndef ARPOINTCLOUD_T2004641850_H #define ARPOINTCLOUD_T2004641850_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARPointCloud struct ARPointCloud_t2004641850 : public RuntimeObject { public: // System.IntPtr UnityEngine.XR.iOS.ARPointCloud::m_Ptr intptr_t ___m_Ptr_0; // UnityEngine.Vector3[] UnityEngine.XR.iOS.ARPointCloud::m_Positions Vector3U5BU5D_t1172311765* ___m_Positions_1; // System.UInt64[] UnityEngine.XR.iOS.ARPointCloud::m_Identifiers UInt64U5BU5D_t1668688775* ___m_Identifiers_2; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(ARPointCloud_t2004641850, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } inline static int32_t get_offset_of_m_Positions_1() { return static_cast<int32_t>(offsetof(ARPointCloud_t2004641850, ___m_Positions_1)); } inline Vector3U5BU5D_t1172311765* get_m_Positions_1() const { return ___m_Positions_1; } inline Vector3U5BU5D_t1172311765** get_address_of_m_Positions_1() { return &___m_Positions_1; } inline void set_m_Positions_1(Vector3U5BU5D_t1172311765* value) { ___m_Positions_1 = value; Il2CppCodeGenWriteBarrier((&___m_Positions_1), value); } inline static int32_t get_offset_of_m_Identifiers_2() { return static_cast<int32_t>(offsetof(ARPointCloud_t2004641850, ___m_Identifiers_2)); } inline UInt64U5BU5D_t1668688775* get_m_Identifiers_2() const { return ___m_Identifiers_2; } inline UInt64U5BU5D_t1668688775** get_address_of_m_Identifiers_2() { return &___m_Identifiers_2; } inline void set_m_Identifiers_2(UInt64U5BU5D_t1668688775* value) { ___m_Identifiers_2 = value; Il2CppCodeGenWriteBarrier((&___m_Identifiers_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARPOINTCLOUD_T2004641850_H #ifndef ARPLANEANCHORALIGNMENT_T2379298071_H #define ARPLANEANCHORALIGNMENT_T2379298071_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARPlaneAnchorAlignment struct ARPlaneAnchorAlignment_t2379298071 { public: // System.Int64 UnityEngine.XR.iOS.ARPlaneAnchorAlignment::value__ int64_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ARPlaneAnchorAlignment_t2379298071, ___value___1)); } inline int64_t get_value___1() const { return ___value___1; } inline int64_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int64_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARPLANEANCHORALIGNMENT_T2379298071_H #ifndef UNITYARMATRIX4X4_T100931615_H #define UNITYARMATRIX4X4_T100931615_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARMatrix4x4 struct UnityARMatrix4x4_t100931615 { public: // UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARMatrix4x4::column0 Vector4_t2243707581 ___column0_0; // UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARMatrix4x4::column1 Vector4_t2243707581 ___column1_1; // UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARMatrix4x4::column2 Vector4_t2243707581 ___column2_2; // UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARMatrix4x4::column3 Vector4_t2243707581 ___column3_3; public: inline static int32_t get_offset_of_column0_0() { return static_cast<int32_t>(offsetof(UnityARMatrix4x4_t100931615, ___column0_0)); } inline Vector4_t2243707581 get_column0_0() const { return ___column0_0; } inline Vector4_t2243707581 * get_address_of_column0_0() { return &___column0_0; } inline void set_column0_0(Vector4_t2243707581 value) { ___column0_0 = value; } inline static int32_t get_offset_of_column1_1() { return static_cast<int32_t>(offsetof(UnityARMatrix4x4_t100931615, ___column1_1)); } inline Vector4_t2243707581 get_column1_1() const { return ___column1_1; } inline Vector4_t2243707581 * get_address_of_column1_1() { return &___column1_1; } inline void set_column1_1(Vector4_t2243707581 value) { ___column1_1 = value; } inline static int32_t get_offset_of_column2_2() { return static_cast<int32_t>(offsetof(UnityARMatrix4x4_t100931615, ___column2_2)); } inline Vector4_t2243707581 get_column2_2() const { return ___column2_2; } inline Vector4_t2243707581 * get_address_of_column2_2() { return &___column2_2; } inline void set_column2_2(Vector4_t2243707581 value) { ___column2_2 = value; } inline static int32_t get_offset_of_column3_3() { return static_cast<int32_t>(offsetof(UnityARMatrix4x4_t100931615, ___column3_3)); } inline Vector4_t2243707581 get_column3_3() const { return ___column3_3; } inline Vector4_t2243707581 * get_address_of_column3_3() { return &___column3_3; } inline void set_column3_3(Vector4_t2243707581 value) { ___column3_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARMATRIX4X4_T100931615_H #ifndef UNITYVIDEOPARAMS_T2644681676_H #define UNITYVIDEOPARAMS_T2644681676_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityVideoParams struct UnityVideoParams_t2644681676 { public: // System.Int32 UnityEngine.XR.iOS.UnityVideoParams::yWidth int32_t ___yWidth_0; // System.Int32 UnityEngine.XR.iOS.UnityVideoParams::yHeight int32_t ___yHeight_1; // System.Int32 UnityEngine.XR.iOS.UnityVideoParams::screenOrientation int32_t ___screenOrientation_2; // System.Single UnityEngine.XR.iOS.UnityVideoParams::texCoordScale float ___texCoordScale_3; // System.IntPtr UnityEngine.XR.iOS.UnityVideoParams::cvPixelBufferPtr intptr_t ___cvPixelBufferPtr_4; public: inline static int32_t get_offset_of_yWidth_0() { return static_cast<int32_t>(offsetof(UnityVideoParams_t2644681676, ___yWidth_0)); } inline int32_t get_yWidth_0() const { return ___yWidth_0; } inline int32_t* get_address_of_yWidth_0() { return &___yWidth_0; } inline void set_yWidth_0(int32_t value) { ___yWidth_0 = value; } inline static int32_t get_offset_of_yHeight_1() { return static_cast<int32_t>(offsetof(UnityVideoParams_t2644681676, ___yHeight_1)); } inline int32_t get_yHeight_1() const { return ___yHeight_1; } inline int32_t* get_address_of_yHeight_1() { return &___yHeight_1; } inline void set_yHeight_1(int32_t value) { ___yHeight_1 = value; } inline static int32_t get_offset_of_screenOrientation_2() { return static_cast<int32_t>(offsetof(UnityVideoParams_t2644681676, ___screenOrientation_2)); } inline int32_t get_screenOrientation_2() const { return ___screenOrientation_2; } inline int32_t* get_address_of_screenOrientation_2() { return &___screenOrientation_2; } inline void set_screenOrientation_2(int32_t value) { ___screenOrientation_2 = value; } inline static int32_t get_offset_of_texCoordScale_3() { return static_cast<int32_t>(offsetof(UnityVideoParams_t2644681676, ___texCoordScale_3)); } inline float get_texCoordScale_3() const { return ___texCoordScale_3; } inline float* get_address_of_texCoordScale_3() { return &___texCoordScale_3; } inline void set_texCoordScale_3(float value) { ___texCoordScale_3 = value; } inline static int32_t get_offset_of_cvPixelBufferPtr_4() { return static_cast<int32_t>(offsetof(UnityVideoParams_t2644681676, ___cvPixelBufferPtr_4)); } inline intptr_t get_cvPixelBufferPtr_4() const { return ___cvPixelBufferPtr_4; } inline intptr_t* get_address_of_cvPixelBufferPtr_4() { return &___cvPixelBufferPtr_4; } inline void set_cvPixelBufferPtr_4(intptr_t value) { ___cvPixelBufferPtr_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYVIDEOPARAMS_T2644681676_H #ifndef ARREFERENCEOBJECT_T2984430917_H #define ARREFERENCEOBJECT_T2984430917_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARReferenceObject struct ARReferenceObject_t2984430917 : public RuntimeObject { public: // System.IntPtr UnityEngine.XR.iOS.ARReferenceObject::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(ARReferenceObject_t2984430917, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARREFERENCEOBJECT_T2984430917_H #ifndef UNITYARVIDEOFORMAT_T544330776_H #define UNITYARVIDEOFORMAT_T544330776_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARVideoFormat struct UnityARVideoFormat_t544330776 { public: // System.IntPtr UnityEngine.XR.iOS.UnityARVideoFormat::videoFormatPtr intptr_t ___videoFormatPtr_0; // System.Single UnityEngine.XR.iOS.UnityARVideoFormat::imageResolutionWidth float ___imageResolutionWidth_1; // System.Single UnityEngine.XR.iOS.UnityARVideoFormat::imageResolutionHeight float ___imageResolutionHeight_2; // System.Int32 UnityEngine.XR.iOS.UnityARVideoFormat::framesPerSecond int32_t ___framesPerSecond_3; public: inline static int32_t get_offset_of_videoFormatPtr_0() { return static_cast<int32_t>(offsetof(UnityARVideoFormat_t544330776, ___videoFormatPtr_0)); } inline intptr_t get_videoFormatPtr_0() const { return ___videoFormatPtr_0; } inline intptr_t* get_address_of_videoFormatPtr_0() { return &___videoFormatPtr_0; } inline void set_videoFormatPtr_0(intptr_t value) { ___videoFormatPtr_0 = value; } inline static int32_t get_offset_of_imageResolutionWidth_1() { return static_cast<int32_t>(offsetof(UnityARVideoFormat_t544330776, ___imageResolutionWidth_1)); } inline float get_imageResolutionWidth_1() const { return ___imageResolutionWidth_1; } inline float* get_address_of_imageResolutionWidth_1() { return &___imageResolutionWidth_1; } inline void set_imageResolutionWidth_1(float value) { ___imageResolutionWidth_1 = value; } inline static int32_t get_offset_of_imageResolutionHeight_2() { return static_cast<int32_t>(offsetof(UnityARVideoFormat_t544330776, ___imageResolutionHeight_2)); } inline float get_imageResolutionHeight_2() const { return ___imageResolutionHeight_2; } inline float* get_address_of_imageResolutionHeight_2() { return &___imageResolutionHeight_2; } inline void set_imageResolutionHeight_2(float value) { ___imageResolutionHeight_2 = value; } inline static int32_t get_offset_of_framesPerSecond_3() { return static_cast<int32_t>(offsetof(UnityARVideoFormat_t544330776, ___framesPerSecond_3)); } inline int32_t get_framesPerSecond_3() const { return ___framesPerSecond_3; } inline int32_t* get_address_of_framesPerSecond_3() { return &___framesPerSecond_3; } inline void set_framesPerSecond_3(int32_t value) { ___framesPerSecond_3 = value; } }; struct UnityARVideoFormat_t544330776_StaticFields { public: // System.Collections.Generic.List`1<UnityEngine.XR.iOS.UnityARVideoFormat> UnityEngine.XR.iOS.UnityARVideoFormat::videoFormatsList List_1_t4208419204 * ___videoFormatsList_4; // UnityEngine.XR.iOS.VideoFormatEnumerator UnityEngine.XR.iOS.UnityARVideoFormat::<>f__mg$cache0 VideoFormatEnumerator_t1718260816 * ___U3CU3Ef__mgU24cache0_5; // UnityEngine.XR.iOS.VideoFormatEnumerator UnityEngine.XR.iOS.UnityARVideoFormat::<>f__mg$cache1 VideoFormatEnumerator_t1718260816 * ___U3CU3Ef__mgU24cache1_6; public: inline static int32_t get_offset_of_videoFormatsList_4() { return static_cast<int32_t>(offsetof(UnityARVideoFormat_t544330776_StaticFields, ___videoFormatsList_4)); } inline List_1_t4208419204 * get_videoFormatsList_4() const { return ___videoFormatsList_4; } inline List_1_t4208419204 ** get_address_of_videoFormatsList_4() { return &___videoFormatsList_4; } inline void set_videoFormatsList_4(List_1_t4208419204 * value) { ___videoFormatsList_4 = value; Il2CppCodeGenWriteBarrier((&___videoFormatsList_4), value); } inline static int32_t get_offset_of_U3CU3Ef__mgU24cache0_5() { return static_cast<int32_t>(offsetof(UnityARVideoFormat_t544330776_StaticFields, ___U3CU3Ef__mgU24cache0_5)); } inline VideoFormatEnumerator_t1718260816 * get_U3CU3Ef__mgU24cache0_5() const { return ___U3CU3Ef__mgU24cache0_5; } inline VideoFormatEnumerator_t1718260816 ** get_address_of_U3CU3Ef__mgU24cache0_5() { return &___U3CU3Ef__mgU24cache0_5; } inline void set_U3CU3Ef__mgU24cache0_5(VideoFormatEnumerator_t1718260816 * value) { ___U3CU3Ef__mgU24cache0_5 = value; Il2CppCodeGenWriteBarrier((&___U3CU3Ef__mgU24cache0_5), value); } inline static int32_t get_offset_of_U3CU3Ef__mgU24cache1_6() { return static_cast<int32_t>(offsetof(UnityARVideoFormat_t544330776_StaticFields, ___U3CU3Ef__mgU24cache1_6)); } inline VideoFormatEnumerator_t1718260816 * get_U3CU3Ef__mgU24cache1_6() const { return ___U3CU3Ef__mgU24cache1_6; } inline VideoFormatEnumerator_t1718260816 ** get_address_of_U3CU3Ef__mgU24cache1_6() { return &___U3CU3Ef__mgU24cache1_6; } inline void set_U3CU3Ef__mgU24cache1_6(VideoFormatEnumerator_t1718260816 * value) { ___U3CU3Ef__mgU24cache1_6 = value; Il2CppCodeGenWriteBarrier((&___U3CU3Ef__mgU24cache1_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARVIDEOFORMAT_T544330776_H #ifndef ARUSERANCHOR_T4064312267_H #define ARUSERANCHOR_T4064312267_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARUserAnchor struct ARUserAnchor_t4064312267 { public: // System.String UnityEngine.XR.iOS.ARUserAnchor::identifier String_t* ___identifier_0; // UnityEngine.Matrix4x4 UnityEngine.XR.iOS.ARUserAnchor::transform Matrix4x4_t2933234003 ___transform_1; public: inline static int32_t get_offset_of_identifier_0() { return static_cast<int32_t>(offsetof(ARUserAnchor_t4064312267, ___identifier_0)); } inline String_t* get_identifier_0() const { return ___identifier_0; } inline String_t** get_address_of_identifier_0() { return &___identifier_0; } inline void set_identifier_0(String_t* value) { ___identifier_0 = value; Il2CppCodeGenWriteBarrier((&___identifier_0), value); } inline static int32_t get_offset_of_transform_1() { return static_cast<int32_t>(offsetof(ARUserAnchor_t4064312267, ___transform_1)); } inline Matrix4x4_t2933234003 get_transform_1() const { return ___transform_1; } inline Matrix4x4_t2933234003 * get_address_of_transform_1() { return &___transform_1; } inline void set_transform_1(Matrix4x4_t2933234003 value) { ___transform_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.XR.iOS.ARUserAnchor struct ARUserAnchor_t4064312267_marshaled_pinvoke { char* ___identifier_0; Matrix4x4_t2933234003 ___transform_1; }; // Native definition for COM marshalling of UnityEngine.XR.iOS.ARUserAnchor struct ARUserAnchor_t4064312267_marshaled_com { Il2CppChar* ___identifier_0; Matrix4x4_t2933234003 ___transform_1; }; #endif // ARUSERANCHOR_T4064312267_H #ifndef ARTRACKINGSTATEREASON_T4227173799_H #define ARTRACKINGSTATEREASON_T4227173799_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARTrackingStateReason struct ARTrackingStateReason_t4227173799 { public: // System.Int32 UnityEngine.XR.iOS.ARTrackingStateReason::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ARTrackingStateReason_t4227173799, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARTRACKINGSTATEREASON_T4227173799_H #ifndef ARTRACKINGSTATE_T2048880995_H #define ARTRACKINGSTATE_T2048880995_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARTrackingState struct ARTrackingState_t2048880995 { public: // System.Int32 UnityEngine.XR.iOS.ARTrackingState::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ARTrackingState_t2048880995, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARTRACKINGSTATE_T2048880995_H #ifndef ARTRACKINGQUALITY_T55960597_H #define ARTRACKINGQUALITY_T55960597_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARTrackingQuality struct ARTrackingQuality_t55960597 { public: // System.Int64 UnityEngine.XR.iOS.ARTrackingQuality::value__ int64_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ARTrackingQuality_t55960597, ___value___1)); } inline int64_t get_value___1() const { return ___value___1; } inline int64_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int64_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARTRACKINGQUALITY_T55960597_H #ifndef ARTEXTUREHANDLESSTRUCT_T617670158_H #define ARTEXTUREHANDLESSTRUCT_T617670158_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARTextureHandles/ARTextureHandlesStruct struct ARTextureHandlesStruct_t617670158 { public: // System.IntPtr UnityEngine.XR.iOS.ARTextureHandles/ARTextureHandlesStruct::textureY intptr_t ___textureY_0; // System.IntPtr UnityEngine.XR.iOS.ARTextureHandles/ARTextureHandlesStruct::textureCbCr intptr_t ___textureCbCr_1; public: inline static int32_t get_offset_of_textureY_0() { return static_cast<int32_t>(offsetof(ARTextureHandlesStruct_t617670158, ___textureY_0)); } inline intptr_t get_textureY_0() const { return ___textureY_0; } inline intptr_t* get_address_of_textureY_0() { return &___textureY_0; } inline void set_textureY_0(intptr_t value) { ___textureY_0 = value; } inline static int32_t get_offset_of_textureCbCr_1() { return static_cast<int32_t>(offsetof(ARTextureHandlesStruct_t617670158, ___textureCbCr_1)); } inline intptr_t get_textureCbCr_1() const { return ___textureCbCr_1; } inline intptr_t* get_address_of_textureCbCr_1() { return &___textureCbCr_1; } inline void set_textureCbCr_1(intptr_t value) { ___textureCbCr_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARTEXTUREHANDLESSTRUCT_T617670158_H #ifndef OBJECT_T1021602117_H #define OBJECT_T1021602117_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Object struct Object_t1021602117 : public RuntimeObject { public: // System.IntPtr UnityEngine.Object::m_CachedPtr intptr_t ___m_CachedPtr_0; public: inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_t1021602117, ___m_CachedPtr_0)); } inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; } inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; } inline void set_m_CachedPtr_0(intptr_t value) { ___m_CachedPtr_0 = value; } }; struct Object_t1021602117_StaticFields { public: // System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1; public: inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_t1021602117_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); } inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; } inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; } inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value) { ___OffsetOfInstanceIDInCPlusPlusObject_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Object struct Object_t1021602117_marshaled_pinvoke { intptr_t ___m_CachedPtr_0; }; // Native definition for COM marshalling of UnityEngine.Object struct Object_t1021602117_marshaled_com { intptr_t ___m_CachedPtr_0; }; #endif // OBJECT_T1021602117_H #ifndef ARWORLDMAP_T3922181545_H #define ARWORLDMAP_T3922181545_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARWorldMap struct ARWorldMap_t3922181545 : public RuntimeObject { public: // System.IntPtr UnityEngine.XR.iOS.ARWorldMap::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(ARWorldMap_t3922181545, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARWORLDMAP_T3922181545_H #ifndef UNITYARPLANEGEOMETRY_T1435619558_H #define UNITYARPLANEGEOMETRY_T1435619558_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARPlaneGeometry struct UnityARPlaneGeometry_t1435619558 { public: // System.Int32 UnityEngine.XR.iOS.UnityARPlaneGeometry::vertexCount int32_t ___vertexCount_0; // System.IntPtr UnityEngine.XR.iOS.UnityARPlaneGeometry::vertices intptr_t ___vertices_1; // System.Int32 UnityEngine.XR.iOS.UnityARPlaneGeometry::textureCoordinateCount int32_t ___textureCoordinateCount_2; // System.IntPtr UnityEngine.XR.iOS.UnityARPlaneGeometry::textureCoordinates intptr_t ___textureCoordinates_3; // System.Int32 UnityEngine.XR.iOS.UnityARPlaneGeometry::triangleCount int32_t ___triangleCount_4; // System.IntPtr UnityEngine.XR.iOS.UnityARPlaneGeometry::triangleIndices intptr_t ___triangleIndices_5; // System.Int32 UnityEngine.XR.iOS.UnityARPlaneGeometry::boundaryVertexCount int32_t ___boundaryVertexCount_6; // System.IntPtr UnityEngine.XR.iOS.UnityARPlaneGeometry::boundaryVertices intptr_t ___boundaryVertices_7; public: inline static int32_t get_offset_of_vertexCount_0() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1435619558, ___vertexCount_0)); } inline int32_t get_vertexCount_0() const { return ___vertexCount_0; } inline int32_t* get_address_of_vertexCount_0() { return &___vertexCount_0; } inline void set_vertexCount_0(int32_t value) { ___vertexCount_0 = value; } inline static int32_t get_offset_of_vertices_1() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1435619558, ___vertices_1)); } inline intptr_t get_vertices_1() const { return ___vertices_1; } inline intptr_t* get_address_of_vertices_1() { return &___vertices_1; } inline void set_vertices_1(intptr_t value) { ___vertices_1 = value; } inline static int32_t get_offset_of_textureCoordinateCount_2() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1435619558, ___textureCoordinateCount_2)); } inline int32_t get_textureCoordinateCount_2() const { return ___textureCoordinateCount_2; } inline int32_t* get_address_of_textureCoordinateCount_2() { return &___textureCoordinateCount_2; } inline void set_textureCoordinateCount_2(int32_t value) { ___textureCoordinateCount_2 = value; } inline static int32_t get_offset_of_textureCoordinates_3() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1435619558, ___textureCoordinates_3)); } inline intptr_t get_textureCoordinates_3() const { return ___textureCoordinates_3; } inline intptr_t* get_address_of_textureCoordinates_3() { return &___textureCoordinates_3; } inline void set_textureCoordinates_3(intptr_t value) { ___textureCoordinates_3 = value; } inline static int32_t get_offset_of_triangleCount_4() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1435619558, ___triangleCount_4)); } inline int32_t get_triangleCount_4() const { return ___triangleCount_4; } inline int32_t* get_address_of_triangleCount_4() { return &___triangleCount_4; } inline void set_triangleCount_4(int32_t value) { ___triangleCount_4 = value; } inline static int32_t get_offset_of_triangleIndices_5() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1435619558, ___triangleIndices_5)); } inline intptr_t get_triangleIndices_5() const { return ___triangleIndices_5; } inline intptr_t* get_address_of_triangleIndices_5() { return &___triangleIndices_5; } inline void set_triangleIndices_5(intptr_t value) { ___triangleIndices_5 = value; } inline static int32_t get_offset_of_boundaryVertexCount_6() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1435619558, ___boundaryVertexCount_6)); } inline int32_t get_boundaryVertexCount_6() const { return ___boundaryVertexCount_6; } inline int32_t* get_address_of_boundaryVertexCount_6() { return &___boundaryVertexCount_6; } inline void set_boundaryVertexCount_6(int32_t value) { ___boundaryVertexCount_6 = value; } inline static int32_t get_offset_of_boundaryVertices_7() { return static_cast<int32_t>(offsetof(UnityARPlaneGeometry_t1435619558, ___boundaryVertices_7)); } inline intptr_t get_boundaryVertices_7() const { return ___boundaryVertices_7; } inline intptr_t* get_address_of_boundaryVertices_7() { return &___boundaryVertices_7; } inline void set_boundaryVertices_7(intptr_t value) { ___boundaryVertices_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARPLANEGEOMETRY_T1435619558_H #ifndef ARWORLDMAPPINGSTATUS_T1070279697_H #define ARWORLDMAPPINGSTATUS_T1070279697_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARWorldMappingStatus struct ARWorldMappingStatus_t1070279697 { public: // System.Int32 UnityEngine.XR.iOS.ARWorldMappingStatus::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ARWorldMappingStatus_t1070279697, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARWORLDMAPPINGSTATUS_T1070279697_H #ifndef ARHITTESTRESULTTYPE_T3616749745_H #define ARHITTESTRESULTTYPE_T3616749745_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARHitTestResultType struct ARHitTestResultType_t3616749745 { public: // System.Int64 UnityEngine.XR.iOS.ARHitTestResultType::value__ int64_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ARHitTestResultType_t3616749745, ___value___1)); } inline int64_t get_value___1() const { return ___value___1; } inline int64_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int64_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARHITTESTRESULTTYPE_T3616749745_H #ifndef UNITYARSESSIONRUNOPTION_T3123075684_H #define UNITYARSESSIONRUNOPTION_T3123075684_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARSessionRunOption struct UnityARSessionRunOption_t3123075684 { public: // System.Int32 UnityEngine.XR.iOS.UnityARSessionRunOption::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(UnityARSessionRunOption_t3123075684, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARSESSIONRUNOPTION_T3123075684_H #ifndef UNITYARFACEGEOMETRY_T49674351_H #define UNITYARFACEGEOMETRY_T49674351_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARFaceGeometry struct UnityARFaceGeometry_t49674351 { public: // System.Int32 UnityEngine.XR.iOS.UnityARFaceGeometry::vertexCount int32_t ___vertexCount_0; // System.IntPtr UnityEngine.XR.iOS.UnityARFaceGeometry::vertices intptr_t ___vertices_1; // System.Int32 UnityEngine.XR.iOS.UnityARFaceGeometry::textureCoordinateCount int32_t ___textureCoordinateCount_2; // System.IntPtr UnityEngine.XR.iOS.UnityARFaceGeometry::textureCoordinates intptr_t ___textureCoordinates_3; // System.Int32 UnityEngine.XR.iOS.UnityARFaceGeometry::triangleCount int32_t ___triangleCount_4; // System.IntPtr UnityEngine.XR.iOS.UnityARFaceGeometry::triangleIndices intptr_t ___triangleIndices_5; public: inline static int32_t get_offset_of_vertexCount_0() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t49674351, ___vertexCount_0)); } inline int32_t get_vertexCount_0() const { return ___vertexCount_0; } inline int32_t* get_address_of_vertexCount_0() { return &___vertexCount_0; } inline void set_vertexCount_0(int32_t value) { ___vertexCount_0 = value; } inline static int32_t get_offset_of_vertices_1() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t49674351, ___vertices_1)); } inline intptr_t get_vertices_1() const { return ___vertices_1; } inline intptr_t* get_address_of_vertices_1() { return &___vertices_1; } inline void set_vertices_1(intptr_t value) { ___vertices_1 = value; } inline static int32_t get_offset_of_textureCoordinateCount_2() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t49674351, ___textureCoordinateCount_2)); } inline int32_t get_textureCoordinateCount_2() const { return ___textureCoordinateCount_2; } inline int32_t* get_address_of_textureCoordinateCount_2() { return &___textureCoordinateCount_2; } inline void set_textureCoordinateCount_2(int32_t value) { ___textureCoordinateCount_2 = value; } inline static int32_t get_offset_of_textureCoordinates_3() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t49674351, ___textureCoordinates_3)); } inline intptr_t get_textureCoordinates_3() const { return ___textureCoordinates_3; } inline intptr_t* get_address_of_textureCoordinates_3() { return &___textureCoordinates_3; } inline void set_textureCoordinates_3(intptr_t value) { ___textureCoordinates_3 = value; } inline static int32_t get_offset_of_triangleCount_4() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t49674351, ___triangleCount_4)); } inline int32_t get_triangleCount_4() const { return ___triangleCount_4; } inline int32_t* get_address_of_triangleCount_4() { return &___triangleCount_4; } inline void set_triangleCount_4(int32_t value) { ___triangleCount_4 = value; } inline static int32_t get_offset_of_triangleIndices_5() { return static_cast<int32_t>(offsetof(UnityARFaceGeometry_t49674351, ___triangleIndices_5)); } inline intptr_t get_triangleIndices_5() const { return ___triangleIndices_5; } inline intptr_t* get_address_of_triangleIndices_5() { return &___triangleIndices_5; } inline void set_triangleIndices_5(intptr_t value) { ___triangleIndices_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARFACEGEOMETRY_T49674351_H #ifndef ARERRORCODE_T2887756272_H #define ARERRORCODE_T2887756272_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARErrorCode struct ARErrorCode_t2887756272 { public: // System.Int64 UnityEngine.XR.iOS.ARErrorCode::value__ int64_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ARErrorCode_t2887756272, ___value___1)); } inline int64_t get_value___1() const { return ___value___1; } inline int64_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int64_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARERRORCODE_T2887756272_H #ifndef UNITYARENVIRONMENTTEXTURING_T952972607_H #define UNITYARENVIRONMENTTEXTURING_T952972607_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityAREnvironmentTexturing struct UnityAREnvironmentTexturing_t952972607 { public: // System.Int32 UnityEngine.XR.iOS.UnityAREnvironmentTexturing::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(UnityAREnvironmentTexturing_t952972607, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARENVIRONMENTTEXTURING_T952972607_H #ifndef DELEGATE_T3022476291_H #define DELEGATE_T3022476291_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Delegate struct Delegate_t3022476291 : public RuntimeObject { public: // System.IntPtr System.Delegate::method_ptr Il2CppMethodPointer ___method_ptr_0; // System.IntPtr System.Delegate::invoke_impl intptr_t ___invoke_impl_1; // System.Object System.Delegate::m_target RuntimeObject * ___m_target_2; // System.IntPtr System.Delegate::method intptr_t ___method_3; // System.IntPtr System.Delegate::delegate_trampoline intptr_t ___delegate_trampoline_4; // System.IntPtr System.Delegate::method_code intptr_t ___method_code_5; // System.Reflection.MethodInfo System.Delegate::method_info MethodInfo_t * ___method_info_6; // System.Reflection.MethodInfo System.Delegate::original_method_info MethodInfo_t * ___original_method_info_7; // System.DelegateData System.Delegate::data DelegateData_t1572802995 * ___data_8; public: inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_ptr_0)); } inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; } inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; } inline void set_method_ptr_0(Il2CppMethodPointer value) { ___method_ptr_0 = value; } inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___invoke_impl_1)); } inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; } inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; } inline void set_invoke_impl_1(intptr_t value) { ___invoke_impl_1 = value; } inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___m_target_2)); } inline RuntimeObject * get_m_target_2() const { return ___m_target_2; } inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; } inline void set_m_target_2(RuntimeObject * value) { ___m_target_2 = value; Il2CppCodeGenWriteBarrier((&___m_target_2), value); } inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_3)); } inline intptr_t get_method_3() const { return ___method_3; } inline intptr_t* get_address_of_method_3() { return &___method_3; } inline void set_method_3(intptr_t value) { ___method_3 = value; } inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___delegate_trampoline_4)); } inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; } inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; } inline void set_delegate_trampoline_4(intptr_t value) { ___delegate_trampoline_4 = value; } inline static int32_t get_offset_of_method_code_5() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_code_5)); } inline intptr_t get_method_code_5() const { return ___method_code_5; } inline intptr_t* get_address_of_method_code_5() { return &___method_code_5; } inline void set_method_code_5(intptr_t value) { ___method_code_5 = value; } inline static int32_t get_offset_of_method_info_6() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_info_6)); } inline MethodInfo_t * get_method_info_6() const { return ___method_info_6; } inline MethodInfo_t ** get_address_of_method_info_6() { return &___method_info_6; } inline void set_method_info_6(MethodInfo_t * value) { ___method_info_6 = value; Il2CppCodeGenWriteBarrier((&___method_info_6), value); } inline static int32_t get_offset_of_original_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___original_method_info_7)); } inline MethodInfo_t * get_original_method_info_7() const { return ___original_method_info_7; } inline MethodInfo_t ** get_address_of_original_method_info_7() { return &___original_method_info_7; } inline void set_original_method_info_7(MethodInfo_t * value) { ___original_method_info_7 = value; Il2CppCodeGenWriteBarrier((&___original_method_info_7), value); } inline static int32_t get_offset_of_data_8() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___data_8)); } inline DelegateData_t1572802995 * get_data_8() const { return ___data_8; } inline DelegateData_t1572802995 ** get_address_of_data_8() { return &___data_8; } inline void set_data_8(DelegateData_t1572802995 * value) { ___data_8 = value; Il2CppCodeGenWriteBarrier((&___data_8), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DELEGATE_T3022476291_H #ifndef MARSHALDIRECTIONALLIGHTESTIMATE_T3614627546_H #define MARSHALDIRECTIONALLIGHTESTIMATE_T3614627546_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.MarshalDirectionalLightEstimate struct MarshalDirectionalLightEstimate_t3614627546 { public: // UnityEngine.Vector4 UnityEngine.XR.iOS.MarshalDirectionalLightEstimate::primaryDirAndIntensity Vector4_t2243707581 ___primaryDirAndIntensity_0; // System.IntPtr UnityEngine.XR.iOS.MarshalDirectionalLightEstimate::sphericalHarmonicCoefficientsPtr intptr_t ___sphericalHarmonicCoefficientsPtr_1; public: inline static int32_t get_offset_of_primaryDirAndIntensity_0() { return static_cast<int32_t>(offsetof(MarshalDirectionalLightEstimate_t3614627546, ___primaryDirAndIntensity_0)); } inline Vector4_t2243707581 get_primaryDirAndIntensity_0() const { return ___primaryDirAndIntensity_0; } inline Vector4_t2243707581 * get_address_of_primaryDirAndIntensity_0() { return &___primaryDirAndIntensity_0; } inline void set_primaryDirAndIntensity_0(Vector4_t2243707581 value) { ___primaryDirAndIntensity_0 = value; } inline static int32_t get_offset_of_sphericalHarmonicCoefficientsPtr_1() { return static_cast<int32_t>(offsetof(MarshalDirectionalLightEstimate_t3614627546, ___sphericalHarmonicCoefficientsPtr_1)); } inline intptr_t get_sphericalHarmonicCoefficientsPtr_1() const { return ___sphericalHarmonicCoefficientsPtr_1; } inline intptr_t* get_address_of_sphericalHarmonicCoefficientsPtr_1() { return &___sphericalHarmonicCoefficientsPtr_1; } inline void set_sphericalHarmonicCoefficientsPtr_1(intptr_t value) { ___sphericalHarmonicCoefficientsPtr_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MARSHALDIRECTIONALLIGHTESTIMATE_T3614627546_H #ifndef UNITYARALIGNMENT_T2379988631_H #define UNITYARALIGNMENT_T2379988631_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARAlignment struct UnityARAlignment_t2379988631 { public: // System.Int32 UnityEngine.XR.iOS.UnityARAlignment::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(UnityARAlignment_t2379988631, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARALIGNMENT_T2379988631_H #ifndef UNITYARPLANEDETECTION_T612575857_H #define UNITYARPLANEDETECTION_T612575857_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARPlaneDetection struct UnityARPlaneDetection_t612575857 { public: // System.Int32 UnityEngine.XR.iOS.UnityARPlaneDetection::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(UnityARPlaneDetection_t612575857, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARPLANEDETECTION_T612575857_H #ifndef LIGHTDATATYPE_T1811330778_H #define LIGHTDATATYPE_T1811330778_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.LightDataType struct LightDataType_t1811330778 { public: // System.Int32 UnityEngine.XR.iOS.LightDataType::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(LightDataType_t1811330778, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LIGHTDATATYPE_T1811330778_H #ifndef UNITYARDIRECTIONALLIGHTESTIMATE_T1689150542_H #define UNITYARDIRECTIONALLIGHTESTIMATE_T1689150542_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARDirectionalLightEstimate struct UnityARDirectionalLightEstimate_t1689150542 : public RuntimeObject { public: // UnityEngine.Vector3 UnityEngine.XR.iOS.UnityARDirectionalLightEstimate::primaryLightDirection Vector3_t2243707580 ___primaryLightDirection_0; // System.Single UnityEngine.XR.iOS.UnityARDirectionalLightEstimate::primaryLightIntensity float ___primaryLightIntensity_1; // System.Single[] UnityEngine.XR.iOS.UnityARDirectionalLightEstimate::sphericalHarmonicsCoefficients SingleU5BU5D_t577127397* ___sphericalHarmonicsCoefficients_2; public: inline static int32_t get_offset_of_primaryLightDirection_0() { return static_cast<int32_t>(offsetof(UnityARDirectionalLightEstimate_t1689150542, ___primaryLightDirection_0)); } inline Vector3_t2243707580 get_primaryLightDirection_0() const { return ___primaryLightDirection_0; } inline Vector3_t2243707580 * get_address_of_primaryLightDirection_0() { return &___primaryLightDirection_0; } inline void set_primaryLightDirection_0(Vector3_t2243707580 value) { ___primaryLightDirection_0 = value; } inline static int32_t get_offset_of_primaryLightIntensity_1() { return static_cast<int32_t>(offsetof(UnityARDirectionalLightEstimate_t1689150542, ___primaryLightIntensity_1)); } inline float get_primaryLightIntensity_1() const { return ___primaryLightIntensity_1; } inline float* get_address_of_primaryLightIntensity_1() { return &___primaryLightIntensity_1; } inline void set_primaryLightIntensity_1(float value) { ___primaryLightIntensity_1 = value; } inline static int32_t get_offset_of_sphericalHarmonicsCoefficients_2() { return static_cast<int32_t>(offsetof(UnityARDirectionalLightEstimate_t1689150542, ___sphericalHarmonicsCoefficients_2)); } inline SingleU5BU5D_t577127397* get_sphericalHarmonicsCoefficients_2() const { return ___sphericalHarmonicsCoefficients_2; } inline SingleU5BU5D_t577127397** get_address_of_sphericalHarmonicsCoefficients_2() { return &___sphericalHarmonicsCoefficients_2; } inline void set_sphericalHarmonicsCoefficients_2(SingleU5BU5D_t577127397* value) { ___sphericalHarmonicsCoefficients_2 = value; Il2CppCodeGenWriteBarrier((&___sphericalHarmonicsCoefficients_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARDIRECTIONALLIGHTESTIMATE_T1689150542_H #ifndef UNITYARHITTESTRESULT_T4129824344_H #define UNITYARHITTESTRESULT_T4129824344_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARHitTestResult struct UnityARHitTestResult_t4129824344 { public: // UnityEngine.XR.iOS.ARHitTestResultType UnityEngine.XR.iOS.UnityARHitTestResult::type int64_t ___type_0; // System.Double UnityEngine.XR.iOS.UnityARHitTestResult::distance double ___distance_1; // UnityEngine.Matrix4x4 UnityEngine.XR.iOS.UnityARHitTestResult::localTransform Matrix4x4_t2933234003 ___localTransform_2; // UnityEngine.Matrix4x4 UnityEngine.XR.iOS.UnityARHitTestResult::worldTransform Matrix4x4_t2933234003 ___worldTransform_3; // System.IntPtr UnityEngine.XR.iOS.UnityARHitTestResult::anchor intptr_t ___anchor_4; // System.Boolean UnityEngine.XR.iOS.UnityARHitTestResult::isValid bool ___isValid_5; public: inline static int32_t get_offset_of_type_0() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___type_0)); } inline int64_t get_type_0() const { return ___type_0; } inline int64_t* get_address_of_type_0() { return &___type_0; } inline void set_type_0(int64_t value) { ___type_0 = value; } inline static int32_t get_offset_of_distance_1() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___distance_1)); } inline double get_distance_1() const { return ___distance_1; } inline double* get_address_of_distance_1() { return &___distance_1; } inline void set_distance_1(double value) { ___distance_1 = value; } inline static int32_t get_offset_of_localTransform_2() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___localTransform_2)); } inline Matrix4x4_t2933234003 get_localTransform_2() const { return ___localTransform_2; } inline Matrix4x4_t2933234003 * get_address_of_localTransform_2() { return &___localTransform_2; } inline void set_localTransform_2(Matrix4x4_t2933234003 value) { ___localTransform_2 = value; } inline static int32_t get_offset_of_worldTransform_3() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___worldTransform_3)); } inline Matrix4x4_t2933234003 get_worldTransform_3() const { return ___worldTransform_3; } inline Matrix4x4_t2933234003 * get_address_of_worldTransform_3() { return &___worldTransform_3; } inline void set_worldTransform_3(Matrix4x4_t2933234003 value) { ___worldTransform_3 = value; } inline static int32_t get_offset_of_anchor_4() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___anchor_4)); } inline intptr_t get_anchor_4() const { return ___anchor_4; } inline intptr_t* get_address_of_anchor_4() { return &___anchor_4; } inline void set_anchor_4(intptr_t value) { ___anchor_4 = value; } inline static int32_t get_offset_of_isValid_5() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___isValid_5)); } inline bool get_isValid_5() const { return ___isValid_5; } inline bool* get_address_of_isValid_5() { return &___isValid_5; } inline void set_isValid_5(bool value) { ___isValid_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.XR.iOS.UnityARHitTestResult struct UnityARHitTestResult_t4129824344_marshaled_pinvoke { int64_t ___type_0; double ___distance_1; Matrix4x4_t2933234003 ___localTransform_2; Matrix4x4_t2933234003 ___worldTransform_3; intptr_t ___anchor_4; int32_t ___isValid_5; }; // Native definition for COM marshalling of UnityEngine.XR.iOS.UnityARHitTestResult struct UnityARHitTestResult_t4129824344_marshaled_com { int64_t ___type_0; double ___distance_1; Matrix4x4_t2933234003 ___localTransform_2; Matrix4x4_t2933234003 ___worldTransform_3; intptr_t ___anchor_4; int32_t ___isValid_5; }; #endif // UNITYARHITTESTRESULT_T4129824344_H #ifndef SCRIPTABLEOBJECT_T1975622470_H #define SCRIPTABLEOBJECT_T1975622470_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ScriptableObject struct ScriptableObject_t1975622470 : public Object_t1021602117 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.ScriptableObject struct ScriptableObject_t1975622470_marshaled_pinvoke : public Object_t1021602117_marshaled_pinvoke { }; // Native definition for COM marshalling of UnityEngine.ScriptableObject struct ScriptableObject_t1975622470_marshaled_com : public Object_t1021602117_marshaled_com { }; #endif // SCRIPTABLEOBJECT_T1975622470_H #ifndef UNITYARUSERANCHORDATA_T2645079618_H #define UNITYARUSERANCHORDATA_T2645079618_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARUserAnchorData struct UnityARUserAnchorData_t2645079618 { public: // System.IntPtr UnityEngine.XR.iOS.UnityARUserAnchorData::ptrIdentifier intptr_t ___ptrIdentifier_0; // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARUserAnchorData::transform UnityARMatrix4x4_t100931615 ___transform_1; public: inline static int32_t get_offset_of_ptrIdentifier_0() { return static_cast<int32_t>(offsetof(UnityARUserAnchorData_t2645079618, ___ptrIdentifier_0)); } inline intptr_t get_ptrIdentifier_0() const { return ___ptrIdentifier_0; } inline intptr_t* get_address_of_ptrIdentifier_0() { return &___ptrIdentifier_0; } inline void set_ptrIdentifier_0(intptr_t value) { ___ptrIdentifier_0 = value; } inline static int32_t get_offset_of_transform_1() { return static_cast<int32_t>(offsetof(UnityARUserAnchorData_t2645079618, ___transform_1)); } inline UnityARMatrix4x4_t100931615 get_transform_1() const { return ___transform_1; } inline UnityARMatrix4x4_t100931615 * get_address_of_transform_1() { return &___transform_1; } inline void set_transform_1(UnityARMatrix4x4_t100931615 value) { ___transform_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARUSERANCHORDATA_T2645079618_H #ifndef ARCAMERA_T4158705974_H #define ARCAMERA_T4158705974_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARCamera struct ARCamera_t4158705974 { public: // UnityEngine.Matrix4x4 UnityEngine.XR.iOS.ARCamera::worldTransform Matrix4x4_t2933234003 ___worldTransform_0; // UnityEngine.Vector3 UnityEngine.XR.iOS.ARCamera::eulerAngles Vector3_t2243707580 ___eulerAngles_1; // UnityEngine.XR.iOS.ARTrackingQuality UnityEngine.XR.iOS.ARCamera::trackingQuality int64_t ___trackingQuality_2; // UnityEngine.Vector3 UnityEngine.XR.iOS.ARCamera::intrinsics_row1 Vector3_t2243707580 ___intrinsics_row1_3; // UnityEngine.Vector3 UnityEngine.XR.iOS.ARCamera::intrinsics_row2 Vector3_t2243707580 ___intrinsics_row2_4; // UnityEngine.Vector3 UnityEngine.XR.iOS.ARCamera::intrinsics_row3 Vector3_t2243707580 ___intrinsics_row3_5; // UnityEngine.XR.iOS.ARSize UnityEngine.XR.iOS.ARCamera::imageResolution ARSize_t3911821096 ___imageResolution_6; public: inline static int32_t get_offset_of_worldTransform_0() { return static_cast<int32_t>(offsetof(ARCamera_t4158705974, ___worldTransform_0)); } inline Matrix4x4_t2933234003 get_worldTransform_0() const { return ___worldTransform_0; } inline Matrix4x4_t2933234003 * get_address_of_worldTransform_0() { return &___worldTransform_0; } inline void set_worldTransform_0(Matrix4x4_t2933234003 value) { ___worldTransform_0 = value; } inline static int32_t get_offset_of_eulerAngles_1() { return static_cast<int32_t>(offsetof(ARCamera_t4158705974, ___eulerAngles_1)); } inline Vector3_t2243707580 get_eulerAngles_1() const { return ___eulerAngles_1; } inline Vector3_t2243707580 * get_address_of_eulerAngles_1() { return &___eulerAngles_1; } inline void set_eulerAngles_1(Vector3_t2243707580 value) { ___eulerAngles_1 = value; } inline static int32_t get_offset_of_trackingQuality_2() { return static_cast<int32_t>(offsetof(ARCamera_t4158705974, ___trackingQuality_2)); } inline int64_t get_trackingQuality_2() const { return ___trackingQuality_2; } inline int64_t* get_address_of_trackingQuality_2() { return &___trackingQuality_2; } inline void set_trackingQuality_2(int64_t value) { ___trackingQuality_2 = value; } inline static int32_t get_offset_of_intrinsics_row1_3() { return static_cast<int32_t>(offsetof(ARCamera_t4158705974, ___intrinsics_row1_3)); } inline Vector3_t2243707580 get_intrinsics_row1_3() const { return ___intrinsics_row1_3; } inline Vector3_t2243707580 * get_address_of_intrinsics_row1_3() { return &___intrinsics_row1_3; } inline void set_intrinsics_row1_3(Vector3_t2243707580 value) { ___intrinsics_row1_3 = value; } inline static int32_t get_offset_of_intrinsics_row2_4() { return static_cast<int32_t>(offsetof(ARCamera_t4158705974, ___intrinsics_row2_4)); } inline Vector3_t2243707580 get_intrinsics_row2_4() const { return ___intrinsics_row2_4; } inline Vector3_t2243707580 * get_address_of_intrinsics_row2_4() { return &___intrinsics_row2_4; } inline void set_intrinsics_row2_4(Vector3_t2243707580 value) { ___intrinsics_row2_4 = value; } inline static int32_t get_offset_of_intrinsics_row3_5() { return static_cast<int32_t>(offsetof(ARCamera_t4158705974, ___intrinsics_row3_5)); } inline Vector3_t2243707580 get_intrinsics_row3_5() const { return ___intrinsics_row3_5; } inline Vector3_t2243707580 * get_address_of_intrinsics_row3_5() { return &___intrinsics_row3_5; } inline void set_intrinsics_row3_5(Vector3_t2243707580 value) { ___intrinsics_row3_5 = value; } inline static int32_t get_offset_of_imageResolution_6() { return static_cast<int32_t>(offsetof(ARCamera_t4158705974, ___imageResolution_6)); } inline ARSize_t3911821096 get_imageResolution_6() const { return ___imageResolution_6; } inline ARSize_t3911821096 * get_address_of_imageResolution_6() { return &___imageResolution_6; } inline void set_imageResolution_6(ARSize_t3911821096 value) { ___imageResolution_6 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARCAMERA_T4158705974_H #ifndef ARKITWORLDTRACKINGSESSIONCONFIGURATION_T1371796706_H #define ARKITWORLDTRACKINGSESSIONCONFIGURATION_T1371796706_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration struct ARKitWorldTrackingSessionConfiguration_t1371796706 { public: // UnityEngine.XR.iOS.UnityARAlignment UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::alignment int32_t ___alignment_0; // UnityEngine.XR.iOS.UnityARPlaneDetection UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::planeDetection int32_t ___planeDetection_1; // System.Boolean UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::getPointCloudData bool ___getPointCloudData_2; // System.Boolean UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::enableLightEstimation bool ___enableLightEstimation_3; // System.Boolean UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::enableAutoFocus bool ___enableAutoFocus_4; // UnityEngine.XR.iOS.UnityAREnvironmentTexturing UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::environmentTexturing int32_t ___environmentTexturing_5; // System.Int32 UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::maximumNumberOfTrackedImages int32_t ___maximumNumberOfTrackedImages_6; // System.IntPtr UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::videoFormat intptr_t ___videoFormat_7; // System.String UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::referenceImagesGroupName String_t* ___referenceImagesGroupName_8; // System.String UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::referenceObjectsGroupName String_t* ___referenceObjectsGroupName_9; // System.IntPtr UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::dynamicReferenceObjectsPtr intptr_t ___dynamicReferenceObjectsPtr_10; // System.IntPtr UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration::m_worldMapPtr intptr_t ___m_worldMapPtr_11; public: inline static int32_t get_offset_of_alignment_0() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___alignment_0)); } inline int32_t get_alignment_0() const { return ___alignment_0; } inline int32_t* get_address_of_alignment_0() { return &___alignment_0; } inline void set_alignment_0(int32_t value) { ___alignment_0 = value; } inline static int32_t get_offset_of_planeDetection_1() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___planeDetection_1)); } inline int32_t get_planeDetection_1() const { return ___planeDetection_1; } inline int32_t* get_address_of_planeDetection_1() { return &___planeDetection_1; } inline void set_planeDetection_1(int32_t value) { ___planeDetection_1 = value; } inline static int32_t get_offset_of_getPointCloudData_2() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___getPointCloudData_2)); } inline bool get_getPointCloudData_2() const { return ___getPointCloudData_2; } inline bool* get_address_of_getPointCloudData_2() { return &___getPointCloudData_2; } inline void set_getPointCloudData_2(bool value) { ___getPointCloudData_2 = value; } inline static int32_t get_offset_of_enableLightEstimation_3() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___enableLightEstimation_3)); } inline bool get_enableLightEstimation_3() const { return ___enableLightEstimation_3; } inline bool* get_address_of_enableLightEstimation_3() { return &___enableLightEstimation_3; } inline void set_enableLightEstimation_3(bool value) { ___enableLightEstimation_3 = value; } inline static int32_t get_offset_of_enableAutoFocus_4() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___enableAutoFocus_4)); } inline bool get_enableAutoFocus_4() const { return ___enableAutoFocus_4; } inline bool* get_address_of_enableAutoFocus_4() { return &___enableAutoFocus_4; } inline void set_enableAutoFocus_4(bool value) { ___enableAutoFocus_4 = value; } inline static int32_t get_offset_of_environmentTexturing_5() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___environmentTexturing_5)); } inline int32_t get_environmentTexturing_5() const { return ___environmentTexturing_5; } inline int32_t* get_address_of_environmentTexturing_5() { return &___environmentTexturing_5; } inline void set_environmentTexturing_5(int32_t value) { ___environmentTexturing_5 = value; } inline static int32_t get_offset_of_maximumNumberOfTrackedImages_6() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___maximumNumberOfTrackedImages_6)); } inline int32_t get_maximumNumberOfTrackedImages_6() const { return ___maximumNumberOfTrackedImages_6; } inline int32_t* get_address_of_maximumNumberOfTrackedImages_6() { return &___maximumNumberOfTrackedImages_6; } inline void set_maximumNumberOfTrackedImages_6(int32_t value) { ___maximumNumberOfTrackedImages_6 = value; } inline static int32_t get_offset_of_videoFormat_7() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___videoFormat_7)); } inline intptr_t get_videoFormat_7() const { return ___videoFormat_7; } inline intptr_t* get_address_of_videoFormat_7() { return &___videoFormat_7; } inline void set_videoFormat_7(intptr_t value) { ___videoFormat_7 = value; } inline static int32_t get_offset_of_referenceImagesGroupName_8() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___referenceImagesGroupName_8)); } inline String_t* get_referenceImagesGroupName_8() const { return ___referenceImagesGroupName_8; } inline String_t** get_address_of_referenceImagesGroupName_8() { return &___referenceImagesGroupName_8; } inline void set_referenceImagesGroupName_8(String_t* value) { ___referenceImagesGroupName_8 = value; Il2CppCodeGenWriteBarrier((&___referenceImagesGroupName_8), value); } inline static int32_t get_offset_of_referenceObjectsGroupName_9() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___referenceObjectsGroupName_9)); } inline String_t* get_referenceObjectsGroupName_9() const { return ___referenceObjectsGroupName_9; } inline String_t** get_address_of_referenceObjectsGroupName_9() { return &___referenceObjectsGroupName_9; } inline void set_referenceObjectsGroupName_9(String_t* value) { ___referenceObjectsGroupName_9 = value; Il2CppCodeGenWriteBarrier((&___referenceObjectsGroupName_9), value); } inline static int32_t get_offset_of_dynamicReferenceObjectsPtr_10() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___dynamicReferenceObjectsPtr_10)); } inline intptr_t get_dynamicReferenceObjectsPtr_10() const { return ___dynamicReferenceObjectsPtr_10; } inline intptr_t* get_address_of_dynamicReferenceObjectsPtr_10() { return &___dynamicReferenceObjectsPtr_10; } inline void set_dynamicReferenceObjectsPtr_10(intptr_t value) { ___dynamicReferenceObjectsPtr_10 = value; } inline static int32_t get_offset_of_m_worldMapPtr_11() { return static_cast<int32_t>(offsetof(ARKitWorldTrackingSessionConfiguration_t1371796706, ___m_worldMapPtr_11)); } inline intptr_t get_m_worldMapPtr_11() const { return ___m_worldMapPtr_11; } inline intptr_t* get_address_of_m_worldMapPtr_11() { return &___m_worldMapPtr_11; } inline void set_m_worldMapPtr_11(intptr_t value) { ___m_worldMapPtr_11 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration struct ARKitWorldTrackingSessionConfiguration_t1371796706_marshaled_pinvoke { int32_t ___alignment_0; int32_t ___planeDetection_1; int32_t ___getPointCloudData_2; int32_t ___enableLightEstimation_3; int32_t ___enableAutoFocus_4; int32_t ___environmentTexturing_5; int32_t ___maximumNumberOfTrackedImages_6; intptr_t ___videoFormat_7; char* ___referenceImagesGroupName_8; char* ___referenceObjectsGroupName_9; intptr_t ___dynamicReferenceObjectsPtr_10; intptr_t ___m_worldMapPtr_11; }; // Native definition for COM marshalling of UnityEngine.XR.iOS.ARKitWorldTrackingSessionConfiguration struct ARKitWorldTrackingSessionConfiguration_t1371796706_marshaled_com { int32_t ___alignment_0; int32_t ___planeDetection_1; int32_t ___getPointCloudData_2; int32_t ___enableLightEstimation_3; int32_t ___enableAutoFocus_4; int32_t ___environmentTexturing_5; int32_t ___maximumNumberOfTrackedImages_6; intptr_t ___videoFormat_7; Il2CppChar* ___referenceImagesGroupName_8; Il2CppChar* ___referenceObjectsGroupName_9; intptr_t ___dynamicReferenceObjectsPtr_10; intptr_t ___m_worldMapPtr_11; }; #endif // ARKITWORLDTRACKINGSESSIONCONFIGURATION_T1371796706_H #ifndef MULTICASTDELEGATE_T3201952435_H #define MULTICASTDELEGATE_T3201952435_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MulticastDelegate struct MulticastDelegate_t3201952435 : public Delegate_t3022476291 { public: // System.MulticastDelegate System.MulticastDelegate::prev MulticastDelegate_t3201952435 * ___prev_9; // System.MulticastDelegate System.MulticastDelegate::kpm_next MulticastDelegate_t3201952435 * ___kpm_next_10; public: inline static int32_t get_offset_of_prev_9() { return static_cast<int32_t>(offsetof(MulticastDelegate_t3201952435, ___prev_9)); } inline MulticastDelegate_t3201952435 * get_prev_9() const { return ___prev_9; } inline MulticastDelegate_t3201952435 ** get_address_of_prev_9() { return &___prev_9; } inline void set_prev_9(MulticastDelegate_t3201952435 * value) { ___prev_9 = value; Il2CppCodeGenWriteBarrier((&___prev_9), value); } inline static int32_t get_offset_of_kpm_next_10() { return static_cast<int32_t>(offsetof(MulticastDelegate_t3201952435, ___kpm_next_10)); } inline MulticastDelegate_t3201952435 * get_kpm_next_10() const { return ___kpm_next_10; } inline MulticastDelegate_t3201952435 ** get_address_of_kpm_next_10() { return &___kpm_next_10; } inline void set_kpm_next_10(MulticastDelegate_t3201952435 * value) { ___kpm_next_10 = value; Il2CppCodeGenWriteBarrier((&___kpm_next_10), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MULTICASTDELEGATE_T3201952435_H #ifndef ARKITSESSIONCONFIGURATION_T318899795_H #define ARKITSESSIONCONFIGURATION_T318899795_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARKitSessionConfiguration struct ARKitSessionConfiguration_t318899795 { public: // UnityEngine.XR.iOS.UnityARAlignment UnityEngine.XR.iOS.ARKitSessionConfiguration::alignment int32_t ___alignment_0; // System.Boolean UnityEngine.XR.iOS.ARKitSessionConfiguration::getPointCloudData bool ___getPointCloudData_1; // System.Boolean UnityEngine.XR.iOS.ARKitSessionConfiguration::enableLightEstimation bool ___enableLightEstimation_2; public: inline static int32_t get_offset_of_alignment_0() { return static_cast<int32_t>(offsetof(ARKitSessionConfiguration_t318899795, ___alignment_0)); } inline int32_t get_alignment_0() const { return ___alignment_0; } inline int32_t* get_address_of_alignment_0() { return &___alignment_0; } inline void set_alignment_0(int32_t value) { ___alignment_0 = value; } inline static int32_t get_offset_of_getPointCloudData_1() { return static_cast<int32_t>(offsetof(ARKitSessionConfiguration_t318899795, ___getPointCloudData_1)); } inline bool get_getPointCloudData_1() const { return ___getPointCloudData_1; } inline bool* get_address_of_getPointCloudData_1() { return &___getPointCloudData_1; } inline void set_getPointCloudData_1(bool value) { ___getPointCloudData_1 = value; } inline static int32_t get_offset_of_enableLightEstimation_2() { return static_cast<int32_t>(offsetof(ARKitSessionConfiguration_t318899795, ___enableLightEstimation_2)); } inline bool get_enableLightEstimation_2() const { return ___enableLightEstimation_2; } inline bool* get_address_of_enableLightEstimation_2() { return &___enableLightEstimation_2; } inline void set_enableLightEstimation_2(bool value) { ___enableLightEstimation_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.XR.iOS.ARKitSessionConfiguration struct ARKitSessionConfiguration_t318899795_marshaled_pinvoke { int32_t ___alignment_0; int32_t ___getPointCloudData_1; int32_t ___enableLightEstimation_2; }; // Native definition for COM marshalling of UnityEngine.XR.iOS.ARKitSessionConfiguration struct ARKitSessionConfiguration_t318899795_marshaled_com { int32_t ___alignment_0; int32_t ___getPointCloudData_1; int32_t ___enableLightEstimation_2; }; #endif // ARKITSESSIONCONFIGURATION_T318899795_H #ifndef ARKITFACETRACKINGCONFIGURATION_T2393628587_H #define ARKITFACETRACKINGCONFIGURATION_T2393628587_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARKitFaceTrackingConfiguration struct ARKitFaceTrackingConfiguration_t2393628587 { public: // UnityEngine.XR.iOS.UnityARAlignment UnityEngine.XR.iOS.ARKitFaceTrackingConfiguration::alignment int32_t ___alignment_0; // System.Boolean UnityEngine.XR.iOS.ARKitFaceTrackingConfiguration::enableLightEstimation bool ___enableLightEstimation_1; // System.IntPtr UnityEngine.XR.iOS.ARKitFaceTrackingConfiguration::videoFormat intptr_t ___videoFormat_2; public: inline static int32_t get_offset_of_alignment_0() { return static_cast<int32_t>(offsetof(ARKitFaceTrackingConfiguration_t2393628587, ___alignment_0)); } inline int32_t get_alignment_0() const { return ___alignment_0; } inline int32_t* get_address_of_alignment_0() { return &___alignment_0; } inline void set_alignment_0(int32_t value) { ___alignment_0 = value; } inline static int32_t get_offset_of_enableLightEstimation_1() { return static_cast<int32_t>(offsetof(ARKitFaceTrackingConfiguration_t2393628587, ___enableLightEstimation_1)); } inline bool get_enableLightEstimation_1() const { return ___enableLightEstimation_1; } inline bool* get_address_of_enableLightEstimation_1() { return &___enableLightEstimation_1; } inline void set_enableLightEstimation_1(bool value) { ___enableLightEstimation_1 = value; } inline static int32_t get_offset_of_videoFormat_2() { return static_cast<int32_t>(offsetof(ARKitFaceTrackingConfiguration_t2393628587, ___videoFormat_2)); } inline intptr_t get_videoFormat_2() const { return ___videoFormat_2; } inline intptr_t* get_address_of_videoFormat_2() { return &___videoFormat_2; } inline void set_videoFormat_2(intptr_t value) { ___videoFormat_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.XR.iOS.ARKitFaceTrackingConfiguration struct ARKitFaceTrackingConfiguration_t2393628587_marshaled_pinvoke { int32_t ___alignment_0; int32_t ___enableLightEstimation_1; intptr_t ___videoFormat_2; }; // Native definition for COM marshalling of UnityEngine.XR.iOS.ARKitFaceTrackingConfiguration struct ARKitFaceTrackingConfiguration_t2393628587_marshaled_com { int32_t ___alignment_0; int32_t ___enableLightEstimation_1; intptr_t ___videoFormat_2; }; #endif // ARKITFACETRACKINGCONFIGURATION_T2393628587_H #ifndef UNITYAROBJECTANCHORDATA_T938871002_H #define UNITYAROBJECTANCHORDATA_T938871002_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARObjectAnchorData struct UnityARObjectAnchorData_t938871002 { public: // System.IntPtr UnityEngine.XR.iOS.UnityARObjectAnchorData::ptrIdentifier intptr_t ___ptrIdentifier_0; // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARObjectAnchorData::transform UnityARMatrix4x4_t100931615 ___transform_1; // System.IntPtr UnityEngine.XR.iOS.UnityARObjectAnchorData::referenceObjectNamePtr intptr_t ___referenceObjectNamePtr_2; // System.IntPtr UnityEngine.XR.iOS.UnityARObjectAnchorData::referenceObjectPtr intptr_t ___referenceObjectPtr_3; public: inline static int32_t get_offset_of_ptrIdentifier_0() { return static_cast<int32_t>(offsetof(UnityARObjectAnchorData_t938871002, ___ptrIdentifier_0)); } inline intptr_t get_ptrIdentifier_0() const { return ___ptrIdentifier_0; } inline intptr_t* get_address_of_ptrIdentifier_0() { return &___ptrIdentifier_0; } inline void set_ptrIdentifier_0(intptr_t value) { ___ptrIdentifier_0 = value; } inline static int32_t get_offset_of_transform_1() { return static_cast<int32_t>(offsetof(UnityARObjectAnchorData_t938871002, ___transform_1)); } inline UnityARMatrix4x4_t100931615 get_transform_1() const { return ___transform_1; } inline UnityARMatrix4x4_t100931615 * get_address_of_transform_1() { return &___transform_1; } inline void set_transform_1(UnityARMatrix4x4_t100931615 value) { ___transform_1 = value; } inline static int32_t get_offset_of_referenceObjectNamePtr_2() { return static_cast<int32_t>(offsetof(UnityARObjectAnchorData_t938871002, ___referenceObjectNamePtr_2)); } inline intptr_t get_referenceObjectNamePtr_2() const { return ___referenceObjectNamePtr_2; } inline intptr_t* get_address_of_referenceObjectNamePtr_2() { return &___referenceObjectNamePtr_2; } inline void set_referenceObjectNamePtr_2(intptr_t value) { ___referenceObjectNamePtr_2 = value; } inline static int32_t get_offset_of_referenceObjectPtr_3() { return static_cast<int32_t>(offsetof(UnityARObjectAnchorData_t938871002, ___referenceObjectPtr_3)); } inline intptr_t get_referenceObjectPtr_3() const { return ___referenceObjectPtr_3; } inline intptr_t* get_address_of_referenceObjectPtr_3() { return &___referenceObjectPtr_3; } inline void set_referenceObjectPtr_3(intptr_t value) { ___referenceObjectPtr_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYAROBJECTANCHORDATA_T938871002_H #ifndef UNITYARLIGHTDATA_T1178200316_H #define UNITYARLIGHTDATA_T1178200316_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARLightData struct UnityARLightData_t1178200316 { public: // UnityEngine.XR.iOS.LightDataType UnityEngine.XR.iOS.UnityARLightData::arLightingType int32_t ___arLightingType_0; // UnityEngine.XR.iOS.UnityARLightEstimate UnityEngine.XR.iOS.UnityARLightData::arLightEstimate UnityARLightEstimate_t311267890 ___arLightEstimate_1; // UnityEngine.XR.iOS.UnityARDirectionalLightEstimate UnityEngine.XR.iOS.UnityARLightData::arDirectonalLightEstimate UnityARDirectionalLightEstimate_t1689150542 * ___arDirectonalLightEstimate_2; public: inline static int32_t get_offset_of_arLightingType_0() { return static_cast<int32_t>(offsetof(UnityARLightData_t1178200316, ___arLightingType_0)); } inline int32_t get_arLightingType_0() const { return ___arLightingType_0; } inline int32_t* get_address_of_arLightingType_0() { return &___arLightingType_0; } inline void set_arLightingType_0(int32_t value) { ___arLightingType_0 = value; } inline static int32_t get_offset_of_arLightEstimate_1() { return static_cast<int32_t>(offsetof(UnityARLightData_t1178200316, ___arLightEstimate_1)); } inline UnityARLightEstimate_t311267890 get_arLightEstimate_1() const { return ___arLightEstimate_1; } inline UnityARLightEstimate_t311267890 * get_address_of_arLightEstimate_1() { return &___arLightEstimate_1; } inline void set_arLightEstimate_1(UnityARLightEstimate_t311267890 value) { ___arLightEstimate_1 = value; } inline static int32_t get_offset_of_arDirectonalLightEstimate_2() { return static_cast<int32_t>(offsetof(UnityARLightData_t1178200316, ___arDirectonalLightEstimate_2)); } inline UnityARDirectionalLightEstimate_t1689150542 * get_arDirectonalLightEstimate_2() const { return ___arDirectonalLightEstimate_2; } inline UnityARDirectionalLightEstimate_t1689150542 ** get_address_of_arDirectonalLightEstimate_2() { return &___arDirectonalLightEstimate_2; } inline void set_arDirectonalLightEstimate_2(UnityARDirectionalLightEstimate_t1689150542 * value) { ___arDirectonalLightEstimate_2 = value; Il2CppCodeGenWriteBarrier((&___arDirectonalLightEstimate_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.XR.iOS.UnityARLightData struct UnityARLightData_t1178200316_marshaled_pinvoke { int32_t ___arLightingType_0; UnityARLightEstimate_t311267890 ___arLightEstimate_1; UnityARDirectionalLightEstimate_t1689150542 * ___arDirectonalLightEstimate_2; }; // Native definition for COM marshalling of UnityEngine.XR.iOS.UnityARLightData struct UnityARLightData_t1178200316_marshaled_com { int32_t ___arLightingType_0; UnityARLightEstimate_t311267890 ___arLightEstimate_1; UnityARDirectionalLightEstimate_t1689150542 * ___arDirectonalLightEstimate_2; }; #endif // UNITYARLIGHTDATA_T1178200316_H #ifndef UNITYMARSHALLIGHTDATA_T3773526525_H #define UNITYMARSHALLIGHTDATA_T3773526525_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityMarshalLightData struct UnityMarshalLightData_t3773526525 { public: // UnityEngine.XR.iOS.LightDataType UnityEngine.XR.iOS.UnityMarshalLightData::arLightingType int32_t ___arLightingType_0; // UnityEngine.XR.iOS.UnityARLightEstimate UnityEngine.XR.iOS.UnityMarshalLightData::arLightEstimate UnityARLightEstimate_t311267890 ___arLightEstimate_1; // UnityEngine.XR.iOS.MarshalDirectionalLightEstimate UnityEngine.XR.iOS.UnityMarshalLightData::arDirectonalLightEstimate MarshalDirectionalLightEstimate_t3614627546 ___arDirectonalLightEstimate_2; public: inline static int32_t get_offset_of_arLightingType_0() { return static_cast<int32_t>(offsetof(UnityMarshalLightData_t3773526525, ___arLightingType_0)); } inline int32_t get_arLightingType_0() const { return ___arLightingType_0; } inline int32_t* get_address_of_arLightingType_0() { return &___arLightingType_0; } inline void set_arLightingType_0(int32_t value) { ___arLightingType_0 = value; } inline static int32_t get_offset_of_arLightEstimate_1() { return static_cast<int32_t>(offsetof(UnityMarshalLightData_t3773526525, ___arLightEstimate_1)); } inline UnityARLightEstimate_t311267890 get_arLightEstimate_1() const { return ___arLightEstimate_1; } inline UnityARLightEstimate_t311267890 * get_address_of_arLightEstimate_1() { return &___arLightEstimate_1; } inline void set_arLightEstimate_1(UnityARLightEstimate_t311267890 value) { ___arLightEstimate_1 = value; } inline static int32_t get_offset_of_arDirectonalLightEstimate_2() { return static_cast<int32_t>(offsetof(UnityMarshalLightData_t3773526525, ___arDirectonalLightEstimate_2)); } inline MarshalDirectionalLightEstimate_t3614627546 get_arDirectonalLightEstimate_2() const { return ___arDirectonalLightEstimate_2; } inline MarshalDirectionalLightEstimate_t3614627546 * get_address_of_arDirectonalLightEstimate_2() { return &___arDirectonalLightEstimate_2; } inline void set_arDirectonalLightEstimate_2(MarshalDirectionalLightEstimate_t3614627546 value) { ___arDirectonalLightEstimate_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYMARSHALLIGHTDATA_T3773526525_H #ifndef UNITYARIMAGEANCHORDATA_T29968876_H #define UNITYARIMAGEANCHORDATA_T29968876_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARImageAnchorData struct UnityARImageAnchorData_t29968876 { public: // System.IntPtr UnityEngine.XR.iOS.UnityARImageAnchorData::ptrIdentifier intptr_t ___ptrIdentifier_0; // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARImageAnchorData::transform UnityARMatrix4x4_t100931615 ___transform_1; // System.IntPtr UnityEngine.XR.iOS.UnityARImageAnchorData::referenceImageNamePtr intptr_t ___referenceImageNamePtr_2; // System.Single UnityEngine.XR.iOS.UnityARImageAnchorData::referenceImagePhysicalSize float ___referenceImagePhysicalSize_3; // System.Int32 UnityEngine.XR.iOS.UnityARImageAnchorData::isTracked int32_t ___isTracked_4; public: inline static int32_t get_offset_of_ptrIdentifier_0() { return static_cast<int32_t>(offsetof(UnityARImageAnchorData_t29968876, ___ptrIdentifier_0)); } inline intptr_t get_ptrIdentifier_0() const { return ___ptrIdentifier_0; } inline intptr_t* get_address_of_ptrIdentifier_0() { return &___ptrIdentifier_0; } inline void set_ptrIdentifier_0(intptr_t value) { ___ptrIdentifier_0 = value; } inline static int32_t get_offset_of_transform_1() { return static_cast<int32_t>(offsetof(UnityARImageAnchorData_t29968876, ___transform_1)); } inline UnityARMatrix4x4_t100931615 get_transform_1() const { return ___transform_1; } inline UnityARMatrix4x4_t100931615 * get_address_of_transform_1() { return &___transform_1; } inline void set_transform_1(UnityARMatrix4x4_t100931615 value) { ___transform_1 = value; } inline static int32_t get_offset_of_referenceImageNamePtr_2() { return static_cast<int32_t>(offsetof(UnityARImageAnchorData_t29968876, ___referenceImageNamePtr_2)); } inline intptr_t get_referenceImageNamePtr_2() const { return ___referenceImageNamePtr_2; } inline intptr_t* get_address_of_referenceImageNamePtr_2() { return &___referenceImageNamePtr_2; } inline void set_referenceImageNamePtr_2(intptr_t value) { ___referenceImageNamePtr_2 = value; } inline static int32_t get_offset_of_referenceImagePhysicalSize_3() { return static_cast<int32_t>(offsetof(UnityARImageAnchorData_t29968876, ___referenceImagePhysicalSize_3)); } inline float get_referenceImagePhysicalSize_3() const { return ___referenceImagePhysicalSize_3; } inline float* get_address_of_referenceImagePhysicalSize_3() { return &___referenceImagePhysicalSize_3; } inline void set_referenceImagePhysicalSize_3(float value) { ___referenceImagePhysicalSize_3 = value; } inline static int32_t get_offset_of_isTracked_4() { return static_cast<int32_t>(offsetof(UnityARImageAnchorData_t29968876, ___isTracked_4)); } inline int32_t get_isTracked_4() const { return ___isTracked_4; } inline int32_t* get_address_of_isTracked_4() { return &___isTracked_4; } inline void set_isTracked_4(int32_t value) { ___isTracked_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARIMAGEANCHORDATA_T29968876_H #ifndef ARHITTESTRESULT_T3275513025_H #define ARHITTESTRESULT_T3275513025_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARHitTestResult struct ARHitTestResult_t3275513025 { public: // UnityEngine.XR.iOS.ARHitTestResultType UnityEngine.XR.iOS.ARHitTestResult::type int64_t ___type_0; // System.Double UnityEngine.XR.iOS.ARHitTestResult::distance double ___distance_1; // UnityEngine.Matrix4x4 UnityEngine.XR.iOS.ARHitTestResult::localTransform Matrix4x4_t2933234003 ___localTransform_2; // UnityEngine.Matrix4x4 UnityEngine.XR.iOS.ARHitTestResult::worldTransform Matrix4x4_t2933234003 ___worldTransform_3; // System.String UnityEngine.XR.iOS.ARHitTestResult::anchorIdentifier String_t* ___anchorIdentifier_4; // System.Boolean UnityEngine.XR.iOS.ARHitTestResult::isValid bool ___isValid_5; public: inline static int32_t get_offset_of_type_0() { return static_cast<int32_t>(offsetof(ARHitTestResult_t3275513025, ___type_0)); } inline int64_t get_type_0() const { return ___type_0; } inline int64_t* get_address_of_type_0() { return &___type_0; } inline void set_type_0(int64_t value) { ___type_0 = value; } inline static int32_t get_offset_of_distance_1() { return static_cast<int32_t>(offsetof(ARHitTestResult_t3275513025, ___distance_1)); } inline double get_distance_1() const { return ___distance_1; } inline double* get_address_of_distance_1() { return &___distance_1; } inline void set_distance_1(double value) { ___distance_1 = value; } inline static int32_t get_offset_of_localTransform_2() { return static_cast<int32_t>(offsetof(ARHitTestResult_t3275513025, ___localTransform_2)); } inline Matrix4x4_t2933234003 get_localTransform_2() const { return ___localTransform_2; } inline Matrix4x4_t2933234003 * get_address_of_localTransform_2() { return &___localTransform_2; } inline void set_localTransform_2(Matrix4x4_t2933234003 value) { ___localTransform_2 = value; } inline static int32_t get_offset_of_worldTransform_3() { return static_cast<int32_t>(offsetof(ARHitTestResult_t3275513025, ___worldTransform_3)); } inline Matrix4x4_t2933234003 get_worldTransform_3() const { return ___worldTransform_3; } inline Matrix4x4_t2933234003 * get_address_of_worldTransform_3() { return &___worldTransform_3; } inline void set_worldTransform_3(Matrix4x4_t2933234003 value) { ___worldTransform_3 = value; } inline static int32_t get_offset_of_anchorIdentifier_4() { return static_cast<int32_t>(offsetof(ARHitTestResult_t3275513025, ___anchorIdentifier_4)); } inline String_t* get_anchorIdentifier_4() const { return ___anchorIdentifier_4; } inline String_t** get_address_of_anchorIdentifier_4() { return &___anchorIdentifier_4; } inline void set_anchorIdentifier_4(String_t* value) { ___anchorIdentifier_4 = value; Il2CppCodeGenWriteBarrier((&___anchorIdentifier_4), value); } inline static int32_t get_offset_of_isValid_5() { return static_cast<int32_t>(offsetof(ARHitTestResult_t3275513025, ___isValid_5)); } inline bool get_isValid_5() const { return ___isValid_5; } inline bool* get_address_of_isValid_5() { return &___isValid_5; } inline void set_isValid_5(bool value) { ___isValid_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.XR.iOS.ARHitTestResult struct ARHitTestResult_t3275513025_marshaled_pinvoke { int64_t ___type_0; double ___distance_1; Matrix4x4_t2933234003 ___localTransform_2; Matrix4x4_t2933234003 ___worldTransform_3; char* ___anchorIdentifier_4; int32_t ___isValid_5; }; // Native definition for COM marshalling of UnityEngine.XR.iOS.ARHitTestResult struct ARHitTestResult_t3275513025_marshaled_com { int64_t ___type_0; double ___distance_1; Matrix4x4_t2933234003 ___localTransform_2; Matrix4x4_t2933234003 ___worldTransform_3; Il2CppChar* ___anchorIdentifier_4; int32_t ___isValid_5; }; #endif // ARHITTESTRESULT_T3275513025_H #ifndef ARFACEGEOMETRY_T2928150040_H #define ARFACEGEOMETRY_T2928150040_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARFaceGeometry struct ARFaceGeometry_t2928150040 : public RuntimeObject { public: // UnityEngine.XR.iOS.UnityARFaceGeometry UnityEngine.XR.iOS.ARFaceGeometry::<uFaceGeometry>k__BackingField UnityARFaceGeometry_t49674351 ___U3CuFaceGeometryU3Ek__BackingField_0; // UnityEngine.Vector3[] UnityEngine.XR.iOS.ARFaceGeometry::m_Vertices Vector3U5BU5D_t1172311765* ___m_Vertices_1; // UnityEngine.Vector2[] UnityEngine.XR.iOS.ARFaceGeometry::m_TextureCoordinates Vector2U5BU5D_t686124026* ___m_TextureCoordinates_2; // System.Int32[] UnityEngine.XR.iOS.ARFaceGeometry::m_TriangleIndices Int32U5BU5D_t3030399641* ___m_TriangleIndices_3; // System.Single[] UnityEngine.XR.iOS.ARFaceGeometry::m_WorkVertices SingleU5BU5D_t577127397* ___m_WorkVertices_4; // System.Single[] UnityEngine.XR.iOS.ARFaceGeometry::m_WorkTextureCoordinates SingleU5BU5D_t577127397* ___m_WorkTextureCoordinates_5; // System.Int16[] UnityEngine.XR.iOS.ARFaceGeometry::m_WorkIndices Int16U5BU5D_t3104283263* ___m_WorkIndices_6; // System.Int32 UnityEngine.XR.iOS.ARFaceGeometry::m_VertexCount int32_t ___m_VertexCount_7; // System.Int32 UnityEngine.XR.iOS.ARFaceGeometry::m_TextureCoordinateCount int32_t ___m_TextureCoordinateCount_8; // System.Int32 UnityEngine.XR.iOS.ARFaceGeometry::m_TriangleCount int32_t ___m_TriangleCount_9; // System.Int32 UnityEngine.XR.iOS.ARFaceGeometry::m_IndexCount int32_t ___m_IndexCount_10; // System.Int32 UnityEngine.XR.iOS.ARFaceGeometry::m_WorkVertexCount int32_t ___m_WorkVertexCount_11; // System.Int32 UnityEngine.XR.iOS.ARFaceGeometry::m_WorkTextureCoordinateCount int32_t ___m_WorkTextureCoordinateCount_12; public: inline static int32_t get_offset_of_U3CuFaceGeometryU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___U3CuFaceGeometryU3Ek__BackingField_0)); } inline UnityARFaceGeometry_t49674351 get_U3CuFaceGeometryU3Ek__BackingField_0() const { return ___U3CuFaceGeometryU3Ek__BackingField_0; } inline UnityARFaceGeometry_t49674351 * get_address_of_U3CuFaceGeometryU3Ek__BackingField_0() { return &___U3CuFaceGeometryU3Ek__BackingField_0; } inline void set_U3CuFaceGeometryU3Ek__BackingField_0(UnityARFaceGeometry_t49674351 value) { ___U3CuFaceGeometryU3Ek__BackingField_0 = value; } inline static int32_t get_offset_of_m_Vertices_1() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_Vertices_1)); } inline Vector3U5BU5D_t1172311765* get_m_Vertices_1() const { return ___m_Vertices_1; } inline Vector3U5BU5D_t1172311765** get_address_of_m_Vertices_1() { return &___m_Vertices_1; } inline void set_m_Vertices_1(Vector3U5BU5D_t1172311765* value) { ___m_Vertices_1 = value; Il2CppCodeGenWriteBarrier((&___m_Vertices_1), value); } inline static int32_t get_offset_of_m_TextureCoordinates_2() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_TextureCoordinates_2)); } inline Vector2U5BU5D_t686124026* get_m_TextureCoordinates_2() const { return ___m_TextureCoordinates_2; } inline Vector2U5BU5D_t686124026** get_address_of_m_TextureCoordinates_2() { return &___m_TextureCoordinates_2; } inline void set_m_TextureCoordinates_2(Vector2U5BU5D_t686124026* value) { ___m_TextureCoordinates_2 = value; Il2CppCodeGenWriteBarrier((&___m_TextureCoordinates_2), value); } inline static int32_t get_offset_of_m_TriangleIndices_3() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_TriangleIndices_3)); } inline Int32U5BU5D_t3030399641* get_m_TriangleIndices_3() const { return ___m_TriangleIndices_3; } inline Int32U5BU5D_t3030399641** get_address_of_m_TriangleIndices_3() { return &___m_TriangleIndices_3; } inline void set_m_TriangleIndices_3(Int32U5BU5D_t3030399641* value) { ___m_TriangleIndices_3 = value; Il2CppCodeGenWriteBarrier((&___m_TriangleIndices_3), value); } inline static int32_t get_offset_of_m_WorkVertices_4() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_WorkVertices_4)); } inline SingleU5BU5D_t577127397* get_m_WorkVertices_4() const { return ___m_WorkVertices_4; } inline SingleU5BU5D_t577127397** get_address_of_m_WorkVertices_4() { return &___m_WorkVertices_4; } inline void set_m_WorkVertices_4(SingleU5BU5D_t577127397* value) { ___m_WorkVertices_4 = value; Il2CppCodeGenWriteBarrier((&___m_WorkVertices_4), value); } inline static int32_t get_offset_of_m_WorkTextureCoordinates_5() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_WorkTextureCoordinates_5)); } inline SingleU5BU5D_t577127397* get_m_WorkTextureCoordinates_5() const { return ___m_WorkTextureCoordinates_5; } inline SingleU5BU5D_t577127397** get_address_of_m_WorkTextureCoordinates_5() { return &___m_WorkTextureCoordinates_5; } inline void set_m_WorkTextureCoordinates_5(SingleU5BU5D_t577127397* value) { ___m_WorkTextureCoordinates_5 = value; Il2CppCodeGenWriteBarrier((&___m_WorkTextureCoordinates_5), value); } inline static int32_t get_offset_of_m_WorkIndices_6() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_WorkIndices_6)); } inline Int16U5BU5D_t3104283263* get_m_WorkIndices_6() const { return ___m_WorkIndices_6; } inline Int16U5BU5D_t3104283263** get_address_of_m_WorkIndices_6() { return &___m_WorkIndices_6; } inline void set_m_WorkIndices_6(Int16U5BU5D_t3104283263* value) { ___m_WorkIndices_6 = value; Il2CppCodeGenWriteBarrier((&___m_WorkIndices_6), value); } inline static int32_t get_offset_of_m_VertexCount_7() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_VertexCount_7)); } inline int32_t get_m_VertexCount_7() const { return ___m_VertexCount_7; } inline int32_t* get_address_of_m_VertexCount_7() { return &___m_VertexCount_7; } inline void set_m_VertexCount_7(int32_t value) { ___m_VertexCount_7 = value; } inline static int32_t get_offset_of_m_TextureCoordinateCount_8() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_TextureCoordinateCount_8)); } inline int32_t get_m_TextureCoordinateCount_8() const { return ___m_TextureCoordinateCount_8; } inline int32_t* get_address_of_m_TextureCoordinateCount_8() { return &___m_TextureCoordinateCount_8; } inline void set_m_TextureCoordinateCount_8(int32_t value) { ___m_TextureCoordinateCount_8 = value; } inline static int32_t get_offset_of_m_TriangleCount_9() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_TriangleCount_9)); } inline int32_t get_m_TriangleCount_9() const { return ___m_TriangleCount_9; } inline int32_t* get_address_of_m_TriangleCount_9() { return &___m_TriangleCount_9; } inline void set_m_TriangleCount_9(int32_t value) { ___m_TriangleCount_9 = value; } inline static int32_t get_offset_of_m_IndexCount_10() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_IndexCount_10)); } inline int32_t get_m_IndexCount_10() const { return ___m_IndexCount_10; } inline int32_t* get_address_of_m_IndexCount_10() { return &___m_IndexCount_10; } inline void set_m_IndexCount_10(int32_t value) { ___m_IndexCount_10 = value; } inline static int32_t get_offset_of_m_WorkVertexCount_11() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_WorkVertexCount_11)); } inline int32_t get_m_WorkVertexCount_11() const { return ___m_WorkVertexCount_11; } inline int32_t* get_address_of_m_WorkVertexCount_11() { return &___m_WorkVertexCount_11; } inline void set_m_WorkVertexCount_11(int32_t value) { ___m_WorkVertexCount_11 = value; } inline static int32_t get_offset_of_m_WorkTextureCoordinateCount_12() { return static_cast<int32_t>(offsetof(ARFaceGeometry_t2928150040, ___m_WorkTextureCoordinateCount_12)); } inline int32_t get_m_WorkTextureCoordinateCount_12() const { return ___m_WorkTextureCoordinateCount_12; } inline int32_t* get_address_of_m_WorkTextureCoordinateCount_12() { return &___m_WorkTextureCoordinateCount_12; } inline void set_m_WorkTextureCoordinateCount_12(int32_t value) { ___m_WorkTextureCoordinateCount_12 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARFACEGEOMETRY_T2928150040_H #ifndef UNITYARFACEANCHORDATA_T2991923452_H #define UNITYARFACEANCHORDATA_T2991923452_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARFaceAnchorData struct UnityARFaceAnchorData_t2991923452 { public: // System.IntPtr UnityEngine.XR.iOS.UnityARFaceAnchorData::ptrIdentifier intptr_t ___ptrIdentifier_0; // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARFaceAnchorData::transform UnityARMatrix4x4_t100931615 ___transform_1; // UnityEngine.XR.iOS.UnityARFaceGeometry UnityEngine.XR.iOS.UnityARFaceAnchorData::faceGeometry UnityARFaceGeometry_t49674351 ___faceGeometry_2; // System.IntPtr UnityEngine.XR.iOS.UnityARFaceAnchorData::blendShapes intptr_t ___blendShapes_3; // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARFaceAnchorData::leftEyeTransform UnityARMatrix4x4_t100931615 ___leftEyeTransform_4; // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARFaceAnchorData::rightEyeTransform UnityARMatrix4x4_t100931615 ___rightEyeTransform_5; // UnityEngine.Vector3 UnityEngine.XR.iOS.UnityARFaceAnchorData::lookAtPoint Vector3_t2243707580 ___lookAtPoint_6; // System.Boolean UnityEngine.XR.iOS.UnityARFaceAnchorData::isTracked bool ___isTracked_7; public: inline static int32_t get_offset_of_ptrIdentifier_0() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2991923452, ___ptrIdentifier_0)); } inline intptr_t get_ptrIdentifier_0() const { return ___ptrIdentifier_0; } inline intptr_t* get_address_of_ptrIdentifier_0() { return &___ptrIdentifier_0; } inline void set_ptrIdentifier_0(intptr_t value) { ___ptrIdentifier_0 = value; } inline static int32_t get_offset_of_transform_1() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2991923452, ___transform_1)); } inline UnityARMatrix4x4_t100931615 get_transform_1() const { return ___transform_1; } inline UnityARMatrix4x4_t100931615 * get_address_of_transform_1() { return &___transform_1; } inline void set_transform_1(UnityARMatrix4x4_t100931615 value) { ___transform_1 = value; } inline static int32_t get_offset_of_faceGeometry_2() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2991923452, ___faceGeometry_2)); } inline UnityARFaceGeometry_t49674351 get_faceGeometry_2() const { return ___faceGeometry_2; } inline UnityARFaceGeometry_t49674351 * get_address_of_faceGeometry_2() { return &___faceGeometry_2; } inline void set_faceGeometry_2(UnityARFaceGeometry_t49674351 value) { ___faceGeometry_2 = value; } inline static int32_t get_offset_of_blendShapes_3() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2991923452, ___blendShapes_3)); } inline intptr_t get_blendShapes_3() const { return ___blendShapes_3; } inline intptr_t* get_address_of_blendShapes_3() { return &___blendShapes_3; } inline void set_blendShapes_3(intptr_t value) { ___blendShapes_3 = value; } inline static int32_t get_offset_of_leftEyeTransform_4() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2991923452, ___leftEyeTransform_4)); } inline UnityARMatrix4x4_t100931615 get_leftEyeTransform_4() const { return ___leftEyeTransform_4; } inline UnityARMatrix4x4_t100931615 * get_address_of_leftEyeTransform_4() { return &___leftEyeTransform_4; } inline void set_leftEyeTransform_4(UnityARMatrix4x4_t100931615 value) { ___leftEyeTransform_4 = value; } inline static int32_t get_offset_of_rightEyeTransform_5() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2991923452, ___rightEyeTransform_5)); } inline UnityARMatrix4x4_t100931615 get_rightEyeTransform_5() const { return ___rightEyeTransform_5; } inline UnityARMatrix4x4_t100931615 * get_address_of_rightEyeTransform_5() { return &___rightEyeTransform_5; } inline void set_rightEyeTransform_5(UnityARMatrix4x4_t100931615 value) { ___rightEyeTransform_5 = value; } inline static int32_t get_offset_of_lookAtPoint_6() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2991923452, ___lookAtPoint_6)); } inline Vector3_t2243707580 get_lookAtPoint_6() const { return ___lookAtPoint_6; } inline Vector3_t2243707580 * get_address_of_lookAtPoint_6() { return &___lookAtPoint_6; } inline void set_lookAtPoint_6(Vector3_t2243707580 value) { ___lookAtPoint_6 = value; } inline static int32_t get_offset_of_isTracked_7() { return static_cast<int32_t>(offsetof(UnityARFaceAnchorData_t2991923452, ___isTracked_7)); } inline bool get_isTracked_7() const { return ___isTracked_7; } inline bool* get_address_of_isTracked_7() { return &___isTracked_7; } inline void set_isTracked_7(bool value) { ___isTracked_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.XR.iOS.UnityARFaceAnchorData struct UnityARFaceAnchorData_t2991923452_marshaled_pinvoke { intptr_t ___ptrIdentifier_0; UnityARMatrix4x4_t100931615 ___transform_1; UnityARFaceGeometry_t49674351 ___faceGeometry_2; intptr_t ___blendShapes_3; UnityARMatrix4x4_t100931615 ___leftEyeTransform_4; UnityARMatrix4x4_t100931615 ___rightEyeTransform_5; Vector3_t2243707580 ___lookAtPoint_6; int32_t ___isTracked_7; }; // Native definition for COM marshalling of UnityEngine.XR.iOS.UnityARFaceAnchorData struct UnityARFaceAnchorData_t2991923452_marshaled_com { intptr_t ___ptrIdentifier_0; UnityARMatrix4x4_t100931615 ___transform_1; UnityARFaceGeometry_t49674351 ___faceGeometry_2; intptr_t ___blendShapes_3; UnityARMatrix4x4_t100931615 ___leftEyeTransform_4; UnityARMatrix4x4_t100931615 ___rightEyeTransform_5; Vector3_t2243707580 ___lookAtPoint_6; int32_t ___isTracked_7; }; #endif // UNITYARFACEANCHORDATA_T2991923452_H #ifndef UNITYARANCHORDATA_T2901866349_H #define UNITYARANCHORDATA_T2901866349_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARAnchorData struct UnityARAnchorData_t2901866349 { public: // System.IntPtr UnityEngine.XR.iOS.UnityARAnchorData::ptrIdentifier intptr_t ___ptrIdentifier_0; // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARAnchorData::transform UnityARMatrix4x4_t100931615 ___transform_1; // UnityEngine.XR.iOS.ARPlaneAnchorAlignment UnityEngine.XR.iOS.UnityARAnchorData::alignment int64_t ___alignment_2; // UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARAnchorData::center Vector4_t2243707581 ___center_3; // UnityEngine.Vector4 UnityEngine.XR.iOS.UnityARAnchorData::extent Vector4_t2243707581 ___extent_4; // UnityEngine.XR.iOS.UnityARPlaneGeometry UnityEngine.XR.iOS.UnityARAnchorData::planeGeometry UnityARPlaneGeometry_t1435619558 ___planeGeometry_5; public: inline static int32_t get_offset_of_ptrIdentifier_0() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t2901866349, ___ptrIdentifier_0)); } inline intptr_t get_ptrIdentifier_0() const { return ___ptrIdentifier_0; } inline intptr_t* get_address_of_ptrIdentifier_0() { return &___ptrIdentifier_0; } inline void set_ptrIdentifier_0(intptr_t value) { ___ptrIdentifier_0 = value; } inline static int32_t get_offset_of_transform_1() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t2901866349, ___transform_1)); } inline UnityARMatrix4x4_t100931615 get_transform_1() const { return ___transform_1; } inline UnityARMatrix4x4_t100931615 * get_address_of_transform_1() { return &___transform_1; } inline void set_transform_1(UnityARMatrix4x4_t100931615 value) { ___transform_1 = value; } inline static int32_t get_offset_of_alignment_2() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t2901866349, ___alignment_2)); } inline int64_t get_alignment_2() const { return ___alignment_2; } inline int64_t* get_address_of_alignment_2() { return &___alignment_2; } inline void set_alignment_2(int64_t value) { ___alignment_2 = value; } inline static int32_t get_offset_of_center_3() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t2901866349, ___center_3)); } inline Vector4_t2243707581 get_center_3() const { return ___center_3; } inline Vector4_t2243707581 * get_address_of_center_3() { return &___center_3; } inline void set_center_3(Vector4_t2243707581 value) { ___center_3 = value; } inline static int32_t get_offset_of_extent_4() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t2901866349, ___extent_4)); } inline Vector4_t2243707581 get_extent_4() const { return ___extent_4; } inline Vector4_t2243707581 * get_address_of_extent_4() { return &___extent_4; } inline void set_extent_4(Vector4_t2243707581 value) { ___extent_4 = value; } inline static int32_t get_offset_of_planeGeometry_5() { return static_cast<int32_t>(offsetof(UnityARAnchorData_t2901866349, ___planeGeometry_5)); } inline UnityARPlaneGeometry_t1435619558 get_planeGeometry_5() const { return ___planeGeometry_5; } inline UnityARPlaneGeometry_t1435619558 * get_address_of_planeGeometry_5() { return &___planeGeometry_5; } inline void set_planeGeometry_5(UnityARPlaneGeometry_t1435619558 value) { ___planeGeometry_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARANCHORDATA_T2901866349_H #ifndef ARKITOBJECTSCANNINGSESSIONCONFIGURATION_T3781767695_H #define ARKITOBJECTSCANNINGSESSIONCONFIGURATION_T3781767695_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARKitObjectScanningSessionConfiguration struct ARKitObjectScanningSessionConfiguration_t3781767695 { public: // UnityEngine.XR.iOS.UnityARAlignment UnityEngine.XR.iOS.ARKitObjectScanningSessionConfiguration::alignment int32_t ___alignment_0; // UnityEngine.XR.iOS.UnityARPlaneDetection UnityEngine.XR.iOS.ARKitObjectScanningSessionConfiguration::planeDetection int32_t ___planeDetection_1; // System.Boolean UnityEngine.XR.iOS.ARKitObjectScanningSessionConfiguration::getPointCloudData bool ___getPointCloudData_2; // System.Boolean UnityEngine.XR.iOS.ARKitObjectScanningSessionConfiguration::enableLightEstimation bool ___enableLightEstimation_3; // System.Boolean UnityEngine.XR.iOS.ARKitObjectScanningSessionConfiguration::enableAutoFocus bool ___enableAutoFocus_4; public: inline static int32_t get_offset_of_alignment_0() { return static_cast<int32_t>(offsetof(ARKitObjectScanningSessionConfiguration_t3781767695, ___alignment_0)); } inline int32_t get_alignment_0() const { return ___alignment_0; } inline int32_t* get_address_of_alignment_0() { return &___alignment_0; } inline void set_alignment_0(int32_t value) { ___alignment_0 = value; } inline static int32_t get_offset_of_planeDetection_1() { return static_cast<int32_t>(offsetof(ARKitObjectScanningSessionConfiguration_t3781767695, ___planeDetection_1)); } inline int32_t get_planeDetection_1() const { return ___planeDetection_1; } inline int32_t* get_address_of_planeDetection_1() { return &___planeDetection_1; } inline void set_planeDetection_1(int32_t value) { ___planeDetection_1 = value; } inline static int32_t get_offset_of_getPointCloudData_2() { return static_cast<int32_t>(offsetof(ARKitObjectScanningSessionConfiguration_t3781767695, ___getPointCloudData_2)); } inline bool get_getPointCloudData_2() const { return ___getPointCloudData_2; } inline bool* get_address_of_getPointCloudData_2() { return &___getPointCloudData_2; } inline void set_getPointCloudData_2(bool value) { ___getPointCloudData_2 = value; } inline static int32_t get_offset_of_enableLightEstimation_3() { return static_cast<int32_t>(offsetof(ARKitObjectScanningSessionConfiguration_t3781767695, ___enableLightEstimation_3)); } inline bool get_enableLightEstimation_3() const { return ___enableLightEstimation_3; } inline bool* get_address_of_enableLightEstimation_3() { return &___enableLightEstimation_3; } inline void set_enableLightEstimation_3(bool value) { ___enableLightEstimation_3 = value; } inline static int32_t get_offset_of_enableAutoFocus_4() { return static_cast<int32_t>(offsetof(ARKitObjectScanningSessionConfiguration_t3781767695, ___enableAutoFocus_4)); } inline bool get_enableAutoFocus_4() const { return ___enableAutoFocus_4; } inline bool* get_address_of_enableAutoFocus_4() { return &___enableAutoFocus_4; } inline void set_enableAutoFocus_4(bool value) { ___enableAutoFocus_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.XR.iOS.ARKitObjectScanningSessionConfiguration struct ARKitObjectScanningSessionConfiguration_t3781767695_marshaled_pinvoke { int32_t ___alignment_0; int32_t ___planeDetection_1; int32_t ___getPointCloudData_2; int32_t ___enableLightEstimation_3; int32_t ___enableAutoFocus_4; }; // Native definition for COM marshalling of UnityEngine.XR.iOS.ARKitObjectScanningSessionConfiguration struct ARKitObjectScanningSessionConfiguration_t3781767695_marshaled_com { int32_t ___alignment_0; int32_t ___planeDetection_1; int32_t ___getPointCloudData_2; int32_t ___enableLightEstimation_3; int32_t ___enableAutoFocus_4; }; #endif // ARKITOBJECTSCANNINGSESSIONCONFIGURATION_T3781767695_H #ifndef ARTEXTUREHANDLES_T3764914833_H #define ARTEXTUREHANDLES_T3764914833_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARTextureHandles struct ARTextureHandles_t3764914833 : public RuntimeObject { public: // UnityEngine.XR.iOS.ARTextureHandles/ARTextureHandlesStruct UnityEngine.XR.iOS.ARTextureHandles::m_ARTextureHandlesStruct ARTextureHandlesStruct_t617670158 ___m_ARTextureHandlesStruct_0; public: inline static int32_t get_offset_of_m_ARTextureHandlesStruct_0() { return static_cast<int32_t>(offsetof(ARTextureHandles_t3764914833, ___m_ARTextureHandlesStruct_0)); } inline ARTextureHandlesStruct_t617670158 get_m_ARTextureHandlesStruct_0() const { return ___m_ARTextureHandlesStruct_0; } inline ARTextureHandlesStruct_t617670158 * get_address_of_m_ARTextureHandlesStruct_0() { return &___m_ARTextureHandlesStruct_0; } inline void set_m_ARTextureHandlesStruct_0(ARTextureHandlesStruct_t617670158 value) { ___m_ARTextureHandlesStruct_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARTEXTUREHANDLES_T3764914833_H #ifndef ARPLANEGEOMETRY_T1176774719_H #define ARPLANEGEOMETRY_T1176774719_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARPlaneGeometry struct ARPlaneGeometry_t1176774719 : public RuntimeObject { public: // UnityEngine.XR.iOS.UnityARPlaneGeometry UnityEngine.XR.iOS.ARPlaneGeometry::uPlaneGeometry UnityARPlaneGeometry_t1435619558 ___uPlaneGeometry_0; public: inline static int32_t get_offset_of_uPlaneGeometry_0() { return static_cast<int32_t>(offsetof(ARPlaneGeometry_t1176774719, ___uPlaneGeometry_0)); } inline UnityARPlaneGeometry_t1435619558 get_uPlaneGeometry_0() const { return ___uPlaneGeometry_0; } inline UnityARPlaneGeometry_t1435619558 * get_address_of_uPlaneGeometry_0() { return &___uPlaneGeometry_0; } inline void set_uPlaneGeometry_0(UnityARPlaneGeometry_t1435619558 value) { ___uPlaneGeometry_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARPLANEGEOMETRY_T1176774719_H #ifndef VIDEOFORMATENUMERATOR_T1718260816_H #define VIDEOFORMATENUMERATOR_T1718260816_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.VideoFormatEnumerator struct VideoFormatEnumerator_t1718260816 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VIDEOFORMATENUMERATOR_T1718260816_H #ifndef INTERNAL_ARIMAGEANCHORREMOVED_T2214597294_H #define INTERNAL_ARIMAGEANCHORREMOVED_T2214597294_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARSessionNativeInterface/internal_ARImageAnchorRemoved struct internal_ARImageAnchorRemoved_t2214597294 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNAL_ARIMAGEANCHORREMOVED_T2214597294_H #ifndef INTERNAL_ARIMAGEANCHORUPDATED_T1722259079_H #define INTERNAL_ARIMAGEANCHORUPDATED_T1722259079_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARSessionNativeInterface/internal_ARImageAnchorUpdated struct internal_ARImageAnchorUpdated_t1722259079 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNAL_ARIMAGEANCHORUPDATED_T1722259079_H #ifndef INTERNAL_ARIMAGEANCHORADDED_T3318396380_H #define INTERNAL_ARIMAGEANCHORADDED_T3318396380_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARSessionNativeInterface/internal_ARImageAnchorAdded struct internal_ARImageAnchorAdded_t3318396380 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNAL_ARIMAGEANCHORADDED_T3318396380_H #ifndef INTERNAL_ARUSERANCHORUPDATED_T1661963345_H #define INTERNAL_ARUSERANCHORUPDATED_T1661963345_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARSessionNativeInterface/internal_ARUserAnchorUpdated struct internal_ARUserAnchorUpdated_t1661963345 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNAL_ARUSERANCHORUPDATED_T1661963345_H #ifndef INTERNAL_ARUSERANCHORREMOVED_T4166385952_H #define INTERNAL_ARUSERANCHORREMOVED_T4166385952_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARSessionNativeInterface/internal_ARUserAnchorRemoved struct internal_ARUserAnchorRemoved_t4166385952 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNAL_ARUSERANCHORREMOVED_T4166385952_H #ifndef INTERNAL_ARFACEANCHORUPDATED_T2983102933_H #define INTERNAL_ARFACEANCHORUPDATED_T2983102933_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARSessionNativeInterface/internal_ARFaceAnchorUpdated struct internal_ARFaceAnchorUpdated_t2983102933 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNAL_ARFACEANCHORUPDATED_T2983102933_H #ifndef INTERNAL_ARFACEANCHORADDED_T1146330100_H #define INTERNAL_ARFACEANCHORADDED_T1146330100_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARSessionNativeInterface/internal_ARFaceAnchorAdded struct internal_ARFaceAnchorAdded_t1146330100 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNAL_ARFACEANCHORADDED_T1146330100_H #ifndef INTERNAL_ARFACEANCHORREMOVED_T689428754_H #define INTERNAL_ARFACEANCHORREMOVED_T689428754_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARSessionNativeInterface/internal_ARFaceAnchorRemoved struct internal_ARFaceAnchorRemoved_t689428754 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNAL_ARFACEANCHORREMOVED_T689428754_H #ifndef AROBJECTANCHOR_T4188951463_H #define AROBJECTANCHOR_T4188951463_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARObjectAnchor struct ARObjectAnchor_t4188951463 : public RuntimeObject { public: // UnityEngine.XR.iOS.UnityARObjectAnchorData UnityEngine.XR.iOS.ARObjectAnchor::objectAnchorData UnityARObjectAnchorData_t938871002 ___objectAnchorData_0; public: inline static int32_t get_offset_of_objectAnchorData_0() { return static_cast<int32_t>(offsetof(ARObjectAnchor_t4188951463, ___objectAnchorData_0)); } inline UnityARObjectAnchorData_t938871002 get_objectAnchorData_0() const { return ___objectAnchorData_0; } inline UnityARObjectAnchorData_t938871002 * get_address_of_objectAnchorData_0() { return &___objectAnchorData_0; } inline void set_objectAnchorData_0(UnityARObjectAnchorData_t938871002 value) { ___objectAnchorData_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // AROBJECTANCHOR_T4188951463_H #ifndef UNITYARCAMERA_T4198559457_H #define UNITYARCAMERA_T4198559457_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARCamera struct UnityARCamera_t4198559457 { public: // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARCamera::worldTransform UnityARMatrix4x4_t100931615 ___worldTransform_0; // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARCamera::projectionMatrix UnityARMatrix4x4_t100931615 ___projectionMatrix_1; // UnityEngine.XR.iOS.ARTrackingState UnityEngine.XR.iOS.UnityARCamera::trackingState int32_t ___trackingState_2; // UnityEngine.XR.iOS.ARTrackingStateReason UnityEngine.XR.iOS.UnityARCamera::trackingReason int32_t ___trackingReason_3; // UnityEngine.XR.iOS.UnityVideoParams UnityEngine.XR.iOS.UnityARCamera::videoParams UnityVideoParams_t2644681676 ___videoParams_4; // UnityEngine.XR.iOS.UnityARLightData UnityEngine.XR.iOS.UnityARCamera::lightData UnityARLightData_t1178200316 ___lightData_5; // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.UnityARCamera::displayTransform UnityARMatrix4x4_t100931615 ___displayTransform_6; // UnityEngine.XR.iOS.ARPointCloud UnityEngine.XR.iOS.UnityARCamera::pointCloud ARPointCloud_t2004641850 * ___pointCloud_7; // UnityEngine.XR.iOS.ARWorldMappingStatus UnityEngine.XR.iOS.UnityARCamera::worldMappingStatus int32_t ___worldMappingStatus_8; public: inline static int32_t get_offset_of_worldTransform_0() { return static_cast<int32_t>(offsetof(UnityARCamera_t4198559457, ___worldTransform_0)); } inline UnityARMatrix4x4_t100931615 get_worldTransform_0() const { return ___worldTransform_0; } inline UnityARMatrix4x4_t100931615 * get_address_of_worldTransform_0() { return &___worldTransform_0; } inline void set_worldTransform_0(UnityARMatrix4x4_t100931615 value) { ___worldTransform_0 = value; } inline static int32_t get_offset_of_projectionMatrix_1() { return static_cast<int32_t>(offsetof(UnityARCamera_t4198559457, ___projectionMatrix_1)); } inline UnityARMatrix4x4_t100931615 get_projectionMatrix_1() const { return ___projectionMatrix_1; } inline UnityARMatrix4x4_t100931615 * get_address_of_projectionMatrix_1() { return &___projectionMatrix_1; } inline void set_projectionMatrix_1(UnityARMatrix4x4_t100931615 value) { ___projectionMatrix_1 = value; } inline static int32_t get_offset_of_trackingState_2() { return static_cast<int32_t>(offsetof(UnityARCamera_t4198559457, ___trackingState_2)); } inline int32_t get_trackingState_2() const { return ___trackingState_2; } inline int32_t* get_address_of_trackingState_2() { return &___trackingState_2; } inline void set_trackingState_2(int32_t value) { ___trackingState_2 = value; } inline static int32_t get_offset_of_trackingReason_3() { return static_cast<int32_t>(offsetof(UnityARCamera_t4198559457, ___trackingReason_3)); } inline int32_t get_trackingReason_3() const { return ___trackingReason_3; } inline int32_t* get_address_of_trackingReason_3() { return &___trackingReason_3; } inline void set_trackingReason_3(int32_t value) { ___trackingReason_3 = value; } inline static int32_t get_offset_of_videoParams_4() { return static_cast<int32_t>(offsetof(UnityARCamera_t4198559457, ___videoParams_4)); } inline UnityVideoParams_t2644681676 get_videoParams_4() const { return ___videoParams_4; } inline UnityVideoParams_t2644681676 * get_address_of_videoParams_4() { return &___videoParams_4; } inline void set_videoParams_4(UnityVideoParams_t2644681676 value) { ___videoParams_4 = value; } inline static int32_t get_offset_of_lightData_5() { return static_cast<int32_t>(offsetof(UnityARCamera_t4198559457, ___lightData_5)); } inline UnityARLightData_t1178200316 get_lightData_5() const { return ___lightData_5; } inline UnityARLightData_t1178200316 * get_address_of_lightData_5() { return &___lightData_5; } inline void set_lightData_5(UnityARLightData_t1178200316 value) { ___lightData_5 = value; } inline static int32_t get_offset_of_displayTransform_6() { return static_cast<int32_t>(offsetof(UnityARCamera_t4198559457, ___displayTransform_6)); } inline UnityARMatrix4x4_t100931615 get_displayTransform_6() const { return ___displayTransform_6; } inline UnityARMatrix4x4_t100931615 * get_address_of_displayTransform_6() { return &___displayTransform_6; } inline void set_displayTransform_6(UnityARMatrix4x4_t100931615 value) { ___displayTransform_6 = value; } inline static int32_t get_offset_of_pointCloud_7() { return static_cast<int32_t>(offsetof(UnityARCamera_t4198559457, ___pointCloud_7)); } inline ARPointCloud_t2004641850 * get_pointCloud_7() const { return ___pointCloud_7; } inline ARPointCloud_t2004641850 ** get_address_of_pointCloud_7() { return &___pointCloud_7; } inline void set_pointCloud_7(ARPointCloud_t2004641850 * value) { ___pointCloud_7 = value; Il2CppCodeGenWriteBarrier((&___pointCloud_7), value); } inline static int32_t get_offset_of_worldMappingStatus_8() { return static_cast<int32_t>(offsetof(UnityARCamera_t4198559457, ___worldMappingStatus_8)); } inline int32_t get_worldMappingStatus_8() const { return ___worldMappingStatus_8; } inline int32_t* get_address_of_worldMappingStatus_8() { return &___worldMappingStatus_8; } inline void set_worldMappingStatus_8(int32_t value) { ___worldMappingStatus_8 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.XR.iOS.UnityARCamera struct UnityARCamera_t4198559457_marshaled_pinvoke { UnityARMatrix4x4_t100931615 ___worldTransform_0; UnityARMatrix4x4_t100931615 ___projectionMatrix_1; int32_t ___trackingState_2; int32_t ___trackingReason_3; UnityVideoParams_t2644681676 ___videoParams_4; UnityARLightData_t1178200316_marshaled_pinvoke ___lightData_5; UnityARMatrix4x4_t100931615 ___displayTransform_6; ARPointCloud_t2004641850 * ___pointCloud_7; int32_t ___worldMappingStatus_8; }; // Native definition for COM marshalling of UnityEngine.XR.iOS.UnityARCamera struct UnityARCamera_t4198559457_marshaled_com { UnityARMatrix4x4_t100931615 ___worldTransform_0; UnityARMatrix4x4_t100931615 ___projectionMatrix_1; int32_t ___trackingState_2; int32_t ___trackingReason_3; UnityVideoParams_t2644681676 ___videoParams_4; UnityARLightData_t1178200316_marshaled_com ___lightData_5; UnityARMatrix4x4_t100931615 ___displayTransform_6; ARPointCloud_t2004641850 * ___pointCloud_7; int32_t ___worldMappingStatus_8; }; #endif // UNITYARCAMERA_T4198559457_H #ifndef INTERNAL_UNITYARCAMERA_T2580192745_H #define INTERNAL_UNITYARCAMERA_T2580192745_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.internal_UnityARCamera struct internal_UnityARCamera_t2580192745 { public: // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.internal_UnityARCamera::worldTransform UnityARMatrix4x4_t100931615 ___worldTransform_0; // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.internal_UnityARCamera::projectionMatrix UnityARMatrix4x4_t100931615 ___projectionMatrix_1; // UnityEngine.XR.iOS.ARTrackingState UnityEngine.XR.iOS.internal_UnityARCamera::trackingState int32_t ___trackingState_2; // UnityEngine.XR.iOS.ARTrackingStateReason UnityEngine.XR.iOS.internal_UnityARCamera::trackingReason int32_t ___trackingReason_3; // UnityEngine.XR.iOS.UnityVideoParams UnityEngine.XR.iOS.internal_UnityARCamera::videoParams UnityVideoParams_t2644681676 ___videoParams_4; // UnityEngine.XR.iOS.UnityMarshalLightData UnityEngine.XR.iOS.internal_UnityARCamera::lightData UnityMarshalLightData_t3773526525 ___lightData_5; // UnityEngine.XR.iOS.UnityARMatrix4x4 UnityEngine.XR.iOS.internal_UnityARCamera::displayTransform UnityARMatrix4x4_t100931615 ___displayTransform_6; // System.IntPtr UnityEngine.XR.iOS.internal_UnityARCamera::pointCloud intptr_t ___pointCloud_7; // System.UInt32 UnityEngine.XR.iOS.internal_UnityARCamera::getLightEstimation uint32_t ___getLightEstimation_8; // UnityEngine.XR.iOS.ARWorldMappingStatus UnityEngine.XR.iOS.internal_UnityARCamera::worldMappngStatus int32_t ___worldMappngStatus_9; public: inline static int32_t get_offset_of_worldTransform_0() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t2580192745, ___worldTransform_0)); } inline UnityARMatrix4x4_t100931615 get_worldTransform_0() const { return ___worldTransform_0; } inline UnityARMatrix4x4_t100931615 * get_address_of_worldTransform_0() { return &___worldTransform_0; } inline void set_worldTransform_0(UnityARMatrix4x4_t100931615 value) { ___worldTransform_0 = value; } inline static int32_t get_offset_of_projectionMatrix_1() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t2580192745, ___projectionMatrix_1)); } inline UnityARMatrix4x4_t100931615 get_projectionMatrix_1() const { return ___projectionMatrix_1; } inline UnityARMatrix4x4_t100931615 * get_address_of_projectionMatrix_1() { return &___projectionMatrix_1; } inline void set_projectionMatrix_1(UnityARMatrix4x4_t100931615 value) { ___projectionMatrix_1 = value; } inline static int32_t get_offset_of_trackingState_2() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t2580192745, ___trackingState_2)); } inline int32_t get_trackingState_2() const { return ___trackingState_2; } inline int32_t* get_address_of_trackingState_2() { return &___trackingState_2; } inline void set_trackingState_2(int32_t value) { ___trackingState_2 = value; } inline static int32_t get_offset_of_trackingReason_3() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t2580192745, ___trackingReason_3)); } inline int32_t get_trackingReason_3() const { return ___trackingReason_3; } inline int32_t* get_address_of_trackingReason_3() { return &___trackingReason_3; } inline void set_trackingReason_3(int32_t value) { ___trackingReason_3 = value; } inline static int32_t get_offset_of_videoParams_4() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t2580192745, ___videoParams_4)); } inline UnityVideoParams_t2644681676 get_videoParams_4() const { return ___videoParams_4; } inline UnityVideoParams_t2644681676 * get_address_of_videoParams_4() { return &___videoParams_4; } inline void set_videoParams_4(UnityVideoParams_t2644681676 value) { ___videoParams_4 = value; } inline static int32_t get_offset_of_lightData_5() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t2580192745, ___lightData_5)); } inline UnityMarshalLightData_t3773526525 get_lightData_5() const { return ___lightData_5; } inline UnityMarshalLightData_t3773526525 * get_address_of_lightData_5() { return &___lightData_5; } inline void set_lightData_5(UnityMarshalLightData_t3773526525 value) { ___lightData_5 = value; } inline static int32_t get_offset_of_displayTransform_6() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t2580192745, ___displayTransform_6)); } inline UnityARMatrix4x4_t100931615 get_displayTransform_6() const { return ___displayTransform_6; } inline UnityARMatrix4x4_t100931615 * get_address_of_displayTransform_6() { return &___displayTransform_6; } inline void set_displayTransform_6(UnityARMatrix4x4_t100931615 value) { ___displayTransform_6 = value; } inline static int32_t get_offset_of_pointCloud_7() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t2580192745, ___pointCloud_7)); } inline intptr_t get_pointCloud_7() const { return ___pointCloud_7; } inline intptr_t* get_address_of_pointCloud_7() { return &___pointCloud_7; } inline void set_pointCloud_7(intptr_t value) { ___pointCloud_7 = value; } inline static int32_t get_offset_of_getLightEstimation_8() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t2580192745, ___getLightEstimation_8)); } inline uint32_t get_getLightEstimation_8() const { return ___getLightEstimation_8; } inline uint32_t* get_address_of_getLightEstimation_8() { return &___getLightEstimation_8; } inline void set_getLightEstimation_8(uint32_t value) { ___getLightEstimation_8 = value; } inline static int32_t get_offset_of_worldMappngStatus_9() { return static_cast<int32_t>(offsetof(internal_UnityARCamera_t2580192745, ___worldMappngStatus_9)); } inline int32_t get_worldMappngStatus_9() const { return ___worldMappngStatus_9; } inline int32_t* get_address_of_worldMappngStatus_9() { return &___worldMappngStatus_9; } inline void set_worldMappngStatus_9(int32_t value) { ___worldMappngStatus_9 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNAL_UNITYARCAMERA_T2580192745_H #ifndef ARIMAGEANCHOR_T416321645_H #define ARIMAGEANCHOR_T416321645_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARImageAnchor struct ARImageAnchor_t416321645 : public RuntimeObject { public: // UnityEngine.XR.iOS.UnityARImageAnchorData UnityEngine.XR.iOS.ARImageAnchor::imageAnchorData UnityARImageAnchorData_t29968876 ___imageAnchorData_0; public: inline static int32_t get_offset_of_imageAnchorData_0() { return static_cast<int32_t>(offsetof(ARImageAnchor_t416321645, ___imageAnchorData_0)); } inline UnityARImageAnchorData_t29968876 get_imageAnchorData_0() const { return ___imageAnchorData_0; } inline UnityARImageAnchorData_t29968876 * get_address_of_imageAnchorData_0() { return &___imageAnchorData_0; } inline void set_imageAnchorData_0(UnityARImageAnchorData_t29968876 value) { ___imageAnchorData_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARIMAGEANCHOR_T416321645_H #ifndef ARPLANEANCHOR_T1439520888_H #define ARPLANEANCHOR_T1439520888_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARPlaneAnchor struct ARPlaneAnchor_t1439520888 : public RuntimeObject { public: // UnityEngine.XR.iOS.UnityARAnchorData UnityEngine.XR.iOS.ARPlaneAnchor::planeAnchorData UnityARAnchorData_t2901866349 ___planeAnchorData_0; // System.String UnityEngine.XR.iOS.ARPlaneAnchor::<identifierStr>k__BackingField String_t* ___U3CidentifierStrU3Ek__BackingField_1; public: inline static int32_t get_offset_of_planeAnchorData_0() { return static_cast<int32_t>(offsetof(ARPlaneAnchor_t1439520888, ___planeAnchorData_0)); } inline UnityARAnchorData_t2901866349 get_planeAnchorData_0() const { return ___planeAnchorData_0; } inline UnityARAnchorData_t2901866349 * get_address_of_planeAnchorData_0() { return &___planeAnchorData_0; } inline void set_planeAnchorData_0(UnityARAnchorData_t2901866349 value) { ___planeAnchorData_0 = value; } inline static int32_t get_offset_of_U3CidentifierStrU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(ARPlaneAnchor_t1439520888, ___U3CidentifierStrU3Ek__BackingField_1)); } inline String_t* get_U3CidentifierStrU3Ek__BackingField_1() const { return ___U3CidentifierStrU3Ek__BackingField_1; } inline String_t** get_address_of_U3CidentifierStrU3Ek__BackingField_1() { return &___U3CidentifierStrU3Ek__BackingField_1; } inline void set_U3CidentifierStrU3Ek__BackingField_1(String_t* value) { ___U3CidentifierStrU3Ek__BackingField_1 = value; Il2CppCodeGenWriteBarrier((&___U3CidentifierStrU3Ek__BackingField_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARPLANEANCHOR_T1439520888_H #ifndef UNITYARKITPLUGINSETTINGS_T857412912_H #define UNITYARKITPLUGINSETTINGS_T857412912_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityARKitPluginSettings struct UnityARKitPluginSettings_t857412912 : public ScriptableObject_t1975622470 { public: // System.Boolean UnityARKitPluginSettings::m_ARKitUsesFacetracking bool ___m_ARKitUsesFacetracking_2; // System.Boolean UnityARKitPluginSettings::AppRequiresARKit bool ___AppRequiresARKit_3; public: inline static int32_t get_offset_of_m_ARKitUsesFacetracking_2() { return static_cast<int32_t>(offsetof(UnityARKitPluginSettings_t857412912, ___m_ARKitUsesFacetracking_2)); } inline bool get_m_ARKitUsesFacetracking_2() const { return ___m_ARKitUsesFacetracking_2; } inline bool* get_address_of_m_ARKitUsesFacetracking_2() { return &___m_ARKitUsesFacetracking_2; } inline void set_m_ARKitUsesFacetracking_2(bool value) { ___m_ARKitUsesFacetracking_2 = value; } inline static int32_t get_offset_of_AppRequiresARKit_3() { return static_cast<int32_t>(offsetof(UnityARKitPluginSettings_t857412912, ___AppRequiresARKit_3)); } inline bool get_AppRequiresARKit_3() const { return ___AppRequiresARKit_3; } inline bool* get_address_of_AppRequiresARKit_3() { return &___AppRequiresARKit_3; } inline void set_AppRequiresARKit_3(bool value) { ___AppRequiresARKit_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYARKITPLUGINSETTINGS_T857412912_H #ifndef ARFRAME_T1001293426_H #define ARFRAME_T1001293426_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARFrame struct ARFrame_t1001293426 { public: // System.Double UnityEngine.XR.iOS.ARFrame::timestamp double ___timestamp_0; // System.IntPtr UnityEngine.XR.iOS.ARFrame::capturedImage intptr_t ___capturedImage_1; // UnityEngine.XR.iOS.ARCamera UnityEngine.XR.iOS.ARFrame::camera ARCamera_t4158705974 ___camera_2; // UnityEngine.XR.iOS.ARLightEstimate UnityEngine.XR.iOS.ARFrame::lightEstimate ARLightEstimate_t3477821059 ___lightEstimate_3; public: inline static int32_t get_offset_of_timestamp_0() { return static_cast<int32_t>(offsetof(ARFrame_t1001293426, ___timestamp_0)); } inline double get_timestamp_0() const { return ___timestamp_0; } inline double* get_address_of_timestamp_0() { return &___timestamp_0; } inline void set_timestamp_0(double value) { ___timestamp_0 = value; } inline static int32_t get_offset_of_capturedImage_1() { return static_cast<int32_t>(offsetof(ARFrame_t1001293426, ___capturedImage_1)); } inline intptr_t get_capturedImage_1() const { return ___capturedImage_1; } inline intptr_t* get_address_of_capturedImage_1() { return &___capturedImage_1; } inline void set_capturedImage_1(intptr_t value) { ___capturedImage_1 = value; } inline static int32_t get_offset_of_camera_2() { return static_cast<int32_t>(offsetof(ARFrame_t1001293426, ___camera_2)); } inline ARCamera_t4158705974 get_camera_2() const { return ___camera_2; } inline ARCamera_t4158705974 * get_address_of_camera_2() { return &___camera_2; } inline void set_camera_2(ARCamera_t4158705974 value) { ___camera_2 = value; } inline static int32_t get_offset_of_lightEstimate_3() { return static_cast<int32_t>(offsetof(ARFrame_t1001293426, ___lightEstimate_3)); } inline ARLightEstimate_t3477821059 get_lightEstimate_3() const { return ___lightEstimate_3; } inline ARLightEstimate_t3477821059 * get_address_of_lightEstimate_3() { return &___lightEstimate_3; } inline void set_lightEstimate_3(ARLightEstimate_t3477821059 value) { ___lightEstimate_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARFRAME_T1001293426_H #ifndef DICTIONARYVISITORHANDLER_T245332630_H #define DICTIONARYVISITORHANDLER_T245332630_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARFaceAnchor/DictionaryVisitorHandler struct DictionaryVisitorHandler_t245332630 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DICTIONARYVISITORHANDLER_T245332630_H #ifndef ARFACEANCHOR_T4162019119_H #define ARFACEANCHOR_T4162019119_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.ARFaceAnchor struct ARFaceAnchor_t4162019119 : public RuntimeObject { public: // UnityEngine.XR.iOS.UnityARFaceAnchorData UnityEngine.XR.iOS.ARFaceAnchor::faceAnchorData UnityARFaceAnchorData_t2991923452 ___faceAnchorData_0; // UnityEngine.XR.iOS.ARFaceGeometry UnityEngine.XR.iOS.ARFaceAnchor::m_FaceGeometry ARFaceGeometry_t2928150040 * ___m_FaceGeometry_2; public: inline static int32_t get_offset_of_faceAnchorData_0() { return static_cast<int32_t>(offsetof(ARFaceAnchor_t4162019119, ___faceAnchorData_0)); } inline UnityARFaceAnchorData_t2991923452 get_faceAnchorData_0() const { return ___faceAnchorData_0; } inline UnityARFaceAnchorData_t2991923452 * get_address_of_faceAnchorData_0() { return &___faceAnchorData_0; } inline void set_faceAnchorData_0(UnityARFaceAnchorData_t2991923452 value) { ___faceAnchorData_0 = value; } inline static int32_t get_offset_of_m_FaceGeometry_2() { return static_cast<int32_t>(offsetof(ARFaceAnchor_t4162019119, ___m_FaceGeometry_2)); } inline ARFaceGeometry_t2928150040 * get_m_FaceGeometry_2() const { return ___m_FaceGeometry_2; } inline ARFaceGeometry_t2928150040 ** get_address_of_m_FaceGeometry_2() { return &___m_FaceGeometry_2; } inline void set_m_FaceGeometry_2(ARFaceGeometry_t2928150040 * value) { ___m_FaceGeometry_2 = value; Il2CppCodeGenWriteBarrier((&___m_FaceGeometry_2), value); } }; struct ARFaceAnchor_t4162019119_StaticFields { public: // System.Collections.Generic.Dictionary`2<System.String,System.Single> UnityEngine.XR.iOS.ARFaceAnchor::blendshapesDictionary Dictionary_2_t3991289194 * ___blendshapesDictionary_1; // UnityEngine.XR.iOS.ARFaceAnchor/DictionaryVisitorHandler UnityEngine.XR.iOS.ARFaceAnchor::<>f__mg$cache0 DictionaryVisitorHandler_t245332630 * ___U3CU3Ef__mgU24cache0_3; public: inline static int32_t get_offset_of_blendshapesDictionary_1() { return static_cast<int32_t>(offsetof(ARFaceAnchor_t4162019119_StaticFields, ___blendshapesDictionary_1)); } inline Dictionary_2_t3991289194 * get_blendshapesDictionary_1() const { return ___blendshapesDictionary_1; } inline Dictionary_2_t3991289194 ** get_address_of_blendshapesDictionary_1() { return &___blendshapesDictionary_1; } inline void set_blendshapesDictionary_1(Dictionary_2_t3991289194 * value) { ___blendshapesDictionary_1 = value; Il2CppCodeGenWriteBarrier((&___blendshapesDictionary_1), value); } inline static int32_t get_offset_of_U3CU3Ef__mgU24cache0_3() { return static_cast<int32_t>(offsetof(ARFaceAnchor_t4162019119_StaticFields, ___U3CU3Ef__mgU24cache0_3)); } inline DictionaryVisitorHandler_t245332630 * get_U3CU3Ef__mgU24cache0_3() const { return ___U3CU3Ef__mgU24cache0_3; } inline DictionaryVisitorHandler_t245332630 ** get_address_of_U3CU3Ef__mgU24cache0_3() { return &___U3CU3Ef__mgU24cache0_3; } inline void set_U3CU3Ef__mgU24cache0_3(DictionaryVisitorHandler_t245332630 * value) { ___U3CU3Ef__mgU24cache0_3 = value; Il2CppCodeGenWriteBarrier((&___U3CU3Ef__mgU24cache0_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARFACEANCHOR_T4162019119_H #ifndef INTERNAL_ARUSERANCHORADDED_T3999066834_H #define INTERNAL_ARUSERANCHORADDED_T3999066834_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARSessionNativeInterface/internal_ARUserAnchorAdded struct internal_ARUserAnchorAdded_t3999066834 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNAL_ARUSERANCHORADDED_T3999066834_H #ifndef INTERNAL_ARSESSIONTRACKINGCHANGED_T1558153491_H #define INTERNAL_ARSESSIONTRACKINGCHANGED_T1558153491_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARSessionNativeInterface/internal_ARSessionTrackingChanged struct internal_ARSessionTrackingChanged_t1558153491 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNAL_ARSESSIONTRACKINGCHANGED_T1558153491_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2000 = { sizeof (internal_ARUserAnchorAdded_t3999066834), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2001 = { sizeof (internal_ARUserAnchorUpdated_t1661963345), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2002 = { sizeof (internal_ARUserAnchorRemoved_t4166385952), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2003 = { sizeof (internal_ARFaceAnchorAdded_t1146330100), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2004 = { sizeof (internal_ARFaceAnchorUpdated_t2983102933), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2005 = { sizeof (internal_ARFaceAnchorRemoved_t689428754), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2006 = { sizeof (internal_ARImageAnchorAdded_t3318396380), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2007 = { sizeof (internal_ARImageAnchorUpdated_t1722259079), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2008 = { sizeof (internal_ARImageAnchorRemoved_t2214597294), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2009 = { sizeof (internal_ARSessionTrackingChanged_t1558153491), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2010 = { sizeof (ARErrorCode_t2887756272)+ sizeof (RuntimeObject), sizeof(int64_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2010[5] = { ARErrorCode_t2887756272::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2011 = { sizeof (ARBlendShapeLocation_t3927368462), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2011[52] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2012 = { sizeof (UnityARFaceGeometry_t49674351)+ sizeof (RuntimeObject), sizeof(UnityARFaceGeometry_t49674351 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2012[6] = { UnityARFaceGeometry_t49674351::get_offset_of_vertexCount_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceGeometry_t49674351::get_offset_of_vertices_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceGeometry_t49674351::get_offset_of_textureCoordinateCount_2() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceGeometry_t49674351::get_offset_of_textureCoordinates_3() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceGeometry_t49674351::get_offset_of_triangleCount_4() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceGeometry_t49674351::get_offset_of_triangleIndices_5() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2013 = { sizeof (UnityARFaceAnchorData_t2991923452)+ sizeof (RuntimeObject), sizeof(UnityARFaceAnchorData_t2991923452_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable2013[8] = { UnityARFaceAnchorData_t2991923452::get_offset_of_ptrIdentifier_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceAnchorData_t2991923452::get_offset_of_transform_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceAnchorData_t2991923452::get_offset_of_faceGeometry_2() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceAnchorData_t2991923452::get_offset_of_blendShapes_3() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceAnchorData_t2991923452::get_offset_of_leftEyeTransform_4() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceAnchorData_t2991923452::get_offset_of_rightEyeTransform_5() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceAnchorData_t2991923452::get_offset_of_lookAtPoint_6() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARFaceAnchorData_t2991923452::get_offset_of_isTracked_7() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2014 = { sizeof (ARFaceGeometry_t2928150040), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2014[13] = { ARFaceGeometry_t2928150040::get_offset_of_U3CuFaceGeometryU3Ek__BackingField_0(), ARFaceGeometry_t2928150040::get_offset_of_m_Vertices_1(), ARFaceGeometry_t2928150040::get_offset_of_m_TextureCoordinates_2(), ARFaceGeometry_t2928150040::get_offset_of_m_TriangleIndices_3(), ARFaceGeometry_t2928150040::get_offset_of_m_WorkVertices_4(), ARFaceGeometry_t2928150040::get_offset_of_m_WorkTextureCoordinates_5(), ARFaceGeometry_t2928150040::get_offset_of_m_WorkIndices_6(), ARFaceGeometry_t2928150040::get_offset_of_m_VertexCount_7(), ARFaceGeometry_t2928150040::get_offset_of_m_TextureCoordinateCount_8(), ARFaceGeometry_t2928150040::get_offset_of_m_TriangleCount_9(), ARFaceGeometry_t2928150040::get_offset_of_m_IndexCount_10(), ARFaceGeometry_t2928150040::get_offset_of_m_WorkVertexCount_11(), ARFaceGeometry_t2928150040::get_offset_of_m_WorkTextureCoordinateCount_12(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2015 = { sizeof (ARFaceAnchor_t4162019119), -1, sizeof(ARFaceAnchor_t4162019119_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable2015[4] = { ARFaceAnchor_t4162019119::get_offset_of_faceAnchorData_0(), ARFaceAnchor_t4162019119_StaticFields::get_offset_of_blendshapesDictionary_1(), ARFaceAnchor_t4162019119::get_offset_of_m_FaceGeometry_2(), ARFaceAnchor_t4162019119_StaticFields::get_offset_of_U3CU3Ef__mgU24cache0_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2016 = { sizeof (DictionaryVisitorHandler_t245332630), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2017 = { sizeof (ARFrame_t1001293426)+ sizeof (RuntimeObject), sizeof(ARFrame_t1001293426 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2017[4] = { ARFrame_t1001293426::get_offset_of_timestamp_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ARFrame_t1001293426::get_offset_of_capturedImage_1() + static_cast<int32_t>(sizeof(RuntimeObject)), ARFrame_t1001293426::get_offset_of_camera_2() + static_cast<int32_t>(sizeof(RuntimeObject)), ARFrame_t1001293426::get_offset_of_lightEstimate_3() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2018 = { sizeof (ARHitTestResult_t3275513025)+ sizeof (RuntimeObject), sizeof(ARHitTestResult_t3275513025_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable2018[6] = { ARHitTestResult_t3275513025::get_offset_of_type_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ARHitTestResult_t3275513025::get_offset_of_distance_1() + static_cast<int32_t>(sizeof(RuntimeObject)), ARHitTestResult_t3275513025::get_offset_of_localTransform_2() + static_cast<int32_t>(sizeof(RuntimeObject)), ARHitTestResult_t3275513025::get_offset_of_worldTransform_3() + static_cast<int32_t>(sizeof(RuntimeObject)), ARHitTestResult_t3275513025::get_offset_of_anchorIdentifier_4() + static_cast<int32_t>(sizeof(RuntimeObject)), ARHitTestResult_t3275513025::get_offset_of_isValid_5() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2019 = { sizeof (ARHitTestResultType_t3616749745)+ sizeof (RuntimeObject), sizeof(int64_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2019[7] = { ARHitTestResultType_t3616749745::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2020 = { sizeof (UnityARImageAnchorData_t29968876)+ sizeof (RuntimeObject), sizeof(UnityARImageAnchorData_t29968876 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2020[5] = { UnityARImageAnchorData_t29968876::get_offset_of_ptrIdentifier_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARImageAnchorData_t29968876::get_offset_of_transform_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARImageAnchorData_t29968876::get_offset_of_referenceImageNamePtr_2() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARImageAnchorData_t29968876::get_offset_of_referenceImagePhysicalSize_3() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARImageAnchorData_t29968876::get_offset_of_isTracked_4() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2021 = { sizeof (ARImageAnchor_t416321645), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2021[1] = { ARImageAnchor_t416321645::get_offset_of_imageAnchorData_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2022 = { sizeof (ARLightEstimate_t3477821059)+ sizeof (RuntimeObject), sizeof(ARLightEstimate_t3477821059 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2022[1] = { ARLightEstimate_t3477821059::get_offset_of_ambientIntensity_0() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2023 = { sizeof (UnityARLightEstimate_t311267890)+ sizeof (RuntimeObject), sizeof(UnityARLightEstimate_t311267890 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2023[2] = { UnityARLightEstimate_t311267890::get_offset_of_ambientIntensity_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARLightEstimate_t311267890::get_offset_of_ambientColorTemperature_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2024 = { sizeof (MarshalDirectionalLightEstimate_t3614627546)+ sizeof (RuntimeObject), sizeof(MarshalDirectionalLightEstimate_t3614627546 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2024[2] = { MarshalDirectionalLightEstimate_t3614627546::get_offset_of_primaryDirAndIntensity_0() + static_cast<int32_t>(sizeof(RuntimeObject)), MarshalDirectionalLightEstimate_t3614627546::get_offset_of_sphericalHarmonicCoefficientsPtr_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2025 = { sizeof (UnityARDirectionalLightEstimate_t1689150542), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2025[3] = { UnityARDirectionalLightEstimate_t1689150542::get_offset_of_primaryLightDirection_0(), UnityARDirectionalLightEstimate_t1689150542::get_offset_of_primaryLightIntensity_1(), UnityARDirectionalLightEstimate_t1689150542::get_offset_of_sphericalHarmonicsCoefficients_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2026 = { sizeof (LightDataType_t1811330778)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2026[3] = { LightDataType_t1811330778::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2027 = { sizeof (UnityMarshalLightData_t3773526525)+ sizeof (RuntimeObject), sizeof(UnityMarshalLightData_t3773526525 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2027[3] = { UnityMarshalLightData_t3773526525::get_offset_of_arLightingType_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityMarshalLightData_t3773526525::get_offset_of_arLightEstimate_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityMarshalLightData_t3773526525::get_offset_of_arDirectonalLightEstimate_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2028 = { sizeof (UnityARLightData_t1178200316)+ sizeof (RuntimeObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2028[3] = { UnityARLightData_t1178200316::get_offset_of_arLightingType_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARLightData_t1178200316::get_offset_of_arLightEstimate_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARLightData_t1178200316::get_offset_of_arDirectonalLightEstimate_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2029 = { sizeof (UnityARObjectAnchorData_t938871002)+ sizeof (RuntimeObject), sizeof(UnityARObjectAnchorData_t938871002 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2029[4] = { UnityARObjectAnchorData_t938871002::get_offset_of_ptrIdentifier_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARObjectAnchorData_t938871002::get_offset_of_transform_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARObjectAnchorData_t938871002::get_offset_of_referenceObjectNamePtr_2() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARObjectAnchorData_t938871002::get_offset_of_referenceObjectPtr_3() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2030 = { sizeof (ARObjectAnchor_t4188951463), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2030[1] = { ARObjectAnchor_t4188951463::get_offset_of_objectAnchorData_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2031 = { sizeof (UnityARPlaneGeometry_t1435619558)+ sizeof (RuntimeObject), sizeof(UnityARPlaneGeometry_t1435619558 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2031[8] = { UnityARPlaneGeometry_t1435619558::get_offset_of_vertexCount_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARPlaneGeometry_t1435619558::get_offset_of_vertices_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARPlaneGeometry_t1435619558::get_offset_of_textureCoordinateCount_2() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARPlaneGeometry_t1435619558::get_offset_of_textureCoordinates_3() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARPlaneGeometry_t1435619558::get_offset_of_triangleCount_4() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARPlaneGeometry_t1435619558::get_offset_of_triangleIndices_5() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARPlaneGeometry_t1435619558::get_offset_of_boundaryVertexCount_6() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARPlaneGeometry_t1435619558::get_offset_of_boundaryVertices_7() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2032 = { sizeof (UnityARAnchorData_t2901866349)+ sizeof (RuntimeObject), sizeof(UnityARAnchorData_t2901866349 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2032[6] = { UnityARAnchorData_t2901866349::get_offset_of_ptrIdentifier_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARAnchorData_t2901866349::get_offset_of_transform_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARAnchorData_t2901866349::get_offset_of_alignment_2() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARAnchorData_t2901866349::get_offset_of_center_3() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARAnchorData_t2901866349::get_offset_of_extent_4() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARAnchorData_t2901866349::get_offset_of_planeGeometry_5() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2033 = { sizeof (ARPlaneGeometry_t1176774719), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2033[1] = { ARPlaneGeometry_t1176774719::get_offset_of_uPlaneGeometry_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2034 = { sizeof (ARPlaneAnchor_t1439520888), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2034[2] = { ARPlaneAnchor_t1439520888::get_offset_of_planeAnchorData_0(), ARPlaneAnchor_t1439520888::get_offset_of_U3CidentifierStrU3Ek__BackingField_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2035 = { sizeof (ARPlaneAnchorAlignment_t2379298071)+ sizeof (RuntimeObject), sizeof(int64_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2035[3] = { ARPlaneAnchorAlignment_t2379298071::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2036 = { sizeof (ARPoint_t3436811567)+ sizeof (RuntimeObject), sizeof(ARPoint_t3436811567 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2036[2] = { ARPoint_t3436811567::get_offset_of_x_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ARPoint_t3436811567::get_offset_of_y_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2037 = { sizeof (ARPointCloud_t2004641850), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2037[3] = { ARPointCloud_t2004641850::get_offset_of_m_Ptr_0(), ARPointCloud_t2004641850::get_offset_of_m_Positions_1(), ARPointCloud_t2004641850::get_offset_of_m_Identifiers_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2038 = { sizeof (ARRect_t3555590363)+ sizeof (RuntimeObject), sizeof(ARRect_t3555590363 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2038[2] = { ARRect_t3555590363::get_offset_of_origin_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ARRect_t3555590363::get_offset_of_size_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2039 = { sizeof (ARReferenceObject_t2984430917), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2039[1] = { ARReferenceObject_t2984430917::get_offset_of_m_Ptr_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2040 = { sizeof (ARKitObjectScanningSessionConfiguration_t3781767695)+ sizeof (RuntimeObject), sizeof(ARKitObjectScanningSessionConfiguration_t3781767695_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable2040[5] = { ARKitObjectScanningSessionConfiguration_t3781767695::get_offset_of_alignment_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitObjectScanningSessionConfiguration_t3781767695::get_offset_of_planeDetection_1() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitObjectScanningSessionConfiguration_t3781767695::get_offset_of_getPointCloudData_2() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitObjectScanningSessionConfiguration_t3781767695::get_offset_of_enableLightEstimation_3() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitObjectScanningSessionConfiguration_t3781767695::get_offset_of_enableAutoFocus_4() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2041 = { sizeof (serializableARReferenceObject_t284449772), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2041[1] = { serializableARReferenceObject_t284449772::get_offset_of_arReferenceObjectData_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2042 = { sizeof (ARSize_t3911821096)+ sizeof (RuntimeObject), sizeof(ARSize_t3911821096 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2042[2] = { ARSize_t3911821096::get_offset_of_width_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ARSize_t3911821096::get_offset_of_height_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2043 = { sizeof (ARTextureHandles_t3764914833), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2043[1] = { ARTextureHandles_t3764914833::get_offset_of_m_ARTextureHandlesStruct_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2044 = { sizeof (ARTextureHandlesStruct_t617670158)+ sizeof (RuntimeObject), sizeof(ARTextureHandlesStruct_t617670158 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2044[2] = { ARTextureHandlesStruct_t617670158::get_offset_of_textureY_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ARTextureHandlesStruct_t617670158::get_offset_of_textureCbCr_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2045 = { sizeof (ARTrackingQuality_t55960597)+ sizeof (RuntimeObject), sizeof(int64_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2045[5] = { ARTrackingQuality_t55960597::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2046 = { sizeof (ARTrackingState_t2048880995)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2046[4] = { ARTrackingState_t2048880995::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2047 = { sizeof (ARTrackingStateReason_t4227173799)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2047[6] = { ARTrackingStateReason_t4227173799::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2048 = { sizeof (ARUserAnchor_t4064312267)+ sizeof (RuntimeObject), sizeof(ARUserAnchor_t4064312267_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable2048[2] = { ARUserAnchor_t4064312267::get_offset_of_identifier_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ARUserAnchor_t4064312267::get_offset_of_transform_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2049 = { sizeof (UnityARVideoFormat_t544330776)+ sizeof (RuntimeObject), sizeof(UnityARVideoFormat_t544330776 ), sizeof(UnityARVideoFormat_t544330776_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable2049[7] = { UnityARVideoFormat_t544330776::get_offset_of_videoFormatPtr_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARVideoFormat_t544330776::get_offset_of_imageResolutionWidth_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARVideoFormat_t544330776::get_offset_of_imageResolutionHeight_2() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARVideoFormat_t544330776::get_offset_of_framesPerSecond_3() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARVideoFormat_t544330776_StaticFields::get_offset_of_videoFormatsList_4(), UnityARVideoFormat_t544330776_StaticFields::get_offset_of_U3CU3Ef__mgU24cache0_5(), UnityARVideoFormat_t544330776_StaticFields::get_offset_of_U3CU3Ef__mgU24cache1_6(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2050 = { sizeof (VideoFormatEnumerator_t1718260816), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2051 = { sizeof (ARWorldMappingStatus_t1070279697)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2051[5] = { ARWorldMappingStatus_t1070279697::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2052 = { sizeof (ARWorldMap_t3922181545), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2052[1] = { ARWorldMap_t3922181545::get_offset_of_m_Ptr_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2053 = { sizeof (serializableARWorldMap_t3518979552), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2053[1] = { serializableARWorldMap_t3518979552::get_offset_of_arWorldMapData_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2054 = { sizeof (UnityARMatrix4x4_t100931615)+ sizeof (RuntimeObject), sizeof(UnityARMatrix4x4_t100931615 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2054[4] = { UnityARMatrix4x4_t100931615::get_offset_of_column0_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARMatrix4x4_t100931615::get_offset_of_column1_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARMatrix4x4_t100931615::get_offset_of_column2_2() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARMatrix4x4_t100931615::get_offset_of_column3_3() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2055 = { sizeof (UnityVideoParams_t2644681676)+ sizeof (RuntimeObject), sizeof(UnityVideoParams_t2644681676 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2055[5] = { UnityVideoParams_t2644681676::get_offset_of_yWidth_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityVideoParams_t2644681676::get_offset_of_yHeight_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityVideoParams_t2644681676::get_offset_of_screenOrientation_2() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityVideoParams_t2644681676::get_offset_of_texCoordScale_3() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityVideoParams_t2644681676::get_offset_of_cvPixelBufferPtr_4() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2056 = { sizeof (internal_UnityARCamera_t2580192745)+ sizeof (RuntimeObject), sizeof(internal_UnityARCamera_t2580192745 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2056[10] = { internal_UnityARCamera_t2580192745::get_offset_of_worldTransform_0() + static_cast<int32_t>(sizeof(RuntimeObject)), internal_UnityARCamera_t2580192745::get_offset_of_projectionMatrix_1() + static_cast<int32_t>(sizeof(RuntimeObject)), internal_UnityARCamera_t2580192745::get_offset_of_trackingState_2() + static_cast<int32_t>(sizeof(RuntimeObject)), internal_UnityARCamera_t2580192745::get_offset_of_trackingReason_3() + static_cast<int32_t>(sizeof(RuntimeObject)), internal_UnityARCamera_t2580192745::get_offset_of_videoParams_4() + static_cast<int32_t>(sizeof(RuntimeObject)), internal_UnityARCamera_t2580192745::get_offset_of_lightData_5() + static_cast<int32_t>(sizeof(RuntimeObject)), internal_UnityARCamera_t2580192745::get_offset_of_displayTransform_6() + static_cast<int32_t>(sizeof(RuntimeObject)), internal_UnityARCamera_t2580192745::get_offset_of_pointCloud_7() + static_cast<int32_t>(sizeof(RuntimeObject)), internal_UnityARCamera_t2580192745::get_offset_of_getLightEstimation_8() + static_cast<int32_t>(sizeof(RuntimeObject)), internal_UnityARCamera_t2580192745::get_offset_of_worldMappngStatus_9() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2057 = { sizeof (UnityARCamera_t4198559457)+ sizeof (RuntimeObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2057[9] = { UnityARCamera_t4198559457::get_offset_of_worldTransform_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARCamera_t4198559457::get_offset_of_projectionMatrix_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARCamera_t4198559457::get_offset_of_trackingState_2() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARCamera_t4198559457::get_offset_of_trackingReason_3() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARCamera_t4198559457::get_offset_of_videoParams_4() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARCamera_t4198559457::get_offset_of_lightData_5() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARCamera_t4198559457::get_offset_of_displayTransform_6() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARCamera_t4198559457::get_offset_of_pointCloud_7() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARCamera_t4198559457::get_offset_of_worldMappingStatus_8() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2058 = { sizeof (UnityARUserAnchorData_t2645079618)+ sizeof (RuntimeObject), sizeof(UnityARUserAnchorData_t2645079618 ), 0, 0 }; extern const int32_t g_FieldOffsetTable2058[2] = { UnityARUserAnchorData_t2645079618::get_offset_of_ptrIdentifier_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARUserAnchorData_t2645079618::get_offset_of_transform_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2059 = { sizeof (UnityARHitTestResult_t4129824344)+ sizeof (RuntimeObject), sizeof(UnityARHitTestResult_t4129824344_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable2059[6] = { UnityARHitTestResult_t4129824344::get_offset_of_type_0() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARHitTestResult_t4129824344::get_offset_of_distance_1() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARHitTestResult_t4129824344::get_offset_of_localTransform_2() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARHitTestResult_t4129824344::get_offset_of_worldTransform_3() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARHitTestResult_t4129824344::get_offset_of_anchor_4() + static_cast<int32_t>(sizeof(RuntimeObject)), UnityARHitTestResult_t4129824344::get_offset_of_isValid_5() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2060 = { sizeof (UnityARAlignment_t2379988631)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2060[4] = { UnityARAlignment_t2379988631::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2061 = { sizeof (UnityARPlaneDetection_t612575857)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2061[5] = { UnityARPlaneDetection_t612575857::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2062 = { sizeof (ARKitSessionConfiguration_t318899795)+ sizeof (RuntimeObject), sizeof(ARKitSessionConfiguration_t318899795_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable2062[3] = { ARKitSessionConfiguration_t318899795::get_offset_of_alignment_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitSessionConfiguration_t318899795::get_offset_of_getPointCloudData_1() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitSessionConfiguration_t318899795::get_offset_of_enableLightEstimation_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2063 = { sizeof (ARKitWorldTrackingSessionConfiguration_t1371796706)+ sizeof (RuntimeObject), sizeof(ARKitWorldTrackingSessionConfiguration_t1371796706_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable2063[12] = { ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_alignment_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_planeDetection_1() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_getPointCloudData_2() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_enableLightEstimation_3() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_enableAutoFocus_4() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_environmentTexturing_5() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_maximumNumberOfTrackedImages_6() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_videoFormat_7() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_referenceImagesGroupName_8() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_referenceObjectsGroupName_9() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_dynamicReferenceObjectsPtr_10() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitWorldTrackingSessionConfiguration_t1371796706::get_offset_of_m_worldMapPtr_11() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2064 = { sizeof (ARKitFaceTrackingConfiguration_t2393628587)+ sizeof (RuntimeObject), sizeof(ARKitFaceTrackingConfiguration_t2393628587_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable2064[3] = { ARKitFaceTrackingConfiguration_t2393628587::get_offset_of_alignment_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitFaceTrackingConfiguration_t2393628587::get_offset_of_enableLightEstimation_1() + static_cast<int32_t>(sizeof(RuntimeObject)), ARKitFaceTrackingConfiguration_t2393628587::get_offset_of_videoFormat_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2065 = { sizeof (UnityARSessionRunOption_t3123075684)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2065[3] = { UnityARSessionRunOption_t3123075684::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2066 = { sizeof (UnityARKitPluginSettings_t857412912), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2066[2] = { UnityARKitPluginSettings_t857412912::get_offset_of_m_ARKitUsesFacetracking_2(), UnityARKitPluginSettings_t857412912::get_offset_of_AppRequiresARKit_3(), }; #ifdef __clang__ #pragma clang diagnostic pop #endif
42.862857
240
0.83157
skarian92
db34e06a9e3044060d413dc08b5936f60256d177
35,612
cxx
C++
EMCAL/EMCALsim/AliEMCALv0.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
null
null
null
EMCAL/EMCALsim/AliEMCALv0.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
2
2016-11-25T08:40:56.000Z
2019-10-11T12:29:29.000Z
EMCAL/EMCALsim/AliEMCALv0.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //_________________________________________________________________________ // Implementation version v0 of EMCAL Manager class // An object of this class does not produce hits nor digits // It is the one to use if you do not want to produce outputs in TREEH or TREED // This class places a Geometry of the EMCAL in the ALICE Detector as defined in AliEMCALGeometry.cxx //*-- Author: Yves Schutz (SUBATECH) //*-- and : Sahal Yacoob (LBL / UCT) // : Alexei Pavlinov (WSU) SHASHLYK // : Adapted for DCAL by M.L. Wang CCNU & Subatech Oct-19-2012 // --- ROOT system --- #include <cassert> #include <TGeometry.h> #include <TGeoPhysicalNode.h> #include <TGeoManager.h> #include <TGeoMatrix.h> #include <TVirtualMC.h> #include <TArrayI.h> #include <TROOT.h> #include <TList.h> #include <TVector2.h> #include <cassert> // --- Standard library --- //#include <stdio.h> // --- AliRoot header files --- #include "AliRun.h" #include "AliLog.h" #include "AliGeomManager.h" //--- EMCAL system--- #include "AliEMCALShishKebabTrd1Module.h" #include "AliEMCALv0.h" #include "AliEMCALGeometry.h" #include "AliEMCALSpaceFrame.h" ClassImp(AliEMCALv0) // EMCAL material: look to the AliEMCAL.cxx enum { kIdAIR = 1599, kIdPB = 1600, kIdSC = 1601, kIdAL = 1602, kIdSTEEL = 1603, kIdPAPER = 1604 }; //______________________________________________________________________ AliEMCALv0::AliEMCALv0() : AliEMCAL(), fShishKebabModules(),fEnvelop1(0),fIdRotm(0),fIdTmedArr(0), fSampleWidth(0),fSmodPar0(0),fSmodPar1(0),fSmodPar2(0), fInnerEdge(0),fCalFrame(0) { //default ctor for(Int_t i = 0; i < 5 ; i++) fParEMOD[i]=0.0; } //______________________________________________________________________ AliEMCALv0::AliEMCALv0(const char *name, const char *title, const Bool_t checkGeoAndRun) : AliEMCAL(name,title,checkGeoAndRun), fShishKebabModules(),fEnvelop1(0),fIdRotm(0),fIdTmedArr(0), fSampleWidth(0),fSmodPar0(0),fSmodPar1(0),fSmodPar2(0), fInnerEdge(0),fCalFrame(0) { // ctor : title is used to identify the layout // Apr 25, 2006 // Nov 22, 2006 - case of 1X1 for(Int_t i = 0; i < 5 ; i++) fParEMOD[i]=0.0; TString ntmp(GetTitle()); ntmp.ToUpper(); fGeometry = GetGeometry() ; TString gn(fGeometry->GetName()); gn.ToUpper(); fShishKebabModules = fGeometry->GetShishKebabTrd1Modules(); fSampleWidth = Double_t(fGeometry->GetECPbRadThick() + fGeometry->GetECScintThick()); if(gn.Contains("V1")) fSampleWidth += 2.*fGeometry->GetTrd1BondPaperThick(); AliDebug(2,Form("fGeometry %p : TVirtualMC::GetMC() %p : fSampleWidth %5.4f\n", fGeometry, TVirtualMC::GetMC(), fSampleWidth)); // Set geometry name again, in case it was changed during the initialization of the geometry. SetTitle(fGeometry->GetEMCGeometry()->GetName()); } //______________________________________________________________________ void AliEMCALv0::CreateGeometry() { // Create the EMCAL geometry for Geant // Geometry of a tower AliEMCALGeometry * geom = GetGeometry() ; TString gn(geom->GetName()); gn.ToUpper(); if(!(geom->IsInitialized())){ Error("CreateGeometry","EMCAL Geometry class has not been set up."); } // end if // Get pointer to the array containing media indices fIdTmedArr = fIdtmed->GetArray() - 1599 ; fIdRotm = 1; // TVirtualMC::GetMC()->Matrix(nmat, theta1, phi1, theta2, phi2, theta3, phi3) - see AliModule AliMatrix(fIdRotm, 90.0, 0., 90.0, 90.0, 0.0, 0.0) ; // Create the EMCAL Mother Volume (a polygone) within which to place the Detector and named XEN1 Float_t envelopA[10]; if(gn.Contains("WSUC") ) { // TRD1 for WSUC facility // Nov 25,2010 envelopA[0] = 30.; envelopA[1] = 30; envelopA[2] = 20; TVirtualMC::GetMC()->Gsvolu("XEN1", "BOX", fIdTmedArr[kIdSC], envelopA, 3) ; fEnvelop1.Set(3); for(Int_t i=0; i<3; i++) fEnvelop1[i] = envelopA[i]; // 23-may-05 // Position the EMCAL Mother Volume (XEN1) in WSUC. // Look to AliEMCALWsuCosmicRaySetUp. TVirtualMC::GetMC()->Gspos("XEN1", 1, "WSUC", 0.0, 0.0, + 265., fIdRotm, "ONLY") ; } else { envelopA[0] = geom->GetArm1PhiMin(); // minimum phi angle envelopA[1] = geom->GetArm1PhiMax() - geom->GetArm1PhiMin(); // angular range in phi envelopA[2] = envelopA[1]/geom->GetEMCGeometry()->GetPhiSuperModule(); // Section of that envelopA[3] = 2; // 2: z coordinates envelopA[4] = -geom->GetEnvelop(2)/2.; // zmin - includes padding envelopA[5] = geom->GetEnvelop(0) ; // rmin at z1 - includes padding envelopA[6] = geom->GetEnvelop(1) ; // rmax at z1 - includes padding envelopA[7] = geom->GetEnvelop(2)/2.; // zmax includes padding envelopA[8] = envelopA[5] ; // radii are the same. envelopA[9] = envelopA[6] ; // radii are the same. TVirtualMC::GetMC()->Gsvolu("XEN1", "PGON", fIdTmedArr[kIdAIR], envelopA, 10) ; // Polygone filled with air fEnvelop1.Set(10, envelopA); if (gDebug==2) { printf("CreateGeometry: XEN1 = %f, %f\n", envelopA[5], envelopA[6]); printf("CreateGeometry: XU0 = %f, %f\n", envelopA[5], envelopA[6]); } // Position the EMCAL Mother Volume (XEN1) in Alice (ALIC) TVirtualMC::GetMC()->Gspos(geom->GetNameOfEMCALEnvelope(), 1, "ALIC", 0.0, 0.0, 0.0, fIdRotm, "ONLY") ; } // COMPACT, TRD1 AliDebug(2,Form("Shish-Kebab geometry : %s", GetTitle())); CreateShishKebabGeometry(); if(gn.Contains("WSUC")==0) { // Nov 24,2010 for TB //Space Frame AliDebug(2,"Creating EMCAL Space Frame"); fCalFrame = new AliEMCALSpaceFrame(); fCalFrame->CreateGeometry(); } // Set the sampling fraction used at creation hit level // Previously called in AliEMCALEMCGeometry::Init(), put it here for proper initialization by Geant3/4 geom->GetEMCGeometry()->DefineSamplingFraction(TVirtualMC::GetMC()->GetName(),TVirtualMC::GetMC()->GetTitle()); } //______________________________________________________________________ void AliEMCALv0::Init(void) { // Just prints an information message AliEMCAL::Init(); if(AliLog::GetGlobalDebugLevel()>0) { TString message("\n") ; message += "*****************************************\n" ; // Here the EMCAL initialisation code (if any!) AliEMCALGeometry * geom = GetGeometry() ; if (geom!=0) { message += "AliEMCAL " ; message += Version() ; message += "EMCAL geometry initialized for " ; message += geom->GetName() ; } else { message += "AliEMCAL " ; message += Version() ; message += "EMCAL geometry initialization failed !" ; } message += "\n*****************************************" ; printf("%s",message.Data() ) ; } } // 24-aug-04 by PAI //______________________________________________________________________ void AliEMCALv0::CreateShishKebabGeometry() { // Oct 26,2010 // TRD1 AliEMCALGeometry * g = GetGeometry(); TString gn(g->GetName()); gn.ToUpper(); Double_t trd1Angle = g->GetTrd1Angle()*TMath::DegToRad(), tanTrd1 = TMath::Tan(trd1Angle/2.); // see AliModule::fFIdTmedArr // fIdTmedArr = fIdtmed->GetArray() - 1599 ; // see AliEMCAL::::CreateMaterials() // Int_t kIdAIR=1599, kIdPB = 1600, kIdSC = 1601, kIdSTEEL = 1603; // idAL = 1602; Double_t par[10], xpos=0., ypos=0., zpos=0.; CreateSmod(g->GetNameOfEMCALEnvelope()); Int_t * SMTypeList = g->GetEMCSystem(); Int_t tmpType = -1; for(Int_t i = 0 ; i < g->GetNumberOfSuperModules(); i++) { if( SMTypeList[i] == tmpType) continue; else tmpType = SMTypeList[i]; if( tmpType == AliEMCALGeometry::kEMCAL_Standard ) CreateEmod("SMOD","EMOD"); // 18-may-05 else if( tmpType == AliEMCALGeometry::kEMCAL_Half ) CreateEmod("SM10","EMOD"); // Nov 1,2006 1/2 SM else if( tmpType == AliEMCALGeometry::kEMCAL_3rd ) CreateEmod("SM3rd","EMOD"); // Feb 1,2012 1/3 SM else if( tmpType == AliEMCALGeometry::kDCAL_Standard ) CreateEmod("DCSM","EMOD"); // Mar 13, 2012, 6 or 10 DCSM else if( tmpType == AliEMCALGeometry::kDCAL_Ext ) CreateEmod("DCEXT","EMOD"); // Mar 13, 2012, DCAL extension SM else AliError("Unkown SM Type!!"); } // Sensitive SC (2x2 tiles) Double_t parSCM0[5]={0,0,0,0}, *dummy = 0, parTRAP[11]; if(!gn.Contains("V1")) { Double_t wallThickness = g->GetPhiModuleSize()/g->GetNPHIdiv() - g->GetPhiTileSize(); for(Int_t i=0; i<3; i++) parSCM0[i] = fParEMOD[i] - wallThickness; parSCM0[3] = fParEMOD[3]; TVirtualMC::GetMC()->Gsvolu("SCM0", "TRD1", fIdTmedArr[kIdAIR], parSCM0, 4); TVirtualMC::GetMC()->Gspos("SCM0", 1, "EMOD", 0., 0., 0., 0, "ONLY") ; } else { Double_t wTh = g->GetLateralSteelStrip(); parSCM0[0] = fParEMOD[0] - wTh + tanTrd1*g->GetTrd1AlFrontThick(); parSCM0[1] = fParEMOD[1] - wTh; parSCM0[2] = fParEMOD[2] - wTh; parSCM0[3] = fParEMOD[3] - g->GetTrd1AlFrontThick()/2.; TVirtualMC::GetMC()->Gsvolu("SCM0", "TRD1", fIdTmedArr[kIdAIR], parSCM0, 4); Double_t zshift = g->GetTrd1AlFrontThick()/2.; TVirtualMC::GetMC()->Gspos("SCM0", 1, "EMOD", 0., 0., zshift, 0, "ONLY"); // CreateAlFrontPlate("EMOD","ALFP"); } if(g->GetNPHIdiv()==2 && g->GetNETAdiv()==2) { // Division to tile size - 1-oct-04 AliDebug(2,Form(" Divide SCM0 on y-axis %i\n", g->GetNETAdiv())); TVirtualMC::GetMC()->Gsdvn("SCMY","SCM0", g->GetNETAdiv(), 2); // y-axis // Trapesoid 2x2 parTRAP[0] = parSCM0[3]; // dz parTRAP[1] = TMath::ATan2((parSCM0[1]-parSCM0[0])/2.,2.*parSCM0[3])*180./TMath::Pi(); // theta parTRAP[2] = 0.; // phi // bottom parTRAP[3] = parSCM0[2]/2.; // H1 parTRAP[4] = parSCM0[0]/2.; // BL1 parTRAP[5] = parTRAP[4]; // TL1 parTRAP[6] = 0.0; // ALP1 // top parTRAP[7] = parSCM0[2]/2.; // H2 parTRAP[8] = parSCM0[1]/2.; // BL2 parTRAP[9] = parTRAP[8]; // TL2 parTRAP[10]= 0.0; // ALP2 AliDebug(2,Form(" ** TRAP ** \n")); for(Int_t i=0; i<11; i++) AliDebug(3, Form(" par[%2.2i] %9.4f\n", i, parTRAP[i])); TVirtualMC::GetMC()->Gsvolu("SCMX", "TRAP", fIdTmedArr[kIdSC], parTRAP, 11); xpos = +(parSCM0[1]+parSCM0[0])/4.; TVirtualMC::GetMC()->Gspos("SCMX", 1, "SCMY", xpos, 0.0, 0.0, 0, "ONLY") ; // Using rotation because SCMX should be the same due to Pb tiles xpos = -xpos; AliMatrix(fIdRotm, 90.0,180., 90.0, 270.0, 0.0,0.0) ; TVirtualMC::GetMC()->Gspos("SCMX", 2, "SCMY", xpos, 0.0, 0.0, fIdRotm, "ONLY"); // put LED to the SCM0 AliEMCALShishKebabTrd1Module *mod = (AliEMCALShishKebabTrd1Module*)fShishKebabModules->At(0); Double_t tanBetta = mod->GetTanBetta(); Int_t nr=0; ypos = 0.0; Double_t xCenterSCMX = (parTRAP[4] + parTRAP[8])/2.; if(!gn.Contains("V1")) { par[1] = parSCM0[2]/2; // y par[2] = g->GetECPbRadThick()/2.; // z TVirtualMC::GetMC()->Gsvolu("PBTI", "BOX", fIdTmedArr[kIdPB], dummy, 0); zpos = -fSampleWidth*g->GetNECLayers()/2. + g->GetECPbRadThick()/2.; AliDebug(2,Form(" Pb tiles \n")); for(Int_t iz=0; iz<g->GetNECLayers(); iz++){ par[0] = (parSCM0[0] + tanBetta*fSampleWidth*iz)/2.; xpos = par[0] - xCenterSCMX; TVirtualMC::GetMC()->Gsposp("PBTI", ++nr, "SCMX", xpos, ypos, zpos, 0, "ONLY", par, 3) ; AliDebug(3,Form(" %i xpos %f zpos %f par[0] %f \n", iz+1, xpos, zpos, par[0])); zpos += fSampleWidth; } AliDebug(2,Form(" Number of Pb tiles in SCMX %i \n", nr)); } else { // Oct 26, 2010 // First sheet of paper par[1] = parSCM0[2]/2.; // y par[2] = g->GetTrd1BondPaperThick()/2.; // z par[0] = parSCM0[0]/2.; // x TVirtualMC::GetMC()->Gsvolu("PAP1", "BOX", fIdTmedArr[kIdPAPER], par, 3); xpos = par[0] - xCenterSCMX; zpos = -parSCM0[3] + g->GetTrd1BondPaperThick()/2.; TVirtualMC::GetMC()->Gspos("PAP1", 1, "SCMX", xpos, ypos, zpos, 0, "ONLY"); for(Int_t iz=0; iz<g->GetNECLayers()-1; iz++){ nr = iz + 1; Double_t dz = g->GetECScintThick() + g->GetTrd1BondPaperThick() + fSampleWidth*iz; // PB + 2 paper sheets par[2] = g->GetECPbRadThick()/2. + g->GetTrd1BondPaperThick(); // z par[0] = (parSCM0[0] + tanBetta*dz)/2.; TString pa(Form("PA%2.2i",nr)); TVirtualMC::GetMC()->Gsvolu(pa.Data(), "BOX", fIdTmedArr[kIdPAPER], par, 3); xpos = par[0] - xCenterSCMX; zpos = -parSCM0[3] + dz + par[2]; TVirtualMC::GetMC()->Gspos(pa.Data(), 1, "SCMX", xpos, ypos, zpos, 0, "ONLY") ; // Pb TString pb(Form("PB%2.2i",nr)); par[2] = g->GetECPbRadThick()/2.; // z TVirtualMC::GetMC()->Gsvolu(pb.Data(), "BOX", fIdTmedArr[kIdPB], par, 3); TVirtualMC::GetMC()->Gspos(pb.Data(), 1, pa.Data(), 0.0, 0.0, 0.0, 0, "ONLY") ; } } } else if(g->GetNPHIdiv()==3 && g->GetNETAdiv()==3) { printf(" before AliEMCALv0::Trd1Tower3X3() : parSCM0"); for(Int_t i=0; i<4; i++) printf(" %7.4f ", parSCM0[i]); printf("\n"); Trd1Tower3X3(parSCM0); } else if(g->GetNPHIdiv()==1 && g->GetNETAdiv()==1) { // no division in SCM0 Trd1Tower1X1(parSCM0); } } //______________________________________________________________________ void AliEMCALv0::CreateSmod(const char* mother) { // 18-may-05; mother="XEN1"; // child="SMOD" from first to 10th, "SM10" (11th and 12th) // "DCSM" from 13th to 18/22th (TRD1 case), "DCEXT"(18th and 19th) adapted for DCAL, Oct-23-2012 AliEMCALGeometry * g = GetGeometry(); TString gn(g->GetName()); gn.ToUpper(); Double_t par[3], xpos=0., ypos=0., zpos=0., rpos=0., dphi=0., phi=0.0, phiRad=0.; Double_t parC[3] = {0}; TString smName; Int_t tmpType = -1; // ===== define Super Module from air - 14x30 module ==== ; AliDebug(2,Form("\n ## Super Module | fSampleWidth %5.3f ## %s \n", fSampleWidth, gn.Data())); par[0] = g->GetShellThickness()/2.; par[1] = g->GetPhiModuleSize()*g->GetNPhi()/2.; par[2] = g->GetEtaModuleSize()*g->GetNEta()/2.; fIdRotm=0; Int_t nSMod = g->GetNumberOfSuperModules(); Int_t nphism = nSMod/2; // 20-may-05 if(nphism > 0) { dphi = g->GetEMCGeometry()->GetPhiSuperModule(); rpos = (g->GetEnvelop(0) + g->GetEnvelop(1))/2.; AliDebug(2,Form(" rpos %8.2f : dphi %6.1f degree \n", rpos, dphi)); } if(gn.Contains("WSUC")) { Int_t nr=0; par[0] = g->GetPhiModuleSize()*g->GetNPhi()/2.; par[1] = g->GetShellThickness()/2.; par[2] = g->GetEtaModuleSize()*g->GetNZ()/2. + 5; TVirtualMC::GetMC()->Gsvolu("SMOD", "BOX", fIdTmedArr[kIdAIR], par, 3); AliDebug(2,Form("SMOD in WSUC : tmed %i | dx %7.2f dy %7.2f dz %7.2f (SMOD, BOX)\n", fIdTmedArr[kIdAIR], par[0],par[1],par[2])); fSmodPar0 = par[0]; fSmodPar1 = par[1]; fSmodPar2 = par[2]; nphism = g->GetNumberOfSuperModules(); for(Int_t i=0; i<nphism; i++) { xpos = ypos = zpos = 0.0; fIdRotm = 0; TVirtualMC::GetMC()->Gspos("SMOD", 1, mother, xpos, ypos, zpos, fIdRotm, "ONLY") ; printf(" fIdRotm %3i phi %6.1f(%5.3f) xpos %7.2f ypos %7.2f zpos %7.2f \n", fIdRotm, phi, phiRad, xpos, ypos, zpos); nr++; } } else {// ALICE AliDebug(2,Form(" par[0] %7.2f (old) \n", par[0])); for(Int_t i=0; i<3; i++) par[i] = g->GetSuperModulesPar(i); fSmodPar0 = par[0]; fSmodPar2 = par[2]; Int_t SMOrder = -1; tmpType = -1; for (Int_t smodnum = 0; smodnum < nSMod; ++smodnum) { for(Int_t i=0; i<3; i++) parC[i] = par[i]; if(g->GetSMType(smodnum) == tmpType) { SMOrder++; } else { tmpType = g->GetSMType(smodnum); SMOrder = 1; } phiRad = g->GetPhiCenterOfSMSec(smodnum); // NEED phi= 90, 110, 130, 150, 170, 190(not center)... phi = phiRad *180./TMath::Pi(); Double_t phiy = 90. + phi; Double_t phiz = 0.; xpos = rpos * TMath::Cos(phiRad); ypos = rpos * TMath::Sin(phiRad); zpos = fSmodPar2; // 21-sep-04 if( tmpType == AliEMCALGeometry::kEMCAL_Standard ) { smName="SMOD"; } else if( tmpType == AliEMCALGeometry::kEMCAL_Half ) { smName="SM10"; parC[1] /= 2.; xpos += (par[1]/2. * TMath::Sin(phiRad)); ypos -= (par[1]/2. * TMath::Cos(phiRad)); } else if( tmpType == AliEMCALGeometry::kEMCAL_3rd ) { smName="SM3rd"; parC[1] /= 3.; xpos += (2.*par[1]/3. * TMath::Sin(phiRad)); ypos -= (2.*par[1]/3. * TMath::Cos(phiRad)); } else if( tmpType == AliEMCALGeometry::kDCAL_Standard ) { smName="DCSM"; parC[2] *= 2./3.; zpos = fSmodPar2 + g->GetDCALInnerEdge()/2.; // 21-sep-04 } else if( tmpType == AliEMCALGeometry::kDCAL_Ext ) { smName="DCEXT"; parC[1] /= 3.; xpos += (2.*par[1]/3. * TMath::Sin(phiRad)); ypos -= (2.*par[1]/3. * TMath::Cos(phiRad)); } else AliError("Unkown SM Type!!"); if(SMOrder == 1) {//first time, create the SM TVirtualMC::GetMC()->Gsvolu(smName.Data(), "BOX", fIdTmedArr[kIdAIR], parC, 3); AliDebug(2,Form(" Super module with name \"%s\" was created in \"box\" with: par[0] = %f, par[1] = %f, par[2] = %f\n", smName.Data(), parC[0], parC[1], parC[2])); } if( smodnum%2 == 1) { phiy += 180.; if(phiy>=360.) phiy -= 360.; phiz = 180.; zpos *= -1.; } AliMatrix(fIdRotm, 90.0, phi, 90.0, phiy, phiz, 0.0); TVirtualMC::GetMC()->Gspos(smName.Data(), SMOrder, mother, xpos, ypos, zpos, fIdRotm, "ONLY") ; AliDebug(3, Form(" %s : %2i, fIdRotm %3i phi %6.1f(%5.3f) xpos %7.2f ypos %7.2f zpos %7.2f : i %i \n", smName.Data(), SMOrder, fIdRotm, phi, phiRad, xpos, ypos, zpos, smodnum)); } } AliDebug(2,Form(" Number of Super Modules %i \n", nSMod)); // Steel plate if(g->GetSteelFrontThickness() > 0.0) { // 28-mar-05 par[0] = g->GetSteelFrontThickness()/2.; TVirtualMC::GetMC()->Gsvolu("STPL", "BOX", fIdTmedArr[kIdSTEEL], par, 3); printf("tmed %i | dx %7.2f dy %7.2f dz %7.2f (STPL) \n", fIdTmedArr[kIdSTEEL], par[0],par[1],par[2]); xpos = -(g->GetShellThickness() - g->GetSteelFrontThickness())/2.; TVirtualMC::GetMC()->Gspos("STPL", 1, "SMOD", xpos, 0.0, 0.0, 0, "ONLY") ; } } //______________________________________________________________________ void AliEMCALv0::CreateEmod(const char* mother, const char* child) { // 17-may-05; mother="SMOD"; child="EMOD" // Oct 26,2010 AliEMCALGeometry * g = GetGeometry(); TString gn(g->GetName()); gn.ToUpper(); // Module definition Double_t xpos=0., ypos=0., zpos=0.; //Double_t trd1Angle = g->GetTrd1Angle()*TMath::DegToRad();tanTrd1 = TMath::Tan(trd1Angle/2.); if(strcmp(mother,"SMOD")==0) { fParEMOD[0] = g->GetEtaModuleSize()/2.; // dx1 fParEMOD[1] = g->Get2Trd1Dx2()/2.; // dx2 fParEMOD[2] = g->GetPhiModuleSize()/2.;; // dy fParEMOD[3] = g->GetLongModuleSize()/2.; // dz TVirtualMC::GetMC()->Gsvolu(child, "TRD1", fIdTmedArr[kIdSTEEL], fParEMOD, 4); } Int_t nr=0; fIdRotm=0; // X->Z(0, 0); Y->Y(90, 90); Z->X(90, 0) AliEMCALShishKebabTrd1Module *mod=0; // current module for(Int_t iz=0; iz<g->GetNZ(); iz++) { Double_t angle=90., phiOK=0; mod = (AliEMCALShishKebabTrd1Module*)fShishKebabModules->At(iz); angle = mod->GetThetaInDegree(); if(!gn.Contains("WSUC")) { // ALICE AliMatrix(fIdRotm, 90.-angle,180., 90.0,90.0, angle, 0.); phiOK = mod->GetCenterOfModule().Phi()*180./TMath::Pi(); AliDebug(4,Form(" %2i | angle | %6.3f - %6.3f = %6.3f(eta %5.3f)\n", iz+1, angle, phiOK, angle-phiOK, mod->GetEtaOfCenterOfModule())); xpos = mod->GetPosXfromR() + g->GetSteelFrontThickness() - fSmodPar0; zpos = mod->GetPosZ() - fSmodPar2; Int_t iyMax = g->GetNPhi(); if(strcmp(mother,"SM10") == 0 ) { iyMax /= 2; } else if(strcmp(mother,"SM3rd") == 0 ) { iyMax /= 3; } else if(strcmp(mother,"DCEXT") == 0 ) { iyMax /= 3; } else if(strcmp(mother,"DCSM") == 0 ) { if(iz < 8 ) continue;//!!!DCSM from 8th to 23th zpos = mod->GetPosZ() - fSmodPar2 - g->GetDCALInnerEdge()/2.; } else if(strcmp(mother,"SMOD") != 0 ) AliError("Unknown super module Type!!"); for(Int_t iy=0; iy<iyMax; iy++) { // flat in phi ypos = g->GetPhiModuleSize()*(2*iy+1 - iyMax)/2.; TVirtualMC::GetMC()->Gspos(child, ++nr, mother, xpos, ypos, zpos, fIdRotm, "ONLY") ; // //printf(" %2i xpos %7.2f ypos %7.2f zpos %7.2f fIdRotm %i\n", nr, xpos, ypos, zpos, fIdRotm); AliDebug(3,Form("%3.3i(%2.2i,%2.2i) ", nr,iy+1,iz+1)); } //PH printf("\n"); } else { //WSUC if(iz == 0) AliMatrix(fIdRotm, 0.,0., 90.,0., 90.,90.); // (x')z; y'(x); z'(y) else AliMatrix(fIdRotm, 90-angle,270., 90.0,0.0, angle,90.); phiOK = mod->GetCenterOfModule().Phi()*180./TMath::Pi(); AliDebug(4,Form(" %2i | angle -phiOK | %6.3f - %6.3f = %6.3f(eta %5.3f)\n", iz+1, angle, phiOK, angle-phiOK, mod->GetEtaOfCenterOfModule())); zpos = mod->GetPosZ() - fSmodPar2; ypos = mod->GetPosXfromR() - fSmodPar1; //printf(" zpos %7.2f ypos %7.2f fIdRotm %i\n xpos ", zpos, xpos, fIdRotm); for(Int_t ix=0; ix<g->GetNPhi(); ix++) { // flat in phi xpos = g->GetPhiModuleSize()*(2*ix+1 - g->GetNPhi())/2.; TVirtualMC::GetMC()->Gspos(child, ++nr, mother, xpos, ypos, zpos, fIdRotm, "ONLY") ; //printf(" %7.2f ", xpos); } //printf("\n"); } } AliDebug(2,Form(" Number of modules in Super Module(%s) %i \n", mother, nr)); } void AliEMCALv0::CreateAlFrontPlate(const char* mother, const char* child) { // Oct 26,2010 : Al front plate : ALFP AliEMCALGeometry * g = GetGeometry(); TString gn(g->GetName()); gn.ToUpper(); Double_t trd1Angle = g->GetTrd1Angle()*TMath::DegToRad(), tanTrd1 = TMath::Tan(trd1Angle/2.); Double_t parALFP[5], zposALFP=0.; parALFP[0] = g->GetEtaModuleSize()/2. - g->GetLateralSteelStrip(); // dx1 parALFP[1] = parALFP[0] + tanTrd1*g->GetTrd1AlFrontThick(); // dx2 parALFP[2] = g->GetPhiModuleSize()/2. - g->GetLateralSteelStrip(); // dy parALFP[3] = g->GetTrd1AlFrontThick()/2.; // dz TVirtualMC::GetMC()->Gsvolu(child, "TRD1", fIdTmedArr[kIdAL], parALFP, 4); zposALFP = -fParEMOD[3] + g->GetTrd1AlFrontThick()/2.; TVirtualMC::GetMC()->Gspos (child, 1, mother, 0.0, 0.0, zposALFP, 0, "ONLY"); } //______________________________________________________________________ void AliEMCALv0::Trd1Tower3X3(const Double_t *parSCM0) { // Started Dec 8,2004 by PAI // Fixed Nov 13,2006 printf(" AliEMCALv0::Trd1Tower3X3() : parSCM0"); for(Int_t i=0; i<4; i++) printf(" %7.4f ", parSCM0[i]); printf("\n"); // Nov 10, 2006 - different name of SCMX Double_t parTRAP[11], *dummy=0; AliEMCALGeometry * g = GetGeometry(); TString gn(g->GetName()), scmx; gn.ToUpper(); // Division to tile size AliDebug(2,Form("Trd1Tower3X3() : Divide SCM0 on y-axis %i", g->GetNETAdiv())); TVirtualMC::GetMC()->Gsdvn("SCMY","SCM0", g->GetNETAdiv(), 2); // y-axis Double_t dx1=parSCM0[0], dx2=parSCM0[1], dy=parSCM0[2], dz=parSCM0[3]; Double_t ndiv=3., xpos=0.0; // should be defined once TVirtualMC::GetMC()->Gsvolu("PBTI", "BOX", fIdTmedArr[kIdPB], dummy, 0); for(Int_t ix=1; ix<=3; ix++) { // 3X3 scmx = "SCX"; // Nov 10,2006 // ix=1 parTRAP[0] = dz; Double_t xCentBot = 2.*dx1/3.; Double_t xCentTop = 2.*(dx2/4. + dx1/12.); parTRAP[1] = TMath::ATan2((xCentTop-xCentBot),2.*dz)*TMath::RadToDeg(); // theta parTRAP[2] = 0.; // phi // bottom parTRAP[3] = dy/ndiv; // H1 parTRAP[4] = dx1/ndiv; // BL1 parTRAP[5] = parTRAP[4]; // TL1 parTRAP[6] = 0.0; // ALP1 // top parTRAP[7] = dy/ndiv; // H2 parTRAP[8] = dx2/2 - dx1/6.;// BL2 parTRAP[9] = parTRAP[8]; // TL2 parTRAP[10]= 0.0; // ALP2 xpos = (xCentBot+xCentTop)/2.; if (ix==3) { parTRAP[1] = -parTRAP[1]; xpos = -xpos; } else if(ix==2) { // central part is box but we treat as trapesoid due to numbering parTRAP[1] = 0.; parTRAP[8] = dx1/ndiv; // BL2 parTRAP[9] = parTRAP[8]; // TL2 xpos = 0.0; } AliDebug(2,Form(" ** TRAP ** xpos %9.3f\n", xpos)); for(Int_t i=0; i<11; i++) AliDebug(2,Form(" par[%2.2i] %9.4f\n", i, parTRAP[i])); scmx += ix; TVirtualMC::GetMC()->Gsvolu(scmx.Data(), "TRAP", fIdTmedArr[kIdSC], parTRAP, 11); TVirtualMC::GetMC()->Gspos(scmx.Data(), 1, "SCMY", xpos, 0.0, 0.0, 0, "ONLY") ; PbInTrap(parTRAP, scmx); } AliDebug(2,"Trd1Tower3X3 - Ver. 1.0 : was tested."); } // 8-dec-04 by PAI //______________________________________________________________________ void AliEMCALv0::PbInTrap(const Double_t parTRAP[11], TString n) { // see for example CreateShishKebabGeometry(); just for case TRD1 static Int_t nr=0; AliDebug(2,Form(" Pb tiles : nrstart %i\n", nr)); AliEMCALGeometry * g = GetGeometry(); Double_t par[3]; Double_t xpos = 0.0, ypos = 0.0; Double_t zpos = -fSampleWidth*g->GetNECLayers()/2. + g->GetECPbRadThick()/2.; Double_t coef = (parTRAP[8] - parTRAP[4]) / (2.*parTRAP[0]); Double_t xCenterSCMX = (parTRAP[4] + parTRAP[8])/2.; // ?? // Double_t tan = TMath::Tan(parTRAP[1]*TMath::DegToRad()); par[1] = parTRAP[3]; // y par[2] = g->GetECPbRadThick()/2.; // z for(Int_t iz=0; iz<g->GetNECLayers(); iz++){ par[0] = parTRAP[4] + coef*fSampleWidth*iz; xpos = par[0] - xCenterSCMX; if(parTRAP[1] < 0.) xpos = -xpos; TVirtualMC::GetMC()->Gsposp("PBTI", ++nr, n.Data(), xpos, ypos, zpos, 0, "ONLY", par, 3) ; AliDebug(2,Form(" %i xpos %9.3f zpos %9.3f par[0] %9.3f |", iz+1, xpos, zpos, par[0])); zpos += fSampleWidth; if(iz%2>0) printf("\n"); } AliDebug(2,Form(" Number of Pb tiles in SCMX %i coef %9.7f \n", nr, coef)); AliDebug(2,Form(" par[1] %9.3f par[2] %9.3f ypos %9.3f \n", par[1], par[2], ypos)); AliDebug(2,Form(" PbInTrap Ver. 1.0 : was tested.")); } //______________________________________________________________________ void AliEMCALv0::Trd1Tower1X1(Double_t *parSCM0) { // Started Nov 22,2006 by PAI AliDebug(1," AliEMCALv0::Trd1Tower1X1() : parSCM0"); for(Int_t i=0; i<4; i++) printf(" %7.4f ", parSCM0[i]); printf("\n"); // No division - keeping the same volume logic // and as consequence the same abs is scheme AliDebug(2,"Trd1Tower1X1() : Create SCMX(SCMY) as SCM0"); TVirtualMC::GetMC()->Gsvolu("SCMY", "TRD1", fIdTmedArr[kIdAIR], parSCM0, 4); TVirtualMC::GetMC()->Gspos("SCMY", 1, "SCM0", 0.0, 0.0, 0.0, 0, "ONLY"); TVirtualMC::GetMC()->Gsvolu("SCMX", "TRD1", fIdTmedArr[kIdSC], parSCM0, 4); TVirtualMC::GetMC()->Gspos("SCMX", 1, "SCMY", 0.0, 0.0, 0.0, 0, "ONLY"); // should be defined once Double_t *dummy=0; TVirtualMC::GetMC()->Gsvolu("PBTI", "BOX", fIdTmedArr[kIdPB], dummy, 0); PbInTrd1(parSCM0, "SCMX"); AliDebug(1,"Trd1Tower1X1() : Ver. 0.1 : was tested."); } //______________________________________________________________________ void AliEMCALv0::PbInTrd1(const Double_t *parTrd1, TString n) { // see PbInTrap(const Double_t parTrd1[11], TString n) static Int_t nr=0, ndeb=2; AliDebug(ndeb,Form(" Pb tiles : nrstart %i\n", nr)); AliEMCALGeometry * g = GetGeometry(); Double_t par[3]; Double_t xpos = 0.0, ypos = 0.0; Double_t zpos = -fSampleWidth*g->GetNECLayers()/2. + g->GetECPbRadThick()/2.; Double_t coef = (parTrd1[1] - parTrd1[0]) / (2.*parTrd1[3]); par[1] = parTrd1[2]; // y par[2] = g->GetECPbRadThick()/2.; // z for(Int_t iz=0; iz<g->GetNECLayers(); iz++){ par[0] = parTrd1[0] + coef*fSampleWidth*iz; TVirtualMC::GetMC()->Gsposp("PBTI", ++nr, n.Data(), xpos, ypos, zpos, 0, "ONLY", par, 3) ; AliDebug(2,Form(" %i xpos %9.3f zpos %9.3f par[0] %9.3f |", iz+1, xpos, zpos, par[0])); zpos += fSampleWidth; if(iz%2>0) printf("\n"); } AliDebug(ndeb,Form(" Number of Pb tiles in SCMX %i coef %9.7f ", nr, coef)); AliDebug(ndeb,Form(" PbInTrd1 Ver. 0.1 : was tested.")); } //______________________________________________________________________ AliEMCALShishKebabTrd1Module* AliEMCALv0::GetShishKebabModule(Int_t neta) { // 28-oct-05 AliEMCALShishKebabTrd1Module* trd1=0; if(fShishKebabModules && neta>=0 && neta<fShishKebabModules->GetSize()) { trd1 = (AliEMCALShishKebabTrd1Module*)fShishKebabModules->At(neta); } return trd1; } //_____________________________________________________________________________ void AliEMCALv0::AddAlignableVolumes() const { //Add volumes which are alignable (?) TString ntmp(GetTitle()); // name of EMCAL geometry if(ntmp.Contains("WSUC")) { AddAlignableVolumesInWSUC(); // WSUC case } else { AddAlignableVolumesInALICE(); // ALICE case } } //______________________________________________________________________ void AliEMCALv0::AddAlignableVolumesInALICE() const { // // Create entries for alignable volumes associating the symbolic volume // name with the corresponding volume path. Needs to be synchronized with // eventual changes in the geometry. // Float_t pars[] = {GetGeometry()->GetSuperModulesPar(0),GetGeometry()->GetSuperModulesPar(1),GetGeometry()->GetSuperModulesPar(2)}; Double_t rpos = (GetGeometry()->GetEnvelop(0) + GetGeometry()->GetEnvelop(1))/2.; Double_t phi, phiRad, xpos, ypos, zpos; AliGeomManager::ELayerID idEMCAL = AliGeomManager::kEMCAL; Int_t modUID, modnum = 0; TString volpath, symname; AliEMCALGeometry * geom = GetGeometry(); Int_t nSMod = geom->GetNumberOfSuperModules(); TString SMPathName; TString SMName; Int_t tmpType = -1; Int_t SMOrder = 0; for (Int_t smodnum = 0; smodnum < nSMod; ++smodnum) { modUID = AliGeomManager::LayerToVolUID(idEMCAL,modnum++); if(geom->GetSMType(smodnum) == AliEMCALGeometry::kEMCAL_Standard ) { SMPathName = "SMOD"; SMName = "FullSupermodule";} else if(geom->GetSMType(smodnum) == AliEMCALGeometry::kEMCAL_Half ) { SMPathName = "SM10"; SMName = "HalfSupermodule";} else if(geom->GetSMType(smodnum) == AliEMCALGeometry::kEMCAL_3rd ) { SMPathName = "SM3rd"; SMName = "OneThrdSupermodule";} else if( geom->GetSMType(smodnum) == AliEMCALGeometry::kDCAL_Standard ) { SMPathName = "DCSM"; SMName = "DCALSupermodule";} else if( geom->GetSMType(smodnum) == AliEMCALGeometry::kDCAL_Ext ) { SMPathName = "DCEXT"; SMName = "DCALExtensionSM";} else AliError("Unkown SM Type!!"); if(geom->GetSMType(smodnum) == tmpType) { SMOrder++; } else { tmpType = geom->GetSMType(smodnum); SMOrder = 1; } volpath.Form("ALIC_1/XEN1_1/%s_%d",SMPathName.Data(), SMOrder); symname.Form("EMCAL/%s%d",SMName.Data(), SMOrder); if(!gGeoManager->SetAlignableEntry(symname.Data(),volpath.Data(),modUID)) AliFatal(Form("AliEMCALv0::Unable to set alignable entry!!\nName: %s\t Path: %s\t ModuleID: %d\n",symname.Data(),volpath.Data(), modUID)); // Creates the Tracking to Local transformation matrix for EMCAL // modules TGeoPNEntry *alignableEntry = gGeoManager->GetAlignableEntryByUID(modUID) ; phiRad = GetGeometry()->GetPhiCenterOfSM(smodnum); //comes in radians, not degrees phi = phiRad*180./TMath::Pi(); //need degrees for rot. matrix xpos = rpos * TMath::Cos(phiRad); ypos = rpos * TMath::Sin(phiRad); zpos = pars[2]; if( geom->GetSMType(smodnum) == AliEMCALGeometry::kEMCAL_Half ) { xpos += (pars[1]/2. * TMath::Sin(phiRad)); // half SM! ypos -= (pars[1]/2. * TMath::Cos(phiRad)); } else if ( geom->GetSMType(smodnum) == AliEMCALGeometry::kEMCAL_3rd || geom->GetSMType(smodnum) == AliEMCALGeometry::kDCAL_Ext ) { xpos += (pars[1]/3. * TMath::Sin(phiRad)); // one_third SM ! ypos -= (pars[1]/3. * TMath::Cos(phiRad)); } else if( geom->GetSMType(smodnum) == AliEMCALGeometry::kDCAL_Standard ) { zpos = pars[2]*2./3. + GetGeometry()->GetDCALInnerEdge()/2.; } AliDebug(3, Form(" fIdRotm %3i phi %6.13f(%5.3f) xpos %7.2f ypos %7.2f zpos %7.2f : smodnum %i \n", fIdRotm, phi, phiRad, xpos, ypos, zpos, smodnum)); TGeoHMatrix *matTtoL; TGeoHMatrix *globMatrix = alignableEntry->GetGlobalOrig(); if(smodnum%2 == 0) { // pozitive z TGeoTranslation geoTran0(xpos, ypos, zpos); TGeoRotation geoRot0("geoRot0", 90.0, phi, 90.0, 90.0+phi, 0.0, 0.0); TGeoCombiTrans mat0(geoTran0, geoRot0); matTtoL = new TGeoHMatrix(mat0); matTtoL->MultiplyLeft(&(globMatrix->Inverse())); alignableEntry->SetMatrix(matTtoL); } else { // negative z Double_t phiy = 90. + phi + 180.; if(phiy>=360.) phiy -= 360.; TGeoTranslation geoTran1(xpos,ypos,-zpos); TGeoRotation geoRot1("geoRot1", 90.0, phi, 90.0, phiy, 180.0, 0.0); TGeoCombiTrans mat1(geoTran1, geoRot1); matTtoL = new TGeoHMatrix(mat1); matTtoL->MultiplyLeft(&(globMatrix->Inverse())); alignableEntry->SetMatrix(matTtoL); } } } //______________________________________________________________________ void AliEMCALv0::AddAlignableVolumesInWSUC() const { // // Create entries for alignable volumes associating the symbolic volume // name with the corresponding volume path. Needs to be synchronized with // eventual changes in the geometry. // TString vpstr1 = "WSUC_1/XEN1_1/SMOD_"; TString snstr1 = "EMCAL/CosmicTestSupermodule"; TString volpath, symname; // #SM is just one for (Int_t smodnum=0; smodnum < 1; smodnum++) { symname = snstr1; symname += (smodnum+1); volpath = vpstr1; volpath += (smodnum+1); if(!gGeoManager->SetAlignableEntry(symname.Data(),volpath.Data())) AliFatal("Unable to set alignable entry!!"); } }
40.606613
170
0.601426
AllaMaevskaya
db37971f6bd1816e76f0f25b1412ae4a362862dd
4,372
cpp
C++
main.cpp
AbsoluteStratos/mpi-wave
10b8b82cab42c4985a63af7f9065f06c090838cd
[ "MIT" ]
null
null
null
main.cpp
AbsoluteStratos/mpi-wave
10b8b82cab42c4985a63af7f9065f06c090838cd
[ "MIT" ]
null
null
null
main.cpp
AbsoluteStratos/mpi-wave
10b8b82cab42c4985a63af7f9065f06c090838cd
[ "MIT" ]
null
null
null
/* * C++ solver for the 2D wave equation through hetergenous media * with MPI parallelization. * Primary author: Nicholas Geneva (ngeneva at nd.edu) * * To compile in parallel: * mpicxx *cpp -std=c++11 -lboost_system -lboost_filesystem -D__MPI__ */ #include "common.h" #include "mpi_grid.h" #include "boundary.h" #include "data_io.h" #include "source.h" #include "finite_difference.h" #if defined(__MPI__) #include "mpi.h" #endif /*if defined(__MPI__)*/ using namespace std; int main(int argc, char *argv[]) { int myId, nProc; // ===== MODEL PARAMETERS ======= // int nx = 250, ny = 250; // 0 = periodic, 1 = dirichlet, 2 = open int bType = 0; /* Time-step variables */ // double tStart= 0.0; double tEnd = 20; double dt = 0.01; int saveItr = 25; /* Timing variables */ double starttime = 0.0; double endtime = 0.0; #if defined(__MPI__) MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nProc); MPI_Comm_rank(MPI_COMM_WORLD, &myId); MPI_Grid mpi_grid(myId, nProc, nx, ny); starttime = MPI_Wtime(); #else myId = 0; nProc = 1; MPI_Grid mpi_grid(myId, nProc, nx, ny); #endif DataIO dataio(mpi_grid); Source source(mpi_grid); int sX = nx/4; int sY = ny/4; double sourceMag = 0.1/(dt*dt)*(nx/50.)*(ny/50.); // Point source: xpos, ypos, mag, duration source.set_point_source(sX, sY, sourceMag, 2.0); // Harmonic source: xpos, ypos, mag, duration, freq. // source.set_harmonic_source(sX, sY, sourceMag, 5.0, 2.0); Finite_Difference fd(mpi_grid, 1.0/nx, 1.0/ny, dt); int bnds[4]; if(bType == 0){ // Periodic bnds[0]=0; bnds[1]=0; bnds[2]=0; bnds[3]=0; }else if(bType == 1){ // Dirichlet bnds[0]=1; bnds[1]=1; bnds[2]=1; bnds[3]=1; }else if(bType == 2){ // Open bnds[0]=2; bnds[1]=2; bnds[2]=2; bnds[3]=2; }else{ cout << "Boundary type not supported. Defaulting to periodic..." << endl; bnds[0]=0; bnds[1]=0; bnds[2]=0; bnds[3]=0; } Boundary boundary(mpi_grid, bnds); boundary.set_discretization(1.0/nx, 1.0/ny, dt); int lx, ly; mpi_grid.get_domain_size(&lx, &ly); cout << myId << " Domain size: " << lx <<"," << ly<<endl; // Start wall-clock execution timer starttime = MPI_Wtime(); // Allocate state matrix double** U; alloc_2d_array(ly+2, lx+2, U); for(int i=1; i<=ly; i++){ for(int j=1; j<=lx; j++){ U[i][j] = 0; } } // Allocate previous time-step state matrix double** U0; alloc_2d_array(ly, lx, U0); for(int i=0; i<ly; i++){ for(int j=0; j<lx; j++){ U0[i][j] = 0; } } // Allocate source field double** S; alloc_2d_array(ly, lx, S); // Allocate and read material field double** K; alloc_2d_array(ly, lx, K); dataio.load_material(K, "perm_gen/mat.bin"); // Uniform // for(int i=0; i<ly; i++){ // for(int j=0; j<lx; j++){ // K[i][j] = 0.1; // } // } boundary.set_material_field(K); // Block to make sure all processes get thier stuff allocated MPI_Barrier(MPI_COMM_WORLD); // ====================== Main Time Loop ====================== // double currT = 0; for(int t=0; t<int(tEnd/dt); t++){ // First deal with boundaries boundary.set_boundaries(U); // Update source field source.get_source(S, currT); // Data log if(t%saveItr == 0){ if(myId == 0){ cout << "Saving current time-step: "<< round(currT*100)/100 << endl; } dataio.save_state(U, currT); } // Forward euler fd.forward_euler(U, U0, K, S); currT+=dt; } MPI_Barrier(MPI_COMM_WORLD); endtime = MPI_Wtime(); if(myId == 0){ cout << myId << ": Took " << round(1000*(endtime-starttime))/1000 << " sec. to execute." << endl; } #if defined(__MPI__) MPI_Finalize(); #endif }
27.496855
109
0.510979
AbsoluteStratos
db3884e003ce28650c6f1b5aaf88f20b8f782611
3,371
cpp
C++
2018/cpp/src/day11.cpp
Chrinkus/advent-of-code
b2ae137dc7a1d6fc9e20f29549e891404591c47f
[ "MIT" ]
1
2021-12-04T20:55:02.000Z
2021-12-04T20:55:02.000Z
2018/cpp/src/day11.cpp
Chrinkus/advent-of-code
b2ae137dc7a1d6fc9e20f29549e891404591c47f
[ "MIT" ]
null
null
null
2018/cpp/src/day11.cpp
Chrinkus/advent-of-code
b2ae137dc7a1d6fc9e20f29549e891404591c47f
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <get_input.hpp> constexpr int grid_size = 300; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * struct Fuel_square { int x, y, size, total; }; std::ostream& operator<<(std::ostream& os, const Fuel_square& fs) { return os << fs.x << ',' << fs.y << ',' << fs.size; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * class Grid { public: Grid(int s_no) : serial{s_no} { init_grid(); set_power_levels(); } Fuel_square get_largest_3x3() const; Fuel_square get_largest_possible() const; private: void init_grid(); void set_power_levels(); int shift_x(int x) const { return x + 1; } int shift_y(int y) const { return y + 1; } int get_rack_id(int x) const { return shift_x(x) + 10; } // MAGIC int get_power_lvl(int x, int y) const; Fuel_square sum_3x3(int x, int y) const; Fuel_square sum_kxk(int x, int y, int k) const; int serial; std::vector<std::vector<int>> grid; }; Fuel_square Grid::get_largest_3x3() const { std::vector<Fuel_square> vf; for (size_t i = 0; i < grid.size() - 3; ++i) for (size_t j = 0; j < grid[i].size() - 3; ++j) vf.push_back(sum_3x3(j, i)); return *std::max_element(std::begin(vf), std::end(vf), [](const auto& a, const auto& b) { return a.total < b.total; }); } Fuel_square Grid::get_largest_possible() const { std::vector<Fuel_square> vf; for (size_t k = grid_size - 1; k > 0; --k) for (size_t i = 0; i < grid.size() - k; ++i) for (size_t j = 0; j < grid[i].size() - k; ++j) vf.push_back(sum_kxk(j, i, k)); return *std::max_element(std::begin(vf), std::end(vf), [](const auto& a, const auto& b) { return a.total < b.total; }); } void Grid::init_grid() { grid.resize(grid_size); for (auto& vi : grid) vi.resize(grid_size); } void Grid::set_power_levels() { for (size_t i = 0; i < grid.size(); ++i) { for (size_t j = 0; j < grid[i].size(); ++j) { grid[i][j] = get_power_lvl(j, i); } } } int Grid::get_power_lvl(int x, int y) const { int rack_id = get_rack_id(x); int power_lvl = rack_id * shift_y(y); power_lvl += serial; power_lvl *= rack_id; power_lvl = power_lvl / 100 % 10; power_lvl -= 5; return power_lvl; } Fuel_square Grid::sum_3x3(int x, int y) const { int total = 0; for (int i = y; i < y + 3; ++i) for (int j = x; j < x + 3; ++j) total += grid[i][j]; return Fuel_square{shift_x(x), shift_y(y), 3, total}; } Fuel_square Grid::sum_kxk(int x, int y, int k) const { int total = 0; for (int i = y; i < y + k; ++i) for (int j = x; j < x + k; ++j) total += grid[i][j]; return Fuel_square{shift_x(x), shift_y(y), k, total}; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * int main(int argc, char* argv[]) { std::cout << "AoC 2018 Day 11 - Chronal Charge\n"; auto input = utils::get_input_string(argc, argv, "11"); auto cells = Grid{std::stoi(input)}; auto part1 = cells.get_largest_3x3(); std::cout << "Part 1: " << part1 << '\n'; auto part2 = cells.get_largest_possible(); std::cout << "Part 2: " << part2 << '\n'; }
25.930769
79
0.528033
Chrinkus
db388602868762164769c754748d3836ab8b18b8
1,545
cpp
C++
Problems/542. 01 Matrix/bfsearch.cpp
uSlashVlad/MyLeetCode
3d5e8e347716beb0ffadb538c92eceb42ab7fcf9
[ "MIT" ]
1
2022-01-29T01:52:58.000Z
2022-01-29T01:52:58.000Z
Problems/542. 01 Matrix/bfsearch.cpp
uSlashVlad/MyLeetCode
3d5e8e347716beb0ffadb538c92eceb42ab7fcf9
[ "MIT" ]
null
null
null
Problems/542. 01 Matrix/bfsearch.cpp
uSlashVlad/MyLeetCode
3d5e8e347716beb0ffadb538c92eceb42ab7fcf9
[ "MIT" ]
null
null
null
#include "../includes.hpp" using namespace std; // This solution goes from 0s to all nearest 1s, calculates distance and // stores it in the result matrix class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>> &matrix) { int m = matrix.size(); int n = matrix[0].size(); vector<vector<int>> distances(m, vector<int>(n, INT32_MAX)); queue<pair<int, int>> coordsQueue; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == 0) { distances[i][j] = 0; coordsQueue.push({i, j}); // Put all 0s in the queue. } } } int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; while (!coordsQueue.empty()) { pair<int, int> cell = coordsQueue.front(); coordsQueue.pop(); for (int i = 0; i < 4; i++) { int newY = cell.first + dir[i][0]; int newX = cell.second + dir[i][1]; if (newY >= 0 && newX >= 0 && newY < m && newX < n) { if (distances[newY][newX] > distances[cell.first][cell.second] + 1) { distances[newY][newX] = distances[cell.first][cell.second] + 1; coordsQueue.push({newY, newX}); } } } } return distances; } };
29.711538
87
0.422006
uSlashVlad
db3ad6421865f19b280f783d2f98accbdb7a2049
124
cpp
C++
tests/cpp/test-simplifyline.cpp
JeremyBYU/simplifyline
fd0ee7c93f0351460b017d165956bc8f731b8047
[ "MIT" ]
1
2020-12-02T03:41:14.000Z
2020-12-02T03:41:14.000Z
tests/cpp/test-simplifyline.cpp
JeremyBYU/simplifyline
fd0ee7c93f0351460b017d165956bc8f731b8047
[ "MIT" ]
null
null
null
tests/cpp/test-simplifyline.cpp
JeremyBYU/simplifyline
fd0ee7c93f0351460b017d165956bc8f731b8047
[ "MIT" ]
1
2021-05-23T14:25:54.000Z
2021-05-23T14:25:54.000Z
#include "doctest/doctest.h" #include "SimplifyLine/SimplifyLine.hpp" #include <vector> TEST_SUITE("Simplify Line") { }
11.272727
40
0.733871
JeremyBYU
db41212db602c621df3105c89fd47680e95b893e
1,704
cpp
C++
zbo/factory_test.cpp
Lenzebo/zbo
6b3f64b828ac33f25db98a7cf8051c04132cf051
[ "MIT" ]
null
null
null
zbo/factory_test.cpp
Lenzebo/zbo
6b3f64b828ac33f25db98a7cf8051c04132cf051
[ "MIT" ]
null
null
null
zbo/factory_test.cpp
Lenzebo/zbo
6b3f64b828ac33f25db98a7cf8051c04132cf051
[ "MIT" ]
null
null
null
#include "factory.h" #include <gtest/gtest.h> namespace zbo::test { struct TestInterface { using Key = std::string; virtual ~TestInterface() = default; }; struct TestInstance1 : public TestInterface { static constexpr auto ID = "test1"; }; struct TestInstance2 : public TestInterface { static constexpr auto ID = "test2"; }; ZBO_REGISTER_IN_FACTORY(TestInstance1, TestInterface, TestInstance1::ID); ZBO_REGISTER_IN_FACTORY(TestInstance2, TestInterface, TestInstance2::ID); using TestFactory = Factory<TestInterface>; TEST(Factory, ClassesAreRegistered) { std::unique_ptr<TestInterface> in1 = TestFactory::make(TestInstance1::ID); std::unique_ptr<TestInterface> in2 = TestFactory::make(TestInstance2::ID); ASSERT_TRUE(in1); ASSERT_TRUE(in2); // check that we can cast it to the specific function ASSERT_TRUE(dynamic_cast<TestInstance1*>(in1.get())); ASSERT_TRUE(dynamic_cast<TestInstance2*>(in2.get())); } TEST(Factory, InvalidKey) { // NOLINTNEXTLINE(cppcoreguidelines-avoid-goto) ASSERT_THROW(TestFactory::make("non-existing"), std::invalid_argument); } TEST(Factory, AvailableKeys) { const auto keys = TestFactory::getAvailableKeys(); const std::vector<std::string> expectedKeys{TestInstance2::ID, TestInstance1::ID}; ASSERT_TRUE(std::is_permutation(keys.begin(), keys.end(), expectedKeys.begin())); } class DummyInterface { }; class DummyImpl : public DummyInterface { }; TEST(Factory, InterfaceWithoutKeyType) { using DummyFactory = Factory<DummyInterface, int>; DummyFactory::registerType<DummyImpl>(0); auto dummyInstance = DummyFactory::make(0); ASSERT_TRUE(dummyInstance); } } // namespace zbo::test
24.342857
86
0.733568
Lenzebo
db43626d5732b174bcd4a5064db491f7c1f8d32f
2,480
cpp
C++
test/test_transformations.cpp
cbandera/codewars_katas
8093d6f07429f079e57fb79288acb8234ec8e547
[ "BSD-3-Clause" ]
null
null
null
test/test_transformations.cpp
cbandera/codewars_katas
8093d6f07429f079e57fb79288acb8234ec8e547
[ "BSD-3-Clause" ]
null
null
null
test/test_transformations.cpp
cbandera/codewars_katas
8093d6f07429f079e57fb79288acb8234ec8e547
[ "BSD-3-Clause" ]
null
null
null
#include "catch2/catch.hpp" #include "transformations.hpp" TEST_CASE("Rotations_And_Reflections_I", "[Dih4]") { REQUIRE(Dih4::ROTATE_180.is_rotation()); REQUIRE(Dih4::REFLECT_VERTICAL.is_reflection()); REQUIRE(Dih4::ROTATE_90_CLOCKWISE.inv() == Dih4::ROTATE_90_ANTICLOCKWISE); REQUIRE(Dih4::ROTATE_90_CLOCKWISE.then(Dih4::REFLECT_VERTICAL) == Dih4::REFLECT_REVERSE_DIAGONAL); Dih4 r = Dih4::ROTATE_90_ANTICLOCKWISE; Dih4 f = Dih4::REFLECT_HORIZONTAL; REQUIRE(r.then(r).then(r) == r.inv()); REQUIRE(r.inv().then(f) == f.then(r)); REQUIRE(Dih4::ROTATE_90_CLOCKWISE == Dih4::ROTATE_90_CLOCKWISE); REQUIRE(Dih4::ROTATE_90_CLOCKWISE != Dih4::ROTATE_90_ANTICLOCKWISE); } using namespace std; ostream &operator<<(ostream &os, Dih4 r); /* -------------------------------------------------------------------------------------- */ // Output of Dih4 objects (used by the test framework when asserts fail). ostream &operator<<(ostream &os, Dih4 r) { return os << (r == Dih4::IDENTITY ? "(identity transformation)" : r == Dih4::ROTATE_90_ANTICLOCKWISE ? "(rotation 90 degrees anticlockwise)" : r == Dih4::ROTATE_180 ? "(rotation 180 degrees)" : r == Dih4::ROTATE_90_CLOCKWISE ? "(rotation 90 degrees clockwise)" : r == Dih4::REFLECT_VERTICAL ? "(reflection in vertical line)" : r == Dih4::REFLECT_FORWARD_DIAGONAL ? "(reflection in " "forward-diagonal line)" : r == Dih4::REFLECT_HORIZONTAL ? "(reflection in " "horizontal line)" : r == Dih4::REFLECT_REVERSE_DIAGONAL ? "(reflection in " "reverse-diagonal " "line)" : "(unknown Dih4 " "value)"); }
45.925926
90
0.426613
cbandera
b9cd1c78aedfa807332bd92293a21abe21219ec8
2,311
hpp
C++
checkers_client.hpp
acheeseye/ai-playing-checkers
fc02ef095fbcad8d730a25b156373cc6370d4f58
[ "MIT" ]
null
null
null
checkers_client.hpp
acheeseye/ai-playing-checkers
fc02ef095fbcad8d730a25b156373cc6370d4f58
[ "MIT" ]
12
2018-01-25T05:33:28.000Z
2018-04-04T04:37:52.000Z
checkers_client.hpp
acheeseye/ai-playing-checkers
fc02ef095fbcad8d730a25b156373cc6370d4f58
[ "MIT" ]
null
null
null
/*! @file */ #ifndef CHECKERS_CLIENT_HPP #define CHECKERS_CLIENT_HPP #include "checkers.hpp" #include <cstdint> #include <map> #include <string> namespace skynet { namespace checkers { /** \struct game_info_t *Stores game information. */ struct game_info_t { //!Status of the game. skynet::checkers::status_t status; //!All boards played during the game (beginning with the initial board). skynet::checkers::board_list_t boards; //!Time of game creation (in seconds since the Unix epoch). uint64_t create_time; //!Last time game was modified (such as a board was played, in seconds since the Unix epoch). uint64_t modify_time; }; //!Game list map type (key being the game name and value being the info for that game). typedef std::map<std::string,game_info_t> game_list_t; /**Downloads information for all checkers games on a given server (throws on error). \param server DNS name or IP address of the hosting server (ex: "skynet.cs.uaf.edu" or "137.229.25.135"). \return Map of games. */ game_list_t list_games(const std::string& server); /**Downloads information for a specific checkers game on a given server (throws on error). \param server DNS name or IP address of the hosting server (ex: "skynet.cs.uaf.edu" or "137.229.25.135"). \param game_name Name of the game to get info for. \return Map of games. */ game_info_t info_game(const std::string& server,const std::string& game_name); /**Places a board (makes a move) for a given server and game name. (throws on error). \param server DNS name or IP address of the hosting server (ex: "skynet.cs.uaf.edu" or "137.229.25.135"). \param game_name Name of the game to make a move on. \param board Board to play. */ void play_game(const std::string& server,const std::string& game_name,const skynet::checkers::board_t& board); } } namespace std { /**Converts a map of games to a JSON string. \param list Map of game names to game info structs. \return Stringified JSON object. */ std::string to_string(const skynet::checkers::game_list_t& list); /**Converts a game info object to a JSON string. \param info Game info struct. \return Stringified JSON object. */ std::string to_string(const skynet::checkers::game_info_t& info); } #endif
32.097222
112
0.710948
acheeseye
b9cd61f7750770fd1a666cca20ea532debb4ba99
7,229
cc
C++
xic/src/tech/tech_convert.cc
wrcad/xictools
f46ba6d42801426739cc8b2940a809b74f1641e2
[ "Apache-2.0" ]
73
2017-10-26T12:40:24.000Z
2022-03-02T16:59:43.000Z
xic/src/tech/tech_convert.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
12
2017-11-01T10:18:22.000Z
2022-03-20T19:35:36.000Z
xic/src/tech/tech_convert.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
34
2017-10-06T17:04:21.000Z
2022-02-18T16:22:03.000Z
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * 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 NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * Xic Integrated Circuit Layout and Schematic Editor * * * *========================================================================* $Id:$ *========================================================================*/ #include "dsp.h" #include "cd_layer.h" #include "cd_variable.h" #include "fio.h" #include "fio_gdsii.h" #include "tech.h" #include "tech_kwords.h" #include "cvrt_variables.h" // Parse the per-layer data conversion keywords. // TCret cTech::ParseCvtLayerBlock() { if (Matching(Tkw.StreamData())) { // Set the stream layer number and data type for the layer // being defined, applies to physical and electrical modes. // For backward compatibility. // TCret tcret = CheckLD(); if (tcret != TCnone) return (tcret); int lnum = 0; int dtyp = -1; if (sscanf(tc_inbuf, "%d %d", &lnum, &dtyp) < 1) return (SaveError("%s: bad or missing data.", Tkw.StreamData())); if (lnum < 0 || lnum >= GDS_MAX_LAYERS) { return (SaveError("%s: layer number out of range (0..%d).", Tkw.StreamData(), GDS_MAX_LAYERS-1)); } if (dtyp < -1 || dtyp >= GDS_MAX_DTYPES) { return (SaveError("%s: datatype number out of range (0..%d).", Tkw.StreamData(), GDS_MAX_DTYPES-1)); } char buf[32]; if (dtyp >= 0) sprintf(buf, "%d, %d", lnum, dtyp); else sprintf(buf, "%d", lnum); if (!tc_last_layer->setStrmIn(buf)) { return (SaveError( "%s: failed to set input mapping, unknown error.", Tkw.StreamData())); } if (dtyp < 0) dtyp = 0; tc_last_layer->addStrmOut(lnum, dtyp); return (TCmatch); } if (Matching(Tkw.StreamIn())) { // Set the Stream input mapping TCret tcret = CheckLD(); if (tcret != TCnone) return (tcret); if (!tc_last_layer->setStrmIn(tc_inbuf)) return (SaveError("%s: bad specification.", Tkw.StreamIn())); return (TCmatch); } if (Matching(Tkw.StreamOut())) { // Set Stream output mapping TCret tcret = CheckLD(); if (tcret != TCnone) return (tcret); int lnum = 0;; int dtyp = 0; if (sscanf(tc_inbuf, "%d %d", &lnum, &dtyp) < 1) return (SaveError("%s: bad or missing data.", Tkw.StreamOut())); if (lnum < 0 || lnum >= GDS_MAX_LAYERS) { return (SaveError("%s: layer number out of range (0..%d).", Tkw.StreamOut(), GDS_MAX_LAYERS-1)); } if (dtyp < 0 || dtyp >= GDS_MAX_DTYPES) { return (SaveError("%s: datatype number out of range (0..%d).", Tkw.StreamOut(), GDS_MAX_DTYPES-1)); } tc_last_layer->addStrmOut(lnum, dtyp); return (TCmatch); } if (Matching(Tkw.NoDrcDataType())) { TCret tcret = CheckLD(); if (tcret != TCnone) return (tcret); int i; if (sscanf(tc_inbuf, "%d", &i) == 1 && i >= 0 && i < GDS_MAX_DTYPES) { tc_last_layer->setNoDRC(true); tc_last_layer->setDatatype(CDNODRC_DT, i); } else { return (SaveError("%s: datatype out of range (0..%d).", Tkw.NoDrcDataType(), GDS_MAX_DTYPES-1)); } return (TCmatch); } return (TCnone); } // Print the per-layer conversion keyword lines to fp or lstr. If // cmts, also print associated comments. // void cTech::PrintCvtLayerBlock(FILE *fp, sLstr *lstr, bool cmts, const CDl *ld, DisplayMode mode) { if (!ld) return; tBlkType tbt = mode == Physical ? tBlkPlyr : tBlkElyr; char buf[256]; // StreamIn if (ld->strmIn()) { PutStr(fp, lstr, Tkw.StreamIn()); PutChr(fp, lstr, ' '); ld->strmIn()->print(fp, lstr); } if (cmts) CommentDump(fp, lstr, tbt, ld->name(), Tkw.StreamIn()); // StreamOut for (strm_odata *so = ld->strmOut(); so; so = so->next()) { sprintf(buf, "%s %d %d\n", Tkw.StreamOut(), so->layer(), so->dtype()); PutStr(fp, lstr, buf); } if (cmts) CommentDump(fp, lstr, tbt, ld->name(), Tkw.StreamOut()); // NoDrcDataType if (mode == Physical) { if (ld->isNoDRC()) { sprintf(buf, "%s %d\n", Tkw.NoDrcDataType(), ld->datatype(CDNODRC_DT)); PutStr(fp, lstr, buf); } if (cmts) CommentDump(fp, lstr, tbt, ld->name(), Tkw.NoDrcDataType()); } }
40.161111
78
0.475723
wrcad
b9ce9e9f1d6b4beec6b1f1359a3ee6a4ae16eeec
397
cpp
C++
SessionManager.cpp
patrickwang96/pvt-box
e66b01351d0ebe70a2d7489c969da8f951bca2ba
[ "MIT" ]
null
null
null
SessionManager.cpp
patrickwang96/pvt-box
e66b01351d0ebe70a2d7489c969da8f951bca2ba
[ "MIT" ]
null
null
null
SessionManager.cpp
patrickwang96/pvt-box
e66b01351d0ebe70a2d7489c969da8f951bca2ba
[ "MIT" ]
null
null
null
// // Created by Ruochen WANG on 12/5/2020. // #include "SessionManager.h" SessionManager::SessionManager() { } void SessionManager::start(session_ptr s) { _sessions.insert(s); s->start(); } void SessionManager::stop(session_ptr s) { _sessions.erase(s); s->stop(); } void SessionManager::stop_all() { for (auto s: _sessions) s->stop(); _sessions.clear(); }
14.178571
43
0.634761
patrickwang96
b9dbc48aa4d730ba2bfeb9294ecd3aed59d95ef2
23,208
cc
C++
src/core/analysis/score_processor.cc
5003/jumanpp
9f50ee3d62591936a079ade18c6e1d1e8a6d3463
[ "Apache-2.0" ]
1
2018-03-18T15:53:27.000Z
2018-03-18T15:53:27.000Z
src/core/analysis/score_processor.cc
5003/jumanpp
9f50ee3d62591936a079ade18c6e1d1e8a6d3463
[ "Apache-2.0" ]
null
null
null
src/core/analysis/score_processor.cc
5003/jumanpp
9f50ee3d62591936a079ade18c6e1d1e8a6d3463
[ "Apache-2.0" ]
null
null
null
// // Created by Arseny Tolmachev on 2017/03/07. // #include "score_processor.h" #include <numeric> #include "core/analysis/analyzer_impl.h" #include "core/analysis/lattice_types.h" #include "core/impl/feature_impl_types.h" #include "util/logging.hpp" namespace jumanpp { namespace core { namespace analysis { std::pair<Status, ScoreProcessor *> ScoreProcessor::make(AnalyzerImpl *impl) { auto alloc = impl->alloc(); auto procBuf = alloc->allocate<ScoreProcessor>(); auto proc = new (procBuf) ScoreProcessor{impl}; return std::make_pair(Status::Ok(), proc); } ScoreProcessor::ScoreProcessor(AnalyzerImpl *analyzer) : ngramApply_{analyzer->core().features().ngramPartial}, lattice_{analyzer->lattice()}, cfg_{&analyzer->cfg()}, t1PtrData_{analyzer->alloc()} { u32 maxNodes = 0; u32 maxEnds = 0; for (u32 idx = 2; idx < lattice_->createdBoundaryCount(); ++idx) { auto bnd = lattice_->boundary(idx); maxNodes = std::max<u32>(maxNodes, bnd->localNodeCount()); maxEnds = std::max<u32>(maxEnds, bnd->ends()->nodePtrs().size()); } this->runStats_.maxStarts = maxNodes; this->runStats_.maxEnds = maxEnds; this->globalBeamSize_ = analyzer->cfg().globalBeamSize; auto *alloc = analyzer->alloc(); scores_.prepare(alloc, maxNodes); auto &lcfg = lattice_->config(); beamCandidates_ = alloc->allocateBuf<BeamCandidate>(maxEnds * lcfg.beamSize, 64); analyzer->core().features().ngramPartial->allocateBuffers(&featureBuffer_, runStats_, alloc); util::fill(featureBuffer_.valueBuffer1, 0); globalBeamSize_ = analyzer->cfg().globalBeamSize; if (globalBeamSize_ > 0) { t1PtrData_.reserve(globalBeamSize_); globalBeam_ = alloc->allocateBuf<BeamCandidate>(maxEnds * lcfg.beamSize, 64); const u64 *gbeamPtr = reinterpret_cast<const u64 *>(globalBeam_.data()); lattice_->setLastGbeam(gbeamPtr); t1positions_ = alloc->allocateBuf<u32>(globalBeamSize_); t1patBuf_ = alloc->allocate2d<u64>(maxEnds, lcfg.numFeaturePatterns); t2patBuf_ = alloc->allocate2d<u64>(globalBeamSize_, lcfg.numFeaturePatterns); gbeamScoreBuf_ = alloc->allocateBuf<Score>(globalBeamSize_); beamIdxBuffer_ = alloc->allocateBuf<u32>(globalBeamSize_); if (cfg_->rightGbeamCheck > 0) { t0prescores_ = alloc->allocate2d<Score>(cfg_->rightGbeamCheck, maxNodes, 64); t0cutoffBuffer_ = alloc->allocateBuf<Score>(maxNodes); t0cutoffIdxBuffer_ = alloc->allocateBuf<u32>(maxNodes); } } patternStatic_ = analyzer->core().features().patternStatic.get(); patternDynamic_ = analyzer->core().features().patternDynamic.get(); plugin_ = analyzer->plugin(); } void ScoreProcessor::copyFeatureScores(i32 left, i32 beam, LatticeBoundaryScores *bndconn) { bndconn->importBeamScore(left, 0, beam, scores_.bufferT2()); } void ScoreProcessor::applyPluginToFullBeam(i32 bndNum, i32 left, i32 beam) { if (!plugin_) { return; } auto &prev = beamPtrs_.at(beam); auto score = scores_.bufferT2(); for (u16 t0 = 0; t0 < score.size(); ++t0) { ConnectionPtr ptr{static_cast<u16>(bndNum), static_cast<u16>(left), t0, static_cast<u16>(beam), &prev.ptr}; plugin_->updateScore(lattice_, ptr, &score.at(t0)); } } void ScoreProcessor::resolveBeamAt(i32 boundary, i32 position) { auto bnd = lattice_->boundary(boundary); auto startData = bnd->starts(); auto beam = startData->beamData().row(position); beamSize_ = 0; for (auto &e : beam) { if (EntryBeam::isFake(e)) { break; } ++beamSize_; } beamPtrs_ = util::ArraySlice<ConnectionBeamElement>{beam, 0, (u32)beamSize_}; } void ScoreProcessor::startBoundary(u32 currentNodes) { scores_.newBoundary(currentNodes); } void ScoreProcessor::applyT0(i32 boundary, FeatureScorer *features) { auto patterns = lattice_->boundary(boundary)->starts()->patternFeatureData(); ngramApply_->applyUni(&featureBuffer_, patterns, features, scores_.bufferT0()); ngramApply_->applyBiStep1(&featureBuffer_, patterns); ngramApply_->applyTriStep1(&featureBuffer_, patterns); } void ScoreProcessor::computeT0All( i32 boundary, FeatureScorer *features, features::impl::PrimitiveFeatureContext *pfc) { auto bnd = lattice_->boundary(boundary)->starts(); auto nodeInfo = bnd->nodeInfo(); auto nodeFeatures = bnd->entryData(); auto scores = scores_.bufferT0(); featureBuffer_.currentElems = static_cast<u32>(bnd->numEntries()); patternStatic_->patternsAndUnigramsApply( pfc, nodeInfo, nodeFeatures, &featureBuffer_, bnd->patternFeatureData(), features, scores); } void ScoreProcessor::applyT1(i32 boundary, i32 position, FeatureScorer *features) { auto result = scores_.bufferT1(); util::copy_buffer(scores_.bufferT0(), result); auto item = lattice_->boundary(boundary)->starts()->patternFeatureData().row( position); ngramApply_->applyBiStep2(&featureBuffer_, item, features, result); ngramApply_->applyTriStep2(&featureBuffer_, item); } void ScoreProcessor::applyT2(i32 beamIdx, FeatureScorer *features) { auto &beam = beamPtrs_.at(beamIdx); auto ptr = beam.ptr.previous; auto item = lattice_->boundary(ptr->boundary) ->starts() ->patternFeatureData() .row(ptr->right); auto result = scores_.bufferT2(); util::copy_buffer(scores_.bufferT1(), result); ngramApply_->applyTriStep3(&featureBuffer_, item, features, result); } namespace { u32 fillBeamCandidates(Lattice *l, LatticeBoundary *bnd, NodeScores scores, const ScorerDef *pDef, util::MutableArraySlice<BeamCandidate> cands) { auto &weights = pDef->scoreWeights; JPP_DCHECK_EQ(scores.numScorers(), weights.size()); auto ends = bnd->ends(); u32 activeBeams = 0; for (u16 left = 0; left < scores.left(); ++left) { auto leftPtr = ends->nodePtrs().at(left); auto leftBeam = l->boundary(leftPtr.boundary) ->starts() ->beamData() .row(leftPtr.position); for (u16 beam = 0; beam < scores.beam(); ++beam) { auto &leftElm = leftBeam.at(beam); if (EntryBeam::isFake(leftElm)) { break; } auto s = scores.beamLeft(beam, left); auto localScore = s.at(0); auto score = leftElm.totalScore + localScore; cands.at(activeBeams) = BeamCandidate{score, left, beam}; activeBeams += 1; } } return activeBeams; } util::ArraySlice<BeamCandidate> processBeamCandidates( util::MutableArraySlice<BeamCandidate> candidates, u32 maxBeam) { auto comp = std::greater<>(); if (candidates.size() > maxBeam * 2) { u32 maxElems = maxBeam * 2; auto iter = util::partition(candidates.begin(), candidates.end(), comp, maxBeam, maxElems); u32 sz = static_cast<u32>(iter - candidates.begin()); candidates = util::MutableArraySlice<BeamCandidate>{candidates, 0, sz}; } std::sort(candidates.begin(), candidates.end(), comp); auto size = std::min<u64>(maxBeam, candidates.size()); return util::ArraySlice<BeamCandidate>{candidates, 0, size}; } } // namespace void ScoreProcessor::makeBeams(i32 boundary, LatticeBoundary *bnd, const ScorerDef *sc) { auto myNodes = bnd->localNodeCount(); auto prevData = bnd->ends()->nodePtrs(); auto maxBeam = lattice_->config().beamSize; util::MutableArraySlice<BeamCandidate> cands{beamCandidates_, 0, maxBeam * prevData.size()}; auto scores = bnd->scores(); auto beamData = bnd->starts()->beamData(); for (int node = 0; node < myNodes; ++node) { auto cnt = fillBeamCandidates(lattice_, bnd, scores->nodeScores(node), sc, cands); util::MutableArraySlice<BeamCandidate> candSlice{cands, 0, cnt}; auto res = processBeamCandidates(candSlice, maxBeam); auto beamElems = beamData.row(node); // fill the beam u16 beam = 0; for (; beam < res.size(); ++beam) { auto beamCand = res.at(beam); auto prevPtr = prevData.at(beamCand.left()); auto prevBnd = lattice_->boundary(prevPtr.boundary); auto prevNode = prevBnd->starts()->beamData().row(prevPtr.position); ConnectionPtr ptr{static_cast<u16>(boundary), beamCand.left(), static_cast<u16>(node), beamCand.beam(), &prevNode.at(beamCand.beam()).ptr}; beamElems.at(beam) = ConnectionBeamElement{ptr, beamCand.score()}; } size_t rest = maxBeam - beam; if (rest > 0) { std::memset(&beamElems.at(beam), 0xff, rest * sizeof(ConnectionBeamElement)); } } } util::ArraySlice<BeamCandidate> ScoreProcessor::makeGlobalBeam(i32 bndIdx, i32 maxElems) { auto bnd = lattice_->boundary(bndIdx); auto ends = bnd->ends(); u32 count = 0; util::ArraySlice<LatticeNodePtr> leftNodes = ends->nodePtrs(); for (u16 left = 0; left < leftNodes.size(); ++left) { auto ptr = leftNodes.at(left); auto endBnd = lattice_->boundary(ptr.boundary); auto endBeam = endBnd->starts()->beamData().row(ptr.position); u16 beamIdx = 0; for (auto &el : endBeam) { if (EntryBeam::isFake(el)) { break; } globalBeam_[count] = BeamCandidate{el.totalScore, left, beamIdx}; ++count; ++beamIdx; } } util::MutableArraySlice<BeamCandidate> slice{globalBeam_, 0, count}; auto res = processBeamCandidates(slice, maxElems); auto gbptrs = ends->globalBeam(); if (gbptrs.size() > 0) { JPP_DCHECK_LE(res.size(), gbptrs.size()); ends->setGlobalBeamSize(res.size()); for (int i = 0; i < res.size(); ++i) { auto beamEl = res.at(i); auto left = leftNodes.at(beamEl.left()); auto nodeBnd = lattice_->boundary(left.boundary); auto beams = nodeBnd->starts()->beamData(); gbptrs.at(i) = &beams.row(left.position).at(beamEl.beam()); } } return res; } void ScoreProcessor::computeGbeamScores(i32 bndIdx, util::ArraySlice<BeamCandidate> gbeam, FeatureScorer *features) { auto bnd = lattice_->boundary(bndIdx); auto t1Ptrs = dedupT1(bndIdx, gbeam); util::Sliceable<u64> t1data = gatherT1(); util::Sliceable<u64> t2data = gatherT2(bndIdx, gbeam); auto right = bnd->starts(); auto t0data = right->patternFeatureData(); util::MutableArraySlice<Score> result{gbeamScoreBuf_, 0, gbeam.size()}; if (cfg_->rightGbeamCheck > 0) { // we cut off right elements as well auto size = static_cast<size_t>(cfg_->rightGbeamCheck); auto fullBeamApplySize = std::min<size_t>({size, bnd->localNodeCount(), gbeam.size()}); auto toKeep = std::min<u32>(static_cast<u32>(cfg_->rightGbeamSize), bnd->localNodeCount()); u32 remainingItems = std::max<u32>(gbeam.size() - fullBeamApplySize, 0); auto t1PtrTail = util::ArraySlice<u32>{t1Ptrs, fullBeamApplySize, remainingItems}; auto t2Tail = t2data.rows(fullBeamApplySize, t2data.numRows()); util::MutableArraySlice<Score> resultTail{result, fullBeamApplySize, remainingItems}; util::ArraySlice<BeamCandidate> gbeamHead{gbeam, 0, fullBeamApplySize}; util::ArraySlice<BeamCandidate> gbeamTail{gbeam, fullBeamApplySize, remainingItems}; computeT0Prescores(gbeam, features); applyPluginToPrescores(bndIdx, gbeamHead); makeT0cutoffBeam(static_cast<u32>(fullBeamApplySize), toKeep); auto t0pos = 0; // first, we process elements which require feature/score computation for (; t0pos < toKeep; ++t0pos) { auto t0idx = t0cutoffIdxBuffer_.at(t0pos); auto t0 = t0data.row(t0idx); for (int i = 0; i < fullBeamApplySize; ++i) { result.at(i) = t0prescores_.row(i).at(t0idx); } copyT0Scores(bndIdx, t0idx, gbeamHead, result, 0); if (t1PtrTail.size() > 0) { auto t0Score = scores_.bufferT0().at(t0idx); ngramApply_->applyBiTri(&featureBuffer_, t0idx, t0, t1data, t2Tail, t1PtrTail, features, resultTail); applyPluginToGbeam(bndIdx, t0idx, gbeamTail, resultTail); copyT0Scores(bndIdx, t0idx, gbeamTail, resultTail, t0Score); } makeT0Beam(bndIdx, t0idx, gbeam, result); } // then we form beams for the remaining items for (; t0pos < t0data.numRows(); ++t0pos) { auto t0idx = t0cutoffIdxBuffer_.at(t0pos); for (int i = 0; i < fullBeamApplySize; ++i) { result.at(i) = t0prescores_.row(i).at(t0idx); } copyT0Scores(bndIdx, t0idx, gbeamHead, result, 0); makeT0Beam(bndIdx, t0idx, gbeamHead, result); } } else { // we score all gbeam <-> right pairs for (auto t0idx = 0; t0idx < t0data.numRows(); ++t0idx) { JPP_CAPTURE(t0idx); auto t0 = t0data.row(t0idx); ngramApply_->applyBiTri(&featureBuffer_, t0idx, t0, t1data, t2data, t1Ptrs, features, result); auto t0Score = scores_.bufferT0().at(t0idx); applyPluginToGbeam(bndIdx, t0idx, gbeam, result); copyT0Scores(bndIdx, t0idx, gbeam, result, t0Score); makeT0Beam(bndIdx, t0idx, gbeam, result); } } } util::ArraySlice<u32> ScoreProcessor::dedupT1( i32 bndIdx, util::ArraySlice<BeamCandidate> gbeam) { auto left = lattice_->boundary(bndIdx)->ends()->nodePtrs(); t1PtrData_.clear_no_resize(); util::MutableArraySlice<u32> subset{t1positions_, 0, gbeam.size()}; for (int i = 0; i < gbeam.size(); ++i) { auto &it = left.at(gbeam.at(i).left()); u32 curSize = static_cast<u32>(t1PtrData_.size()); auto idx = t1PtrData_.findOrInsert(it, [curSize]() { return curSize; }); subset[i] = idx; } return subset; } util::Sliceable<u64> ScoreProcessor::gatherT1() { util::Sliceable<u64> result = t1patBuf_.topRows(t1PtrData_.size()); for (auto &obj : t1PtrData_) { auto bnd = lattice_->boundary(obj.first.boundary); const auto pats = bnd->starts()->patternFeatureData(); auto therow = pats.row(obj.first.position); auto target = result.row(obj.second); util::copy_buffer(therow, target); } return result; } util::Sliceable<u64> ScoreProcessor::gatherT2( i32 bndIdx, util::ArraySlice<BeamCandidate> gbeam) { util::Sliceable<u64> result = t2patBuf_.topRows(gbeam.size()); auto ptrs = lattice_->boundary(bndIdx)->ends()->nodePtrs(); int i = 0; for (auto &c : gbeam) { auto pt = ptrs.at(c.left()); auto bnd = lattice_->boundary(pt.boundary); auto beam = bnd->starts()->beamData().row(pt.position); auto &beamPtr = beam.at(c.beam()); auto prev = beamPtr.ptr.previous; auto t2Bnd = lattice_->boundary(prev->boundary)->starts(); auto therow = t2Bnd->patternFeatureData().row(prev->right); auto target = result.row(i); util::copy_buffer(therow, target); ++i; } return result; } void ScoreProcessor::copyT0Scores(i32 bndIdx, i32 t0idx, util::ArraySlice<BeamCandidate> gbeam, util::MutableArraySlice<Score> scores, Score t0Score) { auto sholder = lattice_->boundary(bndIdx)->scores(); auto nscores = sholder->nodeScores(t0idx); for (int i = 0; i < gbeam.size(); ++i) { auto &v = scores.at(i); v += t0Score; auto &gb = gbeam.at(i); nscores.beamLeft(gb.beam(), gb.left()).at(0) = v; v += gb.score(); } } void ScoreProcessor::makeT0Beam(i32 bndIdx, i32 t0idx, util::ArraySlice<BeamCandidate> gbeam, util::MutableArraySlice<Score> scores) { auto maxBeam = lattice_->config().beamSize; util::MutableArraySlice<u32> idxes{beamIdxBuffer_, 0, gbeam.size()}; std::iota(idxes.begin(), idxes.end(), 0); auto comp = [&scores](u32 i1, u32 i2) { return scores[i1] > scores[i2]; }; auto itr = idxes.end(); auto partitionBoundary = maxBeam * 4 / 3; if (idxes.size() > partitionBoundary) { itr = util::partition(idxes.begin(), itr, comp, maxBeam, partitionBoundary); } std::sort(idxes.begin(), itr, comp); auto start = lattice_->boundary(bndIdx)->starts(); auto beam = start->beamData().row(t0idx); const auto ends = lattice_->boundary(bndIdx)->ends(); auto gbeamNodes = ends->globalBeam(); u32 beamIdx = 0; for (auto it = idxes.begin(); it < itr; ++it) { if (beamIdx >= maxBeam) { break; } auto &prev = gbeam.at(*it); auto prevPtr = gbeamNodes.at(*it); auto globalScore = scores.at(*it); ConnectionPtr cp{static_cast<u16>(bndIdx), prev.left(), static_cast<u16>(t0idx), prev.beam(), &prevPtr->ptr}; ConnectionBeamElement cbe{cp, globalScore}; // LOG_TRACE() << "assign beam " << cbe << " at " << bndIdx << ", " << // t0idx << " gb: " << *it << " -> " << beamIdx; beam.at(beamIdx) = cbe; ++beamIdx; } size_t rest = maxBeam - beamIdx; if (rest > 0) { std::memset(&beam.at(beamIdx), 0xff, rest * sizeof(ConnectionBeamElement)); } } void ScoreProcessor::makeT0cutoffBeam(u32 fullAnalysis, u32 rightBeam) { auto slice = t0prescores_.topRows(fullAnalysis); auto curElemCnt = featureBuffer_.currentElems; util::MutableArraySlice<u32> idxBuf{t0cutoffIdxBuffer_, 0, curElemCnt}; std::iota(idxBuf.begin(), idxBuf.end(), 0); if (curElemCnt <= rightBeam) { return; } util::MutableArraySlice<Score> cutoffScores{t0cutoffBuffer_, 0, curElemCnt}; for (int i = 0; i < curElemCnt; ++i) { Score s = 0; for (int j = 0; j < fullAnalysis; ++j) { s += slice.row(j).at(i); } cutoffScores.at(i) = s; } auto comp = [&](u32 a, u32 b) { return cutoffScores.at(a) > cutoffScores.at(b); }; std::nth_element(idxBuf.begin(), idxBuf.begin() + rightBeam, idxBuf.end(), comp); } void ScoreProcessor::computeT0Prescores(util::ArraySlice<BeamCandidate> gbeam, FeatureScorer *scorer) { auto max = cfg_->rightGbeamCheck; auto theMax = std::min<i32>(max, gbeam.size()); for (int i = 0; i < theMax; ++i) { auto t1idx = t1positions_.at(i); auto t1 = t1patBuf_.row(t1idx); auto t2 = t2patBuf_.row(i); auto scores = t0prescores_.row(i); util::copy_buffer(scores_.bufferT0(), scores); ngramApply_->applyTriStep2(&featureBuffer_, t1); ngramApply_->applyBiStep2(&featureBuffer_, t1, scorer, scores); ngramApply_->applyTriStep3(&featureBuffer_, t2, scorer, scores); } } void ScoreProcessor::computeUniOnlyPatterns( i32 bndIdx, features::impl::PrimitiveFeatureContext *pfc) { auto bnd = lattice_->boundary(bndIdx)->starts(); features::impl::PrimitiveFeatureData pfdata{bnd->nodeInfo(), bnd->entryData(), bnd->patternFeatureData()}; patternDynamic_->applyUniOnly(pfc, &pfdata); } void ScoreProcessor::adjustBeamScores(util::ArraySlice<float> scoreWeights) { auto nbnd = lattice_->createdBoundaryCount(); // going through global beam, it is on end side // so start iteration from the 3-rd boundary for (u32 latBnd = 3; latBnd < nbnd; ++latBnd) { auto curBnd = lattice_->boundary(latBnd); if (curBnd->localNodeCount() == 0) { continue; } auto end = curBnd->ends(); auto gbeam = end->globalBeam(); for (auto el : gbeam) { auto elScores = lattice_->boundary(el->ptr.boundary)->scores(); auto nodeScores = elScores->nodeScores(el->ptr.right); auto scores = nodeScores.beamLeft(el->ptr.beam, el->ptr.left); float localScore = 0; for (int i = 0; i < scoreWeights.size(); ++i) { localScore += scores.at(i) * scoreWeights.at(i); } auto prevPtr = el->ptr.previous; // underlying object IS ConnectionBeamElement auto prevBeam = reinterpret_cast<const ConnectionBeamElement *>(prevPtr); localScore += prevBeam->totalScore; // underlying object is not const, so this is safe auto mutEL = const_cast<ConnectionBeamElement *>(el); mutEL->totalScore = localScore; } } } void ScoreProcessor::remakeEosBeam(util::ArraySlice<float> scoreWeights) { auto nbnd = lattice_->createdBoundaryCount(); auto eosBnd = lattice_->boundary(nbnd - 1); auto rawGbeamData = lattice_->lastGbeamRaw(); auto fullGbeam = eosBnd->ends()->globalBeam(); util::MutableArraySlice<BeamCandidate> lastGbeam{ reinterpret_cast<BeamCandidate *>(const_cast<u64 *>(rawGbeamData)), fullGbeam.size()}; util::MutableArraySlice<Score> fullScores{gbeamScoreBuf_, 0, fullGbeam.size()}; auto rawScores = eosBnd->scores()->nodeScores(0); for (int i = 0; i < fullGbeam.size(); ++i) { float localScore = 0; auto gbeamCand = lastGbeam.at(i); auto beamScore = fullGbeam.at(i)->totalScore; lastGbeam.at(i) = BeamCandidate{beamScore, gbeamCand.left(), gbeamCand.beam()}; auto localScoreData = rawScores.beamLeft(gbeamCand.beam(), gbeamCand.left()); for (int j = 0; j < scoreWeights.size(); ++j) { localScore += localScoreData.at(j) * scoreWeights.at(j); } fullScores.at(i) = localScore + beamScore; } makeT0Beam(nbnd - 1, 0, lastGbeam, fullScores); } void ScoreProcessor::applyPluginToPrescores( i32 bndIdx, util::ArraySlice<BeamCandidate> gbeam) { if (plugin_) { auto bnd = lattice_->boundary(bndIdx); auto t0num = bnd->localNodeCount(); for (u32 t1i = 0; t1i < gbeam.size(); ++t1i) { auto scores = t0prescores_.row(t1i); auto &t1bc = gbeam.at(t1i); auto &t1nptr = bnd->ends()->nodePtrs().at(t1bc.left()); auto t1bnd = lattice_->boundary(t1nptr.boundary)->starts(); auto &t1beam = t1bnd->beamData().row(t1nptr.position).at(t1bc.beam()); for (int t0 = 0; t0 < t0num; ++t0) { ConnectionPtr ptr{static_cast<u16>(bndIdx), t1bc.left(), static_cast<u16>(t0), t1bc.beam(), &t1beam.ptr}; plugin_->updateScore(lattice_, ptr, &scores.at(t0)); } } } } void ScoreProcessor::applyPluginToGbeam(i32 bndIdx, i32 t0idx, util::ArraySlice<BeamCandidate> gbeam, util::MutableArraySlice<Score> scores) { if (plugin_) { auto bnd = lattice_->boundary(bndIdx); for (u32 t1i = 0; t1i < gbeam.size(); ++t1i) { auto &t1bc = gbeam.at(t1i); auto &t1nptr = bnd->ends()->nodePtrs().at(t1bc.left()); auto t1bnd = lattice_->boundary(t1nptr.boundary)->starts(); auto &t1beam = t1bnd->beamData().row(t1nptr.position).at(t1bc.beam()); ConnectionPtr ptr{static_cast<u16>(bndIdx), t1bc.left(), static_cast<u16>(t0idx), t1bc.beam(), &t1beam.ptr}; plugin_->updateScore(lattice_, ptr, &scores.at(t1i)); } } } } // namespace analysis } // namespace core } // namespace jumanpp
38.108374
80
0.636246
5003
b9e1c66c9f79a394d9c12e2af4d5580e17c5f22b
1,848
cpp
C++
source/src/CloudsLayer.cpp
jane8384/seven-monkeys
119cb7312f25d54e88f212a8710a512b893b046d
[ "MIT" ]
3
2017-11-16T01:54:09.000Z
2018-05-20T15:33:21.000Z
src/CloudsLayer.cpp
aitorfernandez/seven-monkeys
8f2440fd5ae7a9e86bb71dba800efe9424f3792e
[ "MIT" ]
null
null
null
src/CloudsLayer.cpp
aitorfernandez/seven-monkeys
8f2440fd5ae7a9e86bb71dba800efe9424f3792e
[ "MIT" ]
3
2017-09-18T11:44:41.000Z
2019-12-25T11:30:26.000Z
// // CloudsLayer.cpp // SevenMonkeys // #include "CloudsLayer.hpp" USING_NS_CC; USING_NS_SM; CloudsLayer::CloudsLayer() { CCLOG("// CloudsLayer %x Constructor", (int)(long)this); std::string fullPath = FileUtils::getInstance()->fullPathForFilename("data/CloudsLayer.json"); std::string json = FileUtils::getInstance()->getStringFromFile(fullPath); mvDocument.Parse<rapidjson::ParseFlag::kParseDefaultFlags>(json.c_str()); } CloudsLayer::~CloudsLayer() { CCLOG("// CloudsLayer %x Destructor", (int)(long)this); } bool CloudsLayer::init(const char* color) { if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); const rapidjson::Value& clouds = mvDocument[color]; char cloudFrame[20] = { 0 }; for (rapidjson::SizeType i = 0; i < clouds.Size(); i++) { if (strcmp(color, "white") != 0) sprintf(cloudFrame, "BlackCloud%02d.png", i + 1); else sprintf(cloudFrame, "WhiteCloud%02d.png", i + 1); auto cloudSprite = Sprite::createWithSpriteFrameName(cloudFrame); cloudSprite->setPosition(Vec2(origin.x + (((visibleSize.width / 2) * clouds[i][0].GetDouble()) / .5f), origin.y + (((visibleSize.height / 2) * clouds[i][1].GetDouble()) / .5f))); this->addChild(cloudSprite, i); auto delay = DelayTime::create(randFloat()); Vec2 to = Vec2(origin.x + (i < 3 ? (visibleSize.width + 20) : ((visibleSize.width * -1) - 20)), 0); auto move = MoveBy::create(randInt(150, 450), to); auto sequence = Sequence::create(move, delay, move->reverse(), delay, nullptr); cloudSprite->runAction(RepeatForever::create(sequence)); } return true; }
28.430769
113
0.621212
jane8384
b9e339ed51eb6fd750f2d88fefa1cae9a5c6facc
1,541
hpp
C++
include/eigenpy/registration.hpp
rhaschke/eigenpy
65ade259193c85c79701530bae70f80bc3af05d8
[ "BSD-2-Clause" ]
2
2020-05-31T01:30:36.000Z
2020-08-24T12:06:39.000Z
include/eigenpy/registration.hpp
rhaschke/eigenpy
65ade259193c85c79701530bae70f80bc3af05d8
[ "BSD-2-Clause" ]
null
null
null
include/eigenpy/registration.hpp
rhaschke/eigenpy
65ade259193c85c79701530bae70f80bc3af05d8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2014-2019, CNRS * Copyright 2018-2019, INRIA */ #ifndef __eigenpy_registration_hpp__ #define __eigenpy_registration_hpp__ #include <boost/python.hpp> #include <boost/python/scope.hpp> namespace eigenpy { /// /// \brief Check at runtime the registration of the type T inside the boost python registry. /// /// \tparam T The type to check the registration. /// /// \returns true if the type T is already registered. /// template<typename T> inline bool check_registration() { namespace bp = boost::python; const bp::type_info info = bp::type_id<T>(); const bp::converter::registration* reg = bp::converter::registry::query(info); if (reg == NULL) return false; else if ((*reg).m_to_python == NULL) return false; return true; } /// /// \brief Symlink to the current scope the already registered class T. /// /// \returns true if the type T is effectively symlinked. /// /// \tparam T The type to symlink. /// template<typename T> inline bool register_symbolic_link_to_registered_type() { namespace bp = boost::python; if(eigenpy::check_registration<T>()) { const bp::type_info info = bp::type_id<T>(); const bp::converter::registration* reg = bp::converter::registry::query(info); bp::handle<> class_obj(reg->get_class_object()); bp::scope().attr(reg->get_class_object()->tp_name) = bp::object(class_obj); return true; } return false; } } #endif // ifndef __eigenpy_registration_hpp__
25.683333
94
0.662557
rhaschke
b9e8d0ae8ba3f0aa1f93cdec2107a41852104883
777
cpp
C++
src/execution/compiler/expression/star_translator.cpp
AhnJaeChan/terrier
21ef01353439cddb8643b5fc2a5a304813809585
[ "MIT" ]
1
2020-05-27T03:54:36.000Z
2020-05-27T03:54:36.000Z
src/execution/compiler/expression/star_translator.cpp
AhnJaeChan/terrier
21ef01353439cddb8643b5fc2a5a304813809585
[ "MIT" ]
7
2020-04-06T19:31:12.000Z
2020-05-12T23:05:09.000Z
src/execution/compiler/expression/star_translator.cpp
AhnJaeChan/terrier
21ef01353439cddb8643b5fc2a5a304813809585
[ "MIT" ]
1
2020-11-24T10:00:01.000Z
2020-11-24T10:00:01.000Z
#include "execution/compiler/expression/star_translator.h" #include "execution/compiler/translator_factory.h" #include "execution/sql/value.h" #include "parser/expression/star_expression.h" #include "type/transient_value_peeker.h" namespace terrier::execution::compiler { StarTranslator::StarTranslator(const terrier::parser::AbstractExpression *expression, CodeGen *codegen) : ExpressionTranslator(expression, codegen) {} ast::Expr *StarTranslator::DeriveExpr(ExpressionEvaluator *evaluator) { // TODO(Amadou): COUNT(*) will increment its counter regardless of the input we pass in. // So the value we return here does not matter. The StarExpression can just be replaced by a constant. return codegen_->IntToSql(0); } }; // namespace terrier::execution::compiler
45.705882
104
0.785071
AhnJaeChan
b9ec32e6fff7bdcbe24e78f09779531e53cae9f9
274,213
cpp
C++
src/common/backend/utils/cache/relcache.cpp
Purlemon/openGuass-603
14b7414a8da671f1dfbafa2006660f5da27f6a36
[ "MulanPSL-1.0" ]
1
2021-11-05T10:14:39.000Z
2021-11-05T10:14:39.000Z
src/common/backend/utils/cache/relcache.cpp
Purlemon/openGuass-603
14b7414a8da671f1dfbafa2006660f5da27f6a36
[ "MulanPSL-1.0" ]
null
null
null
src/common/backend/utils/cache/relcache.cpp
Purlemon/openGuass-603
14b7414a8da671f1dfbafa2006660f5da27f6a36
[ "MulanPSL-1.0" ]
null
null
null
/* ------------------------------------------------------------------------- * * relcache.c * POSTGRES relation descriptor cache code * * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * Portions Copyright (c) 2010-2012 Postgres-XC Development Group * * * IDENTIFICATION * src/backend/utils/cache/relcache.c * * ------------------------------------------------------------------------- */ /* * INTERFACE ROUTINES * RelationCacheInitialize - initialize relcache (to empty) * RelationCacheInitializePhase2 - initialize shared-catalog entries * RelationCacheInitializePhase3 - finish initializing relcache * RelationIdGetRelation - get a reldesc by relation id * RelationClose - close an open relation * * NOTES * The following code contains many undocumented hacks. Please be * careful.... */ #include "postgres.h" #include "knl/knl_variable.h" #include <sys/file.h> #include <catalog/pg_obsscaninfo.h> #include "access/reloptions.h" #include "access/sysattr.h" #include "access/transam.h" #include "access/xact.h" #include "access/xlog.h" #include "catalog/catalog.h" #include "catalog/heap.h" #include "catalog/catversion.h" #include "catalog/index.h" #include "catalog/indexing.h" #include "catalog/namespace.h" #include "catalog/pg_aggregate.h" #include "catalog/pg_am.h" #include "catalog/pg_amop.h" #include "catalog/pg_amproc.h" #include "catalog/pg_app_workloadgroup_mapping.h" #include "catalog/pg_attrdef.h" #include "catalog/pg_attribute.h" #include "catalog/pg_auth_history.h" #include "catalog/pg_auth_members.h" #include "catalog/pg_authid.h" #include "catalog/pg_cast.h" #include "catalog/pg_class.h" #include "catalog/pg_collation.h" #include "catalog/pg_constraint.h" #include "catalog/pg_conversion.h" #include "catalog/pg_database.h" #include "catalog/pg_db_role_setting.h" #include "catalog/pg_default_acl.h" #include "catalog/pg_depend.h" #include "catalog/pg_description.h" #include "catalog/pg_directory.h" #include "catalog/pg_enum.h" #include "catalog/pg_extension.h" #include "catalog/pg_foreign_data_wrapper.h" #include "catalog/pg_foreign_server.h" #include "catalog/pg_foreign_table.h" #include "catalog/pg_index.h" #include "catalog/pg_inherits.h" #include "catalog/pg_job.h" #include "catalog/pg_job_proc.h" #include "catalog/gs_asp.h" #include "catalog/pg_language.h" #include "catalog/pg_largeobject.h" #include "catalog/pg_largeobject_metadata.h" #include "catalog/pg_namespace.h" #include "catalog/pg_object.h" #include "catalog/pg_opclass.h" #include "catalog/pg_operator.h" #include "catalog/pg_opfamily.h" #include "catalog/pg_partition.h" #include "catalog/pg_pltemplate.h" #include "catalog/pg_proc.h" #include "catalog/pg_range.h" #include "catalog/pg_resource_pool.h" #include "catalog/pg_rewrite.h" #include "catalog/pg_rlspolicy.h" #include "catalog/pg_seclabel.h" #include "catalog/pg_shdepend.h" #include "catalog/pg_shdescription.h" #include "catalog/pg_shseclabel.h" #include "catalog/pg_statistic.h" #include "catalog/pg_statistic_ext.h" #include "catalog/pg_synonym.h" #include "catalog/pg_tablespace.h" #include "catalog/pg_trigger.h" #include "catalog/pg_ts_config.h" #include "catalog/pg_ts_config_map.h" #include "catalog/pg_ts_dict.h" #include "catalog/pg_ts_parser.h" #include "catalog/pg_ts_template.h" #include "catalog/pg_type.h" #include "catalog/pg_user_mapping.h" #include "catalog/pg_user_status.h" #include "catalog/pg_workload_group.h" #include "catalog/gs_policy_label.h" #include "catalog/gs_auditing_policy.h" #include "catalog/gs_auditing_policy_acc.h" #include "catalog/gs_auditing_policy_filter.h" #include "catalog/gs_auditing_policy_priv.h" #include "catalog/gs_masking_policy.h" #include "catalog/gs_masking_policy_actions.h" #include "catalog/gs_masking_policy_filters.h" #include "catalog/gs_encrypted_columns.h" #include "catalog/gs_column_keys.h" #include "catalog/gs_column_keys_args.h" #include "catalog/gs_client_global_keys.h" #include "catalog/gs_client_global_keys_args.h" #include "catalog/gs_matview.h" #include "catalog/gs_matview_dependency.h" #include "catalog/gs_opt_model.h" #ifdef PGXC #include "catalog/pgxc_class.h" #include "catalog/gs_global_config.h" #include "catalog/pgxc_group.h" #include "catalog/pgxc_node.h" #include "catalog/pgxc_slice.h" #endif #include "catalog/schemapg.h" #include "catalog/storage.h" #include "catalog/storage_gtt.h" #include "catalog/pg_extension_data_source.h" #include "catalog/pg_streaming_stream.h" #include "catalog/pg_streaming_cont_query.h" #include "catalog/pg_streaming_reaper_status.h" #include "commands/matview.h" #include "commands/sec_rls_cmds.h" #include "commands/tablespace.h" #include "commands/trigger.h" #include "commands/vacuum.h" #include "miscadmin.h" #include "optimizer/clauses.h" #include "optimizer/planmain.h" #include "optimizer/prep.h" #include "optimizer/var.h" #include "pgstat.h" #ifdef PGXC #include "pgxc/pgxc.h" #include "pgxc/locator.h" #include "postmaster/autovacuum.h" #include "replication/catchup.h" #include "replication/walsender.h" #endif #include "rewrite/rewriteDefine.h" #include "rewrite/rewriteRlsPolicy.h" #include "storage/lmgr.h" #include "storage/smgr.h" #include "threadpool/threadpool.h" #include "utils/array.h" #include "utils/builtins.h" #include "utils/fmgroids.h" #include "utils/inval.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/relmapper.h" #include "utils/resowner.h" #include "utils/sec_rls_utils.h" #include "utils/snapmgr.h" #include "utils/syscache.h" #include "access/heapam.h" #include "utils/partitionmap.h" #include "utils/partitionmap_gs.h" #include "utils/resowner.h" #include "access/cstore_am.h" #include "nodes/nodeFuncs.h" #include "nodes/makefuncs.h" #ifdef ENABLE_MULTIPLE_NODES #include "tsdb/common/ts_tablecmds.h" #endif /* ENABLE_MULTIPLE_NODES */ /* * name of relcache init file(s), used to speed up backend startup */ #define RELCACHE_INIT_FILENAME "pg_internal.init" #define RELCACHE_INIT_FILEMAGIC 0x573266 /* version ID value */ /* * hardcoded tuple descriptors, contents generated by genbki.pl */ static const FormData_pg_attribute Desc_pg_class[Natts_pg_class] = {Schema_pg_class}; static const FormData_pg_attribute Desc_pg_attribute[Natts_pg_attribute] = {Schema_pg_attribute}; static const FormData_pg_attribute Desc_pg_proc[Natts_pg_proc] = {Schema_pg_proc}; static const FormData_pg_attribute Desc_pg_type[Natts_pg_type] = {Schema_pg_type}; static const FormData_pg_attribute Desc_pg_database[Natts_pg_database] = {Schema_pg_database}; static const FormData_pg_attribute Desc_pg_authid[Natts_pg_authid] = {Schema_pg_authid}; static const FormData_pg_attribute Desc_pg_auth_members[Natts_pg_auth_members] = {Schema_pg_auth_members}; static const FormData_pg_attribute Desc_pg_index[Natts_pg_index] = {Schema_pg_index}; static const FormData_pg_attribute Desc_pg_user_status[Natts_pg_user_status] = {Schema_pg_user_status}; static const FormData_pg_attribute Desc_pg_default_acl[Natts_pg_default_acl] = {Schema_pg_default_acl}; static const FormData_pg_attribute Desc_pg_pltemplate[Natts_pg_pltemplate] = {Schema_pg_pltemplate}; static const FormData_pg_attribute Desc_pg_tablespace[Natts_pg_tablespace] = {Schema_pg_tablespace}; static const FormData_pg_attribute Desc_pg_shdepend[Natts_pg_shdepend] = {Schema_pg_shdepend}; static const FormData_pg_attribute Desc_pg_foreign_server[Natts_pg_foreign_server] = {Schema_pg_foreign_server}; static const FormData_pg_attribute Desc_pg_user_mapping[Natts_pg_user_mapping] = {Schema_pg_user_mapping}; static const FormData_pg_attribute Desc_pg_foreign_data_wrapper[Natts_pg_foreign_data_wrapper] = { Schema_pg_foreign_data_wrapper}; static const FormData_pg_attribute Desc_pg_shdescription[Natts_pg_shdescription] = {Schema_pg_shdescription}; static const FormData_pg_attribute Desc_pg_aggregate[Natts_pg_aggregate] = {Schema_pg_aggregate}; static const FormData_pg_attribute Desc_pg_am[Natts_pg_am] = {Schema_pg_am}; static const FormData_pg_attribute Desc_pg_amop[Natts_pg_amop] = {Schema_pg_amop}; static const FormData_pg_attribute Desc_pg_amproc[Natts_pg_amproc] = {Schema_pg_amproc}; static const FormData_pg_attribute Desc_pg_attrdef[Natts_pg_attrdef] = {Schema_pg_attrdef}; static const FormData_pg_attribute Desc_pg_cast[Natts_pg_cast] = {Schema_pg_cast}; static const FormData_pg_attribute Desc_pg_constraint[Natts_pg_constraint] = {Schema_pg_constraint}; static const FormData_pg_attribute Desc_pg_conversion[Natts_pg_conversion] = {Schema_pg_conversion}; static const FormData_pg_attribute Desc_pg_depend[Natts_pg_depend] = {Schema_pg_depend}; static const FormData_pg_attribute Desc_pg_description[Natts_pg_description] = {Schema_pg_description}; static const FormData_pg_attribute Desc_pg_inherits[Natts_pg_inherits] = {Schema_pg_inherits}; static const FormData_pg_attribute Desc_pg_language[Natts_pg_language] = {Schema_pg_language}; static const FormData_pg_attribute Desc_pg_largeobject[Natts_pg_largeobject] = {Schema_pg_largeobject}; static const FormData_pg_attribute Desc_pg_namespace[Natts_pg_namespace] = {Schema_pg_namespace}; static const FormData_pg_attribute Desc_pg_opclass[Natts_pg_opclass] = {Schema_pg_opclass}; static const FormData_pg_attribute Desc_pg_operator[Natts_pg_operator] = {Schema_pg_operator}; static const FormData_pg_attribute Desc_pg_rewrite[Natts_pg_rewrite] = {Schema_pg_rewrite}; static const FormData_pg_attribute Desc_pg_statistic[Natts_pg_statistic] = {Schema_pg_statistic}; static const FormData_pg_attribute Desc_pg_trigger[Natts_pg_trigger] = {Schema_pg_trigger}; static const FormData_pg_attribute Desc_pg_opfamily[Natts_pg_opfamily] = {Schema_pg_opfamily}; static const FormData_pg_attribute Desc_pg_db_role_setting[Natts_pg_db_role_setting] = {Schema_pg_db_role_setting}; static const FormData_pg_attribute Desc_pg_largeobject_metadata[Natts_pg_largeobject_metadata] = { Schema_pg_largeobject_metadata}; static const FormData_pg_attribute Desc_pg_extension[Natts_pg_extension] = {Schema_pg_extension}; static const FormData_pg_attribute Desc_pg_foreign_table[Natts_pg_foreign_table] = {Schema_pg_foreign_table}; static const FormData_pg_attribute Desc_pg_statistic_ext[Natts_pg_statistic_ext] = {Schema_pg_statistic_ext}; static const FormData_pg_attribute Desc_pg_rlspolicy[Natts_pg_rlspolicy] = {Schema_pg_rlspolicy}; static const FormData_pg_attribute Desc_pg_resource_pool[Natts_pg_resource_pool] = {Schema_pg_resource_pool}; static const FormData_pg_attribute Desc_pg_workload_group[Natts_pg_workload_group] = {Schema_pg_workload_group}; static const FormData_pg_attribute Desc_pg_collation[Natts_pg_collation] = {Schema_pg_collation}; static const FormData_pg_attribute Desc_pg_auth_history[Natts_pg_auth_history] = {Schema_pg_auth_history}; static const FormData_pg_attribute Desc_pg_app_workloadgroup_mapping[Natts_pg_app_workloadgroup_mapping] = { Schema_pg_app_workloadgroup_mapping}; static const FormData_pg_attribute Desc_pg_enum[Natts_pg_enum] = {Schema_pg_enum}; static const FormData_pg_attribute Desc_pg_range[Natts_pg_range] = {Schema_pg_range}; static const FormData_pg_attribute Desc_pg_shseclabel[Natts_pg_shseclabel] = {Schema_pg_shseclabel}; static const FormData_pg_attribute Desc_pg_seclabel[Natts_pg_seclabel] = {Schema_pg_seclabel}; static const FormData_pg_attribute Desc_pg_ts_dict[Natts_pg_ts_dict] = {Schema_pg_ts_dict}; static const FormData_pg_attribute Desc_pg_ts_parser[Natts_pg_ts_parser] = {Schema_pg_ts_parser}; static const FormData_pg_attribute Desc_pg_ts_config[Natts_pg_ts_config] = {Schema_pg_ts_config}; static const FormData_pg_attribute Desc_pg_ts_config_map[Natts_pg_ts_config_map] = {Schema_pg_ts_config_map}; static const FormData_pg_attribute Desc_pg_ts_template[Natts_pg_ts_template] = {Schema_pg_ts_template}; static const FormData_pg_attribute Desc_pg_extension_data_source[Natts_pg_extension_data_source] = { Schema_pg_extension_data_source}; static const FormData_pg_attribute Desc_pg_directory[Natts_pg_directory] = {Schema_pg_directory}; static const FormData_pg_attribute Desc_pg_obsscaninfo[Natts_pg_obsscaninfo] = {Schema_pg_obsscaninfo}; static const FormData_pg_attribute Desc_pgxc_class[Natts_pgxc_class] = {Schema_pgxc_class}; static const FormData_pg_attribute Desc_pgxc_group[Natts_pgxc_group] = {Schema_pgxc_group}; static const FormData_pg_attribute Desc_pgxc_node[Natts_pgxc_node] = {Schema_pgxc_node}; static const FormData_pg_attribute Desc_pg_partition[Natts_pg_partition] = {Schema_pg_partition}; static const FormData_pg_attribute Desc_pg_job[Natts_pg_job] = {Schema_pg_job}; static const FormData_pg_attribute Desc_pg_job_proc[Natts_pg_job_proc] = {Schema_pg_job_proc}; static const FormData_pg_attribute Desc_pg_object[Natts_pg_object] = {Schema_pg_object}; static const FormData_pg_attribute Desc_pg_synonym[Natts_pg_synonym] = {Schema_pg_synonym}; static const FormData_pg_attribute Desc_pg_hashbucket[Natts_pg_hashbucket] = {Schema_pg_hashbucket}; static const FormData_pg_attribute Desc_gs_global_config[Natts_gs_global_config] = {Schema_gs_global_config}; static const FormData_pg_attribute Desc_streaming_stream[Natts_streaming_stream] = {Schema_streaming_stream}; static const FormData_pg_attribute Desc_streaming_cont_query[Natts_streaming_cont_query] = {Schema_streaming_cont_query}; static const FormData_pg_attribute Desc_streaming_reaper_status[Natts_streaming_reaper_status] = \ {Schema_streaming_reaper_status}; static const FormData_pg_attribute Desc_gs_policy_label[Natts_gs_policy_label] = {Schema_gs_policy_label}; static const FormData_pg_attribute Desc_gs_auditing_policy[Natts_gs_auditing_policy] = {Schema_gs_auditing_policy}; static const FormData_pg_attribute Desc_gs_auditing_policy_acc[Natts_gs_auditing_policy_acc] = {Schema_gs_auditing_policy_access}; static const FormData_pg_attribute Desc_gs_auditing_policy_filter[Natts_gs_auditing_policy_filters] = {Schema_gs_auditing_policy_filters}; static const FormData_pg_attribute Desc_gs_auditing_policy_priv[Natts_gs_auditing_policy_priv] = {Schema_gs_auditing_policy_privileges}; static const FormData_pg_attribute Desc_gs_masking_policy[Natts_gs_masking_policy] = {Schema_gs_masking_policy}; static const FormData_pg_attribute Desc_gs_masking_policy_actions[Natts_gs_masking_policy_actions] = {Schema_gs_masking_policy_actions}; static const FormData_pg_attribute Desc_gs_masking_policy_filters[Natts_gs_masking_policy_filters] = {Schema_gs_masking_policy_filters}; static const FormData_pg_attribute Desc_gs_asp[Natts_gs_asp] = {Schema_gs_asp}; static const FormData_pg_attribute Desc_gs_matview[Natts_gs_matview] = {Schema_gs_matview}; static const FormData_pg_attribute Desc_gs_matview_dependency[Natts_gs_matview_dependency] = {Schema_gs_matview_dependency}; static const FormData_pg_attribute Desc_pgxc_slice[Natts_pgxc_slice] = {Schema_pgxc_slice}; static const FormData_pg_attribute Desc_gs_column_keys[Natts_gs_column_keys] = {Schema_gs_column_keys}; static const FormData_pg_attribute Desc_gs_column_keys_args[Natts_gs_column_keys_args] = {Schema_gs_column_keys_args}; static const FormData_pg_attribute Desc_gs_encrypted_columns[Natts_gs_encrypted_columns] = {Schema_gs_encrypted_columns}; static const FormData_pg_attribute Desc_gs_client_global_keys[Natts_gs_client_global_keys] = {Schema_gs_client_global_keys}; static const FormData_pg_attribute Desc_gs_client_global_keys_args[Natts_gs_client_global_keys_args] = {Schema_gs_client_global_keys_args}; static const FormData_pg_attribute Desc_gs_opt_model[Natts_gs_opt_model] = {Schema_gs_opt_model}; /* Please add to the array in ascending order of oid value */ static struct CatalogRelationBuildParam catalogBuildParam[CATALOG_NUM] = {{DefaultAclRelationId, "pg_default_acl", DefaultAclRelation_Rowtype_Id, false, true, Natts_pg_default_acl, Desc_pg_default_acl, false, true}, {PLTemplateRelationId, "pg_pltemplate", PLTemplateRelation_Rowtype_Id, true, false, Natts_pg_pltemplate, Desc_pg_pltemplate, false, true}, {TableSpaceRelationId, "pg_tablespace", TableSpaceRelation_Rowtype_Id, true, true, Natts_pg_tablespace, Desc_pg_tablespace, false, true}, {SharedDependRelationId, "pg_shdepend", SharedDependRelation_Rowtype_Id, true, false, Natts_pg_shdepend, Desc_pg_shdepend, false, true}, {TypeRelationId, "pg_type", TypeRelation_Rowtype_Id, false, true, Natts_pg_type, Desc_pg_type, true, true}, {AttributeRelationId, "pg_attribute", AttributeRelation_Rowtype_Id, false, false, Natts_pg_attribute, Desc_pg_attribute, true, true}, {ProcedureRelationId, "pg_proc", ProcedureRelation_Rowtype_Id, false, true, Natts_pg_proc, Desc_pg_proc, true, true}, {RelationRelationId, "pg_class", RelationRelation_Rowtype_Id, false, true, Natts_pg_class, Desc_pg_class, true, true}, {AuthIdRelationId, "pg_authid", AuthIdRelation_Rowtype_Id, true, true, Natts_pg_authid, Desc_pg_authid, true, true}, {AuthMemRelationId, "pg_auth_members", AuthMemRelation_Rowtype_Id, true, false, Natts_pg_auth_members, Desc_pg_auth_members, true, true}, {DatabaseRelationId, "pg_database", DatabaseRelation_Rowtype_Id, true, true, Natts_pg_database, Desc_pg_database, true, true}, {ForeignServerRelationId, "pg_foreign_server", ForeignServerRelation_Rowtype_Id, false, true, Natts_pg_foreign_server, Desc_pg_foreign_server, false, true}, {UserMappingRelationId, "pg_user_mapping", UserMappingRelation_Rowtype_Id, false, true, Natts_pg_user_mapping, Desc_pg_user_mapping, false, true}, {ForeignDataWrapperRelationId, "pg_foreign_data_wrapper", ForeignDataWrapperRelation_Rowtype_Id, false, true, Natts_pg_foreign_data_wrapper, Desc_pg_foreign_data_wrapper, false, true}, {SharedDescriptionRelationId, "pg_shdescription", SharedDescriptionRelation_Rowtype_Id, true, false, Natts_pg_shdescription, Desc_pg_shdescription, false, true}, {AggregateRelationId, "pg_aggregate", AggregateRelation_Rowtype_Id, false, false, Natts_pg_aggregate, Desc_pg_aggregate, false, true}, {AccessMethodRelationId, "pg_am", AccessMethodRelation_Rowtype_Id, false, true, Natts_pg_am, Desc_pg_am, false, true}, {AccessMethodOperatorRelationId, "pg_amop", AccessMethodOperatorRelation_Rowtype_Id, false, true, Natts_pg_amop, Desc_pg_amop, false, true}, {AccessMethodProcedureRelationId, "pg_amproc", AccessMethodProcedureRelation_Rowtype_Id, false, true, Natts_pg_amproc, Desc_pg_amproc, false, true}, {AttrDefaultRelationId, "pg_attrdef", AttrDefaultRelation_Rowtype_Id, false, true, Natts_pg_attrdef, Desc_pg_attrdef, false, true}, {CastRelationId, "pg_cast", CastRelation_Rowtype_Id, false, true, Natts_pg_cast, Desc_pg_cast, false, true}, {ConstraintRelationId, "pg_constraint", ConstraintRelation_Rowtype_Id, false, true, Natts_pg_constraint, Desc_pg_constraint, false, true}, {ConversionRelationId, "pg_conversion", ConversionRelation_Rowtype_Id, false, true, Natts_pg_conversion, Desc_pg_conversion, false, true}, {DependRelationId, "pg_depend", DependRelation_Rowtype_Id, false, false, Natts_pg_depend, Desc_pg_depend, false, true}, {DescriptionRelationId, "pg_description", DescriptionRelation_Rowtype_Id, false, false, Natts_pg_description, Desc_pg_description, false, true}, {IndexRelationId, "pg_index", IndexRelation_Rowtype_Id, false, false, Natts_pg_index, Desc_pg_index, false, true}, {InheritsRelationId, "pg_inherits", InheritsRelation_Rowtype_Id, false, false, Natts_pg_inherits, Desc_pg_inherits, false, true}, {LanguageRelationId, "pg_language", LanguageRelation_Rowtype_Id, false, true, Natts_pg_language, Desc_pg_language, false, true}, {LargeObjectRelationId, "pg_largeobject", LargeObjectRelation_Rowtype_Id, false, false, Natts_pg_largeobject, Desc_pg_largeobject, false, true}, {NamespaceRelationId, "pg_namespace", NamespaceRelation_Rowtype_Id, false, true, Natts_pg_namespace, Desc_pg_namespace, false, true}, {OperatorClassRelationId, "pg_opclass", OperatorClassRelation_Rowtype_Id, false, true, Natts_pg_opclass, Desc_pg_opclass, false, true}, {OperatorRelationId, "pg_operator", OperatorRelation_Rowtype_Id, false, true, Natts_pg_operator, Desc_pg_operator, false, true}, {RewriteRelationId, "pg_rewrite", RewriteRelation_Rowtype_Id, false, true, Natts_pg_rewrite, Desc_pg_rewrite, false, true}, {StatisticRelationId, "pg_statistic", StatisticRelation_Rowtype_Id, false, false, Natts_pg_statistic, Desc_pg_statistic, false, true}, {TriggerRelationId, "pg_trigger", TriggerRelation_Rowtype_Id, false, true, Natts_pg_trigger, Desc_pg_trigger, false, true}, {OperatorFamilyRelationId, "pg_opfamily", OperatorFamilyRelation_Rowtype_Id, false, true, Natts_pg_opfamily, Desc_pg_opfamily, false, true}, {DbRoleSettingRelationId, "pg_db_role_setting", DbRoleSettingRelation_Rowtype_Id, true, false, Natts_pg_db_role_setting, Desc_pg_db_role_setting, false, true}, {LargeObjectMetadataRelationId, "pg_largeobject_metadata", LargeObjectMetadataRelation_Rowtype_Id, false, true, Natts_pg_largeobject_metadata, Desc_pg_largeobject_metadata, false, true}, {ExtensionRelationId, "pg_extension", ExtensionRelation_Rowtype_Id, false, true, Natts_pg_extension, Desc_pg_extension, false, true}, {ForeignTableRelationId, "pg_foreign_table", ForeignTableRelation_Rowtype_Id, false, false, Natts_pg_foreign_table, Desc_pg_foreign_table, false, true}, {StatisticExtRelationId, "pg_statistic_ext", StatisticExtRelation_Rowtype_Id, false, false, Natts_pg_statistic_ext, Desc_pg_statistic_ext, false, true}, {RlsPolicyRelationId, "pg_rlspolicy", RlsPolicyRelation_Rowtype_Id, false, true, Natts_pg_rlspolicy, Desc_pg_rlspolicy, false, true}, {ResourcePoolRelationId, "pg_resource_pool", ResourcePoolRelation_Rowtype_Id, true, true, Natts_pg_resource_pool, Desc_pg_resource_pool, false, true}, {WorkloadGroupRelationId, "pg_workload_group", WorkloadGroupRelation_Rowtype_Id, true, true, Natts_pg_workload_group, Desc_pg_workload_group, false, true}, {CollationRelationId, "pg_collation", CollationRelation_Rowtype_Id, false, true, Natts_pg_collation, Desc_pg_collation, false, true}, {AuthHistoryRelationId, "pg_auth_history", AuthHistoryRelation_Rowtype_Id, true, true, Natts_pg_auth_history, Desc_pg_auth_history, false, true}, {UserStatusRelationId, "pg_user_status", UserStatusRelation_Rowtype_Id, true, true, Natts_pg_user_status, Desc_pg_user_status, true, true}, {AppWorkloadGroupMappingRelationId, "pg_app_workloadgroup_mapping", AppWorkloadGroupMappingRelation_Rowtype_Id, true, true, Natts_pg_app_workloadgroup_mapping, Desc_pg_app_workloadgroup_mapping, false, true}, {EnumRelationId, "pg_enum", EnumRelation_Rowtype_Id, false, true, Natts_pg_enum, Desc_pg_enum, false, true}, {RangeRelationId, "pg_range", RangeRelation_Rowtype_Id, false, false, Natts_pg_range, Desc_pg_range, false, true}, {PgSynonymRelationId, "pg_synonym", PgSynonymRelationId_Rowtype_Id, false, true, Natts_pg_synonym, Desc_pg_synonym, false, true}, {SharedSecLabelRelationId, "pg_shseclabel", SharedSecLabelRelation_Rowtype_Id, true, false, Natts_pg_shseclabel, Desc_pg_shseclabel, false, true}, {SecLabelRelationId, "pg_seclabel", SecLabelRelation_Rowtype_Id, false, false, Natts_pg_seclabel, Desc_pg_seclabel, false, true}, {TSDictionaryRelationId, "pg_ts_dict", TSDictionaryRelation_Rowtype_Id, false, true, Natts_pg_ts_dict, Desc_pg_ts_dict, false, true}, {TSParserRelationId, "pg_ts_parser", TSParserRelation_Rowtype_Id, false, true, Natts_pg_ts_parser, Desc_pg_ts_parser, false, true}, {TSConfigRelationId, "pg_ts_config", TSConfigRelation_Rowtype_Id, false, true, Natts_pg_ts_config, Desc_pg_ts_config, false, true}, {TSConfigMapRelationId, "pg_ts_config_map", TSConfigMapRelation_Rowtype_Id, false, false, Natts_pg_ts_config_map, Desc_pg_ts_config_map, false, true}, {TSTemplateRelationId, "pg_ts_template", TSTemplateRelation_Rowtype_Id, false, true, Natts_pg_ts_template, Desc_pg_ts_template, false, true}, {DataSourceRelationId, "pg_extension_data_source", DataSourceRelation_Rowtype_Id, true, true, Natts_pg_extension_data_source, Desc_pg_extension_data_source, false, true}, {PgDirectoryRelationId, "pg_directory", PgDirectoryRelation_Rowtype_Id, false, true, Natts_pg_directory, Desc_pg_directory, false, true}, {ObsScanInfoRelationId, "pg_obsscaninfo", ObsScanInfoRelation_Rowtype_Id, false, false, Natts_pg_obsscaninfo, Desc_pg_obsscaninfo, false, true}, {PgxcClassRelationId, "pgxc_class", PgxcClassRelation_Rowtype_Id, false, false, Natts_pgxc_class, Desc_pgxc_class, false, true}, {PgxcGroupRelationId, "pgxc_group", PgxcGroupRelation_Rowtype_Id, true, true, Natts_pgxc_group, Desc_pgxc_group, false, true}, {PgxcNodeRelationId, "pgxc_node", PgxcNodeRelation_Rowtype_Id, true, true, Natts_pgxc_node, Desc_pgxc_node, false, true}, {PartitionRelationId, "pg_partition", PartitionRelation_Rowtype_Id, false, true, Natts_pg_partition, Desc_pg_partition, false, true}, {PgJobRelationId, "pg_job", PgJobRelation_Rowtype_Id, true, true, Natts_pg_job, Desc_pg_job, false, true}, {PgJobProcRelationId, "pg_job_proc", PgJobProcRelation_Rowtype_Id, true, true, Natts_pg_job_proc, Desc_pg_job_proc, false, true}, {PgObjectRelationId, "pg_object", PgObjectRelationId_Rowtype_Id, false, false, Natts_pg_object, Desc_pg_object, false, true}, {HashBucketRelationId, "pg_hashbucket", HashBucketRelationId_Rowtype_Id, false, true, Natts_pg_hashbucket, Desc_pg_hashbucket, false, true}, {StreamingStreamRelationId, "streaming_stream", StreamingStreamRelation_Rowtype_Id, false, true, Natts_streaming_stream, Desc_streaming_stream, false, true}, {StreamingContQueryRelationId, "streaming_cont_query", StreamingContQueryRelation_Rowtype_Id, false, true, Natts_streaming_cont_query, Desc_streaming_cont_query, false, true}, {StreamingReaperStatusRelationId, "streaming_reaper_status", StreamingReaperStatusRelation_Rowtype_Id, false, true, Natts_streaming_reaper_status, Desc_streaming_reaper_status, false, true}, {PgxcSliceRelationId, "pgxc_slice", PgxcSliceRelation_Rowtype_Id, false, false, Natts_pgxc_slice, Desc_pgxc_slice, false, true}, {GsGlobalConfigRelationId, "gs_global_config", GsGlobalConfigRelationId_Rowtype_Id, true, false, Natts_gs_global_config, Desc_gs_global_config, false, true}, {GsPolicyLabelRelationId, "gs_policy_label", GsPolicyLabelRelationId_Rowtype_Id, false, true, Natts_gs_policy_label, Desc_gs_policy_label, false, true}, {GsAuditingPolicyRelationId, "gs_auditing_policy", GsAuditingPolicyRelationId_Rowtype_Id, false, true, Natts_gs_auditing_policy, Desc_gs_auditing_policy, false, true}, {GsAuditingPolicyAccessRelationId, "gs_auditing_policy_acc", GsAuditingPolicyAccessRelationId_Rowtype_Id, false, true, Natts_gs_auditing_policy_acc, Desc_gs_auditing_policy_acc, false, true}, {GsAuditingPolicyPrivilegesRelationId, "gs_auditing_policy_priv", GsAuditingPolicyPrivilegesRelationId_Rowtype_Id, false, true, Natts_gs_auditing_policy_priv, Desc_gs_auditing_policy_priv, false, true}, {GsAspRelationId, "gs_asp", GsAspRelation_Rowtype_Id, false, false, Natts_gs_asp, Desc_gs_asp, false, true}, {GsAuditingPolicyFiltersRelationId, "gs_auditing_policy_filter", GsAuditingPolicyFiltersRelationId_Rowtype_Id, false, true, Natts_gs_auditing_policy_filters, Desc_gs_auditing_policy_filter, false, true}, {GsMaskingPolicyRelationId, "gs_masking_policy", GsMaskingPolicyRelationId_Rowtype_Id, false, true, Natts_gs_masking_policy, Desc_gs_masking_policy, false, true}, {GsMaskingPolicyFiltersId, "gs_masking_policy_filters", GsMaskingPolicyFiltersId_Rowtype_Id, false, true, Natts_gs_masking_policy_filters, Desc_gs_masking_policy_filters, false, true}, {GsMaskingPolicyActionsId, "gs_masking_policy_actions", GsMaskingPolicyActionsId_Rowtype_Id, false, true, Natts_gs_masking_policy_actions, Desc_gs_masking_policy_actions, false, true}, {ClientLogicCachedColumnsId, "gs_encrypted_columns", ClientLogicCachedColumnsId_Rowtype_Id, false, true, Natts_gs_encrypted_columns, Desc_gs_encrypted_columns, false, true}, {ClientLogicGlobalSettingsId, "gs_client_global_keys", ClientLogicGlobalSettingsId_Rowtype_Id, false, true, Natts_gs_client_global_keys, Desc_gs_client_global_keys, false, true}, {ClientLogicColumnSettingsId, "gs_column_keys", ClientLogicColumnSettingsId_Rowtype_Id, false, true, Natts_gs_column_keys, Desc_gs_column_keys, false, true}, {ClientLogicGlobalSettingsArgsId, "gs_client_global_keys_args", ClientLogicGlobalSettingsArgsId_Rowtype_Id, false, true, Natts_gs_client_global_keys_args, Desc_gs_client_global_keys_args, false, true}, {ClientLogicColumnSettingsArgsId, "gs_column_keys_args", ClientLogicColumnSettingsArgsId_Rowtype_Id, false, true, Natts_gs_column_keys_args, Desc_gs_column_keys_args, false, true}, {MatviewRelationId, "gs_matview", MatviewRelationId_Rowtype_Id, false, true, Natts_gs_matview, Desc_gs_matview, false, true}, {MatviewDependencyId, "gs_matview_dependency", MatviewDependencyId_Rowtype_Id, false, true, Natts_gs_matview_dependency, Desc_gs_matview_dependency, false, true}, {OptModelRelationId, "gs_opt_model", OptModelRelationId_Rowtype_Id, false, false, Natts_gs_opt_model, Desc_gs_opt_model, false, true}}; // Get cluster information of relation // static void ClusterConstraintFetch(__inout Relation relation); /* * Hash tables that index the relation cache * * We used to index the cache by both name and OID, but now there * is only an index by OID. */ typedef struct relidcacheent { Oid reloid; Relation reldesc; } RelIdCacheEnt; /* * This flag is false until we have hold the CriticalCacheBuildLock */ THR_LOCAL bool needNewLocalCacheFile = false; /* * macros to manipulate the lookup hashtables */ #define RelationCacheInsert(RELATION) \ do { \ RelIdCacheEnt* idhentry = NULL; \ bool found = false; \ idhentry = (RelIdCacheEnt*)hash_search( \ u_sess->relcache_cxt.RelationIdCache, (void*)&((RELATION)->rd_id), HASH_ENTER, &found); \ /* used to give notice if found -- now just keep quiet */ \ idhentry->reldesc = RELATION; \ } while (0) #define RelationIdCacheLookup(ID, RELATION) \ do { \ RelIdCacheEnt* hentry = NULL; \ hentry = (RelIdCacheEnt*)hash_search(u_sess->relcache_cxt.RelationIdCache, (void*)&(ID), HASH_FIND, NULL); \ if (hentry != NULL) \ (RELATION) = hentry->reldesc; \ else \ (RELATION) = NULL; \ } while (0) #define RelationCacheDelete(RELATION) \ do { \ RelIdCacheEnt* idhentry; \ idhentry = (RelIdCacheEnt*)hash_search( \ u_sess->relcache_cxt.RelationIdCache, (void*)&((RELATION)->rd_id), HASH_REMOVE, NULL); \ if (idhentry == NULL) \ ereport(WARNING, (errmsg("trying to delete a rd_id reldesc that does not exist"))); \ } while (0) /* * Special cache for opclass-related information * * Note: only default support procs get cached, ie, those with * lefttype = righttype = opcintype. */ typedef struct opclasscacheent { Oid opclassoid; /* lookup key: OID of opclass */ bool valid; /* set TRUE after successful fill-in */ StrategyNumber numSupport; /* max # of support procs (from pg_am) */ Oid opcfamily; /* OID of opclass's family */ Oid opcintype; /* OID of opclass's declared input type */ RegProcedure* supportProcs; /* OIDs of support procedures */ } OpClassCacheEnt; /* non-export function prototypes */ static void partitionMapDestroyRangeArray(RangeElement* rangeArray, int arrLen); static void PartitionMapDestroyHashArray(HashPartElement* hashArray, int arrLen); static void RelationDestroyPartitionMap(Relation relation); static void RelationDestroyRelation(Relation relation, bool remember_tupdesc); static void RememberToFreeTupleDescAtEOX(TupleDesc td); static void RelationClearRelation(Relation relation, bool rebuild); static void RelationReloadIndexInfo(Relation relation); static void RelationFlushRelation(Relation relation); static bool load_relcache_init_file(bool shared); static void write_relcache_init_file(bool shared); static void write_item(const void* data, Size len, FILE* fp); static void formrdesc(const char* relationName, Oid relationReltype, bool isshared, bool hasoids, int natts, const FormData_pg_attribute* attrs); static Relation AllocateRelationDesc(Form_pg_class relp); static void RelationParseRelOptions(Relation relation, HeapTuple tuple); static void RelationBuildTupleDesc(Relation relation, bool onlyLoadInitDefVal); static Relation RelationBuildDesc(Oid targetRelId, bool insertIt, bool buildkey = true); static void RelationInitPhysicalAddr(Relation relation); static void RelationInitBucketKey(Relation relation, HeapTuple tuple); static void RelationInitBucketInfo(Relation relation, HeapTuple tuple); static void load_critical_index(Oid indexoid, Oid heapoid); static TupleDesc GetPgClassDescriptor(void); static TupleDesc GetPgIndexDescriptor(void); static void AttrDefaultFetch(Relation relation); static void CheckConstraintFetch(Relation relation); static List* insert_ordered_oid(List* list, Oid datum); static void IndexSupportInitialize(oidvector* indclass, RegProcedure* indexSupport, Oid* opFamily, Oid* opcInType, StrategyNumber maxSupportNumber, AttrNumber maxAttributeNumber); static OpClassCacheEnt* LookupOpclassInfo(Oid operatorClassOid, StrategyNumber numSupport); static void RelationCacheInitFileRemoveInDir(const char* tblspcpath); static void unlink_initfile(const char* initfilename); static void SetBackendId(Relation relation); /* * ScanPgRelation * * This is used by RelationBuildDesc to find a pg_class * tuple matching targetRelId. The caller must hold at least * AccessShareLock on the target relid to prevent concurrent-update * scenarios --- else our SnapshotNow scan might fail to find any * version that it thinks is live. * * NB: the returned tuple has been copied into palloc'd storage * and must eventually be freed with heap_freetuple. */ HeapTuple ScanPgRelation(Oid targetRelId, bool indexOK, bool force_non_historic) { HeapTuple pg_class_tuple; Relation pg_class_desc; SysScanDesc pg_class_scan; ScanKeyData key[1]; Snapshot snapshot = NULL; /* * If something goes wrong during backend startup, we might find ourselves * trying to read pg_class before we've selected a database. That ain't * gonna work, so bail out with a useful error message. If this happens, * it probably means a relcache entry that needs to be nailed isn't. */ if (!OidIsValid(u_sess->proc_cxt.MyDatabaseId)) ereport(FATAL, (errmsg("cannot read pg_class without having selected a database"))); /* * form a scan key */ ScanKeyInit(&key[0], ObjectIdAttributeNumber, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(targetRelId)); /* * Open pg_class and fetch a tuple. Force heap scan if we haven't yet * built the critical relcache entries (this includes initdb and startup * without a pg_internal.init file). The caller can also force a heap * scan by setting indexOK == false. */ pg_class_desc = heap_open(RelationRelationId, AccessShareLock); /* * for logical decoding */ snapshot = SnapshotNow; if (HistoricSnapshotActive()) snapshot = GetCatalogSnapshot(RelationRelationId); /* * The caller might need a tuple that's newer than the one the historic * snapshot; currently the only case requiring to do so is looking up the * relfilenode of non mapped system relations during decoding. */ pg_class_scan = systable_beginscan( pg_class_desc, ClassOidIndexId, indexOK && u_sess->relcache_cxt.criticalRelcachesBuilt, snapshot, 1, key); pg_class_tuple = systable_getnext(pg_class_scan); /* * Must copy tuple before releasing buffer. */ if (HeapTupleIsValid(pg_class_tuple)) pg_class_tuple = heap_copytuple(pg_class_tuple); /* all done */ systable_endscan(pg_class_scan); heap_close(pg_class_desc, AccessShareLock); return pg_class_tuple; } /* * AllocateRelationDesc * * This is used to allocate memory for a new relation descriptor * and initialize the rd_rel field from the given pg_class tuple. */ static Relation AllocateRelationDesc(Form_pg_class relp) { Relation relation; MemoryContext oldcxt; Form_pg_class relationForm; /* Relcache entries must live in u_sess->cache_mem_cxt */ oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); /* * allocate and zero space for new relation descriptor */ relation = (Relation)palloc0(sizeof(RelationData)); /* make sure relation is marked as having no open file yet */ relation->rd_smgr = NULL; /* init bucketkey to point itself means bucket key is not build yet */ relation->rd_bucketkey = (RelationBucketKey *)&(relation->rd_bucketkey); relation->rd_bucketoid = InvalidOid; /* * Copy the relation tuple form * * We only allocate space for the fixed fields, ie, CLASS_TUPLE_SIZE. The * variable-length fields (relacl, reloptions) are NOT stored in the * relcache --- there'd be little point in it, since we don't copy the * tuple's nulls bitmap and hence wouldn't know if the values are valid. * Bottom line is that relacl *cannot* be retrieved from the relcache. Get * it from the syscache if you need it. The same goes for the original * form of reloptions (however, we do store the parsed form of reloptions * in rd_options). */ relationForm = (Form_pg_class)palloc(sizeof(FormData_pg_class)); MemCpy(relationForm, relp, CLASS_TUPLE_SIZE); /* initialize relation tuple form */ relation->rd_rel = relationForm; /* and allocate attribute tuple form storage */ relation->rd_att = CreateTemplateTupleDesc(relationForm->relnatts, relationForm->relhasoids, TAM_INVALID); //TODO:this should be TAM_invalid when merge ustore relation->rd_tam_type = TAM_HEAP; /* which we mark as a reference-counted tupdesc */ relation->rd_att->tdrefcount = 1; (void)MemoryContextSwitchTo(oldcxt); return relation; } /* * RelationParseRelOptions * Convert pg_class.reloptions into pre-parsed rd_options * * tuple is the real pg_class tuple (not rd_rel!) for relation * * Note: rd_rel and (if an index) rd_am must be valid already */ static void RelationParseRelOptions(Relation relation, HeapTuple tuple) { bytea* options = NULL; relation->rd_options = NULL; /* Fall out if relkind should not have options */ switch (relation->rd_rel->relkind) { case RELKIND_RELATION: case RELKIND_TOASTVALUE: case RELKIND_INDEX: case RELKIND_GLOBAL_INDEX: case RELKIND_VIEW: case RELKIND_CONTQUERY: case RELKIND_MATVIEW: break; default: return; } /* * Fetch reloptions from tuple; have to use a hardwired descriptor because * we might not have any other for pg_class yet (consider executing this * code for pg_class itself) */ options = extractRelOptions( tuple, GetPgClassDescriptor(), RelationIsIndex(relation) ? relation->rd_am->amoptions : InvalidOid); /* * Copy parsed data into u_sess->cache_mem_cxt. To guard against the * possibility of leaks in the reloptions code, we want to do the actual * parsing in the caller's memory context and copy the results into * u_sess->cache_mem_cxt after the fact. */ if (options != NULL) { relation->rd_options = (bytea*)MemoryContextAlloc(u_sess->cache_mem_cxt, VARSIZE(options)); MemCpy(relation->rd_options, options, VARSIZE(options)); pfree_ext(options); } } /* * RelationBuildTupleDesc * * Form the relation's tuple descriptor from information in * the pg_attribute, pg_attrdef & pg_constraint system catalogs. * * For catalog relcache built from schemapg.h or init file, we * need to load their initial default values separately. */ static void RelationBuildTupleDesc(Relation relation, bool onlyLoadInitDefVal) { HeapTuple pg_attribute_tuple; Relation pg_attribute_desc; SysScanDesc pg_attribute_scan; ScanKeyData skey[2]; int need; TupleConstr* constr = NULL; AttrDefault* attrdef = NULL; int ndef = 0; /* alter table instantly */ Datum dval; bool isNull = false; bool hasInitDefval = false; TupInitDefVal* initdvals = NULL; if (!onlyLoadInitDefVal) { /* copy some fields from pg_class row to rd_att */ relation->rd_att->tdtypeid = relation->rd_rel->reltype; relation->rd_att->tdtypmod = -1; /* unnecessary, but... */ relation->rd_att->tdhasoid = relation->rd_rel->relhasoids; constr = (TupleConstr*)MemoryContextAllocZero(u_sess->cache_mem_cxt, sizeof(TupleConstr)); constr->has_not_null = false; } /* * Form a scan key that selects only user attributes (attnum > 0). * (Eliminating system attribute rows at the index level is lots faster * than fetching them.) */ ScanKeyInit(&skey[0], Anum_pg_attribute_attrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(relation))); ScanKeyInit(&skey[1], Anum_pg_attribute_attnum, BTGreaterStrategyNumber, F_INT2GT, Int16GetDatum(0)); /* * Open pg_attribute and begin a scan. Force heap scan if we haven't yet * built the critical relcache entries (this includes initdb and startup * without a pg_internal.init file). */ pg_attribute_desc = heap_open(AttributeRelationId, AccessShareLock); pg_attribute_scan = systable_beginscan( pg_attribute_desc, AttributeRelidNumIndexId, u_sess->relcache_cxt.criticalRelcachesBuilt, SnapshotNow, 2, skey); /* * add attribute data to relation->rd_att */ need = RelationGetNumberOfAttributes(relation); /* alter table instantly or load catalog init default during backend startup */ Assert(relation->rd_att->initdefvals == NULL || onlyLoadInitDefVal); if (relation->rd_att->initdefvals != NULL && onlyLoadInitDefVal) return; /* set all the *TupInitDefVal* objects later. */ initdvals = (TupInitDefVal*)MemoryContextAllocZero(u_sess->cache_mem_cxt, need * sizeof(TupInitDefVal)); while (HeapTupleIsValid(pg_attribute_tuple = systable_getnext(pg_attribute_scan))) { Form_pg_attribute attp; attp = (Form_pg_attribute)GETSTRUCT(pg_attribute_tuple); if (attp->attnum <= 0 || attp->attnum > RelationGetNumberOfAttributes(relation)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid attribute number %d for %s", attp->attnum, RelationGetRelationName(relation)))); if (!onlyLoadInitDefVal) { /* * Check if the attribute has been updated. * Some modification can change relation attributes concurrently * without holding any relation lock. Currently, we use snapshot satisifyNow * to decide the visibility of tuples, so it can see the different version of tuples * of the same hot update chain. * e.g: grant xxx on table to user1. revoke xxx on table from user1. * Since relation->rd_att->atts palloc0 in function CreateTemplateTupleDesc, * its attnum should be zero, use it to check if above scenario happened. */ if (relation->rd_att->attrs[attp->attnum - 1]->attnum != 0) { ereport(ERROR,(errmsg("Catalog attribute %d for relation \"%s\" has been updated concurrently", attp->attnum, RelationGetRelationName(relation)))); } errno_t rc = memcpy_s( relation->rd_att->attrs[attp->attnum - 1], ATTRIBUTE_FIXED_PART_SIZE, attp, ATTRIBUTE_FIXED_PART_SIZE); securec_check(rc, "\0", "\0"); } if (initdvals != NULL) { dval = fastgetattr(pg_attribute_tuple, Anum_pg_attribute_attinitdefval, pg_attribute_desc->rd_att, &isNull); if (isNull) { initdvals[attp->attnum - 1].isNull = true; initdvals[attp->attnum - 1].datum = NULL; initdvals[attp->attnum - 1].dataLen = 0; } else { /* fetch and copy the default value. */ bytea* val = DatumGetByteaP(dval); int len = VARSIZE(val) - VARHDRSZ; char* buf = (char*)MemoryContextAlloc(u_sess->cache_mem_cxt, len); MemCpy(buf, VARDATA(val), len); initdvals[attp->attnum - 1].isNull = false; initdvals[attp->attnum - 1].datum = (Datum*)buf; initdvals[attp->attnum - 1].dataLen = len; hasInitDefval = true; } } /* Update constraint/default info */ if (attp->attnotnull && !onlyLoadInitDefVal) constr->has_not_null = true; if (attp->atthasdef && !onlyLoadInitDefVal) { if (attrdef == NULL) attrdef = (AttrDefault*)MemoryContextAllocZero( u_sess->cache_mem_cxt, RelationGetNumberOfAttributes(relation) * sizeof(AttrDefault)); attrdef[ndef].adnum = attp->attnum; attrdef[ndef].adbin = NULL; ndef++; } need--; if (need == 0) break; } /* * end the scan and close the attribute relation */ systable_endscan(pg_attribute_scan); heap_close(pg_attribute_desc, AccessShareLock); if (need != 0) { /* find all missed attributes, and print them */ StringInfo missing_attnums = makeStringInfo(); for (int i = 0; i < RelationGetNumberOfAttributes(relation); i++) { if (0 == relation->rd_att->attrs[i]->attnum) { appendStringInfo(missing_attnums, "%d ", (i + 1)); } } ereport(ERROR, (errcode(ERRCODE_NO_DATA), errmsg("Catalog is missing %d attribute(s) for relid %u", need, RelationGetRelid(relation)), errdetail("Relation \"%s\" expects %d attribute(s), but not found [%s]", RelationGetRelationName(relation), relation->rd_rel->relnatts, missing_attnums->data))); } /* * if this relation doesn't have any alter-table-instantly data, * free and reset *initdefvals* to be null. */ if (initdvals != NULL && !hasInitDefval) pfree_ext(initdvals); else if (initdvals != NULL && relation->rd_att->initdefvals != NULL) { for (int i = 0; i < RelationGetNumberOfAttributes(relation); ++i) { if (initdvals[i].datum != NULL) pfree_ext(initdvals[i].datum); } pfree_ext(initdvals); } else relation->rd_att->initdefvals = initdvals; if (onlyLoadInitDefVal) return; /* * The attcacheoff values we read from pg_attribute should all be -1 * ("unknown"). Verify this if assert checking is on. They will be * computed when and if needed during tuple access. * * If we are separately loading catalog relcache initial default, their * attcacheoff may have been updated. In such case, skip assertation. */ #ifdef USE_ASSERT_CHECKING { int i; for (i = 0; i < RelationGetNumberOfAttributes(relation); i++) Assert(relation->rd_att->attrs[i]->attcacheoff == -1); } #endif /* * However, we can easily set the attcacheoff value for the first * attribute: it must be zero. This eliminates the need for special cases * for attnum=1 that used to exist in fastgetattr() and index_getattr(). */ if (RelationGetNumberOfAttributes(relation) > 0) relation->rd_att->attrs[0]->attcacheoff = 0; /* * Set up constraint/default info */ if (constr->has_not_null || ndef > 0 || relation->rd_rel->relchecks || relation->rd_rel->relhasclusterkey) { relation->rd_att->constr = constr; if (ndef > 0) /* DEFAULTs */ { if (ndef < RelationGetNumberOfAttributes(relation)) constr->defval = (AttrDefault*)repalloc(attrdef, ndef * sizeof(AttrDefault)); else constr->defval = attrdef; constr->num_defval = ndef; AttrDefaultFetch(relation); } else { constr->num_defval = 0; constr->defval = NULL; } if (relation->rd_rel->relchecks > 0) /* CHECKs */ { constr->num_check = relation->rd_rel->relchecks; constr->check = (ConstrCheck*)MemoryContextAllocZero(u_sess->cache_mem_cxt, constr->num_check * sizeof(ConstrCheck)); CheckConstraintFetch(relation); } else { constr->num_check = 0; constr->check = NULL; } /* Relation has cluster keys */ if (relation->rd_rel->relhasclusterkey) { ClusterConstraintFetch(relation); } else { constr->clusterKeyNum = 0; constr->clusterKeys = NULL; } } else { pfree_ext(constr); relation->rd_att->constr = NULL; } } /* * RelationBuildRuleLock * * Form the relation's rewrite rules from information in * the pg_rewrite system catalog. * * Note: The rule parsetrees are potentially very complex node structures. * To allow these trees to be freed when the relcache entry is flushed, * we make a private memory context to hold the RuleLock information for * each relcache entry that has associated rules. The context is used * just for rule info, not for any other subsidiary data of the relcache * entry, because that keeps the update logic in RelationClearRelation() * manageable. The other subsidiary data structures are simple enough * to be easy to free explicitly, anyway. */ static void RelationBuildRuleLock(Relation relation) { MemoryContext rulescxt; MemoryContext oldcxt; HeapTuple rewrite_tuple; Relation rewrite_desc; TupleDesc rewrite_tupdesc; SysScanDesc rewrite_scan; ScanKeyData key; RuleLock* rulelock = NULL; int numlocks; RewriteRule** rules; int maxlocks; /* * Make the private context. Parameters are set on the assumption that * it'll probably not contain much data. */ rulescxt = AllocSetContextCreate(u_sess->cache_mem_cxt, RelationGetRelationName(relation), ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_SMALL_MAXSIZE); relation->rd_rulescxt = rulescxt; /* * allocate an array to hold the rewrite rules (the array is extended if * necessary) */ maxlocks = 4; rules = (RewriteRule**)MemoryContextAlloc(rulescxt, sizeof(RewriteRule*) * maxlocks); numlocks = 0; /* * form a scan key */ ScanKeyInit( &key, Anum_pg_rewrite_ev_class, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(relation))); /* * open pg_rewrite and begin a scan * * Note: since we scan the rules using RewriteRelRulenameIndexId, we will * be reading the rules in name order, except possibly during * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn * ensures that rules will be fired in name order. */ rewrite_desc = heap_open(RewriteRelationId, AccessShareLock); rewrite_tupdesc = RelationGetDescr(rewrite_desc); rewrite_scan = systable_beginscan(rewrite_desc, RewriteRelRulenameIndexId, true, SnapshotNow, 1, &key); while (HeapTupleIsValid(rewrite_tuple = systable_getnext(rewrite_scan))) { Form_pg_rewrite rewrite_form = (Form_pg_rewrite)GETSTRUCT(rewrite_tuple); bool isnull = false; Datum rule_datum; char* rule_str = NULL; RewriteRule* rule = NULL; rule = (RewriteRule*)MemoryContextAlloc(rulescxt, sizeof(RewriteRule)); rule->ruleId = HeapTupleGetOid(rewrite_tuple); rule->event = (CmdType)(rewrite_form->ev_type - '0'); rule->attrno = rewrite_form->ev_attr; rule->enabled = rewrite_form->ev_enabled; rule->isInstead = rewrite_form->is_instead; /* * Must use heap_getattr to fetch ev_action and ev_qual. Also, the * rule strings are often large enough to be toasted. To avoid * leaking memory in the caller's context, do the detoasting here so * we can free the detoasted version. */ rule_datum = heap_getattr(rewrite_tuple, Anum_pg_rewrite_ev_action, rewrite_tupdesc, &isnull); Assert(!isnull); rule_str = TextDatumGetCString(rule_datum); oldcxt = MemoryContextSwitchTo(rulescxt); rule->actions = (List*)stringToNode(rule_str); (void)MemoryContextSwitchTo(oldcxt); pfree_ext(rule_str); rule_datum = heap_getattr(rewrite_tuple, Anum_pg_rewrite_ev_qual, rewrite_tupdesc, &isnull); Assert(!isnull); rule_str = TextDatumGetCString(rule_datum); oldcxt = MemoryContextSwitchTo(rulescxt); rule->qual = (Node*)stringToNode(rule_str); (void)MemoryContextSwitchTo(oldcxt); pfree_ext(rule_str); /* * We want the rule's table references to be checked as though by the * table owner, not the user referencing the rule. Therefore, scan * through the rule's actions and set the checkAsUser field on all * rtable entries. We have to look at the qual as well, in case it * contains sublinks. * * The reason for doing this when the rule is loaded, rather than when * it is stored, is that otherwise ALTER TABLE OWNER would have to * grovel through stored rules to update checkAsUser fields. Scanning * the rule tree during load is relatively cheap (compared to * constructing it in the first place), so we do it here. */ setRuleCheckAsUser((Node*)rule->actions, relation->rd_rel->relowner); setRuleCheckAsUser(rule->qual, relation->rd_rel->relowner); if (numlocks >= maxlocks) { maxlocks *= 2; rules = (RewriteRule**)repalloc(rules, sizeof(RewriteRule*) * maxlocks); } rules[numlocks++] = rule; } /* * end the scan and close the attribute relation */ systable_endscan(rewrite_scan); heap_close(rewrite_desc, AccessShareLock); /* * there might not be any rules (if relhasrules is out-of-date) */ if (numlocks == 0) { relation->rd_rules = NULL; relation->rd_rulescxt = NULL; MemoryContextDelete(rulescxt); return; } /* * form a RuleLock and insert into relation */ rulelock = (RuleLock*)MemoryContextAlloc(rulescxt, sizeof(RuleLock)); rulelock->numLocks = numlocks; rulelock->rules = rules; relation->rd_rules = rulelock; } /* * equalRuleLocks * * Determine whether two RuleLocks are equivalent * * Probably this should be in the rules code someplace... */ static bool equalRuleLocks(RuleLock* rlock1, RuleLock* rlock2) { int i; /* * As of 7.3 we assume the rule ordering is repeatable, because * RelationBuildRuleLock should read 'em in a consistent order. So just * compare corresponding slots. */ if (rlock1 != NULL) { if (rlock2 == NULL) return false; if (rlock1->numLocks != rlock2->numLocks) return false; for (i = 0; i < rlock1->numLocks; i++) { RewriteRule* rule1 = rlock1->rules[i]; RewriteRule* rule2 = rlock2->rules[i]; if (rule1->ruleId != rule2->ruleId) return false; if (rule1->event != rule2->event) return false; if (rule1->attrno != rule2->attrno) return false; if (rule1->enabled != rule2->enabled) return false; if (rule1->isInstead != rule2->isInstead) return false; if (!equal(rule1->qual, rule2->qual)) return false; if (!equal(rule1->actions, rule2->actions)) return false; } } else if (rlock2 != NULL) return false; return true; } static Relation CatalogRelationBuildDesc(const char* relationName, Oid relationReltype, bool isshared, bool hasoids, int natts, const FormData_pg_attribute* attrs, bool isnailed, bool insertIt) { Relation relation; int i; bool has_not_null = false; MemoryContext oldcxt; /* Relcache entries must live in t_thrd.mem_cxt.cache_mem_cxt */ oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); /* * allocate new relation desc, clear all fields of reldesc */ relation = (Relation)palloc0(sizeof(RelationData)); /* make sure relation is marked as having no open file yet */ relation->rd_smgr = NULL; relation->rd_bucketkey = NULL; relation->rd_bucketoid = InvalidOid; relation->rd_rel = (Form_pg_class)palloc0(sizeof(FormData_pg_class)); /* * initialize reference count: 1 because it is nailed in cache */ relation->rd_refcnt = isnailed ? 1 : 0; relation->rd_isnailed = isnailed; relation->rd_createSubid = InvalidSubTransactionId; relation->rd_newRelfilenodeSubid = InvalidSubTransactionId; relation->rd_backend = InvalidBackendId; relation->rd_islocaltemp = false; namestrcpy(&relation->rd_rel->relname, relationName); relation->rd_rel->relnamespace = PG_CATALOG_NAMESPACE; relation->rd_rel->reltype = relationReltype; relation->rd_rel->relisshared = isshared; ereport(DEBUG1, (errmsg("relation->rd_rel->relisshared %d", relation->rd_rel->relisshared))); if (isshared) relation->rd_rel->reltablespace = GLOBALTABLESPACE_OID; /* formrdesc is used only for permanent relations */ relation->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT; relation->rd_rel->relpages = 0; relation->rd_rel->reltuples = 0; relation->rd_rel->relallvisible = 0; relation->rd_rel->relkind = RELKIND_RELATION; relation->rd_rel->relhasoids = hasoids; relation->rd_rel->relnatts = (int16)natts; // Catalog tables are heap table type. relation->rd_tam_type = TAM_HEAP; relation->rd_att = CreateTemplateTupleDesc(natts, hasoids, TAM_HEAP); relation->rd_att->tdrefcount = 1; /* mark as refcounted */ relation->rd_att->tdtypeid = relationReltype; relation->rd_att->tdtypmod = -1; has_not_null = false; for (i = 0; i < natts; i++) { errno_t rc = EOK; rc = memcpy_s(relation->rd_att->attrs[i], ATTRIBUTE_FIXED_PART_SIZE, &attrs[i], ATTRIBUTE_FIXED_PART_SIZE); securec_check(rc, "\0", "\0"); has_not_null = has_not_null || attrs[i].attnotnull; /* make sure attcacheoff is valid */ relation->rd_att->attrs[i]->attcacheoff = -1; } /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */ relation->rd_att->attrs[0]->attcacheoff = 0; /* mark not-null status */ if (has_not_null) { TupleConstr* constr = (TupleConstr*)palloc0(sizeof(TupleConstr)); constr->has_not_null = true; relation->rd_att->constr = constr; } /* * initialize relation id from info in att array (my, this is ugly) */ RelationGetRelid(relation) = relation->rd_att->attrs[0]->attrelid; (void)MemoryContextSwitchTo(oldcxt); return relation; } CatalogRelationBuildParam GetCatalogParam(Oid targetId) { struct CatalogRelationBuildParam result; errno_t rc = memset_s(&result, sizeof(result), 0, sizeof(result)); securec_check(rc, "\0", "\0"); int flag = 1; int low = 0; int high = CATALOG_NUM - 1; while (low <= high) { int mid = (low + high) / 2; struct CatalogRelationBuildParam midVal = catalogBuildParam[mid]; if (midVal.oid < targetId) { low = mid + 1; } else if (midVal.oid > targetId) { high = mid - 1; } else { flag = 0; result = midVal; break; } } if (flag == 1) { result.oid = 0; } return result; } static void SetBackendId(Relation relation) { switch (relation->rd_rel->relpersistence) { case RELPERSISTENCE_UNLOGGED: case RELPERSISTENCE_PERMANENT: case RELPERSISTENCE_TEMP: // @Temp Table. Temp table here is just like unlogged table. relation->rd_backend = InvalidBackendId; break; case RELPERSISTENCE_GLOBAL_TEMP: // global temp table relation->rd_backend = BackendIdForTempRelations; break; default: ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid relpersistence: %c", relation->rd_rel->relpersistence))); break; } } /* * RelationBuildDesc * * Build a relation descriptor. The caller must hold at least * AccessShareLock on the target relid. * * The new descriptor is inserted into the hash table if insertIt is true. * * Returns NULL if no pg_class row could be found for the given relid * (suggesting we are trying to access a just-deleted relation). * Any other error is reported via elog. */ static Relation RelationBuildDesc(Oid targetRelId, bool insertIt, bool buildkey) { Relation relation; HeapTuple pg_class_tuple; Form_pg_class relp; Oid relid; /* * find the tuple in pg_class corresponding to the given relation id */ pg_class_tuple = ScanPgRelation(targetRelId, true, false); /* * if no such tuple exists, return NULL */ if (!HeapTupleIsValid(pg_class_tuple)) return NULL; /* * get information from the pg_class_tuple */ relid = HeapTupleGetOid(pg_class_tuple); relp = (Form_pg_class)GETSTRUCT(pg_class_tuple); Assert(relid == targetRelId); CatalogRelationBuildParam catalogParam = GetCatalogParam(targetRelId); if (catalogParam.oid != 0) { int natts = 0; relation = CatalogRelationBuildDesc(catalogParam.relationName, catalogParam.relationReltype, catalogParam.isshared, catalogParam.hasoids, catalogParam.natts, catalogParam.attrs, catalogParam.isnailed, insertIt); /* * Copy tuple to relation->rd_rel. (See notes in * AllocateRelationDesc()) * But pay attention to relnatts of rd_rel because we hardcoded all system catalogs, * relnatts in pg_class might be old and will not be updated. * Use need to use hardcoded info in schemapg.h to fix it. */ natts = relation->rd_rel->relnatts; errno_t rc = EOK; rc = memcpy_s((char*)relation->rd_rel, CLASS_TUPLE_SIZE, (char*)relp, CLASS_TUPLE_SIZE); securec_check(rc, "\0", "\0"); relation->rd_rel->relnatts = natts; } else { /* * allocate storage for the relation descriptor, and copy pg_class_tuple * to relation->rd_rel. */ relation = AllocateRelationDesc(relp); /* * initialize the relation's relation id (relation->rd_id) */ RelationGetRelid(relation) = relid; /* * normal relations are not nailed into the cache; nor can a pre-existing * relation be new. It could be temp though. (Actually, it could be new * too, but it's okay to forget that fact if forced to flush the entry.) */ relation->rd_refcnt = 0; relation->rd_isnailed = false; relation->rd_createSubid = InvalidSubTransactionId; relation->rd_newRelfilenodeSubid = InvalidSubTransactionId; relation->rd_islocaltemp = false; SetBackendId(relation); if (relation->rd_rel->relpersistence == RELPERSISTENCE_GLOBAL_TEMP) { BlockNumber relpages = 0; double reltuples = 0; BlockNumber relallvisible = 0; get_gtt_relstats(RelationGetRelid(relation), &relpages, &reltuples, &relallvisible, NULL); relation->rd_rel->relpages = (float8)relpages; relation->rd_rel->reltuples = (float8)reltuples; relation->rd_rel->relallvisible = (int4)relallvisible; } /* * initialize the tuple descriptor (relation->rd_att). */ RelationBuildTupleDesc(relation, false); } /* * Fetch rules and triggers that affect this relation */ if (relation->rd_rel->relhasrules) RelationBuildRuleLock(relation); else { relation->rd_rules = NULL; relation->rd_rulescxt = NULL; } if (relation->rd_rel->relhastriggers) RelationBuildTriggers(relation); else relation->trigdesc = NULL; #ifdef PGXC if (IS_PGXC_COORDINATOR && relation->rd_id >= FirstNormalObjectId) RelationBuildLocator(relation); #endif /* * if it's an index, initialize index-related information */ if (OidIsValid(relation->rd_rel->relam)) RelationInitIndexAccessInfo(relation); /* extract reloptions if any */ RelationParseRelOptions(relation, pg_class_tuple); if (RelationIsRedistributeDest(relation)) relation->rd_att->tdisredistable = true; /* get the table access method type from reloptions * and populate them in relation and tuple descriptor */ relation->rd_tam_type = get_tableam_from_reloptions(relation->rd_options, relation->rd_rel->relkind); relation->rd_att->tdTableAmType = relation->rd_tam_type; /* get row level security policies for this relation */ if (RelationEnableRowSecurity(relation)) RelationBuildRlsPolicies(relation); else relation->rd_rlsdesc = NULL; /* * if it's a partitioned table or value partitioned table(HDFS), we initialize * partitionmap data structure for it */ if (RELATION_IS_PARTITIONED(relation) || RelationIsValuePartitioned(relation)) { RelationInitPartitionMap(relation); } /* fetch bucket info from pgclass tuple */ RelationInitBucketInfo(relation, pg_class_tuple); /* hash bucket columns cannot be changed, so there is no need to rebuild them */ if (buildkey) { RelationInitBucketKey(relation, pg_class_tuple); } relation->parentId = InvalidOid; /* * initialize the relation lock manager information */ RelationInitLockInfo(relation); /* see lmgr.c */ /* * initialize physical addressing information for the relation */ RelationInitPhysicalAddr(relation); /* make sure relation is marked as having no open file yet */ relation->rd_smgr = NULL; if (relation->rd_rel->relkind == RELKIND_MATVIEW && heap_is_matview_init_state(relation)) relation->rd_isscannable = false; else relation->rd_isscannable = true; /* * now we can free the memory allocated for pg_class_tuple */ heap_freetuple_ext(pg_class_tuple); /* * mlog oid */ if (!IsCatalogRelation(relation)) { relation->rd_mlogoid = find_matview_mlog_table(relid); } /* * Insert newly created relation into relcache hash table, if requested. */ if (insertIt) RelationCacheInsert(relation); /* It's fully valid */ relation->rd_isvalid = true; return relation; } /* * @@GaussDB@@ * Brief : * Description : When load RelationData to relcache, intalize Bucket info which * stores bucket oid. */ static void RelationInitBucketInfo(Relation relation, HeapTuple tuple) { bool isNull = false; Datum datum; /* fetch relbucketoid from pg_class tuple */ datum = heap_getattr(tuple, Anum_pg_class_relbucket, GetDefaultPgClassDesc(), &isNull); if (isNull) { relation->rd_bucketoid = InvalidOid; } else { relation->rd_bucketoid = DatumGetObjectId(datum); Assert(OidIsValid(relation->rd_bucketoid)); } } static int16 *relationGetHBucketKey(HeapTuple tuple, int *nColumn) { Datum bkey_raw; bool isNull = false; ArrayType *bkey_columns = NULL; Assert(PointerIsValid(nColumn)); /* Get the raw data which contain patition key's columns */ bkey_raw = heap_getattr(tuple, Anum_pg_class_relbucketkey, GetDefaultPgClassDesc(), &isNull); /* if the raw value of bucket key is null, then set bucketkey to NULL*/ if (isNull) { *nColumn = 0; return NULL; } /* convert Datum to ArrayType*/ bkey_columns = DatumGetArrayTypeP(bkey_raw); /* Get number of bucket key columns from int2verctor*/ *nColumn = ARR_DIMS(bkey_columns)[0]; /*CHECK: the ArrayType of bucket key is valid*/ if (ARR_NDIM(bkey_columns) != 1 || *nColumn < 0 || ARR_HASNULL(bkey_columns) || ARR_ELEMTYPE(bkey_columns) != INT2OID) { ereport(ERROR, (errcode(ERRCODE_ARRAY_ELEMENT_ERROR), errmsg("bucket key column's number is not a 1-D smallint array"))); } /* Get int2 array of bucket key column numbers*/ return (int16 *)ARR_DATA_PTR(bkey_columns); } /* * @@GaussDB@@ * Brief : * Description : When load RelationData to relcache, intalize BucketKey which * stores bucket key column number. * Notes : We must note than the bucket key cannot be changed so we don't * need to reload it. */ static void RelationInitBucketKey(Relation relation, HeapTuple tuple) { MemoryContext old_context = NULL; int2vector *bkey = NULL; Oid *bkeytype = NULL; int16 *attNum = NULL; int nColumn; Form_pg_attribute *rel_attrs = RelationGetDescr(relation)->attrs; if (!RelationIsRelation(relation) || !OidIsValid(relation->rd_bucketoid)) { relation->rd_bucketkey = NULL; return; } /* Get int2 array of bucket key column numbers*/ attNum = relationGetHBucketKey(tuple, &nColumn); /* if the raw value of bucket key is null, then set bucketkey to NULL*/ if (attNum == NULL) { relation->rd_bucketkey = NULL; return; } /* build Bucket key */ old_context = MemoryContextSwitchTo(u_sess->cache_mem_cxt); /* Initialize int2verctor structure for attribute number array of bucket key*/ bkey = buildint2vector(NULL, nColumn); bkeytype = (Oid*)palloc0(sizeof(Oid)*nColumn); /* specify value to int2verctor and build type oid array*/ for (int i = 0; i < nColumn; i++) { bkey->values[i] = attNum[i]; for (int j = 0; j < RelationGetDescr(relation)->natts; j++) { if (attNum[i] == rel_attrs[j]->attnum) { bkeytype[i] = rel_attrs[j]->atttypid; break; } } } relation->rd_bucketkey = (RelationBucketKey*) palloc0(sizeof(RelationBucketKey)); relation->rd_bucketkey->bucketKey = bkey; relation->rd_bucketkey->bucketKeyType = bkeytype; (void)MemoryContextSwitchTo(old_context); } /* * Initialize the physical addressing info (RelFileNode) for a relcache entry * * Note: at the physical level, relations in the pg_global tablespace must * be treated as shared, even if relisshared isn't set. Hence we do not * look at relisshared here. */ static void RelationInitPhysicalAddr(Relation relation) { relation->rd_node.spcNode = ConvertToRelfilenodeTblspcOid(relation->rd_rel->reltablespace); if (relation->rd_node.spcNode == GLOBALTABLESPACE_OID) relation->rd_node.dbNode = InvalidOid; else relation->rd_node.dbNode = u_sess->proc_cxt.MyDatabaseId; if (relation->rd_rel->relfilenode) { /* * Even if we are using a decoding snapshot that doesn't represent * the current state of the catalog we need to make sure the * filenode points to the current file since the older file will * be gone (or truncated). The new file will still contain older * rows so lookups in them will work correctly. This wouldn't work * correctly if rewrites were allowed to change the schema in a * noncompatible way, but those are prevented both on catalog * tables and on user tables declared as additional catalog * tables. */ if (HistoricSnapshotActive() && RelationIsAccessibleInLogicalDecoding(relation) && IsTransactionState()) { HeapTuple phys_tuple; Form_pg_class physrel; phys_tuple = ScanPgRelation(RelationGetRelid(relation), RelationGetRelid(relation) != ClassOidIndexId, true); if (!HeapTupleIsValid(phys_tuple)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("could not find pg_class entry for %u", RelationGetRelid(relation)))); physrel = (Form_pg_class)GETSTRUCT(phys_tuple); relation->rd_rel->reltablespace = physrel->reltablespace; relation->rd_rel->relfilenode = physrel->relfilenode; heap_freetuple_ext(phys_tuple); } if (RELATION_IS_GLOBAL_TEMP(relation)) { Oid newrelnode = gtt_fetch_current_relfilenode(RelationGetRelid(relation)); if (newrelnode != InvalidOid && newrelnode != relation->rd_rel->relfilenode) { relation->rd_node.relNode = newrelnode; } else { relation->rd_node.relNode = relation->rd_rel->relfilenode; } } else { relation->rd_node.relNode = relation->rd_rel->relfilenode; } } else { /* Consult the relation mapper */ relation->rd_node.relNode = RelationMapOidToFilenode(relation->rd_id, relation->rd_rel->relisshared); if (!OidIsValid(relation->rd_node.relNode)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("could not find relation mapping for relation \"%s\", OID %u", RelationGetRelationName(relation), relation->rd_id))); } relation->rd_node.bucketNode = RELATION_CREATE_BUCKET(relation) ? DIR_BUCKET_ID : InvalidBktId; } static void IndexRelationInitKeyNums(Relation relation) { int indnkeyatts; bool isnull = false; if (heap_attisnull(relation->rd_indextuple, Anum_pg_index_indnkeyatts, NULL)) { /* This scenario will only occur after the upgrade */ indnkeyatts = RelationGetNumberOfAttributes(relation); } else { Datum indkeyDatum = heap_getattr(relation->rd_indextuple, Anum_pg_index_indnkeyatts, GetPgIndexDescriptor(), &isnull); Assert(!isnull); indnkeyatts = DatumGetInt16(indkeyDatum); } relation->rd_indnkeyatts = indnkeyatts; } /* * Initialize index-access-method support data for an index relation */ void RelationInitIndexAccessInfo(Relation relation, HeapTuple index_tuple) { HeapTuple tuple; Form_pg_am aform; Datum indcollDatum; Datum indclassDatum; Datum indoptionDatum; bool isnull = false; oidvector* indcoll = NULL; oidvector* indclass = NULL; int2vector* indoption = NULL; MemoryContext indexcxt; MemoryContext oldcontext; int indnatts; int indnkeyatts; uint16 amsupport; errno_t rc; /* * Make a copy of the pg_index entry for the index. Since pg_index * contains variable-length and possibly-null fields, we have to do this * honestly rather than just treating it as a Form_pg_index struct. */ if (index_tuple != NULL) { /* hack : for timeseries query, we cached index tuple ourselves */ tuple = index_tuple; } else { tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(RelationGetRelid(relation))); } if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_CACHE_LOOKUP_FAILED), errmsg("cache lookup failed for index %u", RelationGetRelid(relation)))); oldcontext = MemoryContextSwitchTo(u_sess->cache_mem_cxt); relation->rd_indextuple = heap_copytuple(tuple); relation->rd_index = (Form_pg_index)GETSTRUCT(relation->rd_indextuple); (void)MemoryContextSwitchTo(oldcontext); if (index_tuple == NULL) { ReleaseSysCache(tuple); } /* Just Use for partitionGetRelation */ relation->rd_partHeapOid = InvalidOid; /* * Make a copy of the pg_am entry for the index's access method */ tuple = SearchSysCache1(AMOID, ObjectIdGetDatum(relation->rd_rel->relam)); if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_CACHE_LOOKUP_FAILED), errmsg("cache lookup failed for access method %u", relation->rd_rel->relam))); aform = (Form_pg_am)MemoryContextAlloc(u_sess->cache_mem_cxt, sizeof *aform); rc = memcpy_s(aform, sizeof(*aform), GETSTRUCT(tuple), sizeof(*aform)); securec_check(rc, "\0", "\0"); ReleaseSysCache(tuple); relation->rd_am = aform; indnatts = RelationGetNumberOfAttributes(relation); if (indnatts != IndexRelationGetNumberOfAttributes(relation)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("relnatts disagrees with indnatts for index %u", RelationGetRelid(relation)))); IndexRelationInitKeyNums(relation); indnkeyatts = IndexRelationGetNumberOfKeyAttributes(relation); amsupport = aform->amsupport; if (indnkeyatts > INDEX_MAX_KEYS) { ereport( ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("must index at most %u column", INDEX_MAX_KEYS))); } /* * Make the private context to hold index access info. The reason we need * a context, and not just a couple of pallocs, is so that we won't leak * any subsidiary info attached to fmgr lookup records. * * Context parameters are set on the assumption that it'll probably not * contain much data. */ indexcxt = AllocSetContextCreate(u_sess->cache_mem_cxt, RelationGetRelationName(relation), ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_SMALL_MAXSIZE); relation->rd_indexcxt = indexcxt; /* * Allocate arrays to hold data. Opclasses are not used for included * columns, so allocate them for indnkeyatts only. */ relation->rd_aminfo = (RelationAmInfo*)MemoryContextAllocZero(indexcxt, sizeof(RelationAmInfo)); relation->rd_opfamily = (Oid*)MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid)); relation->rd_opcintype = (Oid*)MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid)); if (amsupport > 0) { int nsupport = indnatts * amsupport; relation->rd_support = (RegProcedure*)MemoryContextAllocZero(indexcxt, nsupport * sizeof(RegProcedure)); relation->rd_supportinfo = (FmgrInfo*)MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo)); } else { relation->rd_support = NULL; relation->rd_supportinfo = NULL; } relation->rd_indcollation = (Oid*)MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(Oid)); relation->rd_indoption = (int16*)MemoryContextAllocZero(indexcxt, indnkeyatts * sizeof(int16)); /* * indcollation cannot be referenced directly through the C struct, * because it comes after the variable-width indkey field. Must extract * the datum the hard way... */ indcollDatum = fastgetattr(relation->rd_indextuple, Anum_pg_index_indcollation, GetPgIndexDescriptor(), &isnull); Assert(!isnull); indcoll = (oidvector*)DatumGetPointer(indcollDatum); rc = memcpy_s(relation->rd_indcollation, indnkeyatts * sizeof(Oid), indcoll->values, indnkeyatts * sizeof(Oid)); securec_check(rc, "\0", "\0"); /* * indclass cannot be referenced directly through the C struct, because it * comes after the variable-width indkey field. Must extract the datum * the hard way... */ indclassDatum = fastgetattr(relation->rd_indextuple, Anum_pg_index_indclass, GetPgIndexDescriptor(), &isnull); Assert(!isnull); indclass = (oidvector*)DatumGetPointer(indclassDatum); /* * Fill the support procedure OID array, as well as the info about * opfamilies and opclass input types. (aminfo and supportinfo are left * as zeroes, and are filled on-the-fly when used) */ IndexSupportInitialize( indclass, relation->rd_support, relation->rd_opfamily, relation->rd_opcintype, amsupport, indnkeyatts); /* * Similarly extract indoption and copy it to the cache entry */ indoptionDatum = fastgetattr(relation->rd_indextuple, Anum_pg_index_indoption, GetPgIndexDescriptor(), &isnull); Assert(!isnull); indoption = (int2vector*)DatumGetPointer(indoptionDatum); rc = memcpy_s(relation->rd_indoption, indnkeyatts * sizeof(int16), indoption->values, indnkeyatts * sizeof(int16)); securec_check(rc, "\0", "\0"); /* * expressions, predicate, exclusion caches will be filled later */ relation->rd_indexprs = NIL; relation->rd_indpred = NIL; relation->rd_exclops = NULL; relation->rd_exclprocs = NULL; relation->rd_exclstrats = NULL; relation->rd_amcache = NULL; } /* * IndexSupportInitialize * Initializes an index's cached opclass information, * given the index's pg_index.indclass entry. * * Data is returned into *indexSupport, *opFamily, and *opcInType, * which are arrays allocated by the caller. * * The caller also passes maxSupportNumber and maxAttributeNumber, since these * indicate the size of the arrays it has allocated --- but in practice these * numbers must always match those obtainable from the system catalog entries * for the index and access method. */ static void IndexSupportInitialize(oidvector* indclass, RegProcedure* indexSupport, Oid* opFamily, Oid* opcInType, StrategyNumber maxSupportNumber, AttrNumber maxAttributeNumber) { int attIndex; for (attIndex = 0; attIndex < maxAttributeNumber; attIndex++) { OpClassCacheEnt* opcentry = NULL; if (!OidIsValid(indclass->values[attIndex])) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("bogus pg_index tuple"))); /* look up the info for this opclass, using a cache */ opcentry = LookupOpclassInfo(indclass->values[attIndex], maxSupportNumber); /* copy cached data into relcache entry */ opFamily[attIndex] = opcentry->opcfamily; opcInType[attIndex] = opcentry->opcintype; if (maxSupportNumber > 0) { errno_t rc = memcpy_s(&indexSupport[attIndex * maxSupportNumber], maxSupportNumber * sizeof(RegProcedure), opcentry->supportProcs, maxSupportNumber * sizeof(RegProcedure)); securec_check(rc, "\0", "\0"); } } } /* * LookupOpclassInfo * * This routine maintains a per-opclass cache of the information needed * by IndexSupportInitialize(). This is more efficient than relying on * the catalog cache, because we can load all the info about a particular * opclass in a single indexscan of pg_amproc. * * The information from pg_am about expected range of support function * numbers is passed in, rather than being looked up, mainly because the * caller will have it already. * * Note there is no provision for flushing the cache. This is OK at the * moment because there is no way to ALTER any interesting properties of an * existing opclass --- all you can do is drop it, which will result in * a useless but harmless dead entry in the cache. To support altering * opclass membership (not the same as opfamily membership!), we'd need to * be able to flush this cache as well as the contents of relcache entries * for indexes. */ static OpClassCacheEnt* LookupOpclassInfo(Oid operatorClassOid, StrategyNumber numSupport) { OpClassCacheEnt* opcentry = NULL; bool found = false; Relation rel; SysScanDesc scan; ScanKeyData skey[3]; HeapTuple htup; bool indexOK = false; if (u_sess->relcache_cxt.OpClassCache == NULL) { /* First time through: initialize the opclass cache */ HASHCTL ctl; MemSet(&ctl, 0, sizeof(ctl)); ctl.keysize = sizeof(Oid); ctl.entrysize = sizeof(OpClassCacheEnt); ctl.hash = oid_hash; ctl.hcxt = u_sess->cache_mem_cxt; u_sess->relcache_cxt.OpClassCache = hash_create("Operator class cache", 64, &ctl, HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT); } opcentry = (OpClassCacheEnt*)hash_search(u_sess->relcache_cxt.OpClassCache, (void*)&operatorClassOid, HASH_ENTER, &found); /* * After opcentry->supportProcs palloc failed, but opcentry has been inserted * to the u_sess->relcache_cxt.OpClassCache and can not delete, so we will report PANIC. */ START_CRIT_SECTION(); if (!found) { /* Need to allocate memory for new entry */ opcentry->valid = false; /* until known OK */ opcentry->numSupport = numSupport; if (numSupport > 0) opcentry->supportProcs = (RegProcedure*)MemoryContextAllocZero(u_sess->cache_mem_cxt, numSupport * sizeof(RegProcedure)); else opcentry->supportProcs = NULL; } else { Assert(numSupport == opcentry->numSupport); } END_CRIT_SECTION(); /* * When testing for cache-flush hazards, we intentionally disable the * operator class cache and force reloading of the info on each call. This * is helpful because we want to test the case where a cache flush occurs * while we are loading the info, and it's very hard to provoke that if * this happens only once per opclass per backend. */ #if defined(CLOBBER_CACHE_ALWAYS) opcentry->valid = false; #endif if (opcentry->valid) return opcentry; /* * Need to fill in new entry. * * To avoid infinite recursion during startup, force heap scans if we're * looking up info for the opclasses used by the indexes we would like to * reference here. */ indexOK = u_sess->relcache_cxt.criticalRelcachesBuilt || (operatorClassOid != OID_BTREE_OPS_OID && operatorClassOid != INT2_BTREE_OPS_OID); /* * We have to fetch the pg_opclass row to determine its opfamily and * opcintype, which are needed to look up related operators and functions. * It'd be convenient to use the syscache here, but that probably doesn't * work while bootstrapping. */ ScanKeyInit(&skey[0], ObjectIdAttributeNumber, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(operatorClassOid)); rel = heap_open(OperatorClassRelationId, AccessShareLock); scan = systable_beginscan(rel, OpclassOidIndexId, indexOK, SnapshotNow, 1, skey); if (HeapTupleIsValid(htup = systable_getnext(scan))) { Form_pg_opclass opclassform = (Form_pg_opclass)GETSTRUCT(htup); opcentry->opcfamily = opclassform->opcfamily; opcentry->opcintype = opclassform->opcintype; } else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("could not find tuple for opclass %u", operatorClassOid))); systable_endscan(scan); heap_close(rel, AccessShareLock); /* * Scan pg_amproc to obtain support procs for the opclass. We only fetch * the default ones (those with lefttype = righttype = opcintype). */ if (numSupport > 0) { ScanKeyInit(&skey[0], Anum_pg_amproc_amprocfamily, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(opcentry->opcfamily)); ScanKeyInit(&skey[1], Anum_pg_amproc_amproclefttype, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(opcentry->opcintype)); ScanKeyInit(&skey[2], Anum_pg_amproc_amprocrighttype, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(opcentry->opcintype)); rel = heap_open(AccessMethodProcedureRelationId, AccessShareLock); scan = systable_beginscan(rel, AccessMethodProcedureIndexId, indexOK, SnapshotNow, 3, skey); while (HeapTupleIsValid(htup = systable_getnext(scan))) { Form_pg_amproc amprocform = (Form_pg_amproc)GETSTRUCT(htup); if (amprocform->amprocnum <= 0 || (StrategyNumber)amprocform->amprocnum > numSupport) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid amproc number %d for opclass %u", amprocform->amprocnum, operatorClassOid))); opcentry->supportProcs[amprocform->amprocnum - 1] = amprocform->amproc; } systable_endscan(scan); heap_close(rel, AccessShareLock); } opcentry->valid = true; return opcentry; } /* * formrdesc * * This is a special cut-down version of RelationBuildDesc(), * used while initializing the relcache. * The relation descriptor is built just from the supplied parameters, * without actually looking at any system table entries. We cheat * quite a lot since we only need to work for a few basic system * catalogs. * * formrdesc is currently used for: pg_database, pg_authid, pg_auth_members, * pg_class, pg_attribute, pg_proc, and pg_type * (see RelationCacheInitializePhase2/3). * * Note that these catalogs can't have constraints (except attnotnull), * default values, rules, or triggers, since we don't cope with any of that. * (Well, actually, this only matters for properties that need to be valid * during bootstrap or before RelationCacheInitializePhase3 runs, and none of * these properties matter then...) * * NOTE: we assume we are already switched into u_sess->cache_mem_cxt. */ static void formrdesc(const char* relationName, Oid relationReltype, bool isshared, bool hasoids, int natts, const FormData_pg_attribute* attrs) { Relation relation; int i; bool has_not_null = false; /* * allocate new relation desc, clear all fields of reldesc */ relation = (Relation)palloc0(sizeof(RelationData)); /* make sure relation is marked as having no open file yet */ relation->rd_smgr = NULL; relation->rd_bucketkey = NULL; relation->rd_bucketoid = InvalidOid; /* * initialize reference count: 1 because it is nailed in cache */ relation->rd_refcnt = 1; /* * all entries built with this routine are nailed-in-cache; none are for * new or temp relations. */ relation->rd_isnailed = true; relation->rd_createSubid = InvalidSubTransactionId; relation->rd_newRelfilenodeSubid = InvalidSubTransactionId; relation->rd_backend = InvalidBackendId; relation->rd_islocaltemp = false; /* * initialize relation tuple form * * The data we insert here is pretty incomplete/bogus, but it'll serve to * get us launched. RelationCacheInitializePhase3() will read the real * data from pg_class and replace what we've done here. Note in * particular that relowner is left as zero; this cues * RelationCacheInitializePhase3 that the real data isn't there yet. */ relation->rd_rel = (Form_pg_class)palloc0(sizeof(FormData_pg_class)); namestrcpy(&relation->rd_rel->relname, relationName); relation->rd_rel->relnamespace = PG_CATALOG_NAMESPACE; relation->rd_rel->reltype = relationReltype; /* * It's important to distinguish between shared and non-shared relations, * even at bootstrap time, to make sure we know where they are stored. */ relation->rd_rel->relisshared = isshared; ereport(DEBUG1, (errmsg("relation->rd_rel->relisshared %d", relation->rd_rel->relisshared))); if (isshared) relation->rd_rel->reltablespace = GLOBALTABLESPACE_OID; /* formrdesc is used only for permanent relations */ relation->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT; relation->rd_rel->relpages = 0; relation->rd_rel->reltuples = 0; relation->rd_rel->relallvisible = 0; relation->rd_rel->relkind = RELKIND_RELATION; relation->rd_rel->relhasoids = hasoids; relation->rd_rel->relnatts = (int16)natts; /* * initialize attribute tuple form * * Unlike the case with the relation tuple, this data had better be right * because it will never be replaced. The data comes from * src/include/catalog/ headers via genbki.pl. */ /* * Below Catalog tables are heap table type. pg_database, pg_authid, pg_auth_members, pg_class, pg_attribute, pg_proc, and pg_type */ relation->rd_att = CreateTemplateTupleDesc(natts, hasoids, TAM_HEAP); relation->rd_tam_type = TAM_HEAP; relation->rd_att->tdrefcount = 1; /* mark as refcounted */ relation->rd_att->tdtypeid = relationReltype; relation->rd_att->tdtypmod = -1; /* unnecessary, but... */ /* * initialize tuple desc info */ has_not_null = false; for (i = 0; i < natts; i++) { MemCpy(relation->rd_att->attrs[i], &attrs[i], ATTRIBUTE_FIXED_PART_SIZE); has_not_null = has_not_null || attrs[i].attnotnull; /* make sure attcacheoff is valid */ relation->rd_att->attrs[i]->attcacheoff = -1; } /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */ relation->rd_att->attrs[0]->attcacheoff = 0; /* mark not-null status */ if (has_not_null) { TupleConstr* constr = (TupleConstr*)palloc0(sizeof(TupleConstr)); constr->has_not_null = true; relation->rd_att->constr = constr; } /* * initialize relation id from info in att array (my, this is ugly) */ RelationGetRelid(relation) = relation->rd_att->attrs[0]->attrelid; /* * All relations made with formrdesc are mapped. This is necessarily so * because there is no other way to know what filenode they currently * have. In bootstrap mode, add them to the initial relation mapper data, * specifying that the initial filenode is the same as the OID. */ relation->rd_rel->relfilenode = InvalidOid; if (IsBootstrapProcessingMode()) RelationMapUpdateMap(RelationGetRelid(relation), RelationGetRelid(relation), isshared, true); /* * initialize the relation lock manager information */ RelationInitLockInfo(relation); /* see lmgr.c */ /* * initialize physical addressing information for the relation */ RelationInitPhysicalAddr(relation); relation->rd_isscannable = true; /* * initialize the rel-has-index flag, using hardwired knowledge */ if (IsBootstrapProcessingMode()) { /* In bootstrap mode, we have no indexes */ relation->rd_rel->relhasindex = false; } else { /* Otherwise, all the rels formrdesc is used for have indexes */ relation->rd_rel->relhasindex = true; } /* * add new reldesc to relcache */ RelationCacheInsert(relation); /* It's fully valid */ relation->rd_isvalid = true; } /* ---------------------------------------------------------------- * Relation Descriptor Lookup Interface * ---------------------------------------------------------------- */ /* * RelationIdGetRelation * * Lookup a reldesc by OID; make one if not already in cache. * * Returns NULL if no pg_class row could be found for the given relid * (suggesting we are trying to access a just-deleted relation). * Any other error is reported via elog. * * NB: caller should already have at least AccessShareLock on the * relation ID, else there are nasty race conditions. * * NB: relation ref count is incremented, or set to 1 if new entry. * Caller should eventually decrement count. (Usually, * that happens by calling RelationClose().) */ Relation RelationIdGetRelation(Oid relationId) { Relation rd; /* * first try to find reldesc in the cache */ RelationIdCacheLookup(relationId, rd); if (RelationIsValid(rd)) { RelationIncrementReferenceCount(rd); /* revalidate cache entry if necessary */ if (!rd->rd_isvalid) { /* * Indexes only have a limited number of possible schema changes, * and we don't want to use the full-blown procedure because it's * a headache for indexes that reload itself depends on. */ if (RelationIsIndex(rd)) RelationReloadIndexInfo(rd); else RelationClearRelation(rd, true); } /* * In some cases, after the relcache is built, the temp table's node group is dropped * because of cluster resizeing, so we should do checking when get the rel directly from * relcache. */ if (rd->rd_rel->relpersistence == RELPERSISTENCE_TEMP) (void)checkGroup(relationId, RELATION_IS_OTHER_TEMP(rd)); return rd; } /* * no reldesc in the cache, so have RelationBuildDesc() build one and add * it. */ rd = RelationBuildDesc(relationId, true); if (RelationIsValid(rd)) RelationIncrementReferenceCount(rd); return rd; } /* ---------------------------------------------------------------- * cache invalidation support routines * ---------------------------------------------------------------- */ /* * RelationIncrementReferenceCount * Increments relation reference count. * * Note: bootstrap mode has its own weird ideas about relation refcount * behavior; we ought to fix it someday, but for now, just disable * reference count ownership tracking in bootstrap mode. */ void RelationIncrementReferenceCount(Relation rel) { /* The partition as a relation should be added to fakerelrefs rather than relrefs. */ if (RelationIsPartition(rel) || RelationIsBucket(rel)) { return; } ResourceOwnerEnlargeRelationRefs(t_thrd.utils_cxt.CurrentResourceOwner); rel->rd_refcnt += 1; if (!IsBootstrapProcessingMode()) ResourceOwnerRememberRelationRef(t_thrd.utils_cxt.CurrentResourceOwner, rel); } /* * RelationDecrementReferenceCount * Decrements relation reference count. */ void RelationDecrementReferenceCount(Relation rel) { /* The partition as a relation should be added to fakerelrefs rather than relrefs. */ if (RelationIsPartition(rel) || RelationIsBucket(rel)) { return; } Assert(rel->rd_refcnt > 0); rel->rd_refcnt -= 1; if (!IsBootstrapProcessingMode()) ResourceOwnerForgetRelationRef(t_thrd.utils_cxt.CurrentResourceOwner, rel); } void RelationIncrementReferenceCount(Oid relationId) { RelationIdGetRelation(relationId); } void RelationDecrementReferenceCount(Oid relationId) { Relation rd; RelationIdCacheLookup(relationId, rd); if (RelationIsValid(rd)) { RelationDecrementReferenceCount(rd); } } /* * RelationClose - close an open relation * * Actually, we just decrement the refcount. * * NOTE: if compiled with -DRELCACHE_FORCE_RELEASE then relcache entries * will be freed as soon as their refcount goes to zero. In combination * with aset.c's CLOBBER_FREED_MEMORY option, this provides a good test * to catch references to already-released relcache entries. It slows * things down quite a bit, however. */ void RelationClose(Relation relation) { /* Note: no locking manipulations needed */ RelationDecrementReferenceCount(relation); #ifdef RELCACHE_FORCE_RELEASE if (RelationHasReferenceCountZero(relation) && relation->rd_createSubid == InvalidSubTransactionId && relation->rd_newRelfilenodeSubid == InvalidSubTransactionId) RelationClearRelation(relation, false); #endif } /* * RelationReloadIndexInfo - reload minimal information for an open index * * This function is used only for indexes. A relcache inval on an index * can mean that its pg_class or pg_index row changed. There are only * very limited changes that are allowed to an existing index's schema, * so we can update the relcache entry without a complete rebuild; which * is fortunate because we can't rebuild an index entry that is "nailed" * and/or in active use. We support full replacement of the pg_class row, * as well as updates of a few simple fields of the pg_index row. * * We can't necessarily reread the catalog rows right away; we might be * in a failed transaction when we receive the SI notification. If so, * RelationClearRelation just marks the entry as invalid by setting * rd_isvalid to false. This routine is called to fix the entry when it * is next needed. * * We assume that at the time we are called, we have at least AccessShareLock * on the target index. (Note: in the calls from RelationClearRelation, * this is legitimate because we know the rel has positive refcount.) * * If the target index is an index on pg_class or pg_index, we'd better have * previously gotten at least AccessShareLock on its underlying catalog, * else we are at risk of deadlock against someone trying to exclusive-lock * the heap and index in that order. This is ensured in current usage by * only applying this to indexes being opened or having positive refcount. */ static void RelationReloadIndexInfo(Relation relation) { bool indexOK = false; HeapTuple pg_class_tuple; Form_pg_class relp; /* Should be called only for invalidated indexes */ Assert(RelationIsIndex(relation) && !relation->rd_isvalid); /* Should be closed at smgr level */ Assert(relation->rd_smgr == NULL); /* Must free any AM cached data upon relcache flush */ if (relation->rd_amcache) pfree_ext(relation->rd_amcache); relation->rd_amcache = NULL; /* * If it's a shared index, we might be called before backend startup has * finished selecting a database, in which case we have no way to read * pg_class yet. However, a shared index can never have any significant * schema updates, so it's okay to ignore the invalidation signal. Just * mark it valid and return without doing anything more. */ ereport(DEBUG1, (errmsg("relation->rd_rel->relisshared-%d criticalRelcachesBuilt-%d", relation->rd_rel->relisshared, u_sess->relcache_cxt.criticalRelcachesBuilt))); if (relation->rd_rel->relisshared && !u_sess->relcache_cxt.criticalRelcachesBuilt) { relation->rd_isvalid = true; return; } /* * Read the pg_class row * * Don't try to use an indexscan of pg_class_oid_index to reload the info * for pg_class_oid_index ... */ indexOK = (RelationGetRelid(relation) != ClassOidIndexId); pg_class_tuple = ScanPgRelation(RelationGetRelid(relation), indexOK, false); if (!HeapTupleIsValid(pg_class_tuple)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("could not find pg_class tuple for index %u", RelationGetRelid(relation)))); relp = (Form_pg_class)GETSTRUCT(pg_class_tuple); MemCpy(relation->rd_rel, relp, CLASS_TUPLE_SIZE); /* Reload reloptions in case they changed */ if (relation->rd_options) pfree_ext(relation->rd_options); RelationParseRelOptions(relation, pg_class_tuple); /* fetch bucket info from pgclass tuple */ RelationInitBucketInfo(relation, pg_class_tuple); /* We must recalculate physical address in case it changed */ RelationInitPhysicalAddr(relation); relation->rd_isscannable = true; /* done with pg_class tuple */ heap_freetuple_ext(pg_class_tuple); /* * For a non-system index, there are fields of the pg_index row that are * allowed to change, so re-read that row and update the relcache entry. * Most of the info derived from pg_index (such as support function lookup * info) cannot change, and indeed the whole point of this routine is to * update the relcache entry without clobbering that data; so wholesale * replacement is not appropriate. */ if (!IsSystemRelation(relation)) { HeapTuple tuple; Form_pg_index index; tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(RelationGetRelid(relation))); if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_CACHE_LOOKUP_FAILED), errmsg("cache lookup failed for index %u", RelationGetRelid(relation)))); index = (Form_pg_index)GETSTRUCT(tuple); /* * Basically, let's just copy all the bool fields. There are one or * two of these that can't actually change in the current code, but * it's not worth it to track exactly which ones they are. None of * the array fields are allowed to change, though. */ relation->rd_index->indisunique = index->indisunique; relation->rd_index->indisprimary = index->indisprimary; relation->rd_index->indisexclusion = index->indisexclusion; relation->rd_index->indimmediate = index->indimmediate; relation->rd_index->indisclustered = index->indisclustered; relation->rd_index->indisvalid = index->indisvalid; relation->rd_index->indcheckxmin = index->indcheckxmin; relation->rd_index->indisready = index->indisready; /* Copy xmin too, as that is needed to make sense of indcheckxmin */ HeapTupleCopyBase(relation->rd_indextuple, tuple); HeapTupleSetXmin(relation->rd_indextuple, HeapTupleGetRawXmin(tuple)); ReleaseSysCache(tuple); gtt_fix_index_state(relation); } /* Okay, now it's valid again */ relation->rd_isvalid = true; } /* * @@GaussDB@@ * Target : data partition * Brief : * Description : * Notes : */ static void partitionMapDestroyRangeArray(RangeElement* rangeArray, int arrLen) { int i, j; RangeElement* range = NULL; Const* maxConst = NULL; if (NULL == rangeArray || arrLen < 1) { return; } /*before free range array, free max array in each rangeElement*/ for (i = 0; i < arrLen; i++) { range = &(rangeArray[i]); for (j = 0; j < range->len; j++) { maxConst = range->boundary[j]; if (PointerIsValid(maxConst)) { if (!maxConst->constbyval && !maxConst->constisnull && PointerIsValid(DatumGetPointer(maxConst->constvalue))) { pfree(DatumGetPointer(maxConst->constvalue)); } pfree_ext(maxConst); maxConst = NULL; } } } /*free range array*/ pfree_ext(rangeArray); } static void PartitionMapDestroyHashArray(HashPartElement* hashArray, int arrLen) { int i; HashPartElement* hashValues = NULL; Const* value = NULL; if (NULL == hashArray || arrLen < 1) { return; } /*before free range array, free max array in each rangeElement*/ for (i = 0; i < arrLen; i++) { hashValues = &(hashArray[i]); value = hashValues->boundary[0]; if (PointerIsValid(value)) { if (!value->constbyval && !value->constisnull && PointerIsValid(DatumGetPointer(value->constvalue))) { pfree(DatumGetPointer(value->constvalue)); } pfree_ext(value); value = NULL; } } pfree_ext(hashArray); } /* * @@GaussDB@@ * Target : data partition * Brief : * Description : * Notes : */ static void RelationDestroyPartitionMap(Relation relation) { /*already a non-partitioned relation, just return*/ if (!relation->partMap) return; /*partitioned relation, destroy the partition map*/ if (relation->partMap->type == PART_TYPE_RANGE || relation->partMap->type == PART_TYPE_INTERVAL) { RangePartitionMap* range_map = ((RangePartitionMap*)(relation->partMap)); /*first free partKeyNum/partitionKeyDataType/ranges in the range map*/ if (range_map->partitionKey) { pfree_ext(range_map->partitionKey); } if (range_map->partitionKeyDataType) { pfree_ext(range_map->partitionKeyDataType); } if (range_map->intervalValue) { pfree_ext(range_map->intervalValue); } if (range_map->intervalTablespace) { pfree_ext(range_map->intervalTablespace); } if (range_map->rangeElements) { partitionMapDestroyRangeArray(range_map->rangeElements, range_map->rangeElementsNum); } } else if (relation->partMap->type == PART_TYPE_LIST) { ListPartitionMap* list_map = (ListPartitionMap*)(relation->partMap); if (list_map->partitionKey) { pfree_ext(list_map->partitionKey); list_map->partitionKey = NULL; } if (list_map->partitionKeyDataType) { pfree_ext(list_map->partitionKeyDataType); list_map->partitionKeyDataType = NULL; } if (list_map->listElements) { DestroyListElements(list_map->listElements, list_map->listElementsNum); list_map->listElements = NULL; } } else if (relation->partMap->type == PART_TYPE_HASH) { HashPartitionMap* hash_map = (HashPartitionMap*)(relation->partMap); if (hash_map->partitionKey) { pfree_ext(hash_map->partitionKey); hash_map->partitionKey = NULL; } if (hash_map->partitionKeyDataType) { pfree_ext(hash_map->partitionKeyDataType); hash_map->partitionKeyDataType = NULL; } if (hash_map->hashElements) { PartitionMapDestroyHashArray(hash_map->hashElements, hash_map->hashElementsNum); hash_map->hashElements = NULL; } } pfree_ext(relation->partMap); return; } static void RelationDestroySliceMap(Relation relation) { RangePartitionMap* range_map = (RangePartitionMap*)(relation->sliceMap); pfree_ext(range_map->partitionKey); pfree_ext(range_map->partitionKeyDataType); pfree_ext(range_map->intervalValue); pfree_ext(range_map->intervalTablespace); partitionMapDestroyRangeArray(range_map->rangeElements, range_map->rangeElementsNum); pfree_ext(relation->sliceMap); return; } /* * RelationDestroyRelation * * Physically delete a relation cache entry and all subsidiary data. * Caller must already have unhooked the entry from the hash table. */ static void RelationDestroyRelation(Relation relation, bool remember_tupdesc) { Assert(RelationHasReferenceCountZero(relation)); /* * Make sure smgr and lower levels close the relation's files, if they * weren't closed already. (This was probably done by caller, but let's * just be real sure.) */ RelationCloseSmgr(relation); /* * Free all the subsidiary data structures of the relcache entry, then the * entry itself. */ if (relation->rd_rel) pfree_ext(relation->rd_rel); /* can't use DecrTupleDescRefCount here */ Assert(relation->rd_att->tdrefcount > 0); if (--relation->rd_att->tdrefcount == 0) { /* * If we Rebuilt a relcache entry during a transaction then its * possible we did that because the TupDesc changed as the result * of an ALTER TABLE that ran at less than AccessExclusiveLock. * It's possible someone copied that TupDesc, in which case the * copy would point to free'd memory. So if we rebuild an entry * we keep the TupDesc around until end of transaction, to be safe. */ if (remember_tupdesc) { RememberToFreeTupleDescAtEOX(relation->rd_att); } else { FreeTupleDesc(relation->rd_att); } } list_free_ext(relation->rd_indexlist); bms_free_ext(relation->rd_indexattr); bms_free_ext(relation->rd_idattr); FreeTriggerDesc(relation->trigdesc); if (relation->rd_rlsdesc) { MemoryContextDelete(relation->rd_rlsdesc->rlsCxt); relation->rd_rlsdesc = NULL; } if (relation->rd_options) pfree_ext(relation->rd_options); if (relation->rd_indextuple) pfree_ext(relation->rd_indextuple); if (relation->rd_am) pfree_ext(relation->rd_am); if (relation->rd_indexcxt) MemoryContextDelete(relation->rd_indexcxt); if (relation->rd_rulescxt) MemoryContextDelete(relation->rd_rulescxt); if (relation->rd_fdwroutine) pfree_ext(relation->rd_fdwroutine); if (relation->partMap) { RelationDestroyPartitionMap(relation); } if (REALTION_BUCKETKEY_VALID(relation)) { pfree_ext(relation->rd_bucketkey->bucketKey); pfree_ext(relation->rd_bucketkey->bucketKeyType); pfree_ext(relation->rd_bucketkey); } if (relation->rd_locator_info) { FreeRelationLocInfo(relation->rd_locator_info); } if (relation->sliceMap != NULL) { RelationDestroySliceMap(relation); } pfree_ext(relation); } /* * RelationClearRelation * * Physically blow away a relation cache entry, or reset it and rebuild * it from scratch (that is, from catalog entries). The latter path is * used when we are notified of a change to an open relation (one with * refcount > 0). * * NB: when rebuilding, we'd better hold some lock on the relation, * else the catalog data we need to read could be changing under us. * Also, a rel to be rebuilt had better have refcnt > 0. This is because * an sinval reset could happen while we're accessing the catalogs, and * the rel would get blown away underneath us by RelationCacheInvalidate * if it has zero refcnt. * * The "rebuild" parameter is redundant in current usage because it has * to match the relation's refcnt status, but we keep it as a crosscheck * that we're doing what the caller expects. */ static void RelationClearRelation(Relation relation, bool rebuild) { /* * As per notes above, a rel to be rebuilt MUST have refcnt > 0; while of * course it would be an equally bad idea to blow away one with nonzero * refcnt, since that would leave someone somewhere with a dangling * pointer. All callers are expected to have verified that this holds. */ Assert(rebuild ? !RelationHasReferenceCountZero(relation) : RelationHasReferenceCountZero(relation)); /*if relation is transformed from partitionGetRelation(), it is freed by releaseDummyRelation(), * not by RelationClearRelation(), so we can add a assertion here */ Assert(!RelationIsPartition(relation)); /* * Make sure smgr and lower levels close the relation's files, if they * weren't closed already. If the relation is not getting deleted, the * next smgr access should reopen the files automatically. This ensures * that the low-level file access state is updated after, say, a vacuum * truncation. */ RelationCloseSmgr(relation); /* * Never, never ever blow away a nailed-in system relation, because we'd * be unable to recover. However, we must redo RelationInitPhysicalAddr * in case it is a mapped relation whose mapping changed. * * If it's a nailed index, then we need to re-read the pg_class row to see * if its relfilenode changed. We can't necessarily do that here, because * we might be in a failed transaction. We assume it's okay to do it if * there are open references to the relcache entry (cf notes for * AtEOXact_RelationCache). Otherwise just mark the entry as possibly * invalid, and it'll be fixed when next opened. */ if (relation->rd_isnailed) { RelationInitPhysicalAddr(relation); if (relation->rd_rel->relkind == RELKIND_MATVIEW && heap_is_matview_init_state(relation)) relation->rd_isscannable = false; else relation->rd_isscannable = true; if (RelationIsIndex(relation)) { relation->rd_isvalid = false; /* needs to be revalidated */ if (relation->rd_refcnt > 1) RelationReloadIndexInfo(relation); } return; } /* * Even non-system indexes should not be blown away if they are open and * have valid index support information. This avoids problems with active * use of the index support information. As with nailed indexes, we * re-read the pg_class row to handle possible physical relocation of the * index, and we check for pg_index updates too. */ if (RelationIsIndex(relation) && relation->rd_refcnt > 0 && relation->rd_indexcxt != NULL) { relation->rd_isvalid = false; /* needs to be revalidated */ RelationReloadIndexInfo(relation); return; } if (IsInitProcessingMode() && relation->rd_att->constr != NULL && relation->rd_att->constr->num_defval != 0 && relation->rd_att->constr->defval == NULL) relation->rd_att->constr->num_defval = 0; /* Mark it invalid until we've finished rebuild */ relation->rd_isvalid = false; /* * If we're really done with the relcache entry, blow it away. But if * someone is still using it, reconstruct the whole deal without moving * the physical RelationData record (so that the someone's pointer is * still valid). */ if (!rebuild) { /* Remove it from the hash table */ RelationCacheDelete(relation); /* And release storage */ RelationDestroyRelation(relation, false); } else { /* * Our strategy for rebuilding an open relcache entry is to build a * new entry from scratch, swap its contents with the old entry, and * finally delete the new entry (along with any infrastructure swapped * over from the old entry). This is to avoid trouble in case an * error causes us to lose control partway through. The old entry * will still be marked !rd_isvalid, so we'll try to rebuild it again * on next access. Meanwhile it's not any less valid than it was * before, so any code that might expect to continue accessing it * isn't hurt by the rebuild failure. (Consider for example a * subtransaction that ALTERs a table and then gets canceled partway * through the cache entry rebuild. The outer transaction should * still see the not-modified cache entry as valid.) The worst * consequence of an error is leaking the necessarily-unreferenced new * entry, and this shouldn't happen often enough for that to be a big * problem. * * When rebuilding an open relcache entry, we must preserve ref count, * rd_createSubid/rd_newRelfilenodeSubid, and rd_toastoid state. Also * attempt to preserve the pg_class entry (rd_rel), tupledesc, and * rewrite-rule substructures in place, because various places assume * that these structures won't move while they are working with an * open relcache entry. (Note: the refcount mechanism for tupledescs * might someday allow us to remove this hack for the tupledesc.) * * Note that this process does not touch CurrentResourceOwner; which * is good because whatever ref counts the entry may have do not * necessarily belong to that resource owner. */ Relation newrel; Oid save_relid = RelationGetRelid(relation); bool keep_tupdesc = false; bool keep_rules = false; bool buildkey = !REALTION_BUCKETKEY_INITED(relation); /* Build temporary entry, but don't link it into hashtable */ newrel = RelationBuildDesc(save_relid, false, buildkey); if (newrel == NULL) { /* * We can validly get here, if we're using a historic snapshot in * which a relation, accessed from outside logical decoding, is * still invisible. In that case it's fine to just mark the * relation as invalid and return - it'll fully get reloaded by * the cache reset at the end of logical decoding (or at the next * access). During normal processing we don't want to ignore this * case as it shouldn't happen there, as explained below. */ if (HistoricSnapshotActive()) return; /* * This shouldn't happen as dropping a relation is intended to be * impossible if still referenced (c.f. CheckTableNotInUse()). But * if we get here anyway, we can't just delete the relcache entry, * as it possibly could get accessed later (as e.g. the error * might get trapped and handled via a subtransaction rollback). */ ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("relation %u deleted while still in use", save_relid))); } newrel->rd_isnailed = relation->rd_isnailed; keep_tupdesc = equalTupleDescs(relation->rd_att, newrel->rd_att); keep_rules = equalRuleLocks(relation->rd_rules, newrel->rd_rules); /* * Perform swapping of the relcache entry contents. Within this * process the old entry is momentarily invalid, so there *must* be no * possibility of CHECK_FOR_INTERRUPTS within this sequence. Do it in * all-in-line code for safety. * * Since the vast majority of fields should be swapped, our method is * to swap the whole structures and then re-swap those few fields we * didn't want swapped. */ #define SWAPFIELD(fldtype, fldname) \ do { \ fldtype _tmp = newrel->fldname; \ newrel->fldname = relation->fldname; \ relation->fldname = _tmp; \ } while (0) /* swap all Relation struct fields */ { RelationData tmpstruct; MemCpy(&tmpstruct, newrel, sizeof(RelationData)); MemCpy(newrel, relation, sizeof(RelationData)); MemCpy(relation, &tmpstruct, sizeof(RelationData)); } /* rd_smgr must not be swapped, due to back-links from smgr level */ SWAPFIELD(SMgrRelation, rd_smgr); /* rd_refcnt must be preserved */ SWAPFIELD(int, rd_refcnt); /* isnailed shouldn't change */ Assert(newrel->rd_isnailed == relation->rd_isnailed); /* creation sub-XIDs must be preserved */ SWAPFIELD(SubTransactionId, rd_createSubid); SWAPFIELD(SubTransactionId, rd_newRelfilenodeSubid); /* un-swap rd_rel pointers, swap contents instead */ SWAPFIELD(Form_pg_class, rd_rel); /* ... but actually, we don't have to update newrel->rd_rel */ MemCpy(relation->rd_rel, newrel->rd_rel, CLASS_TUPLE_SIZE); if (newrel->partMap) { RebuildPartitonMap(newrel->partMap, relation->partMap); SWAPFIELD(PartitionMap*, partMap); } if (!buildkey) { /* no need to rebuild bucket key info, so just preserve it */ SWAPFIELD(RelationBucketKey*, rd_bucketkey); } else { /* no need to free rd_bucketkey from relation */ newrel->rd_bucketkey = NULL; } /* preserve old tupledesc and rules if no logical change */ if (keep_tupdesc) SWAPFIELD(TupleDesc, rd_att); if (keep_rules) { SWAPFIELD(RuleLock*, rd_rules); SWAPFIELD(MemoryContext, rd_rulescxt); } /* toast OID override must be preserved */ SWAPFIELD(Oid, rd_toastoid); /* pgstat_info must be preserved */ SWAPFIELD(struct PgStat_TableStatus*, pgstat_info); /* mlog OID override must be preserved */ SWAPFIELD(Oid, rd_mlogoid); #undef SWAPFIELD /* And now we can throw away the temporary entry */ RelationDestroyRelation(newrel, !keep_tupdesc); } } /* * RelationFlushRelation * * Rebuild the relation if it is open (refcount > 0), else blow it away. */ static void RelationFlushRelation(Relation relation) { if (relation->rd_createSubid != InvalidSubTransactionId || relation->rd_newRelfilenodeSubid != InvalidSubTransactionId) { /* * New relcache entries are always rebuilt, not flushed; else we'd * forget the "new" status of the relation, which is a useful * optimization to have. Ditto for the new-relfilenode status. * * The rel could have zero refcnt here, so temporarily increment the * refcnt to ensure it's safe to rebuild it. We can assume that the * current transaction has some lock on the rel already. */ RelationIncrementReferenceCount(relation); RelationClearRelation(relation, true); RelationDecrementReferenceCount(relation); } else { /* * Pre-existing rels can be dropped from the relcache if not open. */ bool rebuild = !RelationHasReferenceCountZero(relation); RelationClearRelation(relation, rebuild); } } /* * RelationForgetRelation - unconditionally remove a relcache entry * * External interface for destroying a relcache entry when we * drop the relation. */ void RelationForgetRelation(Oid rid) { Relation relation; RelationIdCacheLookup(rid, relation); if (!PointerIsValid(relation)) return; /* not in cache, nothing to do */ if (!RelationHasReferenceCountZero(relation)) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("relation %u is still open", rid))); /* Unconditionally destroy the relcache entry */ RelationClearRelation(relation, false); } /* * RelationCacheInvalidateEntry * * This routine is invoked for SI cache flush messages. * * Any relcache entry matching the relid must be flushed. (Note: caller has * already determined that the relid belongs to our database or is a shared * relation.) * * We used to skip local relations, on the grounds that they could * not be targets of cross-backend SI update messages; but it seems * safer to process them, so that our *own* SI update messages will * have the same effects during CommandCounterIncrement for both * local and nonlocal relations. */ void RelationCacheInvalidateEntry(Oid relationId) { Relation relation; RelationIdCacheLookup(relationId, relation); if (PointerIsValid(relation)) { u_sess->relcache_cxt.relcacheInvalsReceived++; RelationFlushRelation(relation); } } /* * RelationCacheInvalidate * Blow away cached relation descriptors that have zero reference counts, * and rebuild those with positive reference counts. Also reset the smgr * relation cache and re-read relation mapping data. * * This is currently used only to recover from SI message buffer overflow, * so we do not touch new-in-transaction relations; they cannot be targets * of cross-backend SI updates (and our own updates now go through a * separate linked list that isn't limited by the SI message buffer size). * Likewise, we need not discard new-relfilenode-in-transaction hints, * since any invalidation of those would be a local event. * * We do this in two phases: the first pass deletes deletable items, and * the second one rebuilds the rebuildable items. This is essential for * safety, because hash_seq_search only copes with concurrent deletion of * the element it is currently visiting. If a second SI overflow were to * occur while we are walking the table, resulting in recursive entry to * this routine, we could crash because the inner invocation blows away * the entry next to be visited by the outer scan. But this way is OK, * because (a) during the first pass we won't process any more SI messages, * so hash_seq_search will complete safely; (b) during the second pass we * only hold onto pointers to nondeletable entries. * * The two-phase approach also makes it easy to update relfilenodes for * mapped relations before we do anything else, and to ensure that the * second pass processes nailed-in-cache items before other nondeletable * items. This should ensure that system catalogs are up to date before * we attempt to use them to reload information about other open relations. */ void RelationCacheInvalidate(void) { HASH_SEQ_STATUS status; RelIdCacheEnt* idhentry = NULL; Relation relation; List* rebuildFirstList = NIL; List* rebuildList = NIL; ListCell* l = NULL; /* * Reload relation mapping data before starting to reconstruct cache. */ RelationMapInvalidateAll(); /* Phase 1 */ hash_seq_init(&status, u_sess->relcache_cxt.RelationIdCache); while ((idhentry = (RelIdCacheEnt*)hash_seq_search(&status)) != NULL) { relation = idhentry->reldesc; /* Must close all smgr references to avoid leaving dangling ptrs */ RelationCloseSmgr(relation); /* Ignore new relations, since they are never cross-backend targets */ if (relation->rd_createSubid != InvalidSubTransactionId) continue; u_sess->relcache_cxt.relcacheInvalsReceived++; if (RelationHasReferenceCountZero(relation)) { /* Delete this entry immediately */ Assert(!relation->rd_isnailed); RelationClearRelation(relation, false); } else { /* * If it's a mapped relation, immediately update its rd_node in * case its relfilenode changed. We must do this during phase 1 * in case the relation is consulted during rebuild of other * relcache entries in phase 2. It's safe since consulting the * map doesn't involve any access to relcache entries. */ if (RelationIsMapped(relation)) RelationInitPhysicalAddr(relation); /* * Add this entry to list of stuff to rebuild in second pass. * pg_class goes to the front of rebuildFirstList while * pg_class_oid_index goes to the back of rebuildFirstList, so * they are done first and second respectively. Other nailed * relations go to the front of rebuildList, so they'll be done * next in no particular order; and everything else goes to the * back of rebuildList. */ if (RelationGetRelid(relation) == RelationRelationId) rebuildFirstList = lcons(relation, rebuildFirstList); else if (RelationGetRelid(relation) == ClassOidIndexId) rebuildFirstList = lappend(rebuildFirstList, relation); else if (relation->rd_isnailed) rebuildList = lcons(relation, rebuildList); else rebuildList = lappend(rebuildList, relation); } } /* * Now zap any remaining smgr cache entries. This must happen before we * start to rebuild entries, since that may involve catalog fetches which * will re-open catalog files. */ smgrcloseall(); /* Phase 2: rebuild the items found to need rebuild in phase 1 */ foreach (l, rebuildFirstList) { relation = (Relation)lfirst(l); RelationClearRelation(relation, true); } list_free_ext(rebuildFirstList); foreach (l, rebuildList) { relation = (Relation)lfirst(l); RelationClearRelation(relation, true); } list_free_ext(rebuildList); } /* * RelationCacheInvalidateBuckets * Invalidate bucket_ptr in all relcache entries. * * Need to invalidate bucket_ptr after modify node group. */ void RelationCacheInvalidateBuckets(void) { HASH_SEQ_STATUS status; RelIdCacheEnt* idhentry = NULL; Relation relation; hash_seq_init(&status, u_sess->relcache_cxt.RelationIdCache); while ((idhentry = (RelIdCacheEnt*)hash_seq_search(&status)) != NULL) { relation = idhentry->reldesc; if (relation->rd_locator_info != NULL) { InvalidateBuckets(relation->rd_locator_info); } } } /* * RelationCloseSmgrByOid - close a relcache entry's smgr link * * Needed in some cases where we are changing a relation's physical mapping. * The link will be automatically reopened on next use. */ void RelationCloseSmgrByOid(Oid relationId) { Relation relation; RelationIdCacheLookup(relationId, relation); if (!PointerIsValid(relation)) return; /* not in cache, nothing to do */ RelationCloseSmgr(relation); } Oid RelationGetBucketOid(Relation relation) { return relation->rd_bucketoid; } /* Remember old tupleDescs when processing invalid messages */ void RememberToFreeTupleDescAtEOX(TupleDesc td) { if (u_sess->relcache_cxt.EOXactTupleDescArray == NULL) { MemoryContext oldcxt = NULL; oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); u_sess->relcache_cxt.EOXactTupleDescArray = (TupleDesc *) palloc(16 * sizeof(TupleDesc)); u_sess->relcache_cxt.EOXactTupleDescArrayLen = 16; u_sess->relcache_cxt.NextEOXactTupleDescNum = 0; MemoryContextSwitchTo(oldcxt); } else if (u_sess->relcache_cxt.NextEOXactTupleDescNum >= u_sess->relcache_cxt.EOXactTupleDescArrayLen) { int32 newlen = u_sess->relcache_cxt.EOXactTupleDescArrayLen * 2; Assert(u_sess->relcache_cxt.EOXactTupleDescArrayLen > 0); u_sess->relcache_cxt.EOXactTupleDescArray = (TupleDesc *) repalloc(u_sess->relcache_cxt.EOXactTupleDescArray, newlen * sizeof(TupleDesc)); u_sess->relcache_cxt.EOXactTupleDescArrayLen = newlen; } u_sess->relcache_cxt.EOXactTupleDescArray[u_sess->relcache_cxt.NextEOXactTupleDescNum++] = td; } /* Free all tupleDescs remembered in RememberToFreeTupleDescAtEOX in a batch when a transaction ends */ void AtEOXact_FreeTupleDesc() { if (u_sess->relcache_cxt.EOXactTupleDescArrayLen > 0) { Assert(u_sess->relcache_cxt.EOXactTupleDescArray != NULL); int i; for (i = 0; i < u_sess->relcache_cxt.NextEOXactTupleDescNum; i++) FreeTupleDesc(u_sess->relcache_cxt.EOXactTupleDescArray[i]); pfree(u_sess->relcache_cxt.EOXactTupleDescArray); u_sess->relcache_cxt.EOXactTupleDescArray = NULL; } u_sess->relcache_cxt.NextEOXactTupleDescNum = 0; u_sess->relcache_cxt.EOXactTupleDescArrayLen = 0; } /* * AtEOXact_RelationCache * * Clean up the relcache at main-transaction commit or abort. * * Note: this must be called *before* processing invalidation messages. * In the case of abort, we don't want to try to rebuild any invalidated * cache entries (since we can't safely do database accesses). Therefore * we must reset refcnts before handling pending invalidations. * * As of PostgreSQL 8.1, relcache refcnts should get released by the * ResourceOwner mechanism. This routine just does a debugging * cross-check that no pins remain. However, we also need to do special * cleanup when the current transaction created any relations or made use * of forced index lists. */ void AtEOXact_RelationCache(bool isCommit) { HASH_SEQ_STATUS status; RelIdCacheEnt* idhentry = NULL; /* * To speed up transaction exit, we want to avoid scanning the relcache * unless there is actually something for this routine to do. Other than * the debug-only Assert checks, most transactions don't create any work * for us to do here, so we keep a static flag that gets set if there is * anything to do. (Currently, this means either a relation is created in * the current xact, or one is given a new relfilenode, or an index list * is forced.) For simplicity, the flag remains set till end of top-level * transaction, even though we could clear it at subtransaction end in * some cases. */ if (!u_sess->relcache_cxt.need_eoxact_work #ifdef USE_ASSERT_CHECKING && !assert_enabled #endif ) return; hash_seq_init(&status, u_sess->relcache_cxt.RelationIdCache); while ((idhentry = (RelIdCacheEnt*)hash_seq_search(&status)) != NULL) { Relation relation = idhentry->reldesc; /* * The relcache entry's ref count should be back to its normal * not-in-a-transaction state: 0 unless it's nailed in cache. * * In bootstrap mode, this is NOT true, so don't check it --- the * bootstrap code expects relations to stay open across start/commit * transaction calls. (That seems bogus, but it's not worth fixing.) */ if (!IsBootstrapProcessingMode()) { int expected_refcnt; expected_refcnt = relation->rd_isnailed ? 1 : 0; if (relation->rd_refcnt != expected_refcnt && IsolatedResourceOwner != NULL) { elog(WARNING, "relation \"%s\" rd_refcnt is %d but expected_refcnt %d. ", RelationGetRelationName(relation), relation->rd_refcnt, expected_refcnt); PrintResourceOwnerLeakWarning(); } #ifdef USE_ASSERT_CHECKING Assert(relation->rd_refcnt == expected_refcnt); #endif } /* * Is it a relation created in the current transaction? * * During commit, reset the flag to zero, since we are now out of the * creating transaction. During abort, simply delete the relcache * entry --- it isn't interesting any longer. (NOTE: if we have * forgotten the new-ness of a new relation due to a forced cache * flush, the entry will get deleted anyway by shared-cache-inval * processing of the aborted pg_class insertion.) */ if (relation->rd_createSubid != InvalidSubTransactionId) { if (isCommit) relation->rd_createSubid = InvalidSubTransactionId; else if (RelationHasReferenceCountZero(relation)) { RelationClearRelation(relation, false); continue; } else { /* * Hmm, somewhere there's a (leaked?) reference to the relation. * We daren't remove the entry for fear of dereferencing a * dangling pointer later. Bleat, and mark it as not belonging to * the current transaction. Hopefully it'll get cleaned up * eventually. This must be just a WARNING to avoid * error-during-error-recovery loops. */ relation->rd_createSubid = InvalidSubTransactionId; ereport(WARNING, (errmsg("cannot remove relcache entry for \"%s\" because it has nonzero refcount", RelationGetRelationName(relation)))); } } /* * Likewise, reset the hint about the relfilenode being new. */ relation->rd_newRelfilenodeSubid = InvalidSubTransactionId; /* * Flush any temporary index list. */ if (relation->rd_indexvalid == 2) { list_free_ext(relation->rd_indexlist); relation->rd_indexlist = NIL; relation->rd_oidindex = InvalidOid; relation->rd_indexvalid = 0; } } /* Once done with the transaction, we can reset u_sess->relcache_cxt.need_eoxact_work */ u_sess->relcache_cxt.need_eoxact_work = false; } /* * AtEOSubXact_RelationCache * * Clean up the relcache at sub-transaction commit or abort. * * Note: this must be called *before* processing invalidation messages. */ void AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid) { HASH_SEQ_STATUS status; RelIdCacheEnt* idhentry = NULL; /* * Skip the relcache scan if nothing to do --- see notes for * AtEOXact_RelationCache. */ if (!u_sess->relcache_cxt.need_eoxact_work) return; hash_seq_init(&status, u_sess->relcache_cxt.RelationIdCache); while ((idhentry = (RelIdCacheEnt*)hash_seq_search(&status)) != NULL) { Relation relation = idhentry->reldesc; /* * Is it a relation created in the current subtransaction? * * During subcommit, mark it as belonging to the parent, instead. * During subabort, simply delete the relcache entry. */ if (relation->rd_createSubid == mySubid) { if (isCommit) relation->rd_createSubid = parentSubid; else if (RelationHasReferenceCountZero(relation)) { RelationClearRelation(relation, false); continue; } else { /* * Hmm, somewhere there's a (leaked?) reference to the relation. * We daren't remove the entry for fear of dereferencing a * dangling pointer later. Bleat, and transfer it to the parent * subtransaction so we can try again later. This must be just a * WARNING to avoid error-during-error-recovery loops. */ relation->rd_createSubid = parentSubid; ereport(WARNING, (errmsg("cannot remove relcache entry for \"%s\" because it has nonzero refcount", RelationGetRelationName(relation)))); } } /* * Likewise, update or drop any new-relfilenode-in-subtransaction * hint. */ if (relation->rd_newRelfilenodeSubid == mySubid) { if (isCommit) relation->rd_newRelfilenodeSubid = parentSubid; else relation->rd_newRelfilenodeSubid = InvalidSubTransactionId; } /* * Flush any temporary index list. */ if (relation->rd_indexvalid == 2) { list_free_ext(relation->rd_indexlist); relation->rd_indexlist = NIL; relation->rd_oidindex = InvalidOid; relation->rd_indexvalid = 0; } } } /* * RelationBuildLocalRelation * Build a relcache entry for an about-to-be-created relation, * and enter it into the relcache. */ Relation RelationBuildLocalRelation(const char* relname, Oid relnamespace, TupleDesc tupDesc, Oid relid, Oid relfilenode, Oid reltablespace, bool shared_relation, bool mapped_relation, char relpersistence, char relkind, int8 row_compress, TableAmType tam_type) { Relation rel; MemoryContext oldcxt; int natts = tupDesc->natts; int i; bool has_not_null = false; bool nailit = false; AssertArg(natts >= 0); /* * check for creation of a rel that must be nailed in cache. * * XXX this list had better match the relations specially handled in * RelationCacheInitializePhase2/3. */ switch (relid) { case DatabaseRelationId: case AuthIdRelationId: case AuthMemRelationId: case RelationRelationId: case AttributeRelationId: case ProcedureRelationId: case TypeRelationId: case UserStatusRelationId: nailit = true; break; default: nailit = false; break; } /* * check that hardwired list of shared rels matches what's in the * bootstrap .bki file. If you get a failure here during initdb, you * probably need to fix IsSharedRelation() to match whatever you've done * to the set of shared relations. */ if (shared_relation != IsSharedRelation(relid)) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("shared_relation flag for \"%s\" does not match IsSharedRelation(%u)", relname, relid))); /* Shared relations had better be mapped, too */ Assert(mapped_relation || !shared_relation); /* * switch to the cache context to create the relcache entry. */ oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); /* * allocate a new relation descriptor and fill in basic state fields. */ rel = (Relation)palloc0(sizeof(RelationData)); /* make sure relation is marked as having no open file yet */ rel->rd_smgr = NULL; /* init bucketkey to point itself means bucket key is not build yet */ rel->rd_bucketkey = (RelationBucketKey *)&(rel->rd_bucketkey); rel->rd_bucketoid = InvalidOid; /* mark it nailed if appropriate */ rel->rd_isnailed = nailit; rel->rd_refcnt = nailit ? 1 : 0; /* it's being created in this transaction */ rel->rd_createSubid = GetCurrentSubTransactionId(); rel->rd_newRelfilenodeSubid = InvalidSubTransactionId; /* must flag that we have rels created in this transaction */ u_sess->relcache_cxt.need_eoxact_work = true; /* * create a new tuple descriptor from the one passed in. We do this * partly to copy it into the cache context, and partly because the new * relation can't have any defaults or constraints yet; they have to be * added in later steps, because they require additions to multiple system * catalogs. We can copy attnotnull constraints here, however. */ rel->rd_att = CreateTupleDescCopy(tupDesc); rel->rd_tam_type = tam_type; rel->rd_att->tdTableAmType = tam_type; rel->rd_att->tdrefcount = 1; /* mark as refcounted */ has_not_null = false; for (i = 0; i < natts; i++) { rel->rd_att->attrs[i]->attnotnull = tupDesc->attrs[i]->attnotnull; has_not_null = has_not_null || tupDesc->attrs[i]->attnotnull; } if (has_not_null) { TupleConstr* constr = (TupleConstr*)palloc0(sizeof(TupleConstr)); constr->has_not_null = true; rel->rd_att->constr = constr; } /* * initialize relation tuple form (caller may add/override data later) */ rel->rd_rel = (Form_pg_class)palloc0(sizeof(FormData_pg_class)); namestrcpy(&rel->rd_rel->relname, relname); rel->rd_rel->relnamespace = relnamespace; rel->rd_rel->relkind = relkind; rel->rd_rel->relhasoids = rel->rd_att->tdhasoid; rel->rd_rel->relnatts = natts; rel->rd_rel->reltype = InvalidOid; /* needed when bootstrapping: */ rel->rd_rel->relowner = BOOTSTRAP_SUPERUSERID; rel->rd_rel->parttype = PARTTYPE_NON_PARTITIONED_RELATION; rel->rd_rel->relrowmovement = false; /* set up persistence and relcache fields dependent on it */ rel->rd_rel->relpersistence = relpersistence; switch (relpersistence) { case RELPERSISTENCE_UNLOGGED: case RELPERSISTENCE_PERMANENT: case RELPERSISTENCE_TEMP: //@Temp Table. Temp table here is just like unlogged table. rel->rd_backend = InvalidBackendId; rel->rd_islocaltemp = false; break; case RELPERSISTENCE_GLOBAL_TEMP: // global temp table rel->rd_backend = BackendIdForTempRelations; rel->rd_islocaltemp = false; break; default: ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid relpersistence: %c", relpersistence))); break; } /* * Insert relation physical and logical identifiers (OIDs) into the right * places. For a mapped relation, we set relfilenode to zero and rely on * RelationInitPhysicalAddr to consult the map. */ rel->rd_rel->relisshared = shared_relation; RelationGetRelid(rel) = relid; for (i = 0; i < natts; i++) rel->rd_att->attrs[i]->attrelid = relid; rel->rd_rel->reltablespace = reltablespace; if (mapped_relation) { rel->rd_rel->relfilenode = InvalidOid; /* Add it to the active mapping information */ RelationMapUpdateMap(relid, relfilenode, shared_relation, true); } else rel->rd_rel->relfilenode = relfilenode; /* * case 1: table in system level; * case 2: invalid COMPRESS type; */ if ((relid < FirstNormalObjectId) || !CHECK_CMPRS_VALID(row_compress)) { row_compress = REL_CMPRS_NOT_SUPPORT; } RELATION_SET_CMPRS_ATTR(rel, row_compress); RelationInitLockInfo(rel); /* see lmgr.c */ RelationInitPhysicalAddr(rel); /* materialized view not initially scannable */ if (relkind == RELKIND_MATVIEW) rel->rd_isscannable = false; else rel->rd_isscannable = true; /* * Okay to insert into the relcache hash tables. */ RelationCacheInsert(rel); /* * done building relcache entry. */ (void)MemoryContextSwitchTo(oldcxt); /* It's fully valid */ rel->rd_isvalid = true; /* * Caller expects us to pin the returned entry. */ RelationIncrementReferenceCount(rel); return rel; } // function protype declaim extern void heap_create_init_fork(Relation rel); // set new filenode for delta table void DeltaTableSetNewRelfilenode(Oid relid, TransactionId freezeXid, bool partition) { Relation deltaRel = heap_open(relid, AccessExclusiveLock); RelationSetNewRelfilenode(deltaRel, freezeXid); // skip partition because one partition CANNOT be unlogged. if (!partition && RELPERSISTENCE_UNLOGGED == deltaRel->rd_rel->relpersistence) { heap_create_init_fork(deltaRel); } heap_close(deltaRel, NoLock); } // set new filenode for CUDesc table void DescTableSetNewRelfilenode(Oid relid, TransactionId freezeXid, bool partition) { // Step 1: CUDesc relation must set new relfilenode // Because indexRelation has locked as AccessExclusiveLock, so it is safe // Relation cudescRel = heap_open(relid, AccessExclusiveLock); RelationSetNewRelfilenode(cudescRel, freezeXid); // skip partition because one partition CANNOT be unlogged. if (!partition && RELPERSISTENCE_UNLOGGED == cudescRel->rd_rel->relpersistence) { heap_create_init_fork(cudescRel); } // Step 2: CUDesc index must be set new relfilenode // ListCell* indlist = NULL; foreach (indlist, RelationGetIndexList(cudescRel)) { Oid indexId = lfirst_oid(indlist); Relation currentIndex = index_open(indexId, AccessExclusiveLock); RelationSetNewRelfilenode(currentIndex, InvalidTransactionId); // keep the same logic with row index relation, and // skip checking RELPERSISTENCE_UNLOGGED persistence /* Initialize the index and rebuild */ /* Note: we do not need to re-establish pkey setting */ /* Fetch info needed for index_build */ IndexInfo* indexInfo = BuildIndexInfo(currentIndex); index_build(cudescRel, NULL, currentIndex, NULL, indexInfo, false, true, INDEX_CREATE_NONE_PARTITION); index_close(currentIndex, NoLock); } heap_close(cudescRel, NoLock); } /* * RelationSetNewRelfilenode * * Assign a new relfilenode (physical file name) to the relation. * * This allows a full rewrite of the relation to be done with transactional * safety (since the filenode assignment can be rolled back). Note however * that there is no simple way to access the relation's old data for the * remainder of the current transaction. This limits the usefulness to cases * such as TRUNCATE or rebuilding an index from scratch. * * Caller must already hold exclusive lock on the relation. * * The relation is marked with relfrozenxid = freezeXid (InvalidTransactionId * must be passed for indexes and sequences). This should be a lower bound on * the XIDs that will be put into the new relation contents. */ void RelationSetNewRelfilenode(Relation relation, TransactionId freezeXid, bool isDfsTruncate) { Oid newrelfilenode; RelFileNodeBackend newrnode; Relation pg_class; HeapTuple tuple; HeapTuple nctup; Form_pg_class classform; Datum values[Natts_pg_class]; bool nulls[Natts_pg_class]; bool replaces[Natts_pg_class]; errno_t rc = EOK; bool modifyPgClass = !RELATION_IS_GLOBAL_TEMP(relation); /* Indexes, sequences must have Invalid frozenxid; other rels must not */ Assert(((RelationIsIndex(relation) || relation->rd_rel->relkind == RELKIND_SEQUENCE) ? freezeXid == InvalidTransactionId : TransactionIdIsNormal(freezeXid)) || relation->rd_rel->relkind == RELKIND_RELATION); /* Allocate a new relfilenode */ newrelfilenode = GetNewRelFileNode(relation->rd_rel->reltablespace, NULL, relation->rd_rel->relpersistence); // We must consider cudesc relation and delta relation when it is a CStore relation // We skip main partitioned table for setting new filenode, as relcudescrelid and reldeltarelid are zero when // constructing partitioned table. if (RelationIsColStore(relation)) { // step 1: CUDesc relation must set new relfilenode // step 2: CUDesc index must be set new relfilenode // if (!RelationIsPartitioned(relation)) { DescTableSetNewRelfilenode(relation->rd_rel->relcudescrelid, freezeXid, false); // Step 3: Deta relation must be set new relfilenode // DeltaTableSetNewRelfilenode(relation->rd_rel->reldeltarelid, freezeXid, false); } /* Both PAXformat and CUFormat will enther this logic * Only if it's CUFormat, we need to do step 4 */ if (RelationIsCUFormat(relation)) { // Step 4: Create first data file for newrelfilenode // Note that we need add xlog when create file // CStore::CreateStorage(relation, newrelfilenode); } } if (modifyPgClass) { /* * Get a writable copy of the pg_class tuple for the given relation. */ pg_class = heap_open(RelationRelationId, RowExclusiveLock); tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(RelationGetRelid(relation))); if (!HeapTupleIsValid(tuple)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("could not find tuple for relation %u", RelationGetRelid(relation)))); } classform = (Form_pg_class) GETSTRUCT(tuple); } ereport(LOG, (errmsg("Relation %s(%u) set newfilenode %u oldfilenode %u xid %lu", RelationGetRelationName(relation), RelationGetRelid(relation), newrelfilenode, relation->rd_node.relNode, GetCurrentTransactionIdIfAny()))); /* * Create storage for the main fork of the new relfilenode. * * NOTE: any conflict in relfilenode value will be caught here, if * GetNewRelFileNode messes up for any reason. */ newrnode.node = relation->rd_node; newrnode.node.relNode = newrelfilenode; newrnode.backend = relation->rd_backend; RelationCreateStorage(newrnode.node, relation->rd_rel->relpersistence, relation->rd_rel->relowner, relation->rd_bucketoid, newrelfilenode, relation); smgrclosenode(newrnode); /* * Schedule unlinking of the old storage at transaction commit. */ RelationDropStorage(relation, isDfsTruncate); if (!modifyPgClass) { Oid relnode = gtt_fetch_current_relfilenode(RelationGetRelid(relation)); Assert(RELATION_IS_GLOBAL_TEMP(relation)); Assert(!RelationIsMapped(relation)); relation->rd_node.relNode = relnode; CacheInvalidateRelcache(relation); } else { /* * Now update the pg_class row. However, if we're dealing with a mapped * index, pg_class.relfilenode doesn't change; instead we have to send the * update to the relation mapper. */ if (RelationIsMapped(relation)) RelationMapUpdateMap(RelationGetRelid(relation), newrelfilenode, relation->rd_rel->relisshared, false); else classform->relfilenode = newrelfilenode; /* These changes are safe even for a mapped relation */ if (relation->rd_rel->relkind != RELKIND_SEQUENCE) { classform->relpages = 0; /* it's empty until further notice */ classform->reltuples = 0; classform->relallvisible = 0; } /* set classform's relfrozenxid and relfrozenxid64 */ classform->relfrozenxid = (ShortTransactionId)InvalidTransactionId; rc = memset_s(values, sizeof(values), 0, sizeof(values)); securec_check(rc, "\0", "\0"); rc = memset_s(nulls, sizeof(nulls), false, sizeof(nulls)); securec_check(rc, "\0", "\0"); rc = memset_s(replaces, sizeof(replaces), false, sizeof(replaces)); securec_check(rc, "\0", "\0"); replaces[Anum_pg_class_relfrozenxid64 - 1] = true; values[Anum_pg_class_relfrozenxid64 - 1] = TransactionIdGetDatum(freezeXid); nctup = heap_modify_tuple(tuple, RelationGetDescr(pg_class), values, nulls, replaces); simple_heap_update(pg_class, &nctup->t_self, nctup); CatalogUpdateIndexes(pg_class, nctup); heap_freetuple_ext(nctup); heap_freetuple_ext(tuple); heap_close(pg_class, RowExclusiveLock); } /* * Make the pg_class row change visible, as well as the relation map * change if any. This will cause the relcache entry to get updated, too. */ CommandCounterIncrement(); /* * Mark the rel as having been given a new relfilenode in the current * (sub) transaction. This is a hint that can be used to optimize later * operations on the rel in the same transaction. */ relation->rd_newRelfilenodeSubid = GetCurrentSubTransactionId(); /* ... and now we have eoxact cleanup work to do */ u_sess->relcache_cxt.need_eoxact_work = true; } /* * RelationCacheInitialize * * This initializes the relation descriptor cache. At the time * that this is invoked, we can't do database access yet (mainly * because the transaction subsystem is not up); all we are doing * is making an empty cache hashtable. This must be done before * starting the initialization transaction, because otherwise * AtEOXact_RelationCache would crash if that transaction aborts * before we can get the relcache set up. */ #define INITRELCACHESIZE 400 void RelationCacheInitialize(void) { HASHCTL ctl; /* * create hashtable that indexes the relcache */ MemSet(&ctl, 0, sizeof(ctl)); ctl.keysize = sizeof(Oid); ctl.entrysize = sizeof(RelIdCacheEnt); ctl.hash = oid_hash; ctl.hcxt = u_sess->cache_mem_cxt; u_sess->relcache_cxt.RelationIdCache = hash_create("Relcache by OID", INITRELCACHESIZE, &ctl, HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT); /* * relation mapper needs to be initialized too */ RelationMapInitialize(); } /* * RelationCacheInitializePhase2 * * This is called to prepare for access to shared catalogs during startup. * We must at least set up nailed reldescs for pg_database, pg_authid, * and pg_auth_members. Ideally we'd like to have reldescs for their * indexes, too. We attempt to load this information from the shared * relcache init file. If that's missing or broken, just make phony * entries for the catalogs themselves. RelationCacheInitializePhase3 * will clean up as needed. */ void RelationCacheInitializePhase2(void) { MemoryContext oldcxt; /* * relation mapper needs initialized too */ RelationMapInitializePhase2(); /* * In bootstrap mode, the shared catalogs aren't there yet anyway, so do * nothing. */ if (IsBootstrapProcessingMode()) return; /* * switch to cache memory context */ oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); /* * Try to load the shared relcache cache file. If unsuccessful, bootstrap * the cache with pre-made descriptors for the critical shared catalogs. */ if (!load_relcache_init_file(true)) { formrdesc("pg_database", DatabaseRelation_Rowtype_Id, true, true, Natts_pg_database, Desc_pg_database); formrdesc("pg_authid", AuthIdRelation_Rowtype_Id, true, true, Natts_pg_authid, Desc_pg_authid); formrdesc( "pg_auth_members", AuthMemRelation_Rowtype_Id, true, false, Natts_pg_auth_members, Desc_pg_auth_members); formrdesc( "pg_user_status", UserStatusRelation_Rowtype_Id, true, true, Natts_pg_user_status, Desc_pg_user_status); #define NUM_CRITICAL_SHARED_RELS 4 /* fix if you change list above */ } (void)MemoryContextSwitchTo(oldcxt); } void RelationCacheInvalidOid(Relation relation) { HeapTuple htup; Form_pg_class relp; int natts = 0; htup = SearchSysCache1(RELOID, ObjectIdGetDatum(RelationGetRelid(relation))); if (!HeapTupleIsValid(htup)) ereport(FATAL, (errmsg("cache lookup failed for relation %u", RelationGetRelid(relation)))); relp = (Form_pg_class)GETSTRUCT(htup); /* * Copy tuple to relation->rd_rel. (See notes in * AllocateRelationDesc()) * But pay attention to relnatts of rd_rel because we hardcoded all system catalogs, * relnatts in pg_class might be old and will not be updated. * Use need to use hardcoded info in schemapg.h to fix it. */ natts = relation->rd_rel->relnatts; errno_t rc = EOK; MemCpy((char*)relation->rd_rel, (char*)relp, CLASS_TUPLE_SIZE); securec_check(rc, "\0", "\0"); relation->rd_rel->relnatts = natts; /* Update rd_options while we have the tuple */ if (relation->rd_options) pfree_ext(relation->rd_options); RelationParseRelOptions(relation, htup); /* * Check the values in rd_att were set up correctly. (We cannot * just copy them over now: formrdesc must have set up the rd_att * data correctly to start with, because it may already have been * copied into one or more catcache entries.) */ Assert(relation->rd_att->tdtypeid == relp->reltype); Assert(relation->rd_att->tdtypmod == -1); Assert(relation->rd_att->tdhasoid == relp->relhasoids); ReleaseSysCache(htup); } /* * RelationCacheInitializePhase3 * * This is called as soon as the catcache and transaction system * are functional and we have determined u_sess->proc_cxt.MyDatabaseId. At this point * we can actually read data from the database's system catalogs. * We first try to read pre-computed relcache entries from the local * relcache init file. If that's missing or broken, make phony entries * for the minimum set of nailed-in-cache relations. Then (unless * bootstrapping) make sure we have entries for the critical system * indexes. Once we've done all this, we have enough infrastructure to * open any system catalog or use any catcache. The last step is to * rewrite the cache files if needed. */ void RelationCacheInitializePhase3(void) { HASH_SEQ_STATUS status; RelIdCacheEnt* idhentry = NULL; MemoryContext oldcxt; bool needNewCacheFile = !u_sess->relcache_cxt.criticalSharedRelcachesBuilt; /* * relation mapper needs initialized too */ RelationMapInitializePhase3(); /* * switch to cache memory context */ oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); /* * Try to load the local relcache cache file. If unsuccessful, bootstrap * the cache with pre-made descriptors for the critical "nailed-in" system * catalogs. * * Vacuum-full pg_class will move entries of indexes on pg_class to the end * of pg_class. When bootstraping critical catcaches and relcached from scratch, * we have to do sequential scan for these entries. For databases with millions * of pg_class entries, this could take quite a long time. To make matters worse, * when multiple backends parallelly do this, they may block one another severly * due to lock on the same share buffer partition. To avoid such case, we only allow * one backend to bootstrap critical catcaches at one time. When it is done, the other * parallel backends would first try to load from init file once again. * Since share catalogs usually have much less entries, we only do so for local catalogs * at present. */ retry: if (IsBootstrapProcessingMode() || !load_relcache_init_file(false)) { if (!IsBootstrapProcessingMode()) { uint32 state = 0; if (pg_atomic_compare_exchange_u32( &t_thrd.xact_cxt.ShmemVariableCache->CriticalCacheBuildLock, &state, 1)) { /* Get the lock */ needNewLocalCacheFile = true; } else { /* Someone hold the lock, sleep and retry */ pg_usleep(10000); /* 10ms */ goto retry; } } if (IsBootstrapProcessingMode() || !load_relcache_init_file(false)) { needNewCacheFile = true; formrdesc("pg_class", RelationRelation_Rowtype_Id, false, true, Natts_pg_class, Desc_pg_class); formrdesc( "pg_attribute", AttributeRelation_Rowtype_Id, false, false, Natts_pg_attribute, Desc_pg_attribute); formrdesc("pg_proc", ProcedureRelation_Rowtype_Id, false, true, Natts_pg_proc, Desc_pg_proc); formrdesc("pg_type", TypeRelation_Rowtype_Id, false, true, Natts_pg_type, Desc_pg_type); } else { Assert(needNewLocalCacheFile); needNewLocalCacheFile = false; pg_atomic_exchange_u32(&t_thrd.xact_cxt.ShmemVariableCache->CriticalCacheBuildLock, 0); } #define NUM_CRITICAL_LOCAL_RELS 4 /* fix if you change list above */ } (void)MemoryContextSwitchTo(oldcxt); /* In bootstrap mode, the faked-up formrdesc info is all we'll have */ if (IsBootstrapProcessingMode()) return; /* * If we didn't get the critical system indexes loaded into relcache, do * so now. These are critical because the catcache and/or opclass cache * depend on them for fetches done during relcache load. Thus, we have an * infinite-recursion problem. We can break the recursion by doing * heapscans instead of indexscans at certain key spots. To avoid hobbling * performance, we only want to do that until we have the critical indexes * loaded into relcache. Thus, the flag u_sess->relcache_cxt.criticalRelcachesBuilt is used to * decide whether to do heapscan or indexscan at the key spots, and we set * it true after we've loaded the critical indexes. * * The critical indexes are marked as "nailed in cache", partly to make it * easy for load_relcache_init_file to count them, but mainly because we * cannot flush and rebuild them once we've set u_sess->relcache_cxt.criticalRelcachesBuilt to * true. (NOTE: perhaps it would be possible to reload them by * temporarily setting u_sess->relcache_cxt.criticalRelcachesBuilt to false again. For now, * though, we just nail 'em in.) * * RewriteRelRulenameIndexId and TriggerRelidNameIndexId are not critical * in the same way as the others, because the critical catalogs don't * (currently) have any rules or triggers, and so these indexes can be * rebuilt without inducing recursion. However they are used during * relcache load when a rel does have rules or triggers, so we choose to * nail them for performance reasons. */ if (!u_sess->relcache_cxt.criticalRelcachesBuilt) { load_critical_index(ClassOidIndexId, RelationRelationId); load_critical_index(AttributeRelidNumIndexId, AttributeRelationId); load_critical_index(IndexRelidIndexId, IndexRelationId); load_critical_index(OpclassOidIndexId, OperatorClassRelationId); load_critical_index(AccessMethodProcedureIndexId, AccessMethodProcedureRelationId); load_critical_index(RewriteRelRulenameIndexId, RewriteRelationId); load_critical_index(TriggerRelidNameIndexId, TriggerRelationId); #define NUM_CRITICAL_LOCAL_INDEXES 7 /* fix if you change list above */ u_sess->relcache_cxt.criticalRelcachesBuilt = true; } /* * Process critical shared indexes too. * * DatabaseNameIndexId isn't critical for relcache loading, but rather for * initial lookup of u_sess->proc_cxt.MyDatabaseId, without which we'll never find any * non-shared catalogs at all. Autovacuum calls InitPostgres with a * database OID, so it instead depends on DatabaseOidIndexId. We also * need to nail up some indexes on pg_authid and pg_auth_members for use * during client authentication. */ if (!u_sess->relcache_cxt.criticalSharedRelcachesBuilt) { load_critical_index(DatabaseNameIndexId, DatabaseRelationId); load_critical_index(DatabaseOidIndexId, DatabaseRelationId); load_critical_index(AuthIdRolnameIndexId, AuthIdRelationId); load_critical_index(AuthIdOidIndexId, AuthIdRelationId); load_critical_index(AuthMemMemRoleIndexId, AuthMemRelationId); load_critical_index(UserStatusRoleidIndexId, UserStatusRelationId); #define NUM_CRITICAL_SHARED_INDEXES 6 /* fix if you change list above */ u_sess->relcache_cxt.criticalSharedRelcachesBuilt = true; } /* * Now, scan all the relcache entries and update anything that might be * wrong in the results from formrdesc or the relcache cache file. If we * faked up relcache entries using formrdesc, then read the real pg_class * rows and replace the fake entries with them. Also, if any of the * relcache entries have rules or triggers, load that info the hard way * since it isn't recorded in the cache file. * * Whenever we access the catalogs to read data, there is a possibility of * a shared-inval cache flush causing relcache entries to be removed. * Since hash_seq_search only guarantees to still work after the *current* * entry is removed, it's unsafe to continue the hashtable scan afterward. * We handle this by restarting the scan from scratch after each access. * This is theoretically O(N^2), but the number of entries that actually * need to be fixed is small enough that it doesn't matter. */ hash_seq_init(&status, u_sess->relcache_cxt.RelationIdCache); while ((idhentry = (RelIdCacheEnt*)hash_seq_search(&status)) != NULL) { Relation relation = idhentry->reldesc; bool restart = false; /* * Make sure *this* entry doesn't get flushed while we work with it. */ RelationIncrementReferenceCount(relation); /* * If it's a faked-up entry, read the real pg_class tuple. */ if (relation->rd_rel->relowner == InvalidOid) { RelationCacheInvalidOid(relation); /* relowner had better be OK now, else we'll loop forever */ if (relation->rd_rel->relowner == InvalidOid) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid relowner in pg_class entry for \"%s\"", RelationGetRelationName(relation)))); restart = true; } /* * Fix data that isn't saved in relcache cache file. * * relhasrules or relhastriggers could possibly be wrong or out of * date. If we don't actually find any rules or triggers, clear the * local copy of the flag so that we don't get into an infinite loop * here. We don't make any attempt to fix the pg_class entry, though. */ if (relation->rd_rel->relhasrules && relation->rd_rules == NULL) { RelationBuildRuleLock(relation); if (relation->rd_rules == NULL) relation->rd_rel->relhasrules = false; restart = true; } if (relation->rd_rel->relhastriggers && relation->trigdesc == NULL) { RelationBuildTriggers(relation); if (relation->trigdesc == NULL) relation->rd_rel->relhastriggers = false; restart = true; } /* get row level security policies for this relation */ if (RelationEnableRowSecurity(relation) && relation->rd_rlsdesc == NULL) { RelationBuildRlsPolicies(relation); Assert(relation->rd_rlsdesc != NULL); restart = true; } /* Release hold on the relation */ RelationDecrementReferenceCount(relation); /* Now, restart the hashtable scan if needed */ if (restart) { hash_seq_term(&status); hash_seq_init(&status, u_sess->relcache_cxt.RelationIdCache); } } /* * Lastly, write out new relcache cache files if needed. We don't bother * to distinguish cases where only one of the two needs an update. */ if (needNewCacheFile) { /* * Force all the catcaches to finish initializing and thereby open the * catalogs and indexes they use. This will preload the relcache with * entries for all the most important system catalogs and indexes, so * that the init files will be most useful for future backends. */ InitCatalogCachePhase2(); /* reset t_thrd.relcache_cxt.initFileRelationIds list; we'll fill it during write */ u_sess->relcache_cxt.initFileRelationIds = NIL; /* now write the files */ write_relcache_init_file(true); write_relcache_init_file(false); if (needNewLocalCacheFile) { needNewLocalCacheFile = false; pg_atomic_exchange_u32(&t_thrd.xact_cxt.ShmemVariableCache->CriticalCacheBuildLock, 0); } } } /* * Load one critical system index into the relcache * * indexoid is the OID of the target index, heapoid is the OID of the catalog * it belongs to. */ static void load_critical_index(Oid indexoid, Oid heapoid) { Relation ird; int curRetryCnt = 0; int const maxRetryCnt = 10; retry_if_standby_mode: /* * We must lock the underlying catalog before locking the index to avoid * deadlock, since RelationBuildDesc might well need to read the catalog, * and if anyone else is exclusive-locking this catalog and index they'll * be doing it in that order. */ LockRelationOid(heapoid, AccessShareLock); LockRelationOid(indexoid, AccessShareLock); ird = RelationBuildDesc(indexoid, true); if (ird == NULL) { /* * in standby mode real minRecoveryPoint may not be reached. * see branch XLByteLT(EndRecPtr, minRecoveryPoint) in function XLogPageRead() * so we have to retry in standby mode. */ if (IsServerModeStandby() && curRetryCnt < maxRetryCnt) { /* release index && heap lock before retry again */ UnlockRelationOid(indexoid, AccessShareLock); UnlockRelationOid(heapoid, AccessShareLock); if (0 == curRetryCnt++) { ereport(LOG, (errmsg("the first fail to open critical system index %u of heap %u", indexoid, heapoid))); } pg_usleep(1000000); goto retry_if_standby_mode; } ereport(PANIC, (errmsg("could not open critical system index %u", indexoid))); } else if (0 != curRetryCnt) { ereport(LOG, (errmsg("the last fail to open critical system index %u of heap %u, count %d", indexoid, heapoid, curRetryCnt))); } ird->rd_isnailed = true; ird->rd_refcnt = 1; UnlockRelationOid(indexoid, AccessShareLock); UnlockRelationOid(heapoid, AccessShareLock); } /* * GetPgClassDescriptor -- get a predefined tuple descriptor for pg_class * GetPgIndexDescriptor -- get a predefined tuple descriptor for pg_index * * We need this kluge because we have to be able to access non-fixed-width * fields of pg_class and pg_index before we have the standard catalog caches * available. We use predefined data that's set up in just the same way as * the bootstrapped reldescs used by formrdesc(). The resulting tupdesc is * not 100% kosher: it does not have the correct rowtype OID in tdtypeid, nor * does it have a TupleConstr field. But it's good enough for the purpose of * extracting fields. */ TupleDesc BuildHardcodedDescriptor(int natts, const FormData_pg_attribute* attrs, bool hasoids) { TupleDesc result; MemoryContext oldcxt; int i; oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); result = CreateTemplateTupleDesc(natts, hasoids, TAM_HEAP); result->tdtypeid = RECORDOID; /* not right, but we don't care */ result->tdtypmod = -1; for (i = 0; i < natts; i++) { MemCpy(result->attrs[i], &attrs[i], ATTRIBUTE_FIXED_PART_SIZE); /* make sure attcacheoff is valid */ result->attrs[i]->attcacheoff = -1; } /* initialize first attribute's attcacheoff, cf RelationBuildTupleDesc */ result->attrs[0]->attcacheoff = 0; /* Note: we don't bother to set up a TupleConstr entry */ (void)MemoryContextSwitchTo(oldcxt); return result; } static TupleDesc GetPgClassDescriptor(void) { /* Already done? */ if (u_sess->relcache_cxt.pgclassdesc == NULL) u_sess->relcache_cxt.pgclassdesc = BuildHardcodedDescriptor(Natts_pg_class, Desc_pg_class, true); return u_sess->relcache_cxt.pgclassdesc; } /* * Replace with GetPgClassDescriptor * * Ban to release return value since it is a static value, and it is used * frequently in relation operation */ TupleDesc GetDefaultPgClassDesc(void) { return GetPgClassDescriptor(); } static TupleDesc GetPgIndexDescriptor(void) { /* Already done? */ if (u_sess->relcache_cxt.pgindexdesc == NULL) u_sess->relcache_cxt.pgindexdesc = BuildHardcodedDescriptor(Natts_pg_index, Desc_pg_index, false); return u_sess->relcache_cxt.pgindexdesc; } /* * Replace with get_pg_index_descriptor * * Ban to release return value since it is a static value, and it is used * frequently in relation operation */ TupleDesc GetDefaultPgIndexDesc(void) { return GetPgIndexDescriptor(); } /* * Load any default attribute value definitions for the relation. */ static void AttrDefaultFetch(Relation relation) { AttrDefault* attrdef = relation->rd_att->constr->defval; int ndef = relation->rd_att->constr->num_defval; Relation adrel; SysScanDesc adscan; ScanKeyData skey; HeapTuple htup; Datum val; bool isnull = false; int found; int i; ScanKeyInit( &skey, Anum_pg_attrdef_adrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(relation))); adrel = heap_open(AttrDefaultRelationId, AccessShareLock); adscan = systable_beginscan(adrel, AttrDefaultIndexId, true, SnapshotNow, 1, &skey); found = 0; while (HeapTupleIsValid(htup = systable_getnext(adscan))) { Form_pg_attrdef adform = (Form_pg_attrdef)GETSTRUCT(htup); for (i = 0; i < ndef; i++) { if (adform->adnum != attrdef[i].adnum) continue; if (attrdef[i].adbin != NULL) ereport(WARNING, (errmsg("multiple attrdef records found for attr %s of rel %s", NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname), RelationGetRelationName(relation)))); else found++; val = fastgetattr(htup, Anum_pg_attrdef_adbin, adrel->rd_att, &isnull); if (isnull) ereport(WARNING, (errmsg("null adbin for attr %s of rel %s", NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname), RelationGetRelationName(relation)))); else attrdef[i].adbin = MemoryContextStrdup(u_sess->cache_mem_cxt, TextDatumGetCString(val)); break; } if (i >= ndef) ereport(WARNING, (errmsg("unexpected attrdef record found for attr %d of rel %s", adform->adnum, RelationGetRelationName(relation)))); } systable_endscan(adscan); heap_close(adrel, AccessShareLock); if (found != ndef) ereport(WARNING, (errmsg("%d attrdef record(s) missing for rel %s", ndef - found, RelationGetRelationName(relation)))); } /* * Load any check constraints for the relation. */ static void CheckConstraintFetch(Relation relation) { ConstrCheck* check = relation->rd_att->constr->check; int ncheck = relation->rd_att->constr->num_check; Relation conrel; SysScanDesc conscan; ScanKeyData skey[1]; HeapTuple htup; Datum val; bool isnull = false; int found = 0; ScanKeyInit(&skey[0], Anum_pg_constraint_conrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(relation))); conrel = heap_open(ConstraintRelationId, AccessShareLock); conscan = systable_beginscan(conrel, ConstraintRelidIndexId, true, SnapshotNow, 1, skey); while (HeapTupleIsValid(htup = systable_getnext(conscan))) { Form_pg_constraint conform = (Form_pg_constraint)GETSTRUCT(htup); /* We want check constraints only */ if (conform->contype != CONSTRAINT_CHECK) continue; if (found >= ncheck) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("unexpected constraint record found for rel %s", RelationGetRelationName(relation)))); check[found].ccvalid = conform->convalidated; check[found].ccnoinherit = conform->connoinherit; check[found].ccname = MemoryContextStrdup(u_sess->cache_mem_cxt, NameStr(conform->conname)); /* Grab and test conbin is actually set */ val = fastgetattr(htup, Anum_pg_constraint_conbin, conrel->rd_att, &isnull); if (isnull) ereport(ERROR, (errcode(ERRCODE_UNEXPECTED_NULL_VALUE), errmsg("null conbin for rel %s", RelationGetRelationName(relation)))); check[found].ccbin = MemoryContextStrdup(u_sess->cache_mem_cxt, TextDatumGetCString(val)); found++; } systable_endscan(conscan); heap_close(conrel, AccessShareLock); if (found != ncheck) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg( "%d constraint record(s) missing for rel %s", ncheck - found, RelationGetRelationName(relation)))); } void SaveCopyList(Relation relation, List* result, int oidIndex) { MemoryContext oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); if (relation->rd_indexlist) { list_free_ext(relation->rd_indexlist); } relation->rd_indexlist = list_copy(result); relation->rd_oidindex = oidIndex; relation->rd_indexvalid = 1; (void)MemoryContextSwitchTo(oldcxt); } /* * RelationGetSpecificKindIndexList -- get a list of OIDs of global indexes on this relation or not */ List* RelationGetSpecificKindIndexList(Relation relation, bool isGlobal) { ListCell* indList = NULL; List* result = NULL; List* indexOidList = RelationGetIndexList(relation); /* Ask the relcache to produce a list of the indexes of the rel */ foreach (indList, indexOidList) { Oid indexId = lfirst_oid(indList); Relation currentIndex; /* Open the index relation; use exclusive lock, just to be sure */ currentIndex = index_open(indexId, AccessShareLock); if (isGlobal) { if (RelationIsGlobalIndex(currentIndex)) { result = insert_ordered_oid(result, indexId); } } else { if (!RelationIsGlobalIndex(currentIndex)) { result = insert_ordered_oid(result, indexId); } } index_close(currentIndex, AccessShareLock); } list_free_ext(indexOidList); return result; } /* * RelationGetIndexList -- get a list of OIDs of indexes on this relation * * The index list is created only if someone requests it. We scan pg_index * to find relevant indexes, and add the list to the relcache entry so that * we won't have to compute it again. Note that shared cache inval of a * relcache entry will delete the old list and set rd_indexvalid to 0, * so that we must recompute the index list on next request. This handles * creation or deletion of an index. * * Indexes that are marked not IndexIsLive are omitted from the returned list. * Such indexes are expected to be dropped momentarily, and should not be * touched at all by any caller of this function. * * The returned list is guaranteed to be sorted in order by OID. This is * needed by the executor, since for index types that we obtain exclusive * locks on when updating the index, all backends must lock the indexes in * the same order or we will get deadlocks (see ExecOpenIndices()). Any * consistent ordering would do, but ordering by OID is easy. * * Since shared cache inval causes the relcache's copy of the list to go away, * we return a copy of the list palloc'd in the caller's context. The caller * may list_free_ext() the returned list after scanning it. This is necessary * since the caller will typically be doing syscache lookups on the relevant * indexes, and syscache lookup could cause SI messages to be processed! * * We also update rd_oidindex, which this module treats as effectively part * of the index list. rd_oidindex is valid when rd_indexvalid isn't zero; * it is the pg_class OID of a unique index on OID when the relation has one, * and InvalidOid if there is no such index. */ List* RelationGetIndexList(Relation relation) { Relation indrel; SysScanDesc indscan; ScanKeyData skey; HeapTuple htup; List* result = NIL; char relreplident; Oid oidIndex = InvalidOid; Oid pkeyIndex = InvalidOid; Oid candidateIndex = InvalidOid; Datum replident = (Datum)0; Assert(!RelationIsBucket(relation) && !RelationIsPartition(relation)); /* Quick exit if we already computed the list. */ if (relation->rd_indexvalid != 0) return list_copy(relation->rd_indexlist); bool isNull = false; Relation rel = heap_open(RelationRelationId, AccessShareLock); Oid relid = RelationIsPartition(relation) ? relation->parentId : relation->rd_id; HeapTuple tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid)); if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("pg_class entry for relid %u vanished during RelationGetIndexList", relid))); replident = heap_getattr(tuple, Anum_pg_class_relreplident, RelationGetDescr(rel), &isNull); heap_close(rel, AccessShareLock); heap_freetuple_ext(tuple); if (isNull) relreplident = REPLICA_IDENTITY_NOTHING; else relreplident = CharGetDatum(replident); /* * We build the list we intend to return (in the caller's context) while * doing the scan. After successfully completing the scan, we copy that * list into the relcache entry. This avoids cache-context memory leakage * if we get some sort of error partway through. */ result = NIL; oidIndex = InvalidOid; /* Prepare to scan pg_index for entries having indrelid = this rel. */ ScanKeyInit( &skey, Anum_pg_index_indrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(relation))); indrel = heap_open(IndexRelationId, AccessShareLock); indscan = systable_beginscan(indrel, IndexIndrelidIndexId, true, SnapshotNow, 1, &skey); while (HeapTupleIsValid(htup = systable_getnext(indscan))) { Form_pg_index index = (Form_pg_index)GETSTRUCT(htup); Datum indclassDatum; oidvector* indclass = NULL; bool isnull = false; /* * Ignore any indexes that are currently being dropped. This will * prevent them from being searched, inserted into, or considered in * HOT-safety decisions. It's unsafe to touch such an index at all * since its catalog entries could disappear at any instant. */ if (!IndexIsLive(index)) continue; /* Add index's OID to result list in the proper order */ result = insert_ordered_oid(result, index->indexrelid); /* * indclass cannot be referenced directly through the C struct, * because it comes after the variable-width indkey field. Must * extract the datum the hard way... */ indclassDatum = heap_getattr(htup, Anum_pg_index_indclass, GetPgIndexDescriptor(), &isnull); Assert(!isnull); indclass = (oidvector*)DatumGetPointer(indclassDatum); /* * Invalid, non-unique, non-immediate or predicate indexes aren't * interesting for neither oid indexes nor replication identity * indexes, so don't check them. */ if (!IndexIsValid(index) || !index->indisunique || !index->indimmediate || !heap_attisnull(htup, Anum_pg_index_indpred, NULL)) continue; /* Check to see if is a usable btree index on OID */ if (index->indnatts == 1 && index->indkey.values[0] == ObjectIdAttributeNumber && indclass->values[0] == OID_BTREE_OPS_OID) oidIndex = index->indexrelid; /* always prefer primary keys */ if (index->indisprimary) pkeyIndex = index->indexrelid; bool isNull = true; bool isreplident = false; Datum indisreplident; indisreplident = heap_getattr(htup, Anum_pg_index_indisreplident, RelationGetDescr(indrel), &isNull); if (!isNull) { isreplident = BoolGetDatum(indisreplident); } /* explicitly chosen index */ if (isreplident) candidateIndex = index->indexrelid; } systable_endscan(indscan); /* primary key */ if (relreplident == REPLICA_IDENTITY_DEFAULT && OidIsValid(pkeyIndex)) relation->rd_replidindex = pkeyIndex; /* explicitly chosen index */ else if (relreplident == REPLICA_IDENTITY_INDEX && OidIsValid(candidateIndex)) relation->rd_replidindex = candidateIndex; /* nothing */ else relation->rd_replidindex = InvalidOid; heap_close(indrel, AccessShareLock); /* Now save a copy of the completed list in the relcache entry. */ SaveCopyList(relation, result, oidIndex); return result; } /* * RelationGetIndexInfoList -- get a list of index info * */ List* RelationGetIndexInfoList(Relation relation) { List* index_info_list = NIL; List* index_oid_list = NIL; ListCell* l = NULL; /* Fast path if definitely no indexes */ if (!RelationGetForm(relation)->relhasindex) return NULL; /* * Get cached list of index OIDs */ index_oid_list = RelationGetIndexList(relation); /* Fall out if no indexes (but relhasindex was set) */ if (index_oid_list == NIL) return NIL; /* * For each index, add index info to index_info_list. * * Note: we consider all indexes returned by RelationGetIndexList, even if * they are not indisready or indisvalid. This is important because an * index for which CREATE INDEX CONCURRENTLY has just started must be * included in HOT-safety decisions (see README.HOT). If a DROP INDEX * CONCURRENTLY is far enough along that we should ignore the index, it * won't be returned at all by RelationGetIndexList. */ foreach (l, index_oid_list) { Oid index_oid = lfirst_oid(l); Relation index_desc; IndexInfo* index_info = NULL; index_desc = index_open(index_oid, AccessShareLock); /* Extract index key information from the index's pg_index row */ index_info = BuildIndexInfo(index_desc); index_info_list = lappend(index_info_list, index_info); index_close(index_desc, AccessShareLock); } list_free_ext(index_oid_list); return index_info_list; } /* * Get index num from relation, this function is almost the same * with RelationGetIndexList, except return the length of index * list. */ int RelationGetIndexNum(Relation relation) { Relation indrel; SysScanDesc indscan; ScanKeyData skey; HeapTuple htup; List* result = NULL; Oid oidIndex; Assert(!RelationIsBucket(relation) && !RelationIsPartition(relation)); /* Quick exit if we already computed the list. */ if (relation->rd_indexvalid != 0) return list_length(relation->rd_indexlist); /* * We build the list we intend to return (in the caller's context) while * doing the scan. After successfully completing the scan, we copy that * list into the relcache entry. This avoids cache-context memory leakage * if we get some sort of error partway through. */ result = NIL; oidIndex = InvalidOid; /* Prepare to scan pg_index for entries having indrelid = this rel. */ ScanKeyInit( &skey, Anum_pg_index_indrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(relation))); indrel = heap_open(IndexRelationId, AccessShareLock); indscan = systable_beginscan(indrel, IndexIndrelidIndexId, true, SnapshotNow, 1, &skey); while (HeapTupleIsValid(htup = systable_getnext(indscan))) { Form_pg_index index = (Form_pg_index)GETSTRUCT(htup); Datum indclassDatum; oidvector* indclass = NULL; bool isnull = false; /* * Ignore any indexes that are currently being dropped. This will * prevent them from being searched, inserted into, or considered in * HOT-safety decisions. It's unsafe to touch such an index at all * since its catalog entries could disappear at any instant. */ if (!IndexIsLive(index)) continue; /* Add index's OID to result list in the proper order */ result = insert_ordered_oid(result, index->indexrelid); /* * indclass cannot be referenced directly through the C struct, * because it comes after the variable-width indkey field. Must * extract the datum the hard way... */ indclassDatum = heap_getattr(htup, Anum_pg_index_indclass, GetPgIndexDescriptor(), &isnull); Assert(!isnull); indclass = (oidvector*)DatumGetPointer(indclassDatum); /* Check to see if it is a unique, non-partial btree index on OID */ if (IndexIsValid(index) && index->indnatts == 1 && index->indisunique && index->indimmediate && index->indkey.values[0] == ObjectIdAttributeNumber && indclass->values[0] == OID_BTREE_OPS_OID && heap_attisnull(htup, Anum_pg_index_indpred, NULL)) oidIndex = index->indexrelid; } systable_endscan(indscan); heap_close(indrel, AccessShareLock); /* Now save a copy of the completed list in the relcache entry. */ SaveCopyList(relation, result, oidIndex); list_free_ext(result); return list_length(relation->rd_indexlist); } /* * insert_ordered_oid * Insert a new Oid into a sorted list of Oids, preserving ordering * * Building the ordered list this way is O(N^2), but with a pretty small * constant, so for the number of entries we expect it will probably be * faster than trying to apply qsort(). Most tables don't have very many * indexes... */ static List* insert_ordered_oid(List* list, Oid datum) { ListCell* prev = NULL; /* Does the datum belong at the front? */ if (list == NIL || datum < linitial_oid(list)) return lcons_oid(datum, list); /* No, so find the entry it belongs after */ prev = list_head(list); for (;;) { ListCell* curr = lnext(prev); if (curr == NULL || datum < lfirst_oid(curr)) break; /* it belongs after 'prev', before 'curr' */ prev = curr; } /* Insert datum into list after 'prev' */ lappend_cell_oid(list, prev, datum); return list; } /* * RelationSetIndexList -- externally force the index list contents * * This is used to temporarily override what we think the set of valid * indexes is (including the presence or absence of an OID index). * The forcing will be valid only until transaction commit or abort. * * This should only be applied to nailed relations, because in a non-nailed * relation the hacked index list could be lost at any time due to SI * messages. In practice it is only used on pg_class (see REINDEX). * * It is up to the caller to make sure the given list is correctly ordered. * * We deliberately do not change rd_indexattr here: even when operating * with a temporary partial index list, HOT-update decisions must be made * correctly with respect to the full index set. It is up to the caller * to ensure that a correct rd_indexattr set has been cached before first * calling RelationSetIndexList; else a subsequent inquiry might cause a * wrong rd_indexattr set to get computed and cached. */ void RelationSetIndexList(Relation relation, List* indexIds, Oid oidIndex) { MemoryContext oldcxt; Assert(relation->rd_isnailed); /* Copy the list into the cache context (could fail for lack of mem) */ oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); indexIds = list_copy(indexIds); (void)MemoryContextSwitchTo(oldcxt); /* Okay to replace old list */ list_free_ext(relation->rd_indexlist); relation->rd_indexlist = indexIds; relation->rd_oidindex = oidIndex; relation->rd_indexvalid = 2; /* mark list as forced */ /* must flag that we have a forced index list */ u_sess->relcache_cxt.need_eoxact_work = true; } /* * RelationGetOidIndex -- get the pg_class OID of the relation's OID index * * Returns InvalidOid if there is no such index. */ Oid RelationGetOidIndex(Relation relation) { List* ilist = NULL; /* * If relation doesn't have OIDs at all, caller is probably confused. (We * could just silently return InvalidOid, but it seems better to throw an * assertion.) */ Assert(relation->rd_rel->relhasoids); Assert(!RelationIsBucket(relation) && !RelationIsPartition(relation)); if (relation->rd_indexvalid == 0) { /* RelationGetIndexList does the heavy lifting. */ ilist = RelationGetIndexList(relation); list_free_ext(ilist); Assert(relation->rd_indexvalid != 0); } return relation->rd_oidindex; } /* * RelationGetReplicaIndex -- get OID of the relation's replica identity index * If the table is partition table, return the replica identity index of parent table. * * Returns InvalidOid if there is no such index. */ Oid RelationGetReplicaIndex(Relation relation) { List* ilist = NIL; Relation parentRelation; Oid replidindex; if (RelationIsBucket(relation)) { parentRelation = relation->parent; if (!RelationIsValid(parentRelation)) { Assert(false); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("could not open parent relation with OID %u", relation->parentId))); } replidindex = RelationGetReplicaIndex(parentRelation); return replidindex; } else if (RelationIsPartition(relation)) { parentRelation = RelationIdGetRelation(relation->parentId); if (!RelationIsValid(parentRelation)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("could not open relation with OID %u", relation->parentId))); } replidindex = RelationGetReplicaIndex(parentRelation); RelationClose(parentRelation); return replidindex; } if (relation->rd_indexvalid == 0) { /* RelationGetIndexList does the heavy lifting. */ ilist = RelationGetIndexList(relation); list_free_ext(ilist); Assert(relation->rd_indexvalid != 0); } return relation->rd_replidindex; } /* * RelationGetIndexExpressions -- get the index expressions for an index * * We cache the result of transforming pg_index.indexprs into a node tree. * If the rel is not an index or has no expressional columns, we return NIL. * Otherwise, the returned tree is copied into the caller's memory context. * (We don't want to return a pointer to the relcache copy, since it could * disappear due to relcache invalidation.) */ List* RelationGetIndexExpressions(Relation relation) { List* result = NULL; Datum exprsDatum; bool isnull = false; char* exprsString = NULL; MemoryContext oldcxt; /* Quick exit if we already computed the result. */ if (relation->rd_indexprs) return (List*)copyObject(relation->rd_indexprs); /* Quick exit if there is nothing to do. */ if (relation->rd_indextuple == NULL || heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL)) return NIL; /* * We build the tree we intend to return in the caller's context. After * successfully completing the work, we copy it into the relcache entry. * This avoids problems if we get some sort of error partway through. */ exprsDatum = heap_getattr(relation->rd_indextuple, Anum_pg_index_indexprs, GetPgIndexDescriptor(), &isnull); Assert(!isnull); exprsString = TextDatumGetCString(exprsDatum); result = (List*)stringToNode(exprsString); pfree_ext(exprsString); /* * Run the expressions through eval_const_expressions. This is not just an * optimization, but is necessary, because the planner will be comparing * them to similarly-processed qual clauses, and may fail to detect valid * matches without this. We don't bother with canonicalize_qual, however. */ result = (List*)eval_const_expressions(NULL, (Node*)result); /* May as well fix opfuncids too */ fix_opfuncids((Node*)result); /* Now save a copy of the completed tree in the relcache entry. */ oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt); relation->rd_indexprs = (List*)copyObject(result); (void)MemoryContextSwitchTo(oldcxt); return result; } /* * RelationGetDummyIndexExpressions -- get dummy expressions for an index * * Return a list of dummy expressions (just Const nodes) with the same * types/typmods/collations as the index's real expressions. This is * useful in situations where we don't want to run any user-defined code. */ List* RelationGetDummyIndexExpressions(Relation relation) { List* result; Datum exprsDatum; bool isnull; char* exprsString; List* rawExprs; ListCell* lc; /* Quick exit if there is nothing to do. */ if (relation->rd_indextuple == NULL || heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL)) { return NIL; } /* Extract raw node tree(s) from index tuple. */ exprsDatum = heap_getattr(relation->rd_indextuple, Anum_pg_index_indexprs, GetPgIndexDescriptor(), &isnull); Assert(!isnull); exprsString = TextDatumGetCString(exprsDatum); rawExprs = (List*)stringToNode(exprsString); pfree(exprsString); /* Construct null Consts; the typlen and typbyval are arbitrary. */ result = NIL; foreach (lc, rawExprs) { Node* rawExpr = (Node*)lfirst(lc); result = lappend( result, makeConst(exprType(rawExpr), exprTypmod(rawExpr), exprCollation(rawExpr), 1, (Datum)0, true, true)); } return result; } /* * RelationGetIndexPredicate -- get the index predicate for an index * * We cache the result of transforming pg_index.indpred into an implicit-AND * node tree (suitable for ExecQual). * If the rel is not an index or has no predicate, we return NIL. * Otherwise, the returned tree is copied into the caller's memory context. * (We don't want to return a pointer to the relcache copy, since it could * disappear due to relcache invalidation.) */ List* RelationGetIndexPredicate(Relation relation) { List* result = NULL; Datum predDatum; bool isnull = false; char* predString = NULL; MemoryContext oldcxt; /* Quick exit if we already computed the result. */ if (relation->rd_indpred) return (List*)copyObject(relation->rd_indpred); /* Quick exit if there is nothing to do. */ if (relation->rd_indextuple == NULL || heap_attisnull(relation->rd_indextuple, Anum_pg_index_indpred, NULL)) return NIL; /* * We build the tree we intend to return in the caller's context. After * successfully completing the work, we copy it into the relcache entry. * This avoids problems if we get some sort of error partway through. */ predDatum = heap_getattr(relation->rd_indextuple, Anum_pg_index_indpred, GetPgIndexDescriptor(), &isnull); Assert(!isnull); predString = TextDatumGetCString(predDatum); result = (List*)stringToNode(predString); pfree_ext(predString); /* * Run the expression through const-simplification and canonicalization. * This is not just an optimization, but is necessary, because the planner * will be comparing it to similarly-processed qual clauses, and may fail * to detect valid matches without this. This must match the processing * done to qual clauses in preprocess_expression()! (We can skip the * stuff involving subqueries, however, since we don't allow any in index * predicates.) */ result = (List*)eval_const_expressions(NULL, (Node*)result); result = (List*)canonicalize_qual((Expr*)result, false); /* Also convert to implicit-AND format */ result = make_ands_implicit((Expr*)result); /* May as well fix opfuncids too */ fix_opfuncids((Node*)result); /* Now save a copy of the completed tree in the relcache entry. */ oldcxt = MemoryContextSwitchTo(relation->rd_indexcxt); relation->rd_indpred = (List*)copyObject(result); (void)MemoryContextSwitchTo(oldcxt); return result; } /* * Load any check constraints for the relation. */ static void ClusterConstraintFetch(__inout Relation relation) { AttrNumber** pClusterKeys = &relation->rd_att->constr->clusterKeys; Relation conrel; SysScanDesc conscan; ScanKeyData skey[1]; HeapTuple htup; Datum val; bool isnull = false; ScanKeyInit(&skey[0], Anum_pg_constraint_conrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(relation))); conrel = heap_open(ConstraintRelationId, AccessShareLock); conscan = systable_beginscan(conrel, ConstraintRelidIndexId, true, SnapshotNow, 1, skey); while (HeapTupleIsValid(htup = systable_getnext(conscan))) { Form_pg_constraint conform = (Form_pg_constraint)GETSTRUCT(htup); /* We want check constraints only */ if (conform->contype != CONSTRAINT_CLUSTER) continue; /* Grab and test conbin is actually set */ val = fastgetattr(htup, Anum_pg_constraint_conkey, conrel->rd_att, &isnull); if (isnull) ereport(ERROR, (errcode(ERRCODE_UNEXPECTED_NULL_VALUE), errmsg("null cluster key for rel %s", RelationGetRelationName(relation)))); ArrayType* arr = DatumGetArrayTypeP(val); int numkeys = ARR_DIMS(arr)[0]; errno_t rc = EOK; *pClusterKeys = (AttrNumber*)MemoryContextAllocZero(u_sess->cache_mem_cxt, numkeys * sizeof(AttrNumber)); rc = memcpy_s(*pClusterKeys, numkeys * sizeof(int16), ARR_DATA_PTR(arr), numkeys * sizeof(int16)); securec_check(rc, "\0", "\0"); relation->rd_att->constr->clusterKeyNum = numkeys; /* always only have one */ break; } systable_endscan(conscan); heap_close(conrel, AccessShareLock); } /* * RelationGetIndexAttrBitmap -- get a bitmap of index attribute numbers * * The result has a bit set for each attribute used anywhere in the index * definitions of all the indexes on this relation. (This includes not only * simple index keys, but attributes used in expressions and partial-index * predicates.) * * Depending on attrKind, a bitmap covering the attnums for all index columns, * for all key columns or for all the columns the configured replica identity * are returned. * * Attribute numbers are offset by FirstLowInvalidHeapAttributeNumber so that * we can include system attributes (e.g., OID) in the bitmap representation. * * Caller had better hold at least RowExclusiveLock on the target relation * to ensure that it has a stable set of indexes. This also makes it safe * (deadlock-free) for us to take locks on the relation's indexes. * * The returned result is palloc'd in the caller's memory context and should * be bms_free'd when not needed anymore. */ Bitmapset* RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind) { Bitmapset* indexattrs = NULL; List* indexoidlist = NULL; ListCell* l = NULL; Bitmapset* idindexattrs = NULL; /* columns in the the replica identity */ Oid relreplindex; MemoryContext oldcxt; Assert(!RelationIsBucket(relation) && !RelationIsPartition(relation)); /* Quick exit if we already computed the result. */ if (relation->rd_indexattr != NULL) { switch (attrKind) { case INDEX_ATTR_BITMAP_ALL: return bms_copy(relation->rd_indexattr); case INDEX_ATTR_BITMAP_KEY: ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unknown attrKind %u", attrKind))); case INDEX_ATTR_BITMAP_IDENTITY_KEY: return bms_copy(relation->rd_idattr); default: ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unknown attrKind %u", attrKind))); } } /* Fast path if definitely no indexes */ if (!RelationGetForm(relation)->relhasindex) return NULL; /* * Get cached list of index OIDs */ indexoidlist = RelationGetIndexList(relation); /* Fall out if no indexes (but relhasindex was set) */ if (indexoidlist == NIL) return NULL; /* * Copy the rd_replidindex value computed by RelationGetIndexList before * proceeding. This is needed because a relcache flush could occur inside * index_open below, resetting the fields managed by RelationGetIndexList. * (The values we're computing will still be valid, assuming that caller * has a sufficient lock on the relation.) */ relreplindex = relation->rd_replidindex; /* * For each index, add referenced attributes to indexattrs. * * Note: we consider all indexes returned by RelationGetIndexList, even if * they are not indisready or indisvalid. This is important because an * index for which CREATE INDEX CONCURRENTLY has just started must be * included in HOT-safety decisions (see README.HOT). If a DROP INDEX * CONCURRENTLY is far enough along that we should ignore the index, it * won't be returned at all by RelationGetIndexList. */ indexattrs = NULL; idindexattrs = NULL; foreach (l, indexoidlist) { Oid indexOid = lfirst_oid(l); Relation indexDesc; IndexInfo* indexInfo = NULL; int i; bool isIDKey = false; /* replica identity index */ indexDesc = index_open(indexOid, AccessShareLock); /* Extract index key information from the index's pg_index row */ indexInfo = BuildIndexInfo(indexDesc); /* Is this index the configured (or default) replica identity? */ isIDKey = (indexOid == relreplindex); /* Collect simple attribute references */ for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++) { int attrnum = indexInfo->ii_KeyAttrNumbers[i]; /* * Since we have covering indexes with non-key columns, we must * handle them accurately here. non-key columns must be added into * indexattrs, since they are in index, and HOT-update shouldn't * miss them. Obviously, non-key columns couldn't be referenced by * foreign key or identity key. Hence we do not include them into * uindexattrs, pkindexattrs and idindexattrs bitmaps. */ if (attrnum != 0) { indexattrs = bms_add_member(indexattrs, attrnum - FirstLowInvalidHeapAttributeNumber); if (isIDKey && i < indexInfo->ii_NumIndexKeyAttrs) idindexattrs = bms_add_member(idindexattrs, attrnum - FirstLowInvalidHeapAttributeNumber); } } /* Collect all attributes used in expressions, too */ pull_varattnos((Node*)indexInfo->ii_Expressions, 1, &indexattrs); /* Collect all attributes in the index predicate, too */ pull_varattnos((Node*)indexInfo->ii_Predicate, 1, &indexattrs); index_close(indexDesc, AccessShareLock); } list_free_ext(indexoidlist); /* * Now save copies of the bitmaps in the relcache entry. We intentionally * set rd_indexattr last, because that's the one that signals validity of * the values; if we run out of memory before making that copy, we won't * leave the relcache entry looking like the other ones are valid but * empty. */ oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); relation->rd_idattr = bms_copy(idindexattrs); relation->rd_indexattr = bms_copy(indexattrs); (void)MemoryContextSwitchTo(oldcxt); /* We return our original working copy for caller to play with */ switch (attrKind) { case INDEX_ATTR_BITMAP_ALL: return indexattrs; case INDEX_ATTR_BITMAP_KEY: ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unknown attrKind %u", attrKind))); case INDEX_ATTR_BITMAP_IDENTITY_KEY: return idindexattrs; default: ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unknown attrKind %u", attrKind))); } return NULL; // just for clear compile warning } /* * RelationGetExclusionInfo -- get info about index's exclusion constraint * * This should be called only for an index that is known to have an * associated exclusion constraint. It returns arrays (palloc'd in caller's * context) of the exclusion operator OIDs, their underlying functions' * OIDs, and their strategy numbers in the index's opclasses. We cache * all this information since it requires a fair amount of work to get. */ void RelationGetExclusionInfo(Relation indexRelation, Oid** operators, Oid** procs, uint16** strategies) { int indnkeyatts; Oid* ops = NULL; Oid* funcs = NULL; uint16* strats = NULL; Relation conrel; SysScanDesc conscan; ScanKeyData skey[1]; HeapTuple htup; bool found = false; MemoryContext oldcxt; int i; indnkeyatts = IndexRelationGetNumberOfKeyAttributes(indexRelation); /* Allocate result space in caller context */ *operators = ops = (Oid*)palloc(sizeof(Oid) * indnkeyatts); *procs = funcs = (Oid*)palloc(sizeof(Oid) * indnkeyatts); *strategies = strats = (uint16*)palloc(sizeof(uint16) * indnkeyatts); /* Quick exit if we have the data cached already */ if (indexRelation->rd_exclstrats != NULL) { MemCpy(ops, indexRelation->rd_exclops, sizeof(Oid) * indnkeyatts); MemCpy(funcs, indexRelation->rd_exclprocs, sizeof(Oid) * indnkeyatts); MemCpy(strats, indexRelation->rd_exclstrats, sizeof(uint16) * indnkeyatts); return; } /* * Search pg_constraint for the constraint associated with the index. To * make this not too painfully slow, we use the index on conrelid; that * will hold the parent relation's OID not the index's own OID. */ ScanKeyInit(&skey[0], Anum_pg_constraint_conrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(indexRelation->rd_index->indrelid)); conrel = heap_open(ConstraintRelationId, AccessShareLock); conscan = systable_beginscan(conrel, ConstraintRelidIndexId, true, SnapshotNow, 1, skey); found = false; while (HeapTupleIsValid(htup = systable_getnext(conscan))) { Form_pg_constraint conform = (Form_pg_constraint)GETSTRUCT(htup); Datum val; bool isnull = false; ArrayType* arr = NULL; int nelem; /* We want the exclusion constraint owning the index */ if (conform->contype != CONSTRAINT_EXCLUSION || conform->conindid != RelationGetRelid(indexRelation)) continue; /* There should be only one */ if (found) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("unexpected exclusion constraint record found for rel %s", RelationGetRelationName(indexRelation)))); found = true; /* Extract the operator OIDS from conexclop */ val = fastgetattr(htup, Anum_pg_constraint_conexclop, conrel->rd_att, &isnull); if (isnull) ereport(ERROR, (errcode(ERRCODE_UNEXPECTED_NULL_VALUE), errmsg("null conexclop for rel %s", RelationGetRelationName(indexRelation)))); arr = DatumGetArrayTypeP(val); /* ensure not toasted */ nelem = ARR_DIMS(arr)[0]; if (ARR_NDIM(arr) != 1 || nelem != indnkeyatts || ARR_HASNULL(arr) || ARR_ELEMTYPE(arr) != OIDOID) ereport( ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("conexclop is not a 1-D Oid array"))); int rc = memcpy_s(ops, sizeof(Oid) * indnkeyatts, ARR_DATA_PTR(arr), sizeof(Oid) * indnkeyatts); securec_check(rc, "\0", "\0"); } systable_endscan(conscan); heap_close(conrel, AccessShareLock); if (!found) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("exclusion constraint record missing for rel %s", RelationGetRelationName(indexRelation)))); /* We need the func OIDs and strategy numbers too */ for (i = 0; i < indnkeyatts; i++) { funcs[i] = get_opcode(ops[i]); strats[i] = get_op_opfamily_strategy(ops[i], indexRelation->rd_opfamily[i]); /* shouldn't fail, since it was checked at index creation */ if (strats[i] == InvalidStrategy) ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("could not find strategy for operator %u in family %u", ops[i], indexRelation->rd_opfamily[i]))); } /* Save a copy of the results in the relcache entry. */ oldcxt = MemoryContextSwitchTo(indexRelation->rd_indexcxt); indexRelation->rd_exclops = (Oid*)palloc(sizeof(Oid) * indnkeyatts); indexRelation->rd_exclprocs = (Oid*)palloc(sizeof(Oid) * indnkeyatts); indexRelation->rd_exclstrats = (uint16*)palloc(sizeof(uint16) * indnkeyatts); MemCpy(indexRelation->rd_exclops, ops, sizeof(Oid) * indnkeyatts); MemCpy(indexRelation->rd_exclprocs, funcs, sizeof(Oid) * indnkeyatts); MemCpy(indexRelation->rd_exclstrats, strats, sizeof(uint16) * indnkeyatts); (void)MemoryContextSwitchTo(oldcxt); } /* * load_relcache_init_file, write_relcache_init_file * * In late 1992, we started regularly having databases with more than * a thousand classes in them. With this number of classes, it became * critical to do indexed lookups on the system catalogs. * * Bootstrapping these lookups is very hard. We want to be able to * use an index on pg_attribute, for example, but in order to do so, * we must have read pg_attribute for the attributes in the index, * which implies that we need to use the index. * * In order to get around the problem, we do the following: * * + When the database system is initialized (at initdb time), we * don't use indexes. We do sequential scans. * * + When the backend is started up in normal mode, we load an image * of the appropriate relation descriptors, in internal format, * from an initialization file in the data/base/... directory. * * + If the initialization file isn't there, then we create the * relation descriptors using sequential scans and write 'em to * the initialization file for use by subsequent backends. * * As of Postgres 9.0, there is one local initialization file in each * database, plus one shared initialization file for shared catalogs. * * We could dispense with the initialization files and just build the * critical reldescs the hard way on every backend startup, but that * slows down backend startup noticeably. * * We can in fact go further, and save more relcache entries than * just the ones that are absolutely critical; this allows us to speed * up backend startup by not having to build such entries the hard way. * Presently, all the catalog and index entries that are referred to * by catcaches are stored in the initialization files. * * The same mechanism that detects when catcache and relcache entries * need to be invalidated (due to catalog updates) also arranges to * unlink the initialization files when the contents may be out of date. * The files will then be rebuilt during the next backend startup. */ /* * load_relcache_init_file -- attempt to load cache from the shared * or local cache init file * * If successful, return TRUE and set u_sess->relcache_cxt.criticalRelcachesBuilt or * u_sess->relcache_cxt.criticalSharedRelcachesBuilt to true. * If not successful, return FALSE. * * NOTE: we assume we are already switched into u_sess->cache_mem_cxt. */ static bool load_relcache_init_file(bool shared) { FILE* fp = NULL; char initfilename[MAXPGPATH]; Relation* rels = NULL; int relno, num_rels, max_rels, nailed_rels, nailed_indexes, magic; int i; errno_t rc; if (shared) rc = snprintf_s(initfilename, sizeof(initfilename), sizeof(initfilename) - 1, "global/%s.%u", RELCACHE_INIT_FILENAME, GRAND_VERSION_NUM); else rc = snprintf_s(initfilename, sizeof(initfilename), sizeof(initfilename) - 1, "%s/%s.%u", u_sess->proc_cxt.DatabasePath, RELCACHE_INIT_FILENAME, GRAND_VERSION_NUM); securec_check_ss(rc, "\0", "\0"); fp = AllocateFile(initfilename, PG_BINARY_R); if (fp == NULL) return false; /* * Read the index relcache entries from the file. Note we will not enter * any of them into the cache if the read fails partway through; this * helps to guard against broken init files. */ max_rels = 100; rels = (Relation*)palloc(max_rels * sizeof(Relation)); num_rels = 0; nailed_rels = nailed_indexes = 0; /* check for correct magic number (compatible version) */ if (fread(&magic, 1, sizeof(magic), fp) != sizeof(magic)) goto read_failed; if (magic != RELCACHE_INIT_FILEMAGIC) goto read_failed; for (relno = 0;; relno++) { Size len; size_t nread; Relation rel; Form_pg_class relform; bool has_not_null = false; int default_num; /* first read the relation descriptor length */ nread = fread(&len, 1, sizeof(len), fp); if (nread != sizeof(len)) { if (nread == 0) break; /* end of file */ goto read_failed; } /* safety check for incompatible relcache layout */ if (len != sizeof(RelationData)) goto read_failed; /* allocate another relcache header */ if (num_rels >= max_rels) { max_rels *= 2; rels = (Relation*)repalloc(rels, max_rels * sizeof(Relation)); } rel = rels[num_rels++] = (Relation)palloc(len); /* then, read the Relation structure */ if (fread(rel, 1, len, fp) != len) goto read_failed; /* next read the relation tuple form */ if (fread(&len, 1, sizeof(len), fp) != sizeof(len)) goto read_failed; if (len != CLASS_TUPLE_SIZE) { goto read_failed; } relform = (Form_pg_class)palloc(len); if (fread(relform, 1, len, fp) != len) goto read_failed; rel->rd_rel = relform; /* initialize attribute tuple forms */ //XXTAM: rel->rd_att = CreateTemplateTupleDesc(relform->relnatts, relform->relhasoids, TAM_HEAP); rel->rd_att->tdrefcount = 1; /* mark as refcounted */ rel->rd_att->tdtypeid = relform->reltype; rel->rd_att->tdtypmod = -1; /* unnecessary, but... */ /* next read all the attribute tuple form data entries */ has_not_null = false; default_num = 0; for (i = 0; i < relform->relnatts; i++) { if (fread(&len, 1, sizeof(len), fp) != sizeof(len)) goto read_failed; if (len != ATTRIBUTE_FIXED_PART_SIZE) goto read_failed; if (fread(rel->rd_att->attrs[i], 1, len, fp) != len) goto read_failed; has_not_null = has_not_null || rel->rd_att->attrs[i]->attnotnull; if (rel->rd_att->attrs[i]->atthasdef) { /* * Caution! For autovacuum, catchup and walsender thread, they will return before * calling RelationCacheInitializePhase3, so they cannot load default vaules of adding * new columns during inplace upgrade. * Here, we do not mark those three special threads by increasing default_num, in * case that inconsistent things happen when destroy or rebuild relcache. */ if (!((IsAutoVacuumLauncherProcess() || IsCatchupProcess() || AM_WAL_SENDER) && shared)) default_num++; } } /* next read the access method specific field */ if (fread(&len, 1, sizeof(len), fp) != sizeof(len)) goto read_failed; if (len > 0 && len < MaxAllocSize) { rel->rd_options = (bytea*)palloc(len); if (fread(rel->rd_options, 1, len, fp) != len) goto read_failed; if (len != VARSIZE(rel->rd_options)) goto read_failed; /* sanity check */ } else { rel->rd_options = NULL; } if (RelationIsRedistributeDest(rel)) rel->rd_att->tdisredistable = true; /* mark not-null status */ if (has_not_null || default_num) { TupleConstr* constr = (TupleConstr*)palloc0(sizeof(TupleConstr)); constr->has_not_null = has_not_null; constr->num_defval = default_num; rel->rd_att->constr = constr; } /* If it's an index, there's more to do */ if (RelationIsIndex(rel)) { Form_pg_am am; MemoryContext indexcxt; Oid* opfamily = NULL; Oid* opcintype = NULL; RegProcedure* support = NULL; int nsupport; int16* indoption = NULL; Oid* indcollation = NULL; /* Count nailed indexes to ensure we have 'em all */ if (rel->rd_isnailed) nailed_indexes++; /* next, read the pg_index tuple */ if (fread(&len, 1, sizeof(len), fp) != sizeof(len)) goto read_failed; if (len > HEAPTUPLESIZE + MaxIndexTuplesPerPage) { goto read_failed; } rel->rd_indextuple = (HeapTuple)palloc(len); if (fread(rel->rd_indextuple, 1, len, fp) != len) goto read_failed; /* Fix up internal pointers in the tuple -- see heap_copytuple */ rel->rd_indextuple->t_data = (HeapTupleHeader)((char*)rel->rd_indextuple + HEAPTUPLESIZE); rel->rd_index = (Form_pg_index)GETSTRUCT(rel->rd_indextuple); IndexRelationInitKeyNums(rel); /* next, read the access method tuple form */ if (fread(&len, 1, sizeof(len), fp) != sizeof(len)) goto read_failed; if (len != sizeof(FormData_pg_am)) { goto read_failed; } am = (Form_pg_am)palloc(len); if (fread(am, 1, len, fp) != len) goto read_failed; rel->rd_am = am; /* * prepare index info context --- parameters should match * RelationInitIndexAccessInfo */ indexcxt = AllocSetContextCreate(u_sess->cache_mem_cxt, RelationGetRelationName(rel), ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_SMALL_MAXSIZE); rel->rd_indexcxt = indexcxt; /* next, read the vector of opfamily OIDs */ if (fread(&len, 1, sizeof(len), fp) != sizeof(len)) goto read_failed; if (len > relform->relnatts * sizeof(Oid)) { goto read_failed; } opfamily = (Oid*)MemoryContextAlloc(indexcxt, len); if (fread(opfamily, 1, len, fp) != len) goto read_failed; rel->rd_opfamily = opfamily; /* next, read the vector of opcintype OIDs */ if (fread(&len, 1, sizeof(len), fp) != sizeof(len)) goto read_failed; if (len > relform->relnatts * sizeof(Oid)) { goto read_failed; } opcintype = (Oid*)MemoryContextAlloc(indexcxt, len); if (fread(opcintype, 1, len, fp) != len) goto read_failed; rel->rd_opcintype = opcintype; /* next, read the vector of support procedure OIDs */ if (fread(&len, 1, sizeof(len), fp) != sizeof(len)) goto read_failed; if (len > relform->relnatts * (am->amsupport * sizeof(RegProcedure))) { goto read_failed; } support = (RegProcedure*)MemoryContextAlloc(indexcxt, len); if (fread(support, 1, len, fp) != len) goto read_failed; rel->rd_support = support; /* next, read the vector of collation OIDs */ if (fread(&len, 1, sizeof(len), fp) != sizeof(len)) goto read_failed; if (len > relform->relnatts * sizeof(Oid)) { goto read_failed; } indcollation = (Oid*)MemoryContextAlloc(indexcxt, len); if (fread(indcollation, 1, len, fp) != len) goto read_failed; rel->rd_indcollation = indcollation; /* finally, read the vector of indoption values */ if (fread(&len, 1, sizeof(len), fp) != sizeof(len)) goto read_failed; if (len > relform->relnatts * sizeof(int16)) { goto read_failed; } indoption = (int16*)MemoryContextAlloc(indexcxt, len); if (fread(indoption, 1, len, fp) != len) goto read_failed; rel->rd_indoption = indoption; /* set up zeroed fmgr-info vectors */ rel->rd_aminfo = (RelationAmInfo*)MemoryContextAllocZero(indexcxt, sizeof(RelationAmInfo)); nsupport = relform->relnatts * am->amsupport; rel->rd_supportinfo = (FmgrInfo*)MemoryContextAllocZero(indexcxt, nsupport * sizeof(FmgrInfo)); } else { /* Count nailed rels to ensure we have 'em all */ if (rel->rd_isnailed) nailed_rels++; Assert(rel->rd_index == NULL); Assert(rel->rd_indextuple == NULL); Assert(rel->rd_am == NULL); Assert(rel->rd_indexcxt == NULL); Assert(rel->rd_aminfo == NULL); Assert(rel->rd_opfamily == NULL); Assert(rel->rd_opcintype == NULL); Assert(rel->rd_support == NULL); Assert(rel->rd_supportinfo == NULL); Assert(rel->rd_indoption == NULL); Assert(rel->rd_indcollation == NULL); } /* * Rules and triggers are not saved (mainly because the internal * format is complex and subject to change). They must be rebuilt if * needed by RelationCacheInitializePhase3. This is not expected to * be a big performance hit since few system catalogs have such. Ditto * for index expressions, predicates, exclusion info, and FDW info. */ rel->rd_rules = NULL; rel->rd_rulescxt = NULL; rel->trigdesc = NULL; rel->rd_indexprs = NIL; rel->rd_rlsdesc = NULL; rel->rd_indpred = NIL; rel->rd_exclops = NULL; rel->rd_exclprocs = NULL; rel->rd_exclstrats = NULL; rel->rd_fdwroutine = NULL; /* * Reset transient-state fields in the relcache entry */ rel->rd_smgr = NULL; rel->rd_bucketkey = NULL; rel->rd_bucketoid = InvalidOid; if (rel->rd_isnailed) rel->rd_refcnt = 1; else rel->rd_refcnt = 0; rel->rd_indexvalid = 0; rel->rd_indexlist = NIL; rel->rd_oidindex = InvalidOid; rel->rd_indexattr = NULL; rel->rd_idattr = NULL; rel->rd_createSubid = InvalidSubTransactionId; rel->rd_newRelfilenodeSubid = InvalidSubTransactionId; rel->rd_amcache = NULL; rel->pgstat_info = NULL; /* * Recompute lock and physical addressing info. This is needed in * case the pg_internal.init file was copied from some other database * by CREATE DATABASE. */ RelationInitLockInfo(rel); RelationInitPhysicalAddr(rel); if (rel->rd_rel->relkind == RELKIND_MATVIEW && heap_is_matview_init_state(rel)) rel->rd_isscannable = false; else rel->rd_isscannable = true; } /* * We reached the end of the init file without apparent problem. Did we * get the right number of nailed items? (This is a useful crosscheck in * case the set of critical rels or indexes changes.) */ if (shared) { if (nailed_rels != NUM_CRITICAL_SHARED_RELS || nailed_indexes != NUM_CRITICAL_SHARED_INDEXES) goto read_failed; } else { if (nailed_rels != NUM_CRITICAL_LOCAL_RELS || nailed_indexes != NUM_CRITICAL_LOCAL_INDEXES) goto read_failed; } /* * OK, all appears well. * * Now insert all the new relcache entries into the cache. */ for (relno = 0; relno < num_rels; relno++) { RelationCacheInsert(rels[relno]); /* also make a list of their OIDs, for RelationIdIsInInitFile */ if (!shared) u_sess->relcache_cxt.initFileRelationIds = lcons_oid(RelationGetRelid(rels[relno]), u_sess->relcache_cxt.initFileRelationIds); } pfree_ext(rels); FreeFile(fp); if (shared) u_sess->relcache_cxt.criticalSharedRelcachesBuilt = true; else u_sess->relcache_cxt.criticalRelcachesBuilt = true; return true; /* * init file is broken, so do it the hard way. We don't bother trying to * free the clutter we just allocated; it's not in the relcache so it * won't hurt. */ read_failed: pfree_ext(rels); FreeFile(fp); return false; } /* * Write out a new initialization file with the current contents * of the relcache (either shared rels or local rels, as indicated). */ static void write_relcache_init_file(bool shared) { FILE* fp = NULL; char tempfilename[MAXPGPATH]; char finalfilename[MAXPGPATH]; int magic; HASH_SEQ_STATUS status; RelIdCacheEnt* idhentry = NULL; MemoryContext oldcxt; int i; errno_t rc; /* * We must write a temporary file and rename it into place. Otherwise, * another backend starting at about the same time might crash trying to * read the partially-complete file. * * During inplace or online upgrade, for the first backend that we * launch after we replace new-version gaussdb binary, it would write * a special init file, named as xxx.old_version_num.upgrade, with * all old-version catalog schemas. * Consequent backends launched during upgrade rely on this specific * init file to build catalog relcache. * Then, after upgrade ends, any new backends turn to an init file * named as xxx.new_version_num */ if (shared) { rc = snprintf_s(tempfilename, sizeof(tempfilename), sizeof(tempfilename) - 1, "global/%s.%u.%lu", RELCACHE_INIT_FILENAME, GRAND_VERSION_NUM, t_thrd.proc_cxt.MyProcPid); securec_check_ss(rc, "\0", "\0"); rc = snprintf_s(finalfilename, sizeof(finalfilename), sizeof(finalfilename) - 1, "global/%s.%u", RELCACHE_INIT_FILENAME, GRAND_VERSION_NUM); securec_check_ss(rc, "\0", "\0"); } else { rc = snprintf_s(tempfilename, sizeof(tempfilename), sizeof(tempfilename) - 1, "%s/%s.%u.%lu", u_sess->proc_cxt.DatabasePath, RELCACHE_INIT_FILENAME, GRAND_VERSION_NUM, t_thrd.proc_cxt.MyProcPid); securec_check_ss(rc, "\0", "\0"); rc = snprintf_s(finalfilename, sizeof(finalfilename), sizeof(finalfilename) - 1, "%s/%s.%u", u_sess->proc_cxt.DatabasePath, RELCACHE_INIT_FILENAME, GRAND_VERSION_NUM); securec_check_ss(rc, "\0", "\0"); } unlink(tempfilename); /* in case it exists w/wrong permissions */ fp = AllocateFile(tempfilename, PG_BINARY_W); if (fp == NULL) { /* * We used to consider this a fatal error, but we might as well * continue with backend startup ... */ ereport(WARNING, (errcode_for_file_access(), errmsg("could not create relation-cache initialization file \"%s\": %m", tempfilename), errdetail("Continuing anyway, but there's something wrong."))); return; } /* * Write a magic number to serve as a file version identifier. We can * change the magic number whenever the relcache layout changes. */ magic = RELCACHE_INIT_FILEMAGIC; if (fwrite(&magic, 1, sizeof(magic), fp) != sizeof(magic)) ereport(FATAL, (errmsg("could not write init file"))); /* * Write all the appropriate reldescs (in no particular order). */ hash_seq_init(&status, u_sess->relcache_cxt.RelationIdCache); while ((idhentry = (RelIdCacheEnt*)hash_seq_search(&status)) != NULL) { Relation rel = idhentry->reldesc; Form_pg_class relform = rel->rd_rel; /* ignore if not correct group */ if (relform->relisshared != shared) continue; /* first write the relcache entry proper */ write_item(rel, sizeof(RelationData), fp); /* next write the relation tuple form */ write_item(relform, CLASS_TUPLE_SIZE, fp); /* next, do all the attribute tuple form data entries */ for (i = 0; i < relform->relnatts; i++) { write_item(rel->rd_att->attrs[i], ATTRIBUTE_FIXED_PART_SIZE, fp); } /* next, do the access method specific field */ write_item(rel->rd_options, (rel->rd_options ? VARSIZE(rel->rd_options) : 0), fp); /* If it's an index, there's more to do */ if (RelationIsIndex(rel)) { Form_pg_am am = rel->rd_am; /* write the pg_index tuple */ /* we assume this was created by heap_copytuple! */ write_item(rel->rd_indextuple, HEAPTUPLESIZE + rel->rd_indextuple->t_len, fp); /* next, write the access method tuple form */ write_item(am, sizeof(FormData_pg_am), fp); /* next, write the vector of opfamily OIDs */ write_item(rel->rd_opfamily, relform->relnatts * sizeof(Oid), fp); /* next, write the vector of opcintype OIDs */ write_item(rel->rd_opcintype, relform->relnatts * sizeof(Oid), fp); /* next, write the vector of support procedure OIDs */ write_item(rel->rd_support, relform->relnatts * (am->amsupport * sizeof(RegProcedure)), fp); /* next, write the vector of collation OIDs */ write_item(rel->rd_indcollation, relform->relnatts * sizeof(Oid), fp); /* finally, write the vector of indoption values */ write_item(rel->rd_indoption, relform->relnatts * sizeof(int16), fp); } /* also make a list of their OIDs, for RelationIdIsInInitFile */ if (!shared) { oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); u_sess->relcache_cxt.initFileRelationIds = lcons_oid(RelationGetRelid(rel), u_sess->relcache_cxt.initFileRelationIds); (void)MemoryContextSwitchTo(oldcxt); } } if (FreeFile(fp)) ereport(FATAL, (errmsg("could not write init file"))); /* * Now we have to check whether the data we've so painstakingly * accumulated is already obsolete due to someone else's just-committed * catalog changes. If so, we just delete the temp file and leave it to * the next backend to try again. (Our own relcache entries will be * updated by SI message processing, but we can't be sure whether what we * wrote out was up-to-date.) * * This mustn't run concurrently with the code that unlinks an init file * and sends SI messages, so grab a serialization lock for the duration. */ LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE); /* Make sure we have seen all incoming SI messages */ AcceptInvalidationMessages(); /* * If we have received any SI relcache invals since backend start, assume * we may have written out-of-date data. */ if (u_sess->relcache_cxt.relcacheInvalsReceived == 0L) { /* * OK, rename the temp file to its final name, deleting any * previously-existing init file. * * Note: a failure here is possible under Cygwin, if some other * backend is holding open an unlinked-but-not-yet-gone init file. So * treat this as a noncritical failure; just remove the useless temp * file on failure. */ if (rename(tempfilename, finalfilename) < 0) unlink(tempfilename); } else { /* Delete the already-obsolete temp file */ unlink(tempfilename); } LWLockRelease(RelCacheInitLock); } /* write a chunk of data preceded by its length */ static void write_item(const void* data, Size len, FILE* fp) { if (fwrite(&len, 1, sizeof(len), fp) != sizeof(len)) ereport(FATAL, (errmsg("could not write init file"))); if (fwrite(data, 1, len, fp) != len) ereport(FATAL, (errmsg("could not write init file"))); } /* * Detect whether a given relation (identified by OID) is one of the ones * we store in the local relcache init file. * * Note that we effectively assume that all backends running in a database * would choose to store the same set of relations in the init file; * otherwise there are cases where we'd fail to detect the need for an init * file invalidation. This does not seem likely to be a problem in practice. */ bool RelationIdIsInInitFile(Oid relationId) { return list_member_oid(u_sess->relcache_cxt.initFileRelationIds, relationId); } /* * Invalidate (remove) the init file during commit of a transaction that * changed one or more of the relation cache entries that are kept in the * local init file. * * To be safe against concurrent inspection or rewriting of the init file, * we must take RelCacheInitLock, then remove the old init file, then send * the SI messages that include relcache inval for such relations, and then * release RelCacheInitLock. This serializes the whole affair against * write_relcache_init_file, so that we can be sure that any other process * that's concurrently trying to create a new init file won't move an * already-stale version into place after we unlink. Also, because we unlink * before sending the SI messages, a backend that's currently starting cannot * read the now-obsolete init file and then miss the SI messages that will * force it to update its relcache entries. (This works because the backend * startup sequence gets into the sinval array before trying to load the init * file.) * * We take the lock and do the unlink in RelationCacheInitFilePreInvalidate, * then release the lock in RelationCacheInitFilePostInvalidate. Caller must * send any pending SI messages between those calls. * * Notice this deals only with the local init file, not the shared init file. * The reason is that there can never be a "significant" change to the * relcache entry of a shared relation; the most that could happen is * updates of noncritical fields such as relpages/reltuples. So, while * it's worth updating the shared init file from time to time, it can never * be invalid enough to make it necessary to remove it. */ void RelationCacheInitFilePreInvalidate(void) { char initfilename[MAXPGPATH]; errno_t rc; rc = snprintf_s(initfilename, sizeof(initfilename), sizeof(initfilename) - 1, "%s/%s.%u", u_sess->proc_cxt.DatabasePath, RELCACHE_INIT_FILENAME, GRAND_VERSION_NUM); securec_check_ss(rc, "\0", "\0"); LWLockAcquire(RelCacheInitLock, LW_EXCLUSIVE); if (unlink(initfilename) < 0) { /* * The file might not be there if no backend has been started since * the last removal. But complain about failures other than ENOENT. * Fortunately, it's not too late to abort the transaction if we can't * get rid of the would-be-obsolete init file. */ if (errno != ENOENT) ereport(ERROR, (errcode_for_file_access(), errmsg("could not remove cache file \"%s\": %m", initfilename))); } } void RelationCacheInitFilePostInvalidate(void) { LWLockRelease(RelCacheInitLock); } /* * Remove the init files during postmaster startup. * * We used to keep the init files across restarts, but that is unsafe in PITR * scenarios, and even in simple crash-recovery cases there are windows for * the init files to become out-of-sync with the database. So now we just * remove them during startup and expect the first backend launch to rebuild * them. Of course, this has to happen in each database of the cluster. */ void RelationCacheInitFileRemove(void) { const char* tblspcdir = "pg_tblspc"; DIR* dir = NULL; struct dirent* de = NULL; char path[MAXPGPATH]; errno_t rc; /* * We zap the shared cache file too. In theory it can't get out of sync * enough to be a problem, but in data-corruption cases, who knows ... */ rc = snprintf_s(path, sizeof(path), sizeof(path) - 1, "global/%s.%u", RELCACHE_INIT_FILENAME, GRAND_VERSION_NUM); securec_check_ss(rc, "\0", "\0"); unlink_initfile(path); /* Scan everything in the default tablespace */ RelationCacheInitFileRemoveInDir("base"); /* Scan the tablespace link directory to find non-default tablespaces */ dir = AllocateDir(tblspcdir); if (dir == NULL) { ereport(LOG, (errmsg("could not open tablespace link directory \"%s\": %m", tblspcdir))); return; } while ((de = ReadDir(dir, tblspcdir)) != NULL) { if (strspn(de->d_name, "0123456789") == strlen(de->d_name)) { /* Scan the tablespace dir for per-database dirs */ #ifdef PGXC /* Postgres-XC tablespaces include node name in path */ rc = snprintf_s(path, sizeof(path), sizeof(path) - 1, "%s/%s/%s_%s", tblspcdir, de->d_name, TABLESPACE_VERSION_DIRECTORY, g_instance.attr.attr_common.PGXCNodeName); #else rc = snprintf_s( path, sizeof(path), sizeof(path) - 1, "%s/%s/%s", tblspcdir, de->d_name, TABLESPACE_VERSION_DIRECTORY); #endif securec_check_ss(rc, "\0", "\0"); RelationCacheInitFileRemoveInDir(path); } } FreeDir(dir); } /* Process one per-tablespace directory for RelationCacheInitFileRemove */ static void RelationCacheInitFileRemoveInDir(const char* tblspcpath) { DIR* dir = NULL; struct dirent* de = NULL; char initfilename[MAXPGPATH]; errno_t rc; /* Scan the tablespace directory to find per-database directories */ dir = AllocateDir(tblspcpath); if (dir == NULL) { ereport(LOG, (errmsg("could not open tablespace directory \"%s\": %m", tblspcpath))); return; } while ((de = ReadDir(dir, tblspcpath)) != NULL) { if (strspn(de->d_name, "0123456789") == strlen(de->d_name)) { /* Try to remove the init file in each database */ rc = snprintf_s(initfilename, sizeof(initfilename), sizeof(initfilename) - 1, "%s/%s/%s.%u", tblspcpath, de->d_name, RELCACHE_INIT_FILENAME, GRAND_VERSION_NUM); securec_check_ss(rc, "\0", "\0"); unlink_initfile(initfilename); } } FreeDir(dir); } static void unlink_initfile(const char* initfilename) { if (unlink(initfilename) < 0) { /* It might not be there, but log any error other than ENOENT */ if (errno != ENOENT) ereport(LOG, (errmsg("could not remove cache file \"%s\": %m", initfilename))); } } List* PartitionGetPartIndexList(Partition part) { Relation partrel; SysScanDesc indscan; ScanKeyData skey; HeapTuple parttup; List* result = NULL; Oid oidIndex; MemoryContext oldcxt; /* Quick exit if we already computed the list. */ if (part->pd_indexvalid != 0) { return list_copy(part->pd_indexlist); } /* * We build the list we intend to return (in the caller's context) while * doing the scan. After successfully completing the scan, we copy that * list into the relcache entry. This avoids cache-context memory leakage * if we get some sort of error partway through. */ result = NIL; oidIndex = InvalidOid; /* Prepare to scan pg_partition for entries having indextblid = this rel. */ ScanKeyInit(&skey, Anum_pg_partition_indextblid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(PartitionGetPartid(part))); partrel = heap_open(PartitionRelationId, AccessShareLock); indscan = systable_beginscan(partrel, PartitionIndexTableIdIndexId, true, SnapshotNow, 1, &skey); while (HeapTupleIsValid(parttup = systable_getnext(indscan))) { Form_pg_partition partform = (Form_pg_partition)GETSTRUCT(parttup); Form_pg_index indexform; HeapTuple indexTup; Datum indclassDatum; oidvector* indclass = NULL; bool isnull = false; HeapTuple classTup; /* Search 'partform->parentid' in pg_class */ classTup = SearchSysCache1WithLogLevel(RELOID, ObjectIdGetDatum(partform->parentid), LOG); if (!HeapTupleIsValid(classTup)) { ereport(ERROR, (errcode(ERRCODE_CACHE_LOOKUP_FAILED), (errmsg("cache lookup failed for relation %u", partform->parentid)))); } /* Search indexrelid in pg_index */ indexTup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(HeapTupleGetOid(classTup))); if (!HeapTupleIsValid(indexTup)) { ereport(ERROR, (errcode(ERRCODE_CACHE_LOOKUP_FAILED), (errmsg("cache lookup failed for index %u", HeapTupleGetOid(classTup))))); } indexform = (Form_pg_index)GETSTRUCT(indexTup); /* * Ignore any indexes that are currently being dropped or unusable index */ if (!IndexIsLive(indexform)) { ReleaseSysCache(classTup); ReleaseSysCache(indexTup); continue; } /* Add index's OID to result list in the proper order */ result = insert_ordered_oid(result, HeapTupleGetOid(parttup)); /* * indclass cannot be referenced directly through the C struct, * because it comes after the variable-width indkey field. Must * extract the datum the hard way... */ indclassDatum = heap_getattr(indexTup, Anum_pg_index_indclass, GetPgIndexDescriptor(), &isnull); Assert(!isnull); indclass = (oidvector*)DatumGetPointer(indclassDatum); if (!PointerIsValid(indclass)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Fail to get index key for index with oid %u", PartitionGetPartid(part)))); } /* Check to see if it is a unique, non-partial btree index on OID */ if (indexform->indnatts == 1 && indexform->indisunique && indexform->indimmediate && indexform->indkey.values[0] == ObjectIdAttributeNumber && indclass->values[0] == OID_BTREE_OPS_OID && heap_attisnull(indexTup, Anum_pg_index_indpred, NULL)) { oidIndex = indexform->indexrelid; } ReleaseSysCache(classTup); ReleaseSysCache(indexTup); } systable_endscan(indscan); heap_close(partrel, AccessShareLock); /* Now save a copy of the completed list in the relcache entry. */ oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); if (part->pd_indexlist) { list_free_ext(part->pd_indexlist); } part->pd_indexlist = list_copy(result); part->pd_oidindex = oidIndex; part->pd_indexvalid = 1; (void)MemoryContextSwitchTo(oldcxt); return result; } /* * Brief : Determine whether the given relation is a "Dfs" store(HDFS table). * Input : relation, a "RelationData*" struct. * Output : None. * Return Value : Return true if the relation is Dfs store, otherwise retrun false . * Notes : None. */ bool RelationIsDfsStore(Relation relation) { Oid tablespaceId = InvalidOid; char* optionValue = NULL; bool isHdfsStore = false; Assert(NULL != relation); /* If the table is internal relation, the table would not be Dfs store. */ if (RelationIsInternal(relation)) { return false; } tablespaceId = relation->rd_rel->reltablespace; if (OidIsValid(tablespaceId)) { optionValue = GetTablespaceOptionValue(tablespaceId, TABLESPACE_OPTION_FILESYSTEM); if (optionValue && 0 == pg_strncasecmp(optionValue, HDFS, strlen(HDFS))) { isHdfsStore = true; } } return isHdfsStore; } /* * Brief : check whether the relation is hdfs table. * Input : relation oid * Output : None. * Return Value : ture if the relation is hdfs table, else false * Notes : None. */ bool RelationIsPaxFormatByOid(Oid relid) { bool rs = false; Relation rel; if (!OidIsValid(relid)) return false; rel = try_relation_open(relid, AccessShareLock); if (NULL == rel) return false; rs = RelationIsPAXFormat(rel); relation_close(rel, AccessShareLock); return rs; } bool RelationIsCUFormatByOid(Oid relid) { bool rs = false; Relation rel; if (!OidIsValid(relid)) return false; rel = try_relation_open(relid, AccessShareLock); if (NULL == rel) return false; rs = RelationIsCUFormat(rel); relation_close(rel, AccessShareLock); return rs; } #ifdef ENABLE_MOT /* * Brief : check whether the relation is MOT table. * Input : relation oid * Return Value : ture if the relation is MOT table, else false */ bool RelationIsMOTTableByOid(Oid relid) { return isMOTFromTblOid(relid); } #endif /* * Brief : Check Relation redistribution status in pg_class * Input : relation oid * Output : None. * Return Value : ture if the relation is in redistribution * Notes : None. */ bool CheckRelationInRedistribution(Oid rel_oid) { Relation pgclass; HeapTuple tuple; bool isnull = false; Datum datum; bool ret = false; if (!OidIsValid(rel_oid)) return false; pgclass = heap_open(RelationRelationId, RowShareLock); tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(rel_oid)); if (!HeapTupleIsValid(tuple)) { /* * If do not find 'rel_oid', we report error before like: * ereport(ERROR, (errcode(ERRCODE_CACHE_LOOKUP_FAILED), errmsg("cache lookup failed for partition %u", * rel_oid))); * * But at this time because we do not lock this oid, other process can change it by * 'drop+create the same table then commit'. In this case, we cannot find the oid * but should not report error, and go back to refresh syscahe and get the new oid. */ heap_close(pgclass, RowShareLock); return false; } datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull); ret = CheckRelOptionValue(datum, "append_mode"); ReleaseSysCache(tuple); heap_close(pgclass, RowShareLock); return ret; } /* * Brief : package the meta data of the foreign table. * Input : Relation * Return Value : RelationMetaData*, includs all necessary meta data during scan. * Notes : None. */ RelationMetaData* make_relmeta(Relation rel) { errno_t err = EOK; RelationMetaData* node = makeNode(RelationMetaData); node->rd_id = rel->rd_id; node->spcNode = rel->rd_node.spcNode; node->dbNode = rel->rd_node.dbNode; node->relNode = rel->rd_node.relNode; node->bucketNode = rel->rd_node.bucketNode; node->relname = (char*)palloc0(NAMEDATALEN); err = memcpy_s(node->relname, NAMEDATALEN, rel->rd_rel->relname.data, NAMEDATALEN); securec_check_c(err, "\0", "\0"); node->relkind = rel->rd_rel->relkind; node->parttype = rel->rd_rel->parttype; node->natts = rel->rd_att->natts; for (int i = 0; i < rel->rd_att->natts; i++) { AttrMetaData* attr = makeNode(AttrMetaData); attr->attalign = rel->rd_att->attrs[i]->attalign; attr->attbyval = rel->rd_att->attrs[i]->attbyval; attr->attkvtype = rel->rd_att->attrs[i]->attkvtype; attr->attcmprmode = rel->rd_att->attrs[i]->attcmprmode; attr->attcollation = rel->rd_att->attrs[i]->attcollation; attr->atthasdef = rel->rd_att->attrs[i]->atthasdef; attr->attinhcount = rel->rd_att->attrs[i]->attinhcount; attr->attisdropped = rel->rd_att->attrs[i]->attisdropped; attr->attislocal = rel->rd_att->attrs[i]->attislocal; attr->attnotnull = rel->rd_att->attrs[i]->attnotnull; attr->attlen = rel->rd_att->attrs[i]->attlen; attr->attnum = rel->rd_att->attrs[i]->attnum; attr->attstorage = rel->rd_att->attrs[i]->attstorage; attr->atttypid = rel->rd_att->attrs[i]->atttypid; attr->atttypmod = rel->rd_att->attrs[i]->atttypmod; attr->attname = (char*)palloc0(NAMEDATALEN); err = memcpy_s(attr->attname, NAMEDATALEN, rel->rd_att->attrs[i]->attname.data, NAMEDATALEN); securec_check_c(err, "\0", "\0"); node->attrs = lappend(node->attrs, attr); } return node; } /* * Brief : unpackage the meta data of the foreign table. * Input : RelationMetaData*, includs all necessary meta data during scan. * Return Value : Relation* * Notes : None. */ Relation get_rel_from_meta(RelationMetaData* node) { errno_t rc; ereport(DEBUG1, (errmodule(MOD_ACCELERATE), "sizeof(RelationData): %u, sizeof(FormData_pg_class): %u, sizeof(tupleDesc): %u", sizeof(RelationData), sizeof(FormData_pg_class), sizeof(tupleDesc))); Relation rel = (Relation)palloc0(sizeof(RelationData)); rel->rd_id = node->rd_id; rel->rd_node.spcNode = node->spcNode; rel->rd_node.dbNode = node->dbNode; rel->rd_node.relNode = node->relNode; rel->rd_node.bucketNode = node->bucketNode; rel->rd_rel = (Form_pg_class)palloc0(sizeof(FormData_pg_class)); rel->rd_rel->relkind = node->relkind; rel->rd_rel->parttype = node->parttype; rc = memcpy_s(rel->rd_rel->relname.data, NAMEDATALEN, node->relname, strlen(node->relname)); securec_check(rc, "", ""); /* set tupdesc */ rel->rd_att = CreateTemplateTupleDesc(node->natts, false); rel->rd_att->natts = node->natts; for (int i = 0; i < rel->rd_att->natts; i++) { AttrMetaData* attr = (AttrMetaData*)list_nth(node->attrs, i); rel->rd_att->attrs[i]->attalign = attr->attalign; rel->rd_att->attrs[i]->attbyval = attr->attbyval; rel->rd_att->attrs[i]->attkvtype = attr->attkvtype; rel->rd_att->attrs[i]->attcmprmode = attr->attcmprmode; rel->rd_att->attrs[i]->attcollation = attr->attcollation; rel->rd_att->attrs[i]->atthasdef = attr->atthasdef; rel->rd_att->attrs[i]->attinhcount = attr->attinhcount; rel->rd_att->attrs[i]->attisdropped = attr->attisdropped; rel->rd_att->attrs[i]->attislocal = attr->attislocal; rel->rd_att->attrs[i]->attnotnull = attr->attnotnull; rel->rd_att->attrs[i]->attlen = attr->attlen; rel->rd_att->attrs[i]->attnum = attr->attnum; rel->rd_att->attrs[i]->attstorage = attr->attstorage; rel->rd_att->attrs[i]->atttypid = attr->atttypid; rel->rd_att->attrs[i]->atttypmod = attr->atttypmod; rc = memcpy_s(rel->rd_att->attrs[i]->attname.data, NAMEDATALEN, attr->attname, strlen(attr->attname)); securec_check(rc, "", ""); } return rel; } /* * Brief : Get the relation by the given pg_class tuple and it's schema. * Input : pg_class_tuple, the tuple in pg_class; lockmode, lockmode; tuple_desc, cached schema; pg_index_tuple, the * tuple in pg_index if it is an index. * Return Value : Relation* * Notes : This function is used for timeseries, do not call this function directly. */ Relation tuple_get_rel(HeapTuple pg_class_tuple, LOCKMODE lockmode, TupleDesc tuple_desc, HeapTuple pg_index_tuple) { Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES); MemoryContext oldcxt; Oid relid = HeapTupleGetOid(pg_class_tuple); if (lockmode != NoLock) { LockRelationOid(relid, lockmode); } Form_pg_class relp = (Form_pg_class)GETSTRUCT(pg_class_tuple); /* allocate storage for the relation descriptor, and copy pg_class_tuple to relation->rd_rel. */ Relation relation = AllocateRelationDesc(relp); /* initialize the relation's relation id (relation->rd_id) */ RelationGetRelid(relation) = relid; relation->rd_refcnt = 0; relation->rd_isnailed = false; relation->rd_createSubid = InvalidSubTransactionId; relation->rd_backend = InvalidBackendId; relation->rd_islocaltemp = false; /* initialize the tuple descriptor (relation->rd_att). */ oldcxt = MemoryContextSwitchTo(u_sess->cache_mem_cxt); relation->rd_att = CreateTupleDescCopy(tuple_desc); relation->rd_att->tdtypeid = relation->rd_rel->reltype; relation->rd_att->tdtypmod = -1; relation->rd_att->tdhasoid = relation->rd_rel->relhasoids; (void)MemoryContextSwitchTo(oldcxt); /* set rules and triggers that affect this relation */ relation->rd_rules = NULL; relation->rd_rulescxt = NULL; relation->trigdesc = NULL; /* * If it's an index, initialize index-related information. * We modify RelationInitIndexAccessInfo interface to input index tuple which cached by ourself. */ if (OidIsValid(relation->rd_rel->relam) && pg_index_tuple != NULL) RelationInitIndexAccessInfo(relation, pg_index_tuple); /* extract reloptions if any */ RelationParseRelOptions(relation, pg_class_tuple); /* get row level security policies for this relation */ relation->rd_rlsdesc = NULL; /* fetch bucket info from pgclass tuple */ RelationInitBucketInfo(relation, pg_class_tuple); /* hash bucket columns cannot be changed, so there is no need to rebuild them */ RelationInitBucketKey(relation, pg_class_tuple); relation->parentId = InvalidOid; /* initialize the relation lock manager information */ RelationInitLockInfo(relation); /* see lmgr.c */ /* initialize physical addressing information for the relation */ RelationInitPhysicalAddr(relation); /* make sure relation is marked as having no open file yet */ relation->rd_smgr = NULL; /* It's fully valid */ relation->rd_isvalid = true; pgstat_initstats(relation); RelationCacheInsert(relation); relation->rd_att->tdrefcount = 1; if (RelationIsValid(relation)) { RelationIncrementReferenceCount(relation); } return relation; }
37.368902
139
0.658164
Purlemon
b9ecddb3bd555b813cdc4d54b0a1e8a78a50e843
1,893
cpp
C++
05.cpp
rutujak24/refactored-adventure
0dd886ea866d73641a185c4129d995a93d296e44
[ "MIT" ]
null
null
null
05.cpp
rutujak24/refactored-adventure
0dd886ea866d73641a185c4129d995a93d296e44
[ "MIT" ]
null
null
null
05.cpp
rutujak24/refactored-adventure
0dd886ea866d73641a185c4129d995a93d296e44
[ "MIT" ]
null
null
null
/* Spiral Matrix Given a matrix of size N x M. You have to find the Kth element which will obtain while traversing the matrix spirally starting from the top-left corner of the matrix. Example 1: Input: N = 3, M = 3, K = 4 A[] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Output: 6 Explanation: Spiral traversal of matrix: {1, 2, 3, 6, 9, 8, 7, 4, 5}. Fourth element is 6. Example 2: Input: N = 2, M = 2, K = 2 A[] = {{1, 2}, {3, 4}} Output: 2 Explanation: Spiral traversal of matrix: {1, 2, 4, 3}. Second element is 2. Your Task: You don't need to read input or print anything. Complete the function findK() which takes the matrix A[ ][ ], number of rows N, number of columns M, and integer K as input parameters and returns the Kth element in the spiral traversal of the matrix. Expected Time Complexity: O(N*M) Expected Auxiliary Space: O(1) Constraints: 1 ≤ K ≤ N*M ≤ 106 */ class Solution{ public: int findK(vector<vector<int>> &a, int n, int m, int k) { int i=0, j=0; vector <int> v; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (i<n && j<m ) { /* Print the first row from the remaining rows */ for (int k = j; k < m; k++) { v.push_back(a[i][k]); } i++; for (int k = i; k < n; k++) { v.push_back(a[k][m-1]); } m--; //if(i<n){ for (int k = m-1; k >= j; k--) { v.push_back(a[n-1][k]); } n--; //} //if(j<m){ for (int k = n-1; k >= i; k--) { v.push_back(a[k][j]); } j++; //} } return v[k-1]; } };
20.802198
249
0.48019
rutujak24
b9f1e42e3f78ad5febf4643649c50dd12d91beb0
569
cpp
C++
core/api/service/rpc/requests/methods.cpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
core/api/service/rpc/requests/methods.cpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
core/api/service/rpc/requests/methods.cpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "api/service/rpc/requests/methods.hpp" namespace kagome::api::rpc::request { outcome::result<void> Methods::init( const jsonrpc::Request::Parameters &params) { if (!params.empty()) { throw jsonrpc::InvalidParametersFault("Method should not have params"); } return outcome::success(); } outcome::result<std::vector<std::string>> Methods::execute() { return api_->methods(); } } // namespace kagome::api::rpc::request
23.708333
77
0.667838
igor-egorov
b9f3e5a87401edb01c72c69a32cfc8b43581d6c9
60,529
cpp
C++
EU4toV2/Source/V2World/V2World.cpp
hao9889hao/paradoxGameConverters
fd8bf355781ff102fd75f17d6195dae91450b594
[ "MIT" ]
2
2019-05-19T05:15:28.000Z
2019-05-19T05:18:16.000Z
EU4toV2/Source/V2World/V2World.cpp
hao9889hao/paradoxGameConverters
fd8bf355781ff102fd75f17d6195dae91450b594
[ "MIT" ]
null
null
null
EU4toV2/Source/V2World/V2World.cpp
hao9889hao/paradoxGameConverters
fd8bf355781ff102fd75f17d6195dae91450b594
[ "MIT" ]
null
null
null
/*Copyright (c) 2018 The Paradox Game Converters Project 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 "V2World.h" #include <string> #include <iostream> #include <fstream> #include <algorithm> #include <regex> #include <list> #include <queue> #include <cmath> #include <cfloat> #include "ParadoxParser8859_15.h" #include "ParadoxParserUTF8.h" #include "Log.h" #include "OSCompatibilityLayer.h" #include "../Mappers/AdjacencyMapper.h" #include "../Mappers/CountryMapping.h" #include "../Mappers/CultureMapper.h" #include "../Mappers/IdeaEffectMapper.h" #include "../Mappers/MinorityPopMapper.h" #include "../Mappers/ProvinceMapper.h" #include "../Mappers/ReligionMapper.h" #include "../Mappers/SlaveCultureMapper.h" #include "../Mappers/StateMapper.h" #include "../Mappers/Vic2CultureUnionMapper.h" #include "../Configuration.h" #include "../EU4World/Continents.h" #include "../EU4World/EU4World.h" #include "../EU4World/EU4Relations.h" #include "../EU4World/EU4Leader.h" #include "../EU4World/EU4Province.h" #include "../EU4World/EU4Diplomacy.h" #include "V2Province.h" #include "V2State.h" #include "V2Relations.h" #include "V2Army.h" #include "V2Leader.h" #include "V2Pop.h" #include "V2Country.h" #include "V2Reforms.h" #include "V2Flags.h" #include "V2LeaderTraits.h" V2World::V2World(const EU4::world& sourceWorld) { LOG(LogLevel::Info) << "Parsing Vicky2 data"; importProvinces(); importDefaultPops(); //logPopsByCountry(); findCoastalProvinces(); importPotentialCountries(); importTechSchools(); isRandomWorld = sourceWorld.isRandomWorld(); mappers::CountryMappings::createMappings(sourceWorld, potentialCountries); LOG(LogLevel::Info) << "Converting world"; convertCountries(sourceWorld); convertProvinces(sourceWorld); convertDiplomacy(sourceWorld); setupColonies(); setupStates(); convertUncivReforms(sourceWorld); convertTechs(sourceWorld); allocateFactories(sourceWorld); setupPops(sourceWorld); addUnions(); convertArmies(sourceWorld); checkForCivilizedNations(); output(); } void V2World::importProvinces() { LOG(LogLevel::Info) << "Importing provinces"; set<string> provinceFilenames = discoverProvinceFilenames(); for (auto provinceFilename : provinceFilenames) { V2Province* newProvince = new V2Province(provinceFilename); provinces.insert(make_pair(newProvince->getNum(), newProvince)); } if (Utils::DoesFileExist("./blankMod/output/localisation/text.csv")) { importProvinceLocalizations("./blankMod/output/localisation/text.csv"); } else { importProvinceLocalizations((Configuration::getV2Path() + "/localisation/text.csv")); } } set<string> V2World::discoverProvinceFilenames() { set<string> provinceFilenames; Utils::GetAllFilesInFolderRecursive("./blankMod/output/history/provinces", provinceFilenames); if (provinceFilenames.empty()) { Utils::GetAllFilesInFolderRecursive(Configuration::getV2Path() + "/history/provinces", provinceFilenames); } return provinceFilenames; } void V2World::importProvinceLocalizations(const string& file) { ifstream read(file); while (read.good() && !read.eof()) { string line; getline(read, line); if (isAProvinceLocalization(line)) { int position = line.find_first_of(';'); int num = stoi(line.substr(4, position - 4)); string name = line.substr(position + 1, line.find_first_of(';', position + 1) - position - 1); auto provice = provinces.find(num); if (provice != provinces.end()) { provice->second->setName(name); } } } read.close(); } bool V2World::isAProvinceLocalization(const string& line) { return (line.substr(0, 4) == "PROV") && (isdigit(line[4])); } void V2World::importDefaultPops() { LOG(LogLevel::Info) << "Importing historical pops."; totalWorldPopulation = 0; set<string> filenames; Utils::GetAllFilesInFolder("./blankMod/output/history/pops/1836.1.1/", filenames); for (auto filename : filenames) { importPopsFromFile(filename); } } void V2World::importPopsFromFile(const string& filename) { list<int> popProvinces; shared_ptr<Object> fileObj = parser_8859_15::doParseFile(("./blankMod/output/history/pops/1836.1.1/" + filename)); vector<shared_ptr<Object>> provinceObjs = fileObj->getLeaves(); for (auto provinceObj : provinceObjs) { int provinceNum = stoi(provinceObj->getKey()); popProvinces.push_back(provinceNum); importPopsFromProvince(provinceObj); } popRegions.insert(make_pair(filename, popProvinces)); } void V2World::importPopsFromProvince(shared_ptr<Object> provinceObj) { int provinceNum = stoi(provinceObj->getKey()); auto province = provinces.find(provinceNum); if (province == provinces.end()) { LOG(LogLevel::Warning) << "Could not find province " << provinceNum << " for original pops."; return; } int provincePopulation = 0; int provinceSlavePopulation = 0; vector<shared_ptr<Object>> popObjs = provinceObj->getLeaves(); for (auto popObj: popObjs) { V2Pop* newPop = new V2Pop(popObj); province->second->addOldPop(newPop); if (minorityPopMapper::matchMinorityPop(newPop)) { province->second->addMinorityPop(newPop); } totalWorldPopulation += newPop->getSize(); provincePopulation += newPop->getSize(); if (newPop->isSlavePop()) { provinceSlavePopulation += newPop->getSize(); } } province->second->setSlaveProportion(1.0 * provinceSlavePopulation / provincePopulation); } void V2World::logPopsByCountry() const { map<string, map<string, long int>> popsByCountry; // country, poptype, num set<string> filenames; Utils::GetAllFilesInFolder("./blankMod/output/history/pops/1836.1.1/", filenames); for (auto filename : filenames) { logPopsFromFile(filename, popsByCountry); } outputLog(popsByCountry); } void V2World::logPopsFromFile(string filename, map<string, map<string, long int>>& popsByCountry) const { shared_ptr<Object> fileObj = parser_8859_15::doParseFile(("./blankMod/output/history/pops/1836.1.1/" + filename)); vector<shared_ptr<Object>> provinceObjs = fileObj->getLeaves(); for (auto provinceObj : provinceObjs) { logPopsInProvince(provinceObj, popsByCountry); } } void V2World::logPopsInProvince(shared_ptr<Object> provinceObj, map<string, map<string, long int>>& popsByCountry) const { int provinceNum = stoi(provinceObj->getKey()); auto province = provinces.find(provinceNum); if (province == provinces.end()) { LOG(LogLevel::Warning) << "Could not find province " << provinceNum << " for original pops."; return; } auto countryPopItr = getCountryForPopLogging(province->second->getOwner(), popsByCountry); vector<shared_ptr<Object>> pops = provinceObj->getLeaves(); for (auto pop : pops) { logPop(pop, countryPopItr); } } void V2World::logPop(shared_ptr<Object> pop, map<string, map<string, long int>>::iterator countryPopItr) const { string popType = pop->getKey(); auto possibleSizeStr = pop->getLeaf("size"); if (possibleSizeStr) { int popSize = stoi(*possibleSizeStr); auto popItr = countryPopItr->second.find(pop->getKey()); if (popItr == countryPopItr->second.end()) { long int newPopSize = 0; pair<map<string, long int>::iterator, bool> newIterator = countryPopItr->second.insert(make_pair(popType, newPopSize)); popItr = newIterator.first; } popItr->second += popSize; } } map<string, map<string, long int>>::iterator V2World::getCountryForPopLogging(string country, map<string, map<string, long int>>& popsByCountry) const { auto countryPopItr = popsByCountry.find(country); if (countryPopItr == popsByCountry.end()) { map<string, long int> newCountryPop; auto newIterator = popsByCountry.insert(make_pair(country, newCountryPop)); countryPopItr = newIterator.first; } return countryPopItr; } void V2World::outputLog(const map<string, map<string, long int>>& popsByCountry) const { for (auto countryItr : popsByCountry) { long int total = 0; for (auto popsItr : countryItr.second) { total += popsItr.second; } for (auto popsItr : countryItr.second) { LOG(LogLevel::Info) << "," << countryItr.first << "," << popsItr.first << "," << popsItr.second << "," << static_cast<double>(popsItr.second / total); } LOG(LogLevel::Info) << "," << countryItr.first << "," << "Total," << total << "," << static_cast<double>(total / total); } } void V2World::findCoastalProvinces() { LOG(LogLevel::Info) << "Finding coastal provinces."; shared_ptr<Object> positionsObj = parser_8859_15::doParseFile((Configuration::getV2Path() + "/map/positions.txt")); if (positionsObj == nullptr) { LOG(LogLevel::Error) << "Could not parse file " << Configuration::getV2Path() << "/map/positions.txt"; exit(-1); } vector<shared_ptr<Object>> provinceObjs = positionsObj->getLeaves(); for (auto provinceObj: provinceObjs) { determineIfProvinceIsCoastal(provinceObj); } } void V2World::determineIfProvinceIsCoastal(shared_ptr<Object> provinceObj) { vector<shared_ptr<Object>> positionObj = provinceObj->getValue("building_position"); if (positionObj.size() > 0) { vector<shared_ptr<Object>> navalBaseObj = positionObj[0]->getValue("naval_base"); if (navalBaseObj.size() > 0) { int provinceNum = stoi(provinceObj->getKey()); auto province = provinces.find(provinceNum); if (province != provinces.end()) { province->second->setCoastal(true); } } } } void V2World::importPotentialCountries() { LOG(LogLevel::Info) << "Getting potential countries"; potentialCountries.clear(); dynamicCountries.clear(); ifstream V2CountriesInput; V2CountriesInput.open("./blankMod/output/common/countries.txt"); if (!V2CountriesInput.is_open()) { LOG(LogLevel::Error) << "Could not open countries.txt. The converter may be corrupted, try downloading it again."; exit(-1); } bool dynamicSection = false; while (!V2CountriesInput.eof()) { string line; getline(V2CountriesInput, line); if ((line[0] == '#') || (line.size() < 3)) { continue; } else if (line.substr(0, 12) == "dynamic_tags") { dynamicSection = true; continue; } importPotentialCountry(line, dynamicSection); } V2CountriesInput.close(); } void V2World::importPotentialCountry(const string& line, bool dynamicCountry) { string tag = line.substr(0, 3); V2Country* newCountry = new V2Country(line, this, dynamicCountry); potentialCountries.insert(make_pair(tag, newCountry)); if (dynamicCountry) { dynamicCountries.insert(make_pair(tag, newCountry)); } } void V2World::importTechSchools() { LOG(LogLevel::Info) << "Importing tech schools."; techSchools = initTechSchools(); } void V2World::convertCountries(const EU4::world& sourceWorld) { LOG(LogLevel::Info) << "Converting countries"; initializeCountries(sourceWorld); convertNationalValues(); convertPrestige(); addAllPotentialCountries(); } void V2World::initializeCountries(const EU4::world& sourceWorld) { for (auto sourceCountry: sourceWorld.getCountries()) { const string& V2Tag = mappers::CountryMappings::getVic2Tag(sourceCountry.first); if (V2Tag == "") { LOG(LogLevel::Error) << "EU4 tag " << sourceCountry.first << " is unmapped and cannot be converted."; exit(-1); } V2Country* destCountry = createOrLocateCountry(V2Tag, sourceCountry.second); destCountry->initFromEU4Country(sourceCountry.second, techSchools, leaderIDMap); countries.insert(make_pair(V2Tag, destCountry)); } } V2Country* V2World::createOrLocateCountry(const string& V2Tag, const shared_ptr<EU4::Country> sourceCountry) { V2Country* destCountry = nullptr; auto potentialCountry = potentialCountries.find(V2Tag); if (potentialCountry == potentialCountries.end()) { string countryFileName = sourceCountry->getName() + ".txt"; destCountry = new V2Country(V2Tag, countryFileName, this); } else { destCountry = potentialCountry->second; } return destCountry; } bool scoresSorter(pair<V2Country*, int> first, pair<V2Country*, int> second) { return (first.second > second.second); } void V2World::convertNationalValues() { // set national values list< pair<V2Country*, int> > libertyScores; list< pair<V2Country*, int> > equalityScores; set<V2Country*> valuesUnset; for (map<string, V2Country*>::iterator countryItr = countries.begin(); countryItr != countries.end(); countryItr++) { int libertyScore = 1; int equalityScore = 1; int orderScore = 1; countryItr->second->getNationalValueScores(libertyScore, equalityScore, orderScore); if (libertyScore > orderScore) { libertyScores.push_back(make_pair(countryItr->second, libertyScore)); } if ((equalityScore > orderScore) && (equalityScore > libertyScore)) { equalityScores.push_back(make_pair(countryItr->second, equalityScore)); } valuesUnset.insert(countryItr->second); LOG(LogLevel::Debug) << "Value scores for " << countryItr->first << ": order = " << orderScore << ", liberty = " << libertyScore << ", equality = " << equalityScore; } equalityScores.sort(scoresSorter); int equalityLeft = 5; for (list< pair<V2Country*, int> >::iterator equalItr = equalityScores.begin(); equalItr != equalityScores.end(); equalItr++) { if (equalityLeft < 1) { break; } set<V2Country*>::iterator unsetItr = valuesUnset.find(equalItr->first); if (unsetItr != valuesUnset.end()) { valuesUnset.erase(unsetItr); equalItr->first->setNationalValue("nv_equality"); equalityLeft--; LOG(LogLevel::Debug) << equalItr->first->getTag() << " got national value equality"; } } libertyScores.sort(scoresSorter); int libertyLeft = 20; for (list< pair<V2Country*, int> >::iterator libItr = libertyScores.begin(); libItr != libertyScores.end(); libItr++) { if (libertyLeft < 1) { break; } set<V2Country*>::iterator unsetItr = valuesUnset.find(libItr->first); if (unsetItr != valuesUnset.end()) { valuesUnset.erase(unsetItr); libItr->first->setNationalValue("nv_liberty"); libertyLeft--; LOG(LogLevel::Debug) << libItr->first->getTag() << " got national value liberty"; } } for (set<V2Country*>::iterator unsetItr = valuesUnset.begin(); unsetItr != valuesUnset.end(); unsetItr++) { (*unsetItr)->setNationalValue("nv_order"); LOG(LogLevel::Debug) << (*unsetItr)->getTag() << " got national value order"; } } void V2World::convertPrestige() { LOG(LogLevel::Debug) << "Setting prestige"; double highestScore = 0.0; for (map<string, V2Country*>::iterator countryItr = countries.begin(); countryItr != countries.end(); countryItr++) { double score = 0.0; auto srcCountry = countryItr->second->getSourceCountry(); if (srcCountry != nullptr) { score = srcCountry->getScore(); } if (score > highestScore) { highestScore = score; } } for (map<string, V2Country*>::iterator countryItr = countries.begin(); countryItr != countries.end(); countryItr++) { double score = 0.0; auto srcCountry = countryItr->second->getSourceCountry(); if (srcCountry != nullptr) { score = srcCountry->getScore(); } double prestige = (score * 99.0 / highestScore) + 1; countryItr->second->addPrestige(prestige); LOG(LogLevel::Debug) << countryItr->first << " had " << prestige << " prestige"; } } void V2World::addAllPotentialCountries() { // ALL potential countries should be output to the file, otherwise some things don't get initialized right when loading Vic2 for (auto potentialCountry : potentialCountries) { map<string, V2Country*>::iterator citr = countries.find(potentialCountry.first); if (citr == countries.end()) { potentialCountry.second->initFromHistory(); countries.insert(make_pair(potentialCountry.first, potentialCountry.second)); } } } void V2World::checkForCivilizedNations() { unsigned int numPotentialGPs = 0; for (auto country : countries) { auto states = country.second->getStates(); if ((country.second->isCivilized())&&(states.size() > 1)) { numPotentialGPs++; } } if (numPotentialGPs < 8) { LOG(LogLevel::Info) << "There were only " << numPotentialGPs << " civilized nations with more than 1 state. Attempting to editing defines.lua to reduce the number of great powers."; editDefines(numPotentialGPs); } } void V2World::editDefines(int numCivilisedNations) { string greatNationsCount = "8"; LOG(LogLevel::Info) << "Parsing defines.lua"; shared_ptr<Object> definesObj = parser_UTF8::doParseFile("blankmod/output/common/defines.lua"); if (definesObj == nullptr) { LOG(LogLevel::Error) << "Could not parse file defines.lua"; exit(-1); } vector<shared_ptr<Object>> newDefinesObj = definesObj->getValue("defines"); vector<shared_ptr<Object>> countryObj = newDefinesObj[0]->getValue("country"); if (countryObj.size() > 0) { vector<shared_ptr<Object>> countryLeaves = countryObj[0]->getLeaves(); for (unsigned int j = 0; j < countryLeaves.size(); j++) { string keyCoun = countryLeaves[j]->getKey(); // the key if (keyCoun == "GREAT_NATIONS_COUNT") { greatNationsCount = numCivilisedNations; countryLeaves[j]->setValue(greatNationsCount); // sets the number of GPs = number of civilised nations } else { continue; } } } else { LOG(LogLevel::Warning) << "Invalid file structure for defines.lua. You should edit this file yourself in [yourmod]/common"; } } struct MTo1ProvinceComp { vector<EU4Province*> provinces; }; void V2World::convertProvinces(const EU4::world& sourceWorld) { LOG(LogLevel::Info) << "Converting provinces"; for (auto Vic2Province : provinces) { auto EU4ProvinceNumbers = provinceMapper::getEU4ProvinceNumbers(Vic2Province.first); if (EU4ProvinceNumbers.size() == 0) { LOG(LogLevel::Warning) << "No source for " << Vic2Province.second->getName() << " (province " << Vic2Province.first << ')'; continue; } else if (EU4ProvinceNumbers[0] == 0) { continue; } else if ((Configuration::getResetProvinces() == "yes") && provinceMapper::isProvinceResettable(Vic2Province.first)) { Vic2Province.second->setResettable(true); continue; } Vic2Province.second->clearCores(); EU4Province* oldProvince = nullptr; shared_ptr<EU4::Country> oldOwner; // determine ownership by province count, or total population (if province count is tied) map<string, MTo1ProvinceComp> provinceBins; double newProvinceTotalBaseTax = 0; for (auto EU4ProvinceNumber : EU4ProvinceNumbers) { EU4Province* province = sourceWorld.getProvince(EU4ProvinceNumber); if (!province) { LOG(LogLevel::Warning) << "Old province " << EU4ProvinceNumber << " does not exist (bad mapping?)"; continue; } auto owner = province->getOwner(); string tag; if (owner != nullptr) { tag = owner->getTag(); } else { tag = ""; } if (provinceBins.find(tag) == provinceBins.end()) { provinceBins[tag] = MTo1ProvinceComp(); } if (((Configuration::getV2Gametype() == "HOD") || (Configuration::getV2Gametype() == "HoD-NNM")) && false && (owner != nullptr)) { auto stateIndex = stateMapper::getStateIndex(Vic2Province.first); if (stateIndex == -1) { LOG(LogLevel::Warning) << "Could not find state index for province " << Vic2Province.first; continue; } else { map<int, set<string>>::iterator colony = colonies.find(stateIndex); if (colony == colonies.end()) { set<string> countries; countries.insert(owner->getTag()); colonies.insert(make_pair(stateIndex, countries)); } else { colony->second.insert(owner->getTag()); } } } else { provinceBins[tag].provinces.push_back(province); newProvinceTotalBaseTax += province->getBaseTax(); // I am the new owner if there is no current owner, or I have more provinces than the current owner, // or I have the same number of provinces, but more population, than the current owner if ( (oldOwner == nullptr) || (provinceBins[tag].provinces.size() > provinceBins[oldOwner->getTag()].provinces.size()) || (provinceBins[tag].provinces.size() == provinceBins[oldOwner->getTag()].provinces.size()) ) { oldOwner = owner; oldProvince = province; } } } if (oldOwner == nullptr) { Vic2Province.second->setOwner(""); continue; } const std::string& V2Tag = mappers::CountryMappings::getVic2Tag(oldOwner->getTag()); if (V2Tag.empty()) { LOG(LogLevel::Warning) << "Could not map provinces owned by " << oldOwner->getTag(); } else { Vic2Province.second->setOwner(V2Tag); map<string, V2Country*>::iterator ownerItr = countries.find(V2Tag); if (ownerItr != countries.end()) { ownerItr->second->addProvince(Vic2Province.second); } Vic2Province.second->convertFromOldProvince(oldProvince); for (map<string, MTo1ProvinceComp>::iterator mitr = provinceBins.begin(); mitr != provinceBins.end(); ++mitr) { for (vector<EU4Province*>::iterator vitr = mitr->second.provinces.begin(); vitr != mitr->second.provinces.end(); ++vitr) { // assign cores vector<shared_ptr<EU4::Country>> oldCores = (*vitr)->getCores(sourceWorld.getCountries()); for (auto j = oldCores.begin(); j != oldCores.end(); j++) { std::string coreEU4Tag = (*j)->getTag(); // skip this core if the country is the owner of the EU4 province but not the V2 province // (i.e. "avoid boundary conflicts that didn't exist in EU4"). // this country may still get core via a province that DID belong to the current V2 owner if ((coreEU4Tag == mitr->first) && (coreEU4Tag != oldOwner->getTag())) { continue; } const std::string& coreV2Tag = mappers::CountryMappings::getVic2Tag(coreEU4Tag); if (!coreV2Tag.empty()) { Vic2Province.second->addCore(coreV2Tag); } } // determine demographics double provPopRatio = (*vitr)->getBaseTax() / newProvinceTotalBaseTax; auto popRatios = (*vitr)->getPopRatios(); vector<V2Demographic> demographics = determineDemographics(popRatios, *vitr, Vic2Province.second, oldOwner, Vic2Province.first, provPopRatio); for (auto demographic : demographics) { Vic2Province.second->addPopDemographic(demographic); } // set forts and naval bases if ((*vitr)->hasBuilding("fort4") || (*vitr)->hasBuilding("fort5") || (*vitr)->hasBuilding("fort6")) { Vic2Province.second->setFortLevel(1); } } } } } } vector<V2Demographic> V2World::determineDemographics(vector<EU4PopRatio>& popRatios, EU4Province* eProv, V2Province* vProv, shared_ptr<EU4::Country> oldOwner, int destNum, double provPopRatio) { vector<V2Demographic> demographics; for (auto prItr : popRatios) { string dstCulture = "no_culture"; bool matched = mappers::cultureMapper::cultureMatch(prItr.culture, dstCulture, prItr.religion, eProv->getNum(), oldOwner->getTag()); if (!matched) { LOG(LogLevel::Warning) << "Could not set culture for pops in Vic2 province " << destNum; } string religion = religionMapper::getVic2Religion(prItr.religion);; if (religion == "") { LOG(LogLevel::Warning) << "Could not set religion for pops in Vic2 province " << destNum; } string slaveCulture = ""; matched = mappers::slaveCultureMapper::cultureMatch(prItr.culture, slaveCulture, prItr.religion, eProv->getNum(), oldOwner->getTag());; if (!matched) { auto thisContinent = EU4::continents::getEU4Continent(eProv->getNum()); if ((thisContinent) && ((thisContinent == "asia") || (thisContinent == "oceania"))) { //LOG(LogLevel::Warning) << "No mapping for slave culture in province " << destNum << " - using native culture (" << prItr.culture << ")."; slaveCulture = prItr.culture; } else { //LOG(LogLevel::Warning) << "No mapping for slave culture for pops in Vic2 province " << destNum << " - using african_minor."; slaveCulture = "african_minor"; } } V2Demographic demographic; demographic.culture = dstCulture; demographic.slaveCulture = slaveCulture; demographic.religion = religion; demographic.upperRatio = prItr.upperPopRatio * provPopRatio; demographic.middleRatio = prItr.middlePopRatio * provPopRatio; demographic.lowerRatio = prItr.lowerPopRatio * provPopRatio; demographic.oldCountry = oldOwner; demographic.oldProvince = eProv; //LOG(LogLevel::Info) << "EU4 Province " << eProv->getNum() << ", Vic2 Province " << vProv->getNum() << ", Culture: " << culture << ", Religion: " << religion << ", upperPopRatio: " << prItr.upperPopRatio << ", middlePopRatio: " << prItr.middlePopRatio << ", lowerPopRatio: " << prItr.lowerPopRatio << ", provPopRatio: " << provPopRatio << ", upperRatio: " << demographic.upperRatio << ", middleRatio: " << demographic.middleRatio << ", lowerRatio: " << demographic.lowerRatio; demographics.push_back(demographic); } return demographics; } void V2World::convertDiplomacy(const EU4::world& sourceWorld) { LOG(LogLevel::Info) << "Converting diplomacy"; vector<EU4Agreement> agreements = sourceWorld.getDiplomaticAgreements(); for (vector<EU4Agreement>::iterator itr = agreements.begin(); itr != agreements.end(); ++itr) { const std::string& EU4Tag1 = itr->country1; const std::string& V2Tag1 = mappers::CountryMappings::getVic2Tag(EU4Tag1); if (V2Tag1.empty()) { continue; } const std::string& EU4Tag2 = itr->country2; const std::string& V2Tag2 = mappers::CountryMappings::getVic2Tag(EU4Tag2); if (V2Tag2.empty()) { continue; } map<string, V2Country*>::iterator country1 = countries.find(V2Tag1); map<string, V2Country*>::iterator country2 = countries.find(V2Tag2); if (country1 == countries.end()) { LOG(LogLevel::Warning) << "Vic2 country " << V2Tag1 << " used in diplomatic agreement doesn't exist"; continue; } if (country2 == countries.end()) { LOG(LogLevel::Warning) << "Vic2 country " << V2Tag2 << " used in diplomatic agreement doesn't exist"; continue; } V2Relations* r1 = country1->second->getRelations(V2Tag2); if (!r1) { r1 = new V2Relations(V2Tag2); country1->second->addRelation(r1); } V2Relations* r2 = country2->second->getRelations(V2Tag1); if (!r2) { r2 = new V2Relations(V2Tag1); country2->second->addRelation(r2); } if (itr->type == "is_colonial"|| itr->type == "colony") { country2->second->setColonyOverlord(country1->second); if (country2->second->getSourceCountry()->getLibertyDesire() < Configuration::getLibertyThreshold()) { country1->second->absorbVassal(country2->second); for (vector<EU4Agreement>::iterator itr2 = agreements.begin(); itr2 != agreements.end(); ++itr2) { if (itr2->country2 == country2->second->getSourceCountry()->getTag()) { itr2->country2 == country1->second->getSourceCountry()->getTag(); } } } else { V2Agreement v2a; v2a.country1 = V2Tag1; v2a.country2 = V2Tag2; v2a.start_date = itr->startDate; v2a.type = "vassal"; diplomacy.addAgreement(v2a); r1->setLevel(5); } } if ((itr->type == "is_march") || (itr->type == "march")) { country1->second->absorbVassal(country2->second); for (vector<EU4Agreement>::iterator itr2 = agreements.begin(); itr2 != agreements.end(); ++itr2) { if (itr2->country1 == country2->second->getSourceCountry()->getTag()) { itr2->country1 = country1->second->getSourceCountry()->getTag(); } } } if ((itr->type == "royal_marriage") || (itr->type == "guarantee")) { // influence level +1, but never exceed 4 if (r1->getLevel() < 4) { r1->setLevel(r1->getLevel() + 1); } } if (itr->type == "royal_marriage") { // royal marriage is bidirectional; influence level +1, but never exceed 4 if (r2->getLevel() < 4) { r2->setLevel(r2->getLevel() + 1); } } if ((itr->type == "vassal") || (itr->type == "client_vassal") || (itr->type == "daimyo_vassal") || (itr->type == "union") || (itr->type == "personal_union") || (itr->type == "protectorate") || (itr->type == "tributary_state")) { // influence level = 5 r1->setLevel(5); /* FIXME: is this desirable? // if relations are too poor, country2 will immediately eject country1's ambassadors at the start of the game // so, for stability's sake, give their relations a boost if (r1->getRelations() < 1) r1->setRelations(1); if (r2->getRelations() < 1) r2->setRelations(1); */ } if ((itr->type == "alliance") || (itr->type == "vassal") || (itr->type == "client_vassal") || (itr->type == "daimyo_vassal") || (itr->type == "union") || (itr->type == "personal_union") || (itr->type == "guarantee")) { // copy agreement V2Agreement v2a; v2a.country1 = V2Tag1; v2a.country2 = V2Tag2; v2a.start_date = itr->startDate; v2a.type = itr->type; diplomacy.addAgreement(v2a); } } } void V2World::setupColonies() { LOG(LogLevel::Info) << "Setting colonies"; for (map<string, V2Country*>::iterator countryItr = countries.begin(); countryItr != countries.end(); countryItr++) { // find all land connections to capitals map<int, V2Province*> openProvinces = provinces; queue<int> goodProvinces; map<int, V2Province*>::iterator openItr = openProvinces.find(countryItr->second->getCapital()); if (openItr == openProvinces.end()) { continue; } if (openItr->second->getOwner() != countryItr->first) // if the capital is not owned, don't bother running { continue; } openItr->second->setLandConnection(true); goodProvinces.push(openItr->first); openProvinces.erase(openItr); do { int currentProvince = goodProvinces.front(); goodProvinces.pop(); auto adjacencies = mappers::adjacencyMapper::getVic2Adjacencies(currentProvince); if (adjacencies) { for (auto adjacency: *adjacencies) { auto openItr = openProvinces.find(adjacency); if (openItr == openProvinces.end()) { continue; } if (openItr->second->getOwner() != countryItr->first) { continue; } openItr->second->setLandConnection(true); goodProvinces.push(openItr->first); openProvinces.erase(openItr); } } } while (goodProvinces.size() > 0); // find all provinces on the same continent as the owner's capital std::optional<std::string> capitalContinent; map<int, V2Province*>::iterator capital = provinces.find(countryItr->second->getCapital()); if (capital != provinces.end()) { const EU4Province* capitalSrcProv = capital->second->getSrcProvince(); if (!capitalSrcProv) continue; int capitalSrc = capitalSrcProv->getNum(); capitalContinent = EU4::continents::getEU4Continent(capitalSrc); if (!capitalContinent) { continue; } } else { continue; } auto ownedProvinces = countryItr->second->getProvinces(); for (auto provItr = ownedProvinces.begin(); provItr != ownedProvinces.end(); provItr++) { const EU4Province* provSrcProv = provItr->second->getSrcProvince(); if (!provSrcProv) continue; int provSrc = provSrcProv->getNum(); std::optional<std::string> continent = EU4::continents::getEU4Continent(provSrc); if ((continent) && (continent == capitalContinent)) { provItr->second->setSameContinent(true); } } } for (map<int, V2Province*>::iterator provItr = provinces.begin(); provItr != provinces.end(); provItr++) { provItr->second->determineColonial(); } } static int stateId = 0; void V2World::setupStates() { LOG(LogLevel::Info) << "Creating states"; list<V2Province*> unassignedProvs; for (map<int, V2Province*>::iterator itr = provinces.begin(); itr != provinces.end(); ++itr) { unassignedProvs.push_back(itr->second); } LOG(LogLevel::Debug) << "Unassigned Provs:\t" << unassignedProvs.size(); list<V2Province*>::iterator iter; while (unassignedProvs.size() > 0) { iter = unassignedProvs.begin(); int provId = (*iter)->getNum(); string owner = (*iter)->getOwner(); if (owner == "") { unassignedProvs.erase(iter); continue; } V2State* newState = new V2State(stateId, *iter); stateId++; vector<int> neighbors = stateMapper::getOtherProvincesInState(provId); LOG(LogLevel::Debug) << "Neighbors size" << neighbors.size(); bool colonial = (*iter)->isColonial(); newState->setColonial(colonial); iter = unassignedProvs.erase(iter); for (vector<int>::iterator i = neighbors.begin(); i != neighbors.end(); i++) { for (iter = unassignedProvs.begin(); iter != unassignedProvs.end(); iter++) { if ((*iter)->getNum() == *i) { if ((*iter)->getOwner() == owner) { if ((*iter)->isColonial() == colonial) { newState->addProvince(*iter); LOG(LogLevel::Debug) << (*iter)->getName() << " added to " << newState->getID(); iter = unassignedProvs.erase(iter); } } } } } newState->colloectNavalBase(); map<string, V2Country*>::iterator iter2 = countries.find(owner); if (iter2 != countries.end()) { iter2->second->addState(newState); } } } void V2World::convertUncivReforms(const EU4::world& sourceWorld) { LOG(LogLevel::Info) << "Setting unciv reforms"; // tech group enum civConversion { older, newer }; civConversion techGroupAlgoritm = newer; double topTech = 96; int topInstitutions = 7; auto version18 = EU4Version("1.18.0"); if (*(sourceWorld.getVersion()) >= version18) { LOG(LogLevel::Info) << "New tech group conversion method"; techGroupAlgorithm = newer; // Find global max tech and institutions embraced auto sourceCountries = sourceWorld.getCountries(); auto i = sourceCountries.begin(); while (i->second->getProvinces().size() == 0) i++; // Take max from the first country auto currCountry = i->second; double totalTechs = currCountry->getMilTech() + currCountry->getAdmTech() + currCountry->getDipTech(); topTech = totalTechs; int currInstitutions = currCountry->numEmbracedInstitutions(); topInstitutions = currInstitutions; int num = 2; // Calculate max for (i++; i != sourceCountries.end(); i++) { currCountry = i->second; if (currCountry->getProvinces().size() == 0) continue; totalTechs = currCountry->getMilTech() + currCountry->getAdmTech() + currCountry->getDipTech(); if (totalTechs > topTech) topTech = totalTechs; currInstitutions = currCountry->numEmbracedInstitutions(); if (currInstitutions > topInstitutions) topInstitutions = currInstitutions; num++; } } else { LOG(LogLevel::Info) << "Old tech group conversion method"; techGroupAlgorithm = older; } for (map<string, V2Country*>::iterator itr = countries.begin(); itr != countries.end(); ++itr) { itr->second->convertUncivReforms(techGroupAlgorithm, topTech, topInstitutions); } // inherit civilisation level for landless countries from their capital's owner for (map<string, V2Country*>::iterator itr = countries.begin(); itr != countries.end(); ++itr) { if (itr->second->getProvinces().size() == 0) { int capitalNum = itr->second->getCapital(); if (capitalNum == 0) continue; V2Province* capital = getProvince(capitalNum); string capOwnerTag = capital->getOwner(); V2Country* capOwner = getCountry(capOwnerTag); if (capOwner == nullptr) continue; itr->second->convertLandlessReforms(capOwner); } } } void V2World::convertTechs(const EU4::world& sourceWorld) { LOG(LogLevel::Info) << "Converting techs"; auto sourceCountries = sourceWorld.getCountries(); // Helper functions auto getCountryArmyTech = [&](shared_ptr<EU4::Country> country) { return country->getMilTech() + country->getAdmTech() + ideaEffectMapper::getArmyTechFromIdeas(country->getNationalIdeas()); }; auto getCountryNavyTech = [&](shared_ptr<EU4::Country> country) { return country->getMilTech() + country->getDipTech() + ideaEffectMapper::getNavyTechFromIdeas(country->getNationalIdeas()); }; auto getCountryCommerceTech = [&](shared_ptr<EU4::Country> country) { return country->getAdmTech() + country->getDipTech() + ideaEffectMapper::getCommerceTechFromIdeas(country->getNationalIdeas()); }; auto getCountryCultureTech = [&](shared_ptr<EU4::Country> country) { return country->getDipTech() + ideaEffectMapper::getCultureTechFromIdeas(country->getNationalIdeas()); }; auto getCountryIndustryTech = [&](shared_ptr<EU4::Country> country) { return country->getAdmTech() + country->getDipTech() + country->getMilTech() + ideaEffectMapper::getIndustryTechFromIdeas(country->getNationalIdeas()); }; double armyMax, armyMean; double navyMax, navyMean; double commerceMax, commerceMean; double cultureMax, cultureMean; double industryMax, industryMean; auto i = sourceCountries.begin(); while (i->second->getProvinces().size() == 0) i++; // Take mean and max from the first country auto currCountry = i->second; armyMax = armyMean = getCountryArmyTech(currCountry); navyMax = navyMean = getCountryNavyTech(currCountry); commerceMax = commerceMean = getCountryCommerceTech(currCountry); cultureMax = cultureMean = getCountryCultureTech(currCountry); industryMax = industryMean = getCountryIndustryTech(currCountry); int num = 2; // Helper for updating max and mean auto updateMeanMax = [&](double& max, double& mean, double techLevel) { if (techLevel > max) max = techLevel; mean = mean + (techLevel - mean) / num; }; // Calculate max and mean for (i++; i != sourceCountries.end(); i++) { currCountry = i->second; if (currCountry->getProvinces().size() == 0) continue; updateMeanMax(armyMax, armyMean, getCountryArmyTech(currCountry)); updateMeanMax(navyMax, navyMean, getCountryNavyTech(currCountry)); updateMeanMax(commerceMax, commerceMean, getCountryCommerceTech(currCountry)); updateMeanMax(cultureMax, cultureMean, getCountryCultureTech(currCountry)); updateMeanMax(industryMax, industryMean, getCountryIndustryTech(currCountry)); num++; } // Helper to normalize the score auto getNormalizedScore = [](double score, double max, double mean) { if (mean == max) return max; return (score - mean) / (max - mean); }; // Set tech levels from normalized scores for (map<string, V2Country*>::iterator itr = countries.begin(); itr != countries.end(); itr++) { V2Country* country = itr->second; if ((Configuration::getV2Gametype() != "vanilla") && !country->isCivilized()) continue; auto srcCountry = country->getSourceCountry(); if (!srcCountry) continue; country->setArmyTech(getNormalizedScore(getCountryArmyTech(srcCountry), armyMax, armyMean)); country->setNavyTech(getNormalizedScore(getCountryNavyTech(srcCountry), navyMax, navyMean)); country->setCommerceTech(getNormalizedScore(getCountryCommerceTech(srcCountry), commerceMax, commerceMean)); country->setCultureTech(getNormalizedScore(getCountryCultureTech(srcCountry), cultureMax, cultureMean)); country->setIndustryTech(getNormalizedScore(getCountryIndustryTech(srcCountry), industryMax, industryMean)); } } void V2World::allocateFactories(const EU4::world& sourceWorld) { // Construct factory factory LOG(LogLevel::Info) << "Determining factory allocation rules."; V2FactoryFactory factoryBuilder; LOG(LogLevel::Info) << "Allocating starting factories"; // determine average production tech auto sourceCountries = sourceWorld.getCountries(); double admMean = 0.0f; int num = 1; for (auto itr = sourceCountries.begin(); itr != sourceCountries.end(); ++itr) { if ((itr)->second->getProvinces().size() == 0) { continue; } double admTech = (itr)->second->getAdmTech(); admMean += ((admTech - admMean) / num); ++num; } // give all extant civilized nations an industrial score deque<pair<double, V2Country*>> weightedCountries; for (map<string, V2Country*>::iterator itr = countries.begin(); itr != countries.end(); ++itr) { if (!itr->second->isCivilized()) { continue; } auto sourceCountry = itr->second->getSourceCountry(); if (sourceCountry == nullptr) { continue; } if (itr->second->getProvinces().size() == 0) { continue; } // modified manufactory weight follows diminishing returns curve y = x^(3/4)+log((x^2)/5+1) int manuCount = sourceCountry->getManufactoryCount(); double manuWeight = pow(manuCount, 0.75) + log((manuCount * manuCount) / 5.0 + 1.0); double industryWeight = (sourceCountry->getAdmTech() - admMean) + manuWeight; // having one manufactory and average tech is not enough; you must have more than one, or above-average tech if (industryWeight > 1.0) { weightedCountries.push_back(pair<double, V2Country*>(industryWeight, itr->second)); } } if (weightedCountries.size() < 1) { LOG(LogLevel::Warning) << "No countries are able to accept factories"; return; } sort(weightedCountries.begin(), weightedCountries.end()); // allow a maximum of 10 (plus any tied at tenth place) countries to recieve factories deque<pair<double, V2Country*>> restrictCountries; double threshold = 1.0; double totalIndWeight = 0.0; for (deque<pair<double, V2Country*>>::reverse_iterator itr = weightedCountries.rbegin(); itr != weightedCountries.rend(); ++itr) { if ((restrictCountries.size() > 10) && (itr->first < (threshold - FLT_EPSILON))) { break; } restrictCountries.push_front(*itr); // preserve sort totalIndWeight += itr->first; threshold = itr->first; } weightedCountries.swap(restrictCountries); // remove nations that won't have enough industiral score for even one factory deque<V2Factory*> factoryList = factoryBuilder.buildFactories(); while (((weightedCountries.begin()->first / totalIndWeight) * factoryList.size() + 0.5 /*round*/) < 1.0) { weightedCountries.pop_front(); } // determine how many factories each eligible nation gets vector<pair<int, V2Country*>> factoryCounts; for (deque<pair<double, V2Country*>>::iterator itr = weightedCountries.begin(); itr != weightedCountries.end(); ++itr) { int factories = int(((itr->first / totalIndWeight) * factoryList.size()) + 0.5 /*round*/); LOG(LogLevel::Debug) << itr->second->getTag() << " has industrial weight " << itr->first << " granting max " << factories << " factories"; factoryCounts.push_back(pair<int, V2Country*>(factories, itr->second)); } // allocate the factories vector<pair<int, V2Country*>>::iterator lastReceptiveCountry = factoryCounts.end()--; vector<pair<int, V2Country*>>::iterator citr = factoryCounts.begin(); while (factoryList.size() > 0) { bool accepted = false; if (citr->first > 0) // can take more factories { for (deque<V2Factory*>::iterator qitr = factoryList.begin(); qitr != factoryList.end(); ++qitr) { if (citr->second->addFactory(*qitr)) { --(citr->first); lastReceptiveCountry = citr; accepted = true; factoryList.erase(qitr); break; } } } if (!accepted && citr == lastReceptiveCountry) { Log logOutput(LogLevel::Debug); logOutput << "No countries will accept any of the remaining factories:\n"; for (deque<V2Factory*>::iterator qitr = factoryList.begin(); qitr != factoryList.end(); ++qitr) { logOutput << "\t " << (*qitr)->getTypeName() << '\n'; } break; } if (++citr == factoryCounts.end()) { citr = factoryCounts.begin(); // loop around to beginning } } } void V2World::setupPops(const EU4::world& sourceWorld) { LOG(LogLevel::Info) << "Creating pops"; long my_totalWorldPopulation = static_cast<long>(0.55 * totalWorldPopulation); double popWeightRatio = my_totalWorldPopulation / sourceWorld.getWorldWeightSum(); //ofstream output_file("Data.csv"); int popAlgorithm = 0; auto version12 = EU4Version("1.12.0"); if (*(sourceWorld.getVersion()) >= version12) { LOG(LogLevel::Info) << "Using pop conversion algorithm for EU4 versions after 1.12."; popAlgorithm = 2; } else { LOG(LogLevel::Info) << "Using pop conversion algorithm for EU4 versions prior to 1.12."; popAlgorithm = 1; } for (map<string, V2Country*>::iterator itr = countries.begin(); itr != countries.end(); ++itr) { itr->second->setupPops(popWeightRatio, popAlgorithm); } if (Configuration::getConvertPopTotals()) { LOG(LogLevel::Info) << "Total world population: " << my_totalWorldPopulation; } else { LOG(LogLevel::Info) << "Total world population: " << totalWorldPopulation; } LOG(LogLevel::Info) << "Total world weight sum: " << sourceWorld.getWorldWeightSum(); LOG(LogLevel::Info) << my_totalWorldPopulation << " / " << sourceWorld.getWorldWeightSum(); LOG(LogLevel::Info) << "Population per weight point is: " << popWeightRatio; long newTotalPopulation = 0; // Heading /*output_file << "EU ID" << ","; output_file << "EU NAME" << ","; output_file << "OWNER" << ","; output_file << "BTAX" << ","; output_file << "TX INCOME" << ","; output_file << "PROD" << ","; output_file << "MP" << ","; output_file << "BUIDINGS" << ","; output_file << "TRADE" << ","; output_file << "TOTAL" << ","; output_file << "#DEST" << ","; output_file << "V2 ID" << ","; output_file << "V2 NAME" << ","; output_file << "CALC POPS" << ","; output_file << "POPS" << endl;*/ for (auto itr = provinces.begin(); itr != provinces.end(); itr++) { // EU4ID, EU4Name, EU4TAG, BTX, TAX, PROD, MP, BUILD, TRADE, WEIGHT, DESTV2, V2Name, POPs // newTotalPopulation += itr->second->getTotalPopulation(); // EU4 Province ID //if (itr->second->getSrcProvince() != nullptr) //{ // output_file << itr->second->getSrcProvince()->getNum() << ","; //} //else //{ // continue; //} //// EU4 Province Name //if (itr->second->getSrcProvince() != nullptr) //{ // output_file << itr->second->getSrcProvince()->getProvName() << ","; //} //else //{ // output_file << "SEA" << ","; //} //// EU4 Province Owner //if (itr->second->getSrcProvince() != nullptr) //{ // output_file << itr->second->getSrcProvince()->getOwnerString() << ","; //} //else //{ // output_file << "nullptr" << ","; //} //// EU4 Base Tax //if (itr->second->getSrcProvince() != nullptr) //{ // output_file << (2 * itr->second->getSrcProvince()->getBaseTax()) << ","; //} //else //{ // output_file << -1 << ","; //} //// EU4 Total Tax Income //if (itr->second->getSrcProvince() != nullptr) //{ // output_file << 2*(itr->second->getSrcProvince()->getProvTaxIncome()) << ","; //} //else //{ // output_file << -1 << ","; //} //// EU4 Total Prod Income //if (itr->second->getSrcProvince() != nullptr) //{ // output_file << itr->second->getSrcProvince()->getProvProdIncome() << ","; //} //else //{ // output_file << -1 << ","; //} //// EU4 Total Manpower weight //if (itr->second->getSrcProvince() != nullptr) //{ // output_file << itr->second->getSrcProvince()->getProvMPWeight() << ","; //} //else //{ // output_file << -1 << ","; //} //// EU4 Total Building weight //if (itr->second->getSrcProvince() != nullptr) //{ // output_file << itr->second->getSrcProvince()->getProvTotalBuildingWeight() << ","; //} //else //{ // output_file << -1 << ","; //} //// EU4 Total Tradegoods weight //if (itr->second->getSrcProvince() != nullptr) //{ // output_file << itr->second->getSrcProvince()->getCurrTradeGoodWeight() << ","; //} //else //{ // output_file << -1 << ","; //} //// EU4 Province Weight //if (itr->second->getSrcProvince() != nullptr) //{ // output_file << itr->second->getSrcProvince()->getTotalWeight() << ","; //} //else //{ // output_file << -1 << ","; //} //// Number of DestV2Provs //if (itr->second->getSrcProvince() != nullptr) //{ // output_file << itr->second->getSrcProvince()->getNumDestV2Provs() << ","; //} //else //{ // output_file << -2 << ","; //} //// V2 Province ID //output_file << itr->second->getNum() << ","; //// V2 Province Name //if (itr->second->getName() == "") //{ // output_file << itr->second->getNum() << ","; //} //else //{ // output_file << itr->second->getName() << ","; //} //// Calculated V2 POPs //output_file << ((itr->second->getSrcProvince()->getTotalWeight()*popWeightRatio)/itr->second->getSrcProvince()->getNumDestV2Provs()) << ","; //// V2 POPs //output_file << itr->second->getTotalPopulation() << endl; } LOG(LogLevel::Info) << "New total world population: " << newTotalPopulation; //output_file.close(); } void V2World::addUnions() { LOG(LogLevel::Info) << "Adding unions"; for (map<int, V2Province*>::iterator provItr = provinces.begin(); provItr != provinces.end(); provItr++) { if (!provItr->second->wasInfidelConquest() && !provItr->second->wasColony()) { auto cultures = provItr->second->getCulturesOverThreshold(0.5); for (auto culture : cultures) { vector<string> cores = vic2CultureUnionMapper::getCoreForCulture(culture); for (auto core: cores) { provItr->second->addCore(core); } } } } } //#define TEST_V2_PROVINCES void V2World::convertArmies(const EU4::world& sourceWorld) { LOG(LogLevel::Info) << "Converting armies and navies"; // hack for naval bases. not ALL naval bases are in port provinces, and if you spawn a navy at a naval base in // a non-port province, Vicky crashes.... vector<int> port_whitelist; { int temp = 0; ifstream s("port_whitelist.txt"); while (s.good() && !s.eof()) { s >> temp; port_whitelist.push_back(temp); } s.close(); } // get cost per regiment values double cost_per_regiment[num_reg_categories] = { 0.0 }; shared_ptr<Object> obj2 = parser_8859_15::doParseFile("regiment_costs.txt"); if (obj2 == nullptr) { LOG(LogLevel::Error) << "Could not parse file regiment_costs.txt"; exit(-1); } vector<shared_ptr<Object>> objTop = obj2->getLeaves(); if (objTop.size() == 0 || objTop[0]->getLeaves().size() == 0) { LOG(LogLevel::Error) << "regment_costs.txt failed to parse"; exit(1); } for (int i = 0; i < num_reg_categories; ++i) { auto possibleRegimentCost = objTop[0]->getLeaf(RegimentCategoryNames[i]); if (possibleRegimentCost) { cost_per_regiment[i] = stoi(*possibleRegimentCost); } } // convert armies for (map<string, V2Country*>::iterator itr = countries.begin(); itr != countries.end(); ++itr) { itr->second->convertArmies(leaderIDMap, cost_per_regiment, provinces, port_whitelist); } } void V2World::output() const { LOG(LogLevel::Info) << "Outputting mod"; Utils::copyFolder("blankMod/output", "output/output"); Utils::renameFolder("output/output", "output/" + Configuration::getOutputName()); createModFile(); // Create common\countries path. string countriesPath = "Output/" + Configuration::getOutputName() + "/common/countries"; if (!Utils::TryCreateFolder(countriesPath)) { return; } // Output common\countries.txt LOG(LogLevel::Debug) << "Writing countries file"; FILE* allCountriesFile; if (fopen_s(&allCountriesFile, ("Output/" + Configuration::getOutputName() + "/common/countries.txt").c_str(), "w") != 0) { LOG(LogLevel::Error) << "Could not create countries file"; exit(-1); } for (map<string, V2Country*>::const_iterator i = countries.begin(); i != countries.end(); i++) { const V2Country& country = *i->second; map<string, V2Country*>::const_iterator j = dynamicCountries.find(country.getTag()); if (j == dynamicCountries.end()) { country.outputToCommonCountriesFile(allCountriesFile); } } fprintf(allCountriesFile, "\n"); if ((Configuration::getV2Gametype() == "HOD") || (Configuration::getV2Gametype() == "HoD_NNM")) { fprintf(allCountriesFile, "##HoD Dominions\n"); fprintf(allCountriesFile, "dynamic_tags = yes # any tags after this is considered dynamic dominions\n"); for (map<string, V2Country*>::const_iterator i = dynamicCountries.begin(); i != dynamicCountries.end(); i++) { i->second->outputToCommonCountriesFile(allCountriesFile); } } fclose(allCountriesFile); // Create flags for all new countries. V2Flags flags; flags.SetV2Tags(countries); flags.output(); // Create localisations for all new countries. We don't actually know the names yet so we just use the tags as the names. LOG(LogLevel::Debug) << "Writing localisation text"; string localisationPath = "Output/" + Configuration::getOutputName() + "/localisation"; if (!Utils::TryCreateFolder(localisationPath)) { return; } string source = Configuration::getV2Path() + "/localisation/text.csv"; string dest = localisationPath + "/text.csv"; if (isRandomWorld) { LOG(LogLevel::Debug) << "It's a random world"; // we need to strip out the existing country names from the localisation file ifstream sourceFile(source); ofstream targetFile(dest); string line; std::regex countryTag("^[A-Z][A-Z][A-Z];"); std::regex rebels("^REB;"); std::smatch match; while (std::getline(sourceFile, line)) { if (std::regex_search(line, match, countryTag) && !std::regex_search(line, match, rebels)) { continue; } targetFile << line << '\n'; } sourceFile.close(); targetFile.close(); // ...and also empty out 0_Names.csv FILE* zeronamesfile; string zeronamesfilepath = localisationPath + "/0_Names.csv"; if (fopen_s(&zeronamesfile, zeronamesfilepath.c_str(), "w") != 0) fclose(zeronamesfile); } else { LOG(LogLevel::Debug) << "It's not a random world"; } FILE* localisationFile; if (fopen_s(&localisationFile, (localisationPath + "/0_Names.csv").c_str(), "a") != 0) { LOG(LogLevel::Error) << "Could not update localisation text file"; exit(-1); } for (map<string, V2Country*>::const_iterator i = countries.begin(); i != countries.end(); i++) { const V2Country& country = *i->second; if (country.isNewCountry()) { country.outputLocalisation(localisationFile); } } fclose(localisationFile); LOG(LogLevel::Debug) << "Writing provinces"; for (map<int, V2Province*>::const_iterator i = provinces.begin(); i != provinces.end(); i++) { i->second->output(); LOG(LogLevel::Debug) << "province " << i->second->getName() << " has " << i->second->getNavalBaseLevel() << " naval base"; //test } LOG(LogLevel::Debug) << "Writing countries"; for (map<string, V2Country*>::const_iterator itr = countries.begin(); itr != countries.end(); itr++) { itr->second->output(); } diplomacy.output(); outputPops(); // verify countries got written ifstream V2CountriesInput; V2CountriesInput.open(("Output/" + Configuration::getOutputName() + "/common/countries.txt").c_str()); if (!V2CountriesInput.is_open()) { LOG(LogLevel::Error) << "Could not open countries.txt"; exit(1); } bool staticSection = true; while (!V2CountriesInput.eof()) { string line; getline(V2CountriesInput, line); if ((line[0] == '#') || (line.size() < 3)) { continue; } else if (line.substr(0, 12) == "dynamic_tags") { continue; } string countryFileName; int start = line.find_first_of('/'); int size = line.find_last_of('\"') - start - 1; countryFileName = line.substr(start + 1, size); if (Utils::DoesFileExist("Output/" + Configuration::getOutputName() + "/common/countries/" + countryFileName)) { } else if (Utils::DoesFileExist(Configuration::getV2Path() + "/common/countries/" + countryFileName)) { } else { LOG(LogLevel::Warning) << "common/countries/" << countryFileName << " does not exists. This will likely crash Victoria 2."; continue; } } V2CountriesInput.close(); } void V2World::createModFile() const { ofstream modFile("Output/" + Configuration::getOutputName() + ".mod"); if (!modFile.is_open()) { LOG(LogLevel::Error) << "Could not create " << Configuration::getOutputName() << ".mod"; exit(-1); } modFile << "name = \"Converted - " << Configuration::getOutputName() << "\"\n"; modFile << "path = \"mod/" << Configuration::getOutputName() << "\"\n"; modFile << "user_dir = \"" << Configuration::getOutputName() << "\"\n"; modFile << "replace = \"history/provinces\"\n"; modFile << "replace = \"history/countries\"\n"; modFile << "replace = \"history/diplomacy\"\n"; modFile << "replace = \"history/units\"\n"; modFile << "replace = \"history/pops/1836.1.1\"\n"; modFile << "replace = \"common/religion.txt\"\n"; modFile << "replace = \"common/cultures.txt\"\n"; modFile << "replace = \"common/countries.txt\"\n"; modFile << "replace = \"common/countries/\"\n"; modFile << "replace = \"gfx/interface/icon_religion.dds\"\n"; modFile << "replace = \"localisation/0_Names.csv\"\n"; modFile << "replace = \"localisation/0_Cultures.csv\"\n"; modFile << "replace = \"localisation/0_Religions.csv\"\n"; modFile << "replace = \"history/wars\"\n"; modFile.close(); } void V2World::outputPops() const { LOG(LogLevel::Debug) << "Writing pops"; for (auto popRegion : popRegions) { FILE* popsFile; if (fopen_s(&popsFile, ("Output/" + Configuration::getOutputName() + "/history/pops/1836.1.1/" + popRegion.first).c_str(), "w") != 0) { LOG(LogLevel::Error) << "Could not create pops file Output/" << Configuration::getOutputName() << "/history/pops/1836.1.1/" << popRegion.first; exit(-1); } for (auto provinceNumber : popRegion.second) { map<int, V2Province*>::const_iterator provItr = provinces.find(provinceNumber); if (provItr != provinces.end()) { provItr->second->outputPops(popsFile); } else { LOG(LogLevel::Error) << "Could not find province " << provinceNumber << " while outputing pops!"; } } } } V2Province* V2World::getProvince(const int provNum) const { map<int, V2Province*>::const_iterator i = provinces.find(provNum); return (i != provinces.end()) ? i->second : nullptr; } V2Country* V2World::getCountry(string tag) const { map<string, V2Country*>::const_iterator i = countries.find(tag); return (i != countries.end()) ? i->second : nullptr; }
31.120308
480
0.657668
hao9889hao
6a01c930ca3114ba916d0563f001efb87093b525
6,037
cpp
C++
util.cpp
mousewu/bcclient
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
[ "MIT" ]
8
2019-05-31T01:37:08.000Z
2021-10-19T05:52:45.000Z
util.cpp
mousewu/bcclient
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
[ "MIT" ]
3
2017-12-18T17:27:09.000Z
2018-01-15T16:50:05.000Z
util.cpp
mousewu/bcclient
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
[ "MIT" ]
5
2018-01-09T15:05:55.000Z
2020-12-17T13:27:25.000Z
/* Copyright (c) 2014-2015 Ivan Pustogarov Distributed under the MIT/X11 software license, see the accompanying file LICENSE or http://www.opensource.org/licenses/mit-license.php. */ #include "main.hpp" #include "util.hpp" #include <boost/chrono/chrono.hpp> #include <boost/type_traits.hpp> #include <boost/chrono/system_clocks.hpp> #include <boost/chrono/system_clocks.hpp> using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; // Logger handlers void output_to_null(std::ofstream& file, log_level level, const std::string& domain, const std::string& body) { return; } void output_to_file(std::ofstream& file, log_level level, const std::string& domain, const std::string& body) { if (body.empty()) return; char buff[70]; int ms; time_t time_epoch = time(NULL); struct tm time_struct_gmt; struct timeval time_seconds; gmtime_r(&time_epoch, &time_struct_gmt); gettimeofday(&time_seconds, NULL); strftime(buff, sizeof(buff), "%b %d %H:%M:%S", &time_struct_gmt); ms = (int)time_seconds.tv_usec / 1000; //struct timespec tp; //clock_gettime(CLOCK_MONOTONIC_RAW, &tp); boost::chrono::steady_clock::time_point tp_now = boost::chrono::steady_clock::now();//.time_since_epoch(); long int timeSinceEpoch = boost::chrono::duration_cast<boost::chrono::milliseconds>(tp_now.time_since_epoch()).count(); //ret += fprintf(fileout, "%lu.%ld ", tp.tv_sec, tp.tv_nsec); //printf("The year is: %ld\n", gmtime(&now)->tm_year); //file << buff << "." << ms << " " << "(" << tp.tv_sec << "." << tp.tv_nsec << ")"; file << buff << "." << ms << " " << "(" << timeSinceEpoch << ")"; file << " [" << level_repr(level) << "]"; if (!domain.empty()) file << " [" << domain << "]"; file << ": " << body << std::endl; } void output_to_terminal(log_level level, const std::string& domain, const std::string& body) { if (body.empty()) return; char buff[70]; int ms; time_t time_epoch = time(NULL); struct tm time_struct_gmt; struct timeval time_seconds; gmtime_r(&time_epoch, &time_struct_gmt); gettimeofday(&time_seconds, NULL); strftime(buff, sizeof(buff), "%b %d %H:%M:%S", &time_struct_gmt); ms = (int)time_seconds.tv_usec / 1000; //struct timespec tp; //clock_gettime(CLOCK_MONOTONIC_RAW, &tp); boost::chrono::steady_clock::time_point tp_now = boost::chrono::steady_clock::now();//.time_since_epoch(); long int timeSinceEpoch = boost::chrono::duration_cast<boost::chrono::milliseconds>(tp_now.time_since_epoch()).count(); //printf("The year is: %ld\n", gmtime(&now)->tm_year); //std::cout << buff << "." << ms << " " << "(" << tp.tv_sec << "." << tp.tv_nsec << ")"; std::cout << buff << "." << ms << " " << "(" << timeSinceEpoch << ")"; std::cout << " [" << level_repr(level) << "]"; if (!domain.empty()) std::cout << " [" << domain << "]"; std::cout << ": " << body << std::endl; } // Output formatting std::string format_ipv6addr(ip_address_type ip) { char addr_str[256]; sprintf(addr_str, "%02hhx%02hhx:%02hhx%02hhx:" "%02hhx%02hhx:%02hhx%02hhx:" "%02hhx%02hhx:%02hhx%02hhx:" "%02hhx%02hhx:%02hhx%02hhx", ip[0], ip[1], ip[2], ip[3], ip[4], ip[5], ip[6], ip[7], ip[8], ip[9], ip[10],ip[11], ip[12],ip[13],ip[14],ip[15]); return std::string(addr_str); } std::string format_ipv4addr(ip_address_type ip) { char addr_str[256]; sprintf(addr_str, "%hhu.%hhu.%hhu.%hhu", ip[12],ip[13],ip[14],ip[15]); return std::string(addr_str); } /* Checks if a 16-byte array is an ipv4 address Bytes 0-9 should be zero Bytes 10,11 should be 'ff:ff' Bytes 12,13,14,15 represent ipv4 address. */ bool is_ipv4(ip_address_type ip) { int i = 0; for (i=0;i<10;i++) if (ip[i] != 0) return false; if((ip[10] != 0xff) || (ip[11] != 0xff)) return false; return true; } std::string peer_address_to_string(struct peer_address addr) { std::string buff(addr.ip); buff += ":"; buff += std::to_string(addr.port); buff += "."; buff += std::to_string(addr.instance_num); return buff; } // Convert string representation of IP_v4 or IP_v6 (with port) to a bitcoin struct we // can put to 'addr' message struct network_address_type make_bc_addr(const std::string ip_str, long int timestamp_offset) { struct network_address_type addr; addr.timestamp = time(NULL) + timestamp_offset; addr.services = 1; //the address is ipv4 if(ip_str.find(".") != -1) { uint8_t ipb[4]; // stands for ip_bYTES uint16_t port; sscanf(ip_str.c_str(),"%hhu.%hhu.%hhu.%hhu %hu",ipb,ipb+1,ipb+2,ipb+3,&port); addr.ip = ip_address_type{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, ipb[0], ipb[1], ipb[2], ipb[3]}; addr.port = port; log_debug() << "make_bc_addr(): Created addr '" << format_ipv4addr(addr.ip) << ":" << addr.port << "'"; } // ipv6 else if(ip_str.find(":") != -1) { uint8_t ipb[16]; // stands for ip_bYTES uint16_t port; sscanf(ip_str.c_str(),"%02hhx%02hhx:%02hhx%02hhx:" "%02hhx%02hhx:%02hhx%02hhx:" "%02hhx%02hhx:%02hhx%02hhx:" "%02hhx%02hhx:%02hhx%02hhx %hu", ipb,ipb+1,ipb+2,ipb+3, ipb+4,ipb+5,ipb+6,ipb+7, ipb+8,ipb+9,ipb+10,ipb+11, ipb+12,ipb+13,ipb+14,ipb+15,&port); addr.ip = ip_address_type{ipb[0],ipb[1],ipb[2],ipb[3], ipb[4],ipb[5],ipb[6],ipb[7], ipb[8],ipb[9],ipb[10],ipb[11], ipb[12],ipb[13],ipb[14],ipb[15]}; addr.port = port; log_debug() << "make_bc_addr(): Created addr '" << format_ipv6addr(addr.ip) << ":" << addr.port << "'"; } else { log_info() << "make_bc_addr(): Error parsing address (skipping): " << ip_str; addr.port = 0; // Indication of an error } return addr; }
32.111702
123
0.599139
mousewu
6a02c2a4430af2af9ffb0d5b9355a5939f6026be
9,677
cpp
C++
libhwmon/wrapnvml.cpp
levongh/energiminer
eee27b2701abb4f703c3b036bd14864c7c4dc695
[ "MIT" ]
null
null
null
libhwmon/wrapnvml.cpp
levongh/energiminer
eee27b2701abb4f703c3b036bd14864c7c4dc695
[ "MIT" ]
null
null
null
libhwmon/wrapnvml.cpp
levongh/energiminer
eee27b2701abb4f703c3b036bd14864c7c4dc695
[ "MIT" ]
null
null
null
/* * A trivial little dlopen()-based wrapper library for the * NVIDIA NVML library, to allow runtime discovery of NVML on an * arbitrary system. This is all very hackish and simple-minded, but * it serves my immediate needs in the short term until NVIDIA provides * a static NVML wrapper library themselves, hopefully in * CUDA 6.5 or maybe sometime shortly after. * * This trivial code is made available under the "new" 3-clause BSD license, * and/or any of the GPL licenses you prefer. * Feel free to use the code and modify as you see fit. * * John E. Stone - john.stone@gmail.com * * Modified to work with ethminer by * * Philipp Andreas - github@smurfy.de */ #include <stdio.h> #include <stdlib.h> #include "wraphelper.h" #include "wrapnvml.h" #if ETH_ETHASHCUDA #include "cuda_runtime.h" #endif #if defined(__cplusplus) extern "C" { #endif wrap_nvml_handle * wrap_nvml_create() { wrap_nvml_handle *nvmlh = NULL; /* * We use hard-coded library installation locations for the time being... * No idea where or if libnvidia-ml.so is installed on MacOS X, a * deep scouring of the filesystem on one of the Mac CUDA build boxes * I used turned up nothing, so for now it's not going to work on OSX. */ #if defined(_WIN32) /* Windows */ #define libnvidia_ml "%PROGRAMFILES%/NVIDIA Corporation/NVSMI/nvml.dll" #elif defined(__linux) && (defined(__i386__) || defined(__ARM_ARCH_7A__)) /* 32-bit linux assumed */ #define libnvidia_ml "libnvidia-ml.so" #elif defined(__linux) /* 64-bit linux assumed */ #define libnvidia_ml "libnvidia-ml.so" #else #define libnvidia_ml "" #warning "Unrecognized platform: need NVML DLL path for this platform..." return NULL; #endif #ifdef _WIN32 char tmp[512]; ExpandEnvironmentStringsA(libnvidia_ml, tmp, sizeof(tmp)); #else char tmp[512] = libnvidia_ml; #endif void *nvml_dll = wrap_dlopen(tmp); if (nvml_dll == NULL) return NULL; nvmlh = (wrap_nvml_handle *) calloc(1, sizeof(wrap_nvml_handle)); nvmlh->nvml_dll = nvml_dll; nvmlh->nvmlInit = (wrap_nvmlReturn_t (*)(void)) wrap_dlsym(nvmlh->nvml_dll, "nvmlInit"); nvmlh->nvmlDeviceGetCount = (wrap_nvmlReturn_t (*)(int *)) wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetCount_v2"); nvmlh->nvmlDeviceGetHandleByIndex = (wrap_nvmlReturn_t (*)(int, wrap_nvmlDevice_t *)) wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetHandleByIndex_v2"); nvmlh->nvmlDeviceGetPciInfo = (wrap_nvmlReturn_t (*)(wrap_nvmlDevice_t, wrap_nvmlPciInfo_t *)) wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetPciInfo"); nvmlh->nvmlDeviceGetName = (wrap_nvmlReturn_t (*)(wrap_nvmlDevice_t, char *, int)) wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetName"); nvmlh->nvmlDeviceGetTemperature = (wrap_nvmlReturn_t (*)(wrap_nvmlDevice_t, int, unsigned int *)) wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetTemperature"); nvmlh->nvmlDeviceGetFanSpeed = (wrap_nvmlReturn_t (*)(wrap_nvmlDevice_t, unsigned int *)) wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetFanSpeed"); nvmlh->nvmlDeviceGetPowerUsage = (wrap_nvmlReturn_t (*)(wrap_nvmlDevice_t, unsigned int *)) wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetPowerUsage"); nvmlh->nvmlShutdown = (wrap_nvmlReturn_t (*)()) wrap_dlsym(nvmlh->nvml_dll, "nvmlShutdown"); if (nvmlh->nvmlInit == NULL || nvmlh->nvmlShutdown == NULL || nvmlh->nvmlDeviceGetCount == NULL || nvmlh->nvmlDeviceGetHandleByIndex == NULL || nvmlh->nvmlDeviceGetPciInfo == NULL || nvmlh->nvmlDeviceGetName == NULL || nvmlh->nvmlDeviceGetTemperature == NULL || nvmlh->nvmlDeviceGetFanSpeed == NULL || nvmlh->nvmlDeviceGetPowerUsage == NULL ) { #if 0 printf("Failed to obtain all required NVML function pointers\n"); #endif wrap_dlclose(nvmlh->nvml_dll); free(nvmlh); return NULL; } nvmlh->nvmlInit(); nvmlh->nvmlDeviceGetCount(&nvmlh->nvml_gpucount); #if ETH_ETHASHCUDA /* Query CUDA device count, in case it doesn't agree with NVML, since */ /* CUDA will only report GPUs with compute capability greater than 1.0 */ if (cudaGetDeviceCount(&nvmlh->cuda_gpucount) != cudaSuccess) { #if 0 printf("Failed to query CUDA device count!\n"); #endif wrap_dlclose(nvmlh->nvml_dll); free(nvmlh); return NULL; } #endif nvmlh->devs = (wrap_nvmlDevice_t *) calloc(nvmlh->nvml_gpucount, sizeof(wrap_nvmlDevice_t)); nvmlh->nvml_pci_domain_id = (unsigned int*) calloc(nvmlh->nvml_gpucount, sizeof(unsigned int)); nvmlh->nvml_pci_bus_id = (unsigned int*) calloc(nvmlh->nvml_gpucount, sizeof(unsigned int)); nvmlh->nvml_pci_device_id = (unsigned int*) calloc(nvmlh->nvml_gpucount, sizeof(unsigned int)); nvmlh->nvml_cuda_device_id = (int*) calloc(nvmlh->nvml_gpucount, sizeof(int)); nvmlh->cuda_nvml_device_id = (int*) calloc(nvmlh->cuda_gpucount, sizeof(int)); /* Obtain GPU device handles we're going to need repeatedly... */ for (int i=0; i<nvmlh->nvml_gpucount; i++) { nvmlh->nvmlDeviceGetHandleByIndex(i, &nvmlh->devs[i]); } /* Query PCI info for each NVML device, and build table for mapping of */ /* CUDA device IDs to NVML device IDs and vice versa */ for (int i=0; i<nvmlh->nvml_gpucount; i++) { wrap_nvmlPciInfo_t pciinfo; nvmlh->nvmlDeviceGetPciInfo(nvmlh->devs[i], &pciinfo); nvmlh->nvml_pci_domain_id[i] = pciinfo.domain; nvmlh->nvml_pci_bus_id[i] = pciinfo.bus; nvmlh->nvml_pci_device_id[i] = pciinfo.device; } /* build mapping of NVML device IDs to CUDA IDs */ for (int i=0; i<nvmlh->nvml_gpucount; i++) { nvmlh->nvml_cuda_device_id[i] = -1; } #if ETH_ETHASHCUDA for (int i=0; i<nvmlh->cuda_gpucount; i++) { cudaDeviceProp props; nvmlh->cuda_nvml_device_id[i] = -1; if (cudaGetDeviceProperties(&props, i) == cudaSuccess) { int j; for (j=0; j<nvmlh->nvml_gpucount; j++) { if ((nvmlh->nvml_pci_domain_id[j] == (unsigned int)props.pciDomainID) && (nvmlh->nvml_pci_bus_id[j] == (unsigned int)props.pciBusID) && (nvmlh->nvml_pci_device_id[j] == (unsigned int)props.pciDeviceID)) { #if 0 printf("CUDA GPU[%d] matches NVML GPU[%d]\n", i, j); #endif nvmlh->nvml_cuda_device_id[j] = i; nvmlh->cuda_nvml_device_id[i] = j; } } } } #endif nvmlh->opencl_gpucount = 0; nvmlh->nvml_opencl_device_id = (int*)calloc(nvmlh->nvml_gpucount, sizeof(int)); #if ETH_ETHASHCL //Get and count OpenCL devices. std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); std::vector<cl::Device> platdevs; for(unsigned p = 0; p<platforms.size(); p++){ std::string platformName = platforms[p].getInfo<CL_PLATFORM_NAME>(); if (platformName == "NVIDIA CUDA") { platforms[p].getDevices( CL_DEVICE_TYPE_GPU | CL_DEVICE_TYPE_ACCELERATOR, &platdevs ); nvmlh->opencl_gpucount = platdevs.size(); break; } } nvmlh->opencl_nvml_device_id = (int*)calloc(nvmlh->opencl_gpucount, sizeof(int)); //Map NVML to opencl devices for(int i = 0; i<nvmlh->nvml_gpucount; i++){ for(unsigned j = 0; j<platdevs.size(); j++){ cl::Device cldev = platdevs[j]; cl_int busId, slotId; int statusB = clGetDeviceInfo (cldev(), CL_DEVICE_PCI_BUS_ID_NV, sizeof(cl_int), &busId, NULL); int statusS = clGetDeviceInfo (cldev(), CL_DEVICE_PCI_SLOT_ID_NV, sizeof(cl_int), &slotId, NULL); if(statusB == CL_SUCCESS && statusS == CL_SUCCESS) { if((unsigned)busId == nvmlh->nvml_pci_bus_id[i] && (unsigned)slotId == nvmlh->nvml_pci_device_id[i]) { #if 0 printf("[DEBUG] - NVML GPU[%d]%d,%d matches OpenCL GPU[%d]%d,%d\n", i, nvmlh->nvml_pci_bus_id[i], nvmlh->nvml_pci_device_id[i], j, busId, slotId); #endif nvmlh->nvml_opencl_device_id[i] = j; nvmlh->opencl_nvml_device_id[j] = i; } } } } #endif return nvmlh; } int wrap_nvml_destroy(wrap_nvml_handle *nvmlh) { nvmlh->nvmlShutdown(); wrap_dlclose(nvmlh->nvml_dll); free(nvmlh); return 0; } int wrap_nvml_get_gpucount(wrap_nvml_handle *nvmlh, int *gpucount) { *gpucount = nvmlh->nvml_gpucount; return 0; } int wrap_cuda_get_gpucount(wrap_nvml_handle *nvmlh, int *gpucount) { *gpucount = nvmlh->cuda_gpucount; return 0; } int wrap_nvml_get_gpu_name(wrap_nvml_handle *nvmlh, int gpuindex, char *namebuf, int bufsize) { if (gpuindex < 0 || gpuindex >= nvmlh->nvml_gpucount) return -1; if (nvmlh->nvmlDeviceGetName(nvmlh->devs[gpuindex], namebuf, bufsize) != WRAPNVML_SUCCESS) return -1; return 0; } int wrap_nvml_get_tempC(wrap_nvml_handle *nvmlh, int gpuindex, unsigned int *tempC) { wrap_nvmlReturn_t rc; if (gpuindex < 0 || gpuindex >= nvmlh->nvml_gpucount) return -1; rc = nvmlh->nvmlDeviceGetTemperature(nvmlh->devs[gpuindex], 0u /* NVML_TEMPERATURE_GPU */, tempC); if (rc != WRAPNVML_SUCCESS) { return -1; } return 0; } int wrap_nvml_get_fanpcnt(wrap_nvml_handle *nvmlh, int gpuindex, unsigned int *fanpcnt) { wrap_nvmlReturn_t rc; if (gpuindex < 0 || gpuindex >= nvmlh->nvml_gpucount) return -1; rc = nvmlh->nvmlDeviceGetFanSpeed(nvmlh->devs[gpuindex], fanpcnt); if (rc != WRAPNVML_SUCCESS) { return -1; } return 0; } int wrap_nvml_get_power_usage(wrap_nvml_handle *nvmlh, int gpuindex, unsigned int *milliwatts) { if (gpuindex < 0 || gpuindex >= nvmlh->nvml_gpucount) return -1; if (nvmlh->nvmlDeviceGetPowerUsage(nvmlh->devs[gpuindex], milliwatts) != WRAPNVML_SUCCESS) return -1; return 0; } #if defined(__cplusplus) } #endif
32.043046
105
0.682133
levongh
6a0431fb11eef39a528530d0626a89538fb3e340
2,796
cpp
C++
SU2-Quantum/SU2_CFD/src/interfaces/fsi/CDisplacementsInterface.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/src/interfaces/fsi/CDisplacementsInterface.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/src/interfaces/fsi/CDisplacementsInterface.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file CDisplacementsInterface.cpp * \brief Main subroutines for transferring boundary displacements. * \author Ruben Sanchez * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 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. * * SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>. */ #include "../../../include/interfaces/fsi/CDisplacementsInterface.hpp" CDisplacementsInterface::CDisplacementsInterface(unsigned short val_nVar, unsigned short val_nConst, CConfig *config) : CInterface(val_nVar, val_nConst, config) { } CDisplacementsInterface::~CDisplacementsInterface(void) { } void CDisplacementsInterface::GetPhysical_Constants(CSolver *struct_solution, CSolver *flow_solution, CGeometry *struct_geometry, CGeometry *flow_geometry, CConfig *struct_config, CConfig *flow_config) { } void CDisplacementsInterface::GetDonor_Variable(CSolver *struct_solution, CGeometry *struct_geometry, CConfig *struct_config, unsigned long Marker_Struct, unsigned long Vertex_Struct, unsigned long Point_Struct) { su2double *DisplacementDonor; unsigned short iVar; /*--- The displacements come from the predicted solution, but they are no longer incremental ---*/ DisplacementDonor = struct_solution->GetNodes()->GetSolution_Pred(Point_Struct); for (iVar = 0; iVar < nVar; iVar++) Donor_Variable[iVar] = DisplacementDonor[iVar]; } void CDisplacementsInterface::SetTarget_Variable(CSolver *mesh_solver, CGeometry *flow_geometry, CConfig *flow_config, unsigned long Marker_Flow, unsigned long Vertex_Flow, unsigned long Point_Mesh) { /*--- Impose the boundary displacements ---*/ mesh_solver->GetNodes()->SetBound_Disp(Point_Mesh,Target_Variable); }
39.380282
106
0.660229
Agony5757
6a067ba4dd19c7feee72fd4be467f153ea89a262
258
hpp
C++
naos/includes/kernel/util/memory.hpp
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
14
2020-02-12T11:07:58.000Z
2022-02-02T00:05:08.000Z
naos/includes/kernel/util/memory.hpp
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
null
null
null
naos/includes/kernel/util/memory.hpp
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
4
2020-02-27T09:53:53.000Z
2021-11-07T17:43:44.000Z
#pragma once #include "common.hpp" namespace util { void memset(void *dst, u64 val, u64 size); void memzero(void *dst, u64 size); void memcopy(void *dst, const void *src, u64 size); int memcmp(const void *lhs, const void *rhs, u64 size); } // namespace util
25.8
55
0.713178
kadds
6a14eaf8a80a4c95228fdd6537a0866ef236b602
1,748
cpp
C++
InventoryModule.cpp
jbp261/Booksellers-Software-Development
5f5326356b880bcd4dbbb515a24445a7a520c924
[ "MIT" ]
null
null
null
InventoryModule.cpp
jbp261/Booksellers-Software-Development
5f5326356b880bcd4dbbb515a24445a7a520c924
[ "MIT" ]
null
null
null
InventoryModule.cpp
jbp261/Booksellers-Software-Development
5f5326356b880bcd4dbbb515a24445a7a520c924
[ "MIT" ]
1
2018-12-07T05:58:35.000Z
2018-12-07T05:58:35.000Z
#include "InventoryModule.h" InventoryModule::InventoryModule(Inventory* db) : MenuModule(db) { } InventoryModule::~InventoryModule() { } void InventoryModule::PrintMenu() { cout << "\n1. Search By Partial ISBN"; cout << "\n2. Search By Partial Title"; cout << "\n3. Add Book"; cout << "\n4. Edit Book"; cout << "\n5. Delete Book"; cout << "\n6. Exit to previous menu\n"; } void InventoryModule::ProcessUserInput() { string userInput; getline(cin, userInput); if (userInput.length() > 1) throw "Invalid input"; InventoryBook *temp; switch (userInput[0]) { case '1': cout << "Enter search string: "; getline(cin, userInput); if (temp = database->searchBookByPartialIsbn(userInput.c_str())) cout << *temp; break; case '2': cout << "Enter search string: "; getline(cin, userInput); if (temp = database->searchBookByPartialTitle(userInput.c_str())) cout << *temp; break; case '3': temp = new InventoryBook(); temp->getData(); database->addBook(*temp); delete temp; break; case '4': cout << "Searching by title. Enter search string: "; getline(cin, userInput); if (temp = database->searchBookByPartialTitle(userInput.c_str())) database->editBook(temp); break; case '5': cout << "Searching by title. Enter search string: "; getline(cin, userInput); if (temp = database->searchBookByPartialTitle(userInput.c_str())) database->deleteBook(temp); break; case '6': is_terminated = true; break; default: throw "Invalid input"; break; } }
24.277778
72
0.579519
jbp261
6a19d1314c75f0320e227eb5cbffdc6dd6dcb5df
3,944
cpp
C++
Map.cpp
tonyt73/AGD-Viewer
a8fa46a71e57492fbd93afd7bd81d9537bef1d37
[ "MIT" ]
5
2018-06-22T16:03:29.000Z
2019-04-04T03:59:46.000Z
Map.cpp
tonyt73/AGD-Viewer
a8fa46a71e57492fbd93afd7bd81d9537bef1d37
[ "MIT" ]
null
null
null
Map.cpp
tonyt73/AGD-Viewer
a8fa46a71e57492fbd93afd7bd81d9537bef1d37
[ "MIT" ]
1
2019-04-04T03:59:47.000Z
2019-04-04T03:59:47.000Z
//--------------------------------------------------------------------------- #include "agdv.pch.h" #include "Map.h" #include "ErrorReporter.h" //--------------------------------------------------------------------------- #pragma package(smart_init) //--------------------------------------------------------------------------- __fastcall Map::Map(const String& data) { for (auto y = 0; y < 16; y++) for (auto x = 0; x < 16; x++) m_MapData[x][y] = 255; try { auto tokens = SplitString(data.Trim(), " "); String prevToken; auto storeScreens = false; auto x = 0; auto y = 0; auto width = 0; auto size = 0; for (auto token : tokens) { if (token == "left" || token == "right" || token == "top" || token == "bottom") { storeScreens = false; } else if (prevToken.LowerCase() == "startscreen") { m_StartScreen = StrToInt(token.Trim()); storeScreens = true; g_ErrorReporter.Add("Info: Map - Start Screen: " + IntToStr(m_StartScreen)); } else if (storeScreens && token.Trim() != "") { m_MapData[x][y] = StrToInt(token.Trim()); size += m_MapData[x][y] == 255 ? 0 : 1; if (++x == 11) { x = 0; y++; } } else if (prevToken.LowerCase() == "left") { m_Rect.Left = StrToInt(token); } else if (prevToken.LowerCase() == "right") { m_Rect.Right = StrToInt(token); } else if (prevToken.LowerCase() == "top") { m_Rect.Top = StrToInt(token); } else if (prevToken.LowerCase() == "bottom") { m_Rect.Bottom = StrToInt(token); } prevToken = token.Trim(); } m_Width = 16; m_Height = 16; g_ErrorReporter.Add("Info: Map - Screens: " + IntToStr(size) + ", " + IntToStr((int)m_Rect.Width()) + "x" + IntToStr((int)m_Rect.Height())); } catch(...) { g_ErrorReporter.Add("Error: Exception caught while converting Map data: [" + data + "]"); throw; } } //--------------------------------------------------------------------------- void __fastcall Map::Draw(TBitmap* bitmap, int scalar, const Window& window, const ImageList& blocks, const ImageList& objects, const ImageList& sprites, const ScreenList& screens) { if (blocks.size() > 0) { auto sw = window.w * blocks[0]->Width * scalar; auto sh = window.h * blocks[0]->Height * scalar; bitmap->Width = sw * m_Width; bitmap->Height = sh * m_Height; // clear the map BitBlt(bitmap->Canvas->Handle, 0, 0, bitmap->Width, bitmap->Height, NULL, 0, 0, BLACKNESS); auto x = 0; auto y = 0; //for (const auto& screen : m_MapData) for (auto y = 0; y < 16; y++) { for (auto x = 0; x < 16; x++) { auto screen = m_MapData[x][y]; if (screen != 255) { screens[screen]->Draw(screen, x, y, bitmap, scalar, blocks, objects, sprites, window); } } } } } // --------------------------------------------------------------------------- TPoint __fastcall Map::GetRoomPt(int room) { TPoint pt(0,0); for (auto y = 0; y < 16; y++) { for (auto x = 0; x < 16; x++) { if (m_MapData[x][y] == room) { pt.X = x; pt.Y = y; break; } } } return pt; } // ---------------------------------------------------------------------------
33.423729
180
0.393256
tonyt73
6a1ba633660114f4f2d45ea7660872b6cd958ec3
4,929
cpp
C++
Blizzlike/Trinity/Scripts/Units/boss_kruul.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/Trinity/Scripts/Units/boss_kruul.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/Trinity/Scripts/Units/boss_kruul.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * 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, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Kruul SD%Complete: 100 SDComment: Highlord Kruul are presumably no longer in-game on regular bases, however future events could bring him back. SDCategory: Bosses EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #define SPELL_SHADOWVOLLEY 21341 #define SPELL_CLEAVE 20677 #define SPELL_THUNDERCLAP 23931 #define SPELL_TWISTEDREFLECTION 21063 #define SPELL_VOIDBOLT 21066 #define SPELL_RAGE 21340 #define SPELL_CAPTURESOUL 21054 class boss_kruul : public CreatureScript { public: boss_kruul() : CreatureScript("boss_kruul") { } CreatureAI* GetAI(Creature* creature) const { return new boss_kruulAI (creature); } struct boss_kruulAI : public ScriptedAI { boss_kruulAI(Creature* creature) : ScriptedAI(creature) {} uint32 ShadowVolley_Timer; uint32 Cleave_Timer; uint32 ThunderClap_Timer; uint32 TwistedReflection_Timer; uint32 VoidBolt_Timer; uint32 Rage_Timer; uint32 Hound_Timer; void Reset() { ShadowVolley_Timer = 10000; Cleave_Timer = 14000; ThunderClap_Timer = 20000; TwistedReflection_Timer = 25000; VoidBolt_Timer = 30000; Rage_Timer = 60000; //Cast rage after 1 minute Hound_Timer = 8000; } void EnterCombat(Unit* /*who*/) { } void KilledUnit(Unit* /*victim*/) { // When a player, pet or totem gets killed, Lord Kazzak casts this spell to instantly regenerate 70, 000 health. DoCast(me, SPELL_CAPTURESOUL); } void SummonHounds(Unit* victim) { if (Creature* Hound = DoSpawnCreature(19207, float(irand(-9, 9)), float(irand(-9, 9)), 0, 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000)) Hound->AI()->AttackStart(victim); } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; //ShadowVolley_Timer if (ShadowVolley_Timer <= diff) { if (urand(0, 99) < 45) DoCast(me->getVictim(), SPELL_SHADOWVOLLEY); ShadowVolley_Timer = 5000; } else ShadowVolley_Timer -= diff; //Cleave_Timer if (Cleave_Timer <= diff) { if (urand(0, 1)) DoCast(me->getVictim(), SPELL_CLEAVE); Cleave_Timer = 10000; } else Cleave_Timer -= diff; //ThunderClap_Timer if (ThunderClap_Timer <= diff) { if (urand(0, 9) < 2) DoCast(me->getVictim(), SPELL_THUNDERCLAP); ThunderClap_Timer = 12000; } else ThunderClap_Timer -= diff; //TwistedReflection_Timer if (TwistedReflection_Timer <= diff) { DoCast(me->getVictim(), SPELL_TWISTEDREFLECTION); TwistedReflection_Timer = 30000; } else TwistedReflection_Timer -= diff; //VoidBolt_Timer if (VoidBolt_Timer <= diff) { if (urand(0, 9) < 4) DoCast(me->getVictim(), SPELL_VOIDBOLT); VoidBolt_Timer = 18000; } else VoidBolt_Timer -= diff; //Rage_Timer if (Rage_Timer <= diff) { DoCast(me, SPELL_RAGE); Rage_Timer = 70000; } else Rage_Timer -= diff; //Hound_Timer if (Hound_Timer <= diff) { SummonHounds(me->getVictim()); SummonHounds(me->getVictim()); SummonHounds(me->getVictim()); Hound_Timer = 45000; } else Hound_Timer -= diff; DoMeleeAttackIfReady(); } }; }; void AddSC_boss_kruul() { new boss_kruul(); }
30.614907
149
0.570095
499453466
6a1bf2a0a8845e5702d859668cf91e36c1baea15
21,778
cpp
C++
Samples/Win7Samples/security/parentalcontrols/complianceapi/ComplianceAPI.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/security/parentalcontrols/complianceapi/ComplianceAPI.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/security/parentalcontrols/complianceapi/ComplianceAPI.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. /**************************************************************************** FILE: Windows Parental Controls (WPC) Compliance API sample PURPOSE: Demonstrates usage of COM Compliance API used by applications not needing to manage settings via WMI. FUNCTIONS: wmain() - implements overall command line application WpcsCmplApiUserIsLoggingRequired() - updates out param flag specifying whether activity logging policy is on for a user WpcsCmplApiUserSettingsChangeTime() - sets out param time of last change in policy settings for a user WpcsCmplApiUserGetRestrictions() - sets bitfields in out param DWORD of active restriction silos for a user WpcsCmplApiGamesIsBlocked() - sets out param DWORD reason code for any blocking of game specified by AppID GUID for a user WpcsCmplApiWebGetSettings() - sets bitfields in out param DWORD of active web restriction policies for a user WpcsCmplApiWebRequestUrlOverride() - specifying a URL and optionally a set of associated subURLs, this method fires an administrator override request dialog CmdLineParse() - helper handling command line input COMMENTS: None of the Compliance API functions change state of policy settings for a user ****************************************************************************/ #include "ComplianceAPI.h" HRESULT WpcsCmplApiUserIsLoggingRequired(IWindowsParentalControls* pWPC, PCWSTR pcszSID, BOOL* pfLoggingRequired); HRESULT WpcsCmplApiUserSettingsChangeTime(IWindowsParentalControls* pWPC, PCWSTR pcszSID, SYSTEMTIME* pLastTime); HRESULT WpcsCmplApiUserGetRestrictions(IWindowsParentalControls* pWPC, PCWSTR pcszSID, DWORD* pdwRestrictions); HRESULT WpcsCmplApiGamesIsBlocked(IWindowsParentalControls* pWPC, PCWSTR pcszSID, GUID guidAppID, DWORD* pdwBlockedReasons); HRESULT WpcsCmplApiWebGetSettings(IWindowsParentalControls* pWPC, PCWSTR pcszSID, DWORD* pdwWebSettings); HRESULT WpcsCmplApiWebRequestUrlOverride(IWindowsParentalControls* pWPC, HWND hAppWindow, PCWSTR pcszSID, PCWSTR pcszUrl, DWORD dwNumSubUrl, PCWSTR* ppcszSubUrl, BOOL* pfChanged); HRESULT CmdLineParse(int argc, WCHAR* argv[], PARSERESULT* pParseResult); void Usage (PCWSTR pcszProgramName); // call as Usage(argv[0]) void Usage (PCWSTR pcszProgramName) { wprintf(L"Usage: %s [<username>] <function> [additional args]\n", pcszProgramName); wprintf(L" Note: If user name is not specified, report is for current user\n\n"); wprintf(L" Where functions, and arguments are as follows:\n\n"); wprintf(L" user \t\t\t\tShow settings for user\n\n"); wprintf(L"isgameblocked <app ID GUID> \tShow if and why blocked for \n \ \t\t\tspecified game\n\n"); wprintf(L"requrloverride <url> [<subURL1> <subURL2> ..]\n"); wprintf(L"\t\t\t\tRequest URL override, \n\t\t\t\tshowing changed status response\n\n"); } // Application entry point int __cdecl wmain(int argc, __in_ecount(argc) WCHAR* argv[]) { // Declare command line parsing result structure PARSERESULT stParseResult; // Parse operational mode and arguments from command line. // Function is responsible for printing its own errors. HRESULT hr = CmdLineParse(argc, argv, &stParseResult); if (hr == E_INVALIDARG) { // Printf usage and bypass further initialization Usage(argv[0]); } else if (SUCCEEDED(hr)) { hr = WpcuCOMInit(); if (FAILED(hr)) { wprintf(L"Error: Failed to initialize COM, hr is %8x.\n", hr); } else { // Obtain Compliance Interface IWindowsParentalControls* piWPC; hr = CoCreateInstance(__uuidof(WindowsParentalControls), 0, CLSCTX_INPROC_SERVER, __uuidof(IWindowsParentalControls), (LPVOID *)&piWPC); if (FAILED(hr)) { wprintf(L"Info: Parental Controls interface not detected.\n"); wprintf(L"Info: This is an error if on a supported SKU.\n"); hr = E_FAIL; } else { // Perform mode-specific operations switch (stParseResult.eOperation) { case OPERATION_USER: { BOOL fLoggingRequired; SYSTEMTIME LastTime; DWORD dwUserRestrictions; DWORD dwWebSettings; hr = WpcsCmplApiUserIsLoggingRequired(piWPC, stParseResult.pszSID, &fLoggingRequired); if (FAILED(hr)) { wprintf(L"Error: WpcsCmplApiUserIsLoggingRequired() failed, hr is %8x.\n", hr); } else { // Print results hr = WpcsCmplApiUserSettingsChangeTime(piWPC, stParseResult.pszSID, &LastTime); if (FAILED(hr)) { wprintf(L"Error: WpcsCmplApiUserSettingsChangeTime() failed, hr is %8x.\n", hr); } else { hr = WpcsCmplApiUserGetRestrictions(piWPC, stParseResult.pszSID, &dwUserRestrictions); if (FAILED(hr)) { wprintf(L"Error: WpcsCmplApiUserGetRestrictions() failed, hr is %8x.\n", hr); } else { hr = WpcsCmplApiWebGetSettings(piWPC, stParseResult.pszSID, &dwWebSettings); if (FAILED(hr)) { wprintf(L"Error: WpcsmplApiWebGetSettings() failed, hr is %8x.\n", hr); } else { wprintf(L"Info: User IsLoggingRequired is %s\n", (fLoggingRequired == TRUE) ? L"TRUE" : L"FALSE"); // Display SYSTEMTIME info wprintf(L"Info: Last settings change time is %4d/%02d/%02d %02d:%02d:%02d.%03d UTC\n", LastTime.wYear, LastTime.wMonth, LastTime.wDay, LastTime.wHour, LastTime.wMinute, LastTime.wSecond, LastTime.wMilliseconds); // Print web settings wprintf(L"Info: User web settings:"); if (dwWebSettings == WPCFLAG_WEB_SETTING_NOTBLOCKED) { wprintf(L" No blocking\n"); } else { // Leave room for future expansion wprintf(L"\t Download blocking is %s\n", (dwWebSettings & WPCFLAG_WEB_SETTING_DOWNLOADSBLOCKED) ? L"on" : L"off"); } // Print user restrictions fields wprintf(L"Info: User restrictions:"); if (dwUserRestrictions == WPCFLAG_NO_RESTRICTION) { wprintf(L"\t None\n"); } else { wprintf(L"\n\t Logging required is %s\n", (dwUserRestrictions & WPCFLAG_LOGGING_REQUIRED) ? L"on" : L"off"); wprintf(L"\t Web restrictions are %s\n", (dwUserRestrictions & WPCFLAG_WEB_FILTERED) ? L"on" : L"off"); wprintf(L"\t Hours restrictions are %s\n", (dwUserRestrictions & WPCFLAG_HOURS_RESTRICTED) ? L"on" : L"off"); wprintf(L"\t Games restrictions are %s\n", (dwUserRestrictions & WPCFLAG_HOURS_RESTRICTED) ? L"on" : L"off"); wprintf(L"\t Application restrictions are %s\n", (dwUserRestrictions & WPCFLAG_APPS_RESTRICTED) ? L"on" : L"off"); } } } } } } break; case OPERATION_ISGAMEBLOCKED: { DWORD dwBlockedReasons = 0; hr = WpcsCmplApiGamesIsBlocked(piWPC, stParseResult.pszSID, stParseResult.guidAppID, &dwBlockedReasons); if (FAILED(hr)) { wprintf(L"Error: WpcsCmplApiGamesIsBlocked() failed, hr is %8x.\n", hr); } else { // Print games IsBlocked reasons wprintf(L"Info: Games IsBlocked reason:\n"); if (dwBlockedReasons == WPCFLAG_ISBLOCKED_NOTBLOCKED) { wprintf(L"\tNot blocked\n"); } else if (dwBlockedReasons == WPCFLAG_ISBLOCKED_INTERNALERROR) { wprintf(L"tInternal error\n"); } else if (dwBlockedReasons & WPCFLAG_ISBLOCKED_EXPLICITBLOCK) { wprintf(L"\tExplicit block\n"); } else if (dwBlockedReasons & WPCFLAG_ISBLOCKED_RATINGBLOCKED) { wprintf(L"\tRating block\n"); } else if (dwBlockedReasons & WPCFLAG_ISBLOCKED_DESCRIPTORBLOCKED) { wprintf(L"\tRating descriptor block\n"); } else { wprintf(L"\tUnknown reason\n"); } } } break; case OPERATION_REQUESTURLOVERRIDE: { BOOL fChanged = FALSE; // Pass in handle of application main window. For purposes of this console-based // sample, NULL is used hr = WpcsCmplApiWebRequestUrlOverride(piWPC, NULL, stParseResult.pszSID, stParseResult.stRequestUrlOverride.pszUrl, stParseResult.stRequestUrlOverride.dwNumSubUrl, stParseResult.stRequestUrlOverride.ppcszSubUrl, &fChanged); if (FAILED(hr)) { wprintf(L"Error: WpcsCmplApiWebRequestUrlOverride() failed, hr is %8x.\n", hr); } else { wprintf(L"Info: User web request URL override changed is %s.\n", fChanged ? L"TRUE" : L"FALSE"); } } break; } piWPC->Release(); } WpcuCOMCleanup(); } } if (stParseResult.pszSID) { LocalFree(stParseResult.pszSID); } return (SUCCEEDED(hr)) ? 0 : 1; } HRESULT WpcsCmplApiUserIsLoggingRequired(IWindowsParentalControls* piWPC, PCWSTR pcszSID, BOOL* pfLoggingRequired) { HRESULT hr = E_INVALIDARG; // Do basic parameter validation. Allow NULL pcszSID to signal method to // use current user SID if (piWPC && pfLoggingRequired) { // Obtain WpcUserSettings interface IWPCSettings* piWPCSettings = NULL; hr = piWPC->GetUserSettings(pcszSID, &piWPCSettings); if (SUCCEEDED(hr)) { // Call method hr = piWPCSettings->IsLoggingRequired(pfLoggingRequired); piWPCSettings->Release(); } } return (hr); } HRESULT WpcsCmplApiUserSettingsChangeTime(IWindowsParentalControls* piWPC, PCWSTR pcszSID, SYSTEMTIME* pLastTime) { HRESULT hr = E_INVALIDARG; // Do basic parameter validation. Allow NULL pcszSID to signal method to // use current user SID if (piWPC && pLastTime) { // Obtain WpcUserSettings interface IWPCSettings* piWPCSettings = NULL; hr = piWPC->GetUserSettings(pcszSID, &piWPCSettings); if (SUCCEEDED(hr)) { // Call method hr = piWPCSettings->GetLastSettingsChangeTime(pLastTime); piWPCSettings->Release(); } } return (hr); } HRESULT WpcsCmplApiUserGetRestrictions(IWindowsParentalControls* piWPC, PCWSTR pcszSID, DWORD* pdwRestrictions) { HRESULT hr = E_INVALIDARG; // Do basic parameter validation. Allow NULL pcszSID to signal method to // use current user SID if (piWPC && pdwRestrictions) { // Obtain WpcUserSettings interface IWPCSettings* piWPCSettings = NULL; hr = piWPC->GetUserSettings(pcszSID, &piWPCSettings); if (SUCCEEDED(hr)) { // Call method hr = piWPCSettings->GetRestrictions(pdwRestrictions); piWPCSettings->Release(); } } return (hr); } HRESULT WpcsCmplApiGamesIsBlocked(IWindowsParentalControls* piWPC, PCWSTR pcszSID, GUID guidAppID, DWORD* pdwBlockedReasons) { HRESULT hr = E_INVALIDARG; // Do basic parameter validation. Allow NULL pcszSID to signal method to // use current user SID if (piWPC && pdwBlockedReasons) { // Obtain WpcGamesSettings interface IWPCGamesSettings* piWPCGamesSettings = NULL; hr = piWPC->GetGamesSettings(pcszSID, &piWPCGamesSettings); if (SUCCEEDED(hr)) { // Call method hr = piWPCGamesSettings->IsBlocked(guidAppID, pdwBlockedReasons); piWPCGamesSettings->Release(); } } return (hr); } HRESULT WpcsCmplApiWebGetSettings(IWindowsParentalControls* piWPC, PCWSTR pcszSID, DWORD* pdwWebSettings) { HRESULT hr = E_INVALIDARG; // Do basic parameter validation. Allow NULL pcszSID to signal method to // use current user SID if (piWPC && pdwWebSettings) { // Obtain WpcWebSettings interface IWPCWebSettings* piWPCWebSettings = NULL; hr = piWPC->GetWebSettings(pcszSID, &piWPCWebSettings); if (SUCCEEDED(hr)) { // Call method hr = piWPCWebSettings->GetSettings(pdwWebSettings); piWPCWebSettings->Release(); } } return (hr); } HRESULT WpcsCmplApiWebRequestUrlOverride(IWindowsParentalControls* piWPC, HWND hAppWindow, PCWSTR pcszSID, PCWSTR pcszUrl, DWORD dwNumSubUrl, PCWSTR* ppcszSubUrl, BOOL* pfChanged) { HRESULT hr = E_INVALIDARG; // Do basic parameter validation. Allow NULL pcszSID to signal method to // use current user SID if (piWPC && pcszUrl && (!dwNumSubUrl || ppcszSubUrl) && pfChanged) { // Obtain WpcWebSettings interface IWPCWebSettings* piWPCWebSettings = NULL; hr = piWPC->GetWebSettings(pcszSID, &piWPCWebSettings); if (SUCCEEDED(hr)) { // Call method hr = piWPCWebSettings->RequestURLOverride(hAppWindow, pcszUrl, dwNumSubUrl, ppcszSubUrl, pfChanged); piWPCWebSettings->Release(); } } return (hr); } // // Helper functions // // Parse the command line HRESULT CmdLineParse(int argc, WCHAR* argv[], PARSERESULT* pParseResult) { // Default is invalid until args are validated HRESULT hr = E_INVALIDARG; // Do basic parameter validation if (pParseResult && argc >= ARGS_MIN) { ZeroMemory(pParseResult, sizeof(PARSERESULT)); BOOL fOperation = FALSE; PCWSTR pcszUserName = NULL; int i; // Determine operational mode and check prerequisites for (i = 1; !fOperation && i < 3 && i < argc; ++i) { if (_wcsicmp(argv[i], L"user") == 0) { pParseResult->eOperation = OPERATION_USER; fOperation = TRUE; } else if (_wcsicmp(argv[i], L"requrloverride") == 0) { pParseResult->eOperation = OPERATION_REQUESTURLOVERRIDE; fOperation = TRUE; } else if (_wcsicmp(argv[i], L"isgameblocked") == 0) { pParseResult->eOperation = OPERATION_ISGAMEBLOCKED; fOperation = TRUE; } if (fOperation && (i == 2)) { //there is a username pcszUserName = argv[1]; } } if (fOperation) { hr = S_OK; switch (pParseResult->eOperation) { case OPERATION_ISGAMEBLOCKED: if (i == argc) { // No app ID hr = E_INVALIDARG; } else { hr = CLSIDFromString(argv[i], &(pParseResult->guidAppID)); } break; case OPERATION_REQUESTURLOVERRIDE: if (i == argc) { // No URL hr = E_INVALIDARG; } else { pParseResult->stRequestUrlOverride.dwNumSubUrl = argc - i -1; pParseResult->stRequestUrlOverride.pszUrl = argv[i]; if (pParseResult->stRequestUrlOverride.dwNumSubUrl > 0) { pParseResult->stRequestUrlOverride.ppcszSubUrl = (PCWSTR*)(&(argv[i+1])); } } break; } } if (SUCCEEDED(hr) && pcszUserName) { // Function allocates local memory for pszSID buffer hr = WpcuSidStringFromUserName(pcszUserName, &pParseResult->pszSID); } } return (hr); }
41.403042
129
0.45298
windows-development
6a1d79cb6463af2a042e131b1402ca061f4d9a6b
6,442
cpp
C++
IndyGL/src/Shader/GLSLShaderProgram.cpp
JJoosten/IndyFramework
7f9441de8baf5c43370357f463d39f4aa60f38a0
[ "MIT" ]
null
null
null
IndyGL/src/Shader/GLSLShaderProgram.cpp
JJoosten/IndyFramework
7f9441de8baf5c43370357f463d39f4aa60f38a0
[ "MIT" ]
null
null
null
IndyGL/src/Shader/GLSLShaderProgram.cpp
JJoosten/IndyFramework
7f9441de8baf5c43370357f463d39f4aa60f38a0
[ "MIT" ]
null
null
null
// Juul Joosten 2013 #include "GLSLShaderProgram.h" #include "GLSLShader.h" #include <IndyCore/CoreDefines.h> namespace Indy { GLSLShaderProgram::GLSLShaderProgram( void) : m_shaderProgramID(0) ,m_vertexShader(NULL) ,m_fragmentShader(NULL) ,m_geometryShader(NULL) ,m_computeShader(NULL) ,m_tesselationControlShader(NULL) ,m_tesselationEvaluationShader(NULL) { } GLSLShaderProgram::~GLSLShaderProgram( void) { if( m_shaderProgramID != 0) BREAKPOINT(GLSLShaderProgram is not yet destroyed use Destroy to destroy the program); } void GLSLShaderProgram::SetVertexShader ( GLSLShader* const vertexShader) { if( m_vertexShader != NULL) m_vertexShader->substractFromReferenceCounter(); m_vertexShader = vertexShader; m_vertexShader->addToReferenceCounter(); } void GLSLShaderProgram::SetFragmentShader( GLSLShader* const fragmentShader) { if( m_fragmentShader != NULL) m_fragmentShader->substractFromReferenceCounter(); m_fragmentShader = fragmentShader; m_fragmentShader->addToReferenceCounter(); } void GLSLShaderProgram::SetGeometryShader( GLSLShader* const geometryShader) { if( m_geometryShader != NULL) m_geometryShader->substractFromReferenceCounter(); m_geometryShader = geometryShader; m_geometryShader->addToReferenceCounter(); } void GLSLShaderProgram::SetComputeShader ( GLSLShader* const computeShader) { if( m_computeShader != NULL) m_computeShader->substractFromReferenceCounter(); m_computeShader = computeShader; m_computeShader->addToReferenceCounter(); } void GLSLShaderProgram::SetTesselationControlShader( GLSLShader* const tesselationControlShader) { if( m_tesselationControlShader != NULL) m_tesselationControlShader->substractFromReferenceCounter(); m_tesselationControlShader = tesselationControlShader; m_tesselationControlShader->addToReferenceCounter(); } void GLSLShaderProgram::SetTesselationEvaluationShader( GLSLShader* const tesselationEvaluationShader) { if( m_tesselationEvaluationShader != NULL) m_tesselationEvaluationShader->substractFromReferenceCounter(); m_tesselationEvaluationShader = tesselationEvaluationShader; m_tesselationEvaluationShader->addToReferenceCounter(); } void GLSLShaderProgram::Create( void) { m_shaderProgramID = glCreateProgram(); } void GLSLShaderProgram::Destroy( void) { if( m_shaderProgramID == 0) BREAKPOINT(GLSLShaderProgram was already destroyed or not created); if( m_vertexShader != NULL) { glDetachShader( m_shaderProgramID, m_vertexShader->GetID()); m_vertexShader->substractFromReferenceCounter(); } if( m_fragmentShader != NULL) { glDetachShader( m_shaderProgramID, m_fragmentShader->GetID()); m_fragmentShader->substractFromReferenceCounter(); } if( m_geometryShader != NULL) { glDetachShader( m_shaderProgramID, m_geometryShader->GetID()); m_geometryShader->substractFromReferenceCounter(); } if( m_computeShader != NULL) { glDetachShader( m_shaderProgramID, m_computeShader->GetID()); m_computeShader->substractFromReferenceCounter(); } glDeleteProgram( m_shaderProgramID); m_shaderProgramID = 0; } bool GLSLShaderProgram::Link( void) const { if( m_vertexShader != NULL) glAttachShader( m_shaderProgramID, m_vertexShader->GetID()); if( m_fragmentShader != NULL) glAttachShader( m_shaderProgramID, m_fragmentShader->GetID()); if( m_geometryShader != NULL) glAttachShader( m_shaderProgramID, m_geometryShader->GetID()); if( m_computeShader != NULL) glAttachShader( m_shaderProgramID, m_computeShader->GetID()); glLinkProgram( m_shaderProgramID); GLint result = 0xDEADBEEF; glGetProgramiv( m_shaderProgramID, GL_LINK_STATUS, &result); if ( result != GL_TRUE) { GLsizei stringLength = 1024; char infoLog[1024]; memset( infoLog, 0, 1024); glGetProgramInfoLog( m_shaderProgramID, stringLength, 0, infoLog); printf("Shader Error Log: %s \n", infoLog); BREAKPOINT( Shader link error occured); return false; } return true; } void GLSLShaderProgram::Bind( void) const { if( m_shaderProgramID == 0) BREAKPOINT(Shader Program is not yet created); glUseProgram( m_shaderProgramID); } void GLSLShaderProgram::Unbind( void) const { glUseProgram(NULL); } GLuint GLSLShaderProgram::GetUniformBlockIndex( const GLchar* uniformBlockName) const { GLuint location = glGetUniformBlockIndex( m_shaderProgramID, uniformBlockName); return location; } GLint GLSLShaderProgram::GetUniformLocation( const GLchar* uniform) const { return glGetUniformLocation( m_shaderProgramID, uniform); } void GLSLShaderProgram::SetUniformf( const GLchar* uniform, const GLfloat value) const { SetUniformf( GetUniformLocation(uniform), value); } void GLSLShaderProgram::SetUniformf( const GLint location, const GLfloat value) const { glUniform1f( location, value); } void GLSLShaderProgram::SetUniform3f( const GLchar* uniform, const GLfloat* value) const { SetUniform3f( GetUniformLocation( uniform), value); } void GLSLShaderProgram::SetUniform3f( const GLint location, const GLfloat* value) const { glUniform3fv( location, 1, value); } void GLSLShaderProgram::SetUniform4x4f( const GLchar* uniform, const GLfloat* value, const GLboolean transpose /* = GL_FALSE */) const { SetUniform4x4f( GetUniformLocation(uniform), value, transpose); } void GLSLShaderProgram::SetUniform4x4f( const GLint location, const GLfloat* value, const GLboolean transpose /* = GL_FALSE */) const { glUniformMatrix4fv( location, 1, transpose, value); } void GLSLShaderProgram::SetUniformi( const GLchar* uniform, const GLint value) const { SetUniformi( GetUniformLocation(uniform), value); } void GLSLShaderProgram::SetUniformi( const GLint location, const GLint value) const { glUniform1i( location, value); } void GLSLShaderProgram::SetUniform2i( const GLchar* uniform, const GLint* value) const { SetUniform2i( GetUniformLocation(uniform), value); } void GLSLShaderProgram::SetUniform2i( const GLint location, const GLint* value) const { glUniform2iv( location, 1, value); } void GLSLShaderProgram::SetUniform2f(const GLchar* uniform, const GLfloat* value) const { SetUniform2f(GetUniformLocation(uniform), value); } void GLSLShaderProgram::SetUniform2f(const GLint location, const GLfloat* value) const { glUniform2fv(location, 1, value); } }
25.164063
135
0.760323
JJoosten
6a1f4c35a0d06d8dc24816604417df6d3dfa512b
2,618
cpp
C++
semester-3/programming-design-and-programming-languages/labs/lab_12/src/UserClass.cpp
Xotab413/bsuir
ae051db9fb237ab78bc0104a3682075d23c88b57
[ "MIT" ]
3
2022-01-19T06:20:41.000Z
2022-02-16T18:19:27.000Z
semester-3/programming-design-and-programming-languages/labs/lab_12/src/UserClass.cpp
Xotab413/bsuir
ae051db9fb237ab78bc0104a3682075d23c88b57
[ "MIT" ]
null
null
null
semester-3/programming-design-and-programming-languages/labs/lab_12/src/UserClass.cpp
Xotab413/bsuir
ae051db9fb237ab78bc0104a3682075d23c88b57
[ "MIT" ]
3
2022-02-24T08:01:17.000Z
2022-03-23T13:25:45.000Z
#include "UserClass.hpp" void UserClass:: Display() { std::cout << "UserClass data:" << std::endl; for (auto it = data.begin(); it != data.end(); ++it) { std::cout << "Key: " << it -> first << " Data: " << it -> second << std::endl; } } UserClass::UserClass() { } void UserClass::Setdata(char key, int Data) { std::cout << "Устанавливаем данные в std::map в UserClass" << std::endl; this -> data[key] = Data; } void UserClass::Operation() { std::cout << "Выполняются математические операции" << std::endl; int i = 0; for (auto it = data.begin(); it != data.end(); ++it, i++) { it -> second += i * 5; it -> second += 12; it -> second --; } } void UserClass::WriteInFile() { std::ofstream on; try { std::cout << "BLOCK TRY" << std::endl; on.open("../resultFile.txt"); std::cout << "Файл resultFile.txt открыт" << std::endl; } catch (std::exception &ex) { std::cout << "BLOCK CATCH" << std::endl; ex.what(); } for (auto it = data.begin(); it != data.end(); ++it) { on << it -> first << '=' << it -> second << '\n'; } on.close(); } void UserClass::AddInformation() { std::cout << "enter key" << std::endl; char key; std::cin >> key; std::cout << "Enter number" << std::endl; int number = enteringANumber(); data.emplace(key,number); std::cout << std::endl << std::endl; } void UserClass:: MathOperation() { for (auto it = data.begin(); it != data.end(); ++it) { std::cout << "Enter number" << std::endl; std::cout << "1 - +" << std::endl; std::cout << "2 - -" << std::endl; std::cout << "3 - *" << std::endl; std::cout << "4 - /" << std::endl; int mathOperation = enteringANumber(); if (mathOperation == 1) { std::cout << "Enter number" << std::endl; int number = enteringANumber(); it -> second += number; } if (mathOperation == 2) { std::cout << "Enter number" << std::endl; int number = enteringANumber(); it -> second -= number; } if (mathOperation == 3) { std::cout << "Enter number" << std::endl; int number = enteringANumber(); it -> second *= number; } if (mathOperation == 4) { std::cout << "Enter number" << std::endl; int number = enteringANumber(); it -> second /= number; } std::cout << std::endl << std::endl; } }
28.456522
86
0.482811
Xotab413
6a1f6f73489d592de1dd21837869c636ac4760e3
16,645
cpp
C++
Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp
Jackerty/o3de
f521a288cf020d166949c1dc243c4938539b5244
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp
Jackerty/o3de
f521a288cf020d166949c1dc243c4938539b5244
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp
Jackerty/o3de
f521a288cf020d166949c1dc243c4938539b5244
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Atom/Feature/Material/MaterialAssignment.h> #include <Atom/RPI.Reflect/Model/ModelAsset.h> #include <AzCore/Asset/AssetSerializer.h> #include <AzCore/RTTI/BehaviorContext.h> #include <AzCore/Serialization/EditContext.h> #include <AzCore/Serialization/Json/RegistrationContext.h> #include <AzCore/Serialization/SerializeContext.h> #include <Material/MaterialAssignmentSerializer.h> namespace AZ { namespace Render { void MaterialAssignment::Reflect(ReflectContext* context) { MaterialAssignmentId::Reflect(context); if (auto jsonContext = azrtti_cast<JsonRegistrationContext*>(context)) { jsonContext->Serializer<JsonMaterialAssignmentSerializer>()->HandlesType<MaterialAssignment>(); } if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) { serializeContext->RegisterGenericType<MaterialAssignmentMap>(); serializeContext->RegisterGenericType<MaterialPropertyOverrideMap>(); serializeContext->Class<MaterialAssignment>() ->Version(2) ->Field("MaterialAsset", &MaterialAssignment::m_materialAsset) ->Field("PropertyOverrides", &MaterialAssignment::m_propertyOverrides) ->Field("ModelUvOverrides", &MaterialAssignment::m_matModUvOverrides) ; if (auto editContext = serializeContext->GetEditContext()) { editContext->Class<MaterialAssignment>( "Material Assignment", "Material Assignment") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Show) ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialAssignment::m_materialAsset, "Material Asset", "") ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialAssignment::m_propertyOverrides, "Property Overrides", "") ; } } if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context)) { behaviorContext->Class<MaterialAssignment>("MaterialAssignment") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "render") ->Attribute(AZ::Script::Attributes::Module, "render") ->Constructor() ->Constructor<const MaterialAssignment&>() ->Constructor<const AZ::Data::AssetId&>() ->Constructor<const Data::Asset<RPI::MaterialAsset>&>() ->Constructor<const Data::Asset<RPI::MaterialAsset>&, const Data::Instance<RPI::Material>&>() ->Method("ToString", &MaterialAssignment::ToString) ->Property("materialAsset", BehaviorValueProperty(&MaterialAssignment::m_materialAsset)) ->Property("propertyOverrides", BehaviorValueProperty(&MaterialAssignment::m_propertyOverrides)); behaviorContext->ConstantProperty("DefaultMaterialAssignment", BehaviorConstant(DefaultMaterialAssignment)) ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "render") ->Attribute(AZ::Script::Attributes::Module, "render"); behaviorContext->ConstantProperty("DefaultMaterialAssignmentId", BehaviorConstant(DefaultMaterialAssignmentId)) ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "render") ->Attribute(AZ::Script::Attributes::Module, "render"); behaviorContext->ConstantProperty("DefaultMaterialAssignmentMap", BehaviorConstant(DefaultMaterialAssignmentMap)) ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "render") ->Attribute(AZ::Script::Attributes::Module, "render"); } } MaterialAssignment::MaterialAssignment(const AZ::Data::AssetId& materialAssetId) : m_materialAsset(materialAssetId, AZ::AzTypeInfo<AZ::RPI::MaterialAsset>::Uuid()) , m_materialInstance() { } MaterialAssignment::MaterialAssignment(const Data::Asset<RPI::MaterialAsset>& asset) : m_materialAsset(asset) , m_materialInstance() { } MaterialAssignment::MaterialAssignment(const Data::Asset<RPI::MaterialAsset>& asset, const Data::Instance<RPI::Material>& instance) : m_materialAsset(asset) , m_materialInstance(instance) { } void MaterialAssignment::RebuildInstance() { if (m_materialInstancePreCreated) { return; } if (m_materialAsset.IsReady()) { m_materialInstance = m_propertyOverrides.empty() ? RPI::Material::FindOrCreate(m_materialAsset) : RPI::Material::Create(m_materialAsset); AZ_Error("MaterialAssignment", m_materialInstance, "Material instance not initialized"); return; } if (m_defaultMaterialAsset.IsReady()) { m_materialInstance = m_propertyOverrides.empty() ? RPI::Material::FindOrCreate(m_defaultMaterialAsset) : RPI::Material::Create(m_defaultMaterialAsset); AZ_Error("MaterialAssignment", m_materialInstance, "Material instance not initialized"); return; } // Clear the existing material instance if no asset was ready m_materialInstance = nullptr; } void MaterialAssignment::Release() { if (!m_materialInstancePreCreated) { m_materialInstance = nullptr; } m_materialAsset.Release(); m_defaultMaterialAsset.Release(); } bool MaterialAssignment::RequiresLoading() const { return !m_materialInstancePreCreated && !m_materialAsset.IsReady() && !m_materialAsset.IsLoading() && !m_defaultMaterialAsset.IsReady() && !m_defaultMaterialAsset.IsLoading(); } bool MaterialAssignment::ApplyProperties() { // if there is no instance or no properties there's nothing to apply if (!m_materialInstance || m_propertyOverrides.empty()) { return true; } if (m_materialInstance->CanCompile()) { for (const auto& propertyPair : m_propertyOverrides) { if (!propertyPair.second.empty()) { bool wasRenamed = false; Name newName; RPI::MaterialPropertyIndex materialPropertyIndex = m_materialInstance->FindPropertyIndex(propertyPair.first, &wasRenamed, &newName); // FindPropertyIndex will have already reported a message about what the old and new names are. Here we just add // some extra info to help the user resolve it. AZ_Warning( "MaterialAssignment", !wasRenamed, "Consider running \"Apply Automatic Property Updates\" to use the latest property names.", propertyPair.first.GetCStr(), newName.GetCStr()); if (wasRenamed && m_propertyOverrides.find(newName) != m_propertyOverrides.end()) { materialPropertyIndex.Reset(); AZ_Warning( "MaterialAssignment", false, "Material property '%s' has been renamed to '%s', and a property override exists for both. The one with " "the old name will be ignored.", propertyPair.first.GetCStr(), newName.GetCStr()); } if (!materialPropertyIndex.IsNull()) { const auto propertyDescriptor = m_materialInstance->GetMaterialPropertiesLayout()->GetPropertyDescriptor(materialPropertyIndex); m_materialInstance->SetPropertyValue( materialPropertyIndex, ConvertMaterialPropertyValueFromScript(propertyDescriptor, propertyPair.second)); } } } return m_materialInstance->Compile(); } return false; } AZStd::string MaterialAssignment::ToString() const { AZStd::string assetPathString; AZ::Data::AssetCatalogRequestBus::BroadcastResult( assetPathString, &AZ::Data::AssetCatalogRequests::GetAssetPathById, m_materialAsset.GetId()); return assetPathString; } const MaterialAssignment& GetMaterialAssignmentFromMap(const MaterialAssignmentMap& materials, const MaterialAssignmentId& id) { const auto& materialItr = materials.find(id); return materialItr != materials.end() ? materialItr->second : DefaultMaterialAssignment; } const MaterialAssignment& GetMaterialAssignmentFromMapWithFallback( const MaterialAssignmentMap& materials, const MaterialAssignmentId& id) { const MaterialAssignment& lodAssignment = GetMaterialAssignmentFromMap(materials, id); if (lodAssignment.m_materialInstance.get()) { return lodAssignment; } const MaterialAssignment& assetAssignment = GetMaterialAssignmentFromMap(materials, MaterialAssignmentId::CreateFromStableIdOnly(id.m_materialSlotStableId)); if (assetAssignment.m_materialInstance.get()) { return assetAssignment; } const MaterialAssignment& defaultAssignment = GetMaterialAssignmentFromMap(materials, DefaultMaterialAssignmentId); if (defaultAssignment.m_materialInstance.get()) { return defaultAssignment; } return DefaultMaterialAssignment; } MaterialAssignmentMap GetMaterialAssignmentsFromModel(Data::Instance<AZ::RPI::Model> model) { MaterialAssignmentMap materials; materials[DefaultMaterialAssignmentId] = MaterialAssignment(); if (model) { size_t lodIndex = 0; for (const Data::Instance<AZ::RPI::ModelLod>& lod : model->GetLods()) { for (const AZ::RPI::ModelLod::Mesh& mesh : lod->GetMeshes()) { if (mesh.m_material) { const MaterialAssignmentId generalId = MaterialAssignmentId::CreateFromStableIdOnly(mesh.m_materialSlotStableId); materials[generalId] = MaterialAssignment(mesh.m_material->GetAsset(), mesh.m_material); const MaterialAssignmentId specificId = MaterialAssignmentId::CreateFromLodAndStableId(lodIndex, mesh.m_materialSlotStableId); materials[specificId] = MaterialAssignment(mesh.m_material->GetAsset(), mesh.m_material); } } ++lodIndex; } } return materials; } MaterialAssignmentId FindMaterialAssignmentIdInLod( const Data::Instance<AZ::RPI::Model>& model, const Data::Instance<AZ::RPI::ModelLod>& lod, const MaterialAssignmentLodIndex lodIndex, const AZStd::string& labelFilter) { for (const AZ::RPI::ModelLod::Mesh& mesh : lod->GetMeshes()) { const AZ::RPI::ModelMaterialSlot& slot = model->GetModelAsset()->FindMaterialSlot(mesh.m_materialSlotStableId); if (AZ::StringFunc::Contains(slot.m_displayName.GetCStr(), labelFilter, true)) { return MaterialAssignmentId::CreateFromLodAndStableId(lodIndex, mesh.m_materialSlotStableId); } } return MaterialAssignmentId(); } MaterialAssignmentId FindMaterialAssignmentIdInModel( const Data::Instance<AZ::RPI::Model>& model, const MaterialAssignmentLodIndex lodFilter, const AZStd::string& labelFilter) { if (model && !labelFilter.empty()) { if (lodFilter < model->GetLodCount()) { return FindMaterialAssignmentIdInLod(model, model->GetLods()[lodFilter], lodFilter, labelFilter); } for (size_t lodIndex = 0; lodIndex < model->GetLodCount(); ++lodIndex) { const MaterialAssignmentId result = FindMaterialAssignmentIdInLod(model, model->GetLods()[lodIndex], MaterialAssignmentId::NonLodIndex, labelFilter); if (!result.IsDefault()) { return result; } } } return MaterialAssignmentId(); } template<typename T> AZ::RPI::MaterialPropertyValue ConvertMaterialPropertyValueNumericType(const AZStd::any& value) { if (value.is<int32_t>()) { return aznumeric_cast<T>(AZStd::any_cast<int32_t>(value)); } if (value.is<uint32_t>()) { return aznumeric_cast<T>(AZStd::any_cast<uint32_t>(value)); } if (value.is<float>()) { return aznumeric_cast<T>(AZStd::any_cast<float>(value)); } if (value.is<double>()) { return aznumeric_cast<T>(AZStd::any_cast<double>(value)); } return AZ::RPI::MaterialPropertyValue::FromAny(value); } AZ::RPI::MaterialPropertyValue ConvertMaterialPropertyValueFromScript( const AZ::RPI::MaterialPropertyDescriptor* propertyDescriptor, const AZStd::any& value) { switch (propertyDescriptor->GetDataType()) { case AZ::RPI::MaterialPropertyDataType::Enum: if (value.is<AZ::Name>()) { return propertyDescriptor->GetEnumValue(AZStd::any_cast<AZ::Name>(value)); } if (value.is<AZStd::string>()) { return propertyDescriptor->GetEnumValue(AZ::Name(AZStd::any_cast<AZStd::string>(value))); } return ConvertMaterialPropertyValueNumericType<uint32_t>(value); case AZ::RPI::MaterialPropertyDataType::Int: return ConvertMaterialPropertyValueNumericType<int32_t>(value); case AZ::RPI::MaterialPropertyDataType::UInt: return ConvertMaterialPropertyValueNumericType<uint32_t>(value); case AZ::RPI::MaterialPropertyDataType::Float: return ConvertMaterialPropertyValueNumericType<float>(value); case AZ::RPI::MaterialPropertyDataType::Bool: return ConvertMaterialPropertyValueNumericType<bool>(value); default: break; } return AZ::RPI::MaterialPropertyValue::FromAny(value); } } // namespace Render } // namespace AZ
45.108401
167
0.571944
Jackerty
6a22a9bc3f90719b14e51054bc9edd1ced993620
173
cpp
C++
test/ios_test_cpp17.cpp
PVIII/cpp_utils
a85d43fedfef46afcd0fb28a0158f6ebe2f45685
[ "MIT" ]
null
null
null
test/ios_test_cpp17.cpp
PVIII/cpp_utils
a85d43fedfef46afcd0fb28a0158f6ebe2f45685
[ "MIT" ]
null
null
null
test/ios_test_cpp17.cpp
PVIII/cpp_utils
a85d43fedfef46afcd0fb28a0158f6ebe2f45685
[ "MIT" ]
null
null
null
#include "cpp_utils/ios.hpp" #include "catch2/catch.hpp" #include <iostream> #ifdef __cpp_deduction_guides SCENARIO("ios types") { ostream_capture c(std::cout); } #endif
17.3
55
0.745665
PVIII
6a28e6462b400d42665076ef43216bf94dbdbb88
19,118
cpp
C++
dep/src/g3dlite/prompt.cpp
Subv/diamondcore
e11891587736b6308e554f71cb56e8df1a1812ad
[ "OpenSSL" ]
1
2018-01-17T08:11:17.000Z
2018-01-17T08:11:17.000Z
dep/src/g3dlite/prompt.cpp
Subv/diamondcore
e11891587736b6308e554f71cb56e8df1a1812ad
[ "OpenSSL" ]
null
null
null
dep/src/g3dlite/prompt.cpp
Subv/diamondcore
e11891587736b6308e554f71cb56e8df1a1812ad
[ "OpenSSL" ]
null
null
null
/** @file prompt.cpp @author Morgan McGuire, http://graphics.cs.williams.edu @cite Windows dialog interface by Max McGuire, mmcguire@ironlore.com @cite Font setting code by Kurt Miller, kurt@flipcode.com @created 2000-08-26 @edited 2005-01-14 */ #include "G3D/prompt.h" #include "G3D/platform.h" #include <stdio.h> #ifdef G3D_WIN32 # include <sstream> # include <conio.h> #else # define _getch getchar #endif #ifdef G3D_OSX /*#ifdef __LP64__ # undef __LP64__ #endif */ # include <Carbon/Carbon.h> /* #ifdef G3D_64BIT # define __LP64__ #endif */ #endif namespace G3D { #ifdef G3D_WIN32 namespace _internal { /** Generic Win32 dialog facility. @author Max McGuire */ class DialogTemplate { public: DialogTemplate(LPCSTR caption, DWORD style, int x, int y, int w, int h, LPCSTR font = NULL, WORD fontSize = 8) { usedBufferLength = sizeof(DLGTEMPLATE); totalBufferLength = usedBufferLength; dialogTemplate = (DLGTEMPLATE*)malloc(totalBufferLength); dialogTemplate->style = style; if (font != NULL) { dialogTemplate->style |= DS_SETFONT; } dialogTemplate->x = (short)x; dialogTemplate->y = (short)y; dialogTemplate->cx = (short)w; dialogTemplate->cy = (short)h; dialogTemplate->cdit = 0; dialogTemplate->dwExtendedStyle = 0; // The dialog box doesn't have a menu or a special class AppendData("\0", 2); AppendData("\0", 2); // Add the dialog's caption to the template AppendString(caption); if (font != NULL) { AppendData(&fontSize, sizeof(WORD)); AppendString(font); } } void AddComponent(LPCSTR type, LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { DLGITEMTEMPLATE item; item.style = style; item.x = (short)x; item.y = (short)y; item.cx = (short)w; item.cy = (short)h; item.id = id; item.dwExtendedStyle = exStyle; AppendData(&item, sizeof(DLGITEMTEMPLATE)); AppendString(type); AppendString(caption); WORD creationDataLength = 0; AppendData(&creationDataLength, sizeof(WORD)); // Increment the component count dialogTemplate->cdit++; } void AddButton(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { AddStandardComponent(0x0080, caption, style, exStyle, x, y, w, h, id); WORD creationDataLength = 0; AppendData(&creationDataLength, sizeof(WORD)); } void AddEditBox(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { AddStandardComponent(0x0081, caption, style, exStyle, x, y, w, h, id); WORD creationDataLength = 0; AppendData(&creationDataLength, sizeof(WORD)); } void AddStatic(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { AddStandardComponent(0x0082, caption, style, exStyle, x, y, w, h, id); WORD creationDataLength = 0; AppendData(&creationDataLength, sizeof(WORD)); } void AddListBox(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { AddStandardComponent(0x0083, caption, style, exStyle, x, y, w, h, id); WORD creationDataLength = sizeof(WORD) + 5 * sizeof(WCHAR); AppendData(&creationDataLength, sizeof(WORD)); AppendString("TEST"); } void AddScrollBar(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { AddStandardComponent(0x0084, caption, style, exStyle, x, y, w, h, id); WORD creationDataLength = 0; AppendData(&creationDataLength, sizeof(WORD)); } void AddComboBox(LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id) { AddStandardComponent(0x0085, caption, style, exStyle, x, y, w, h, id); WORD creationDataLength = 0; AppendData(&creationDataLength, sizeof(WORD)); } /** * * Returns a pointer to the Win32 dialog template which the object * represents. This pointer may become invalid if additional components * are added to the template. * */ operator const DLGTEMPLATE*() const { return dialogTemplate; } virtual ~DialogTemplate() { free(dialogTemplate); } protected: void AddStandardComponent(WORD type, LPCSTR caption, DWORD style, DWORD exStyle, int x, int y, int w, int h, WORD id, LPSTR font = NULL, WORD fontSize = 8) { DLGITEMTEMPLATE item; // DWORD align the beginning of the component data AlignData(sizeof(DWORD)); item.style = style; if (font != NULL) { item.style |= DS_SETFONT; } item.x = (short)x; item.y = (short)y; item.cx = (short)w; item.cy = (short)h; item.id = id; item.dwExtendedStyle = exStyle; AppendData(&item, sizeof(DLGITEMTEMPLATE)); WORD preType = 0xFFFF; AppendData(&preType, sizeof(WORD)); AppendData(&type, sizeof(WORD)); AppendString(caption); if (font != NULL) { AppendData(&fontSize, sizeof(WORD)); AppendString(font); } // Increment the component count dialogTemplate->cdit++; } void AlignData(int size) { int paddingSize = usedBufferLength % size; if (paddingSize != 0) { EnsureSpace(paddingSize); usedBufferLength += paddingSize; } } void AppendString(LPCSTR string) { int length = MultiByteToWideChar(CP_ACP, 0, string, -1, NULL, 0); WCHAR* wideString = (WCHAR*)malloc(sizeof(WCHAR) * length); MultiByteToWideChar(CP_ACP, 0, string, -1, wideString, length); AppendData(wideString, length * sizeof(WCHAR)); free(wideString); } void AppendData(const void* data, int dataLength) { EnsureSpace(dataLength); memcpy((char*)dialogTemplate + usedBufferLength, data, dataLength); usedBufferLength += dataLength; } void EnsureSpace(int length) { if (length + usedBufferLength > totalBufferLength) { totalBufferLength += length * 2; void* newBuffer = malloc(totalBufferLength); memcpy(newBuffer, dialogTemplate, usedBufferLength); free(dialogTemplate); dialogTemplate = (DLGTEMPLATE*)newBuffer; } } private: DLGTEMPLATE* dialogTemplate; int totalBufferLength; int usedBufferLength; }; struct PromptParams { const char* message; const char* title; }; /** * Constants for controls. */ #define IDC_MESSAGE 1000 #define IDC_BUTTON0 2000 INT_PTR CALLBACK PromptDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_INITDIALOG: { PromptParams *params = (PromptParams*)lParam; ::SetWindowTextA(::GetDlgItem(hDlg, IDC_MESSAGE), params->message); ::SetFocus(::GetDlgItem(hDlg, IDC_BUTTON0)); SetWindowTextA(hDlg, params->title); HFONT hfont = CreateFontA(16, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS, PROOF_QUALITY, FIXED_PITCH | FF_MODERN, "Courier New"); SendDlgItemMessage(hDlg, IDC_MESSAGE, WM_SETFONT, (WPARAM)hfont, MAKELPARAM(TRUE,0)); break; } case WM_COMMAND: { int choiceNumber = LOWORD(wParam) - IDC_BUTTON0; if ((choiceNumber >= 0) && (choiceNumber < 10)) { EndDialog(hDlg, choiceNumber); return TRUE; } } break; case WM_NCDESTROY: // Under SDL 1.2.6 we get a NCDESTROY message for no reason and the // window is immediately closed. This is here to debug the problem. (void)0; break; } return FALSE; } }; // namespace _internal using namespace _internal; /** * Show a dialog prompt. */ static int guiPrompt( const char* windowTitle, const char* prompt, const char** choice, int numChoices) { int width = 280; int height = 128; const int buttonSpacing = 2; const int buttonWidth = (width - buttonSpacing * 2 - buttonSpacing * (numChoices - 1)) / numChoices; const int buttonHeight = 13; DialogTemplate dialogTemplate( windowTitle, WS_CAPTION | DS_CENTER | WS_SYSMENU, 10, 10, width, height, "Tahoma"); dialogTemplate.AddEditBox( "Edit", WS_VISIBLE | ES_READONLY | ES_OEMCONVERT | ES_MULTILINE | WS_TABSTOP, WS_EX_STATICEDGE, 2, 2, width - 4, height - buttonHeight - 7, IDC_MESSAGE); int i; for (i = 0; i < numChoices; i++) { int x = buttonSpacing + i * (buttonWidth + buttonSpacing); int y = height - buttonHeight - buttonSpacing; dialogTemplate.AddButton(choice[i], WS_VISIBLE | WS_TABSTOP, 0, x, y, buttonWidth, buttonHeight, IDC_BUTTON0 + (WORD)i); } // Convert all single \n characters to \r\n for proper printing int strLen = 0; const char* pStr = prompt; while (*pStr != '\0') { if ((*pStr == '\n') && (pStr != prompt)) { if (*(pStr - 1) != '\r') { ++strLen; } } ++strLen; ++pStr; } char* newStr = (char*)malloc(strLen + 1); const char* pStr2 = prompt; char* pNew = newStr; while (*pStr2 != '\0') { if ((*pStr2 == '\n') && (pStr2 != prompt)) { if (*(pStr2 - 1) != '\r') { *pNew = '\r'; ++pNew; } } *pNew = *pStr2; ++pNew; ++pStr2; } *pNew = '\0'; PromptParams params; params.message = newStr;; params.title = windowTitle; HMODULE module = GetModuleHandle(0); int ret = DialogBoxIndirectParam(module, dialogTemplate, NULL, (DLGPROC) PromptDlgProc, (DWORD)&params); free(newStr); /* For debugging when DialogBoxIndirectParam fails: // The last error value. (Which is preserved across the call). DWORD lastErr = GetLastError(); // The decoded message from FormatMessage LPTSTR formatMsg = NULL; if (NULL == formatMsg) { FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, lastErr, 0, (LPTSTR)&formatMsg, 0, NULL); } // Make sure the message got translated into something. LPTSTR realLastErr; if (NULL != formatMsg) { realLastErr = formatMsg; } else { realLastErr = "Last error code does not exist."; } // Get rid of the allocated memory from FormatMessage. if (NULL != formatMsg) { LocalFree((LPVOID)formatMsg); } */ return ret; } #endif /** * Show a prompt on stdout */ static int textPrompt( const char* windowTitle, const char* prompt, const char** choice, int numChoices) { printf("\n___________________________________________________\n"); printf("%s\n", windowTitle); printf("%s", prompt); if (numChoices > 10) { numChoices = 10; } int c = -1; if (numChoices > 1) { printf("\n"); printf("Choose an option by number:"); while ((c < 0) || (c >= numChoices)) { printf("\n"); for (int i = 0; i < numChoices; i++) { if (numChoices <= 3) { printf(" (%d) %s ", i, choice[i]); } else { printf(" (%d) %s\n", i, choice[i]); } } printf("\n> "); c = _getch() - '0'; if ((c < 0) || (c >= numChoices)) { printf("'%d' is not a valid choice.", c); } else { printf("%d", c); } } } else if (numChoices == 1) { printf("\nPress any key for '%s'...", choice[0]); _getch(); c = 0; } else { printf("\nPress any key..."); _getch(); c = 0; } printf("\n___________________________________________________\n"); return c; } #ifdef G3D_OSX // See http://developer.apple.com/documentation/Carbon/Reference/Carbon_Event_Manager_Ref/index.html #define CARBON_COMMANDID_START 128 #define CARBON_BUTTON_SPACING 12 #define CARBON_BUTTON_HEIGHT 20 #define CARBON_BUTTON_MINWIDTH 69 #define CARBON_WINDOW_PADDING 20 struct CallbackData { WindowRef refWindow; /** Index of this particular button */ int myIndex; /** Buttons store their index into here when pressed. */ int* whichButton; }; /** Assumes that userData is a pointer to a carbon_evt_data_t. */ static pascal OSStatus DoCommandEvent(EventHandlerCallRef handlerRef, EventRef event, void* userData) { // See http://developer.apple.com/documentation/Carbon/Conceptual/HandlingWindowsControls/index.html CallbackData& callbackData = *(CallbackData*)userData; # pragma unused(handlerRef) callbackData.whichButton[0] = callbackData.myIndex; // If we get here we can close the window ::QuitAppModalLoopForWindow(callbackData.refWindow); // Return noErr to indicate that we handled the event return noErr; } static int guiPrompt (const char* windowTitle, const char* prompt, const char** choice, int numChoices) { WindowRef window; int iNumButtonRows = 0; int iButtonWidth = -1; OSStatus err = noErr; // Determine number of rows of buttons while (iButtonWidth < CARBON_BUTTON_MINWIDTH) { ++iNumButtonRows; iButtonWidth = (550 - (CARBON_WINDOW_PADDING*2 + (CARBON_BUTTON_SPACING*numChoices))) / (numChoices/iNumButtonRows); } // Window Variables Rect rectWin = {0, 0, 200 + ((iNumButtonRows-1) * (CARBON_BUTTON_HEIGHT+CARBON_BUTTON_SPACING)), 550}; // top, left, bottom, right CFStringRef szWindowTitle = CFStringCreateWithCString(kCFAllocatorDefault, windowTitle, kCFStringEncodingUTF8); window = NULL; err = CreateNewWindow(kMovableAlertWindowClass, kWindowStandardHandlerAttribute|kWindowCompositingAttribute, &rectWin, &window); err = SetWindowTitleWithCFString(window, szWindowTitle); err = SetThemeWindowBackground(window, kThemeBrushAlertBackgroundActive, false); assert(err == noErr); // Event Handler Variables EventTypeSpec buttonSpec[] = {{ kEventClassControl, kEventControlHit }, { kEventClassCommand, kEventCommandProcess }}; EventHandlerUPP buttonHandler = NewEventHandlerUPP(DoCommandEvent); // Static Text Variables Rect rectStatic = {20, 20, 152, 530}; CFStringRef szStaticText = CFStringCreateWithCString(kCFAllocatorDefault, prompt, kCFStringEncodingUTF8); ControlRef refStaticText = NULL; err = CreateStaticTextControl(window, &rectStatic, szStaticText, NULL, &refStaticText); // Button Variables Rect bounds[numChoices]; CFStringRef caption[numChoices]; ControlRef button[numChoices]; int whichButton=-1; CallbackData callbackData[numChoices]; // Create the Buttons and assign event handlers for (int i = 0; i < numChoices; ++i) { bounds[i].top = 160 + ((CARBON_BUTTON_HEIGHT+CARBON_BUTTON_SPACING)*(i%iNumButtonRows)); bounds[i].right = 530 - ((iButtonWidth+CARBON_BUTTON_SPACING)*(i/iNumButtonRows)); bounds[i].left = bounds[i].right - iButtonWidth; bounds[i].bottom = bounds[i].top + CARBON_BUTTON_HEIGHT; // Convert the button captions to Apple strings caption[i] = CFStringCreateWithCString(kCFAllocatorDefault, choice[i], kCFStringEncodingUTF8); err = CreatePushButtonControl(window, &bounds[i], caption[i], &button[i]); assert(err == noErr); err = SetControlCommandID(button[i], CARBON_COMMANDID_START + i); assert(err == noErr); callbackData[i].refWindow = window; callbackData[i].myIndex = i; callbackData[i].whichButton = &whichButton; err = InstallControlEventHandler(button[i], buttonHandler, GetEventTypeCount(buttonSpec), buttonSpec, &callbackData[i], NULL); assert(err == noErr); } // Show Dialog err = RepositionWindow(window, NULL, kWindowCenterOnMainScreen); ShowWindow(window); BringToFront(window); err = ActivateWindow(window, true); // Hack to get our window/process to the front... ProcessSerialNumber psn = { 0, kCurrentProcess}; TransformProcessType(&psn, kProcessTransformToForegroundApplication); SetFrontProcess (&psn); // Run in Modal State err = RunAppModalLoopForWindow(window); // Dispose of Button Related Data for (int i = 0; i < numChoices; ++i) { // Dispose of controls DisposeControl(button[i]); // Release CFStrings CFRelease(caption[i]); } // Dispose of Other Controls DisposeControl(refStaticText); // Dispose of Event Handlers DisposeEventHandlerUPP(buttonHandler); // Dispose of Window DisposeWindow(window); // Release CFStrings CFRelease(szWindowTitle); CFRelease(szStaticText); // Return Selection return whichButton; } #endif int prompt( const char* windowTitle, const char* prompt, const char** choice, int numChoices, bool useGui) { #ifdef G3D_WIN32 if (useGui) { // Build the message box return guiPrompt(windowTitle, prompt, choice, numChoices); } #endif #ifdef G3D_OSX if (useGui){ //Will default to text prompt if numChoices > 4 return guiPrompt(windowTitle, prompt, choice, numChoices); } #endif return textPrompt(windowTitle, prompt, choice, numChoices); } void msgBox( const std::string& message, const std::string& title) { const char *choice[] = {"Ok"}; prompt(title.c_str(), message.c_str(), choice, 1, true); } #ifndef G3D_WIN32 #undef _getch #endif };// namespace
26.189041
136
0.589078
Subv
6a2a995b983010d69773a600c6939cbdc0633240
1,853
cpp
C++
test/core/crypto/bip39/entropy_calculation_test.cpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
test/core/crypto/bip39/entropy_calculation_test.cpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
test/core/crypto/bip39/entropy_calculation_test.cpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include <gtest/gtest.h> #include <boost/algorithm/string/join.hpp> #include "common/blob.hpp" #include "common/buffer.hpp" #include "crypto/bip39/impl/bip39_provider_impl.hpp" #include "crypto/bip39/mnemonic.hpp" #include "crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp" #include "testutil/outcome.hpp" using namespace kagome; using namespace crypto; using namespace bip39; struct Bip39EntropyTest : public ::testing::Test { void SetUp() override { auto pbkdf2_provider = std::make_shared<Pbkdf2ProviderImpl>(); bip39_provider = std::make_shared<Bip39ProviderImpl>(pbkdf2_provider); phrase = "legal winner thank year wave sausage worth useful legal winner " "thank yellow"; entropy_hex = "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f"; seed_hex = "4313249608fe8ac10fd5886c92c4579007272cb77c21551ee5b8d60b780416850" "f1e26c1f4b8d88ece681cb058ab66d6182bc2ce5a03181f7b74c27576b5c8bf"; } std::string_view phrase; std::string_view entropy_hex; std::string_view seed_hex; std::shared_ptr<Bip39Provider> bip39_provider; }; /** * @given valid mnemonic, entropy and seed values * @when entropy is calculated by mnemonic * @and seed is calculated by entropy * @then entropy and seed come up with predefined values */ TEST_F(Bip39EntropyTest, DecodeSuccess) { EXPECT_OUTCOME_TRUE(mnemonic, Mnemonic::parse(phrase)); auto joined_words = boost::algorithm::join(mnemonic.words, " "); ASSERT_EQ(joined_words, phrase); EXPECT_OUTCOME_TRUE(entropy, bip39_provider->calculateEntropy(mnemonic.words)); ASSERT_EQ(common::Buffer(entropy).toHex(), entropy_hex); EXPECT_OUTCOME_TRUE(seed, bip39_provider->makeSeed(entropy, "Substrate")); ASSERT_EQ(seed.toHex(), seed_hex); }
31.948276
76
0.748516
FlorianFranzen
6a2f5c26965205cce3030b35417e397d4b68a35d
620
cpp
C++
DCompiler/IDA/TestWin32/main.cpp
longlongwaytogo/Learning.test
ded9a25ba789c153d69b2d216599eda962ef83e9
[ "MIT" ]
null
null
null
DCompiler/IDA/TestWin32/main.cpp
longlongwaytogo/Learning.test
ded9a25ba789c153d69b2d216599eda962ef83e9
[ "MIT" ]
null
null
null
DCompiler/IDA/TestWin32/main.cpp
longlongwaytogo/Learning.test
ded9a25ba789c153d69b2d216599eda962ef83e9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include "lib.h" void main() { TestA a; for(int i = 0; i <10; i++) { int* data = new int; *data = i; a.add(data); } int dd; /* std::cin >>dd;*/ a.clearAll(); std::cout << "test win32 " << std::endl; std::vector<std::string> infos; for(int i = 0; i < 20; i++) { infos.push_back(std::to_string(Add(i,+100))); } std::cout << "output info" << std::endl; std::string str = a.getInfo(15,100,"abceefgh"); std::cout <<str<< std::endl; }
17.222222
55
0.469355
longlongwaytogo
6a32ca429f511bc5571b2a1fd4a6350e00948930
394
cc
C++
type/factor_curve.cc
hitdshu/hitnllls
d69794c64a5f84ebfff69912bb6fa404f2783df3
[ "WTFPL" ]
17
2019-07-18T08:28:51.000Z
2020-04-07T03:43:51.000Z
type/factor_curve.cc
hitdshu/hitnlls
d69794c64a5f84ebfff69912bb6fa404f2783df3
[ "WTFPL" ]
null
null
null
type/factor_curve.cc
hitdshu/hitnlls
d69794c64a5f84ebfff69912bb6fa404f2783df3
[ "WTFPL" ]
4
2020-09-02T03:17:16.000Z
2021-07-19T16:07:55.000Z
#include "factor_curve.h" namespace nlls { typename FactorCurveExp::EvalVectorTypeJet FactorCurveExp::operator()(typename FactorCurveExp::VertexTupleType &vars) { EvalVectorTypeJet result; auto var = vars.GetVertex<0>(); auto est = var->GetEstimateJet(); result = exp(est[0] + Jetf(x_) * est[1]); return result; } NLLS_REGISTER_FACTOR(FactorCurveExp) } // namespace nlls
26.266667
119
0.72335
hitdshu
6a3b35c008dfaa641f14a472d4a3c883c77719e5
3,241
hpp
C++
boost/range/algorithm_ext/for_each.hpp
jonstewart/boost-svn
7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59
[ "BSL-1.0" ]
1
2017-04-08T10:44:28.000Z
2017-04-08T10:44:28.000Z
boost/range/algorithm_ext/for_each.hpp
jonstewart/boost-svn
7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59
[ "BSL-1.0" ]
null
null
null
boost/range/algorithm_ext/for_each.hpp
jonstewart/boost-svn
7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59
[ "BSL-1.0" ]
null
null
null
// Boost.Range library // // Copyright Neil Groves 2009. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see http://www.boost.org/libs/range/ // #ifndef BOOST_RANGE_ALGORITHM_EXT_FOR_EACH_HPP_INCLUDED #define BOOST_RANGE_ALGORITHM_EXT_FOR_EACH_HPP_INCLUDED #include <boost/range/config.hpp> #include <boost/range/concepts.hpp> #include <boost/range/difference_type.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/assert.hpp> namespace boost { namespace range_detail { template<class InputIterator1, class InputIterator2, class Fn2> inline Fn2 for_each_impl(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Fn2 fn) { for (; first1 != last1 && first2 != last2; ++first1, ++first2) { fn(*first1, *first2); } return fn; } } namespace range { template<class SinglePassRange1, class SinglePassRange2, class Fn2> inline Fn2 for_each(const SinglePassRange1& rng1, const SinglePassRange2& rng2, Fn2 fn) { BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange1> )); BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange2> )); return ::boost::range_detail::for_each_impl( ::boost::begin(rng1), ::boost::end(rng1), ::boost::begin(rng2), ::boost::end(rng2), fn); } template<class SinglePassRange1, class SinglePassRange2, class Fn2> inline Fn2 for_each(const SinglePassRange1& rng1, SinglePassRange2& rng2, Fn2 fn) { BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange1> )); BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<SinglePassRange2> )); return ::boost::range_detail::for_each_impl( ::boost::begin(rng1), ::boost::end(rng1), ::boost::begin(rng2), ::boost::end(rng2), fn); } template<class SinglePassRange1, class SinglePassRange2, class Fn2> inline Fn2 for_each(SinglePassRange1& rng1, const SinglePassRange2& rng2, Fn2 fn) { BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<SinglePassRange1> )); BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange2> )); return ::boost::range_detail::for_each_impl( ::boost::begin(rng1), ::boost::end(rng1), ::boost::begin(rng2), ::boost::end(rng2), fn); } template<class SinglePassRange1, class SinglePassRange2, class Fn2> inline Fn2 for_each(SinglePassRange1& rng1, SinglePassRange2& rng2, Fn2 fn) { BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<SinglePassRange1> )); BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<SinglePassRange2> )); return ::boost::range_detail::for_each_impl( ::boost::begin(rng1), ::boost::end(rng1), ::boost::begin(rng2), ::boost::end(rng2), fn); } } // namespace range using range::for_each; } // namespace boost #endif // include guard
37.252874
92
0.683122
jonstewart
6a43fdb07f2284251db1415be620a8577836fcfd
557
hpp
C++
test/Compare.hpp
wojciechpawlak/diku.OptionsPricing
980c0d5292074aaf90b4d33361a023f9583a876b
[ "ISC" ]
3
2019-01-11T11:13:13.000Z
2020-06-16T10:20:46.000Z
test/Compare.hpp
wojciechpawlak/diku.OptionsPricing
980c0d5292074aaf90b4d33361a023f9583a876b
[ "ISC" ]
null
null
null
test/Compare.hpp
wojciechpawlak/diku.OptionsPricing
980c0d5292074aaf90b4d33361a023f9583a876b
[ "ISC" ]
1
2019-01-09T21:47:46.000Z
2019-01-09T21:47:46.000Z
#ifndef COMPARE_HPP #define COMPARE_HPP #include "catch.hpp" #include "../common/Real.hpp" #include <vector> #ifdef USE_DOUBLE #define EPSILON std::numeric_limits<double>::epsilon() * 1000 #else #define EPSILON std::numeric_limits<float>::epsilon() * 1000 #endif void compareVectors(std::vector<trinom::real> test, std::vector<trinom::real> gold) { Approx approx = Approx::custom().margin(EPSILON); REQUIRE(test.size() == gold.size()); for (auto i = 0; i < test.size(); i++) { CHECK(test[i] == approx(gold[i])); } } #endif
20.62963
83
0.660682
wojciechpawlak
6a463d0b887b5b5a6c7f98016bc304204bdad9b4
21,442
cpp
C++
test/source/vstat_test.cpp
foolnotion/vstat
e6d16e7ba279f5e8730328e69a80ffae442702e3
[ "MIT" ]
8
2021-04-01T13:34:50.000Z
2021-04-22T02:46:46.000Z
test/source/vstat_test.cpp
foolnotion/vstat
e6d16e7ba279f5e8730328e69a80ffae442702e3
[ "MIT" ]
null
null
null
test/source/vstat_test.cpp
foolnotion/vstat
e6d16e7ba279f5e8730328e69a80ffae442702e3
[ "MIT" ]
1
2021-04-02T15:32:49.000Z
2021-04-02T15:32:49.000Z
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: Copyright 2019-2021 Heal Research #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include <doctest/doctest.h> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics.hpp> #define ANKERL_NANOBENCH_IMPLEMENT #include "nanobench.h" #include <iostream> #include <memory> #include <random> #include <vector> #include "gsl/gsl_statistics_double.h" #include "gsl/gsl_statistics_float.h" #include <chrono> #include "vstat/vstat.hpp" #include "Statistics.h" namespace ba = boost::accumulators; namespace nb = ankerl::nanobench; struct Foo { double value; }; TEST_SUITE("usage") { TEST_CASE("univariate") { std::vector<float> values { 1.0, 2.0, 3.0, 4.0 }; std::vector<float> weights { 2.0, 4.0, 6.0, 8.0 }; SUBCASE("batch") { auto stats = univariate::accumulate<float>(values.begin(), values.end()); std::cout << "stats:\n" << stats << "\n"; } SUBCASE("batch weighted") { auto stats = univariate::accumulate<float>(values.begin(), values.end(), weights.begin()); std::cout << "stats:\n" << stats << "\n"; } SUBCASE("batch projection") { struct Foo { float value; }; Foo foos[] = { { 1 }, { 3 }, { 5 }, { 2 }, { 8 } }; auto stats = univariate::accumulate<float>(foos, std::size(foos), [](auto const& foo) { return foo.value; }); std::cout << "stats:\n" << stats << "\n"; } SUBCASE("batch binary op projection") { auto stats = univariate::accumulate<float>(values.begin(), values.end(), weights.begin(), [](auto v, auto w) { return (v - w) * (v - w); }); std::cout << "stats:\n" << stats << "\n"; } SUBCASE("accumulator") { univariate_accumulator<float> acc(1.0); acc(2.0); acc(3.0); acc(4.0); auto stats = univariate_statistics(acc); std::cout << "stats:\n" << stats << "\n"; } SUBCASE("accumulator weighted") { univariate_accumulator<float> acc(1.0, 2.0); acc(2.0, 4.0); acc(3.0, 6.0); auto stats = univariate_statistics(acc); std::cout << "stats:\n" << stats << "\n"; } } TEST_CASE("bivariate") { float x[] = { 1., 1., 2., 6. }; float y[] = { 2., 4., 3., 1. }; size_t n = std::size(x); SUBCASE("batch") { auto stats = bivariate::accumulate<float>(x, y, n); std::cout << "stats:\n" << stats << "\n"; } SUBCASE("batch projection") { struct Foo { float value; }; struct Bar { int value; }; Foo foos[] = { { 1 }, { 3 }, { 5 }, { 2 }, { 8 } }; Bar bars[] = { { 3 }, { 2 }, { 1 }, { 4 }, { 11 } }; auto stats = bivariate::accumulate<float>( foos, bars, std::size(foos), [](auto const& foo) { return foo.value; }, [](auto const& bar) { return bar.value; }); std::cout << "stats:\n" << stats << "\n"; } SUBCASE("accumulator") { bivariate_accumulator<float> acc(x[0], y[0]); for (size_t i = 1; i < n; ++i) { acc(x[i], y[i]); } bivariate_statistics stats(acc); std::cout << "stats:\n" << stats << "\n"; } } } TEST_SUITE("correctness") { TEST_CASE("univariate") { const int n = int(1e6); std::vector<float> xf(n); std::vector<double> xd(n); std::vector<float> yf(n); std::vector<double> yd(n); std::vector<float> wf(n); std::vector<double> wd(n); std::default_random_engine rng(1234); std::uniform_real_distribution<double> dist(-1, 1); std::generate(xd.begin(), xd.end(), [&]() { return dist(rng); }); std::generate(yd.begin(), yd.end(), [&]() { return dist(rng); }); std::copy(xd.begin(), xd.end(), xf.begin()); std::copy(yd.begin(), yd.end(), yf.begin()); std::vector<Foo> ff(n); for (int i = 0; i < n; ++i) { ff[i].value = xd[i]; } auto gsl_var_flt = gsl_stats_float_variance(xf.data(), 1, xf.size()); auto gsl_mean_flt = gsl_stats_float_mean(xf.data(), 1, xf.size()); SUBCASE("float") { auto stats = univariate::accumulate<float>(xd.begin(), xd.end(), detail::identity {}); CHECK(std::abs(stats.mean - gsl_mean_flt) < 1e-6); CHECK(std::abs(stats.variance - gsl_var_flt) < 1e-5); } SUBCASE("float weighted") { // now test the weighted version with weights set to 1 std::fill(wf.begin(), wf.end(), 1.0); auto stats = univariate::accumulate<float>(xf.begin(), xf.end(), wf.begin()); CHECK(std::abs(stats.mean - gsl_mean_flt) < 1e-6); CHECK(std::abs(stats.variance - gsl_var_flt) < 1e-5); std::fill(wf.begin(), wf.end(), 0.2); auto gsl_wmean_flt = gsl_stats_float_wmean(wf.data(), 1, xf.data(), 1, n); auto gsl_wvar_flt = gsl_stats_float_wvariance(wf.data(), 1, xf.data(), 1, n); stats = univariate::accumulate<float>(xf.begin(), xf.end(), wf.begin()); CHECK(std::abs(stats.mean - gsl_wmean_flt) < 1e-5); CHECK(std::abs(stats.variance - gsl_wvar_flt) < 1e-5); ba::accumulator_set<float, ba::stats<ba::tag::weighted_variance>, float> acc; for (size_t i = 0; i < n; ++i) { acc(xf[i], ba::weight = wf[i]); } auto ba_wvar_flt = ba::weighted_variance(acc); CHECK(std::abs(ba_wvar_flt - gsl_wvar_flt) < 1e-6); float x[] { 2, 2, 4, 5, 5, 5 }; float y[] { 2, 4, 5 }; float w[] { 2, 1, 3 }; auto stats1 = univariate::accumulate<float>(x, std::size(x)); auto stats2 = univariate::accumulate<float>(y, w, std::size(y)); CHECK(stats1.mean == stats2.mean); CHECK(std::abs(stats1.variance - stats2.variance) < 1e-5); univariate_accumulator<float> a1(x[0]); univariate_accumulator<float> a2(y[0], w[0]); for (size_t i = 1; i < std::size(x); ++i) a1(x[i]); for (size_t i = 1; i < std::size(y); ++i) a2(y[i], w[i]); CHECK(std::abs(univariate_statistics(a1).variance - univariate_statistics(a2).variance) < 1e-6); auto stats3 = univariate::accumulate<float>(y, w, std::size(y), std::multiplies<float> {}); CHECK(stats3.sum == stats2.sum); } SUBCASE("double") { auto gsl_var_dbl = gsl_stats_variance(xd.data(), 1, xd.size()); auto gsl_mean_dbl = gsl_stats_mean(xd.data(), 1, xd.size()); auto stats = univariate::accumulate<double>(xd.begin(), xd.end(), detail::identity {}); CHECK(std::abs(stats.mean - gsl_mean_dbl) < 1e-6); CHECK(std::abs(stats.variance - gsl_var_dbl) < 1e-6); } } TEST_CASE("bivariate") { const int n = int(1e6); std::vector<float> xf(n); std::vector<double> xd(n); std::vector<float> yf(n); std::vector<double> yd(n); std::vector<float> wf(n); std::vector<double> wd(n); std::default_random_engine rng(1234); std::uniform_real_distribution<double> dist(-1, 1); std::generate(xd.begin(), xd.end(), [&]() { return dist(rng); }); std::generate(yd.begin(), yd.end(), [&]() { return dist(rng); }); std::copy(xd.begin(), xd.end(), xf.begin()); std::copy(yd.begin(), yd.end(), yf.begin()); std::vector<Foo> ff(n); for (int i = 0; i < n; ++i) { ff[i].value = xd[i]; } auto gsl_corr_flt = gsl_stats_float_correlation(xf.data(), 1, yf.data(), 1, n); auto gsl_corr_dbl = gsl_stats_correlation(xd.data(), 1, yd.data(), 1, n); auto gsl_cov_flt = gsl_stats_float_covariance(xf.data(), 1, yf.data(), 1, n); auto gsl_cov_dbl = gsl_stats_covariance(xd.data(), 1, yd.data(), 1, n); auto bstats = bivariate::accumulate<float>(xd.begin(), xd.end(), yd.begin()); CHECK(std::abs(gsl_corr_flt - bstats.correlation) < 1e-6); CHECK(std::abs(gsl_cov_flt - bstats.covariance) < 1e-6); bstats = bivariate::accumulate<float>(xd.begin(), xd.end(), yd.begin()); CHECK(std::abs(gsl_corr_dbl - bstats.correlation) < 1e-6); CHECK(std::abs(gsl_cov_dbl - bstats.covariance) < 1e-6); auto stats_x = univariate::accumulate<float>(xd.begin(), xd.end()); auto stats_y = univariate::accumulate<float>(yd.begin(), yd.end()); CHECK(bstats.mean_x == stats_x.mean); CHECK(bstats.mean_y == stats_y.mean); CHECK(bstats.sum_x == stats_x.sum); CHECK(bstats.sum_y == stats_y.sum); } } TEST_SUITE("performance") { TEST_CASE("univariate") { const int n = int(1e6); std::vector<double> v1(n); std::vector<double> v2(n); std::vector<double> v3(n); std::vector<float> u1(n); std::vector<float> u2(n); std::vector<float> u3(n); auto *xd = v1.data(); auto *yd = v2.data(); auto *wd = v3.data(); auto *xf = u1.data(); auto *yf = u2.data(); auto *wf = u3.data(); std::default_random_engine rng(1234); std::uniform_real_distribution<double> dist(-1, 1); std::generate(xd, xd + n, [&]() { return dist(rng); }); std::generate(yd, yd + n, [&]() { return dist(rng); }); std::generate(wd, wd + n, [&]() { return dist(rng); }); std::copy(xd, xd + n, xf); std::copy(yd, yd + n, yf); std::copy(wd, wd + n, wf); std::vector<Foo> ff(n); for (int i = 0; i < n; ++i) { ff[i].value = xd[i]; } ankerl::nanobench::Bench b; b.performanceCounters(true).minEpochIterations(100).batch(n); // print some runtime stats for different data sizes std::vector<int> sizes { 1000, 10000 }; int step = int(1e5); for (int s = step; s <= n; s += step) { sizes.push_back(s); } SUBCASE("vstat accumulator") { double var, count; for (auto s : sizes) { var = count = 0; b.batch(s).run("vstat acc variance float " + std::to_string(s), [&]() { ++count; univariate_accumulator<Vec8f> acc(Vec8f().load(xf)); constexpr auto sz = Vec8f::size(); size_t m = s & (-sz); for (size_t i = sz; i < m; i += sz) { acc(Vec8f().load(xf + i)); } var += univariate_statistics(acc).variance; }); } for (auto s : sizes) { var = count = 0; b.batch(s).run("vstat acc variance float weighted " + std::to_string(s), [&]() { ++count; univariate_accumulator<Vec8f> acc(Vec8f().load(xf), Vec8f().load(wf)); constexpr auto sz = Vec8f::size(); size_t m = s & (-sz); for (size_t i = sz; i < m; i += sz) { acc(Vec8f().load(xf + i), Vec8f().load(wf + i)); } var += univariate_statistics(acc).variance; }); } for (auto s : sizes) { var = count = 0; b.batch(s).run("vstat acc variance double " + std::to_string(s), [&]() { ++count; univariate_accumulator<Vec4d> acc(Vec4d().load(xd)); constexpr auto sz = Vec4d::size(); size_t m = s & (-sz); for (size_t i = sz; i < m; i += sz) { acc(Vec4d().load(xd + i)); } var += univariate_statistics(acc).variance; }); } for (auto s : sizes) { var = count = 0; b.batch(s).run("vstat acc variance double weighted " + std::to_string(s), [&]() { ++count; univariate_accumulator<Vec4d> acc(Vec4d().load(xd), Vec4d().load(wd)); constexpr auto sz = Vec4d::size(); size_t m = s & (-sz); for (size_t i = sz; i < m; i += sz) { acc(Vec4d().load(xd + i), Vec4d().load(wd + i)); } var += univariate_statistics(acc).variance; }); } } SUBCASE("vstat") { double var = 0, count = 0; for (auto s : sizes) { var = count = 0; b.batch(s).run("vstat variance float " + std::to_string(s), [&]() { ++count; var += univariate::accumulate<float>(xf, s).variance; }); } for (auto s : sizes) { var = count = 0; b.batch(s).run("vstat variance double " + std::to_string(s), [&]() { ++count; var += univariate::accumulate<double>(xd, s).variance; }); } } SUBCASE("vstat weighted") { double var = 0, count = 0; for (auto s : sizes) { var = count = 0; b.batch(s).run("vstat variance float weighted " + std::to_string(s), [&]() { ++count; var += univariate::accumulate<float>(xf, wf, s).variance; }); } for (auto s : sizes) { var = count = 0; b.batch(s).run("vstat variance double weighted " + std::to_string(s), [&]() { ++count; var += univariate::accumulate<double>(xd, wd, s).variance; }); } } SUBCASE("linasm") { double var = 0, count = 0; for (auto s : sizes) { var = count = 0; b.batch(s).run("linasm variance float " + std::to_string(s), [&]() { ++count; auto mean = Statistics::Mean(xf, s); var += Statistics::Variance(xf, s, mean); }); } for (auto s : sizes) { b.batch(s).run("linasm variance double " + std::to_string(s), [&]() { ++count; auto mean = Statistics::Mean(xd, s); var += Statistics::Variance(xd, s, mean); }); } } SUBCASE("boost accumulators") { double var = 0, count = 0; for (auto s : sizes) { var = count = 0; b.batch(s).run("boost variance float " + std::to_string(s), [&]() { ++count; ba::accumulator_set<float, ba::features<ba::tag::variance>> acc; for (int i = 0; i < s; ++i) { acc(xf[i]); } var += ba::variance(acc); }); } for (auto s : sizes) { var = count = 0; b.batch(s).run("boost variance double " + std::to_string(s), [&]() { ++count; ba::accumulator_set<double, ba::features<ba::tag::variance>> acc; for (int i = 0; i < s; ++i) { acc(xd[i]); } var += ba::variance(acc); }); } } SUBCASE("gsl") { double var = 0, count = 0; for (auto s : sizes) { var = count = 0; b.batch(s).run("gsl variance float " + std::to_string(s), [&]() { ++count; var += gsl_stats_float_variance(xf, 1, s); }); } for (auto s : sizes) { var = count = 0; b.batch(s).run("gsl variance double " + std::to_string(s), [&]() { ++count; var += gsl_stats_variance(xd, 1, s); }); } } } TEST_CASE("bivariate") { const int n = int(1e6); std::vector<double> v1(n), v2(n); std::vector<float> u1(n), u2(n); auto xd = v1.data(); auto yd = v2.data(); auto xf = u1.data(); auto yf = u2.data(); std::default_random_engine rng(1234); std::uniform_real_distribution<double> dist(-1, 1); std::generate(xd, xd + n, [&]() { return dist(rng); }); std::generate(yd, yd + n, [&]() { return dist(rng); }); std::copy(xd, xd + n, xf); std::copy(yd, yd + n, yf); std::vector<Foo> ff(n); for (int i = 0; i < n; ++i) { ff[i].value = xd[i]; } ankerl::nanobench::Bench b; b.performanceCounters(true).minEpochIterations(100).batch(n); // print some runtime stats for different data sizes std::vector<int> sizes { 1000, 10000 }; int step = int(1e5); for (int s = step; s <= n; s += step) { sizes.push_back(s); } SUBCASE("vstat") { double var = 0, count = 0; for (auto s : sizes) { var = count = 0; b.batch(s).run("vstat covariance float " + std::to_string(s), [&]() { ++count; var += bivariate::accumulate<float>(xf, yf, s).covariance; }); } for (auto s : sizes) { var = count = 0; b.batch(s).run("vstat covariance double " + std::to_string(s), [&]() { ++count; var += bivariate::accumulate<double>(xd, yd, s).covariance; }); } } SUBCASE("vstat") { double var = 0, count = 0; var = count = 0; for (auto s : sizes) { var = count = 0; b.batch(s).run("linasm covariance float " + std::to_string(s), [&]() { ++count; auto xm = Statistics::Mean(xf, s); auto ym = Statistics::Mean(yf, s); var += Statistics::Covariance(xf, yf, s, xm, ym); }); } for (auto s : sizes) { var = count = 0; b.batch(s).run("linasm covariance double " + std::to_string(s), [&]() { ++count; auto xm = Statistics::Mean(xd, s); auto ym = Statistics::Mean(yd, s); var += Statistics::Covariance(xd, yd, s, xm, ym); }); } } SUBCASE("vstat") { double var = 0, count = 0; var = count = 0; for (auto s : sizes) { var = count = 0; b.batch(s).run("boost covariance float " + std::to_string(s), [&]() { ++count; ba::accumulator_set<float, ba::stats<ba::tag::covariance<float, ba::tag::covariate1>>> acc; for (int i = 0; i < s; ++i) { acc(xf[i], ba::covariate1 = yf[i]); } var += ba::covariance(acc); }); } for (auto s : sizes) { var = count = 0; b.batch(s).run("boost covariance double " + std::to_string(s), [&]() { ++count; ba::accumulator_set<double, ba::stats<ba::tag::covariance<double, ba::tag::covariate1>>> acc; for (int i = 0; i < s; ++i) { acc(xd[i], ba::covariate1 = yd[i]); } var += ba::covariance(acc); }); } } SUBCASE("vstat") { double var = 0, count = 0; var = count = 0; for (auto s : sizes) { var = count = 0; b.batch(s).run("gsl covariance float " + std::to_string(s), [&]() { ++count; var += gsl_stats_float_covariance(xf, 1, yf, 1, s); }); } for (auto s : sizes) { var = count = 0; b.batch(s).run("gsl covariance double " + std::to_string(s), [&]() { ++count; var += gsl_stats_covariance(xd, 1, yd, 1, s); }); } } } }
33.927215
152
0.44161
foolnotion
6a4722e1874b9cd7be10676e85da1a43e587aa62
1,417
hpp
C++
Source/CCZ4/Constraints.hpp
boxuange/GRChomboo
22cf6751a3be29776f35a39f433f6bb497280720
[ "BSD-3-Clause" ]
null
null
null
Source/CCZ4/Constraints.hpp
boxuange/GRChomboo
22cf6751a3be29776f35a39f433f6bb497280720
[ "BSD-3-Clause" ]
null
null
null
Source/CCZ4/Constraints.hpp
boxuange/GRChomboo
22cf6751a3be29776f35a39f433f6bb497280720
[ "BSD-3-Clause" ]
1
2022-02-24T23:01:02.000Z
2022-02-24T23:01:02.000Z
/* GRChombo * Copyright 2012 The GRChombo collaboration. * Please refer to LICENSE in GRChombo's root directory. */ // This compute class calculates Hamiltonian and Momentum constraints #ifndef CONSTRAINTS_HPP_ #define CONSTRAINTS_HPP_ #include "BSSNVars.hpp" #include "Cell.hpp" #include "FArrayBox.H" #include "FourthOrderDerivatives.hpp" #include "Tensor.hpp" #include "simd.hpp" #include "CCZ4Geometry.hpp" #include <array> class Constraints { public: /// CCZ4 variables template <class data_t> using Vars = BSSNVars::VarsNoGauge<data_t>; /// CCZ4 variables template <class data_t> using Diff2Vars = BSSNVars::Diff2VarsNoGauge<data_t>; template <class data_t> struct constraints_t { data_t Ham; Tensor<1, data_t> Mom; }; Constraints(double dx, double cosmological_constant = 0); template <class data_t> void compute(Cell<data_t> current_cell) const; protected: const FourthOrderDerivatives m_deriv; double m_cosmological_constant; template <class data_t, template <typename> class vars_t, template <typename> class diff2_vars_t> constraints_t<data_t> constraint_equations(const vars_t<data_t> &vars, const vars_t<Tensor<1, data_t>> &d1, const diff2_vars_t<Tensor<2, data_t>> &d2) const; }; #include "Constraints.impl.hpp" #endif /* CONSTRAINTS_HPP_ */
24.859649
74
0.697248
boxuange
6a47a4facd85cc5bb07ff344080021bfc3b0017c
10,841
hpp
C++
src/xalanc/PlatformSupport/XalanDecimalFormatSymbols.hpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
null
null
null
src/xalanc/PlatformSupport/XalanDecimalFormatSymbols.hpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
1
2021-08-18T12:32:31.000Z
2021-08-18T12:32:31.000Z
src/xalanc/PlatformSupport/XalanDecimalFormatSymbols.hpp
AaronNGray/xalan
6741bbdcb64a9d33df8bd7e21b558d66bb4292ec
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ #if !defined(XALANDECIMALFORMATSYMBOLS_HEADER_GUARD_1357924680) #define XALANDECIMALFORMATSYMBOLS_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp> #include <cassert> #include <xalanc/XalanDOM/XalanDOMString.hpp> XALAN_CPP_NAMESPACE_BEGIN class XALAN_PLATFORMSUPPORT_EXPORT XalanDecimalFormatSymbols { public: // Eventually, this constructor should take a locale to determine // all of the stuff it needs to know. But locales are implemented // on all of our platforms yet. explicit XalanDecimalFormatSymbols(MemoryManager& theManager); XalanDecimalFormatSymbols(const XalanDecimalFormatSymbols& theSource, MemoryManager& theManager); ~XalanDecimalFormatSymbols(); XalanDecimalFormatSymbols& operator=(const XalanDecimalFormatSymbols& theRHS); /** * Retrieve the string denoting the local currency, "$", for example * * @return string used for local currency */ const XalanDOMString& getCurrencySymbol() const { return m_currencySymbol; } /** * Retrieve the character used for decimal sign, '.' for example * * @return character used for decimal sign */ XalanDOMChar getDecimalSeparator() const { return m_decimalSeparator; } /** * Retrieve character used for a digit in a pattern * * @return character used for a digit in a pattern */ XalanDOMChar getDigit() const { return m_digit; } /** * Retrieve the character used for thousands separator, "," for example * * @return character used for thousands separator */ XalanDOMChar getGroupingSeparator() const { return m_groupingSeparator; } /** * Retrieve the string used to represent infinity * * @return string used to represent infinity */ const XalanDOMString& getInfinity() const { return m_infinity; } /** * Retrieve the international string denoting the local currency * * @return international string denoting the local currency */ const XalanDOMString& getInternationalCurrencySymbol() const { return m_internationalCurrencySymbol; } /** * Retrieve the character used to represent minus sign * * @return character used to represent minus sign */ XalanDOMChar getMinusSign() const { return m_minusSign; } /** * Retrieve the monetary decimal separator * * @return character used to separate decimal portion of currency */ XalanDOMChar getMonetaryDecimalSeparator() const { return m_monetaryDecimalSeparator; } /** * Retrieve the string used for a numeric value that cannot be represented * as a number * * @return string representing "not a number" value */ const XalanDOMString& getNaN() const { return m_NaN; } /** * Retrieve the character used to separate positive and negative * subpatterns in a pattern * * @return character used to separate positive and negative subpatterns */ XalanDOMChar getPatternSeparator() const { return m_patternSeparator; } /** * Retrieve the character used for percent sign, "%," for example * * @return character used for percent sign */ XalanDOMChar getPercent() const { return m_percent; } /** * Retrieve the character used for per thousand sign * * @return character used for per thousand sign */ XalanDOMChar getPerMill() const { return m_perMill; } /** * Retrieve the character used for zero * * @return character used for zero */ XalanDOMChar getZeroDigit() const { return m_zeroDigit; } /** * Sets the string denoting the local currency, "$", for example * * @param theCurrencySymbol symbol used for local currency */ void setCurrencySymbol(const XalanDOMString& theCurrencySymbol) { m_currencySymbol = theCurrencySymbol; } /** * Sets the string denoting the local currency, "$", for example * * @param theCurrencySymbol symbol used for local currency */ void setCurrencySymbol(const XalanDOMChar* theCurrencySymbol) { assert(theCurrencySymbol != 0); m_currencySymbol = theCurrencySymbol; } /** * Sets the character used for decimal sign, '.' for example * * @param theDecimalSeparator character used for decimal sign */ void setDecimalSeparator(XalanDOMChar theDecimalSeparator) { m_decimalSeparator = theDecimalSeparator; } /** * Sets the character used for a digit in a pattern * * @param theDigit character used for a digit in a pattern */ void setDigit(XalanDOMChar theDigit) { m_digit = theDigit; } /** * Sets the character used for thousands separator, "," for example * * @param theGroupingSeparator character used for thousands separator */ void setGroupingSeparator(XalanDOMChar theGroupingSeparator) { m_groupingSeparator = theGroupingSeparator; } /** * Sets the string used to represent infinity * * @param theInfinity string used to represent infinity */ void setInfinity(const XalanDOMString& theInfinity) { m_infinity = theInfinity; } /** * Sets the string used to represent infinity * * @param theInfinity string used to represent infinity */ void setInfinity(const XalanDOMChar* theInfinity) { assert(theInfinity != 0); m_infinity = theInfinity; } /** * Sets the international string denoting the local currency * * @param theInternationalCurrencySymbol international string denoting the * local currency */ void setInternationalCurrencySymbol(const XalanDOMString& theInternationalCurrencySymbol) { m_internationalCurrencySymbol = theInternationalCurrencySymbol; } /** * Sets the international string denoting the local currency * * @param theInternationalCurrencySymbol international string denoting the * local currency */ void setInternationalCurrencySymbol(const XalanDOMChar* theInternationalCurrencySymbol) { assert(theInternationalCurrencySymbol != 0); m_internationalCurrencySymbol = theInternationalCurrencySymbol; } /** * Sets the character used to represent minus sign * * @param theMinusSign character used to represent minus sign */ void setMinusSign(XalanDOMChar theMinusSign) { m_minusSign = theMinusSign; } /** * Sets the monetary decimal separator * * @param theMonetaryDecimalSeparator character used to separate decimal * portion of currency */ void setMonetaryDecimalSeparator(XalanDOMChar theMonetaryDecimalSeparator) { m_monetaryDecimalSeparator = theMonetaryDecimalSeparator; } /** * Sets the string used for a numeric value that cannot be represented * as a number * * @param theNaN string representing "not a number" value */ void setNaN(const XalanDOMString& theNaN) { m_NaN = theNaN; } /** * Sets the string used for a numeric value that cannot be represented * as a number * * @param theNaN string representing "not a number" value */ void setNaN(const XalanDOMChar* theNaN) { assert(theNaN != 0); m_NaN = theNaN; } /** * Sets the character used to separate positive and negative subpatterns in * a pattern * * @param thePatternSeparator character used to separate positive and * negative subpatterns */ void setPatternSeparator(XalanDOMChar thePatternSeparator) { m_patternSeparator = thePatternSeparator; } /** * Sets the character used for percent sign, "%," for example * * @param thePercent character used for percent sign */ void setPercent(XalanDOMChar thePercent) { m_percent = thePercent; } /** * Sets the character used for per thousand sign * * @param thePerMill character used for per thousand sign */ void setPerMill(XalanDOMChar thePerMill) { m_perMill = thePerMill; } /** * Sets the character used for zero * * @param theZeroDigit character used for zero */ void setZeroDigit(XalanDOMChar theZeroDigit) { m_zeroDigit = theZeroDigit; } bool operator==(const XalanDecimalFormatSymbols& theRHS) const; bool operator!=(const XalanDecimalFormatSymbols& theRHS) const { return !operator==(theRHS); } private: // not implemented XalanDecimalFormatSymbols(); XalanDecimalFormatSymbols(const XalanDecimalFormatSymbols&); XalanDOMString m_currencySymbol; XalanDOMChar m_decimalSeparator; XalanDOMChar m_digit; XalanDOMChar m_groupingSeparator; XalanDOMString m_infinity; XalanDOMString m_internationalCurrencySymbol; XalanDOMChar m_minusSign; XalanDOMChar m_monetaryDecimalSeparator; XalanDOMString m_NaN; XalanDOMChar m_patternSeparator; XalanDOMChar m_percent; XalanDOMChar m_perMill; XalanDOMChar m_zeroDigit; }; XALAN_CPP_NAMESPACE_END #endif // XALANDECIMALFORMATSYMBOLS_HEADER_GUARD_1357924680
24.307175
91
0.643206
kidaa