hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
2f52bda7fc4a9697b29d5086aed929acb860b90b
925
hpp
C++
src/org/apache/poi/ddf/NullEscherSerializationListener.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ddf/NullEscherSerializationListener.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ddf/NullEscherSerializationListener.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ddf/NullEscherSerializationListener.java #pragma once #include <fwd-POI.hpp> #include <org/apache/poi/ddf/fwd-POI.hpp> #include <java/lang/Object.hpp> #include <org/apache/poi/ddf/EscherSerializationListener.hpp> struct default_init_tag; class poi::ddf::NullEscherSerializationListener : public virtual ::java::lang::Object , public virtual EscherSerializationListener { public: typedef ::java::lang::Object super; void beforeRecordSerialize(int32_t offset, int16_t recordId, EscherRecord* record) override; void afterRecordSerialize(int32_t offset, int16_t recordId, int32_t size, EscherRecord* record) override; // Generated NullEscherSerializationListener(); protected: NullEscherSerializationListener(const ::default_init_tag&); public: static ::java::lang::Class *class_(); private: virtual ::java::lang::Class* getClass0(); };
27.205882
109
0.758919
[ "object" ]
01724f5ada50fad9d7b54438fab44e1b4ce5089e
4,280
cpp
C++
tests/tests_raja_c/CanopyHydrology_kern1_single.cpp
him-28/ELM-Kernels
c617c03679b0efce31730fdab8561838cba1a1ab
[ "BSD-3-Clause" ]
null
null
null
tests/tests_raja_c/CanopyHydrology_kern1_single.cpp
him-28/ELM-Kernels
c617c03679b0efce31730fdab8561838cba1a1ab
[ "BSD-3-Clause" ]
null
null
null
tests/tests_raja_c/CanopyHydrology_kern1_single.cpp
him-28/ELM-Kernels
c617c03679b0efce31730fdab8561838cba1a1ab
[ "BSD-3-Clause" ]
null
null
null
#include <array> #include <sstream> #include <iterator> #include <exception> #include <string> #include <stdlib.h> #include <cstring> #include <vector> #include <iostream> #include <iomanip> #include <numeric> #include <fstream> #include <algorithm> #include "memoryManager.hpp" #include "RAJA/RAJA.hpp" #include "RAJA/util/Timer.hpp" #include "utils.hh" #include "readers.hh" #include "CanopyHydrology.hh" using namespace RAJA; namespace ELM { namespace Utils { static const int n_months = 12; static const int n_pfts = 17; using MatrixState = MatrixStatic<n_months, n_pfts>; static const int n_max_times = 31 * 24 * 2; // max days per month times hours per // day * half hour timestep using MatrixForc = MatrixStatic<n_max_times,1>; } // namespace } // namespace int main(int RAJA_UNUSED_ARG(argc), char **RAJA_UNUSED_ARG(argv[])) { // dimensions const int n_months = 12; const int n_pfts = 17; const int n_max_times = 31 * 24 * 2; // max days per month times hours per // day * half hour timestep // fixed magic parameters for now const int ctype = 1; const int ltype = 1; const bool urbpoi = false; const bool do_capsnow = false; const int frac_veg_nosno = 1; int n_irrig_steps_left = 0; const double dewmx = 0.1; const double dtime = 1800.0; // ELM::Utils::MatrixState elai; // ELM::Utils::MatrixState esai; double* elai = memoryManager::allocate<double>(n_months * n_pfts); double* esai = memoryManager::allocate<double>(n_months * n_pfts); const int DIM = 2; RAJA::View<double, RAJA::Layout<DIM> > h_elai( elai, n_months, n_pfts ); RAJA::View<double, RAJA::Layout<DIM> > h_esai( esai, n_months, n_pfts ); ELM::Utils::read_phenology("../links/surfacedataWBW.nc", n_months, n_pfts, 0, h_elai, h_esai); // forcing state // ELM::Utils::MatrixForc forc_rain; // ELM::Utils::MatrixForc forc_snow; // ELM::Utils::MatrixForc forc_air_temp; double* forc_rain = memoryManager::allocate<double>( n_max_times * 1 ); double* forc_snow = memoryManager::allocate<double>( n_max_times * 1 ); double* forc_air_temp = memoryManager::allocate<double>( n_max_times * 1 ); RAJA::View<double, RAJA::Layout<DIM> > h_forc_rain( forc_rain, n_max_times,1 ); RAJA::View<double, RAJA::Layout<DIM> > h_forc_snow( forc_snow, n_max_times,1 ); RAJA::View<double, RAJA::Layout<DIM> > h_forc_air_temp( forc_air_temp, n_max_times,1 ); const int n_times = ELM::Utils::read_forcing("../links/forcing", n_max_times, 6, 1, h_forc_rain, h_forc_snow, h_forc_air_temp); double h2ocan = 0.0; double qflx_prec_intr = 0.; double qflx_irrig = 0.; double qflx_prec_grnd = 0.; double qflx_snwcp_liq = 0.; double qflx_snwcp_ice = 0.; double qflx_snow_grnd_patch = 0.; double qflx_rain_grnd = 0.; double total_precip = 0.; std::ofstream soln_file; soln_file.open("test_CanopyHydrology_kern1_single.soln"); std::cout << "Timestep, forc_rain, h2ocan, qflx_prec_grnd, qflx_prec_intr, total_precip_loop" << std::endl; soln_file << "Timestep, forc_rain, h2ocan, qflx_prec_grnd, qflx_prec_intr, total_precip_loop" << std::endl; for(size_t itime = 0; itime < n_times; itime += 1) { // note this call puts all precip as rain for testing total_precip = h_forc_rain(itime,0) + h_forc_snow(itime,0); ELM::CanopyHydrology_Interception(dtime, total_precip, 0., 0., ltype, ctype, urbpoi, do_capsnow, h_elai(5,7), h_esai(5,7), dewmx, frac_veg_nosno, h2ocan, n_irrig_steps_left, qflx_prec_intr, qflx_irrig, qflx_prec_grnd, qflx_snwcp_liq, qflx_snwcp_ice, qflx_snow_grnd_patch, qflx_rain_grnd); soln_file << std::setprecision(16) << itime+1 << "\t" << total_precip << "\t" << h2ocan<< "\t" << qflx_prec_grnd << "\t" << qflx_prec_intr << std::endl; std::cout << std::setprecision(16) << itime+1 << "\t" << total_precip << "\t" << h2ocan<< "\t" << qflx_prec_grnd << "\t" << qflx_prec_intr << std::endl; }soln_file.close(); memoryManager::deallocate(elai); memoryManager::deallocate(esai); memoryManager::deallocate(forc_rain); memoryManager::deallocate(forc_snow); memoryManager::deallocate(forc_air_temp); return 0; }
35.966387
157
0.681776
[ "vector" ]
01771208da0b3463e8a0bf29f8700d68417afa8d
3,527
cpp
C++
docker/chiron-valet/reapr/make_plots.cpp
ryfi/Chiron
f34ff65400cf183287d81b40d226e0e293088af7
[ "MIT" ]
21
2017-06-05T12:58:56.000Z
2022-01-08T19:58:28.000Z
docker/chiron-valet/reapr/make_plots.cpp
ryfi/Chiron
f34ff65400cf183287d81b40d226e0e293088af7
[ "MIT" ]
3
2017-06-17T00:56:04.000Z
2018-05-24T17:41:13.000Z
docker/chiron-valet/reapr/make_plots.cpp
ryfi/Chiron
f34ff65400cf183287d81b40d226e0e293088af7
[ "MIT" ]
19
2017-06-02T17:46:38.000Z
2021-09-26T21:41:15.000Z
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <iostream> #include <cstring> #include <fstream> #include <string> #include <vector> #include <sstream> #include <map> using namespace std; const short CHR = 0; const short POS = 1; const short PERFECT_COV = 2; const short READ_F = 3; const short READ_PROP_F = 4; const short READ_ORPHAN_F = 5; const short READ_ISIZE_F = 6; const short READ_BADORIENT_F = 7; const short READ_R = 8; const short READ_PROP_R = 9; const short READ_ORPHAN_R = 10; const short READ_ISIZE_R = 11; const short READ_BADORIENT_R = 12; const short FRAG_COV = 13; const short FRAG_COV_CORRECT = 14; const short FCD_MEAN = 15; const short CLIP_FL = 16; const short CLIP_RL = 17; const short CLIP_FR = 18; const short CLIP_RR = 19; const short FCD_ERR = 20; int main(int argc, char* argv[]) { map<string, vector<short> > plots; map<string, ofstream*> plot_handles; bool firstLine = true; string line; string preout = argv[1]; plots["read_cov"].push_back(READ_F); plots["read_cov"].push_back(READ_R); plots["frag_cov"].push_back(FRAG_COV); plots["frag_cov_cor"].push_back(FRAG_COV_CORRECT); plots["FCD_err"].push_back(FCD_ERR); plots["read_ratio_f"].push_back(READ_PROP_F); plots["read_ratio_f"].push_back(READ_ORPHAN_F); plots["read_ratio_f"].push_back(READ_ISIZE_F); plots["read_ratio_f"].push_back(READ_BADORIENT_F); plots["read_ratio_r"].push_back(READ_PROP_R); plots["read_ratio_r"].push_back(READ_ORPHAN_R); plots["read_ratio_r"].push_back(READ_ISIZE_R); plots["read_ratio_r"].push_back(READ_BADORIENT_R); plots["clip"].push_back(CLIP_FL); plots["clip"].push_back(CLIP_RL); plots["clip"].push_back(CLIP_FR); plots["clip"].push_back(CLIP_RR); while (getline(cin, line) && !cin.eof()) { vector<string> data; string tmp; // split the line into a vector stringstream ss(line); data.clear(); while(getline(ss, tmp, '\t')) { data.push_back(tmp); } // open all the files, if it's the first line of the file if (firstLine) { // check if need to make perfect read mapping plot file if (data[2].compare("-1")) plots["perfect_cov"].push_back(PERFECT_COV); // open the plot files for (map<string, vector<short> >::iterator p = plots.begin(); p != plots.end(); p++) { string fname = preout + "." + p->first + ".plot"; plot_handles[p->first] = new ofstream(fname.c_str()); if (! plot_handles[p->first]->good()) { cerr << "Error opening file " << fname << endl; return 1; } } firstLine = false; } // write data to output files for (map<string, vector<short> >::iterator p = plots.begin(); p != plots.end(); p++) { *(plot_handles[p->first]) << data[0] << '\t' << data[1] << '\t' << data[p->second.front()]; for (vector<short>::iterator i = p->second.begin() + 1; i < p->second.end(); i++) { *plot_handles[p->first] << "\t" + data[*i]; } *plot_handles[p->first] << "\n"; } } // close the plot files for (map<string, vector<short> >::iterator p = plots.begin(); p != plots.end(); p++) { plot_handles[p->first]->close(); } return 0; }
28.216
103
0.588886
[ "vector" ]
017f0a598ba0272d07cd90e91b98d6c6f8492545
1,002
cpp
C++
Source/Types/Transform.cpp
Noxagonal/Vulkan2DRenderer
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
[ "MIT" ]
90
2020-06-20T15:00:31.000Z
2022-03-22T21:03:45.000Z
Source/Types/Transform.cpp
Niko40/Vulkan2DRenderer
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
[ "MIT" ]
39
2019-11-04T01:40:14.000Z
2020-03-09T15:57:00.000Z
Source/Types/Transform.cpp
Niko40/Vulkan2DRenderer
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
[ "MIT" ]
4
2020-12-02T22:39:33.000Z
2021-12-27T07:55:12.000Z
#include "Core/SourceCommon.h" #include "Types/Transform.h" vk2d::Transform::Transform( glm::vec2 position, glm::vec2 scale, float rotation ) : position( position ), scale( scale ), rotation( rotation ) {} VK2D_API void VK2D_APIENTRY vk2d::Transform::Translate( glm::vec2 movement ) { this->position += movement; } VK2D_API void VK2D_APIENTRY vk2d::Transform::Scale( glm::vec2 scale ) { this->scale *= scale; } VK2D_API void VK2D_APIENTRY vk2d::Transform::Rotate( float rotation ) { this->rotation += rotation; } VK2D_API glm::mat4 VK2D_APIENTRY vk2d::Transform::CalculateTransformationMatrix() const { auto position_matrix = glm::mat4( 1.0f ); { position_matrix[ 3 ][ 0 ] = position.x; position_matrix[ 3 ][ 1 ] = position.y; } auto rotation_matrix = vk2d::CreateRotationMatrix4( rotation ); auto scale_matrix = glm::mat4( 1.0f ); { scale_matrix[ 0 ][ 0 ] = scale.x; scale_matrix[ 1 ][ 1 ] = scale.y; } return position_matrix * rotation_matrix * scale_matrix; }
17.892857
87
0.698603
[ "transform" ]
0185b9e6affc9bb231f663395d09ec6855d66ffc
560
cpp
C++
week2/day14_Perform_String_Shifts.cpp
stefpant/30-Day-LeetCoding-Challenge
92ff3a47152559f27203001c0aeb96515154b6e1
[ "MIT" ]
2
2020-05-01T10:04:26.000Z
2020-05-01T11:54:40.000Z
week2/day14_Perform_String_Shifts.cpp
stefpant/30-Day-LeetCoding-Challenge
92ff3a47152559f27203001c0aeb96515154b6e1
[ "MIT" ]
null
null
null
week2/day14_Perform_String_Shifts.cpp
stefpant/30-Day-LeetCoding-Challenge
92ff3a47152559f27203001c0aeb96515154b6e1
[ "MIT" ]
null
null
null
class Solution { public: string stringShift(string s, vector<vector<int>>& shift) { int a,b; int len = s.length(); if(len < 2) return s; for(int i=0; i<shift.size(); i++){ a = shift[i][0]; b = shift[i][1]%len;//no need to have shift amount greater than string length if(!b) continue;//if amount == 0 skip it if(!a) s = s.substr(b,len-b) + s.substr(0,b);//shift left else s = s.substr(len-b,b) + s.substr(0,len-b);//shift right } return s; } };
32.941176
89
0.507143
[ "vector" ]
018c0847b857125c7ca3aadf9101e94c82c8c868
18,780
cpp
C++
Sources/MTM/CGroundBoxes.cpp
jpez1432/Legacy-Monster-Freestyle-Racing
bc370736643531d1bf310bd45453cd98036b58a4
[ "Info-ZIP" ]
null
null
null
Sources/MTM/CGroundBoxes.cpp
jpez1432/Legacy-Monster-Freestyle-Racing
bc370736643531d1bf310bd45453cd98036b58a4
[ "Info-ZIP" ]
null
null
null
Sources/MTM/CGroundBoxes.cpp
jpez1432/Legacy-Monster-Freestyle-Racing
bc370736643531d1bf310bd45453cd98036b58a4
[ "Info-ZIP" ]
null
null
null
// Include #include "CGroundBoxes.h" // Ground Boxes Class Header File extern string RootDir; // Global Root Directory extern float Tint[4]; // Weather Tint // Constructor CGroundBoxes::CGroundBoxes( ) { } // Destructor CGroundBoxes::~CGroundBoxes( ) { SAFE_DELETE( BoxLower ); SAFE_DELETE( BoxUpper ); SAFE_DELETE( BoxTextures ); // Delete OpenGL Display List glDeleteLists( BoxIds[0], BoxIds.size( ) ); // Release Box Id Vector BoxIds.empty( ); } // Return Box Lower Height float CGroundBoxes::Lower( int x, int z ) { // Wrap Values if (x == Dimensions) x = 0; if (z == Dimensions) z = 0; return (float)BoxLower[z+Dimensions*x] / 16.0f; } // Return Box Upper Height float CGroundBoxes::Upper( int x, int z ) { // Wrap Values if (x == Dimensions) x = 0; if (z == Dimensions) z = 0; return (float)BoxUpper[z+Dimensions*x] / 16.0f; } // Return Texture Index int CGroundBoxes::Index( int x, int z, int side ) { // Wrap Values if (x == Dimensions) x = 0; if (z == Dimensions) z = 0; return (int)BoxTextures[z+Dimensions*x].Indices[side] + (int)((BoxTextures[z+Dimensions*x].Rotations[side] & 1 ) << 8); } // Return Texture Rotation int CGroundBoxes::Rotation( int x, int z, int side ) { // Wrap Values if (x == Dimensions) x = 0; if (z == Dimensions) z = 0; return (int)BoxTextures[z+Dimensions*x].Rotations[side]; } // Load Boxes Lower, Upper Heights bool CGroundBoxes::LoadBoxHeights( string LowerFilename, string UpperFilename, CPodIni *cPodIni ) { string Temp; // Temp String ifstream Fs; // Filestream // Find Pod File Information if ( cPodIni->FileInfo( "Data\\" + LowerFilename, PodFile, Size, Offset ) == true ) { PodFile = RootDir + PodFile; // Build GroudBox Filename Fs.open( PodFile.c_str( ), ios::binary | ios::in ); // Open Pod File Fs.seekg( Offset ); // Seek Track File Offset Dimensions = (int)sqrt((double)Size); // Calculate Square Heightmap Size } else { PodFile = RootDir + "Data\\" + LowerFilename; // Build GroundBox Filename Fs.open( PodFile.c_str( ), ios::binary | ios::in ); // Open Track File Fs.seekg( 0, ios::end ); // Seek End Of File Dimensions = Fs.tellg( ); // Get File Length Fs.seekg( 0, ios::beg ); // Seek Beginning Of File Dimensions = (int)sqrt((double) Dimensions); // Calculate Square Heightmap Size } // Valid Ground Box Lower File if ( Fs.is_open( ) ) { // Allocate Box Lower Memory BoxLower = new unsigned char[Dimensions * Dimensions]; // Read Box Lower File Fs.read((char*)BoxLower, Dimensions * Dimensions ); // Close Ground Box Lower File Fs.close( ); } else { // Close Ground Box Lower File Fs.close( ); return false; // Return Error } // Find Pod File Information if ( cPodIni->FileInfo( "Data\\" + UpperFilename, PodFile, Size, Offset ) == true ) { PodFile = RootDir + PodFile; // Build GroudBox Filename Fs.open( PodFile.c_str( ), ios::binary | ios::in ); // Open Pod File Fs.seekg( Offset ); // Seek Track File Offset Dimensions = (int)sqrt((double)Size); // Calculate Square Heightmap Size } else { PodFile = RootDir + "Data\\" + UpperFilename; // Build GroundBox Filename Fs.open( PodFile.c_str( ), ios::binary | ios::in ); // Open Track File Fs.seekg( 0, ios::end ); // Seek End Of File Dimensions = Fs.tellg( ); // Get File Length Fs.seekg( 0, ios::beg ); // Seek Beginning Of File Dimensions = (int)sqrt((double) Dimensions); // Calculate Square Heightmap Size } // Valid Ground Box Upper File if ( Fs.is_open( ) ) { // Allocate Box Upper Memory BoxUpper= new unsigned char[Dimensions * Dimensions]; // Read Box Lower File Fs.read((char*)BoxUpper, Dimensions * Dimensions ); // Close Ground Box Upper File Fs.close( ); } else { // Close Ground Box Upper File Fs.close( ); return false; // Return Error } return true; // Ok } // Load Boxes Texture Information bool CGroundBoxes::LoadTextureInfo( string Filename, CPodIni *cPodIni ) { string Temp; // Temp String ifstream Fs; // Filestream // Find Pod File Information if ( cPodIni->FileInfo( "Data\\" + Filename, PodFile, Size, Offset ) == true ) { PodFile = RootDir + PodFile; // Build GroudBox Info Filename Fs.open( PodFile.c_str( ), ios::binary | ios::in ); // Open Pod File Fs.seekg( Offset ); // Seek Track File Offset Dimensions = Size / 12; // Calculate Box/Sides Difference Dimensions = (int)sqrt((double)Dimensions); // Calculate Square Texture Info Size } else { PodFile = RootDir + "Data\\" + Filename; // Build GroundBox Filename Fs.open( PodFile.c_str( ), ios::binary | ios::in ); // Open Track File Fs.seekg( 0, ios::end ); // Seek End Of File Dimensions = Fs.tellg( ); // Get File Length Fs.seekg( 0, ios::beg ); // Seek Beginning Of File Dimensions /= 12; // Calculate Texture Info Difference Dimensions = (int)sqrt((double)Dimensions); // Calculate Square Texture Information Size } // Valid Ground Box Upper File if ( Fs.is_open( ) ) { // Allocate Lighting Memory BoxTextures = new TextureInfo[Dimensions * Dimensions]; // Read Indices, Rotation Values for (int x = 0; x != Dimensions; x++) { for (int z = 0; z != Dimensions; z++) { for (int s = 0; s != 6; s++) { BoxTextures[z+Dimensions*x].Indices[s] = Fs.get(); // Read Index Value BoxTextures[z+Dimensions*x].Rotations[s] = Fs.get(); // Read Rotation Value } } } // Close Texture Information File Fs.close( ); } else { // Close Texture Information File Fs.close( ); return false; // Return Error } return true; // Return Ok } // Builds Box OpenGL Display Lists bool CGroundBoxes::BuildGroundBoxLists( CTextures *cTextures, CTerrain *cTerrain, CPodIni *cPodIni, float Tint[4] ) { // Variables float Low = 0, High = 0; int Rotate = 0, Mir_x = 0, Mir_y = 0; int Rot = 0; float Lights = 0; int xx = 0, zz = 0; // Allocate Display List Memory BoxIds.resize( 256 ); // Loop Box Chunks for ( int x = 0; x < 16; x++ ) { for ( int z = 0; z < 16; z++ ) { // Generate Chunk List, Compile BoxIds[z + 16 * x]=glGenLists( 1 ); glNewList( BoxIds[z + 16 * x], GL_COMPILE ); glDisable(GL_BLEND); glDisable(GL_ALPHA_TEST); //glEnable( GL_CULL_FACE ); // Loop Chunk Grid for ( float cx = 0; cx < 16; cx++ ) { for ( float cz = 0; cz < 16; cz++ ) { // Set Variables xx = int(x * 16 + cx); zz = int(z * 16 + cz); // Get Upper, Lower Heights High = Upper( xx, zz ); Low = Lower( xx, zz ); // No Ground Box if ( High == 0 && Low == 0 ) continue; // Bind List OpenGL Texture glBindTexture( GL_TEXTURE_2D, cTextures->TextureId( Index( xx, zz, 0 ) ) ); // Draw Quads glBegin(GL_QUADS); // Get Rotation Value Rotate = Rotation( xx, zz, 0 ); Mir_x = (Rotate & 32) >> 5; // Calculate Mirror X Mir_y = (Rotate & 16) >> 4; // Calculate Mirror Y Rot = (Rotate & 192) >> 6; // Calculate Rotation // Texture Coordinate, Vertex 1, Lighting Corner Lights = cTerrain->GetLight( xx, zz ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,1 )); glVertex3f( ( cx ), Low, ( cz ) ); // Texture Coordinate, Vertex 2, Lighting Corner Lights = cTerrain->GetLight( xx, zz ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,1 )); glVertex3f( ( cx ), High, ( cz) ); // Texture Coordinate, Vertex 3, Lighting Corner Lights = cTerrain->GetLight( xx, zz+1 ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,1 )); glVertex3f( ( cx ), High, ( cz+1 ) ); // Texture Coordinate, Vertex 4, Lighting Corner Lights = cTerrain->GetLight( xx, zz+1 ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,1 )); glVertex3f( ( cx ), Low, ( cz+1 ) ); // Quads Finished glEnd( ); // Bind List OpenGL Texture glBindTexture( GL_TEXTURE_2D, cTextures->TextureId( Index( xx, zz, 1 ) ) ); // Draw Quads glBegin(GL_QUADS); // Get Rotation Value Rotate = Rotation( xx, zz, 1 ); Mir_x = (Rotate & 32) >> 5; // Calculate Mirror X Mir_y = (Rotate & 16) >> 4; // Calculate Mirror Y Rot = (Rotate & 192) >> 6; // Calculate Rotation // Texture Coordinate, Vertex 1, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz+1 ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,1 )); glVertex3f( ( cx +1 ), Low, ( cz +1 ) ); // Texture Coordinate, Vertex 2, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz+1 ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,1 )); glVertex3f( ( cx +1 ), High, ( cz +1) ); // Texture Coordinate, Vertex 3, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,1 )); glVertex3f( ( cx +1), High, ( cz ) ); // Texture Coordinate, Vertex 4, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,1 )); glVertex3f( ( cx +1 ), Low, ( cz) ); // Quads Finished glEnd( ); // Bind List OpenGL Texture glBindTexture( GL_TEXTURE_2D, cTextures->TextureId( Index( xx, zz, 2 ) ) ); // Draw Quads glBegin(GL_QUADS); // Get Rotation Value Rotate = Rotation( xx, zz, 2 ); Mir_x = (Rotate & 32) >> 5; // Calculate Mirror X Mir_y = (Rotate & 16) >> 4; // Calculate Mirror Y Rot = (Rotate & 192) >> 6; // Calculate Rotation // Texture Coordinate, Vertex 1, Lighting Corner Lights = cTerrain->GetLight( xx, zz +1); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,1 )); glVertex3f( ( cx ), Low, ( cz + 1 ) ); // Texture Coordinate, Vertex 2, Lighting Corner Lights = cTerrain->GetLight( xx, zz+1 ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,1 )); glVertex3f( ( cx ), High, ( cz +1) ); // Texture Coordinate, Vertex 3, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz+1); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,1 )); glVertex3f( ( cx+1 ), High, ( cz+1 ) ); // Texture Coordinate, Vertex 4, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz+1 ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,1 )); glVertex3f( ( cx+1 ), Low, ( cz+1 ) ); // Quads Finished glEnd( ); // Bind List OpenGL Texture glBindTexture( GL_TEXTURE_2D, cTextures->TextureId( Index( xx, zz, 3 ) ) ); // Draw Quads glBegin(GL_QUADS); // Get Rotation Value Rotate = Rotation( xx, zz, 3 ); Mir_x = (Rotate & 32) >> 5; // Calculate Mirror X Mir_y = (Rotate & 16) >> 4; // Calculate Mirror Y Rot = (Rotate & 192) >> 6; // Calculate Rotation // Texture Coordinate, Vertex 1, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,1 )); glVertex3f( ( cx + 1 ), Low, ( cz ) ); // Texture Coordinate, Vertex 2, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,1 )); glVertex3f( ( cx+1 ), High, ( cz ) ); // Texture Coordinate, Vertex 3, Lighting Corner Lights = cTerrain->GetLight( xx, zz ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,1 )); glVertex3f( ( cx ), High, ( cz ) ); // Texture Coordinate, Vertex 4, Lighting Corner Lights = cTerrain->GetLight( xx, zz ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,1 )); glVertex3f( ( cx ), Low, ( cz ) ); // Quads Finished glEnd( ); // Bind List OpenGL Texture glBindTexture( GL_TEXTURE_2D, cTextures->TextureId( Index( xx, zz, 4 ) ) ); // Draw Quads glBegin(GL_QUADS); // Get Rotation Value Rotate = Rotation( xx, zz, 4 ); Mir_x = (Rotate & 32) >> 5; // Calculate Mirror X Mir_y = (Rotate & 16) >> 4; // Calculate Mirror Y Rot = (Rotate & 192) >> 6; // Calculate Rotation // Texture Coordinate, Vertex 1, Lighting Corner Lights = cTerrain->GetLight( xx, zz ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,1 )); glVertex3f( ( cx ), High, ( cz ) ); // Texture Coordinate, Vertex 2, Lighting Corner Lights = cTerrain->GetLight( xx +1, zz ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,1 )); glVertex3f( ( cx+1 ), High, ( cz ) ); // Texture Coordinate, Vertex 3, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz+1 ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,1 )); glVertex3f( ( cx+1 ), High, ( cz+1 ) ); // Texture Coordinate, Vertex 4, Lighting Corner Lights = cTerrain->GetLight( xx, zz+1 ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,1 )); glVertex3f( ( cx ), High, ( cz+1 ) ); // Quads Finished glEnd( ); // Bind List OpenGL Texture glBindTexture( GL_TEXTURE_2D, cTextures->TextureId( Index( xx, zz, 5 ) ) ); // Draw Quads glBegin(GL_QUADS); // Get Rotation Value Rotate = Rotation( xx, zz, 5 ); Mir_x = (Rotate & 32) >> 5; // Calculate Mirror X Mir_y = (Rotate & 16) >> 4; // Calculate Mirror Y Rot = (Rotate & 192) >> 6; // Calculate Rotation // Texture Coordinate, Vertex 1, Lighting Corner Lights = cTerrain->GetLight( xx, zz ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,0,1 )); glVertex3f( ( cx ), Low, ( cz ) ); // Texture Coordinate, Vertex 2, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,3,1 )); glVertex3f( ( cx ), Low, ( cz+1 ) ); // Texture Coordinate, Vertex 3, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz+1 ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,2,1 )); glVertex3f( ( cx+1 ), Low, ( cz+1 ) ); // Texture Coordinate, Vertex 4, Lighting Corner Lights = cTerrain->GetLight( xx+1, zz+1 ); glColor3f(/* Lights * */Tint[0], /* Lights * */Tint[1], /* Lights * */Tint[2]); glTexCoord2f(cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,0 ),cTextures->GetTexCoords( Mir_x,Mir_y,Rot,1,1 )); glVertex3f( ( cx+1 ), Low, ( cz ) ); // Quads Finished glEnd( ); } } glEnable(GL_BLEND); glEnable(GL_ALPHA_TEST); glDisable( GL_CULL_FACE ); // List Finished glEndList(); } } return true; }
34.20765
121
0.574388
[ "vector" ]
018c372d340003719c249de1d85475662c2aef50
7,200
cpp
C++
Sources/Physics/Rigidbody.cpp
0xflotus/Acid
cf680a13c3894822920737dcf1b7d17aef74a474
[ "MIT" ]
null
null
null
Sources/Physics/Rigidbody.cpp
0xflotus/Acid
cf680a13c3894822920737dcf1b7d17aef74a474
[ "MIT" ]
null
null
null
Sources/Physics/Rigidbody.cpp
0xflotus/Acid
cf680a13c3894822920737dcf1b7d17aef74a474
[ "MIT" ]
null
null
null
#include "Rigidbody.hpp" #include <cassert> #include <BulletCollision/CollisionShapes/btCollisionShape.h> #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h> #include <BulletDynamics/Dynamics/btRigidBody.h> #include <LinearMath/btDefaultMotionState.h> #include "Scenes/Scenes.hpp" #include "Collider.hpp" namespace acid { Rigidbody::Rigidbody(const float &mass, const float &friction, const Transform &localTransform, const Vector3 &linearFactor, const Vector3 &angularFactor) : m_mass(mass), m_friction(friction), m_localTransform(localTransform), m_linearFactor(linearFactor), m_angularFactor(angularFactor), m_shape(nullptr), m_body(nullptr), m_forces(std::vector<std::unique_ptr<Force>>()), m_linearVelocity(Vector3()), m_angularVelocity(Vector3()) { } Rigidbody::~Rigidbody() { btRigidBody *body = btRigidBody::upcast(m_body.get()); if (body && body->getMotionState()) { delete body->getMotionState(); } Scenes::Get()->GetPhysics()->GetDynamicsWorld()->removeCollisionObject(m_body.get()); } void Rigidbody::Start() { btTransform worldTransform = Collider::Convert(GetGameObject()->GetTransform()); auto shape = GetGameObject()->GetComponent<Collider>(); if (shape != nullptr && shape->GetCollisionShape() != nullptr) { m_shape = shape->GetCollisionShape(); m_body = CreateRigidBody(m_mass, worldTransform, m_shape); m_body->setWorldTransform(worldTransform); // m_body->setContactStiffnessAndDamping(1000.0f, 0.1f); m_body->setFriction(m_friction); m_body->setRollingFriction(m_friction); m_body->setSpinningFriction(m_friction); // TODO: Set local transform. m_body->setLinearFactor(Collider::Convert(m_linearFactor)); m_body->setAngularFactor(Collider::Convert(m_angularFactor)); m_body->setUserPointer(GetGameObject()); Scenes::Get()->GetPhysics()->GetDynamicsWorld()->addRigidBody(m_body.get()); m_body->activate(true); } } void Rigidbody::Update() { if (m_body == nullptr) { Start(); return; } auto shape = GetGameObject()->GetComponent<Collider>(); if (shape != nullptr) { if (m_shape != shape->GetCollisionShape()) { m_shape = shape->GetCollisionShape(); m_body->setCollisionShape(m_shape); } if (m_mass != 0.0f) { btVector3 localInertia = btVector3(); shape->GetCollisionShape()->calculateLocalInertia(m_mass, localInertia); m_body->setMassProps(m_mass, localInertia); } } for (auto it = m_forces.begin(); it != m_forces.end();) { (*it)->Update(); m_body->applyForce(Collider::Convert((*it)->GetForce()), Collider::Convert((*it)->GetPosition())); if ((*it)->IsExpired()) { it = m_forces.erase(it); continue; } ++it; } auto &transform = GetGameObject()->GetTransform(); btTransform worldTransform; m_body->getMotionState()->getWorldTransform(worldTransform); transform = Collider::Convert(worldTransform, transform.GetScaling()); // worldTransform->setIdentity(); // worldTransform->setOrigin(Collider::Convert(transform.GetPosition())); // worldTransform->setRotation(Collider::Convert(transform.GetRotation())); m_shape->setLocalScaling(Collider::Convert(m_localTransform.GetScaling() * transform.GetScaling())); // m_body->getMotionState()->setWorldTransform(*worldTransform); m_linearVelocity = Collider::Convert(m_body->getLinearVelocity()); m_angularVelocity = Collider::Convert(m_body->getAngularVelocity()); // m_body->setLinearVelocity(Collider::Convert(m_linearVelocity)); // m_body->setAngularVelocity(Collider::Convert(m_angularVelocity)); } void Rigidbody::Decode(const Metadata &metadata) { m_mass = metadata.GetChild<float>("Mass"); m_friction = metadata.GetChild<float>("Friction"); m_localTransform = metadata.GetChild<Transform>("Local Transform"); m_linearFactor = metadata.GetChild<Vector3>("Linear Factor"); m_angularFactor = metadata.GetChild<Vector3>("Angular Factor"); } void Rigidbody::Encode(Metadata &metadata) const { metadata.SetChild<float>("Mass", m_mass); metadata.SetChild<float>("Friction", m_friction); metadata.SetChild<Transform>("Local Transform", m_localTransform); metadata.SetChild<Vector3>("Linear Factor", m_linearFactor); metadata.SetChild<Vector3>("Angular Factor", m_angularFactor); } bool Rigidbody::InFrustum(const Frustum &frustum) { btVector3 min = btVector3(); btVector3 max = btVector3(); if (m_body != nullptr && m_shape != nullptr) { m_body->getAabb(min, max); } return frustum.CubeInFrustum(Collider::Convert(min), Collider::Convert(max)); } void Rigidbody::SetGravity(const Vector3 &gravity) { m_body->setGravity(Collider::Convert(gravity)); } Force *Rigidbody::AddForce(Force *force) { m_forces.emplace_back(force); return force; } void Rigidbody::ClearForces() { m_body->clearForces(); } void Rigidbody::SetMass(const float &mass) { m_mass = mass; bool isDynamic = m_mass != 0.0f; btVector3 localInertia = btVector3(0.0f, 0.0f, 0.0f); auto shape = GetGameObject()->GetComponent<Collider>(); if (shape != nullptr && isDynamic) { shape->GetCollisionShape()->calculateLocalInertia(m_mass, localInertia); } m_body->setMassProps(m_mass, localInertia); } void Rigidbody::SetFriction(const float &friction) { m_friction = friction; m_body->setFriction(m_friction); m_body->setRollingFriction(m_friction); m_body->setSpinningFriction(m_friction); } void Rigidbody::SetLocalTransform(const Transform &localTransform) { m_localTransform = localTransform; // TODO: Set local transform. } void Rigidbody::SetLinearFactor(const Vector3 &linearFactor) { m_linearFactor = linearFactor; m_body->setLinearFactor(Collider::Convert(m_linearFactor)); } void Rigidbody::SetAngularFactor(const Vector3 &angularFactor) { m_angularFactor = angularFactor; m_body->setAngularFactor(Collider::Convert(m_angularFactor)); } void Rigidbody::SetLinearVelocity(const Vector3 &linearVelocity) { m_linearVelocity = linearVelocity; m_body->setLinearVelocity(Collider::Convert(m_linearVelocity)); } void Rigidbody::SetAngularVelocity(const Vector3 &angularVelocity) { m_angularVelocity = angularVelocity; m_body->setAngularVelocity(Collider::Convert(m_angularVelocity)); } std::unique_ptr<btRigidBody> Rigidbody::CreateRigidBody(float mass, const btTransform &startTransform, btCollisionShape* shape) { assert((!shape || shape->getShapeType() != INVALID_SHAPE_PROXYTYPE) && "Invalid rigidbody shape!"); btVector3 localInertia = btVector3(); // Rigidbody is dynamic if and only if mass is non zero, otherwise static. if (mass != 0.0f) { shape->calculateLocalInertia(mass, localInertia); } // Using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects. btDefaultMotionState *myMotionState = new btDefaultMotionState(startTransform); btRigidBody::btRigidBodyConstructionInfo cInfo(mass, myMotionState, shape, localInertia); auto body = std::make_unique<btRigidBody>(cInfo); // body->setContactProcessingThreshold(m_defaultContactProcessingThreshold); // body->setUserIndex(-1); return body; } }
29.387755
157
0.733056
[ "shape", "vector", "transform" ]
018d3094c9c6e8925ff8f39f26af1ae2504f453e
27,960
cpp
C++
asciified.cpp
Uki99/img2ascii
4805fdf673aae3dd0dce66430e6c15da4187054a
[ "CC0-1.0" ]
null
null
null
asciified.cpp
Uki99/img2ascii
4805fdf673aae3dd0dce66430e6c15da4187054a
[ "CC0-1.0" ]
null
null
null
asciified.cpp
Uki99/img2ascii
4805fdf673aae3dd0dce66430e6c15da4187054a
[ "CC0-1.0" ]
null
null
null
#include "ASCIIFied.h" static const map<FLOAT, vector<CHAR>> luma_char_map = { {0.f, {' '}}, {0.133333f, {'.'}}, {0.155556f, {'-'}}, {0.177778f, {','}}, {0.266667f, {':'}}, {0.311111f, {'+'}}, {0.333333f, {'~'}}, {0.355556f, {';'}}, {0.4f, {'('}}, {0.444444f, {'%'}}, {0.488889f, {'x'}}, {0.511111f, {'1'}}, {0.533333f, {'*'}}, {0.555556f, {'n', 'u'}}, {0.577778f, {'T'}}, {0.6f, {'3'}}, {0.622222f, {'J'}}, {0.644444f, {'5'}}, {0.666667f, {'$'}}, {0.688889f, {'S'}}, {0.711111f, {'4'}}, {0.733333f, {'F', 'P'}}, {0.755556f, {'G', 'O', 'V', 'X'}}, {0.777778f, {'E', 'Z'}}, {0.8f, {'8', 'A', 'U'}}, {0.844444f, {'D', 'H', 'K', 'W'}}, {0.888889f, {'@'}}, {0.911111f, {'B', 'Q'}}, {0.933333f, {'#'}}, {1.f, {'0', 'M', 'N'}}, }; static const Char luma_char_map_x[95] = { { ' ', 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, { '!', 0.25f, 0.625f, 0.f, 0.166667f, 0.555556f, 0.f, 0.f, 0.222222f, 0.f }, { '"', 0.5f, 0.5f, 0.666667f, 0.0833333f, 0.277778f, 0.166667f, 0.f, 0.f, 0.f }, { '#', 0.5f, 0.75f, 0.f, 0.666667f, 1.f, 0.333333f, 0.2f, 0.333333f, 0.f }, { '$', 0.25f, 1.f, 0.f, 0.583333f, 0.583333f, 0.f, 0.f, 0.444444f, 0.f }, { '%', 0.f, 0.f, 0.f, 0.583333f, 0.444444f, 0.f, 0.2f, 0.222222f, 0.f }, { '&', 0.75f, 0.5f, 0.f, 0.916667f, 0.861111f, 0.333333f, 0.2f, 0.333333f, 0.f }, { '\'', 0.f, 0.5f, 0.f, 0.0833333f, 0.166667f, 0.f, 0.f, 0.f, 0.f }, { '(', 0.f, 0.5f, 0.f, 0.25f, 0.444444f, 0.f, 0.f, 0.222222f, 0.f }, { ')', 0.25f, 0.375f, 0.f, 0.f, 0.444444f, 0.f, 0.2f, 0.111111f, 0.f }, { '*', 0.f, 0.f, 0.f, 0.333333f, 0.611111f, 0.666667f, 0.f, 0.f, 0.f }, { '+', 0.f, 0.f, 0.f, 0.0833333f, 0.388889f, 0.166667f, 0.f, 0.f, 0.f }, { ',', 0.f, 0.f, 0.f, 0.f, 0.166667f, 0.f, 0.2f, 0.444444f, 0.f }, { '-', 0.f, 0.f, 0.f, 0.166667f, 0.166667f, 0.166667f, 0.f, 0.f, 0.f }, { '.', 0.f, 0.f, 0.f, 0.f, 0.166667f, 0.f, 0.f, 0.333333f, 0.f }, { '/', 0.f, 0.f, 0.333333f, 0.25f, 0.333333f, 0.166667f, 0.2f, 0.f, 0.f }, { '0', 0.75f, 0.625f, 0.333333f, 1.f, 0.916667f, 1.f, 0.2f, 0.444444f, 0.f }, { '1', 0.f, 0.375f, 0.f, 0.166667f, 0.555556f, 0.f, 0.4f, 0.444444f, 0.f }, { '2', 0.75f, 0.625f, 0.f, 0.416667f, 0.611111f, 0.f, 0.4f, 0.444444f, 0.f }, { '3', 0.75f, 0.625f, 0.f, 0.166667f, 0.583333f, 0.f, 0.2f, 0.333333f, 0.f }, { '4', 0.f, 0.625f, 0.f, 0.416667f, 0.777778f, 0.166667f, 0.f, 0.333333f, 0.f }, { '5', 1.f, 0.5f, 0.f, 0.666667f, 0.5f, 0.f, 0.2f, 0.333333f, 0.f }, { '6', 0.25f, 0.5f, 0.f, 1.f, 0.583333f, 0.f, 0.2f, 0.333333f, 0.f }, { '7', 1.f, 0.625f, 0.666667f, 0.166667f, 0.5f, 0.333333f, 0.f, 0.222222f, 0.f }, { '8', 0.75f, 0.625f, 0.f, 0.916667f, 0.722222f, 0.f, 0.2f, 0.333333f, 0.f }, { '9', 0.75f, 0.625f, 0.f, 0.416667f, 0.638889f, 0.f, 0.2f, 0.222222f, 0.f }, { ':', 0.f, 0.f, 0.f, 0.f, 0.333333f, 0.f, 0.f, 0.f, 0.f }, { ';', 0.f, 0.f, 0.f, 0.f, 0.388889f, 0.f, 0.f, 0.444444f, 0.f }, { '<', 0.f, 0.5f, 0.f, 0.333333f, 0.416667f, 0.f, 0.f, 0.222222f, 0.f }, { '=', 0.f, 0.f, 0.f, 0.166667f, 0.333333f, 0.333333f, 0.f, 0.f, 0.f }, { '>', 0.25f, 0.375f, 0.f, 0.f, 0.444444f, 0.166667f, 0.2f, 0.111111f, 0.f }, { '?', 0.75f, 0.625f, 0.f, 0.f, 0.416667f, 0.f, 0.f, 0.222222f, 0.f }, { '@', 0.75f, 0.625f, 0.333333f, 1.f, 0.777778f, 0.666667f, 0.2f, 0.444444f, 0.f }, { 'A', 0.25f, 0.625f, 0.f, 1.f, 0.75f, 0.f, 0.4f, 0.222222f, 0.f }, { 'B', 0.75f, 0.75f, 0.333333f, 0.5f, 0.944444f, 0.833333f, 0.4f, 0.444444f, 0.f }, { 'C', 0.25f, 0.75f, 0.333333f, 0.916667f, 0.583333f, 0.5f, 0.f, 0.444444f, 0.f }, { 'D', 0.75f, 0.75f, 0.f, 0.5f, 0.888889f, 0.833333f, 0.4f, 0.333333f, 0.f }, { 'E', 0.75f, 0.625f, 0.666667f, 0.5f, 0.75f, 0.166667f, 0.4f, 0.444444f, 0.f }, { 'F', 0.75f, 0.75f, 0.666667f, 0.5f, 0.694444f, 0.166667f, 0.4f, 0.222222f, 0.f }, { 'G', 0.25f, 0.75f, 0.333333f, 0.916667f, 0.694444f, 0.666667f, 0.f, 0.444444f, 0.f }, { 'H', 1.f, 0.5f, 0.f, 1.f, 0.722222f, 0.f, 0.4f, 0.222222f, 0.f }, { 'I', 0.25f, 0.625f, 0.f, 0.f, 0.5f, 0.f, 0.2f, 0.333333f, 0.f }, { 'J', 0.f, 0.625f, 0.333333f, 0.5f, 0.583333f, 0.f, 0.2f, 0.333333f, 0.f }, { 'K', 0.75f, 0.5f, 0.666667f, 0.5f, 0.888889f, 0.166667f, 0.4f, 0.222222f, 0.f }, { 'L', 0.75f, 0.375f, 0.f, 0.5f, 0.694444f, 0.5f, 0.4f, 0.444444f, 0.f }, { 'M', 1.f, 0.5f, 0.666667f, 1.f, 0.916667f, 1.f, 0.4f, 0.111111f, 0.f }, { 'N', 1.f, 0.25f, 0.666667f, 1.f, 0.916667f, 1.f, 0.4f, 0.111111f, 0.f }, { 'O', 0.25f, 0.75f, 0.f, 0.916667f, 0.722222f, 0.833333f, 0.f, 0.333333f, 0.f }, { 'P', 0.75f, 0.75f, 0.333333f, 0.5f, 0.722222f, 0.333333f, 0.4f, 0.222222f, 0.f }, { 'Q', 0.25f, 0.75f, 0.f, 0.916667f, 0.805556f, 0.833333f, 0.f, 0.555556f, 0.f }, { 'R', 0.75f, 0.75f, 0.333333f, 0.5f, 0.916667f, 0.666667f, 0.4f, 0.222222f, .0f }, { 'S', 0.75f, 0.625f, 0.f, 0.75f, 0.611111f, 0.f, 0.2f, 0.333333f, 0.f }, { 'T', 0.75f, 0.875f, 0.f, 0.f, 0.527778f, 0.f, 0.2f, 0.333333f, 0.f }, { 'U', 1.f, 0.5f, 0.f, 1.f, 0.694444f, 0.f, 0.2f, 0.333333f, 0.f }, { 'V', 1.f, 0.5f, 0.f, 0.916667f, 0.666667f, 0.f, 0.f, 0.222222f, 0.f }, { 'W', 1.f, 0.25f, 0.666667f, 0.833333f, 0.805556f, 0.666667f, 0.2f, 0.333333f, 0.f }, { 'X', 1.f, 0.5f, 0.f, 0.666667f, 0.694444f, 0.f, 0.4f, 0.222222f, 0.f }, { 'Y', 1.f, 0.5f, 0.f, 0.416667f, 0.638889f, 0.f, 0.2f, 0.333333f, 0.f }, { 'Z', 1.f, 0.75f, 0.666667f, 0.416667f, 0.666667f, 0.333333f, 0.4f, 0.444444f, 0.f }, { '[', 0.f, 0.75f, 0.f, 0.f, 0.5f, 0.f, 0.f, 0.444444f, 0.f }, { '\\', 0.25f, 0.f, 0.f, 0.25f, 0.333333f, 0.166667f, 0.f, 0.f, 0.f }, { ']', 0.f, 0.75f, 0.f, 0.f, 0.5f, 0.f, 0.f, 0.444444f, 0.f }, { '^', 0.25f, 0.875f, 0.f, 0.166667f, 0.194444f, 0.166667f, 0.f, 0.f, 0.f }, { '_', 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.4f, 0.444444f, 0.f }, { '`', 0.f, 0.75f, 0.f, 0.f, 0.0555556f, 0.f, 0.f, 0.f, 0.f }, { 'a', 0.f, 0.f, 0.f, 0.5f, 0.611111f, 0.f, 0.2f, 0.333333f, 0.f }, { 'b', 0.75f, 0.25f, 0.f, 0.5f, 0.805556f, 0.666667f, 0.4f, 0.333333f, 0.f }, { 'c', 0.f, 0.f, 0.f, 0.75f, 0.444444f, 0.f, 0.2f, 0.333333f, 0.f }, { 'd', 0.f, 0.625f, 0.f, 0.75f, 0.722222f, 0.f, 0.2f, 0.333333f, 0.f }, { 'e', 0.f, 0.f, 0.f, 0.75f, 0.555556f, 0.f, 0.2f, 0.333333f, 0.f }, { 'f', 0.25f, 0.75f, 0.f, 0.583333f, 0.583333f, 0.f, 0.4f, 0.222222f, 0.f }, { 'g', 0.f, 0.f, 0.f, 0.666667f, 0.583333f, 0.166667f, 0.6f, 0.777778f, 0.f }, { 'h', 0.75f, 0.25f, 0.f, 0.5f, 0.805556f, 0.666667f, 0.4f, 0.222222f, 0.f }, { 'i', 0.f, 0.5f, 0.f, 0.0833333f, 0.555556f, 0.f, 0.2f, 0.444444f, 0.f }, { 'j', 0.f, 0.5f, 0.f, 0.f, 0.472222f, 0.f, 1.f, 0.777778f, 0.f }, { 'k', 0.75f, 0.25f, 0.f, 0.5f, 0.777778f, 0.333333f, 0.4f, 0.222222f, 0.f }, { 'l', 0.25f, 0.625f, 0.f, 0.f, 0.555556f, 0.f, 0.2f, 0.444444f, 0.f }, { 'm', 0.f, 0.f, 0.f, 0.833333f, 0.666667f, 0.666667f, 0.4f, 0.111111f, 0.f }, { 'n', 0.f, 0.f, 0.f, 0.833333f, 0.527778f, 0.f, 0.4f, 0.222222f, 0.f }, { 'o', 0.f, 0.f, 0.f, 0.75f, 0.555556f, 0.f, 0.2f, 0.333333f, 0.f }, { 'p', 0.f, 0.f, 0.f, 0.5f, 0.694444f, 0.666667f, 0.8f, 0.777778f, 0.f }, { 'q', 0.f, 0.f, 0.f, 0.75f, 0.611111f, 0.166667f, 0.2f, 1.f, 0.f }, { 'r', 0.f, 0.f, 0.f, 0.5f, 0.583333f, 0.333333f, 0.4f, 0.222222f, 0.f }, { 's', 0.f, 0.f, 0.f, 0.5f, 0.5f, 0.f, 0.2f, 0.333333f, 0.f }, { 't', 0.f, 0.125f, 0.f, 0.583333f, 0.583333f, 0.f, 0.f, 0.333333f, 0.f }, { 'u', 0.f, 0.f, 0.f, 0.833333f, 0.555556f, 0.f, 0.2f, 0.333333f, 0.f }, { 'v', 0.f, 0.f, 0.f, 0.75f, 0.5f, 0.f, 0.f, 0.222222f, 0.f }, { 'w', 0.f, 0.f, 0.f, 0.75f, 0.611111f, 0.666667f, 0.2f, 0.333333f, 0.f }, { 'x', 0.f, 0.f, 0.f, 0.333333f, 0.555556f, 0.166667f, 0.4f, 0.111111f, 0.f }, { 'y', 0.f, 0.f, 0.f, 0.333333f, 0.611111f, 0.666667f, 0.4f, 0.666667f, 0.f }, { 'z', 0.f, 0.f, 0.f, 0.5f, 0.5f, 0.f, 0.4f, 0.444444f, 0.f }, { '{', 0.f, 0.625f, 0.f, 0.333333f, 0.444444f, 0.f, 0.f, 0.333333f, 0.f }, { '|', 0.f, 0.5f, 0.f, 0.f, 0.388889f, 0.f, 0.f, 0.222222f, 0.f }, { '}', 0.5f, 0.375f, 0.f, 0.f, 0.444444f, 0.f, 0.4f, 0.111111f, 0.f }, { '~', 0.75f, 0.5f, 1.f, 0.166667f, 0.222222f, 0.166667f, 0.f, 0.f, 0.f } }; ASCIIFied::ASCIIFied(CONST WCHAR* image_path, UINT chars_per_line, UINT scaled_image_width, bool gamma_brightness_correction, bool edge_detection) { this->chars_per_line = chars_per_line; this->edge_detection = edge_detection; this->decoded_art = nullptr; if (this->chars_per_line > max_line_length) { cerr << "Number of characters per single line provided for ASCII art is bigger than allowed. Please provide a smaller number." << endl; exit(EXIT_FAILURE); } wstring extension = this->get_image_extension(image_path); if (extension != L"jpeg" && extension != L"jpg" && extension != L"png" && extension != L"gif" && extension != L"bmp" && extension != L"tiff") { cerr << "File type provided is different than supported. The supported file types are: jpg, png, gif, bmp and tiff." << endl; exit(EXIT_FAILURE); } // Start Gdiplus GdiplusStartupInput gdiplusStartupInput; GdiplusStartup(&this->gdiplusToken, &gdiplusStartupInput, NULL); this->image = new Bitmap(image_path); if (this->image->GetLastStatus() != Ok) { cerr << "Error opening the requested image file. Terminating the program." << endl; exit(EXIT_FAILURE); } this->width = this->image->GetWidth(); this->height = this->image->GetHeight(); // Check if height and width exceed allowed size if (this->width > max_width || this->height > max_height) { cerr << "File width or height exceedes allowed amount. Please choose a smaller image." << endl; exit(EXIT_FAILURE); } // Scale the input image to the desired width in pixels preserving original aspect ratio this->resize_image(scaled_image_width); if (gamma_brightness_correction) { this->apply_gamma_briCon_correction(this->scaledImage); } // Calculates a suited grid for scaled bitmap and populates each section with corresponding data! this->gridify(this->scaledImage); } ASCIIFied::~ASCIIFied(VOID) { delete this->image; delete this->scaledImage; delete[] this->sectionMap; delete[] this->decoded_art; GdiplusShutdown(this->gdiplusToken); } Section::Section(INT posX, INT posY, UINT width, UINT height, Bitmap* image) { this->image = image; this->posX = posX; this->posY = posY; this->width = width; this->height = height; this->averageBrightness = 0.f; memset(this->averageBrightnessMap, 0, sizeof(FLOAT) * 9); } Section::Section(VOID) { this->image = nullptr; this->height = 0; this->width = 0; this->posX = 0; this->posY = 0; this->averageBrightness = 0; memset(this->averageBrightnessMap, 0, sizeof(FLOAT) * 9); } FLOAT Section::calculate_pixel_brightness(INT x, INT y, BitmapData& imageData) { // Calculating average brightness of a single pixel from the given RGB value for pixel positioned at XY coordinate // Pixel luminance = (0.2126 * R + 0.7152 * G + 0.0722 * B) // https://en.wikipedia.org/wiki/Relative_luminance byte* pixel = (byte*)imageData.Scan0 + (y * imageData.Stride); // Watch out for actual order (BGR)! // 3 stands for bytes per pixel INT bIndex = x * 3; INT gIndex = bIndex + 1; INT rIndex = bIndex + 2; FLOAT red = (FLOAT)pixel[rIndex]; FLOAT green = (FLOAT)pixel[gIndex]; FLOAT blue = (FLOAT)pixel[bIndex]; return ((0.2126f * red + 0.7152f * green + 0.0722f * blue) / 255.f); } VOID Section::calculate_average_brightness(VOID) { if (this->image == nullptr) { cerr << "Section tried to access null pointer image. Terminating the program" << endl; exit(EXIT_FAILURE); } // Calculates average brightness of a section // Locking image data and passing to the function calculate_pixel_brightness() for speed performance! BitmapData image_data; this->image->LockBits(&Rect(0, 0, this->image->GetWidth(), this->image->GetHeight()), ImageLockModeRead, PixelFormat24bppRGB, &image_data); for (UINT i = this->posX; i < this->posX + this->width; ++i) { for (UINT j = this->posY; j < this->posY + this->height; ++j) { this->averageBrightness = this->averageBrightness + this->calculate_pixel_brightness(i, j, image_data); } } this->averageBrightness = this->averageBrightness / (FLOAT)(this->width * this->height); // Unlock the memory this->image->UnlockBits(&image_data); } VOID Section::calculate_disected_brightness(VOID) { if (this->image == nullptr) { cerr << "Section tried to access null pointer image. Terminating the program" << endl; exit(EXIT_FAILURE); } // Locking image data and passing to the function calculate_pixel_brightness() for speed performance! BitmapData image_data; this->image->LockBits(&Rect(0, 0, this->image->GetWidth(), this->image->GetHeight()), ImageLockModeRead, PixelFormat24bppRGB, &image_data); INT w25 = (INT)round((FLOAT)this->width * 0.25f); // 25% width INT h25 = (INT)round((FLOAT)this->height * 0.25f); // 25% height INT w50 = (INT)round((FLOAT)this->width * 0.5f); // 50% width INT h50 = (INT)round((FLOAT)this->height * 0.5f); // 50% height INT w75 = (INT)round((FLOAT)this->width * 0.75f); // 75% width INT h67 = (INT)round((FLOAT)this->height * 0.67f); // 67% height // Top left for (INT i = this->posX; i < this->posX + w25; ++i) { for (INT j = this->posY; j < this->posY + h25; ++j) { this->averageBrightnessMap[0] += this->calculate_pixel_brightness(i, j, image_data); } } this->averageBrightnessMap[0] = this->averageBrightnessMap[0] / (w25 * h25); // Top Middle for (INT i = this->posX + w25; i < this->posX + w25 + w50; ++i) { for (INT j = this->posY; j < this->posY + h25; ++j) { this->averageBrightnessMap[1] += this->calculate_pixel_brightness(i, j, image_data); } } this->averageBrightnessMap[1] = this->averageBrightnessMap[1] / (w50 * h25); // Top Right for (INT i = this->posX + w25 + w50; i < this->posX + (INT)this->width; ++i) { for (INT j = this->posY; j < this->posY + h25; ++j) { this->averageBrightnessMap[2] += this->calculate_pixel_brightness(i, j, image_data); } } this->averageBrightnessMap[2] = this->averageBrightnessMap[2] / (w25 * h25); // Middle left for (INT i = this->posX; i < this->posX + w25; ++i) { for (INT j = this->posY + h25; j < this->posY + h25 + h50; ++j) { this->averageBrightnessMap[3] += this->calculate_pixel_brightness(i, j, image_data); } } this->averageBrightnessMap[3] = this->averageBrightnessMap[3] / (w25 * h50); // Middle (!!!) for (INT i = this->posX + (INT)(w25/2); i < this->posX + (INT)this->width - (INT)(w25/2); ++i) { for (INT j = this->posY + (INT)(h25 * 2 / 3); j < ((this->posY + (INT)this->height) - (INT)(h25 * 2 / 3)); ++j) { this->averageBrightnessMap[4] += this->calculate_pixel_brightness(i, j, image_data); } } this->averageBrightnessMap[4] = this->averageBrightnessMap[4] / (w75 * h67); // Middle right for (INT i = this->posX + w50 + w25; i < this->posX + (INT)this->width; ++i) { for (INT j = this->posY + h25; j < this->posY + h25 + h50; ++j) { this->averageBrightnessMap[5] += this->calculate_pixel_brightness(i, j, image_data); } } this->averageBrightnessMap[5] = this->averageBrightnessMap[5] / (w25 * h50); // Bottom left for (INT i = this->posX; i < this->posX + w25; ++i) { for (INT j = this->posY + h50 + h25; j < this->posY + (INT)this->height; ++j) { this->averageBrightnessMap[6] += this->calculate_pixel_brightness(i, j, image_data); } } this->averageBrightnessMap[6] = this->averageBrightnessMap[6] / (w25 * h25); // Bottom middle for (INT i = this->posX + w25; i < this->posX + w25 + w50; ++i) { for (INT j = this->posY + h50 + h25; j < this->posY + (INT)this->height; ++j) { this->averageBrightnessMap[7] += this->calculate_pixel_brightness(i, j, image_data); } } this->averageBrightnessMap[7] = this->averageBrightnessMap[7] / (w50 * h25); // Bottom right for (INT i = this->posX + w25 + w50; i < this->posX + (INT)this->width; ++i) { for (INT j = this->posY + h50 + h25; j < this->posY + (INT)this->height; ++j) { this->averageBrightnessMap[8] += this->calculate_pixel_brightness(i, j, image_data); } } this->averageBrightnessMap[8] = this->averageBrightnessMap[8] / (w25 * h25); // Unlock the bits once done with calculations this->image->UnlockBits(&image_data); } UINT ASCIIFied::get_output_width(VOID) CONST { return this->chars_per_line; } UINT ASCIIFied::get_output_height(VOID) const { return this->char_height; } Section* ASCIIFied::get_section_map(VOID) CONST { return this->sectionMap; } UINT ASCIIFied::get_section_map_size(VOID) CONST { return this->sectionMapSize; } VOID ASCIIFied::generate_image(VOID) { if (this->decoded_art == nullptr) { cerr << "Failed to produce image from art because it's accessing nullptr reference maybe due to failed art generation or art isn't decoded yet.\nTerminating the program." << endl; exit(EXIT_FAILURE); } // In pixels, each letter is 8x12px + 1px for vertical separation + some breathing space (char_height = vertical amount of characters in art, chars_per_line = same but on horizontal axis) INT image_width = this->chars_per_line * 8 + 100; INT image_height = this->char_height * 13 + 100; // Generate bitmap to draw to Bitmap art_output(image_width, image_height); Graphics g(&art_output); // Sets background to black Color color(Color::Black); g.Clear(color); // Creating proper font HFONT hfont = CreateFont(-12, -8, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, OEM_CHARSET, OUT_RASTER_PRECIS, CLIP_DEFAULT_PRECIS, PROOF_QUALITY, DEFAULT_PITCH, L"Terminal"); // Text bounding rectangle RECT rc = { 50, 50, image_width, image_height}; HDC hdc = g.GetHDC(); // Setting text background and foreground color to console colors along side with font SetBkColor(hdc, RGB(0, 0, 0)); SetTextColor(hdc, RGB(210, 210, 210)); // Apply font SelectObject(hdc, hfont); DrawTextA(hdc, this->decoded_art, strlen(this->decoded_art), &rc, DT_LEFT | DT_TOP | DT_WORDBREAK); g.ReleaseHDC(hdc); DeleteObject(hfont); WCHAR path[MAX_PATH]; // Get Desktop path if (SHGetFolderPathW(NULL, CSIDL_DESKTOPDIRECTORY, NULL, 0, path) != S_OK) { cerr << "DESKTOP path not found!\n"; exit(EXIT_FAILURE); } SYSTEMTIME time_s; GetSystemTime(&time_s); wstring day = to_wstring(time_s.wDay); wstring month = to_wstring(time_s.wMonth); wstring year = to_wstring(time_s.wYear); wstring hour = to_wstring(time_s.wHour); wstring minute = to_wstring(time_s.wMinute); wstring second = to_wstring(time_s.wSecond); wstring image_path(path); image_path += L"\\ascii_art_" + day + L"-" + month + L"-" + year + L"-" + hour + L"-" + minute + L"-" + second + L".png"; CLSID encId = { 0x557cf406, 0x1a04, 0x11d3,{ 0x9a, 0x73, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e } }; art_output.Save(image_path.c_str(), &encId); cout << "Image saved to your desktop." << endl; } VOID ASCIIFied::resize_image(UINT width) { FLOAT aspect_ratio = (FLOAT)width / (FLOAT)this->width; // Calculating new dimensions UINT new_width = width; UINT new_height = (UINT)(this->height * aspect_ratio); // Creating scaled image this->scaledImage = new Bitmap(new_width, new_height, this->image->GetPixelFormat()); Graphics g(this->scaledImage); g.SetInterpolationMode(InterpolationModeHighQualityBicubic); g.SetPixelOffsetMode(PixelOffsetModeHalf); g.DrawImage(this->image, 0, 0, new_width, new_height); } INT ASCIIFied::find_closest_divider(INT divisor, INT divider, bool onlyBiggerDivider) { INT dividerS = divider; INT dividerB = divider; if (onlyBiggerDivider) { while (true) { if (divisor % dividerB == 0) { return dividerB; } dividerB++; } } while (true) { if (divisor % dividerB == 0) { return dividerB; } else if (divisor % dividerS == 0) { return dividerS; } dividerB++; dividerS--; } } wstring ASCIIFied::get_image_extension(CONST WCHAR* path) { wstring imagePath(path); INT pos = imagePath.find_last_of(L"."); wstring extension = imagePath.substr(pos + 1); // Conversion to lower case std::transform(extension.begin(), extension.end(), extension.begin(), towlower); return extension; } VOID ASCIIFied::gridify(Bitmap* base) { UINT scaled_width = base->GetWidth(); UINT scaled_height = base->GetHeight(); // Section width and height are expressed in pixels! // Section width is actually the closest natural divider of scaled image width UINT sectionWidth = scaled_width / this->find_closest_divider(scaled_width, this->chars_per_line, false); // Section height is at least 1.6 times its width and must be devisible by height of the image. Latin alphabet characters are always taller than they are wide. // 1.6 Works well for font Terminal 8x12px but other values might suit better for different fonts // Disabled because most of the time the closest full divider of image height is much more than 1.6 times bigger than section width, yielding highly distorted (elongated) ASCII art //UINT sectionHeight = this->find_closest_divider(scaled_height, (INT)round((FLOAT)sectionWidth * 1.6f), true); // Mathematically rounding the result UINT sectionHeight = (INT)round((FLOAT)sectionWidth * 1.6f); // Updates chars_per_line and char_height with values that are actually going to be used. this->chars_per_line = scaled_width / sectionWidth; //this->char_height = scaled_height / sectionHeight; // Celiling the result so that there is enough space for all sections on vertical axis when allocating the memory this->char_height = (UINT)ceilf((FLOAT)(scaled_height / sectionHeight)); // Allocating memory for section map UINT allocation_size = this->chars_per_line * this->char_height; this->sectionMap = new Section[allocation_size]; // Extremely important variable, it will indicate the amount of sections initiated! UINT iterator = 0; // Populating sections with data // Notice the -1, reserving the last row for resedue pixels for (UINT i = 0; i < this->char_height - 1; ++i) { for (UINT j = 0; j < this->chars_per_line; ++j) { // Order of sections is left to right first, from top to bottom INT positionX = j * sectionWidth; INT positionY = i * sectionHeight; this->sectionMap[iterator] = Section(positionX, positionY, sectionWidth, sectionHeight, base); if (this->edge_detection) { this->sectionMap[iterator++].calculate_disected_brightness(); } else { this->sectionMap[iterator++].calculate_average_brightness(); } } } // Last row of sections where Y coordinate is always the same (here precalculated to be used in loop), only X is changing INT positionY = this->char_height * sectionHeight; // The resedue amount of pixels for the last row of sections UINT height = scaled_height % sectionHeight; // If the resedue amount of pixels for the last row of sections is greater than 35% of rest of sections height for the image, take it into consideration // Otherwise ignore the last row of pixels because it's insignificant and small! if (height > sectionHeight * 0.35) { for (UINT i = 0; i < this->chars_per_line; ++i) { INT positionX = i * sectionWidth; this->sectionMap[iterator] = Section(positionX, positionY, sectionWidth, height, base); if (this->edge_detection) { this->sectionMap[iterator++].calculate_disected_brightness(); } else { this->sectionMap[iterator++].calculate_average_brightness(); } } } // !!! this->sectionMapSize = iterator - 1; } VOID ASCIIFied::apply_gamma_briCon_correction(Bitmap* base) { LevelsParams levels_params; BrightnessContrastParams briConParams; // Negative gamma correction (influencing midtones on levels = gamma correction) levels_params.highlight = 100; levels_params.midtone = -15; levels_params.shadow = 0; // Typical contrast boost briConParams.brightnessLevel = 15; briConParams.contrastLevel = 17; Levels levels; levels.SetParameters(&levels_params); BrightnessContrast briCon; briCon.SetParameters(&briConParams); base->ApplyEffect(&levels, NULL); base->ApplyEffect(&briCon, NULL); } FLOAT ASCIIFied::similarity(CONST FLOAT a[], FLOAT b[]) { // Implementation of euclidean distance // https://en.wikipedia.org/wiki/Euclidean_distance FLOAT powSum = 0; FLOAT similarity = 0; for (INT i = 0; i < 9; i++) { powSum += pow((a[i] - b[i]), 2.f); } similarity = sqrt(powSum); return similarity; } CHAR ASCIIFied::brightness_to_char(CONST map<FLOAT, vector<CHAR>>& map, FLOAT brightness) { auto it = min_element(map.begin(), map.end(), [&](CONST auto& p1, CONST auto& p2) { return abs(p1.first - brightness) < abs(p2.first - brightness); }); srand((UINT)time(NULL)); INT randomIndex = rand() % it->second.size(); return it->second[randomIndex]; } CHAR ASCIIFied::brightness_map_to_char(CONST Char map[], FLOAT brightness_map[]) { FLOAT similarity_map[95]; // Contains euclidean distance of each character to the provided brightness map of a single section. // The smallest distance is actually the most similar array on a chart for (INT i = 0; i < 95; i++) { similarity_map[i] = this->similarity(map[i].b, brightness_map); } INT char_index = distance(similarity_map, min_element(similarity_map, similarity_map + 95)); return map[char_index].c; } VOID ASCIIFied::decode_art(VOID) { if (this->decoded_art != nullptr) { cout << "Art is already decoded!" << endl; return; } CONST UINT line_break = this->get_output_width(); UINT iterator = 0; // Memory allocation for ASCII art // Multiplied by 0.2f to add more memory for new line character which isn't included in section map size itself UINT allocationSize = this->sectionMapSize + (UINT)(this->sectionMapSize * 0.2f); this->decoded_art = new CHAR[allocationSize]; memset(decoded_art, 0, allocationSize); if (this->edge_detection) { for (UINT i = 0; i < this->sectionMapSize; ++i) { if (i % line_break == 0) { this->decoded_art[iterator++] = '\n'; } this->decoded_art[iterator++] = this->brightness_map_to_char(luma_char_map_x, this->sectionMap[i].averageBrightnessMap); } } else { for (UINT i = 0; i < this->sectionMapSize; ++i) { if (i % line_break == 0) { this->decoded_art[iterator++] = '\n'; } this->decoded_art[iterator++] = brightness_to_char(luma_char_map, this->sectionMap[i].averageBrightness); } } } VOID ASCIIFied::output_to_console(VOID) { CONSOLE_FONT_INFOEX cfi; cfi.cbSize = sizeof(cfi); cfi.nFont = 0; cfi.dwFontSize.X = 8; cfi.dwFontSize.Y = 12; cfi.FontFamily = FF_DONTCARE; cfi.FontWeight = FW_NORMAL; wcscpy_s(cfi.FaceName, L"Terminal"); HANDLE readHandle = GetStdHandle(STD_OUTPUT_HANDLE); // Setting font of the console to the optimal one SetCurrentConsoleFontEx(readHandle, FALSE, &cfi); CONSOLE_SCREEN_BUFFER_INFOEX info{ 0 }; info.cbSize = sizeof(info); GetConsoleScreenBufferInfoEx(readHandle, &info); info.srWindow.Right = 499; info.srWindow.Bottom = 499; // Setting console character width and height properties so that art isn't cut off by smaller screen buffer for console SetConsoleScreenBufferInfoEx(readHandle, &info); // Decode the art from section map data this->decode_art(); cout << this->decoded_art << endl << endl; }
35.30303
189
0.618956
[ "vector", "transform" ]
019474ff625dd2f27758fcd6476333a7e4614fa6
13,138
cc
C++
content/browser/compositor/buffer_queue_unittest.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/compositor/buffer_queue_unittest.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/compositor/buffer_queue_unittest.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-04T13:34:56.000Z
2020-11-04T07:17:52.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <set> #include "cc/test/test_context_provider.h" #include "cc/test/test_web_graphics_context_3d.h" #include "content/browser/compositor/buffer_queue.h" #include "content/browser/compositor/gpu_surfaceless_browser_compositor_output_surface.h" #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h" #include "content/common/gpu/client/gl_helper.h" #include "gpu/GLES2/gl2extchromium.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/khronos/GLES2/gl2ext.h" using ::testing::_; using ::testing::Expectation; using ::testing::Ne; using ::testing::Return; namespace content { class StubGpuMemoryBufferImpl : public gfx::GpuMemoryBuffer { public: StubGpuMemoryBufferImpl() {} // Overridden from gfx::GpuMemoryBuffer: void* Map() override { return nullptr; } void Unmap() override {} bool IsMapped() const override { return false; } Format GetFormat() const override { return gfx::GpuMemoryBuffer::RGBX_8888; } uint32 GetStride() const override { return 0; } gfx::GpuMemoryBufferHandle GetHandle() const override { return gfx::GpuMemoryBufferHandle(); } ClientBuffer AsClientBuffer() override { return reinterpret_cast<ClientBuffer>(this); } }; class StubBrowserGpuMemoryBufferManager : public BrowserGpuMemoryBufferManager { public: StubBrowserGpuMemoryBufferManager() : BrowserGpuMemoryBufferManager(nullptr, 1) {} scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBufferForScanout( const gfx::Size& size, gfx::GpuMemoryBuffer::Format format, int32 surface_id) override { return make_scoped_ptr<gfx::GpuMemoryBuffer>(new StubGpuMemoryBufferImpl); } }; class MockBufferQueue : public BufferQueue { public: MockBufferQueue(scoped_refptr<cc::ContextProvider> context_provider, BrowserGpuMemoryBufferManager* gpu_memory_buffer_manager, unsigned int internalformat) : BufferQueue(context_provider, internalformat, nullptr, gpu_memory_buffer_manager, 1) {} MOCK_METHOD4(CopyBufferDamage, void(int, int, const gfx::Rect&, const gfx::Rect&)); }; class BufferQueueTest : public ::testing::Test { public: BufferQueueTest() : doublebuffering_(true), first_frame_(true) {} void SetUp() override { scoped_refptr<cc::TestContextProvider> context_provider = cc::TestContextProvider::Create(cc::TestWebGraphicsContext3D::Create()); context_provider->BindToCurrentThread(); gpu_memory_buffer_manager_.reset(new StubBrowserGpuMemoryBufferManager); output_surface_.reset(new MockBufferQueue( context_provider, gpu_memory_buffer_manager_.get(), GL_RGBA)); output_surface_->Initialize(); } unsigned current_surface() { return output_surface_->current_surface_.image; } const std::vector<BufferQueue::AllocatedSurface>& available_surfaces() { return output_surface_->available_surfaces_; } const std::deque<BufferQueue::AllocatedSurface>& in_flight_surfaces() { return output_surface_->in_flight_surfaces_; } const BufferQueue::AllocatedSurface& last_frame() { return output_surface_->in_flight_surfaces_.back(); } const BufferQueue::AllocatedSurface& next_frame() { return output_surface_->available_surfaces_.back(); } const gfx::Size size() { return output_surface_->size_; } int CountBuffers() { int n = available_surfaces().size() + in_flight_surfaces().size(); if (current_surface()) n++; return n; } // Check that each buffer is unique if present. void CheckUnique() { std::set<unsigned> buffers; EXPECT_TRUE(InsertUnique(&buffers, current_surface())); for (size_t i = 0; i < available_surfaces().size(); i++) EXPECT_TRUE(InsertUnique(&buffers, available_surfaces()[i].image)); for (std::deque<BufferQueue::AllocatedSurface>::const_iterator it = in_flight_surfaces().begin(); it != in_flight_surfaces().end(); ++it) EXPECT_TRUE(InsertUnique(&buffers, it->image)); } void SwapBuffers() { output_surface_->SwapBuffers(gfx::Rect(output_surface_->size_)); } void SendDamagedFrame(const gfx::Rect& damage) { // We don't care about the GL-level implementation here, just how it uses // damage rects. output_surface_->BindFramebuffer(); output_surface_->SwapBuffers(damage); if (doublebuffering_ || !first_frame_) output_surface_->PageFlipComplete(); first_frame_ = false; } void SendFullFrame() { SendDamagedFrame(gfx::Rect(output_surface_->size_)); } protected: bool InsertUnique(std::set<unsigned>* set, unsigned value) { if (!value) return true; if (set->find(value) != set->end()) return false; set->insert(value); return true; } scoped_ptr<BrowserGpuMemoryBufferManager> gpu_memory_buffer_manager_; scoped_ptr<MockBufferQueue> output_surface_; bool doublebuffering_; bool first_frame_; }; namespace { const gfx::Size screen_size = gfx::Size(30, 30); const gfx::Rect screen_rect = gfx::Rect(screen_size); const gfx::Rect small_damage = gfx::Rect(gfx::Size(10, 10)); const gfx::Rect large_damage = gfx::Rect(gfx::Size(20, 20)); const gfx::Rect overlapping_damage = gfx::Rect(gfx::Size(5, 20)); class MockedContext : public cc::TestWebGraphicsContext3D { public: MOCK_METHOD2(bindFramebuffer, void(GLenum, GLuint)); MOCK_METHOD2(bindTexture, void(GLenum, GLuint)); MOCK_METHOD2(bindTexImage2DCHROMIUM, void(GLenum, GLint)); MOCK_METHOD4(createImageCHROMIUM, GLuint(ClientBuffer, GLsizei, GLsizei, GLenum)); MOCK_METHOD1(destroyImageCHROMIUM, void(GLuint)); MOCK_METHOD5(framebufferTexture2D, void(GLenum, GLenum, GLenum, GLuint, GLint)); }; scoped_ptr<BufferQueue> CreateOutputSurfaceWithMock( MockedContext** context, BrowserGpuMemoryBufferManager* gpu_memory_buffer_manager) { *context = new MockedContext(); scoped_refptr<cc::TestContextProvider> context_provider = cc::TestContextProvider::Create( scoped_ptr<cc::TestWebGraphicsContext3D>(*context)); context_provider->BindToCurrentThread(); scoped_ptr<BufferQueue> buffer_queue(new BufferQueue( context_provider, GL_RGBA, nullptr, gpu_memory_buffer_manager, 1)); buffer_queue->Initialize(); return buffer_queue.Pass(); } TEST(BufferQueueStandaloneTest, FboInitialization) { MockedContext* context; scoped_ptr<BrowserGpuMemoryBufferManager> gpu_memory_buffer_manager( new StubBrowserGpuMemoryBufferManager); scoped_ptr<BufferQueue> output_surface = CreateOutputSurfaceWithMock(&context, gpu_memory_buffer_manager.get()); EXPECT_CALL(*context, bindFramebuffer(GL_FRAMEBUFFER, Ne(0U))); ON_CALL(*context, framebufferTexture2D(_, _, _, _, _)) .WillByDefault(Return()); output_surface->Reshape(gfx::Size(10, 20), 1.0f); } TEST(BufferQueueStandaloneTest, FboBinding) { MockedContext* context; scoped_ptr<BrowserGpuMemoryBufferManager> gpu_memory_buffer_manager( new StubBrowserGpuMemoryBufferManager); scoped_ptr<BufferQueue> output_surface = CreateOutputSurfaceWithMock(&context, gpu_memory_buffer_manager.get()); EXPECT_CALL(*context, bindTexture(GL_TEXTURE_2D, Ne(0U))); EXPECT_CALL(*context, destroyImageCHROMIUM(1)); Expectation image = EXPECT_CALL(*context, createImageCHROMIUM(_, 0, 0, GL_RGBA)) .WillOnce(Return(1)); Expectation fb = EXPECT_CALL(*context, bindFramebuffer(GL_FRAMEBUFFER, Ne(0U))); Expectation tex = EXPECT_CALL(*context, bindTexture(GL_TEXTURE_2D, Ne(0U))); Expectation bind_tex = EXPECT_CALL(*context, bindTexImage2DCHROMIUM(GL_TEXTURE_2D, 1)) .After(tex, image); EXPECT_CALL( *context, framebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, Ne(0U), _)) .After(fb, bind_tex); output_surface->BindFramebuffer(); } TEST(BufferQueueStandaloneTest, CheckBoundFramebuffer) { scoped_ptr<BrowserGpuMemoryBufferManager> gpu_memory_buffer_manager; scoped_ptr<BufferQueue> output_surface; scoped_refptr<cc::TestContextProvider> context_provider = cc::TestContextProvider::Create(cc::TestWebGraphicsContext3D::Create()); context_provider->BindToCurrentThread(); gpu_memory_buffer_manager.reset(new StubBrowserGpuMemoryBufferManager); scoped_ptr<GLHelper> gl_helper; gl_helper.reset(new GLHelper(context_provider->ContextGL(), context_provider->ContextSupport())); output_surface.reset(new BufferQueue(context_provider, GL_RGBA, gl_helper.get(), gpu_memory_buffer_manager.get(), 1)); output_surface->Initialize(); output_surface->Reshape(screen_size, 1.0f); // Trigger a sub-buffer copy to exercise all paths. output_surface->BindFramebuffer(); output_surface->SwapBuffers(screen_rect); output_surface->PageFlipComplete(); output_surface->BindFramebuffer(); output_surface->SwapBuffers(small_damage); int current_fbo = 0; context_provider->ContextGL()->GetIntegerv(GL_FRAMEBUFFER_BINDING, &current_fbo); EXPECT_EQ(static_cast<int>(output_surface->fbo()), current_fbo); } TEST_F(BufferQueueTest, PartialSwapReuse) { output_surface_->Reshape(screen_size, 1.0f); ASSERT_TRUE(doublebuffering_); EXPECT_CALL(*output_surface_, CopyBufferDamage(_, _, small_damage, screen_rect)).Times(1); EXPECT_CALL(*output_surface_, CopyBufferDamage(_, _, small_damage, small_damage)).Times(1); EXPECT_CALL(*output_surface_, CopyBufferDamage(_, _, large_damage, small_damage)).Times(1); SendFullFrame(); SendDamagedFrame(small_damage); SendDamagedFrame(small_damage); SendDamagedFrame(large_damage); // Verify that the damage has propagated. EXPECT_EQ(next_frame().damage, large_damage); } TEST_F(BufferQueueTest, PartialSwapFullFrame) { output_surface_->Reshape(screen_size, 1.0f); ASSERT_TRUE(doublebuffering_); EXPECT_CALL(*output_surface_, CopyBufferDamage(_, _, small_damage, screen_rect)).Times(1); SendFullFrame(); SendDamagedFrame(small_damage); SendFullFrame(); SendFullFrame(); EXPECT_EQ(next_frame().damage, screen_rect); } TEST_F(BufferQueueTest, PartialSwapOverlapping) { output_surface_->Reshape(screen_size, 1.0f); ASSERT_TRUE(doublebuffering_); EXPECT_CALL(*output_surface_, CopyBufferDamage(_, _, small_damage, screen_rect)).Times(1); EXPECT_CALL(*output_surface_, CopyBufferDamage(_, _, overlapping_damage, small_damage)) .Times(1); SendFullFrame(); SendDamagedFrame(small_damage); SendDamagedFrame(overlapping_damage); EXPECT_EQ(next_frame().damage, overlapping_damage); } TEST_F(BufferQueueTest, MultipleBindCalls) { // Check that multiple bind calls do not create or change surfaces. output_surface_->BindFramebuffer(); EXPECT_EQ(1, CountBuffers()); unsigned int fb = current_surface(); output_surface_->BindFramebuffer(); EXPECT_EQ(1, CountBuffers()); EXPECT_EQ(fb, current_surface()); } TEST_F(BufferQueueTest, CheckDoubleBuffering) { // Check buffer flow through double buffering path. EXPECT_EQ(0, CountBuffers()); output_surface_->BindFramebuffer(); EXPECT_EQ(1, CountBuffers()); EXPECT_NE(0U, current_surface()); SwapBuffers(); EXPECT_EQ(1U, in_flight_surfaces().size()); output_surface_->PageFlipComplete(); EXPECT_EQ(1U, in_flight_surfaces().size()); output_surface_->BindFramebuffer(); EXPECT_EQ(2, CountBuffers()); CheckUnique(); EXPECT_NE(0U, current_surface()); EXPECT_EQ(1U, in_flight_surfaces().size()); SwapBuffers(); CheckUnique(); EXPECT_EQ(2U, in_flight_surfaces().size()); output_surface_->PageFlipComplete(); CheckUnique(); EXPECT_EQ(1U, in_flight_surfaces().size()); EXPECT_EQ(1U, available_surfaces().size()); output_surface_->BindFramebuffer(); EXPECT_EQ(2, CountBuffers()); CheckUnique(); EXPECT_TRUE(available_surfaces().empty()); } TEST_F(BufferQueueTest, CheckTripleBuffering) { // Check buffer flow through triple buffering path. // This bit is the same sequence tested in the doublebuffering case. output_surface_->BindFramebuffer(); SwapBuffers(); output_surface_->PageFlipComplete(); output_surface_->BindFramebuffer(); SwapBuffers(); EXPECT_EQ(2, CountBuffers()); CheckUnique(); EXPECT_EQ(2U, in_flight_surfaces().size()); output_surface_->BindFramebuffer(); EXPECT_EQ(3, CountBuffers()); CheckUnique(); EXPECT_NE(0U, current_surface()); EXPECT_EQ(2U, in_flight_surfaces().size()); output_surface_->PageFlipComplete(); EXPECT_EQ(3, CountBuffers()); CheckUnique(); EXPECT_NE(0U, current_surface()); EXPECT_EQ(1U, in_flight_surfaces().size()); EXPECT_EQ(1U, available_surfaces().size()); } } // namespace } // namespace content
35.994521
89
0.729335
[ "vector" ]
019745be21888bf00aa8ba120e35ef039b196610
1,185
cpp
C++
ProjectEuler/euler046.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
ProjectEuler/euler046.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
ProjectEuler/euler046.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <cstring> using namespace std; vector<int> primes; const int MAXN = 500001; //returns the amount of possible conjectures for 'n' int checkConjecture(int n) { int current, conjectureCount = 0; for(auto p : primes) { if(p >= n) break; for(int base=1; ; base++) { current = p + 2 * base * base; if(current > n) break; if(current == n) { conjectureCount++; break; } } } return conjectureCount; } int main() { //set primes vector with sieve method bool prime[MAXN]; memset(prime, true, sizeof(prime)); for(int p=2; p*p<MAXN; p++) if(prime[p]) for(int i=p*p; i<MAXN; i+=p) prime[i] = false; for(int p=2; p<MAXN; p++) if(prime[p]) primes.push_back(p); int t, n; cin >> t; while(t--) { cin >> n; cout << checkConjecture(n) << endl; } return 0; } //https://www.hackerrank.com/contests/projecteuler/challenges/euler046/problem
21.545455
78
0.525738
[ "vector" ]
01a39aef49c2b50d743d4be66120dbba26786898
15,299
cpp
C++
sources/Video/RenderSystem/Shader/ShaderManager.cpp
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
13
2017-03-21T22:46:18.000Z
2020-07-30T01:31:57.000Z
sources/Video/RenderSystem/Shader/ShaderManager.cpp
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
null
null
null
sources/Video/RenderSystem/Shader/ShaderManager.cpp
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
2
2018-07-23T19:56:41.000Z
2020-07-30T01:32:01.000Z
/* * Shader manager file * * This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "Video/RenderSystem/Shader/ShaderManager.h" #include "Video/RenderSystem/RenderSystem.h" #include "Video/RenderSystem/Shader/ShaderCompilationException.h" #include "Core/Exception/InvalidArgumentException.h" namespace Fork { namespace Video { /* * Internal functions */ static void ResolveTargetVersion(Shader::Versions& targetVersion) { if (targetVersion == Shader::Versions::__Unspecified__) targetVersion = RenderContext::Active()->HighestShaderModel(); } static std::vector<std::string> DefaultEntryPoints(const char* functionName, size_t num) { switch (num) { case 2: return { "VertexMain", "PixelMain" }; case 3: return { "VertexMain", "Geometry", "PixelMain" }; case 4: return { "VertexMain", "HullMain", "DomainMain", "PixelMain" }; case 5: return { "VertexMain", "HullMain", "DomainMain", "Geometry", "PixelMain" }; default: throw InvalidArgumentException(functionName, "entryPoints", "Invalid number of entry points to detect type of shader composition"); } return {}; } static void LoadShaderFile( Shader* shader, const std::string& filename, const std::string& entryPoint, const Shader::Versions targetVersion) { shader->sourceCode->LoadFromFile(filename, entryPoint, shader->Type(), RenderContext::Active()->ShadingLanguage()); shader->entryPoint = entryPoint; shader->targetVersion = targetVersion; } static void CreateShader( Shader* shader, const std::string& sources, const std::string& entryPoint, const Shader::Versions targetVersion) { shader->sourceCode->Append(sources); shader->targetVersion = targetVersion; shader->entryPoint = entryPoint; } /* * ShaderManager class */ ShaderCompositionPtr ShaderManager::CreateShaderCompositionFromFiles( const std::vector<std::string>& filenames, const std::vector<std::string>& entryPoints, const VertexFormat& vertexFormat, Shader::Versions targetVersion) { if (filenames.size() != entryPoints.size()) throw InvalidArgumentException(__FUNCTION__, "entryPoints", "Number of filenames and entry points must be equal"); ResolveTargetVersion(targetVersion); /* Get active render system */ auto renderSystem = RenderSystem::Active(true); /* Create shader composition */ auto shaderComposition = renderSystem->CreateShaderComposition(); /* Create the shaders, load them from file and attach them to the shader composition */ const auto num = filenames.size(); ShaderFilenamesType shaderFilenames; switch (num) { case 2: { auto vertexShader = renderSystem->CreateVertexShader (); auto pixelShader = renderSystem->CreatePixelShader (); LoadShaderFile( vertexShader.get(), shaderFilenames.vertex = filenames[0], entryPoints[0], targetVersion ); LoadShaderFile( pixelShader.get(), shaderFilenames.pixel = filenames[1], entryPoints[1], targetVersion ); shaderComposition->AttachShader(vertexShader, pixelShader); } break; case 3: { auto vertexShader = renderSystem->CreateVertexShader (); auto geometryShader = renderSystem->CreateGeometryShader(); auto pixelShader = renderSystem->CreatePixelShader (); LoadShaderFile( vertexShader.get(), shaderFilenames.vertex = filenames[0], entryPoints[0], targetVersion); LoadShaderFile( geometryShader.get(), shaderFilenames.geometry = filenames[1], entryPoints[1], targetVersion); LoadShaderFile( pixelShader.get(), shaderFilenames.pixel = filenames[2], entryPoints[2], targetVersion); shaderComposition->AttachShader(vertexShader, geometryShader, pixelShader); } break; case 4: { auto vertexShader = renderSystem->CreateVertexShader (); auto tessControlShader = renderSystem->CreateTessControlShader (); auto tessEvaluationShader = renderSystem->CreateTessEvaluationShader (); auto pixelShader = renderSystem->CreatePixelShader (); LoadShaderFile( vertexShader.get(), shaderFilenames.vertex = filenames[0], entryPoints[0], targetVersion); LoadShaderFile( tessControlShader.get(), shaderFilenames.tessControl = filenames[1], entryPoints[1], targetVersion); LoadShaderFile( tessEvaluationShader.get(), shaderFilenames.tessEvaluation = filenames[2], entryPoints[2], targetVersion); LoadShaderFile( pixelShader.get(), shaderFilenames.pixel = filenames[3], entryPoints[3], targetVersion); shaderComposition->AttachShader( vertexShader, tessControlShader, tessEvaluationShader, pixelShader ); } break; case 5: { auto vertexShader = renderSystem->CreateVertexShader (); auto tessControlShader = renderSystem->CreateTessControlShader (); auto tessEvaluationShader = renderSystem->CreateTessEvaluationShader (); auto geometryShader = renderSystem->CreateGeometryShader (); auto pixelShader = renderSystem->CreatePixelShader (); LoadShaderFile( vertexShader.get(), shaderFilenames.vertex = filenames[0], entryPoints[0], targetVersion); LoadShaderFile( tessControlShader.get(), shaderFilenames.tessControl = filenames[1], entryPoints[1], targetVersion); LoadShaderFile( tessEvaluationShader.get(), shaderFilenames.tessEvaluation = filenames[2], entryPoints[2], targetVersion); LoadShaderFile( geometryShader.get(), shaderFilenames.geometry = filenames[3], entryPoints[3], targetVersion); LoadShaderFile( pixelShader.get(), shaderFilenames.pixel = filenames[4], entryPoints[4], targetVersion); shaderComposition->AttachShader( vertexShader, tessControlShader, tessEvaluationShader, geometryShader, pixelShader ); } break; default: throw InvalidArgumentException(__FUNCTION__, "filenames", "Invalid number of filenames to detect type of shader composition"); } /* Setup vertex format and compile the shader composition */ shaderComposition->SetupVertexFormat(vertexFormat); //shaderComposition->Compile(flags); shaderCompositionFilesMap_[shaderComposition.get()] = shaderFilenames; return AddShaderComposition(shaderComposition); } ShaderCompositionPtr ShaderManager::CreateShaderCompositionFromFiles( const std::vector<std::string>& filenames, const VertexFormat& vertexFormat, Shader::Versions targetVersion) { return CreateShaderCompositionFromFiles( filenames, DefaultEntryPoints(__FUNCTION__, filenames.size()), vertexFormat, targetVersion ); } ShaderCompositionPtr ShaderManager::CreateShaderComposition( const std::vector<std::string>& sources, const std::vector<std::string>& entryPoints, const VertexFormat& vertexFormat, Shader::Versions targetVersion) { ResolveTargetVersion(targetVersion); /* Get active render system */ auto renderSystem = RenderSystem::Active(true); /* Create shader composition */ auto shaderComposition = renderSystem->CreateShaderComposition(); /* Create the shaders, and attach them to the shader composition */ const auto num = sources.size(); switch (num) { case 2: { auto vertexShader = renderSystem->CreateVertexShader (); auto pixelShader = renderSystem->CreatePixelShader (); CreateShader( vertexShader.get(), sources[0], entryPoints[0], targetVersion ); CreateShader( pixelShader.get(), sources[1], entryPoints[1], targetVersion ); shaderComposition->AttachShader(vertexShader, pixelShader); } break; case 3: { auto vertexShader = renderSystem->CreateVertexShader (); auto geometryShader = renderSystem->CreateGeometryShader(); auto pixelShader = renderSystem->CreatePixelShader (); CreateShader( vertexShader.get(), sources[0], entryPoints[0], targetVersion ); CreateShader( geometryShader.get(), sources[1], entryPoints[1], targetVersion ); CreateShader( pixelShader.get(), sources[2], entryPoints[2], targetVersion ); shaderComposition->AttachShader(vertexShader, geometryShader, pixelShader); } break; case 4: { auto vertexShader = renderSystem->CreateVertexShader (); auto tessControlShader = renderSystem->CreateTessControlShader (); auto tessEvaluationShader = renderSystem->CreateTessEvaluationShader (); auto pixelShader = renderSystem->CreatePixelShader (); CreateShader( vertexShader.get(), sources[0], entryPoints[0], targetVersion ); CreateShader( tessControlShader.get(), sources[1], entryPoints[1], targetVersion ); CreateShader( tessEvaluationShader.get(), sources[2], entryPoints[2], targetVersion ); CreateShader( pixelShader.get(), sources[3], entryPoints[3], targetVersion ); shaderComposition->AttachShader( vertexShader, tessControlShader, tessEvaluationShader, pixelShader ); } break; case 5: { auto vertexShader = renderSystem->CreateVertexShader (); auto tessControlShader = renderSystem->CreateTessControlShader (); auto tessEvaluationShader = renderSystem->CreateTessEvaluationShader (); auto geometryShader = renderSystem->CreateGeometryShader (); auto pixelShader = renderSystem->CreatePixelShader (); CreateShader( vertexShader.get(), sources[0], entryPoints[0], targetVersion ); CreateShader( tessControlShader.get(), sources[1], entryPoints[1], targetVersion ); CreateShader( tessEvaluationShader.get(), sources[2], entryPoints[2], targetVersion ); CreateShader( geometryShader.get(), sources[3], entryPoints[3], targetVersion ); CreateShader( pixelShader.get(), sources[4], entryPoints[4], targetVersion ); shaderComposition->AttachShader( vertexShader, tessControlShader, tessEvaluationShader, geometryShader, pixelShader ); } break; default: throw InvalidArgumentException(__FUNCTION__, "sources", "Invalid number of sources to detect type of shader composition"); } /* Setup vertex format and compile the shader composition */ shaderComposition->SetupVertexFormat(vertexFormat); //shaderComposition->Compile(flags); return AddShaderComposition(shaderComposition); } ShaderCompositionPtr ShaderManager::CreateShaderComposition( const std::vector<std::string>& sources, const VertexFormat& vertexFormat, Shader::Versions targetVersion) { return CreateShaderComposition( sources, DefaultEntryPoints(__FUNCTION__, sources.size()), vertexFormat, targetVersion ); } ShaderCompositionPtr ShaderManager::LoadShaderComposition( const std::vector<std::string>& filenames, const std::vector<std::string>& entryPoints, const VertexFormat& vertexFormat, Shader::Versions targetVersion, const Shader::CompilationFlags::DataType flags) { //!TODO! -> make use of pre-loaded shader compositions! auto shaderComposition = CreateShaderCompositionFromFiles( filenames, entryPoints, vertexFormat, targetVersion ); if (!shaderComposition->Compile(flags)) throw ShaderCompilationException(ExtractFileName(filenames[0])); return shaderComposition; } ShaderCompositionPtr ShaderManager::LoadShaderComposition( const std::vector<std::string>& filenames, const VertexFormat& vertexFormat, Shader::Versions targetVersion, const Shader::CompilationFlags::DataType flags) { return LoadShaderComposition( filenames, DefaultEntryPoints(__FUNCTION__, filenames.size()), vertexFormat, targetVersion, flags ); } void ShaderManager::ReleaseShaderComposition(const ShaderComposition* shaderComposition) { /* Remove shader composition from hash map */ //loadedShaderCompositions_.Remove(shaderComposition); /* Remove shader composition from list */ for (auto it = shaderCompositions_.begin(); it != shaderCompositions_.end(); ++it) { if (it->get() == shaderComposition) { shaderCompositions_.erase(it); break; } } } void ShaderManager::ReleaseAllShaderCompositions() { //loadedShaderCompositions_.hashMap.clear(); shaderCompositions_.clear(); } bool ShaderManager::ReloadShaderComposition(ShaderComposition* shaderComposition) { /* Find shader filenames in map */ auto it = shaderCompositionFilesMap_.find(shaderComposition); if (it == shaderCompositionFilesMap_.end()) return false; /* Reload shader code from files */ auto ReloadShaderCode = [](Shader* shader, const std::string& filename) { if (shader && shader->sourceCode && !filename.empty()) shader->sourceCode->LoadFromFile(filename); }; const auto& filenames = it->second; ReloadShaderCode( shaderComposition->GetVertexShader ().get(), filenames.vertex ); ReloadShaderCode( shaderComposition->GetPixelShader ().get(), filenames.pixel ); ReloadShaderCode( shaderComposition->GetGeometryShader ().get(), filenames.geometry ); ReloadShaderCode( shaderComposition->GetTessControlShader ().get(), filenames.tessControl ); ReloadShaderCode( shaderComposition->GetTessEvaluationShader().get(), filenames.tessEvaluation ); ReloadShaderCode( shaderComposition->GetComputeShader ().get(), filenames.compute ); /* Temporarily store and then detach all constant buffers */ const auto constBuffers = shaderComposition->GetConstantBuffers(); shaderComposition->DetachAllConstantBuffers(); /* Recompile shader composition */ if (!shaderComposition->Compile()) return false; /* Re-attach all constant buffers */ for (const auto& cbuffer : constBuffers) shaderComposition->Attach(cbuffer); return true; } /* * ======= Private: ======= */ ShaderCompositionPtr ShaderManager::AddShaderComposition(const ShaderCompositionPtr& shaderComposition) { shaderCompositions_.push_back(shaderComposition); return shaderComposition; } } // /namespace Video } // /namespace Fork // ========================
38.536524
143
0.665272
[ "geometry", "render", "vector" ]
01b555c92509fc5cf90ea1d8a283f4716965d90f
8,398
cpp
C++
src/qlearn/qlearn.cpp
c00k133/q-learning-project
08e0a5dabea09a6a8494ebb056fe3ed25d1abd7e
[ "MIT" ]
null
null
null
src/qlearn/qlearn.cpp
c00k133/q-learning-project
08e0a5dabea09a6a8494ebb056fe3ed25d1abd7e
[ "MIT" ]
null
null
null
src/qlearn/qlearn.cpp
c00k133/q-learning-project
08e0a5dabea09a6a8494ebb056fe3ed25d1abd7e
[ "MIT" ]
null
null
null
#include "qlearn.hpp" void QLearn::init() { sf::VideoMode video_mode(window_width, window_height); window = std::make_shared<sf::RenderWindow>(video_mode, heading); window->setFramerateLimit(framerate_limit); // Set companion object drawer = std::unique_ptr<SFMLDrawer>(new SFMLDrawer(window)); drawer->setScale(scale); // Set master worm, used for centering camera. worms.push_back(std::shared_ptr<WormBrain>(createWormBrain(20, 4, "Master"))); view = sf::View( sf::Vector2f(0, 0), sf::Vector2f(window_width, window_height)); } QLearn::QLearn( std::string heading, unsigned int window_width, unsigned int window_height) : heading(heading), window_width(window_width), window_height(window_height) { init(); } QLearn::QLearn(unsigned int amount, int precision, unsigned int bone_amount, std::string heading, unsigned int window_width, unsigned int window_height) : heading(heading), window_width(window_width), window_height(window_height) { init(); // Create extra worms QLearnUtils::WormType worm_type = { precision, bone_amount, QLEARN_DEFAULT_WORM_COLOR, WORMBRAIN_DEFAULT_NAME }; insertToWorms(amount, worm_type); } inline WormBrain* QLearn::createWormBrain( int precision, unsigned int bone_amount, std::string name) const { return new WormBrain( engine.getWorld(), precision, bone_amount, WORMBRAIN_DEFAULT_MAX_ERROR, name); } WormBrain* QLearn::createWormType( const QLearnUtils::WormType& worm_type) const { WormBrain* worm = createWormBrain( worm_type.precision, worm_type.bone_amount, worm_type.name); worm->setBodyColor(worm_type.color); return worm; } inline std::shared_ptr<WormBrain> QLearn::getMasterWorm() const { return worms[master_worm_index]; } void QLearn::insertToWorms( unsigned int amount, QLearnUtils::WormType worm_type) { std::string original_name = worm_type.name; for (unsigned int i = 0; i < amount; ++i) { worm_type.name = original_name + std::to_string(i + 1); WormBrain* worm = createWormType(worm_type); worms.push_back(std::shared_ptr<WormBrain>(worm)); } } inline float QLearn::scaleValue(float value) const { return value * scale; } void QLearn::printHelp() const { std::ifstream file_stream(help_file_path); if (file_stream.rdstate() & (file_stream.failbit | file_stream.badbit)) { std::cerr << "Failed to load help file!" << std::endl; } else { while (!file_stream.eof()) { std::string line; std::getline(file_stream, line); std::cout << line << std::endl; } } } void QLearn::keyPressEventHandler(sf::Keyboard::Key key_press) { switch (key_press) { case sf::Keyboard::Right: case sf::Keyboard::Left: if (follow_master) { follow_master = false; const float current_master_x = getMasterWorm()->getBodyCoordinatesVector().x; camera_offset = scaleValue(current_master_x); } camera_offset += key_press == sf::Keyboard::Right ? QLEARN_CAMERA_OFFSET_INCREMENT : -QLEARN_CAMERA_OFFSET_INCREMENT; break; case sf::Keyboard::Add: case sf::Keyboard::Subtract: { const float increment = 1.f + (key_press == sf::Keyboard::Add ? -QLEARN_CAMERA_ZOOM_INCREMENT : QLEARN_CAMERA_ZOOM_INCREMENT); view.zoom(increment); zoom_value *= increment; break; } case sf::Keyboard::Space: // Fix camera to original values camera_offset = 0.f; follow_master = true; // Reset the zoom value of the view view.zoom(1.f / zoom_value); zoom_value = 1.f; // Reset engine time step engine.resetTimeStep(); // Reset master worm variables getMasterWorm()->getBody()->resetMaxMotorTorque(); getMasterWorm()->getBody()->resetMotorSpeed(); getMasterWorm()->resetQLearningMoveReward(); break; case sf::Keyboard::Escape: window->close(); break; case sf::Keyboard::H: printHelp(); break; case sf::Keyboard::M: case sf::Keyboard::N: if (key_press == sf::Keyboard::M) master_worm_index = (master_worm_index + 1) % (unsigned int) worms.size(); else master_worm_index = master_worm_index - 1 < 0 ? static_cast<int>(worms.size()) - 1 : master_worm_index - 1; break; case sf::Keyboard::R: { const bool random_act = getMasterWorm()->getRandomAct(); // Invert randomness of master worm getMasterWorm()->setRandomActs(!random_act); break; } case sf::Keyboard::P: run_physics = !run_physics; break; case sf::Keyboard::A: case sf::Keyboard::S: { const float32 change = key_press == sf::Keyboard::A ? -1.f : 1.f; engine.alterTimeStep(change); break; } case sf::Keyboard::Q: { const bool original_run_physics = run_physics; run_physics = true; for (unsigned int i = 0; i < 1000; ++i) { advanceWorld(); } run_physics = original_run_physics; break; } case sf::Keyboard::Z: case sf::Keyboard::X: { const float change = key_press == sf::Keyboard::Z ? 1000.f : -1000.f; getMasterWorm()->getBody()->alterMaxMotorTorque(change); break; } case sf::Keyboard::C: case sf::Keyboard::V: { const float change = key_press == sf::Keyboard::C ? -0.1f : 0.1f; getMasterWorm()->getBody()->alterMotorSpeed(change); break; } case sf::Keyboard::W: case sf::Keyboard::E: { const float change = key_press == sf::Keyboard::W ? 0.05f : -0.05f; getMasterWorm()->alterQLearningMoveReward(change); break; } default: break; } } void QLearn::eventHandler() { sf::Event event; while (window->pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window->close(); break; case sf::Event::KeyPressed: keyPressEventHandler(event.key.code); break; default: break; } } } void QLearn::processWorms() { // One process might take longer than others depending on precision for (auto worm = worms.begin(); worm < worms.end(); ++worm) { (*worm)->process(); } // NOTE: we attempted to use parallelism here through openmp, but // unfortunately it introduced valgrind errors "possibly lost". // This might have been a false positive, but we are staying on the // on the safe side and ignoring parallelism for now. } void QLearn::drawComponents() { // Drawing of worms happen sequentially, drawing in parallel breaks SFML for (const auto& worm : worms) { drawer->drawWorm(*worm); } // Draw the ground based on PhysicsEngine const b2Vec2 ground_dimensions = engine.getGroundDimensions(); drawer->drawGround( engine.getGround(), ground_dimensions, ground_color); // Draw ticks on ground drawer->drawTicks(ground_dimensions.x); // Draw information about the current master worm // TODO(Cookie): find a better way to calculate these const float x_dimension = view.getSize().x / 2 - 3 * scale; const float y_dimension = view.getSize().y / 2 - 53 * scale; auto information_position = view.getCenter() - sf::Vector2f(x_dimension, y_dimension); drawer->drawWormInformation(*getMasterWorm(), information_position); } void QLearn::setViewCenter() { float x_view; if (follow_master) { auto master_coordinates = getMasterWorm()->getBodyCoordinatesVector(); x_view = scaleValue(master_coordinates.x); } else { x_view = camera_offset; } float y_view = scaleValue(window_y_offset); view.setCenter(x_view, y_view); } inline void QLearn::advanceWorld() { if (run_physics) { engine.step(); processWorms(); } } void QLearn::run() { printHelp(); while (window->isOpen()) { // Fix view according to the master worm setViewCenter(); window->setView(view); window->clear(clear_color); // Advance forward in the world: step the PhysicsEngine and process worms advanceWorld(); // Check all events that might have happened eventHandler(); // Draw all components on window drawComponents(); window->display(); } }
27.993333
80
0.644201
[ "object" ]
01b7a8a913913a179d960b0b5fcc177d8cc2b4ea
42,700
cxx
C++
src/McGetEventInfoTool.cxx
fermi-lat/McToolBox
71bb9437abdc3bd5e3ace44e80342f62b36d90e9
[ "BSD-3-Clause" ]
null
null
null
src/McGetEventInfoTool.cxx
fermi-lat/McToolBox
71bb9437abdc3bd5e3ace44e80342f62b36d90e9
[ "BSD-3-Clause" ]
null
null
null
src/McGetEventInfoTool.cxx
fermi-lat/McToolBox
71bb9437abdc3bd5e3ace44e80342f62b36d90e9
[ "BSD-3-Clause" ]
null
null
null
/** * @class McGetEventInfoTool * * @brief A Gaudi tool for extracting information from the McParticle - McPositionHit - * TkrCluster - etc. relational tables. The primary aim is to aid in studies of * track reconstruction performance, particular pattern recognition. * * NOTE: The interface for this Gaudi tool is defined * in GlastSvc/MonteCarlo/IMcGetEventInfoTool * * This version under construction!! 2/19/2004 * * Created 1-Feb-2004 * * @author Tracy Usher * * $Header: /nfs/slac/g/glast/ground/cvs/McToolBox/src/McGetEventInfoTool.cxx,v 1.3 2004/12/16 05:16:06 usher Exp $ */ #include "GlastSvc/MonteCarlo/IMcGetEventInfoTool.h" #include "GaudiKernel/ToolFactory.h" #include "GaudiKernel/SmartDataPtr.h" #include "GaudiKernel/GaudiException.h" #include "GaudiKernel/IParticlePropertySvc.h" #include "GaudiKernel/IDataProviderSvc.h" #include "GaudiKernel/ParticleProperty.h" #include "GaudiKernel/AlgTool.h" #include "Event/TopLevel/EventModel.h" #include "Event/TopLevel/MCEvent.h" #include "Event/MonteCarlo/McEventStructure.h" #include "Event/Recon/TkrRecon/TkrCluster.h" class McGetEventInfoTool : public AlgTool, virtual public IMcGetEventInfoTool { public: /// Standard Gaudi Tool interface constructor McGetEventInfoTool(const std::string& type, const std::string& name, const IInterface* parent); virtual ~McGetEventInfoTool() {} /// @brief Intialization of the tool StatusCode initialize(); /// @brief Following methods return information on type of event and particles /// @brief Also available directly from the TDS const Event::McEventStructure* getMcEventStructure(); /// @brief Returns the number of Monte Carlo tracks in the tracker int getNumMcTracks(); /// @brief Return a vector of McParticles which have hits in the tracker const Event::McParticleRefVec getMcTrackVector(); /// @brief Returns information about the event const unsigned long getClassificationBits(); /// @brief Returns primary McParticle const Event::McParticleRef getPrimaryParticle(); /// @brief Returns secondary particles int getNumSecondaries(); const Event::McParticleRef getSecondary(int mcPartIdx); /// @brief Returns associated particles int getNumAssociated(); const Event::McParticleRef getAssociated(int mcPartIdx); /// @brief Returns a vector of hits associated as one McParticle track const Event::McPartToClusPosHitVec getMcPartTrack(const Event::McParticleRef mcPart); /// @brief Returns the layer number of a given McPositionHit on the track const int getTrackHitLayer(const Event::McParticleRef mcPart, int hitIdx); /// @brief Following methods return information about specific tracks /// @brief Returns number of Tracker (cluster) hits for a given track const int getNumClusterHits(const Event::McParticleRef mcPart); /// @brief Returns number of shared Tracker (cluster) hits for a given track const int getNumSharedTrackHits(const Event::McParticleRef mcPart); /// @brief Compares two tracks and returns information on shared hits (if any) const int getNumGaps(const Event::McParticleRef mcPart); const int getGapSize(const Event::McParticleRef mcPart, int gapIdx); const int getGapStartHitNo(const Event::McParticleRef mcPart, int gapIdx); /// @brief Returns the "straightness" of a given track const double getTrackStraightness(const Event::McParticleRef mcPart, int firstHitIdx=0, int lastHitIdx=40); /// @brief Returns the "direction" defined by the first set of hits on a track const CLHEP::Hep3Vector getTrackDirection(const Event::McParticleRef mcPart, int firstHitIdx=0, int lastHitIdx=40); /// @brief Returns track energy loss information (in the tracker only) const double getTrackTotEneLoss(const Event::McParticleRef mcPart); const double getTrackELastHit(const Event::McParticleRef mcPart); const double getTrackBremELoss(const Event::McParticleRef mcPart, int& nTotRad); const double getTrackDeltaELoss(const Event::McParticleRef mcPart, int& nTotDlta, int& nHitDlta); const int getTrackDeltaRange(const Event::McParticleRef mcPart, double& aveRange, double& maxRange); /// @brief Compares two tracks and returns information on shared hits (if any) const unsigned int getSharedHitInfo(const Event::McParticleRef mcPart); const unsigned int getSharedHitInfo(const Event::McParticleRef mcPart1, const Event::McParticleRef mcPart2); /// @brief Calculate position info from McPositionHits related to a given cluster const HepPoint3D getPosition(const Event::TkrCluster* cluster); const HepPoint3D getPosition(const Event::McPositionHit* mcPosHit); private: /// Method for updating data const bool updateData(); /// Pointer to the service which keeps track of the particle properties (most useful) IParticlePropertySvc* m_ppsvc; /// Event Service member directly useable by concrete classes. IDataProviderSvc* m_dataSvc; /// Event number to key on loading new tables TimeStamp m_time; // Will use this when conversion to it complete int m_lastEventNo; // backup for now /// Pointers to the Monte Carlo information for a single event Event::McEventStructure* m_mcEvent; Event::ClusMcPosHitTab* m_clusHitTab; Event::McPartToClusTab* m_partClusTab; Event::McPartToClusPosHitTab* m_partHitTab; /// Null particle reference Event::McParticle m_nullParticle; }; //static ToolFactory<McGetEventInfoTool> s_factory; //const IToolFactory& McGetEventInfoToolFactory = s_factory; DECLARE_TOOL_FACTORY(McGetEventInfoTool); // // Class constructor, no initialization here // McGetEventInfoTool::McGetEventInfoTool(const std::string& type, const std::string& name, const IInterface* parent) : AlgTool(type, name, parent), m_time(0), m_lastEventNo(-1), m_nullParticle() { //Declare additional interface declareInterface<IMcGetEventInfoTool>(this); m_mcEvent = 0; m_clusHitTab = 0; m_partClusTab = 0; m_partHitTab = 0; return; } // // Initialization of the tool here // StatusCode McGetEventInfoTool::initialize() { AlgTool::initialize(); StatusCode sc = StatusCode::SUCCESS; if( (sc = service("ParticlePropertySvc", m_ppsvc)).isFailure() ) { throw GaudiException("Service [ParticlePropertySvc] not found", name(), sc); } if( (sc = service("EventDataSvc", m_dataSvc)).isFailure() ) { throw GaudiException("Service [EventDataSvc] not found", name(), sc); } return sc; } const bool McGetEventInfoTool::updateData() { // Assume success bool loaded = true; // Retrieve the pointer to the McEventStructure SmartDataPtr<Event::MCEvent> mcEvent(m_dataSvc,EventModel::MC::Event); if (mcEvent.ptr()) { if (mcEvent->time() != m_time || mcEvent->getSequence() != m_lastEventNo) { m_time = mcEvent->time(); m_lastEventNo = mcEvent->getSequence(); // Retrieve the pointer to the McEventStructure m_mcEvent = SmartDataPtr<Event::McEventStructure>(m_dataSvc,EventModel::MC::McEventStructure); // Clean up the last table (if one) if (m_partHitTab) delete m_partHitTab; if (m_partClusTab) delete m_partClusTab; if (m_clusHitTab) delete m_clusHitTab; // Retrieve the TkrCluster <-> McPositionHit table SmartDataPtr<Event::ClusMcPosHitTabList> clusTable(m_dataSvc,EventModel::Digi::TkrClusterHitTab); m_clusHitTab = new Event::ClusMcPosHitTab(clusTable); // Retrieve the McParticle <-> TkrCluster table SmartDataPtr<Event::McPartToClusTabList> hitTable(m_dataSvc,EventModel::MC::McPartToClusTab); m_partClusTab = new Event::McPartToClusTab(hitTable); // Retrieve the McParticle to hit relational table SmartDataPtr<Event::McPartToClusPosHitTabList> partTable(m_dataSvc,EventModel::MC::McPartToClusHitTab); m_partHitTab = new Event::McPartToClusPosHitTab(partTable); } } else { m_time = TimeStamp(0); loaded = false; } return loaded; } // // Define a small class which can be used by the std::sort algorithm // class CompareTrackHits { public: bool operator()(Event::McPartToClusPosHitRel *left, Event::McPartToClusPosHitRel *right) { bool leftTest = false; // Extract the TkrCluster <-> McPositionHit relation const Event::ClusMcPosHitRel* mcHitLeft = left->getSecond(); const Event::ClusMcPosHitRel* mcHitRight = right->getSecond(); // Extract the McPositionHit embedded in this relation const Event::McPositionHit* mcPosHitLeft = mcHitLeft->getSecond(); const Event::McPositionHit* mcPosHitRight = mcHitRight->getSecond(); // If McPositionHits found, sort is by the particle's time of flight if (mcPosHitLeft && mcPosHitRight) { leftTest = mcPosHitLeft->timeOfFlight() < mcPosHitRight->timeOfFlight(); } return leftTest; } private: }; // // Return pointer to the McEventStructure // const Event::McEventStructure* McGetEventInfoTool::getMcEventStructure() { Event::McEventStructure* mcEvent = 0; if (updateData()) mcEvent = m_mcEvent; return mcEvent; } const Event::McParticleRefVec McGetEventInfoTool::getMcTrackVector() { Event::McParticleRefVec hitVec; hitVec.clear(); if (updateData()) { hitVec = m_mcEvent->getTrackVector(); } return hitVec; } // // How many Monte Carlo tracks in the event? // int McGetEventInfoTool::getNumMcTracks() { // Always believe in success StatusCode sc = StatusCode::SUCCESS; // By default, no tracks int numMcTracks = 0; // If it doesn't exist then we need to build the MC structure if (updateData()) { // Obtain the vector of McParticle references from McEventStructure Event::McParticleRefVec trackVec = m_mcEvent->getTrackVector(); Event::McParticleRefVec::const_iterator trackVecIter; for(trackVecIter = trackVec.begin(); trackVecIter != trackVec.end(); trackVecIter++) { // Find the hits associated with this particle Event::McPartToClusPosHitVec hitVec = m_partHitTab->getRelByFirst(*trackVecIter); // Don't bother if really too few hits if (hitVec.size() > 4) numMcTracks++; } /* // If primary particle is charged then count if it is a track if (m_mcEvent->getClassificationBits() & Event::McEventStructure::CHARGED) { // Find the hits associated with this particle Event::McPartToClusPosHitVec hitVec = m_partHitTab->getRelByFirst(m_mcEvent->getPrimaryParticle()); // Don't bother if really too few hits if (hitVec.size() > 4) numMcTracks++; } // Now look at the secondaries Event::McParticleRefVec::const_iterator partIter; for(partIter = m_mcEvent->beginSecondaries(); partIter != m_mcEvent->endSecondaries(); partIter++) { // Find the hits associated with this particle Event::McPartToClusPosHitVec hitVec = m_partHitTab->getRelByFirst(*partIter); // Don't bother if really too few hits if (hitVec.size() > 4) numMcTracks++; } // Finally, any associated tracks for(partIter = m_mcEvent->beginAssociated(); partIter != m_mcEvent->endAssociated(); partIter++) { // Find the hits associated with this particle Event::McPartToClusPosHitVec hitVec = m_partHitTab->getRelByFirst(*partIter); // Don't bother if really too few hits if (hitVec.size() > 4) numMcTracks++; } */ } return numMcTracks; } const unsigned long McGetEventInfoTool::getClassificationBits() { if (updateData()) { return m_mcEvent->getClassificationBits(); } return 0; } const Event::McParticleRef McGetEventInfoTool::getPrimaryParticle() { if (updateData()) { return m_mcEvent->getPrimaryParticle(); } return &m_nullParticle; } int McGetEventInfoTool::getNumSecondaries() { if (updateData()) return m_mcEvent->getNumSecondaries(); return 0; } const Event::McParticleRef McGetEventInfoTool::getSecondary(int mcPartIdx) { if (updateData()) { Event::McParticleRefVec::const_iterator refVec = m_mcEvent->beginSecondaries(); if (mcPartIdx >= 0 && mcPartIdx < m_mcEvent->getNumSecondaries()) return refVec[mcPartIdx]; } return &m_nullParticle; } int McGetEventInfoTool::getNumAssociated() { if (updateData()) return m_mcEvent->getNumAssociated(); return 0; } const Event::McParticleRef McGetEventInfoTool::getAssociated(int mcPartIdx) { if (updateData()) { Event::McParticleRefVec::const_iterator refVec = m_mcEvent->beginAssociated(); if (mcPartIdx >= 0 && mcPartIdx < m_mcEvent->getNumAssociated()) return refVec[mcPartIdx]; } return &m_nullParticle; } const Event::McPartToClusPosHitVec McGetEventInfoTool::getMcPartTrack(const Event::McParticleRef mcPart) { Event::McPartToClusPosHitVec hitVec; hitVec.clear(); if (updateData()) { hitVec = m_partHitTab->getRelByFirst(mcPart); std::sort(hitVec.begin(),hitVec.end(),CompareTrackHits()); } return hitVec; } const int McGetEventInfoTool::getNumClusterHits(const Event::McParticleRef mcPart) { int numTrackHits = 0; if (updateData()) { Event::McPartToClusPosHitVec trackVec = m_partHitTab->getRelByFirst(mcPart); std::sort(trackVec.begin(),trackVec.end(),CompareTrackHits()); Event::McPartToClusPosHitVec::const_iterator trackVecIter; for(trackVecIter = trackVec.begin(); trackVecIter != trackVec.end(); trackVecIter++) { Event::TkrCluster* cluster = ((*trackVecIter)->getSecond())->getFirst(); if (cluster) numTrackHits++; } } return numTrackHits; } const int McGetEventInfoTool::getNumSharedTrackHits(const Event::McParticleRef mcPart) { int numSharedHits = 0; if (updateData()) { Event::McPartToClusPosHitVec trackVec = m_partHitTab->getRelByFirst(mcPart); std::sort(trackVec.begin(),trackVec.end(),CompareTrackHits()); Event::McPartToClusPosHitVec::const_iterator trackVecIter; for(trackVecIter = trackVec.begin(); trackVecIter != trackVec.end(); trackVecIter++) { Event::TkrCluster* cluster = ((*trackVecIter)->getSecond())->getFirst(); Event::McPartToClusVec partVec = m_partClusTab->getRelBySecond(cluster); if (partVec.size() > 1) numSharedHits++; } } return numSharedHits; } const int McGetEventInfoTool::getNumGaps(const Event::McParticleRef mcPart) { int numGaps = 0; if (updateData()) { Event::McPartToClusPosHitVec trackVec = m_partHitTab->getRelByFirst(mcPart); // No need to proceed if not enough hits track if (trackVec.size() > 1) { std::sort(trackVec.begin(),trackVec.end(),CompareTrackHits()); Event::McPartToClusPosHitVec::const_iterator trackVecIter = trackVec.begin(); Event::McPositionHit* layerHit = ((*trackVecIter++)->getSecond())->getSecond(); idents::VolumeIdentifier volId = layerHit->volumeID(); int lastLayer = 2*volId[4] - 1 + volId[6]; for(; trackVecIter != trackVec.end(); trackVecIter++) { layerHit = ((*trackVecIter)->getSecond())->getSecond(); volId = layerHit->volumeID(); int tkrLayer = 2*volId[4] - 1 + volId[6]; if (abs(tkrLayer - lastLayer) > 1) numGaps++; lastLayer = tkrLayer; } } } return numGaps; } const int McGetEventInfoTool::getGapSize(const Event::McParticleRef mcPart, int gapIdx) { int gapSize = 0; if (updateData()) { Event::McPartToClusPosHitVec trackVec = m_partHitTab->getRelByFirst(mcPart); // No need to proceed if not enough hits track if (trackVec.size() > 1) { std::sort(trackVec.begin(),trackVec.end(),CompareTrackHits()); Event::McPartToClusPosHitVec::const_iterator trackVecIter = trackVec.begin(); Event::McPositionHit* layerHit = ((*trackVecIter++)->getSecond())->getSecond(); idents::VolumeIdentifier volId = layerHit->volumeID(); int lastLayer = 2*volId[4] - 1 + volId[6]; int gapNum = 0; for(; trackVecIter != trackVec.end(); trackVecIter++) { layerHit = ((*trackVecIter)->getSecond())->getSecond(); volId = layerHit->volumeID(); int tkrLayer = 2*volId[4] - 1 + volId[6]; if (abs(tkrLayer - lastLayer) > 1) { if (gapNum++ == gapIdx) gapSize = abs(tkrLayer - lastLayer) - 1; } lastLayer = tkrLayer; } } } return gapSize; } const int McGetEventInfoTool::getGapStartHitNo(const Event::McParticleRef mcPart, int gapIdx) { int gapStartHitNo = 0; if (updateData()) { Event::McPartToClusPosHitVec trackVec = m_partHitTab->getRelByFirst(mcPart); // No need to proceed if not enough hits track if (trackVec.size() > 1) { std::sort(trackVec.begin(),trackVec.end(),CompareTrackHits()); Event::McPartToClusPosHitVec::const_iterator trackVecIter = trackVec.begin(); Event::McPositionHit* layerHit = ((*trackVecIter++)->getSecond())->getSecond(); idents::VolumeIdentifier volId = layerHit->volumeID(); int lastLayer = 2*volId[4] - 1 + volId[6]; int gapNum = 0; int hitNo = 0; for(; trackVecIter != trackVec.end(); trackVecIter++) { layerHit = ((*trackVecIter)->getSecond())->getSecond(); volId = layerHit->volumeID(); int tkrLayer = 2*volId[4] - 1 + volId[6]; if (abs(tkrLayer - lastLayer) > 1) { if (gapNum++ == gapIdx) gapStartHitNo = hitNo + 1; } lastLayer = tkrLayer; hitNo++; } } } return gapStartHitNo; } const double McGetEventInfoTool::getTrackStraightness(const Event::McParticleRef mcPart, int firstHitIdx, int lastHitIdx) { double trackAngle = 0.0; int numClusHits = 0; if (updateData()) { Event::McPartToClusPosHitVec trackVec = m_partHitTab->getRelByFirst(mcPart); int numHits = trackVec.size(); // Only keep going if we have enough hits to calculate an angle if (numHits > 3 && lastHitIdx - firstHitIdx > 3) { // Sort the hits to go from start to end of track std::sort(trackVec.begin(),trackVec.end(),CompareTrackHits()); // Iterators over the hits in the track Event::McPartToClusPosHitVec::const_iterator trackVecIter = firstHitIdx < numHits ? trackVec.begin() + firstHitIdx : trackVec.begin(); Event::McPartToClusPosHitVec::const_iterator trackVecStop = lastHitIdx < numHits ? trackVec.begin() + lastHitIdx : trackVec.end(); // Retrieve the first TkrCluster hit and get its position Event::TkrCluster* cluster = ((*trackVecIter++)->getSecond())->getFirst(); // It is possible for an McPositionHit to not make a TkrCluster, watch for this while(!cluster && trackVecIter != trackVecStop) { cluster = ((*trackVecIter++)->getSecond())->getFirst(); } // Retrieve the next TkrCluster hit, but be sure we have no over run the iterator Event::TkrCluster* nextClus = 0; while(!cluster && trackVecIter != trackVecStop) { nextClus = ((*trackVecIter++)->getSecond())->getFirst(); } // If valid cluster hits then proceed if (cluster && nextClus) { // Determine the hit position - based on the cluster but from the McPositionHits HepPoint3D hitLast = getPosition(cluster); HepPoint3D hitPos = getPosition(nextClus); // Form a vector between these hits CLHEP::Hep3Vector vecLast = CLHEP::Hep3Vector(hitPos - hitLast).unit(); // Set up for looping over the remaining hits hitLast = hitPos; numClusHits = 2; // Now loop over the rest of the hits for( ; trackVecIter != trackVecStop; trackVecIter++) { // Get next cluster hit cluster = ((*trackVecIter)->getSecond())->getFirst(); if (!cluster) continue; numClusHits++; // Retrieve the McSiLayerHit position hitPos = getPosition(cluster); // New vector to current hit CLHEP::Hep3Vector vecNext = CLHEP::Hep3Vector(hitPos - hitLast).unit(); // update the track angle double vecAngle = vecNext.angle(vecLast); trackAngle += vecAngle * vecAngle; // update for next loop hitLast = hitPos; vecLast = vecNext; } // Ok, if we found more than 2 clusters then calculate the rms if (numClusHits > 2) { double divisor = numClusHits - 2; trackAngle /= divisor; trackAngle = sqrt(trackAngle); } else trackAngle = 0.; } } } return trackAngle; } const HepPoint3D McGetEventInfoTool::getPosition(const Event::McPositionHit* mcPosHit) { double x = 0.; double y = 0.; double z = 0.; if (updateData()) { x = 0.5* (mcPosHit->globalEntryPoint().x() + mcPosHit->globalExitPoint().x()); y = 0.5* (mcPosHit->globalEntryPoint().y() + mcPosHit->globalExitPoint().y()); z = 0.5* (mcPosHit->globalEntryPoint().z() + mcPosHit->globalExitPoint().z()); } return HepPoint3D(x,y,z); } const HepPoint3D McGetEventInfoTool::getPosition(const Event::TkrCluster* cluster) { double x = 0.; double y = 0.; double z = 0.; if (updateData()) { Event::ClusMcPosHitVec hitVec = m_clusHitTab->getRelByFirst(cluster); Event::ClusMcPosHitVec::const_iterator hitVecIter = hitVec.begin(); // If only one McPositionHit associated with the cluster then task is easy if (hitVec.size() == 1) { Event::McPositionHit* posHit = (*hitVecIter)->getSecond(); // Cluster is from a noise hit can't happen here? Check anyway if (posHit) { x = 0.5* (posHit->globalEntryPoint().x() + posHit->globalExitPoint().x()); y = 0.5* (posHit->globalEntryPoint().y() + posHit->globalExitPoint().y()); z = 0.5* (posHit->globalEntryPoint().z() + posHit->globalExitPoint().z()); } } else if (hitVec.size() > 1) { double xLow = 100000.; double xHigh = -100000.; double yLow = 100000.; double yHigh = -100000.; double zLow = 100000.; double zHigh = -100000.; for( ;hitVecIter != hitVec.end(); hitVecIter++) { Event::McPositionHit* posHit = (*hitVecIter)->getSecond(); // It is possible that a cluster could contain a noise hit (hence, the // McPositionHit in the relation could be null if (!posHit) continue; HepPoint3D entryPoint = posHit->globalEntryPoint(); if (entryPoint.x() < xLow) xLow = entryPoint.x(); if (entryPoint.x() > xHigh) xHigh = entryPoint.x(); if (entryPoint.y() < yLow) yLow = entryPoint.y(); if (entryPoint.y() > yHigh) yHigh = entryPoint.y(); if (entryPoint.z() < zLow) zLow = entryPoint.z(); if (entryPoint.z() > zHigh) zHigh = entryPoint.z(); HepPoint3D exitPoint = posHit->globalExitPoint(); if (exitPoint.x() < xLow) xLow = exitPoint.x(); if (exitPoint.x() > xHigh) xHigh = exitPoint.x(); if (exitPoint.y() < yLow) yLow = exitPoint.y(); if (exitPoint.y() > yHigh) yHigh = exitPoint.y(); if (exitPoint.z() < zLow) zLow = exitPoint.z(); if (exitPoint.z() > zHigh) zHigh = exitPoint.z(); } x = 0.5 * (xLow + xHigh); y = 0.5 * (yLow + yHigh); z = 0.5 * (zLow + zHigh); } } return HepPoint3D(x,y,z); } const CLHEP::Hep3Vector McGetEventInfoTool::getTrackDirection(const Event::McParticleRef mcPart, int firstHitIdx, int lastHitIdx) { double xSlope = 0.; double ySlope = 0.; if (updateData()) { Event::McPartToClusPosHitVec trackVec = m_partHitTab->getRelByFirst(mcPart); int numHits = trackVec.size(); // Only keep going if we have enough hits to calculate an angle if (numHits > 3 && lastHitIdx - firstHitIdx > 3) { std::sort(trackVec.begin(),trackVec.end(),CompareTrackHits()); // Iterator over the hits in the track Event::McPartToClusPosHitVec::const_iterator trackVecIter = firstHitIdx < numHits ? trackVec.begin() + firstHitIdx : trackVec.begin(); Event::McPartToClusPosHitVec::const_iterator trackVecStop = lastHitIdx < numHits ? trackVec.begin() + lastHitIdx : trackVec.end(); double xVals[2]; double yVals[2]; double zVals_x[2]; double zVals_y[2]; int nHitsX = 0; int nHitsY = 0; // Now loop over the rest of the hits for( ; trackVecIter != trackVecStop; trackVecIter++) { // Get the cluster const Event::TkrCluster* tkrClus = ((*trackVecIter)->getSecond())->getFirst(); // Watch out for no cluster! if (!tkrClus) continue; // Check to see which orientation we have, store info accordingly if (tkrClus->getTkrId().getView() == idents::TkrId::eMeasureX && nHitsX < 2) { xVals[nHitsX] = tkrClus->position().x(); zVals_x[nHitsX] = tkrClus->position().z(); if (nHitsX == 1 && zVals_x[0] == zVals_x[1]) break; nHitsX++; } else if (nHitsY < 2) { yVals[nHitsY] = tkrClus->position().y(); zVals_y[nHitsY] = tkrClus->position().z(); if (nHitsY == 1 && zVals_y[0] == zVals_y[1]) break; nHitsY++; } // No use looping forever if done if (nHitsX > 1 && nHitsY > 1) break; } // if enough info then calculate new slopes if (nHitsX == 2 && nHitsY == 2) { xSlope = (xVals[1] - xVals[0]) / (zVals_x[1] - zVals_x[0]); ySlope = (yVals[1] - yVals[0]) / (zVals_y[1] - zVals_y[0]); } } } return CLHEP::Hep3Vector(-xSlope,-ySlope,-1.).unit(); } const int McGetEventInfoTool::getTrackHitLayer(const Event::McParticleRef mcPart, int hitIdx ) { int layer = 50; if (updateData()) { Event::McPartToClusPosHitVec trackVec = m_partHitTab->getRelByFirst(mcPart); int numHits = trackVec.size(); // Only keep going if we have enough hits to calculate an angle if (numHits > 0) { std::sort(trackVec.begin(),trackVec.end(),CompareTrackHits()); if (hitIdx < 0) hitIdx = 0; if (hitIdx >= numHits) hitIdx = numHits - 1; Event::McPositionHit* layerHit = (trackVec[hitIdx]->getSecond())->getSecond(); const idents::VolumeIdentifier volId = layerHit->volumeID(); if (volId[0] == 0 && volId[3] == 1 && volId.size() > 6) { int trayNum = volId[4]; int botTop = volId[6]; layer = 2 * trayNum + botTop - 1; } } } return layer; } const double McGetEventInfoTool::getTrackTotEneLoss(const Event::McParticleRef mcPart) { // Return the total energy loss from particle creation to last hit in tracker double totEloss = mcPart->initialFourMomentum().e() - getTrackELastHit(mcPart); return totEloss; } const double McGetEventInfoTool::getTrackELastHit(const Event::McParticleRef mcPart) { double ELastHit = mcPart->initialFourMomentum().e(); Event::McPartToClusPosHitVec hitVec = getMcPartTrack(mcPart); int hitSize = hitVec.size(); // If we have McPositionHits associated with this particle, return the energy at // the exit point of the last McPositionHit if (hitSize > 0) { // Sort the vector into the proper track order (time ordered) std::sort(hitVec.begin(),hitVec.end(),CompareTrackHits()); // Now get the energy at the last tracker hit Event::McPartToClusPosHitRel* relLast = hitVec.back(); Event::McPositionHit* lastHit = (relLast->getSecond())->getSecond(); ELastHit = lastHit->particleEnergy(); //following unecessary? /* const SmartRefVector<Event::McPositionHit>* mcPosHitVec = lyrLast->getMcPositionHitsVec(); // This loop to take into account that McPositionHits can be broken across a layer // Need to find the last one (lowest energy) SmartRefVector<Event::McPositionHit>::const_iterator posHitIter; for(posHitIter = mcPosHitVec->begin(); posHitIter != mcPosHitVec->end(); posHitIter++) { const Event::McPositionHit* posHit = *posHitIter; if (posHit->particleEnergy() < ELastHit) ELastHit = posHit->particleEnergy(); } */ } else { // We should not be getting to this point int j=0; } return ELastHit; } const double McGetEventInfoTool::getTrackBremELoss(const Event::McParticleRef mcPart, int& nTotRad) { double radEloss = 0.; nTotRad = 0; // McPositionHits for looking at where the last hit is... Event::McPartToClusPosHitVec hitVec = getMcPartTrack(mcPart); const Event::McPositionHit* posHit = 0; int hitSize = hitVec.size(); // If there exist McPositionHits for this mcPart then proceed... if (hitSize > 0) { // Sort the vector into the proper track order std::sort(hitVec.begin(),hitVec.end(),CompareTrackHits()); // Get the last Layer Hit from which we can extract the last McPositionHit Event::McPartToClusPosHitRel* relLast = hitVec.back(); Event::McPositionHit* posHit = (relLast->getSecond())->getSecond(); // Get the daughter vector const SmartRefVector<Event::McParticle>& daughterVec = mcPart->daughterList(); // Loop over particle's daughters SmartRefVector<Event::McParticle>::const_iterator daughterVecIter; for(daughterVecIter = daughterVec.begin(); daughterVecIter != daughterVec.end(); daughterVecIter++) { const Event::McParticle* daughter = *daughterVecIter; // Retrieve the volume identifier so we can check daughter particle origin volume idents::VolumeIdentifier iniVolId = const_cast<Event::McParticle*>(daughter)->getInitialId(); // If the particle starts in the tracker then record the energy it takes away if (iniVolId[0] == 0 && iniVolId[3] == 1 && iniVolId.size() > 3 && daughter->initialPosition().z() > posHit->globalExitPoint().z()) { // Looking only gammas ParticleProperty* ppty = m_ppsvc->findByStdHepID( daughter->particleProperty() ); // why do we have to check this? if (!ppty) continue; if (ppty->particle() == "gamma") { radEloss += daughter->initialFourMomentum().e(); nTotRad++; } } } } return radEloss; } const double McGetEventInfoTool::getTrackDeltaELoss(const Event::McParticleRef mcPart, int& nTotDlta, int& nHitDlta) { double radEloss = 0.; nTotDlta = 0; nHitDlta = 0; // McPositionHits for looking at where the last hit is... Event::McPartToClusPosHitVec hitVec = getMcPartTrack(mcPart); const Event::McPositionHit* posHit = 0; int hitSize = hitVec.size(); // If there exist McPositionHits for this mcPart then proceed... if (hitSize > 0) { // Sort the vector into the proper track order std::sort(hitVec.begin(),hitVec.end(),CompareTrackHits()); // Get the last Layer Hit from which we can extract the last McPositionHit Event::McPartToClusPosHitRel* relLast = hitVec.back(); Event::McPositionHit* posHit = (relLast->getSecond())->getSecond(); const SmartRefVector<Event::McParticle>& daughterVec = mcPart->daughterList(); SmartRefVector<Event::McParticle>::const_iterator daughterVecIter; // Loop over particle's daughters for(daughterVecIter = daughterVec.begin(); daughterVecIter != daughterVec.end(); daughterVecIter++) { const Event::McParticle* daughter = *daughterVecIter; idents::VolumeIdentifier iniVolId = const_cast<Event::McParticle*>(daughter)->getInitialId(); // If the particle starts in the tracker then record the energy it takes away if (iniVolId[0] == 0 && iniVolId[3] == 1 && iniVolId.size() > 3 && daughter->initialPosition().z() > posHit->globalExitPoint().z()) { // Get the particle property ParticleProperty* ppty = m_ppsvc->findByStdHepID( daughter->particleProperty() ); // why do we have to check this? if (!ppty) continue; // Looking for energy carried away by delta rays... if (ppty->particle() != "gamma") { radEloss += (daughter->initialFourMomentum().e() - ppty->mass()); nTotDlta++; if (daughter->statusFlags() & Event::McParticle::POSHIT) nHitDlta++; } } } } return radEloss; } const int McGetEventInfoTool::getTrackDeltaRange(const Event::McParticleRef mcPart, double& aveRange, double& maxRange) { int nTotHits = 0; aveRange = 0.; maxRange = 0.; // McPositionHits for looking at where the last hit is... Event::McPartToClusPosHitVec hitVec = getMcPartTrack(mcPart); const Event::McPositionHit* posHit = 0; int hitSize = hitVec.size(); // If there exist McPositionHits for this mcPart then proceed... if (hitSize > 0) { // Sort the vector into the proper track order std::sort(hitVec.begin(),hitVec.end(),CompareTrackHits()); // Get the last Layer Hit from which we can extract the last McPositionHit Event::McPartToClusPosHitRel* relLast = hitVec.back(); Event::McPositionHit* posHit = (relLast->getSecond())->getSecond(); const SmartRefVector<Event::McParticle>& daughterVec = mcPart->daughterList(); SmartRefVector<Event::McParticle>::const_iterator daughterVecIter; // Loop over particle's daughters for(daughterVecIter = daughterVec.begin(); daughterVecIter != daughterVec.end(); daughterVecIter++) { const Event::McParticle* daughter = *daughterVecIter; idents::VolumeIdentifier iniVolId = const_cast<Event::McParticle*>(daughter)->getInitialId(); // If the particle starts in the tracker then record the energy it takes away if (iniVolId[0] == 0 && iniVolId[3] == 1 && iniVolId.size() > 3 && daughter->initialPosition().z() > posHit->globalExitPoint().z()) { // Get the particle property ParticleProperty* ppty = m_ppsvc->findByStdHepID( daughter->particleProperty() ); // why do we have to check this? if (!ppty) continue; // Looking for energy carried away by delta rays... if (ppty->particle() != "gamma") { HepPoint3D iniPosition = daughter->initialPosition(); HepPoint3D finPosition = daughter->finalPosition(); CLHEP::Hep3Vector traject = finPosition - iniPosition; double range = traject.mag(); aveRange += range; if (range > maxRange) maxRange = range; nTotHits++; } } } // Calculate the average range if (nTotHits > 0) aveRange = aveRange / nTotHits; } return nTotHits; } const unsigned int McGetEventInfoTool::getSharedHitInfo(const Event::McParticleRef mcPart) { unsigned int hitInfo = 0; if (updateData()) { Event::McPartToClusPosHitVec trackVec = m_partHitTab->getRelByFirst(mcPart); std::sort(trackVec.begin(),trackVec.end(),CompareTrackHits()); Event::McPartToClusPosHitVec::const_iterator trackVecIter; int bitIndex = 0; int numShared = 0; for(trackVecIter = trackVec.begin(); trackVecIter != trackVec.end(); trackVecIter++) { Event::TkrCluster* cluster = ((*trackVecIter)->getSecond())->getFirst(); Event::McPartToClusVec partVec = m_partClusTab->getRelBySecond(cluster); if (partVec.size() > 1) { if (numShared < 15) numShared++; else hitInfo |= 0x08000000; if (bitIndex < 24) hitInfo |= 1 << bitIndex; else hitInfo |= 0x00800000; } bitIndex++; } hitInfo = (hitInfo << 4) + numShared; } return hitInfo; } const unsigned int McGetEventInfoTool::getSharedHitInfo(const Event::McParticleRef mcPart1, const Event::McParticleRef mcPart2) { unsigned int hitInfo = 0; if (updateData()) { // Set up to loop over the hits in the first track. Event::McPartToClusPosHitVec trackVec = m_partHitTab->getRelByFirst(mcPart1); std::sort(trackVec.begin(),trackVec.end(),CompareTrackHits()); Event::McPartToClusPosHitVec::const_iterator trackVecIter; int bitIndex = 0; int numShared = 0; // Loop over the hits on the track for(trackVecIter = trackVec.begin(); trackVecIter != trackVec.end(); trackVecIter++) { // Recover the cluster associated with this track Event::TkrCluster* cluster = ((*trackVecIter)->getSecond())->getFirst(); // If no cluster skip to the next hit if (!cluster) continue; // Recover vector of McParticles associated with this cluster Event::McPartToClusVec partVec = m_partClusTab->getRelBySecond(cluster); // If more than one McParticle associated with the cluster then it is shared if (partVec.size() > 1) { // Loop through this vector looking for a match to the second track for(Event::McPartToClusVec::const_iterator mcPartVecIter = partVec.begin(); mcPartVecIter != partVec.end(); mcPartVecIter++) { if ((*mcPartVecIter)->getFirst() == mcPart2) { if (numShared < 15) numShared++; else hitInfo |= 0x08000000; if (bitIndex < 24) hitInfo |= 1 << bitIndex; else hitInfo |= 0x00800000; } } } bitIndex++; } hitInfo = (hitInfo << 4) + numShared; } return hitInfo; }
36.495726
129
0.582436
[ "vector" ]
01c0228b13526573c83792c3381aea0d254461fd
34,333
cpp
C++
old_runtime/DebugRuntime/ScanfSupport.cpp
spurious/safecode-mirror
238e1a381674528f642e1ee6be1e1b7df465672e
[ "NCSA" ]
5
2015-07-23T09:47:12.000Z
2019-11-28T01:34:01.000Z
old_runtime/DebugRuntime/ScanfSupport.cpp
spurious/safecode-mirror
238e1a381674528f642e1ee6be1e1b7df465672e
[ "NCSA" ]
null
null
null
old_runtime/DebugRuntime/ScanfSupport.cpp
spurious/safecode-mirror
238e1a381674528f642e1ee6be1e1b7df465672e
[ "NCSA" ]
3
2015-10-28T18:21:02.000Z
2019-05-06T18:35:41.000Z
//===- ScanfSupport.cpp - Secure scanf() replacement ------------===// // // The SAFECode Compiler Project // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a secure runtime replacement for scanf() and similar // functions. // //===----------------------------------------------------------------------===// // // This code is derived from MINIX's doscan.c; original license follows: // // /cvsup/minix/src/lib/stdio/doscan.c,v 1.1.1.1 2005/04/21 14:56:35 beng Exp $ // // Copyright (c) 1987,1997,2001 Prentice Hall // All rights reserved. // // Redistribution and use of the MINIX operating system in source and // binary forms, with or without modification, are permitted provided // that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of Prentice Hall nor the names of the software // authors or contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, AUTHORS, 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 PRENTICE HALL OR ANY AUTHORS OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include "safecode/Config/config.h" #include "FormatStrings.h" #include <ctype.h> #include <inttypes.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <wchar.h> #ifdef __x86_64__ #define set_pointer(flags) (flags |= FL_LONG) #else #define set_pointer(flags) // nothing #endif // Maximum allowable size for an input number. #define NUMLEN 512 #define NR_CHARS 256 // // Flags describing how to process the input // #define FL_CHAR 0x0001 // hh length modifier #define FL_SHORT 0x0002 // h length modifier #define FL_LLONG 0x0004 // ll length modifier #define FL_LONG 0x0008 // l length modifier #define FL_LONGDOUBLE 0x0010 // L length modifier #define FL_INTMAX 0x0020 // j length modifier #define FL_SIZET 0x0040 // z length modifier #define FL_PTRDIFF 0x0080 // t length modifier #define FL_NOASSIGN 0x0100 // do not assign (* flag) #define FL_WIDTHSPEC 0x0200 // field width specified // // _getc() // // Get the next character from the input. // Returns EOF on reading error or end of file/string. // static inline int _getc(input_parameter *i) { // // Get the next character from the string. // if (i->input_kind == input_parameter::INPUT_FROM_STRING) { const char *string = i->input.string.string; size_t &pos = i->input.string.pos; if (string[pos] == '\0') return EOF; else return string[pos++]; } // // Get the next character from the stream. // else // i->InputKind == input_parameter::INPUT_FROM_STREAM { FILE *file = i->input.stream.stream; char &lastch = i->input.stream.lastch; int ch; // // Call fgetc_unlocked() for performance because the given input stream // should already be locked by the thread. // // Use fgetc() on platforms without fgetc_unlocked(). // #ifndef HAVE_FGETC_UNLOCKED #define fgetc_unlocked fgetc #endif if ((ch = fgetc_unlocked(file)) == EOF) return EOF; else { // Save the character we got in case it is pushed back via _ungetc(). lastch = ch; return ch; } } } // // _ungetc() // // 'Push back' the last character that was read from the input source. // This function assumes at least one character has been read via _getc(). // This function should be called at most once between calls to _getc(), // so that at most one character is pushed back at any given time. // static inline void _ungetc(input_parameter *i) { if (i->input_kind == input_parameter::INPUT_FROM_STRING) // // 'Push back' the string by just decrementing the position. // i->input.string.pos--; else if (i->input_kind == input_parameter::INPUT_FROM_STREAM) { const char lastch = i->input.stream.lastch; // // Use ungetc() to push the last character back into the stream. // See the note over internal_scanf() about the portability of this // operation. // ungetc(lastch, i->input.stream.stream); } } // // input_failure() // // Check if the parameter has had an input failure. // This is defined as EOF or a read error, according to the standard. // For strings an input error is the same as the end of the string. // // Returns: True if the parameter is said to have an input failure, false // otherwise. // static inline bool input_failure(input_parameter *i) { if (i->input_kind == input_parameter::INPUT_FROM_STRING) return i->input.string.string[i->input.string.pos] == 0; else // i->InputKind == input_parameter::INPUT_FROM_STREAM { FILE *f = i->input.stream.stream; return ferror(f) || feof(f); } } // // o_collect() // // Collect a number of characters which constitite an ordinal number. // When the type is 'i', the base can be 8, 10, or 16, depending on the // first 1 or 2 characters. This means that the base must be adjusted // according to the format of the number. At the end of the function, base // is then set to 0, so strtol() will get the right argument. // // Inputs: // // c - the first character to read as an input item // stream - the input_parameter object which contains the rest of the // characters to be read as input items // inp_buf - the buffer into which the number should be written // type - the type of the specifier associated with this conversion, one of // 'i', 'p', 'x', 'X', 'd', 'o', or 'b' // width - the maximum field width // basep - A pointer to an integer. This value is written into with the // numerical base of the value in the buffer, suitable for a call to // strtol() or other function, as determined by this function. // // This function returns NULL if the input buffer was not filled with a valid // integer that could be converted; and otherwise if the input buffer contains // the digits of a valid integer, the function returns the last nonnul position // of the buffer that was written. // // On success, the buffer is suited for a call to strtol() or other integer // conversion function, with the base given in *basep. // static char * o_collect(int c, input_parameter *stream, char *inp_buf, char type, unsigned int width, int *basep) { char *bufp = inp_buf; int base = 0; switch (type) { case 'i': // i means octal, decimal or hexadecimal case 'p': case 'x': case 'X': base = 16; break; case 'd': case 'u': base = 10; break; case 'o': base = 8; break; case 'b': base = 2; break; } // // Process any initial +/- sign. // if (c == '-' || c == '+') { *bufp++ = c; if (--width) c = _getc(stream); else return 0; // An initial [+-] is not a valid number. } // // Determine whether an initial '0' means to process the number in // hexadecimal or octal, if we are given a choice between the two. // if (width && c == '0' && base == 16) { *bufp++ = c; if (--width) c = _getc(stream); if (c != 'x' && c != 'X') { if (type == 'i') base = 8; } else if (width) { *bufp++ = c; if (--width) c = _getc(stream); } else return 0; // Don't accept only an initial [+-]?0[xX] as a valid number. } else if (type == 'i') base = 10; // // Read as many digits as we can. // while (width) { if ( ((base == 10) && isdigit(c) ) || ((base == 16) && isxdigit(c) ) || ((base == 8) && isdigit(c) && (c < '8')) || ((base == 2) && isdigit(c) && (c < '2'))) { *bufp++ = c; if (--width) c = _getc(stream); } else break; } // // Push back any extra read characters that aren't part of an integer. // if (width && c != EOF) _ungetc(stream); if (type == 'i') base = 0; *basep = base; *bufp = '\0'; return bufp == inp_buf ? 0 : bufp - 1; } #ifdef FLOATING_POINT #include "ScanfTables.h" // // f_collect() // // Read the longest valid floating point number prefix from the input buffer. // Upon encountering an error, the function returns and leaves the character // to have caused the error in the input stream. // // Inputs: // c - the first character to read // stream - the parameter from which to get the rest of the characters // inp_buf - the buffer into which to write the number // width - the maximum number of characters to read // // Returns: // On error, the function returns NULL. On success, it returns a pointer to the // last non-nul position in the input buffer. // char * f_collect(int c, input_parameter *stream, char *inp_buf, unsigned int width) { int state = 1; // The start state from the scanner char *buf = inp_buf; int ch; int accept; ch = c; // // This loop matches the input with the transition table. // while (width && state > 0) { // // Handle an 8 bit character or EOF character by breaking immediately. // if (ch == EOF || ch > 127) break; state = yy_nxt[state][ch]; // // Advance to the next state and save the current character, if valid. // if (state > 0) *buf++ = ch; // // Get the next character. // if (--width) ch = _getc(stream); } // // Push back the next character if it was a valid character not part of the // input sequence. // if (width > 0 && ch != EOF) _ungetc(stream); // // Get information about the next action of the scanner. // accept = yy_accept[state < 0 ? -state : state]; // // A value of 0 for accept indicates failure/that the scanner should revert // to the previous accepting state. Since this is not possible without // pushing back more than one character, we should just fail. // // A value of DEFAULT_RULE indicates to the scanner to echo the output // since it is unmatched. This also indicates failure. // #define DEFAULT_RULE 5 if (accept == 0 || accept == DEFAULT_RULE) return 0; else if (buf == inp_buf) return 0; else { *buf = '\0'; return buf - 1; } } #endif // FLOATING_POINT // // eat_whitespace() // // Read all initial whitespace from the input stream. // // Inputs: // stream - the input stream // count - a reference to a counter of the number of characters read // // Returns: // This function returns the first non whitespace character encountered in the // input stream (which could be EOF). // static inline int eat_whitespace(input_parameter *stream, int &count) { int ch; do { ch = _getc(stream); count++; } while (isspace(ch)); return ch; } // // This is a bitvector which specifies a set of characters to match. // typedef struct { enum { FUNCTION, TABLE } kind; union { uint64_t t[4]; int (*f)(int); } s; } scanset_t; const scanset_t all_chars = { scanset_t::TABLE, { { 0xfffffffffffffffful, 0xfffffffffffffffful, 0xfffffffffffffffful, 0xfffffffffffffffful } } }; // Clear the scanset. #define clear_scanset(set) \ for (int i = 0; i < 4; i++) (set)->s.t[i] = 0ul // Add a character to the scanset. #define add_to_scanset(set, c) \ (set)->s.t[((unsigned char) c) >> 6] |= ((uint64_t)1) << (c & 0x3f) // Take the complement of the scanset. #define invert_scanset(set) \ for (int i = 0; i < 4; i++) (set)->s.t[i] = ~(set)->s.t[i] // Query if a character is in the scanset. #define is_in_scanset(set, c) \ ( \ (set)->kind == scanset_t::TABLE ? \ (set)->s.t[((unsigned char) c) >> 6] & (((uint64_t) 1) << (c & 0x3f)) : \ (set)->s.f(c) \ ) // // read_scanset() // // Read the %[...]-style directive embedded in the given format string, and // construct the resuling scanset into *scanset. // // Inputs: // format - the format string, assumed to be pointing to the next character // after the sequence "%[" // scanset - the scanset to fill with the characters in the sequence // // Returns: // The function returns a pointer to the first subsequent character in the // format string that is considered not part of the scanset. This character // will be ']' in a valid directive, or '\0' if the directive is somehow // malformed. // static inline const char * read_scanset(const char *format, scanset_t *scanset) { int reverse; const char *start = format; // // Determine if we take the complement of the scanset. // if (*++format == '^') { reverse = 1; format++; } else reverse = 0; // // Clear the scanset first. // clear_scanset(scanset); // // ']' appearing as the first character in the set does not close the // directive, but rather adds ']' to the scanset. // if (*format == ']') { add_to_scanset(scanset, ']'); format++; } // // Parse the rest of the directive. // while (*format != '\0' && *format != ']') { // // Add a character range to the scanset... // if (*format == '-') { format++; // // ...unless we're in a boundary condition, in which case just add '-'. // if (*format == ']' || &format[-2] == start || (&format[-2] == &start[1] && start[1] == '^')) { add_to_scanset(scanset, '-'); } else if (*format >= format[-2]) { int c; for (c = format[-2] + 1; c <= *format; c++) add_to_scanset(scanset, c); format++; } } else { add_to_scanset(scanset, *format); format++; } } // // Take the complement, if necessary. // if (reverse) invert_scanset(scanset); return format; } // // isnspace() // // Used by the %s directive for reading input. // int isnspace(int c) { return !isspace(c); } // // match_string() // // Read a string of characters that belong in the given scanset, up to size // width. If 'dowrite' is true, write the string (with a nul terminator) into // the buffer associated with the pointer_info argument. Report if there are // any memory safety errors due to writing into the buffer. // // Inputs: // // ci - a pointer to the call_info structure for this function call // p - a pointer to the pointer_info structure that contains the buffer // to write into // flags - the set of flags associated with the current conversion // c - the first character to read // stream - the input stream which contains the rest of the characters // width - the maximum number of characters to read // dowrite - a boolean, if true, the string is written into a buffer // termin - a boolean, if true, the buffer is terminated // nrchars - a reference to a relevant counter of the number of characters // read // set - the set of permissible characters in the string // // Returns: // This function returns the number of characters that it has read. // Reading 0 characters indicates a conversion error. // // If dowrite is true and (flags&FL_LONG) is true, then the buffer is filled // with wide characters converted from the multibyte input stream. Otherwise, // the buffer is filled with the same characters that composed the input, if // dowrite is true. // static inline size_t match_string(call_info *ci, pointer_info *p, int flags, int c, input_parameter *stream, size_t width, const bool dowrite, const bool termin, int &nrchars, const scanset_t *set) { size_t maxwrite = SIZE_MAX; size_t writecount = 0; size_t readcount = 1; // We've "read" c already. char *buf = 0; char mbbuf[MB_LEN_MAX]; size_t mbbufpos = 0; wchar_t wc; size_t wclen; const bool wcs = flags & FL_LONG; mbstate_t ps; if (wcs) memset(&ps, 0, sizeof(mbstate_t)); // // Read the input string. // while (width > 0 && c != EOF && is_in_scanset(set, c)) { // // If after reading a character, the buffer is ready for writing, prepare // it for writing. // if (readcount++ == 1 && dowrite) { // // Get the output buffer. // buf = (char *) p; if (p == NULL) { cerr << "Writing into a NULL object!" << endl; c_library_error(ci, "scanf"); } else if (is_in_whitelist(ci, p) == false) { cerr << "Writing into a non-pointer!" << endl; c_library_error(ci, "scanf"); } else { find_object(ci, p); if (p->flags & HAVEBOUNDS) maxwrite = (size_t) 1 + (char *)p->bounds[1] - (char *) p->ptr; buf = (char *) p->ptr; if (buf == 0) { cerr << "Writing into a NULL object!" << endl; c_library_error(ci, "scanf"); } } } if (dowrite) { if (!wcs) { // // Write directly into the output buffer. // // // Check if this write will go out of bounds. Only report this the first // time that it occurs. // if ((++writecount - maxwrite) == 1) { cerr << "Writing out of bounds!" << endl; write_out_of_bounds_error(ci, p, maxwrite, writecount); } *buf++ = c; } else { // // Read the next multibyte character incrementally. Write it into the // output buffer once we've encountered a valid character. // mbbuf[mbbufpos++] = (char) c; // // Attempt a multibyte to wide character conversion. // wclen = mbrtowc(&wc, &mbbuf[0], mbbufpos, &ps); if (wclen == (size_t) -1) // Conversion error break; else if (wclen == (size_t) -2) ; // The buffer might be holding the prefix of a valid // multibyte character sequence, so try reading more. else { writecount += sizeof(wchar_t); // // Check if the write will go out of bounds. Only report this the // first time that it occurs. // if (writecount - maxwrite > 0 && (writecount - maxwrite) <= sizeof(wchar_t)) { cerr << "Writing out of bounds!" << endl; write_out_of_bounds_error(ci, p, maxwrite, writecount); } ((wchar_t *)buf)[(writecount/sizeof(wchar_t)) - 1] = wc; // // Reset the input buffer. // mbbufpos = 0; } } } if (--width > 0) { c = _getc(stream); nrchars++; } } // // Terminate the string with the appropriate nul terminator, if necessary. // if (termin && dowrite && writecount > 0) { if (!wcs) { if ((++writecount - maxwrite) == 1) { cerr << "Writing out of bounds!" << endl; write_out_of_bounds_error(ci, p, maxwrite, writecount); } *buf = '\0'; } else { writecount += sizeof(wchar_t); if (writecount - maxwrite > 0 && (writecount - maxwrite) <= sizeof(wchar_t)) { cerr << "Writing out of bounds!" << endl; write_out_of_bounds_error(ci, p, maxwrite, writecount); } ((wchar_t *)buf)[(writecount/sizeof(wchar_t)) - 1] = L'\0'; } } // // Push back any character that was read and not in the scanset. // if (width > 0 && c != EOF) { _ungetc(stream); readcount--; nrchars--; } // // Don't count EOF. // else if (c == EOF) { readcount--; nrchars--; } return readcount; } // // SAFEWRITE() // // A macro that attempts to securely write a value into the next parameter. // // Inputs: // ci - pointer to the call_info structure // ap - pointer to the va_list // arg - the variable argument number to be accessed // item - the item to write // type - the type to write the item as // #define SAFEWRITE(ci, ap, arg, item, type) \ do \ { \ pointer_info *p; \ void *dest; \ varg_check(ci, arg++); \ p = va_arg(ap, pointer_info *); \ write_check(ci, p, sizeof(type)); \ dest = unwrap_pointer(ci, p); \ /* if (dest != 0) */ *(type *) dest = (type) item; \ } while (0) // // internal_scanf() // // This is the main logic for the secured scanf() family of functions. // // // IMPLEMENTATION NOTES // - This function uses ungetc() to push back characters into a stream. // This is an error because at most one character can be pushed back // portably, but an ungetc() call is allowed to follow a call to a scan // function without any intervening I/O. Hence if this function calls // ungetc() and then the caller does so again on the same stream, the // result might fail. // // However, glibc appears to have support for consecutive 2 character // pushback, so this doesn't fail on glibc. // // Mac OS X's libc also has support for 2 character pushback. // // - A nonstandard %b specifier is supported, for reading binary integers. // - No support for positional arguments (%n$-style directives) (yet ?). // - The maximum supported width of a numerical constant in the input is 512 // bytes. // int internal_scanf(input_parameter &i, call_info &c, const char *fmt, va_list ap) { int done = 0; // number of items converted int nrchars = 0; // number of characters read int base; // conversion base uintmax_t val; // an integer value char *str; // temporary pointer char *tmp_string; // ditto unsigned width = 0; // width of field int flags; // some flags int kind; int ic = EOF; // the input character char inp_buf[NUMLEN + 1]; // buffer to hold numerical inputs #ifdef FLOATING_POINT long double ld_val; #endif const char *format = fmt; input_parameter *stream = &i; str = 0; // Suppress g++ complaints about unitialized variables. pointer_info *p = 0; // Return immediately for an empty format string. if (*format == '\0') return 0; mbstate_t ps; size_t len; const char *mb_pos; memset(&ps, 0, sizeof(ps)); call_info *ci = &c; unsigned int arg = 1; bool wr; size_t sz; scanset_t nonws; nonws.kind = scanset_t::FUNCTION; nonws.s.f = isnspace; scanset_t scanset; scanset.kind = scanset_t::TABLE; // // Version of SAFEWRITE() relevant to this function. // #define _SAFEWRITE(item, type) SAFEWRITE(ci, ap, arg, item, type) // // The main loop that processes the format string. // At the end of the loop, the count of assignments is updated and the format // string is incremented one position. // while (1) { // // Whitespace in the format string indicates to match all whitespace in the // input stream. // if (isspace(*format)) { while (isspace(*format)) format++; // Skip whitespace in the format string. ic = eat_whitespace(stream, nrchars); if (ic != EOF) _ungetc(stream); } if (*format == '\0') break; // End of format // // Match a multibyte character from the input. // if (*format != '%') { len = mbrtowc(NULL, format, MB_CUR_MAX, &ps); mb_pos = format; format += len; while (mb_pos != format) { ic = _getc(stream); if (ic != *mb_pos) break; else { nrchars++; mb_pos++; } } if (mb_pos != format && ic != *mb_pos) { // // A directive that is an ordinary multibyte character is executed // by reading the next characters of the stream. If any of those // characters differ from the ones composing the directive, the // directive fails and the differing and subsequent characters // remain unread. // // - C99 Standard // if (ic != EOF) { _ungetc(stream); goto match_failure; } else goto failure; } continue; } format++; // We've read '%'; start processing a directive. flags = 0; // // The '%' specifier // if (*format == '%') { ic = eat_whitespace(stream, nrchars); if (ic == '%') { format++; continue; } else { _ungetc(stream); goto failure; } } // // '*' flag: Suppress assignment. // if (*format == '*') { format++; flags |= FL_NOASSIGN; } // // Get the field width, if there is any. // if (isdigit (*format)) { flags |= FL_WIDTHSPEC; for (width = 0; isdigit (*format);) width = width * 10 + *format++ - '0'; } // // Process length modifiers. // switch (*format) { case 'h': if (*++format == 'h') { format++; flags |= FL_CHAR; } else flags |= FL_SHORT; break; case 'l': if (*++format == 'l') { format++; flags |= FL_LLONG; } else flags |= FL_LONG; break; case 'j': format++; flags |= FL_INTMAX; break; case 'z': format++; flags |= FL_SIZET; break; case 't': format++; flags |= FL_PTRDIFF; break; case 'L': format++; flags |= FL_LONGDOUBLE; break; } // // Read the actual specifier. // kind = *format; // // Eat any initial whitespace for specifiers that allow it. // if ((kind != 'c') && (kind != '[') && (kind != 'n')) { ic = eat_whitespace(stream, nrchars); if (ic == EOF) goto failure; } // // Get the initial character of the input, for non-%n specifiers. // else if (kind != 'n') { ic = _getc(stream); if (ic == EOF) goto failure; nrchars++; } // // Process the format specifier. // switch (kind) { default: // not recognized, like %q goto failure; // // %n specifier // case 'n': if (!(flags & FL_NOASSIGN)) { if (flags & FL_CHAR) _SAFEWRITE(nrchars, char); else if (flags & FL_SHORT) _SAFEWRITE(nrchars, short); else if (flags & FL_LONG) _SAFEWRITE(nrchars, long); else if (flags & FL_LLONG) _SAFEWRITE(nrchars, long long); else if (flags & FL_INTMAX) _SAFEWRITE(nrchars, intmax_t); else if (flags & FL_SIZET) _SAFEWRITE(nrchars, size_t); else if (flags & FL_PTRDIFF) _SAFEWRITE(nrchars, ptrdiff_t); else _SAFEWRITE(nrchars, int); } break; // // %p specifier // case 'p': // Set any additional flags regarding pointer representation size. set_pointer(flags); // fallthrough // // Integral specifiers: %b, %d, %i, %o, %u, %x, %X // case 'b': // binary case 'd': // decimal case 'i': // general integer case 'o': // octal case 'u': // unsigned case 'x': // hexadecimal case 'X': // ditto // Don't read more than NUMLEN bytes. if (!(flags & FL_WIDTHSPEC) || width > NUMLEN) width = NUMLEN; if (width == 0) goto match_failure; str = o_collect(ic, stream, inp_buf, kind, width, &base); if (str == 0) goto failure; // // Although the length of the number is str-inp_buf+1 // we don't add the 1 since we counted it already. // nrchars += str - inp_buf; if (!(flags & FL_NOASSIGN)) { if (kind == 'd' || kind == 'i') val = strtoimax(inp_buf, &tmp_string, base); else val = strtoumax(inp_buf, &tmp_string, base); if (flags & FL_CHAR) _SAFEWRITE(val, unsigned char); else if (flags & FL_SHORT) _SAFEWRITE(val, unsigned short); else if (flags & FL_LONG) _SAFEWRITE(val, unsigned long); else if (flags & FL_LLONG) _SAFEWRITE(val, unsigned long long); else if (flags & FL_INTMAX) _SAFEWRITE(val, uintmax_t); else if (flags & FL_SIZET) _SAFEWRITE(val, size_t); else if (flags & FL_PTRDIFF) _SAFEWRITE(val, ptrdiff_t); else _SAFEWRITE(val, unsigned); } break; // // %c specifier // case 'c': // // No specified width means to read a single character. // if (!(flags & FL_WIDTHSPEC)) width = 1; if (width == 0) goto match_failure; wr = !(flags & FL_NOASSIGN); if (wr) { varg_check(ci, arg++); p = va_arg(ap, pointer_info *); } sz = \ match_string( ci, p, flags, ic, stream, width, wr, false, nrchars, &all_chars ); if (sz == 0) goto failure; break; // // %s specifier // case 's': if (!(flags & FL_WIDTHSPEC)) width = UINT_MAX; if (width == 0) goto match_failure; wr = !(flags & FL_NOASSIGN); if (wr) { varg_check(ci, arg++); p = va_arg(ap, pointer_info *); } sz = \ match_string( ci, p, flags, ic, stream, width, wr, true, nrchars, &nonws ); if (sz == 0) goto failure; break; // // %[...] specifier // case '[': if (!(flags & FL_WIDTHSPEC)) width = UINT_MAX; if (width == 0) goto match_failure; format = read_scanset(format, &scanset); // // If the format string points to a '\0', then there was an error // parsing the scanset. // if (*format == '\0') goto match_failure; wr = !(flags & FL_NOASSIGN); if (wr) { varg_check(ci, arg++); p = va_arg(ap, pointer_info *); } sz = \ match_string( ci, p, flags, ic, stream, width, wr, true, nrchars, &scanset ); if (sz == 0) goto failure; break; #ifdef FLOATING_POINT // // Floating point specifiers: %a, %A, %e, %E, %f, %F, %g, %G // case 'a': case 'A': case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': if (!(flags & FL_WIDTHSPEC) || width > NUMLEN) width = NUMLEN; if (!width) goto failure; str = f_collect(ic, stream, inp_buf, width); if (str == 0) goto failure; // // Although the length of the number is str-inp_buf+1 // we don't add the 1 since we counted it already // nrchars += str - inp_buf; if (!(flags & FL_NOASSIGN)) { ld_val = strtold(inp_buf, &tmp_string); if (flags & FL_LONGDOUBLE) _SAFEWRITE(ld_val, long double); else if (flags & FL_LONG) _SAFEWRITE(ld_val, double); else _SAFEWRITE(ld_val, float); } break; #endif } if (!(flags & FL_NOASSIGN) && kind != 'n') done++; format++; } goto finish; failure: // // In the event of a possible input failure (=eof or read error), the // directive should jump to here. // if (done == 0 && input_failure(stream)) return EOF; // // The fscanf function returns the value of the macro EOF if an input failure // occurs before the first conversion (if any) has completed. Otherwise, the // function returns the number of input items assigned, which can be fewer // than provided for, or even zero, in the event of an early matching failure. // // - C99 Standard // match_failure: finish: return done; }
27.643317
80
0.555209
[ "object" ]
01ca8ee9472368fac763057ee4c733b2d17680d4
2,029
cpp
C++
src/Engine/StreamProcessingEngine.cpp
nathan-backman/cmsc491-SPE
b836b6d74dd97f767a09e7d955b8ad2173ca609d
[ "MIT" ]
null
null
null
src/Engine/StreamProcessingEngine.cpp
nathan-backman/cmsc491-SPE
b836b6d74dd97f767a09e7d955b8ad2173ca609d
[ "MIT" ]
null
null
null
src/Engine/StreamProcessingEngine.cpp
nathan-backman/cmsc491-SPE
b836b6d74dd97f767a09e7d955b8ad2173ca609d
[ "MIT" ]
null
null
null
// Copyright 2019 [BVU CMSC491 class] #include "Engine/StreamProcessingEngine.h" void StreamProcessingEngine::connectOperators( Operator* upstreamOp, std::vector<Operator*> downstreamOps) { // Register the downstream operators with the upstream operator upstreamOp->downstreamOperators = downstreamOps; // Add these operators to our running set of all workflow operators which // will be later used by the operator scheduler ops.insert(upstreamOp); ops.insert(downstreamOps.begin(), downstreamOps.end()); } void StreamProcessingEngine::addInputSource( InputSource* inputSource, std::vector<Operator*> downstreamOps) { // Register the downstream operators with the upstream operator inputSource->downstreamOperators = downstreamOps; // Register the inputSource with other input sources to be scheduled later inputSources.push_back(inputSource); } void StreamProcessingEngine::run() { // Launch all of the input threads inputMonitor = std::thread(&StreamProcessingEngine::launchInputs, this); // Schedule the operators where there is Data remaining bool dataInWorkflow = false; bool receivedDataThisRound = false; do { // Try to execute each operator for (auto opPtr : ops) { opPtr->execute(); } receivedDataThisRound = receivingInput; // If the inputs are done, look for leftover data in the workflow if (!receivedDataThisRound) { dataInWorkflow = false; for (auto opPtr : ops) { if (!opPtr->input.empty()) { dataInWorkflow = true; break; } } } } while (receivedDataThisRound || dataInWorkflow); // Clean up the inputMonitor thread inputMonitor.join(); } void StreamProcessingEngine::launchInputs() { // Launch threads for (auto inputSource : inputSources) inputSource->startThread(); // Join threads for (auto inputSource : inputSources) inputSource->waitForCompletion(); // Flag the operator execution code to signal that no more Data is coming receivingInput = false; }
31.703125
76
0.723509
[ "vector" ]
01d03d931b634fb6f99c72971986834220726fc7
2,851
cpp
C++
modules/media/test/apps/test_create_game_list.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
null
null
null
modules/media/test/apps/test_create_game_list.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
1
2016-01-25T13:03:03.000Z
2016-01-25T13:03:03.000Z
modules/media/test/apps/test_create_game_list.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017 Clyde Stanfield * * 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 <nyra/test/Test.h> #include <nyra/media/CreateGameList.h> #include <nyra/core/Path.h> namespace nyra { namespace media { //===========================================================================// TEST(CreateGameList, Create) { std::vector<Game> games = createGameList(core::DATA_PATH, "mtest", true); bool found[3] = {false, false, false}; for (const Game& game : games) { if (game.name == "game 1") { EXPECT_EQ("game 1.bin", game.filename); EXPECT_EQ("", game.boxArtFile); EXPECT_EQ("", game.videoFile); EXPECT_EQ(std::vector<std::string>(), game.zippedFiles); found[0] = true; } else if (game.name == "game 2") { EXPECT_EQ("game 2.bin", game.filename); EXPECT_EQ("game 2.png", game.boxArtFile); EXPECT_EQ("game 2.mp4", game.videoFile); EXPECT_EQ(std::vector<std::string>(), game.zippedFiles); found[1] = true; } else if (game.name == "game 3") { EXPECT_EQ("game 3.7z", game.filename); EXPECT_EQ("game 3.png", game.boxArtFile); EXPECT_EQ("game 3.mp4", game.videoFile); const std::vector<std::string> expectedZip = { "game 3 (U) [!].bin", "game 3 (U) [b0].bin", "game 3 (U) [b1].bin"}; EXPECT_EQ(expectedZip, game.zippedFiles); found[2] = true; } else { throw std::runtime_error("Found unknown game: " + game.name); } } EXPECT_TRUE(found[0]); EXPECT_TRUE(found[1]); EXPECT_TRUE(found[2]); } } } NYRA_TEST()
34.349398
79
0.598036
[ "vector" ]
01d286b0054ac339b28ebb0d3330c6e743c7a684
2,940
cpp
C++
modules/features/src/ourcvfh_estimator.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
2
2021-02-22T11:36:33.000Z
2021-07-20T11:31:08.000Z
modules/features/src/ourcvfh_estimator.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
null
null
null
modules/features/src/ourcvfh_estimator.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
3
2018-10-19T10:39:23.000Z
2021-04-07T13:39:03.000Z
#include <v4r/features/ourcvfh_estimator.h> #include <glog/logging.h> #include <pcl/search/kdtree.h> #include <v4r/features/pcl_ourcvfh.h> namespace v4r { template <typename PointT> bool OURCVFHEstimator<PointT>::compute(Eigen::MatrixXf &signature) { CHECK(cloud_ && !cloud_->points.empty() && normals_); transforms_.clear(); typename pcl::search::KdTree<PointT>::Ptr kdtree(new pcl::search::KdTree<PointT>); OURCVFHEstimation<PointT, pcl::Normal, pcl::VFHSignature308> ourcvfh; ourcvfh.setMinPoints(param_.min_points_); ourcvfh.setAxisRatio(param_.axis_ratio_); ourcvfh.setMinAxisValue(param_.min_axis_value_); ourcvfh.setNormalizeBins(param_.normalize_bins_); ourcvfh.setRefineClusters(param_.refine_factor_); ourcvfh.setSearchMethod(kdtree); if (!indices_.empty()) { typename pcl::PointCloud<PointT>::Ptr cloud_roi(new pcl::PointCloud<PointT>); typename pcl::PointCloud<pcl::Normal>::Ptr normals_roi(new pcl::PointCloud<pcl::Normal>); pcl::copyPointCloud(*cloud_, indices_, *cloud_roi); pcl::copyPointCloud(*normals_, indices_, *normals_roi); ourcvfh.setInputCloud(cloud_roi); ourcvfh.setInputNormals(normals_roi); } else { ourcvfh.setInputCloud(cloud_); ourcvfh.setInputNormals(normals_); } for (float eps_angle_threshold : param_.eps_angle_threshold_vector_) { for (float curvature_threshold : param_.curvature_threshold_vector_) { for (float cluster_tolerance : param_.cluster_tolerance_vector_) { pcl::PointCloud<pcl::VFHSignature308> cvfh_signatures; ourcvfh.setEPSAngleThreshold(eps_angle_threshold); ourcvfh.setCurvatureThreshold(curvature_threshold); ourcvfh.setClusterTolerance(cluster_tolerance); ourcvfh.compute(cvfh_signatures); std::vector<bool> valid_rolls_tmp; std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f>> transforms_tmp; ourcvfh.getTransforms(transforms_tmp); ourcvfh.getValidTransformsVec(valid_rolls_tmp); size_t kept = 0; for (size_t i = 0; i < valid_rolls_tmp.size(); i++) { if (valid_rolls_tmp[i]) { transforms_tmp[kept] = transforms_tmp[i]; cvfh_signatures.points[kept] = cvfh_signatures.points[i]; kept++; } } transforms_tmp.resize(kept); cvfh_signatures.points.resize(kept); transforms_.insert(transforms_.end(), transforms_tmp.begin(), transforms_tmp.end()); signature = Eigen::MatrixXf(cvfh_signatures.points.size(), 308); for (size_t i = 0; i < cvfh_signatures.points.size(); i++) { for (size_t d = 0; d < 308; d++) signature(i, d) = cvfh_signatures.points[i].histogram[d]; } } } } indices_.clear(); return true; } template class V4R_EXPORTS OURCVFHEstimator<pcl::PointXYZ>; template class V4R_EXPORTS OURCVFHEstimator<pcl::PointXYZRGB>; } // namespace v4r
35.421687
95
0.703061
[ "vector" ]
01e48d127fcb4bc5aafcc631d9ef501bdff7879f
14,682
cpp
C++
test/zoneserver.test/EquipmentTest.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
test/zoneserver.test/EquipmentTest.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
test/zoneserver.test/EquipmentTest.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
#include "ZoneServerTestPCH.h" #include "GameTestFixture.h" #include "MockPlayerItemController.h" #include "MockPlayerInventoryController.h" #include "ZoneServer/model/gameobject/Player.h" #include "ZoneServer/model/gameobject/status/CreatureStatus.h" #include <gideon/servertest/MockProxyGameDatabase.h> #include <gideon/servertest/datatable/DataCodes.h> #include <sne/database/DatabaseManager.h> using gideon::servertest::MockProxyGameDatabase; /** * @class EquipmentTest * * 장비 관련 테스트 */ class EquipmentTest : public GameTestFixture { }; TEST_F(EquipmentTest, testCreatureStatusInfo) { const go::Creature* player1 = static_cast<const go::Creature*>(player1_); const Points maxPoints = player1->getCreatureStatus().getMaxPoints(); ASSERT_TRUE(maxPoints.hp_ > hpDefault); ASSERT_TRUE(maxPoints.mp_ > mpDefault); } TEST_F(EquipmentTest, testEquipItemNotOwned) { const ObjectId notOwnedItemId = invalidObjectId; playerInventoryController1_->equipItem(notOwnedItemId); ASSERT_EQ(1, playerInventoryController1_->getCallCount("onEquipItem")); ASSERT_EQ(0, playerInventoryController2_->getCallCount("onEquipItem")); ASSERT_EQ(ecInventoryItemNotFound, playerInventoryController1_->lastErrorCode_); } TEST_F(EquipmentTest, testEquipItemAlreadyEquipped) { const InventoryInfo inven = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* sword = getItemInfo(inven, servertest::defaultOneHandSwordEquipCode); ASSERT_TRUE(sword != nullptr); playerInventoryController1_->equipItem(sword->itemId_); ASSERT_EQ(1, playerInventoryController1_->getCallCount("onEquipItem")); ASSERT_EQ(0, playerInventoryController2_->getCallCount("onEquipItem")); ASSERT_EQ(ecEquipItemAlreadyEquipped, playerInventoryController1_->lastErrorCode_); } TEST_F(EquipmentTest, testEquipNotEquippedItem) { const InventoryInfo invenBefore = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* shoes = getItemInfo(invenBefore, servertest::shoesEquipCode); ASSERT_TRUE(shoes != nullptr); playerInventoryController1_->equipItem(shoes->itemId_); ASSERT_EQ(0, playerInventoryController1_->getCallCount("onEquipItem")); ASSERT_EQ(0, playerInventoryController2_->getCallCount("onEquipItem")); ASSERT_EQ(1, playerInventoryController1_->getCallCount("evEquipItemReplaced")); ASSERT_EQ(0, playerInventoryController2_->getCallCount("evEquipItemReplaced")); ASSERT_EQ(0, playerInventoryController1_->getCallCount("evItemEquipped")); ASSERT_EQ(1, playerInventoryController2_->getCallCount("evItemEquipped")); ASSERT_EQ(shoes->itemCode_, playerInventoryController2_->lastEquipCode_); const MoreCharacterInfo& characterInfo = player1_->getUnionEntityInfo().asCharacterInfo(); ASSERT_EQ(playerInventoryController2_->lastEquipCode_, characterInfo.equipments_[epShoes]); const InventoryInfo invenAfter = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* shoesAfter = getItemInfo(invenAfter, servertest::shoesEquipCode); ASSERT_TRUE(shoesAfter != nullptr); ASSERT_TRUE(shoesAfter->isEquipped()); sne::database::Guard<MockProxyGameDatabase> db(SNE_DATABASE_MANAGER); ASSERT_EQ(1, db->getCallCount("equipItem")); } TEST_F(EquipmentTest, testUnequipItemNotEquipped) { const InventoryInfo invenBefore = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* shoes = getItemInfo(invenBefore, servertest::shoesEquipCode); ASSERT_TRUE(shoes != nullptr); playerInventoryController1_->unequipItem(shoes->itemId_, invalidSlotId); ASSERT_EQ(1, playerInventoryController1_->getCallCount("onUnequipItem")); ASSERT_EQ(0, playerInventoryController2_->getCallCount("onUnequipItem")); ASSERT_EQ(ecUnequipItemNotEquipped, playerInventoryController1_->lastErrorCode_); } TEST_F(EquipmentTest, testUnequipItem) { const InventoryInfo invenBefore = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* helmet = getItemInfo(invenBefore, servertest::defaultHelmetEquipCode); ASSERT_TRUE(helmet != nullptr); const SlotId firstEmptySlotId = invenBefore.getFirstEmptySlotId(); playerInventoryController1_->unequipItem(helmet->itemId_, firstEmptySlotId); ASSERT_EQ(0, playerInventoryController1_->getCallCount("onUnequipItem")); ASSERT_EQ(0, playerInventoryController2_->getCallCount("onUnequipItem")); ASSERT_EQ(1, playerInventoryController1_->getCallCount("evUnequipItemReplaced")); ASSERT_EQ(0, playerInventoryController2_->getCallCount("evUnequipItemReplaced")); ASSERT_EQ(0, playerInventoryController1_->getCallCount("evItemUnequipped")); ASSERT_EQ(1, playerInventoryController2_->getCallCount("evItemUnequipped")); ASSERT_EQ(helmet->itemCode_, playerInventoryController2_->lastUnequipCode_); ASSERT_EQ(1, playerInventoryController1_->getCallCount("evUnequipItemReplaced")); ASSERT_EQ(0, playerInventoryController1_->getCallCount("evEquipItemReplaced")); ASSERT_EQ(0, playerInventoryController1_->getCallCount("evInventoryWithEquipItemReplaced")); const MoreCharacterInfo& characterInfo = player1_->getUnionEntityInfo().asCharacterInfo(); ASSERT_EQ(playerInventoryController2_->lastEquipCode_, characterInfo.equipments_[epHelmet]); const InventoryInfo invenAfter = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* helmetAfter = getItemInfo(invenAfter, servertest::defaultHelmetEquipCode); ASSERT_TRUE(helmetAfter != nullptr); ASSERT_TRUE(! helmetAfter->isEquipped()); ASSERT_EQ(firstEmptySlotId, playerInventoryController1_->lastUnequippedSlotId_); sne::database::Guard<MockProxyGameDatabase> db(SNE_DATABASE_MANAGER); ASSERT_EQ(1, db->getCallCount("unequipItem")); } TEST_F(EquipmentTest, testEquipSamePartItem) { const InventoryInfo invenBefore = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* otherHelmet = getItemInfo(invenBefore, servertest::otherHelmetEquipCode); ASSERT_TRUE(otherHelmet != nullptr); playerInventoryController1_->equipItem(otherHelmet->itemId_); ASSERT_EQ(0, playerInventoryController1_->getCallCount("onEquipItem")); ASSERT_EQ(0, playerInventoryController2_->getCallCount("onEquipItem")); ASSERT_EQ(0, playerInventoryController1_->getCallCount("evItemEquipped")); ASSERT_EQ(1, playerInventoryController2_->getCallCount("evItemEquipped")); ASSERT_EQ(0, playerInventoryController1_->getCallCount("evUnequipItemReplaced")); ASSERT_EQ(0, playerInventoryController1_->getCallCount("evEquipItemReplaced")); ASSERT_EQ(1, playerInventoryController1_->getCallCount("evInventoryWithEquipItemReplaced")); ASSERT_EQ(otherHelmet->itemCode_, playerInventoryController2_->lastEquipCode_); const MoreCharacterInfo& characterInfo = player1_->getUnionEntityInfo().asCharacterInfo(); ASSERT_EQ(playerInventoryController2_->lastEquipCode_, characterInfo.equipments_[epHelmet]); const InventoryInfo invenAfter = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* helmetAfter = getItemInfo(invenAfter, servertest::otherHelmetEquipCode); ASSERT_TRUE(helmetAfter != nullptr); ASSERT_TRUE(helmetAfter->isEquipped()); const ItemInfo* helmetBefore = getItemInfo(invenAfter, servertest::defaultHelmetEquipCode); ASSERT_TRUE(helmetBefore != nullptr); ASSERT_TRUE(! helmetBefore->isEquipped()); // TODO: switch 호출로 바꿀것 //sne::database::Guard<MockProxyGameDatabase> db(SNE_DATABASE_MANAGER); //ASSERT_EQ(1, db->getCallCount("unequipItem")); //ASSERT_EQ(1, db->getCallCount("equipItem")); } TEST_F(EquipmentTest, testEquipTwoHandItem) { const InventoryInfo invenBefore = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* spear = getItemInfo(invenBefore, servertest::lanceEquipCode); ASSERT_TRUE(spear != nullptr); playerInventoryController1_->equipItem(spear->itemId_); ASSERT_EQ(0, playerInventoryController1_->getCallCount("onEquipItem")); ASSERT_EQ(0, playerInventoryController2_->getCallCount("onEquipItem")); ASSERT_EQ(0, playerInventoryController1_->getCallCount("evItemEquipped")); ASSERT_EQ(1, playerInventoryController2_->getCallCount("evItemEquipped")); ASSERT_EQ(1, playerInventoryController1_->getCallCount("evUnequipItemReplaced")); ASSERT_EQ(0, playerInventoryController1_->getCallCount("evEquipItemReplaced")); ASSERT_EQ(1, playerInventoryController1_->getCallCount("evInventoryWithEquipItemReplaced")); ASSERT_EQ(spear->itemCode_, playerInventoryController2_->lastEquipCode_); const MoreCharacterInfo& characterInfo = player1_->getUnionEntityInfo().asCharacterInfo(); ASSERT_EQ(playerInventoryController2_->lastEquipCode_, characterInfo.equipments_[epTwoHands]); const InventoryInfo invenAfter = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* spearAfter = getItemInfo(invenAfter, servertest::lanceEquipCode); ASSERT_TRUE(spearAfter != nullptr); ASSERT_TRUE(spearAfter->isEquipped()); const ItemInfo* leftHandBefore = getItemInfo(invenAfter, servertest::defaultShieldEquipCode); ASSERT_TRUE(leftHandBefore != nullptr); ASSERT_TRUE(! leftHandBefore->isEquipped()); const ItemInfo* rightHandBefore = getItemInfo(invenAfter, servertest::defaultOneHandSwordEquipCode); ASSERT_TRUE(rightHandBefore != nullptr); ASSERT_TRUE(! rightHandBefore->isEquipped()); sne::database::Guard<MockProxyGameDatabase> db(SNE_DATABASE_MANAGER); ASSERT_EQ(1, db->getCallCount("unequipItem")); ASSERT_EQ(1, db->getCallCount("replaceInventoryWithEquipItem")); } TEST_F(EquipmentTest, testUnequipTwoHandItem) { const InventoryInfo invenBefore = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* spear = getItemInfo(invenBefore, servertest::lanceEquipCode); ASSERT_TRUE(spear != nullptr); playerInventoryController1_->equipItem(spear->itemId_); playerInventoryController1_->unequipItem(spear->itemId_, invalidSlotId); ASSERT_EQ(0, playerInventoryController1_->getCallCount("onUnequipItem")); ASSERT_EQ(0, playerInventoryController2_->getCallCount("onUnequipItem")); ASSERT_EQ(1 + 1, playerInventoryController1_->getCallCount("evUnequipItemReplaced")); ASSERT_EQ(0, playerInventoryController1_->getCallCount("evEquipItemReplaced")); ASSERT_EQ(1, playerInventoryController1_->getCallCount("evInventoryWithEquipItemReplaced")); ASSERT_EQ(0, playerInventoryController1_->getCallCount("evItemUnequipped")); ASSERT_EQ(1, playerInventoryController2_->getCallCount("evItemUnequipped")); ASSERT_EQ(spear->itemCode_, playerInventoryController2_->lastUnequipCode_); const MoreCharacterInfo& characterInfo = player1_->getUnionEntityInfo().asCharacterInfo(); ASSERT_EQ(invalidEquipCode, characterInfo.equipments_[epTwoHands]); ASSERT_EQ(invalidEquipCode, characterInfo.equipments_[epLeftHand]); ASSERT_EQ(invalidEquipCode, characterInfo.equipments_[epRightHand]); const InventoryInfo invenAfter = player1_->queryInventoryable()->getInventoryInfo(); const ItemInfo* spearAfter = getItemInfo(invenAfter, servertest::lanceEquipCode); ASSERT_TRUE(spearAfter != nullptr); ASSERT_TRUE(! spearAfter->isEquipped()); sne::database::Guard<MockProxyGameDatabase> db(SNE_DATABASE_MANAGER); ASSERT_EQ(2, db->getCallCount("unequipItem")); ASSERT_EQ(0, db->getCallCount("equipItem")); ASSERT_EQ(1, db->getCallCount("replaceInventoryWithEquipItem")); // TODO: db switch 추가 } TEST_F(EquipmentTest, testMakeEquipItemTest) { //const uint8_t oneHandSwordFragmentCount = 46; //const SlotId slotId = 17; //BaseItemInfo fragmentItem(servertest::oneHandSwordFragmentCode, oneHandSwordFragmentCount); //playerItemController1_->makeEquipItem(servertest::upgradeOneHandSwordEquipCode); //ASSERT_EQ(ecItemNotMakeEquipItem, playerItemController1_->lastErrorCode_); //ASSERT_EQ(1, playerItemController1_->getCallCount("onMakeEquipItem")); //playerItemController1_->makeEquipItem(servertest::defaultOneHandSwordEquipCode); //ASSERT_EQ(ecItemNotEnoughFragmentItem, playerItemController1_->lastErrorCode_); //ASSERT_EQ(2, playerItemController1_->getCallCount("onMakeEquipItem")); //ASSERT_TRUE(playerInventoryController1_->addInventoryItem(fragmentItem, slotId)); //const InventoryInfo beforeInven = player1_->queryInventoryable()->getInventoryInfo(); //playerItemController1_->makeEquipItem(servertest::defaultOneHandSwordEquipCode); //ASSERT_EQ(ecOk, playerItemController1_->lastErrorCode_); //ASSERT_EQ(3, playerItemController1_->getCallCount("onMakeEquipItem")); //ASSERT_EQ(1, playerInventoryController1_->getCallCount("evInventoryItemCountUpdated")); //ASSERT_EQ(1, playerInventoryController1_->getCallCount("evInventoryEquipItemAdded")); //const InventoryInfo afterInven = player1_->queryInventoryable()->getInventoryInfo(); //ASSERT_EQ(beforeInven.items_.size() + 1, afterInven.items_.size()); } TEST_F(EquipmentTest, testUpdateEquipItem) { // TODO: 테스트 복구 (2019-03-26) //const uint8_t oneHandSwordFragmentCount = 46; //const SlotId slotId = 17; //BaseItemInfo fragmentItem(servertest::oneHandSwordFragmentCode, oneHandSwordFragmentCount); //ASSERT_TRUE(playerInventoryController1_->addInventoryItem(fragmentItem, slotId)); //const InventoryInfo beforeInven = player1_->queryInventoryable()->getInventoryInfo(); //const ItemInfo* defaultSword = getItemInfo(beforeInven, // servertest::defaultOneHandSwordEquipCode); //ASSERT_TRUE(defaultSword != nullptr); //const ItemInfo* fragment = getItemInfo(beforeInven, // servertest::oneHandSwordFragmentCode); //ASSERT_TRUE(fragment != nullptr); //for (int i = 0; i < 5; ++i) { // playerItemController1_->upgradeEquipItem(GameObjectInfo(), defaultSword->itemId_, fragment->itemId_); // ASSERT_EQ(ecOk, playerItemController1_->lastErrorCode_); //} //playerItemController1_->upgradeEquipItem(GameObjectInfo(), defaultSword->itemId_, fragment->itemId_); //ASSERT_EQ(ecItemMaxUpgradeEquipItem, playerItemController1_->lastErrorCode_); //const InventoryInfo afterInven = player1_->queryInventoryable()->getInventoryInfo(); //const ItemInfo* upgradeSword = getItemInfo(afterInven, // servertest::upgradeOneHandSwordEquipCode); //ASSERT_TRUE(upgradeSword != nullptr); }
43.566766
111
0.771285
[ "model" ]
01e4ccc73c85cbf687432cd73c2b308217904b6e
2,177
cpp
C++
Shapes/shapes.cpp
MorganM99/LearnCPP
338259165f27e854c87e427d218d6d25a49eafa9
[ "MIT" ]
null
null
null
Shapes/shapes.cpp
MorganM99/LearnCPP
338259165f27e854c87e427d218d6d25a49eafa9
[ "MIT" ]
null
null
null
Shapes/shapes.cpp
MorganM99/LearnCPP
338259165f27e854c87e427d218d6d25a49eafa9
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> class Point { private: int m_x = 0; int m_y = 0; int m_z = 0; public: Point (int x = 0, int y = 0, int z = 0) : m_x (x), m_y (y), m_z (z) {} friend std::ostream& operator<< (std::ostream& out, const Point& p) { out << "Point(" << p.m_x << ", " << p.m_y << ", " << p.m_z << ")"; return out; } }; class Shape { public: Shape() {} virtual std::ostream& print (std::ostream& out) const = 0; friend std::ostream& operator<< (std::ostream& out, const Shape& s) { return s.print (out); } virtual ~Shape() {} }; class Triangle : public Shape { private: Point m_point1; Point m_point2; Point m_point3; public: Triangle (const Point& point1, const Point& point2, const Point& point3) : m_point1 {point1}, m_point2 {point2}, m_point3 {point3} {} virtual std::ostream& print (std::ostream& out) const override { out << "Triangle (" << m_point1 << ", " << m_point2 << ", " << m_point3 << ")" << "\n"; return out; } }; class Circle : public Shape { private: Point m_centre; int m_radius; public: Circle (const Point& centre, int radius = 1) : m_centre {centre}, m_radius {radius} {} virtual std::ostream& print (std::ostream& out) const override { out << "Circle (" << m_centre << ", " << "radius " << m_radius << ")" << "\n"; return out; } int getRadius() const { return m_radius; } }; int getLargestRadius (const std::vector<Shape*>& v) { int largestRadius {0}; for (auto const element : v) { if (Circle* c = dynamic_cast<Circle*> (element)) { if (c->getRadius() > largestRadius) { largestRadius = c->getRadius(); } } } return largestRadius; } int main() { std::vector<Shape*> v; v.push_back (new Circle (Point (1, 2, 3), 7)); v.push_back ( new Triangle (Point (1, 2, 3), Point (4, 5, 6), Point (7, 8, 9))); v.push_back (new Circle (Point (4, 5, 6), 3)); for (auto const element : v) { std::cout << *element; } std::cout << "The largest radius is: " << getLargestRadius (v) << '\n'; for (auto const element : v) { delete element; } return 0; }
23.923077
77
0.5774
[ "shape", "vector" ]
01e57c0cf00ecc722e41ce1907a0e91c98d8ae52
762
cpp
C++
InputManagerComponent.cpp
mado0421/3DGameProgramming_LongTermProject
0802a511dd55dc40f52ad5701f3200cfc4903125
[ "MIT" ]
1
2022-03-08T04:04:14.000Z
2022-03-08T04:04:14.000Z
InputManagerComponent.cpp
druid0228/3DGameProgramming_LongTermProject
c37f43fa9dcb5d2774eded3665800340ddd0189c
[ "MIT" ]
null
null
null
InputManagerComponent.cpp
druid0228/3DGameProgramming_LongTermProject
c37f43fa9dcb5d2774eded3665800340ddd0189c
[ "MIT" ]
1
2022-03-08T03:42:57.000Z
2022-03-08T03:42:57.000Z
#include "stdafx.h" #include "Components.h" #include "Object.h" InputManagerComponent::InputManagerComponent(Object* pObject) :Component(pObject) , m_xmf2MouseMovement(0, 0) { } InputManagerComponent::~InputManagerComponent() { } void InputManagerComponent::InputEvent(UCHAR* pKeyBuffer, XMFLOAT2& xmf2MouseMovement) { memcpy(m_pKeysBuffer, pKeyBuffer, sizeof(UCHAR) * 256); m_xmf2MouseMovement = xmf2MouseMovement; } void InputManagerComponent::Update(float fTimeElapsed) { } bool InputManagerComponent::IsKeyDown(KeyCode key) { return (m_pKeysBuffer[key] & 0xF0); } bool InputManagerComponent::IsKeyUp(KeyCode key) { return !(m_pKeysBuffer[key] & 0xF0); } const XMFLOAT2& InputManagerComponent::GetMouseMovement() { return m_xmf2MouseMovement; }
19.538462
86
0.78084
[ "object" ]
54353b54307cbfcccaafc27f8aef2643d0e49694
6,132
cpp
C++
qSAF.cpp
huihut/qSAF
0ee4919c020e8a1e109be8f8f28674d575f07202
[ "MIT" ]
11
2017-11-23T09:14:15.000Z
2021-12-13T06:13:12.000Z
qSAF.cpp
huihut/qSAF
0ee4919c020e8a1e109be8f8f28674d575f07202
[ "MIT" ]
null
null
null
qSAF.cpp
huihut/qSAF
0ee4919c020e8a1e109be8f8f28674d575f07202
[ "MIT" ]
9
2017-11-20T12:44:53.000Z
2021-01-13T02:14:45.000Z
//########################################################################## //# # //# CLOUDCOMPARE PLUGIN: qSAF # //# # //# 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; version 2 of the License. # //# # //# 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. # //# # //# COPYRIGHT: XXX # //# # //########################################################################## #include "qSAF.h" //Qt #include <QtGui> #include <QApplication> #include <QProgressDialog> #include <QMainWindow> #include <QElapsedTimer> //Dialog #include "ccSAFDlg.h" //System #include <iostream> #include <vector> #include <string> #include <assert.h> //qCC_db #include <ccGenericPointCloud.h> #include <ccPointCloud.h> #include <ccProgressDialog.h> //CC #include <ScalarField.h> qSAF::qSAF(QObject* parent/*=0*/) : QObject(parent) , m_action(0) { } void qSAF::onNewSelection(const ccHObject::Container& selectedEntities) { if (m_action) m_action->setEnabled(selectedEntities.size()==1 && selectedEntities[0]->isA(CC_TYPES::POINT_CLOUD)); } void qSAF::getActions(QActionGroup& group) { if (!m_action) { m_action = new QAction(getName(),this); m_action->setToolTip(getDescription()); m_action->setIcon(getIcon()); //connect appropriate signal connect(m_action, SIGNAL(triggered()), this, SLOT(doAction())); } group.addAction(m_action); } void qSAF::doAction() { //m_app should have already been initialized by CC when plugin is loaded! //(--> pure internal check) assert(m_app); if (!m_app) return; const ccHObject::Container& selectedEntities = m_app->getSelectedEntities(); size_t selNum = selectedEntities.size(); if (selNum != 1) { m_app->dispToConsole("[SAF] Select only one cloud!", ccMainAppInterface::ERR_CONSOLE_MESSAGE); return; } ccHObject* ent = selectedEntities[0]; assert(ent); if (!ent || !ent->isA(CC_TYPES::POINT_CLOUD)) { m_app->dispToConsole("[SAF] Select a real point cloud!", ccMainAppInterface::ERR_CONSOLE_MESSAGE); return; } //to get the point cloud from selected entity. ccPointCloud* pc = static_cast<ccPointCloud*>(ent); //Number of points unsigned count = pc->size(); //initial dialog parameters static double threshold_1 = 20; static double threshold_2 = 70; double threshold_temp = 0; //display the dialog { ccSAFDlg safDlg(m_app->getMainWindow()); safDlg.doubleSpinBox_1->setValue(threshold_1); safDlg.doubleSpinBox_2->setValue(threshold_2); if(!safDlg.exec()) { return; } //save the parameters for next time threshold_1 = safDlg.doubleSpinBox_1->value(); threshold_2 = safDlg.doubleSpinBox_2->value(); } //display the progress dialog QProgressDialog pDlg; pDlg.setWindowTitle("SAF"); pDlg.setLabelText(QString("Scan Angle Filter\nfrom %1 to %2").arg(threshold_1).arg(threshold_2)); //pDlg.setRange(0, count); pDlg.setCancelButton(0); pDlg.show(); QApplication::processEvents(); QElapsedTimer timer; timer.start(); ScalarType scanAngle; CCLib::ReferenceCloud rangeAnglerc(pc); //To ensure that threshold_1 is less than threshold_2 if(threshold_1 > threshold_2) { threshold_temp = threshold_1; threshold_1 = threshold_2; threshold_2 = threshold_temp; } //Index of Scan Angle Rank int scanAngleSFIndex = pc->getScalarFieldIndexByName("Scan Angle Rank"); for(unsigned i = 0; i < count; ++i) { //Get the scan angle for each point scanAngle = pc->getScalarField(scanAngleSFIndex)->getValue(i); //absolute if(scanAngle < 0) { scanAngle = -scanAngle; } //Gets the index of the point within the range if(threshold_1 <= scanAngle && scanAngle <= threshold_2) { rangeAnglerc.addPointIndex(i); } } //partialClone ReferenceCloud to ccPointCloud ccPointCloud* rangeAnglepc = pc->partialClone(&rangeAnglerc); //Whether the rangeAnglepc is null if(!rangeAnglepc) { m_app->dispToConsole("[SAF] Failed to extract the range angle subset.", ccMainAppInterface::ERR_CONSOLE_MESSAGE); return; } //Count the percentage of filtered and spend time m_app->dispToConsole(QString("[SAF] %1% of scan angle points are filtered").arg((rangeAnglerc.size() * 100.0) / count, 0, 'f', 2), ccMainAppInterface::STD_CONSOLE_MESSAGE); m_app->dispToConsole(QString("[SAF] Timing: %1 s.").arg(timer.elapsed() / 1000.0, 0, 'f', 1), ccMainAppInterface::STD_CONSOLE_MESSAGE); //close the process dialog pDlg.close(); QApplication::processEvents(); //hide the original cloud pc->setEnabled(false); //we add new group to DB/display ccHObject* cloudContainer = new ccHObject(pc->getName() + QString("_saf")); //rangeAnglepc rangeAnglepc->setVisible(true); rangeAnglepc->setName("SAF Point Cloud"); cloudContainer->addChild(rangeAnglepc); //add cloudContainer To DBTree m_app->addToDB(cloudContainer); //refresh m_app->refreshAll(); } QIcon qSAF::getIcon() const { return QIcon(":/CC/plugin/qSAF/icon.png"); }
29.623188
176
0.591161
[ "vector" ]
5441603202da0131ebef1e7ce97cd6a646cf670a
1,147
cpp
C++
CookOff/03_20/MYSARA.cpp
vinaysomawat/CodeChef-Solutions
9a0666a4f1badd593cd075f3beb05377e3c6657a
[ "MIT" ]
1
2020-04-12T01:39:10.000Z
2020-04-12T01:39:10.000Z
CookOff/03_20/MYSARA.cpp
vinaysomawat/CodeChef-Solutions
9a0666a4f1badd593cd075f3beb05377e3c6657a
[ "MIT" ]
null
null
null
CookOff/03_20/MYSARA.cpp
vinaysomawat/CodeChef-Solutions
9a0666a4f1badd593cd075f3beb05377e3c6657a
[ "MIT" ]
null
null
null
/* Contest: CodeChef March 2020 Cook-Off challange Problem link:https://www.codechef.com/COOK116B/problems/MYSARA GitHub Solution Repository: https://github.com/vinaysomawat/CodeChef-Solutions Author: Vinay Somawat Author's Webpage: http://vinaysomawat.github.io/ Author's mail: vinaysomawat@hotmail.com */ #include<bits/stdc++.h> #define ll long long int #define mod 1000000007 using namespace std; void solve() { ll n,temp; cin>>n; vector<ll> v; for(int i=0;i<n;i++) { cin>>temp; v.push_back(temp); } ll ans=1; for(int i=0;i<n-1;i++) { if((v[i]&v[i+1])==v[i]) { ll k =v[i]; int p=0; while(k>0) { if(k%2==1) { p++; } k/=2; } ans*=pow(2,p); ans = ans%mod; p=0; } else { ans=0; break; } } cout<<ans%mod<<endl; } int main() { int t; cin>>t; while(t--) { solve(); } return 0; }
18.5
82
0.44551
[ "vector" ]
5446a3e2cb02734ba742ad0764c0bbacb1ef395f
7,420
cpp
C++
src/cpp/shopping_plan.cpp
elemel/code-jam
da4b3d250013489e3781e00cdd198f7b1ccd6c99
[ "MIT" ]
1
2016-05-08T18:55:42.000Z
2016-05-08T18:55:42.000Z
src/cpp/shopping_plan.cpp
elemel/code-jam
da4b3d250013489e3781e00cdd198f7b1ccd6c99
[ "MIT" ]
null
null
null
src/cpp/shopping_plan.cpp
elemel/code-jam
da4b3d250013489e3781e00cdd198f7b1ccd6c99
[ "MIT" ]
null
null
null
#include <algorithm> #include <cassert> #include <cctype> #include <cmath> #include <iomanip> #include <iostream> #include <map> #include <sstream> #include <string> #include <utility> #include <vector> using std::cin; using std::cout; using std::endl; using std::fixed; using std::getline; using std::istream; using std::istringstream; using std::make_pair; using std::map; using std::min; using std::pair; using std::setprecision; using std::sqrt; using std::string; using std::vector; istringstream& read_line(istream& in, istringstream& line) { string str; getline(in, str); line.clear(); line.str(str); return line; } string strip(const string& str) { string::const_iterator first = str.begin(); string::const_iterator last = str.end(); while (first != last && isspace(*first)) { ++first; } while (first != last && isspace(*(last - 1))) { --last; } return string(first, last); } struct context_type { typedef vector<double> gas_cost_vector; typedef pair<int, int> position_type; typedef vector<int> price_list_type; typedef vector<double> min_cost_vector; int item_count; int store_count; int gas_price; vector<string> item_names; int perishables; vector<gas_cost_vector> gas_costs; vector<position_type> positions; vector<price_list_type> price_lists; vector<int> inventories; vector<min_cost_vector> min_costs; context_type() : item_count(0), store_count(0), gas_price(0), perishables(0) { } }; int parse_case_count(istream& in) { istringstream line; int case_count = 0; read_line(in, line) >> case_count; return case_count; } void parse_case_args(istream& in, context_type& context) { istringstream line; read_line(in, line) >> context.item_count >> context.store_count >> context.gas_price; } void parse_items(istream& in, context_type& context) { istringstream line; read_line(in, line); for (int item = 0; item < context.item_count; ++item) { string item_arg; line >> item_arg; item_arg = strip(item_arg); if (item_arg[item_arg.size() - 1] == '!') { item_arg.resize(item_arg.size() - 1); context.perishables |= 1 << item; } context.item_names.push_back(item_arg); } } void parse_stores(istream& in, context_type& context) { istringstream line; for (int store = 0; store < context.store_count; ++store) { int x = 0, y = 0; map<string, int> prices; context_type::price_list_type price_list(context.item_count, -1); int inventory = 0; read_line(in, line); line >> x >> y; for (;;) { string item_name; int price = -1; getline(line, item_name, ':'); item_name = strip(item_name); line >> price; if (price == -1) { break; } prices[item_name] = price; } for (int item = 0; item < context.item_count; ++item) { map<string, int>::iterator found = prices.find(context.item_names[item]); if (found != prices.end()) { price_list[item] = found->second; inventory |= 1 << item; } } context.positions.push_back(make_pair(x, y)); context.price_lists.push_back(price_list); context.inventories.push_back(inventory); } } void parse_case(istream& in, context_type& context) { parse_case_args(in, context); parse_items(in, context); parse_stores(in, context); } void precalc_gas_costs(context_type& context) { for (int store = 0; store <= context.store_count; ++store) { context.gas_costs.resize(context.gas_costs.size() + 1); int store_x = context.positions[store].first; int store_y = context.positions[store].second; for (int dest = 0; dest <= context.store_count; ++dest) { int dest_x = context.positions[dest].first; int dest_y = context.positions[dest].second; int dx = dest_x - store_x, dy = dest_y - store_y; double dist = sqrt(double(dx * dx + dy * dy)); context.gas_costs[store].push_back(context.gas_price * dist); } } } void prealloc_min_costs(context_type& context) { typedef context_type::min_cost_vector min_cost_vector; context.min_costs.resize(2 * (context.store_count + 1), min_cost_vector(1 << context.item_count, -1)); } double min_cost(int store, int items, bool perishing, context_type& context); double calc_min_cost(int store, int items, bool perishing, context_type& context) { if (!items) { // We are done shopping. return context.gas_costs[store][context.store_count]; } else if (perishing) { // Return to the house... double result = context.gas_costs[store][context.store_count] + min_cost(context.store_count, items, false, context); // ...or buy something more here. if (int inventory = items & context.inventories[store]) { for (int item = 0; item < context.item_count; ++item) { if (inventory & (1 << item)) { double cost = context.price_lists[store][item] + min_cost(store, items & ~(1 << item), true, context); result = min(cost, result); } } } return result; } else { // Buy something at a store. double result = -1; for (int dest = 0; dest < context.store_count; ++dest) { if (int inventory = items & context.inventories[dest]) { for (int item = 0; item < context.item_count; ++item) { if (inventory & (1 << item)) { double cost = context.gas_costs[store][dest] + context.price_lists[dest][item] + min_cost(dest, items & ~(1 << item), bool(context.perishables & (1 << item)), context); if (result < 0 || cost < result) { result = cost; } } } } } assert(result >= 0); return result; } } double min_cost(int store, int items, bool perishing, context_type& context) { int key = store << 1 | perishing; double result = context.min_costs[key][items]; if (result < 0) { result = calc_min_cost(store, items, perishing, context); context.min_costs[key][items] = result; } return result; } double min_cost(context_type& context) { return min_cost(context.store_count, (1 << context.item_count) - 1, false, context); } int main() { cout << fixed << setprecision(7); int case_count = parse_case_count(cin); for (int case_ = 0; case_ < case_count; ++case_) { context_type context; parse_case(cin, context); context.positions.push_back(make_pair(0, 0)); precalc_gas_costs(context); prealloc_min_costs(context); cout << "Case #" << case_ + 1 << ": " << min_cost(context) << endl; } return 0; }
29.919355
79
0.573585
[ "vector" ]
544fe1b22cd9ec6989f4d8049efc07dce828d7ac
3,187
cpp
C++
10901 Ferry Loading III.cpp
zihadboss/UVA-Solutions
020fdcb09da79dc0a0411b04026ce3617c09cd27
[ "Apache-2.0" ]
86
2016-01-20T11:36:50.000Z
2022-03-06T19:43:14.000Z
10901 Ferry Loading III.cpp
Mehedishihab/UVA-Solutions
474fe3d9d9ba574b97fd40ca5abb22ada95654a1
[ "Apache-2.0" ]
null
null
null
10901 Ferry Loading III.cpp
Mehedishihab/UVA-Solutions
474fe3d9d9ba574b97fd40ca5abb22ada95654a1
[ "Apache-2.0" ]
113
2015-12-04T06:40:57.000Z
2022-02-11T02:14:28.000Z
#include <iostream> #include <queue> using namespace std; int charToSide[128]; int main() { charToSide['l'] = 0; charToSide['r'] = 1; int T; cin >> T; string sep = "", sideStr; while (T--) { cout << sep; sep = "\n"; int maxLoad, crossTime, totalNumCars; cin >> maxLoad >> crossTime >> totalNumCars; vector<long long> leaveTime(totalNumCars); queue<int> lines[2]; long long currentTime = 0, lastCarTime = -1; int currentSide = 0, numCarsLoaded = 0; cin >> lastCarTime >> sideStr; while (numCarsLoaded < totalNumCars) { // Want to: // Load cars until their time is > the current time // If there are no cars waiting, then change time to be that cars arrival time // If the time was > currentTime, then will be going to other side immediately if (lastCarTime <= currentTime) { // The most recent car loaded would NOT be added immediately lines[charToSide[sideStr[0]]].push(numCarsLoaded); ++numCarsLoaded; // What this should do is load in until it has while (numCarsLoaded < totalNumCars && cin >> lastCarTime >> sideStr && lastCarTime <= currentTime) { lines[charToSide[sideStr[0]]].push(numCarsLoaded); ++numCarsLoaded; } } else if (lines[0].empty() && lines[1].empty()) // Need to go to the future time, cause no cars remaining { currentTime = lastCarTime; lines[charToSide[sideStr[0]]].push(numCarsLoaded); ++numCarsLoaded; while (numCarsLoaded < totalNumCars && cin >> lastCarTime >> sideStr && lastCarTime <= currentTime) { lines[charToSide[sideStr[0]]].push(numCarsLoaded); ++numCarsLoaded; } } // Handle transferring cars over for (int i = 0; i < maxLoad && !lines[currentSide].empty(); ++i) { int carNum = lines[currentSide].front(); lines[currentSide].pop(); leaveTime[carNum] = currentTime + crossTime; } currentSide = 1 - currentSide; currentTime += crossTime; } // While there are cars left, cross back and forth while (!lines[0].empty() || !lines[1].empty()) { for (int i = 0; i < maxLoad && !lines[currentSide].empty(); ++i) { int carNum = lines[currentSide].front(); lines[currentSide].pop(); leaveTime[carNum] = currentTime + crossTime; } currentSide = 1 - currentSide; currentTime += crossTime; } for (int i = 0; i < totalNumCars; ++i) { cout << leaveTime[i] << '\n'; } } }
32.520408
116
0.48133
[ "vector" ]
5451b39932c81ecfb84ab96ec9787a56616ed3cf
9,719
cpp
C++
ROVER/src/sensor/gps.cpp
majitaki/arliss2019_tadpole
22c2f976dfb91d345a6be878a45bcd361247943b
[ "MIT" ]
null
null
null
ROVER/src/sensor/gps.cpp
majitaki/arliss2019_tadpole
22c2f976dfb91d345a6be878a45bcd361247943b
[ "MIT" ]
null
null
null
ROVER/src/sensor/gps.cpp
majitaki/arliss2019_tadpole
22c2f976dfb91d345a6be878a45bcd361247943b
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <sstream> #include<picojson.h> #include <wiringPiI2C.h> #include <wiringPi.h> #include <time.h> #include <string.h> #include <fstream> #include <sstream> #include <unistd.h> #include <stdlib.h> #include <math.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <stdarg.h> #include <wiringSerial.h> #include <iostream> #include <iomanip> #include <ctime> #include <sstream> #include <libgpsmm.h> #include "gps.h" #include "../rover_util/utils.h" #include "gps_constant.h" #define _USE_MATH_DEFINE GPSSensor gGPSSensor; bool GPSSensor::onInit(const struct timespec& time) { mLastUpdateTime = time; mLastGetNewDataTime = time; mLastGetRemoveTime = time; mErrorFlag = true; if (gps_rec.stream(WATCH_ENABLE | WATCH_JSON) == NULL) { Debug::print(LOG_SUMMARY, "Failed to setup GPS Sensor\r\n"); return false; } Debug::print(LOG_SUMMARY, "GPS Sensor is Ready! \n"); mPos.x = mPos.y = mPos.z = 0; mIsNewData = false; mIsLogger = false; mRemoveErrorFlag = true; mUseMeanFlag = false; mClassMeanFlag = false; mSettingSampleNum = GPS_SAMPLES; mSettingStuckTh = GPS_STUCK_THRESHOLD; if(!readJSON()){ mSettingSampleNum = GPS_SAMPLES; mSettingStuckTh = GPS_STUCK_THRESHOLD; } return true; } bool GPSSensor::readJSON() { // JSONデータの読み込み。 std::ifstream ifs("../setting/gps.json", std::ios::in); if (ifs.fail()) { Debug::print(LOG_SUMMARY, "Failed to read GPS JSON\r\n"); return false; } const std::string json((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); ifs.close(); // JSONデータを解析する。 picojson::value v; const std::string err = picojson::parse(v, json); if (err.empty() == false) { std::cerr << err << std::endl; return false; } picojson::object& obj = v.get<picojson::object>(); mSettingStuckTh = obj["gps_stuck_threshold"].get<double>(); mSettingSampleNum = (int)obj["gps_sample_num"].get<double>(); return true; } void GPSSensor::onClean() { } void GPSSensor::onUpdate(const struct timespec& time) { double dt = Time::dt(time, mLastUpdateTime); if (dt < GPS_UPDATE_INTERVAL_TIME)return; mLastUpdateTime = time; mIsNewData = false; //remove old sample double dt_get_new = Time::dt(time, mLastGetNewDataTime); if (dt_get_new > GPS_REMOVE_UPDATE_INTERVAL_TIME && !mLastPos.empty()) { Debug::print(LOG_SUMMARY, "remove old\r\n"); mLastPos.pop_back();//remove most old } if ((newdata = gps_rec.read()) != NULL) { mPos.x = newdata->fix.latitude; mPos.y = newdata->fix.longitude; mPos.z = newdata->fix.altitude; mSatelites = newdata->satellites_visible; mGpsSpeed = newdata->fix.speed; mGpsCourse = newdata->fix.track; if (mSatelites > 0) mGpsTime = newdata->fix.time; //samples input if (finite(mPos.x) && finite(mPos.y) && finite(mPos.z)) { mLastPos.push_front(mPos); mIsNewData = true; mLastGetNewDataTime = time; if (mLastPos.size() > mSettingSampleNum) { mLastPos.pop_back(); } } } double dt_remove_error = Time::dt(time, mLastGetRemoveTime); if ((dt_remove_error > GPS_REMOVE_ERROR_INTERVAL_TIME && !mLastPos.empty()) || mErrorFlag) { //Debug::print(LOG_SUMMARY, "error check \r\n"); //remove error //removeAveNewErrorSample();//remove new error removeErrorSample();//remove sample error mLastGetRemoveTime = time; } if (mIsLogger) showState(); return; } bool GPSSensor::onCommand(const std::vector<std::string>& args) { if (args[0].compare(getName()) != 0) return true; switch (args.size()) { case 1: Debug::print(LOG_PRINT, "\r\n\ gps view : gps view start/stop\r\n\ gps rem_error : remove error true/false\r\n\n\ "); showState(); return true; case 2: if (args[1].compare("view") == 0) { mIsLogger = !mIsLogger; } else if (args[1].compare("rem_error") == 0) { mRemoveErrorFlag = !mRemoveErrorFlag; } return true; default: return false; } } bool GPSSensor::get(VECTOR3& pos, bool disableNewFlag) { VECTOR3 new_pos = mLastPos.front(); if (mSatelites >= 4 && !(new_pos.x == 0 && new_pos.y == 0 && new_pos.z == 0))//3D fix { if (!disableNewFlag)mIsNewData = false; pos = new_pos; return true; } return false;//Invalid Position } double GPSSensor::getPosx() const { return mPos.x; } double GPSSensor::getPosy() const { return mPos.y; } double GPSSensor::getPosz() const { return mPos.z; } bool GPSSensor::isNewPos() const { return mIsNewData; } int GPSSensor::getTime() const { return mGpsTime; } float GPSSensor::getCourse() const { return mGpsCourse; //return NineAxisSensor::normalize(mGpsCourse); } float GPSSensor::getSpeed() const { return mGpsSpeed; } bool GPSSensor::removeErrorSample() { VECTOR3 ave_pos; if (!mRemoveErrorFlag) return false; if (!getAvePos(ave_pos)) return false; if (mLastPos.size() <= mSettingSampleNum / 2) return false; //mLastPos.unique(); auto it = mLastPos.rbegin(); mErrorFlag = false; int count = 0; while (it != mLastPos.rend()) { if (VECTOR3::calcDistanceXY(ave_pos, *it) > GPS_ERROR_AVE_IT_THRESHOLD) { Debug::print(LOG_SUMMARY, "remove error sample \r\n"); mLastPos.erase(--it.base()); mErrorFlag = true; //return true; //it is specification } if (count++ > 2) return true; it++; } return false; } bool GPSSensor::removeAveNewErrorSample()//if remove return true { VECTOR3 ave_pos; if (!getAvePos(ave_pos)) return false; double distance = VECTOR3::calcDistanceXY(mLastPos.front(), ave_pos); if (distance > GPS_ERROR_AVE_NEW_THRESHOLD) { Debug::print(LOG_SUMMARY, "remove error new date \r\n"); mLastPos.erase(mLastPos.end()); return true; } return false; } void GPSSensor::clearSample() { mLastPos.clear(); if (mLastPos.empty()) Debug::print(LOG_SUMMARY, "Cleared All Sample of GPS\r\n"); } bool GPSSensor::getAvePos(VECTOR3& pos) { if (mLastPos.size() <= GPS_MINIMUM_SAMPLES_FOR_AVERAGE) return false; std::list<VECTOR3>::iterator it = mLastPos.begin(); VECTOR3 average; while (it != mLastPos.end()) { average += *it; ++it; } average /= mLastPos.size(); pos = average; return true; } bool GPSSensor::getDirectionAngle(double & angle) { if (mUseMeanFlag) { VECTOR3 currentPos = mLastPos.front(); VECTOR3 avePos; getAvePos(avePos); angle = VECTOR3::calcAngleXY(avePos, currentPos);//���[�o�[�̕��� //VECTOR3 averagePos; //std::list<VECTOR3>::const_iterator it = mLastPos.begin(); //while (it != mLastPos.end()) //{ //averagePos += *it; //++it; //} //averagePos -= mLastPos.back(); //averagePos /= mLastPos.size() - 1; } else if (mClassMeanFlag) { VECTOR3 frontAvePos; VECTOR3 backAvePos; std::list<VECTOR3>::const_iterator it = mLastPos.begin(); int count = 0; while (it != mLastPos.end()) { if (count < int(mLastPos.size()/2)) { frontAvePos += *it; } else { backAvePos += *it; } ++it; count++; } frontAvePos /= int(mLastPos.size() / 2); backAvePos /= mLastPos.size() - int(mLastPos.size() / 2); angle = VECTOR3::calcAngleXY(backAvePos, frontAvePos);//���[�o�[�̕��� } else { VECTOR3 currentPos = mLastPos.front(); VECTOR3 prePos = mLastPos.back(); angle = VECTOR3::calcAngleXY(prePos, currentPos);//���[�o�[�̕��� } return true; } void GPSSensor::clearSamples() { mLastPos.clear(); } bool GPSSensor::isStuckGPS() { VECTOR3 ave_pos; if (!getAvePos(ave_pos)) return false; if(mSatelites == 0) return false; double distance = VECTOR3::calcDistanceXY(mLastPos.front(), ave_pos); return distance < mSettingStuckTh ? true : false; } bool GPSSensor::isStuckGPS(double &distance) { VECTOR3 ave_pos; if (!getAvePos(ave_pos)) return false; if(mSatelites == 0) return false; distance = VECTOR3::calcDistanceXY(mLastPos.front(), ave_pos); Debug::print(LOG_SUMMARY, "isStuck: %f \r\n",distance); return distance < mSettingStuckTh ? true : false; } void GPSSensor::showState() { if (mSatelites < 4) { Debug::print(LOG_SUMMARY, "Unknown Position\r\nSatelites: %d\r\n", mSatelites); } VECTOR3 ave_pos; VECTOR3 new_pos; VECTOR3 old_pos; getAvePos(ave_pos); new_pos.x = mLastPos.front().x; new_pos.y = mLastPos.front().y; new_pos.z = mLastPos.front().z; old_pos.x = mLastPos.back().x; old_pos.y = mLastPos.back().y; old_pos.z = mLastPos.back().z; double distance; double angle; if (!getDirectionAngle(angle)) angle = -1; //angle = VECTOR3::calcAngleXY(a, b); Debug::print(LOG_SUMMARY, "Satelites: %d \r\n", mSatelites); Debug::print(LOG_SUMMARY, "New Position: %f %f %f \r\n", new_pos.x, new_pos.y, new_pos.z); Debug::print(LOG_SUMMARY, "Ave Position: %f %f %f \r\n", ave_pos.x, ave_pos.y, ave_pos.z); Debug::print(LOG_SUMMARY, "Distance between New and Ave: %f \r\n", VECTOR3::calcDistanceXY(new_pos, ave_pos)); Debug::print(LOG_SUMMARY, "Distance between New and Old: %f \r\n", VECTOR3::calcDistanceXY(new_pos, old_pos)); Debug::print(LOG_SUMMARY, "Samples: %d / %d \r\n", mLastPos.size(), mSettingSampleNum); Debug::print(LOG_SUMMARY, "Time: %d \r\n", mGpsTime); Debug::print(LOG_SUMMARY, "Course: %f \r\n", mGpsCourse); Debug::print(LOG_SUMMARY, "Speed: %f \r\n", mGpsSpeed); Debug::print(LOG_SUMMARY, "Angle: %f \r\n", angle); Debug::print(LOG_SUMMARY, "Stuck: %s \r\n", isStuckGPS(distance) ? "true" : "false"); Debug::print(LOG_SUMMARY, "Stuck distance: %f threshold: %f\r\n", distance, mSettingStuckTh); Debug::print(LOG_SUMMARY, "Remove Error function: %s \r\n", mRemoveErrorFlag ? "true" : "false"); } GPSSensor::GPSSensor() : mFileHandle(-1), mPos(), mSatelites(0), mIsNewData(false), gps_rec("localhost", DEFAULT_GPSD_PORT) { setName("gps"); setPriority(TASK_PRIORITY_SENSOR, TASK_INTERVAL_SENSOR); } GPSSensor::~GPSSensor() { }
24.176617
123
0.680934
[ "object", "vector", "3d" ]
5465d5ad07003c36962b88e11ad99da0a2036899
3,128
cpp
C++
2017/bfjit/jit_utils.cpp
mikiec84/code-for-blog
79b2264f9a808eb14f624cb3c5ae7624038c043a
[ "Unlicense" ]
1,199
2015-01-06T14:09:37.000Z
2022-03-29T19:39:51.000Z
2017/bfjit/jit_utils.cpp
mikiec84/code-for-blog
79b2264f9a808eb14f624cb3c5ae7624038c043a
[ "Unlicense" ]
25
2016-07-29T15:44:01.000Z
2021-11-19T16:21:01.000Z
2017/bfjit/jit_utils.cpp
mikiec84/code-for-blog
79b2264f9a808eb14f624cb3c5ae7624038c043a
[ "Unlicense" ]
912
2015-01-04T00:39:50.000Z
2022-03-29T06:50:22.000Z
// Utilities for writing a JIT. // // Note: the implementation is POSIX-specific, requiring mmap/munmap with // appropriate flags. // // Eli Bendersky [http://eli.thegreenplace.net] // This code is in the public domain. #include "jit_utils.h" #include "utils.h" #include <cassert> #include <cstring> #include <limits> #include <sys/mman.h> namespace { // Allocates RW memory of given size and returns a pointer to it. On failure, // prints out the error and returns nullptr. mmap is used to allocate, so // deallocation has to be done with munmap, and the memory is allocated // on a page boundary so it's suitable for calling mprotect. void* alloc_writable_memory(size_t size) { void* ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (ptr == (void*)-1) { perror("mmap"); return nullptr; } return ptr; } // Sets a RX permission on the given memory, which must be page-aligned. Returns // 0 on success. On failure, prints out the error and returns -1. int make_memory_executable(void* m, size_t size) { if (mprotect(m, size, PROT_READ | PROT_EXEC) == -1) { perror("mprotect"); return -1; } return 0; } } // namespace JitProgram::JitProgram(const std::vector<uint8_t>& code) { program_size_ = code.size(); program_memory_ = alloc_writable_memory(program_size_); if (program_memory_ == nullptr) { DIE << "unable to allocate writable memory"; } memcpy(program_memory_, code.data(), program_size_); if (make_memory_executable(program_memory_, program_size_) < 0) { DIE << "unable to mark memory as executable"; } } JitProgram::~JitProgram() { if (program_memory_ != nullptr) { if (munmap(program_memory_, program_size_) < 0) { perror("munmap"); DIE << "unable to unmap memory"; } } } void CodeEmitter::EmitByte(uint8_t v) { code_.push_back(v); } void CodeEmitter::EmitBytes(std::initializer_list<uint8_t> seq) { for (auto v : seq) { EmitByte(v); } } void CodeEmitter::ReplaceByteAtOffset(size_t offset, uint8_t v) { assert(offset < code_.size() && "replacement fits in code"); code_[offset] = v; } void CodeEmitter::ReplaceUint32AtOffset(size_t offset, uint32_t v) { ReplaceByteAtOffset(offset, v & 0xFF); ReplaceByteAtOffset(offset + 1, (v >> 8) & 0xFF); ReplaceByteAtOffset(offset + 2, (v >> 16) & 0xFF); ReplaceByteAtOffset(offset + 3, (v >> 24) & 0xFF); } void CodeEmitter::EmitUint32(uint32_t v) { EmitByte(v & 0xFF); EmitByte((v >> 8) & 0xFF); EmitByte((v >> 16) & 0xFF); EmitByte((v >> 24) & 0xFF); } void CodeEmitter::EmitUint64(uint64_t v) { EmitUint32(v & 0xFFFFFFFF); EmitUint32((v >> 32) & 0xFFFFFFFF); } uint32_t compute_relative_32bit_offset(size_t jump_from, size_t jump_to) { if (jump_to >= jump_from) { size_t diff = jump_to - jump_from; assert(diff < (1ull << 31)); return diff; } else { // Here the diff is negative, so we need to encode it as 2s complement. size_t diff = jump_from - jump_to; assert(diff - 1 < (1ull << 31)); uint32_t diff_unsigned = static_cast<uint32_t>(diff); return ~diff_unsigned + 1; } }
28.18018
80
0.679348
[ "vector" ]
54757db032d7be78d3e89e61dcefc093c43f55a8
57,505
cxx
C++
Modules/Loadable/Sequences/MRML/vtkMRMLSequenceBrowserNode.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
Modules/Loadable/Sequences/MRML/vtkMRMLSequenceBrowserNode.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
Modules/Loadable/Sequences/MRML/vtkMRMLSequenceBrowserNode.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
/*============================================================================== Program: 3D Slicer Copyright (c) Kitware Inc. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Csaba Pinter, PerkLab, Queen's University and was supported through the Applied Cancer Research Unit program of Cancer Care Ontario with funds provided by the Ontario Ministry of Health and Long-Term Care ==============================================================================*/ // MRMLSequence includes #include "vtkMRMLSequenceBrowserNode.h" #include "vtkMRMLSequenceNode.h" // MRML includes #include <vtkMRMLScene.h> #include <vtkMRMLVolumeNode.h> #include <vtkMRMLHierarchyNode.h> // VTK includes #include <vtkNew.h> #include <vtkIntArray.h> #include <vtkCommand.h> #include <vtkCollection.h> #include <vtkCollectionIterator.h> #include <vtkObjectFactory.h> #include <vtkSmartPointer.h> #include <vtksys/RegularExpression.hxx> #include <vtkTimerLog.h> #include <vtkVariant.h> // STD includes #include <sstream> #include <algorithm> // for std::find #include <regex> #if defined(_WIN32) && !defined(__CYGWIN__) # define SNPRINTF _snprintf #else # define SNPRINTF snprintf #endif // First reference is the master sequence node, subsequent references are the synchronized sequence nodes static const char* SEQUENCE_NODE_REFERENCE_ROLE_BASE = "sequenceNodeRef"; // Old: rootNodeRef // TODO: Change this to "proxyNodeRef", but need to maintain backwards-compatibility with "dataNodeRef" static const char* PROXY_NODE_REFERENCE_ROLE_BASE = "dataNodeRef"; static const char* PROXY_NODE_COPY_ATTRIBUTE_NAME = "proxyNodeCopy"; // Declare the Synchronization Properties struct struct vtkMRMLSequenceBrowserNode::SynchronizationProperties { SynchronizationProperties() = default; void FromString( std::string str ); std::string ToString(); bool Playback{true}; bool Recording{false}; bool OverwriteProxyName{false}; // change proxy node name during replay (includes index value) bool SaveChanges{false}; // save proxy node changes into the sequence }; void vtkMRMLSequenceBrowserNode::SynchronizationProperties::FromString( std::string str ) { std::stringstream ss(str); while (!ss.eof()) { std::string attName, attValue; ss >> attName; ss >> attValue; if (!attName.empty() && !attValue.empty()) { std::string subAttValue; if (!attName.compare("playback")) { this->Playback=(!attValue.compare("true")); } if (!attName.compare("recording")) { this->Recording=(!attValue.compare("true")); } if (!attName.compare("overwriteProxyName")) { this->OverwriteProxyName=(!attValue.compare("true")); } if (!attName.compare("saveChanges")) { this->SaveChanges=(!attValue.compare("true")); } } } } std::string vtkMRMLSequenceBrowserNode::SynchronizationProperties::ToString() { std::stringstream ss; ss << "playback" << " " << (this->Playback ? "true" : "false") << " "; ss << "recording" << " " << (this->Recording ? "true" : "false") << " "; ss << "overwriteProxyName" << " " << (this->OverwriteProxyName ? "true" : "false") << " "; ss << "saveChanges" << " " << (this->SaveChanges ? "true" : "false") << " "; return ss.str(); } //------------------------------------------------------------------------------ vtkMRMLNodeNewMacro(vtkMRMLSequenceBrowserNode); //---------------------------------------------------------------------------- vtkMRMLSequenceBrowserNode::vtkMRMLSequenceBrowserNode() : IndexDisplayFormat("%.2f") { this->SetHideFromEditors(false); this->RecordingTimeOffsetSec = vtkTimerLog::GetUniversalTime(); this->LastSaveProxyNodesStateTimeSec = vtkTimerLog::GetUniversalTime(); } //---------------------------------------------------------------------------- vtkMRMLSequenceBrowserNode::~vtkMRMLSequenceBrowserNode() = default; //---------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::WriteXML(ostream& of, int nIndent) { // TODO: Convert to use MRML node macros Superclass::WriteXML(of, nIndent); vtkIndent indent(nIndent); of << indent << " playbackActive=\"" << (this->PlaybackActive ? "true" : "false") << "\""; of << indent << " playbackRateFps=\"" << this->PlaybackRateFps << "\""; of << indent << " playbackItemSkippingEnabled=\"" << (this->PlaybackItemSkippingEnabled ? "true" : "false") << "\""; of << indent << " playbackLooped=\"" << (this->PlaybackLooped ? "true" : "false") << "\""; of << indent << " selectedItemNumber=\"" << this->SelectedItemNumber << "\""; of << indent << " recordingActive=\"" << (this->RecordingActive ? "true" : "false") << "\""; of << indent << " recordOnMasterModifiedOnly=\"" << (this->RecordMasterOnly ? "true" : "false") << "\""; std::string recordingSamplingModeString = this->GetRecordingSamplingModeAsString(); if (!recordingSamplingModeString.empty()) { of << indent << " recordingSamplingMode=\"" << recordingSamplingModeString << "\""; } std::string indexDisplayModeString = this->GetIndexDisplayModeAsString(); if (!indexDisplayModeString.empty()) { of << indent << " indexDisplayMode=\"" << indexDisplayModeString << "\""; } of << indent << "indexDisplayFormat=\"" << this->GetIndexDisplayFormat() << "\""; of << indent << " virtualNodePostfixes=\""; // TODO: Change to "synchronizationPostfixes", but need backwards-compatibility with "virtualNodePostfixes" for(std::vector< std::string >::iterator roleNameIt=this->SynchronizationPostfixes.begin(); roleNameIt!=this->SynchronizationPostfixes.end(); ++roleNameIt) { if (roleNameIt!=this->SynchronizationPostfixes.begin()) { // print separator before printing the (if not the first element) of << " "; } of << roleNameIt->c_str(); } of << "\""; for(std::map< std::string, SynchronizationProperties* >::iterator rolePostfixIt=this->SynchronizationPropertiesMap.begin(); rolePostfixIt!=this->SynchronizationPropertiesMap.end(); ++rolePostfixIt) { of << indent << " SynchronizationPropertiesMap" << rolePostfixIt->first.c_str() << "=\"" << rolePostfixIt->second->ToString() << "\""; } } //---------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::ReadXMLAttributes(const char** atts) { // TODO: Convert to use MRML node macros vtkMRMLNode::ReadXMLAttributes(atts); // Read all MRML node attributes from two arrays of names and values const char* attName; const char* attValue; while (*atts != nullptr) { attName = *(atts++); attValue = *(atts++); if (!strcmp(attName, "playbackActive")) { if (!strcmp(attValue,"true")) { this->SetPlaybackActive(1); } else { this->SetPlaybackActive(0); } } else if (!strcmp(attName, "playbackRateFps")) { std::stringstream ss; ss << attValue; double playbackRateFps=10; ss >> playbackRateFps; this->SetPlaybackRateFps(playbackRateFps); } else if (!strcmp(attName, "playbackItemSkippingEnabled")) { if (!strcmp(attValue, "true")) { this->SetPlaybackItemSkippingEnabled(1); } else { this->SetPlaybackItemSkippingEnabled(0); } } else if (!strcmp(attName, "playbackLooped")) { if (!strcmp(attValue,"true")) { this->SetPlaybackLooped(1); } else { this->SetPlaybackLooped(0); } } else if (!strcmp(attName, "selectedItemNumber")) { std::stringstream ss; ss << attValue; int selectedItemNumber=0; ss >> selectedItemNumber; this->SetSelectedItemNumber(selectedItemNumber); } else if (!strcmp(attName, "recordingActive")) { if (!strcmp(attValue,"true")) { this->SetRecordingActive(1); } else { this->SetRecordingActive(0); } } else if (!strcmp(attName, "recordOnMasterModifiedOnly")) { if (!strcmp(attValue, "true")) { this->SetRecordMasterOnly(1); } else { this->SetRecordMasterOnly(0); } } else if (!strcmp(attName, "recordingSamplingMode")) { int recordingSamplingMode = this->GetRecordingSamplingModeFromString(attValue); if (recordingSamplingMode<0 || recordingSamplingMode >= vtkMRMLSequenceBrowserNode::NumberOfRecordingSamplingModes) { vtkErrorMacro("Invalid recording sampling mode: " << (attValue ? attValue : "(empty). Using LimitedToPlaybackFrameRate.")); recordingSamplingMode = vtkMRMLSequenceBrowserNode::SamplingLimitedToPlaybackFrameRate; } SetRecordingSamplingMode(recordingSamplingMode); } else if (!strcmp(attName, "indexDisplayMode")) { int indexDisplayMode = this->GetIndexDisplayModeFromString(attValue); if (indexDisplayMode<0 || indexDisplayMode >= vtkMRMLSequenceBrowserNode::NumberOfIndexDisplayModes) { vtkErrorMacro("Invalid index display mode: " << (attValue ? attValue : "(empty). Using IndexDisplayAsIndexValue.")); indexDisplayMode = vtkMRMLSequenceBrowserNode::IndexDisplayAsIndexValue; } SetIndexDisplayMode(indexDisplayMode); } else if (!strcmp(attName, "indexDisplayDecimals")) { std::stringstream ss; ss << attValue; int indexDisplayDecimals = 0; ss >> indexDisplayDecimals; std::stringstream indexDisplayFormatSS; indexDisplayFormatSS << "%." << indexDisplayDecimals << "f"; this->SetIndexDisplayFormat(indexDisplayFormatSS.str()); } else if (!strcmp(attName, "indexDisplayFormat")) { if (attValue) { this->SetIndexDisplayFormat(attValue); } } // TODO: Change to "synchronizationPostfixes", but need backwards-compatibility with "virtualNodePostfixes" else if (!strcmp(attName, "virtualNodePostfixes")) { this->SynchronizationPostfixes.clear(); std::stringstream ss(attValue); while (!ss.eof()) { std::string rolePostfix; ss >> rolePostfix; if (!rolePostfix.empty()) { this->SynchronizationPostfixes.push_back(rolePostfix); if (this->SynchronizationPropertiesMap.find(rolePostfix) == this->SynchronizationPropertiesMap.end()) { // Populate with default. If for any reason (e.g. old scene) the associated synchronization properties // are not found, this is better than having NULL. this->SynchronizationPropertiesMap[rolePostfix] = new SynchronizationProperties(); } } } } else if (std::string(attName).find("SynchronizationPropertiesMap")!=std::string::npos) { SynchronizationProperties* currSyncProps = new SynchronizationProperties(); currSyncProps->FromString(attValue); std::string rolePostfix = std::string(attName).substr(std::string(attName).find("SynchronizationPropertiesMap") + std::string("SynchronizationPropertiesMap").length()); this->SynchronizationPropertiesMap[rolePostfix] = currSyncProps; // Possibly overwriting the default, but that is ok } } this->FixSequenceNodeReferenceRoleName(); } //---------------------------------------------------------------------------- // Copy the node's attributes to this object. // Does NOT copy: ID, FilePrefix, Name, VolumeID void vtkMRMLSequenceBrowserNode::Copy(vtkMRMLNode *anode) { // TODO: Convert to use MRML node macros vtkMRMLSequenceBrowserNode* node = vtkMRMLSequenceBrowserNode::SafeDownCast(anode); if (!node) { vtkErrorMacro("Node copy failed: not a vtkMRMLSequenceNode"); return; } int wasModified = this->StartModify(); Superclass::Copy(anode); // Note: node references are copied by the superclass this->SynchronizationPostfixes = node->SynchronizationPostfixes; this->SynchronizationPropertiesMap = node->SynchronizationPropertiesMap; this->RecordingTimeOffsetSec = node->RecordingTimeOffsetSec; this->LastSaveProxyNodesStateTimeSec = node->LastSaveProxyNodesStateTimeSec; this->LastPostfixIndex = node->LastPostfixIndex; this->SetHideFromEditors(node->GetHideFromEditors()); this->SetPlaybackActive(node->GetPlaybackActive()); this->SetPlaybackRateFps(node->GetPlaybackRateFps()); this->SetPlaybackItemSkippingEnabled(node->GetPlaybackItemSkippingEnabled()); this->SetPlaybackLooped(node->GetPlaybackLooped()); this->SetRecordMasterOnly(node->GetRecordMasterOnly()); this->SetRecordingSamplingMode(node->GetRecordingSamplingMode()); this->SetIndexDisplayMode(node->GetIndexDisplayMode()); this->SetIndexDisplayFormat(node->GetIndexDisplayFormat()); this->SetRecordingActive(node->GetRecordingActive()); this->SetSelectedItemNumber(node->GetSelectedItemNumber()); this->EndModify(wasModified); } //---------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::PrintSelf(ostream& os, vtkIndent indent) { // TODO: Convert to use MRML node macros this->Superclass::PrintSelf(os, indent); os << indent << " Playback active: " << (this->PlaybackActive ? "true" : "false") << '\n'; os << indent << " Playback rate (fps): " << this->PlaybackRateFps << '\n'; os << indent << " Playback item skipping enabled: " << (this->PlaybackItemSkippingEnabled ? "true" : "false") << '\n'; os << indent << " Playback looped: " << (this->PlaybackLooped ? "true" : "false") << '\n'; os << indent << " Selected item number: " << this->SelectedItemNumber << '\n'; os << indent << " Recording active: " << (this->RecordingActive ? "true" : "false") << '\n'; os << indent << " Recording on master modified only: " << (this->RecordMasterOnly ? "true" : "false") << '\n'; os << indent << " Recording sampling mode: " << this->GetRecordingSamplingModeAsString() << "\n"; os << indent << " Index display mode: " << this->GetIndexDisplayModeAsString() << "\n"; os << indent << " Index display format: " << this->GetIndexDisplayFormat() << "\n"; os << indent << " Sequence nodes:\n"; if (this->SynchronizationPostfixes.empty()) { os << "(empty)\n"; } else { for (std::vector< std::string >::iterator rolePostfixIt = this->SynchronizationPostfixes.begin(); rolePostfixIt != this->SynchronizationPostfixes.end(); ++rolePostfixIt) { os << indent.GetNextIndent(); if (rolePostfixIt->empty()) { os << "(invalid)\n"; continue; } std::string sequenceNodeReferenceRole = SEQUENCE_NODE_REFERENCE_ROLE_BASE + (*rolePostfixIt); vtkMRMLSequenceNode* sequenceNode = vtkMRMLSequenceNode::SafeDownCast(this->GetNodeReference(sequenceNodeReferenceRole.c_str())); if (sequenceNode != nullptr) { os << "Sequence: " << (sequenceNode->GetName() ? sequenceNode->GetName() : "(unnamed)"); } else { os << "Sequence: (none)"; } std::string proxyNodeReferenceRole = PROXY_NODE_REFERENCE_ROLE_BASE + (*rolePostfixIt); vtkMRMLNode* proxyNode = vtkMRMLSequenceNode::SafeDownCast(this->GetNodeReference(proxyNodeReferenceRole.c_str())); if (proxyNode != nullptr) { os << ", Proxy: " << (proxyNode->GetName() ? proxyNode->GetName() : "(unnamed)"); } else { os << ", Proxy: (none)"; } SynchronizationProperties* syncProps = this->SynchronizationPropertiesMap[*rolePostfixIt]; if (syncProps != nullptr) { os << ", Playback: " << syncProps->Playback; os << ", Recording: " << syncProps->Recording; os << ", OverwriteProxyName: " << syncProps->OverwriteProxyName; os << ", SaveChanges: " << syncProps->SaveChanges; } os << "\n"; } } } //---------------------------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::GenerateSynchronizationPostfix() { while (1) { std::stringstream postfix; postfix << this->LastPostfixIndex; this->LastPostfixIndex++; bool isUnique = (std::find(this->SynchronizationPostfixes.begin(), this->SynchronizationPostfixes.end(), postfix.str()) == this->SynchronizationPostfixes.end()); if (isUnique) { return postfix.str(); } }; } //---------------------------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::SetAndObserveMasterSequenceNodeID(const char *sequenceNodeID) { if (!sequenceNodeID) { // master node can only be nullptr if there are no synchronized nodes this->RemoveAllSequenceNodes(); return ""; } if (this->GetMasterSequenceNode() && this->GetMasterSequenceNode()->GetID() != nullptr && strcmp(this->GetMasterSequenceNode()->GetID(), sequenceNodeID) == 0) { // no change if (!this->SynchronizationPostfixes.empty()) { return this->SynchronizationPostfixes.front(); } else { return ""; } } std::string masterPostfix = this->GetSynchronizationPostfixFromSequenceID(sequenceNodeID); if (masterPostfix.empty() || this->GetMasterSequenceNode() == nullptr) { bool oldModify = this->StartModify(); // Master is not among the browsed nodes, or it is an empty browser node. this->RemoveAllSequenceNodes(); // Master is the first element in the postfixes vector. std::string rolePostfix = this->AddSynchronizedSequenceNodeID(sequenceNodeID); this->SetSelectedItemNumber(0); this->EndModify(oldModify); return rolePostfix; } bool oldModify = this->StartModify(); // Get the currently selected index value (so that we can restore the closest value with the new master) std::string lastSelectedIndexValue = this->GetMasterSequenceNode()->GetNthIndexValue(this->GetSelectedItemNumber()); // Move the new master's postfix to the front of the list std::vector< std::string >::iterator oldMasterPostfixPosition = std::find(this->SynchronizationPostfixes.begin(), this->SynchronizationPostfixes.end(), masterPostfix); iter_swap(oldMasterPostfixPosition, this->SynchronizationPostfixes.begin()); std::string rolePostfix = this->SynchronizationPostfixes.front(); this->Modified(); // Select the closest selected item index in the new master node vtkMRMLSequenceNode* newMasterNode = (this->Scene ? vtkMRMLSequenceNode::SafeDownCast(this->Scene->GetNodeByID(sequenceNodeID)) : nullptr); if (newMasterNode != nullptr) { int newSelectedIndex = newMasterNode->GetItemNumberFromIndexValue(lastSelectedIndexValue, false); this->SetSelectedItemNumber(newSelectedIndex); } else { // We don't know what items are in this new master node this->SetSelectedItemNumber(0); } this->EndModify(oldModify); return rolePostfix; } //---------------------------------------------------------------------------- vtkMRMLSequenceNode* vtkMRMLSequenceBrowserNode::GetMasterSequenceNode() { if (this->SynchronizationPostfixes.empty()) { return nullptr; } std::string sequenceNodeReferenceRole=SEQUENCE_NODE_REFERENCE_ROLE_BASE+this->SynchronizationPostfixes[0]; vtkMRMLSequenceNode* node=vtkMRMLSequenceNode::SafeDownCast(this->GetNodeReference(sequenceNodeReferenceRole.c_str())); return node; } //---------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::RemoveAllProxyNodes() { bool oldModify=this->StartModify(); for (std::vector< std::string >::iterator rolePostfixIt=this->SynchronizationPostfixes.begin(); rolePostfixIt!=this->SynchronizationPostfixes.end(); ++rolePostfixIt) { this->RemoveProxyNode(*rolePostfixIt); } this->EndModify(oldModify); } //---------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::RemoveAllSequenceNodes() { bool oldModify=this->StartModify(); // need to make a copy as this->VirtualNodePostfixes changes as we remove nodes std::vector< std::string > synchronizationPostfixes=this->SynchronizationPostfixes; // start from the end to delete the master sequence node last for (std::vector< std::string >::reverse_iterator rolePostfixIt=synchronizationPostfixes.rbegin(); rolePostfixIt!=synchronizationPostfixes.rend(); ++rolePostfixIt) { std::string sequenceNodeReferenceRole=SEQUENCE_NODE_REFERENCE_ROLE_BASE+(*rolePostfixIt); vtkMRMLSequenceNode* node=vtkMRMLSequenceNode::SafeDownCast(this->GetNodeReference(sequenceNodeReferenceRole.c_str())); if (node==nullptr) { vtkErrorMacro("Invalid sequence node"); std::vector< std::string >::iterator rolePostfixInOriginalIt = std::find(this->SynchronizationPostfixes.begin(), this->SynchronizationPostfixes.end(), (*rolePostfixIt)); if (rolePostfixInOriginalIt!=this->SynchronizationPostfixes.end()) { this->SynchronizationPostfixes.erase(rolePostfixInOriginalIt); } continue; } this->RemoveSynchronizedSequenceNode(node->GetID()); } this->SetSelectedItemNumber(-1); this->EndModify(oldModify); } //---------------------------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::GetSynchronizationPostfixFromSequence(vtkMRMLSequenceNode* sequenceNode) { if (sequenceNode==nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::GetSynchronizationPostfixFromSequence failed: sequenceNode is invalid"); return ""; } for (std::vector< std::string >::iterator rolePostfixIt=this->SynchronizationPostfixes.begin(); rolePostfixIt!=this->SynchronizationPostfixes.end(); ++rolePostfixIt) { std::string sequenceNodeRef=SEQUENCE_NODE_REFERENCE_ROLE_BASE+(*rolePostfixIt); if (this->GetNodeReference(sequenceNodeRef.c_str())==sequenceNode) { return (*rolePostfixIt); } } return ""; } //---------------------------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::GetSynchronizationPostfixFromSequenceID(const char* sequenceNodeID) { if (sequenceNodeID == nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::GetSynchronizationPostfixFromSequenceID failed: sequenceNodeID is invalid"); return ""; } for (std::vector< std::string >::iterator rolePostfixIt = this->SynchronizationPostfixes.begin(); rolePostfixIt != this->SynchronizationPostfixes.end(); ++rolePostfixIt) { std::string sequenceNodeRef = SEQUENCE_NODE_REFERENCE_ROLE_BASE + (*rolePostfixIt); if (strcmp(this->GetNodeReferenceID(sequenceNodeRef.c_str()), sequenceNodeID) == 0) { return (*rolePostfixIt); } } return ""; } //---------------------------------------------------------------------------- vtkMRMLNode* vtkMRMLSequenceBrowserNode::GetProxyNode(vtkMRMLSequenceNode* sequenceNode) { if (sequenceNode==nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::GetVirtualOutputNode failed: sequenceNode is invalid"); return nullptr; } std::string rolePostfix=this->GetSynchronizationPostfixFromSequence(sequenceNode); if (rolePostfix.empty()) { return nullptr; } std::string proxyNodeRef=PROXY_NODE_REFERENCE_ROLE_BASE+rolePostfix; return this->GetNodeReference(proxyNodeRef.c_str()); } //---------------------------------------------------------------------------- vtkMRMLNode* vtkMRMLSequenceBrowserNode::AddProxyNode(vtkMRMLNode* sourceProxyNode, vtkMRMLSequenceNode* sequenceNode, bool copy /* =true */) { if (sequenceNode==nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::AddProxyNode failed: sequenceNode is invalid"); return nullptr; } if (this->Scene==nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::AddProxyNode failed: scene is invalid"); return nullptr; } bool oldModify=this->StartModify(); std::string rolePostfix=this->GetSynchronizationPostfixFromSequence(sequenceNode); if (rolePostfix.empty()) { // Add reference to the sequence node rolePostfix=AddSynchronizedSequenceNodeID(sequenceNode->GetID()); } // Save base name (proxy node name may be overwritten later) if (sourceProxyNode->GetAttribute("Sequences.BaseName") == nullptr) { sourceProxyNode->SetAttribute("Sequences.BaseName", sourceProxyNode->GetName()); } // Add copy of the data node std::string proxyNodeRef=PROXY_NODE_REFERENCE_ROLE_BASE+rolePostfix; // Create a new one from scratch in the new scene to make sure only the needed parts are copied vtkMRMLNode* proxyNode = sourceProxyNode; if ( copy ) { proxyNode = sourceProxyNode->CreateNodeInstance(); std::string proxyNodeName = sequenceNode->GetName(); const char* sequenceBaseName = sequenceNode->GetAttribute("Sequences.Source"); if (sequenceBaseName != nullptr) { proxyNodeName = std::string(this->GetName())+"-"+sequenceBaseName; } proxyNode->SetName(proxyNodeName.c_str()); this->Scene->AddNode(proxyNode); proxyNode->SetAttribute(PROXY_NODE_COPY_ATTRIBUTE_NAME,"true"); // Indicate that this is a copy proxyNode->Delete(); // ownership transferred to the scene, so we can release the pointer } vtkMRMLNode* oldProxyNode=this->GetNodeReference(proxyNodeRef.c_str()); // Remove the old proxy node and refer to the new one // It must not be done if the new proxy node is the same as the old one, // as it would remove the proxy node from the scene that we still need. if (proxyNode!=oldProxyNode) { this->RemoveProxyNode(rolePostfix); // This will also remove the proxy node from the scene if necessary this->SetAndObserveNodeReferenceID(proxyNodeRef.c_str(), proxyNode->GetID(), proxyNode->GetContentModifiedEvents()); } this->EndModify(oldModify); return proxyNode; } //---------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::GetAllProxyNodes(std::vector< vtkMRMLNode* >& nodes) { nodes.clear(); for (std::vector< std::string >::iterator rolePostfixIt=this->SynchronizationPostfixes.begin(); rolePostfixIt!=this->SynchronizationPostfixes.end(); ++rolePostfixIt) { std::string proxyNodeRef=PROXY_NODE_REFERENCE_ROLE_BASE+(*rolePostfixIt); vtkMRMLNode* node = this->GetNodeReference(proxyNodeRef.c_str()); if (node==nullptr) { continue; } nodes.push_back(node); } } //---------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::GetAllProxyNodes(vtkCollection* nodes) { if (nodes==nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::GetAllProxyNodes failed: nodes is invalid"); return; } std::vector< vtkMRMLNode* > nodesVector; this->GetAllProxyNodes(nodesVector); nodes->RemoveAllItems(); for (std::vector< vtkMRMLNode* >::iterator it = nodesVector.begin(); it != nodesVector.end(); ++it) { nodes->AddItem(*it); } } //---------------------------------------------------------------------------- bool vtkMRMLSequenceBrowserNode::IsProxyNode(const char* nodeId) { return this->IsProxyNodeID(nodeId); } //---------------------------------------------------------------------------- bool vtkMRMLSequenceBrowserNode::IsProxyNodeID(const char* nodeId) { std::vector< vtkMRMLNode* > nodesVector; this->GetAllProxyNodes(nodesVector); for (std::vector< vtkMRMLNode* >::iterator it = nodesVector.begin(); it != nodesVector.end(); ++it) { if (strcmp((*it)->GetID(), nodeId)==0) { // found node return true; } } return false; } //---------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::RemoveProxyNode(const std::string& postfix) { bool oldModify=this->StartModify(); std::string proxyNodeRef=PROXY_NODE_REFERENCE_ROLE_BASE+postfix; vtkMRMLNode* proxyNode=this->GetNodeReference(proxyNodeRef.c_str()); if (proxyNode!=nullptr) { if (proxyNode->GetAttribute(PROXY_NODE_COPY_ATTRIBUTE_NAME)!=nullptr) { this->Scene->RemoveNode(proxyNode); } this->RemoveNodeReferenceIDs(proxyNodeRef.c_str()); } this->EndModify(oldModify); } //---------------------------------------------------------------------------- bool vtkMRMLSequenceBrowserNode::IsSynchronizedSequenceNode(const char* nodeId, bool includeMasterNode/*=false*/) { return this->IsSynchronizedSequenceNodeID(nodeId, includeMasterNode); } //---------------------------------------------------------------------------- bool vtkMRMLSequenceBrowserNode::IsSynchronizedSequenceNode(vtkMRMLSequenceNode* sequenceNode, bool includeMasterNode/*=false*/) { if (sequenceNode == nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::IsSynchronizedSequenceNode failed: sequenceNode is invalid"); return false; } return this->IsSynchronizedSequenceNodeID(sequenceNode->GetID(), includeMasterNode); } //---------------------------------------------------------------------------- bool vtkMRMLSequenceBrowserNode::IsSynchronizedSequenceNodeID(const char* nodeId, bool includeMasterNode/*=false*/) { if (nodeId==nullptr) { vtkWarningMacro("vtkMRMLSequenceBrowserNode::IsSynchronizedSequenceNode nodeId is NULL"); return false; } for (std::vector< std::string >::iterator rolePostfixIt=this->SynchronizationPostfixes.begin(); rolePostfixIt!=this->SynchronizationPostfixes.end(); ++rolePostfixIt) { if (!includeMasterNode && rolePostfixIt==this->SynchronizationPostfixes.begin()) { // the first one is the master sequence node, don't consider as a synchronized sequence node continue; } std::string sequenceNodeRef=SEQUENCE_NODE_REFERENCE_ROLE_BASE+(*rolePostfixIt); const char* foundNodeId=this->GetNodeReferenceID(sequenceNodeRef.c_str()); if (foundNodeId==nullptr) { continue; } if (strcmp(foundNodeId,nodeId)==0) { return true; } } return false; } //---------------------------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::AddSynchronizedSequenceNode(vtkMRMLSequenceNode* sequenceNode) { if (sequenceNode == nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::AddSynchronizedSequenceNode failed: sequenceNode is invalid"); return ""; } return this->AddSynchronizedSequenceNodeID(sequenceNode->GetID()); } //---------------------------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::AddSynchronizedSequenceNode(const char* synchronizedSequenceNodeId) { return this->AddSynchronizedSequenceNodeID(synchronizedSequenceNodeId); } //---------------------------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::AddSynchronizedSequenceNodeID(const char* synchronizedSequenceNodeId) { bool oldModify = this->StartModify(); std::string rolePostfix = this->GetSynchronizationPostfixFromSequenceID(synchronizedSequenceNodeId); if (!rolePostfix.empty()) { // already a synchronized sequence node return rolePostfix; } rolePostfix = this->GenerateSynchronizationPostfix(); if (this->SynchronizationPostfixes.empty()) { // first sequence, initialize selected item number this->SetSelectedItemNumber(0); } this->SynchronizationPostfixes.push_back(rolePostfix); std::string sequenceNodeReferenceRole = SEQUENCE_NODE_REFERENCE_ROLE_BASE + rolePostfix; this->SetAndObserveNodeReferenceID(sequenceNodeReferenceRole.c_str(), synchronizedSequenceNodeId); this->SynchronizationPropertiesMap[ rolePostfix ] = new SynchronizationProperties(); this->EndModify(oldModify); return rolePostfix; } //---------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::RemoveSynchronizedSequenceNode(const char* nodeId) { if (this->Scene==nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::RemoveSynchronizedSequenceNode failed: scene is invalid"); return; } if (nodeId==nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::RemoveSynchronizedSequenceNode failed: nodeId is invalid"); return; } for (std::vector< std::string >::iterator rolePostfixIt=this->SynchronizationPostfixes.begin(); rolePostfixIt!=this->SynchronizationPostfixes.end(); ++rolePostfixIt) { std::string sequenceNodeRef=SEQUENCE_NODE_REFERENCE_ROLE_BASE+(*rolePostfixIt); const char* foundNodeId=this->GetNodeReferenceID(sequenceNodeRef.c_str()); if (foundNodeId==nullptr) { continue; } if (strcmp(foundNodeId,nodeId)==0) { // This might have been the last node that was being replayed or recorded this->SetPlaybackActive(false); this->SetRecordingActive(false); // the iterator will become invalid, so make a copy of its content std::string rolePostfix=(*rolePostfixIt); bool oldModify=this->StartModify(); this->SynchronizationPostfixes.erase(rolePostfixIt); this->RemoveNodeReferenceIDs(sequenceNodeRef.c_str()); this->RemoveProxyNode(rolePostfix); this->EndModify(oldModify); return; } } vtkWarningMacro("vtkMRMLSequenceBrowserNode::RemoveSynchronizedSequenceNode did nothing, the specified node was not synchronized"); } //---------------------------------------------------------------------------- int vtkMRMLSequenceBrowserNode::GetNumberOfSynchronizedSequenceNodes(bool includeMasterNode/*=false*/) { int numberOfSynchronizedNodes = this->SynchronizationPostfixes.size(); if (!includeMasterNode) { numberOfSynchronizedNodes--; } if (numberOfSynchronizedNodes < 0) { numberOfSynchronizedNodes = 0; } return numberOfSynchronizedNodes; } //---------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::GetSynchronizedSequenceNodes(std::vector< vtkMRMLSequenceNode* > &synchronizedSequenceNodes, bool includeMasterNode/*=false*/) { synchronizedSequenceNodes.clear(); for (std::vector< std::string >::iterator rolePostfixIt=this->SynchronizationPostfixes.begin(); rolePostfixIt!=this->SynchronizationPostfixes.end(); ++rolePostfixIt) { if (!includeMasterNode && rolePostfixIt==this->SynchronizationPostfixes.begin()) { // the first one is the master sequence node, don't consider as a synchronized sequence node continue; } std::string sequenceNodeRef=SEQUENCE_NODE_REFERENCE_ROLE_BASE+(*rolePostfixIt); vtkMRMLSequenceNode* synchronizedNode=vtkMRMLSequenceNode::SafeDownCast(this->GetNodeReference(sequenceNodeRef.c_str())); if (synchronizedNode==nullptr) { // valid case during scene updates continue; } synchronizedSequenceNodes.push_back(synchronizedNode); } } //---------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::GetSynchronizedSequenceNodes(vtkCollection* synchronizedSequenceNodes, bool includeMasterNode /* =false */) { if (synchronizedSequenceNodes==nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::GetSynchronizedSequenceNodes failed: synchronizedSequenceNodes is invalid"); return; } std::vector< vtkMRMLSequenceNode* > synchronizedDataNodesVector; this->GetSynchronizedSequenceNodes(synchronizedDataNodesVector, includeMasterNode); synchronizedSequenceNodes->RemoveAllItems(); for (std::vector< vtkMRMLSequenceNode* >::iterator it = synchronizedDataNodesVector.begin(); it != synchronizedDataNodesVector.end(); ++it) { synchronizedSequenceNodes->AddItem(*it); } } //--------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::SetRecordingActive(bool recording) { // Before activating the recording, set the initial timestamp to be correct this->RecordingTimeOffsetSec = vtkTimerLog::GetUniversalTime(); int numberOfItems = this->GetNumberOfItems(); if (numberOfItems>0 && this->GetMasterSequenceNode()->GetIndexType()==vtkMRMLSequenceNode::NumericIndex) { std::stringstream timeString; timeString << this->GetMasterSequenceNode()->GetNthIndexValue(numberOfItems - 1); double timeValue = 0; timeString >> timeValue; this->RecordingTimeOffsetSec -= timeValue; } if (this->RecordingActive!=recording) { this->RecordingActive = recording; this->Modified(); } } //--------------------------------------------------------------------------- int vtkMRMLSequenceBrowserNode::SelectFirstItem() { int selectedItemNumber = (this->GetNumberOfItems() > 0) ? 0 :- 1; this->SetSelectedItemNumber(selectedItemNumber); return selectedItemNumber; } //--------------------------------------------------------------------------- int vtkMRMLSequenceBrowserNode::SelectLastItem() { int selectedItemNumber = this->GetNumberOfItems() - 1; this->SetSelectedItemNumber(selectedItemNumber ); return selectedItemNumber; } //--------------------------------------------------------------------------- int vtkMRMLSequenceBrowserNode::SelectNextItem(int selectionIncrement/*=1*/) { int numberOfItems = this->GetNumberOfItems(); if (numberOfItems == 0) { // nothing to replay return -1; } int selectedItemNumber=this->GetSelectedItemNumber(); int browserNodeModify=this->StartModify(); // invoke modification event once all the modifications has been completed if (selectedItemNumber<0) { selectedItemNumber=0; } else { selectedItemNumber += selectionIncrement; if (selectedItemNumber >= numberOfItems) { if (this->GetPlaybackLooped()) { // wrap around and keep playback going selectedItemNumber = selectedItemNumber % numberOfItems; } else { this->SetPlaybackActive(false); selectedItemNumber=0; } } else if (selectedItemNumber<0) { if (this->GetPlaybackLooped()) { // wrap around and keep playback going selectedItemNumber = (selectedItemNumber % numberOfItems) + numberOfItems; } else { this->SetPlaybackActive(false); selectedItemNumber = numberOfItems - 1; } } } this->SetSelectedItemNumber(selectedItemNumber); this->EndModify(browserNodeModify); return selectedItemNumber; } //--------------------------------------------------------------------------- int vtkMRMLSequenceBrowserNode::GetNumberOfItems() { vtkMRMLSequenceNode* sequenceNode = this->GetMasterSequenceNode(); if (!sequenceNode) { return 0; } return sequenceNode->GetNumberOfDataNodes(); } //--------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::ProcessMRMLEvents( vtkObject *caller, unsigned long event, void *callData ) { this->vtkMRMLNode::ProcessMRMLEvents( caller, event, callData ); vtkMRMLNode* modifiedNode = vtkMRMLNode::SafeDownCast(caller); if (modifiedNode == nullptr || !this->IsProxyNode(modifiedNode->GetID())) { // we are only interested in proxy node modified events return; } this->InvokeCustomModifiedEvent(ProxyNodeModifiedEvent, modifiedNode); } //--------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::SaveProxyNodesState() { std::stringstream currTime; bool continuousRecording = this->GetRecordingActive(); if (continuousRecording) { // Continuous recording. // To maintain syncing, we need to record for all sequences at every given timestamp. double currentTime = vtkTimerLog::GetUniversalTime(); double timeElapsedSinceLastSave = currentTime - this->LastSaveProxyNodesStateTimeSec; if (this->RecordingSamplingMode == vtkMRMLSequenceBrowserNode::SamplingLimitedToPlaybackFrameRate) { if (this->GetPlaybackRateFps() > 0 && (timeElapsedSinceLastSave < 1.0 / this->GetPlaybackRateFps())) { // this state is too close in time to the previous saved state, don't record it return; } } this->LastSaveProxyNodesStateTimeSec = currentTime; currTime << (currentTime - this->RecordingTimeOffsetSec); } else { // Recording a single snapshot // TODO: add support for non-numeric index type double lastItemTime = 0; int numberOfItems = this->GetNumberOfItems(); if (numberOfItems > 0) { std::stringstream timeString; timeString << this->GetMasterSequenceNode()->GetNthIndexValue(numberOfItems - 1); timeString >> lastItemTime; } double playbackRateFps = this->GetPlaybackRateFps() != 0.0 ? this->GetPlaybackRateFps() : 1.0; currTime << lastItemTime + 1.0 / playbackRateFps; } // Record into each sequence int wasModified = this->StartModify(); std::vector< vtkMRMLSequenceNode* > sequenceNodes; this->GetSynchronizedSequenceNodes(sequenceNodes, true); bool snapshotAdded = false; for (std::vector< vtkMRMLSequenceNode* >::iterator it = sequenceNodes.begin(); it != sequenceNodes.end(); it++) { vtkMRMLSequenceNode* currSequenceNode = (*it); if (this->GetRecording(currSequenceNode)) { currSequenceNode->SetDataNodeAtValue(this->GetProxyNode(currSequenceNode), currTime.str().c_str()); snapshotAdded = true; } } if (snapshotAdded) { this->Modified(); this->SelectLastItem(); } this->EndModify(wasModified); } //--------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::OnNodeReferenceAdded(vtkMRMLNodeReference* nodeReference) { vtkMRMLNode::OnNodeReferenceAdded(nodeReference); if (std::string(nodeReference->GetReferenceRole()).find( PROXY_NODE_REFERENCE_ROLE_BASE ) != std::string::npos) { // Need to observe the correct events after scene loading this->SetAndObserveNodeReferenceID( nodeReference->GetReferenceRole(), nodeReference->GetReferencedNodeID(), nodeReference->GetReferencedNode()->GetContentModifiedEvents()); // TODO: check if nodeReference->GetReferencedNode() is already valid here } } //--------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::FixSequenceNodeReferenceRoleName() { bool oldModify=this->StartModify(); for (std::vector< std::string >::iterator rolePostfixIt=this->SynchronizationPostfixes.begin(); rolePostfixIt!=this->SynchronizationPostfixes.end(); ++rolePostfixIt) { std::string obsoleteSequenceNodeReferenceRole=std::string("rootNodeRef")+(*rolePostfixIt); std::string sequenceNodeReferenceRole=SEQUENCE_NODE_REFERENCE_ROLE_BASE+(*rolePostfixIt); const char* obsoleteSeqNodeId = this->GetNodeReferenceID(obsoleteSequenceNodeReferenceRole.c_str()); const char* seqNodeId = this->GetNodeReferenceID(sequenceNodeReferenceRole.c_str()); if (seqNodeId==nullptr && obsoleteSeqNodeId!=nullptr) { // we've found an obsolete reference, move it into the new reference this->SetNodeReferenceID(sequenceNodeReferenceRole.c_str(), obsoleteSeqNodeId); this->SetNodeReferenceID(obsoleteSequenceNodeReferenceRole.c_str(), nullptr); } } this->EndModify(oldModify); } //--------------------------------------------------------------------------- vtkMRMLSequenceNode* vtkMRMLSequenceBrowserNode::GetSequenceNode(vtkMRMLNode* proxyNode) { if (proxyNode == nullptr) { vtkErrorMacro("vtkMRMLSequenceBrowserNode::GetSequenceNode failed: virtualOutputDataNode is invalid"); return nullptr; } for (std::vector< std::string >::iterator rolePostfixIt = this->SynchronizationPostfixes.begin(); rolePostfixIt != this->SynchronizationPostfixes.end(); ++rolePostfixIt) { std::string proxyNodeRef = PROXY_NODE_REFERENCE_ROLE_BASE + (*rolePostfixIt); vtkMRMLNode* foundProxyNode = this->GetNodeReference(proxyNodeRef.c_str()); if (foundProxyNode == proxyNode) { std::string sequenceNodeReferenceRole = SEQUENCE_NODE_REFERENCE_ROLE_BASE + (*rolePostfixIt); vtkMRMLSequenceNode* sequenceNode = vtkMRMLSequenceNode::SafeDownCast(this->GetNodeReference(sequenceNodeReferenceRole.c_str())); return sequenceNode; } } return nullptr; } //--------------------------------------------------------------------------- bool vtkMRMLSequenceBrowserNode::IsAnySequenceNodeRecording() { for (std::vector< std::string >::iterator rolePostfixIt = this->SynchronizationPostfixes.begin(); rolePostfixIt != this->SynchronizationPostfixes.end(); ++rolePostfixIt) { SynchronizationProperties* syncProps = this->SynchronizationPropertiesMap[(*rolePostfixIt)]; if (syncProps == nullptr) { continue; } if (syncProps->Recording) { return true; } } return false; } //--------------------------------------------------------------------------- bool vtkMRMLSequenceBrowserNode::GetRecording(vtkMRMLSequenceNode* sequenceNode) { std::string rolePostfix = this->GetSynchronizationPostfixFromSequence(sequenceNode); SynchronizationProperties* syncProps = this->SynchronizationPropertiesMap[ rolePostfix ]; if (rolePostfix=="" || syncProps==nullptr) { return false; } return syncProps->Recording; } //--------------------------------------------------------------------------- bool vtkMRMLSequenceBrowserNode::GetPlayback(vtkMRMLSequenceNode* sequenceNode) { std::string rolePostfix = this->GetSynchronizationPostfixFromSequence(sequenceNode); SynchronizationProperties* syncProps = this->SynchronizationPropertiesMap[ rolePostfix ]; if (rolePostfix=="" || syncProps==nullptr) { return false; } return syncProps->Playback; } //--------------------------------------------------------------------------- bool vtkMRMLSequenceBrowserNode::GetOverwriteProxyName(vtkMRMLSequenceNode* sequenceNode) { std::string rolePostfix = this->GetSynchronizationPostfixFromSequence(sequenceNode); SynchronizationProperties* syncProps = this->SynchronizationPropertiesMap[ rolePostfix ]; if (rolePostfix=="" || syncProps==nullptr) { return false; } return syncProps->OverwriteProxyName; } //--------------------------------------------------------------------------- bool vtkMRMLSequenceBrowserNode::GetSaveChanges(vtkMRMLSequenceNode* sequenceNode) { std::string rolePostfix = this->GetSynchronizationPostfixFromSequence(sequenceNode); SynchronizationProperties* syncProps = this->SynchronizationPropertiesMap[ rolePostfix ]; if (rolePostfix=="" || syncProps==nullptr) { return false; } return syncProps->SaveChanges; } //--------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::SetRecording(vtkMRMLSequenceNode* sequenceNode, bool recording) { std::vector< vtkMRMLSequenceNode* > synchronizedSequenceNodes; if (sequenceNode) { synchronizedSequenceNodes.push_back(sequenceNode); } else { this->GetSynchronizedSequenceNodes(synchronizedSequenceNodes, true); } bool modified = false; for (std::vector< vtkMRMLSequenceNode* >::iterator it = synchronizedSequenceNodes.begin(); it != synchronizedSequenceNodes.end(); ++it) { std::string rolePostfix = this->GetSynchronizationPostfixFromSequence(*it); SynchronizationProperties* syncProps = this->SynchronizationPropertiesMap[rolePostfix]; if (rolePostfix == "" || syncProps == nullptr) { continue; } if (syncProps->Recording != recording) { syncProps->Recording = recording; modified = true; } } if (modified) { this->Modified(); } } //--------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::SetPlayback(vtkMRMLSequenceNode* sequenceNode, bool playback) { std::vector< vtkMRMLSequenceNode* > synchronizedSequenceNodes; if (sequenceNode) { synchronizedSequenceNodes.push_back(sequenceNode); } else { this->GetSynchronizedSequenceNodes(synchronizedSequenceNodes, true); } bool modified = false; for (std::vector< vtkMRMLSequenceNode* >::iterator it = synchronizedSequenceNodes.begin(); it != synchronizedSequenceNodes.end(); ++it) { std::string rolePostfix = this->GetSynchronizationPostfixFromSequence(*it); SynchronizationProperties* syncProps = this->SynchronizationPropertiesMap[rolePostfix]; if (rolePostfix == "" || syncProps == nullptr) { continue; } if (syncProps->Playback != playback) { syncProps->Playback = playback; modified = true; } } if (modified) { this->Modified(); } } //--------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::SetOverwriteProxyName(vtkMRMLSequenceNode* sequenceNode, bool overwrite) { std::vector< vtkMRMLSequenceNode* > synchronizedSequenceNodes; if (sequenceNode) { synchronizedSequenceNodes.push_back(sequenceNode); } else { this->GetSynchronizedSequenceNodes(synchronizedSequenceNodes, true); } bool modified = false; for (std::vector< vtkMRMLSequenceNode* >::iterator it = synchronizedSequenceNodes.begin(); it != synchronizedSequenceNodes.end(); ++it) { std::string rolePostfix = this->GetSynchronizationPostfixFromSequence(*it); SynchronizationProperties* syncProps = this->SynchronizationPropertiesMap[rolePostfix]; if (rolePostfix == "" || syncProps == nullptr) { continue; } if (syncProps->OverwriteProxyName != overwrite) { syncProps->OverwriteProxyName = overwrite; modified = true; } } if (modified) { this->Modified(); } } //--------------------------------------------------------------------------- void vtkMRMLSequenceBrowserNode::SetSaveChanges(vtkMRMLSequenceNode* sequenceNode, bool save) { std::vector< vtkMRMLSequenceNode* > synchronizedSequenceNodes; if (sequenceNode) { synchronizedSequenceNodes.push_back(sequenceNode); } else { this->GetSynchronizedSequenceNodes(synchronizedSequenceNodes, true); } bool modified = false; for (std::vector< vtkMRMLSequenceNode* >::iterator it = synchronizedSequenceNodes.begin(); it != synchronizedSequenceNodes.end(); ++it) { std::string rolePostfix = this->GetSynchronizationPostfixFromSequence(*it); SynchronizationProperties* syncProps = this->SynchronizationPropertiesMap[rolePostfix]; if (rolePostfix == "" || syncProps == nullptr) { continue; } if (syncProps->SaveChanges != save) { syncProps->SaveChanges = save; modified = true; } } if (modified) { this->Modified(); } } //----------------------------------------------------------- void vtkMRMLSequenceBrowserNode::SetRecordingSamplingModeFromString(const char *recordingSamplingModeString) { int recordingSamplingMode = GetRecordingSamplingModeFromString(recordingSamplingModeString); this->SetRecordingSamplingMode(recordingSamplingMode); } //----------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::GetRecordingSamplingModeAsString() { return vtkMRMLSequenceBrowserNode::GetRecordingSamplingModeAsString(this->RecordingSamplingMode); } //----------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::GetRecordingSamplingModeAsString(int recordingSamplingMode) { switch (recordingSamplingMode) { case vtkMRMLSequenceBrowserNode::SamplingAll: return "all"; case vtkMRMLSequenceBrowserNode::SamplingLimitedToPlaybackFrameRate: return "limitedToPlaybackFrameRate"; default: return ""; } } //----------------------------------------------------------- int vtkMRMLSequenceBrowserNode::GetRecordingSamplingModeFromString(const std::string& recordingSamplingModeString) { for (int i = 0; i<vtkMRMLSequenceBrowserNode::NumberOfRecordingSamplingModes; i++) { if (recordingSamplingModeString == GetRecordingSamplingModeAsString(i)) { // found it return i; } } return -1; } //----------------------------------------------------------- void vtkMRMLSequenceBrowserNode::SetIndexDisplayFormat(std::string indexDisplayNode) { vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting IndexDisplayFormat to " << indexDisplayNode); if (this->IndexDisplayFormat != indexDisplayNode) { this->IndexDisplayFormat = indexDisplayNode; this->InvokeCustomModifiedEvent(IndexDisplayFormatModifiedEvent); this->Modified(); } } //----------------------------------------------------------- void vtkMRMLSequenceBrowserNode::SetIndexDisplayModeFromString(const char *indexDisplayModeString) { int indexDisplayMode = GetIndexDisplayModeFromString(indexDisplayModeString); this->SetIndexDisplayMode(indexDisplayMode); } //----------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::GetIndexDisplayModeAsString() { return vtkMRMLSequenceBrowserNode::GetIndexDisplayModeAsString(this->IndexDisplayMode); } //----------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::GetIndexDisplayModeAsString(int indexDisplayMode) { switch (indexDisplayMode) { case vtkMRMLSequenceBrowserNode::IndexDisplayAsIndex: return "[index]"; case vtkMRMLSequenceBrowserNode::IndexDisplayAsIndexValue: return "[indexValue]"; default: return ""; } } //----------------------------------------------------------- int vtkMRMLSequenceBrowserNode::GetIndexDisplayModeFromString(const std::string& indexDisplayModeString) { for (int i = 0; i<vtkMRMLSequenceBrowserNode::NumberOfIndexDisplayModes; i++) { if (indexDisplayModeString == GetIndexDisplayModeAsString(i)) { // found it return i; } } return -1; } //----------------------------------------------------------------------------- std::string vtkMRMLSequenceBrowserNode::GetFormattedIndexValue(int index) { vtkMRMLSequenceNode* sequenceNode = this->GetMasterSequenceNode(); if (!sequenceNode) { return ""; } if (index < 0 || index >= sequenceNode->GetNumberOfDataNodes()) { return ""; } std::string indexValue = sequenceNode->GetNthIndexValue(index); std::string formatString = this->GetIndexDisplayFormat(); std::string sprintfSpecifier; std::string prefix; std::string suffix; bool argFound = vtkMRMLSequenceBrowserNode::ValidateFormatString(sprintfSpecifier, prefix, suffix, formatString, "fFgGeEs"); if (!argFound) { return indexValue; } std::string formattedString = std::string(512, '\0'); vtksys::RegularExpression regExForString("%.*s"); vtksys::RegularExpression regExForFloat("%.*[fFgGeE]"); if (argFound && regExForString.find(sprintfSpecifier)) { SNPRINTF(&formattedString[0], formattedString.size(), sprintfSpecifier.c_str(), indexValue.c_str()); } else if (argFound && regExForFloat.find(sprintfSpecifier)) { vtkVariant indexVariant = vtkVariant(indexValue.c_str()); bool success = false; float floatValue = indexVariant.ToDouble(&success); if (success) { SNPRINTF(&formattedString[0], formattedString.size(), sprintfSpecifier.c_str(), floatValue); } } else { return indexValue; } // Remove trailing null characters left over from sprintf formattedString.erase(std::find(formattedString.begin(), formattedString.end(), '\0'), formattedString.end()); formattedString = prefix + formattedString + suffix; return formattedString; } //----------------------------------------------------------------------------- bool vtkMRMLSequenceBrowserNode::ValidateFormatString(std::string& validatedFormat, std::string& prefix, std::string& suffix, const std::string& requestedFormat, const std::string& typeString) { // This regex finds sprintf specifications. Only the first is used to format the index value std::regex specifierRegex; std::smatch specifierMatch; try { // Regex from: https://stackoverflow.com/a/8915445 specifierRegex = std::regex(R"###(%(?:\d+\$)?[+-]?(?:[ 0]|'.{1})?-?\d*(?:\.\d+)?[)###" + typeString + "]"); std::regex_search(requestedFormat, specifierMatch, specifierRegex); } catch (const std::regex_error& e) { vtkErrorWithObjectMacro(nullptr, "Sequence browser regex error " << e.what()); return false; } if (specifierMatch.size() < 1) { return false; } validatedFormat = specifierMatch.str(0); prefix = specifierMatch.prefix().str(); suffix = specifierMatch.suffix().str(); return true; }
37.052191
159
0.648031
[ "object", "vector", "3d" ]
547ef88c705b00980094663685cc91958e78755e
5,479
cc
C++
src/RouteChoice/patSimulation.cc
godosou/smaroute
e2ccc9492dff54c8ef5c74d5309d2b06758ba342
[ "MIT" ]
4
2015-02-23T16:02:52.000Z
2021-03-26T17:58:53.000Z
src/RouteChoice/patSimulation.cc
godosou/smaroute
e2ccc9492dff54c8ef5c74d5309d2b06758ba342
[ "MIT" ]
null
null
null
src/RouteChoice/patSimulation.cc
godosou/smaroute
e2ccc9492dff54c8ef5c74d5309d2b06758ba342
[ "MIT" ]
5
2015-02-23T16:05:59.000Z
2017-05-04T16:13:16.000Z
/* * patSimulation.cc * * Created on: May 25, 2012 * Author: jchen */ #include "patSimulation.h" #include "patKMLPathWriter.h" #include "patObservation.h" #include "patUtilityFunction.h" #include <vector> #include <map> #include "patMultiModalPath.h" #include "patOd.h" #include <fstream> #include "patObservation.h" #include "patReadChoiceSetFromKML.h" #include "patNetworkEnvironment.h" #include "patNetworkElements.h" #include "patComputePathSize.h" #include <boost/lexical_cast.hpp> #include "patSampleDiscreteDistribution.h" #include "patSimulateProbabilisticPaths.h" #include "patRouter.h" #include <boost/lexical_cast.hpp> patSimulation::patSimulation(const patNetworkEnvironment* network_environment, patUtilityFunction* utility_function, int rng) : m_network_environment(network_environment), m_utility_function( utility_function), m_rnd(rng) { } void patSimulation::run(string folder, const patRouter* router) { patObservation observation; patReadChoiceSetFromKML rc(&m_network_environment->getNetworkElements()); string choiceset_file = folder + "universal_choice_set.kml"; if (!ifstream(choiceset_file.c_str())) { return; } map<patOd, patChoiceSet> od_choice_set = rc.read(choiceset_file, m_rnd); // DEBUG_MESSAGE(od_choice_set.size()); patOd od = od_choice_set.begin()->first; patChoiceSet choice_set = od_choice_set.begin()->second; set<patMultiModalPath> paths_set = choice_set.getChoiceSet(); // DEBUG_MESSAGE(paths_set.size()); vector<patMultiModalPath> paths_vector; vector<double> utility_vector; //Normalize utility vector vector<int> sampled_observations; vector<double> sampled_empirical_proba; vector<double> sampled_count; DEBUG_MESSAGE("universal path size"<<paths_set.size()); patComputePathSize ps_computer; map<const patMultiModalPath, double> ps = ps_computer.computePS(choice_set); DEBUG_MESSAGE("ps calculated"<<ps.size()); for (set<patMultiModalPath>::iterator path_iter = paths_set.begin(); path_iter != paths_set.end(); ++path_iter) { paths_vector.push_back(*path_iter); map<const patMultiModalPath, double>::const_iterator find_ps = ps.find( *path_iter); if (find_ps == ps.end()) { throw RuntimeException("no ps found"); } DEBUG_MESSAGE( m_utility_function->getCost( *path_iter)<<"+"<< m_utility_function->getLinkCostScale()<<"*"<<m_utility_function->getPathSizeCoefficient()<<"*"<<log(find_ps->second)); double utility = m_utility_function->getCostWithPathSize(*path_iter, find_ps->second); utility_vector.push_back(exp(utility)); DEBUG_MESSAGE(utility<<","<<utility_vector.back()); sampled_empirical_proba.push_back(0.0); sampled_count.push_back(0); } double sum = 0.0; for (vector<double>::const_iterator u_iter = utility_vector.begin(); u_iter != utility_vector.end(); ++u_iter) { sum += *u_iter; } for (vector<double>::size_type i = 0; i < utility_vector.size(); ++i) { utility_vector[i] /= sum; } // return; DEBUG_MESSAGE(paths_vector.size()<<" alternatives"); unsigned int total_sampled_count = 1000; ofstream sampled_file((folder + "sampled.txt").c_str()); for (unsigned int i = 0; i < total_sampled_count; ++i) { // if (i % 10 == 0) { // DEBUG_MESSAGE(i); // } string i_str = boost::lexical_cast<string>(i); patKMLPathWriter kml_writer(folder + "observations/" + i_str + ".kml"); int sampled = patSampleDiscreteDistribution()(utility_vector, m_rnd); sampled_file << sampled << endl; sampled_observations.push_back(sampled); sampled_empirical_proba[sampled] += 1.0 / (double) total_sampled_count; sampled_count[sampled]++; map<string, string> attrs_true; attrs_true["true"] = boost::lexical_cast<string>( utility_vector[sampled]); attrs_true["id"] = boost::lexical_cast<string>(sampled); attrs_true["proba"] = boost::lexical_cast<string>( 1.0 - patNBParameters::the()->errorInSimulatedObservations); kml_writer.writePath(paths_vector[sampled], attrs_true); //Deprecated and replaced by patSimulationProbabilisicObs // if (patNBParameters::the()->errorInSimulatedObservations > 0.0 // && patNBParameters::the()->nbrOfSimulatedErrorPaths > 0) { // patSimulateProbabilisticPaths simulate_prob_paths( // paths_vector[sampled], router); // map<patMultiModalPath, double> simulated_paths = // simulate_prob_paths.run( // patNBParameters::the()->nbrOfSimulatedErrorPaths, // patNBParameters::the()->errorInSimulatedObservations); // for (map<patMultiModalPath, double>::iterator path_iter = // simulated_paths.begin(); path_iter != simulated_paths.end(); // ++path_iter) { // map<string, string> attrs; // attrs["true"] = boost::lexical_cast<string>( // utility_vector[sampled]); // attrs["id"] = boost::lexical_cast<string>(sampled); // attrs["proba"] = boost::lexical_cast<string>(path_iter->second); // kml_writer.writePath(path_iter->first, attrs); // // } // } kml_writer.close(); } sampled_file.close(); double chi2 = 0.0; for (unsigned int i = 0; i < utility_vector.size(); ++i) { double empirical_proba = (double) sampled_count[i] / total_sampled_count; double theo_proba = utility_vector[i]; chi2 += total_sampled_count * (theo_proba - empirical_proba) * (theo_proba - empirical_proba) / theo_proba; DEBUG_MESSAGE( utility_vector[i]<<","<<sampled_count[i]/(double)total_sampled_count); }DEBUG_MESSAGE("chi2: "<<chi2); } patSimulation::~patSimulation() { // TODO Auto-generated destructor stub }
35.348387
170
0.730243
[ "vector" ]
54813e0ce0605ed72295f2135bc2bca7ed53fc4d
3,107
hh
C++
gecode/string/extensional.hh
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
1
2021-05-26T13:27:00.000Z
2021-05-26T13:27:00.000Z
gecode/string/extensional.hh
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
gecode/string/extensional.hh
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
#ifndef __GECODE_STRING_EXT_HH__ #define __GECODE_STRING_EXT_HH__ namespace Gecode { namespace String { // DFA data structure for non-reified regular. struct stringDFA { typedef std::vector<std::vector<std::pair<int, int>>> delta_t; int ua; int ur; int n_states; int final_fst; int final_lst; delta_t delta; stringDFA(const DFA&); void negate(const NSIntSet&); bool final(int) const; int search(int, int) const; bool accepted(string) const; bool univ_accepted(const NSIntSet& Q) const; bool univ_rejected(const NSIntSet& Q) const; NSIntSet alphabet() const; NSIntSet neighbours(int) const; NSIntSet neighbours(int, const DSIntSet&) const; void compute_univ(const NSIntSet& alphabet); protected: int nstate(int) const; }; // Complete DFA for reified regular. struct stringCDFA : public stringDFA { stringCDFA(const DFA&, const NSIntSet&); void negate(); }; /** * \brief %Propagator for DFA. * */ class Reg : public UnaryPropagator<StringView, PC_STRING_DOM> { private: stringDFA* dfa; protected: using UnaryPropagator<StringView, PC_STRING_DOM>::x0; /// Constructor for cloning \a p Reg(Space& home, Reg& p); /// Constructor for posting Reg(Home home, StringView, stringDFA* p); public: /// Copy propagator during cloning virtual Actor* copy(Space& home); /// Perform propagation virtual ExecStatus propagate(Space& home, const ModEventDelta& med); /// Post propagator static ExecStatus post(Home home, StringView x, const DFA& dfa); static ExecStatus post(Home home, StringView x, stringDFA* pdfa); static NSBlocks dom(stringDFA*); static std::vector<NSIntSet> reach_fwd( stringDFA*, const NSIntSet&, const DSBlock&, bool reif = false, bool bwd = false ); static NSBlocks reach_bwd(stringDFA*, const std::vector<NSIntSet>&, NSIntSet&, const DSBlock&, bool&, bool rev = false ); ~Reg(); }; /** * \brief %Propagator for reified DFA. * */ template<class CtrlView, ReifyMode rm> class ReReg : public Propagator { protected: StringView x0; CtrlView b; /// Constructor for cloning \a p ReReg(Space& home, ReReg&); /// Constructor for posting ReReg(Home home, StringView x, stringCDFA* d, CtrlView b); private: stringCDFA* dfa; public: /// Copy propagator during cloning virtual Actor* copy(Space& home); /// Cost function (defined as PC_TERNARY_LO) virtual PropCost cost(const Space& home, const ModEventDelta& med) const; /// Schedule function virtual void reschedule(Space& home); /// Delete propagator and return its size virtual size_t dispose(Space& home); /// Perform propagation virtual ExecStatus propagate(Space& home, const ModEventDelta& med); /// Post propagator for \f$ (x=y) \Leftrightarrow b\f$ static ExecStatus post(Home home, StringView x, const DFA& d, CtrlView b); ~ReReg(); }; }} #include <gecode/string/ext/reg.hpp> #include <gecode/string/ext/re-reg.hpp> #endif
29.311321
78
0.674284
[ "vector" ]
5485658c92908dc86ff062f72fa9be5584479e56
1,984
cpp
C++
solved/0-b/array-queries/array-segtree.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/0-b/array-queries/array-segtree.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/0-b/array-queries/array-segtree.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <algorithm> #include <cmath> #include <cstdio> #include <vector> using namespace std; #define MAXN 100000 typedef unsigned int u32; typedef vector<int> IV; // // I/O // #define BUF 524288 struct Reader { char buf[BUF]; char b; int bi, bz; Reader() { bi=bz=0; read(); } void read() { if (bi==bz) { bi=0; bz = fread(buf, 1, BUF, stdin); } b = bz ? buf[bi++] : 0; } void skip() { while (b > 0 && b <= 32) read(); } u32 next_u32() { u32 v = 0; for (skip(); b > 32; read()) v = v*10 + b-48; return v; } }; // // Segment Tree // struct SegTree { IV A, M; int n; SegTree(int N) : n(N) { A.resize(n); int h = 1 + ceil(log2(n)); M.resize(1 << h); } void init() { tree_init(1, 0, n - 1); } int query_val(int i, int j) { return A[tree_query(1, 0, n - 1, i, j)]; } void tree_init(int x, int a, int b) { if (a == b) { M[x] = a; return; } int l = 2*x, r = 2*x + 1, m = (a+b)/2; tree_init(l, a, m); tree_init(r, m + 1, b); M[x] = A[M[l]] <= A[M[r]] ? M[l] : M[r]; } int tree_query(int x, int a, int b, int i, int j) { if (j < a || i > b) return -1; if (a >= i && b <= j) return M[x]; int l = 2*x, r = 2*x + 1, m = (a+b)/2; int q1 = tree_query(l, a, m, i, j); int q2 = tree_query(r, m + 1, b, i, j); if (q1 < 0) return q2; if (q2 < 0) return q1; return A[q1] <= A[q2] ? q1 : q2; } }; int N, q; int I, J; int main() { Reader rr; int T = rr.next_u32(); int ncase = 0; while (T--) { N = rr.next_u32(); q = rr.next_u32(); SegTree tree(N); for (int i = 0; i < N; ++i) tree.A[i] = rr.next_u32(); printf("Case %d:\n", ++ncase); tree.init(); while (q--) { I = rr.next_u32(); J = rr.next_u32(); printf("%d\n", tree.query_val(I - 1, J - 1)); } } return 0; }
21.565217
76
0.448085
[ "vector" ]
548faa6bd9bfebb683b8f94dc50dd46a9ec4a12a
3,573
cc
C++
scsp/src/model/TransferCallToAgentRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
scsp/src/model/TransferCallToAgentRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
scsp/src/model/TransferCallToAgentRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/scsp/model/TransferCallToAgentRequest.h> using AlibabaCloud::Scsp::Model::TransferCallToAgentRequest; TransferCallToAgentRequest::TransferCallToAgentRequest() : RpcServiceRequest("scsp", "2020-07-02", "TransferCallToAgent") { setMethod(HttpRequest::Method::Post); } TransferCallToAgentRequest::~TransferCallToAgentRequest() {} std::string TransferCallToAgentRequest::getClientToken()const { return clientToken_; } void TransferCallToAgentRequest::setClientToken(const std::string& clientToken) { clientToken_ = clientToken; setBodyParameter("ClientToken", clientToken); } std::string TransferCallToAgentRequest::getInstanceId()const { return instanceId_; } void TransferCallToAgentRequest::setInstanceId(const std::string& instanceId) { instanceId_ = instanceId; setBodyParameter("InstanceId", instanceId); } std::string TransferCallToAgentRequest::getAccountName()const { return accountName_; } void TransferCallToAgentRequest::setAccountName(const std::string& accountName) { accountName_ = accountName; setBodyParameter("AccountName", accountName); } std::string TransferCallToAgentRequest::getTargetAccountName()const { return targetAccountName_; } void TransferCallToAgentRequest::setTargetAccountName(const std::string& targetAccountName) { targetAccountName_ = targetAccountName; setBodyParameter("TargetAccountName", targetAccountName); } std::string TransferCallToAgentRequest::getCallId()const { return callId_; } void TransferCallToAgentRequest::setCallId(const std::string& callId) { callId_ = callId; setBodyParameter("CallId", callId); } std::string TransferCallToAgentRequest::getJobId()const { return jobId_; } void TransferCallToAgentRequest::setJobId(const std::string& jobId) { jobId_ = jobId; setBodyParameter("JobId", jobId); } std::string TransferCallToAgentRequest::getConnectionId()const { return connectionId_; } void TransferCallToAgentRequest::setConnectionId(const std::string& connectionId) { connectionId_ = connectionId; setBodyParameter("ConnectionId", connectionId); } std::string TransferCallToAgentRequest::getHoldConnectionId()const { return holdConnectionId_; } void TransferCallToAgentRequest::setHoldConnectionId(const std::string& holdConnectionId) { holdConnectionId_ = holdConnectionId; setBodyParameter("HoldConnectionId", holdConnectionId); } int TransferCallToAgentRequest::getType()const { return type_; } void TransferCallToAgentRequest::setType(int type) { type_ = type; setBodyParameter("Type", std::to_string(type)); } std::string TransferCallToAgentRequest::getIsSingleTransfer()const { return isSingleTransfer_; } void TransferCallToAgentRequest::setIsSingleTransfer(const std::string& isSingleTransfer) { isSingleTransfer_ = isSingleTransfer; setBodyParameter("IsSingleTransfer", isSingleTransfer); }
25.521429
92
0.769661
[ "model" ]
549b763da45bc03d5c8c25d70460be91db82000d
30,422
cc
C++
Core/DianYing/Source/Core/Thread/TDyIO.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
4
2019-03-17T19:46:54.000Z
2019-12-09T20:11:01.000Z
Core/DianYing/Source/Core/Thread/TDyIO.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
null
null
null
Core/DianYing/Source/Core/Thread/TDyIO.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
null
null
null
#include <precompiled.h> /// /// MIT License /// Copyright (c) 2018-2019 Jongmin Yun /// /// 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. /// /// Header file #include <Dy/Core/Thread/TRescIO.h> #include <assimp/Importer.hpp> #include <Dy/Core/Thread/SIOConnectionHelper.h> #include <Dy/Core/Resource/Resource/FResourceModel.h> #include <Dy/Core/Resource/Resource/FrameBuffer/FResourceFrameBufferGeneral.h> #include <Dy/Core/Resource/Resource/FrameBuffer/FResourceFrameBufferPingPong.h> #include <Dy/Core/Resource/Internal/FMeshVBOIntermediate.h> #include <Dy/Meta/Information/MetaInfoMaterial.h> #include <Dy/Meta/Information/MetaInfoModelAnim.h> #include <Dy/Meta/Information/MetaInfoFrameBuffer.h> #include <Dy/Management/IO/MIORescInfo.h> #include <Dy/Management/IO/MIOResource.h> #include <Dy/Management/IO/MIOMeta.h> #include <Dy/Management/MWindow.h> #include <Dy/Builtin/Constant/GeneralValue.h> constexpr TU8 kDefaultPriority = 128; namespace dy { TRescIO::TRescIO() { this->MIOMetaManager = &MIOMeta::GetInstance(); this->mIODataManager = &MIORescInfo::GetInstance(); this->mIOResourceManager = &MIOResource::GetInstance(); } TRescIO::~TRescIO() { this->mIOResourceManager = nullptr; this->mIODataManager = nullptr; this->MIOMetaManager = nullptr; } EDySuccess TRescIO::Initialize() { // Initialize IOWorkers with context. const auto& windowManager = MWindow::GetInstance(); const auto& workerWndList = windowManager.GetGLWorkerWindowList(); MDY_ASSERT_MSG( workerWndList.size() == this->mWorkerList.size(), "WndList and I/O Worker list size must be same."); // Make worker instance list. for (TIndex i = 0, size = this->mWorkerList.size(); i < size; ++i) { auto& [instance, thread] = this->mWorkerList[i]; instance = std::make_unique<TRescIOWorker>(MIOMeta::GetInstance()); thread = std::thread(&TRescIOWorker::operator(), std::ref(*instance), std::ref(*workerWndList[i])); } return EDySuccess::DY_SUCCESS; } void TRescIO::Release() { } void TRescIO::operator()() { MDY_CALL_ASSERT_SUCCESS(this->Initialize()); while (true) { DRescIOTask task; { // Wait task in the queue, and try pop task when not empty. // Wait for condition variable for task queueing processing routine. MDY_SYNC_WAIT_CONDITION( this->mMutexTaskQueue, this->mConditionVariable, [this] { return this->mIsThreadStopped == true || this->mIOTaskQueue.empty() == false; } ); // If IO thread must be stopped, reset all task queue. if (this->mIsThreadStopped == false) { task = this->mIOTaskQueue.top(); this->mIOTaskQueue.pop(); } else { while (this->mIOTaskQueue.empty() == false) { this->mIOTaskQueue.pop(); } for (auto& [workerInstance, workerThread] : this->mWorkerList) { // Wait all worker thread are terminated. // Wait worker instance to be ended and return `mMutexTask` signal. workerInstance->SyncTryStop(); workerThread.join(); workerInstance = nullptr; } break; } } // Wait any worker is idle, if there is idle worker assign task to worker. // We used spinlock, for avoiding complexity of control semaphore and counter. while (true) { for (auto& [instance, thread] : this->mWorkerList) { const auto isSucceeded = instance->outTryAssign(task); if (isSucceeded == EDySuccess::DY_SUCCESS) { // We use goto statement intentionally. goto LABEL_DY_AFTER_INSERT_TASK; } } } LABEL_DY_AFTER_INSERT_TASK: MDY_SLEEP_FOR_ATOMIC_TIME(); } this->Release(); } void TRescIO::SyncInsertResult(const DRescIOWorkerResult& result) noexcept { MDY_SYNC_LOCK_GUARD(this->mResultListMutex); this->mWorkerResultList.emplace_back(result); } void TRescIO::SyncTryForwardTaskToMainList(const DRescIOTask& forwardedMainTask) noexcept { MDY_SYNC_LOCK_GUARD(this->mMutexMainProcessTask); this->mIOProcessMainTaskList.emplace_back(forwardedMainTask); } void TRescIO::SyncTryStop() { MDY_ASSERT_MSG(this->outIsIOThreadSlept() == true, "To stop io thread, IO Thread must be slept."); { MDY_SYNC_LOCK_GUARD(this->mMutexTaskQueue); this->mIsThreadStopped = true; } this->mConditionVariable.notify_one(); MDY_SLEEP_FOR_ATOMIC_TIME(); } EDySuccess TRescIO::outTryEnqueueTask( const std::string& iSpecifier, EResourceType iResourceType, EResourceStyle iResourceStyle, EResourceScope iScope, bool iIsDerivedFromResource) { if (iResourceStyle == EResourceStyle::Information) { const auto specifier = TryRemovePostfix(iSpecifier, kInstancingPostfix); MDY_ASSERT_MSG_FORCE( this->outIsMetaInformationExist(specifier, iResourceType) == true, "Meta information must be exist."); } // Query there is Reference Instance for myself. If found, just return do nothing. { std::vector<PRIVerificationItem> itselfRIItem{}; itselfRIItem.emplace_back(iSpecifier, iResourceType, iResourceStyle, iScope); const auto result = this->pCheckAndUpdateReferenceInstance(itselfRIItem); if (result.empty() == true || result.begin()->second != ERIState::NotExist) { return EDySuccess::DY_SUCCESS; } } // Make dependency list. DRescIODeferredTask::TConditionList conditionList = {}; const auto checkList = this->pMakeDependenciesCheckList(iSpecifier, iResourceType, iResourceStyle, iScope); if (checkList.empty() == false) { // And get not-found list from dependency list. const auto notFoundRIList = this->pCheckAndUpdateReferenceInstance(checkList); if (notFoundRIList.empty() == false) { for (const auto& [instance, status] : notFoundRIList) { // Require depende resource tasks only if NotValid but RI is exist. const auto& [specifier, type, style, scope] = instance; if (status == ERIState::NotExist) { outTryEnqueueTask(specifier, type, style, scope, true); } conditionList.emplace_back(specifier, type, style); } } } // Require itself own resource task. MDY_CALL_ASSERT_SUCCESS( this->CreateReferenceInstance(iSpecifier, iResourceType, iResourceStyle, iScope) ); // Construct IO Tasks. DRescIOTask task; { task.mSpecifierName = iSpecifier; task.mResourceType = iResourceType; task.mResourcecStyle = iResourceStyle; task.mScope = iScope; task.mTaskPriority = kDefaultPriority; task.mIsResourceDeferred = iIsDerivedFromResource; task.mBoundObjectStyle = EDyObject::Etc_NotBindedYet; task.mPtrBoundObject = nullptr; } // If this is model & resource task, change `mResourceType` to `__ModelVBO` as intermediate task. // Because VAO can not be created and shared from other thread not main thread. if (task.mResourceType == EResourceType::Mesh && task.mResourcecStyle == EResourceStyle::Resource) { task.mResourceType = EResourceType::__MeshVBO; } // Make deferred task and forward deferred task to list (atomic) if (conditionList.empty() == false) { this->SyncInsertTaskToDeferredList({task, conditionList}); } else { // Just insert task to queue, if anything does not happen. { // Critical section. MDY_SYNC_LOCK_GUARD(this->mMutexTaskQueue); if (this->mIsThreadStopped == true) { return EDySuccess::DY_FAILURE; } this->mIOTaskQueue.emplace(task); } this->mConditionVariable.notify_one(); } return EDySuccess::DY_SUCCESS; } EDySuccess TRescIO::CreateReferenceInstance( const std::string& specifier, EResourceType type, EResourceStyle style, EResourceScope scope) { switch (style) { case EResourceStyle::Information: return this->mRIInformationMap.CreateReferenceInstance(specifier, type, style, scope); case EResourceStyle::Resource: return this->mRIResourceMap.CreateReferenceInstance(specifier, type, style, scope); default: MDY_UNEXPECTED_BRANCH(); throw 0; } } std::vector<TRescIO::PRIVerificationItem> TRescIO::pMakeDependenciesCheckList( const std::string& iSpecifier, EResourceType iResourceType, EResourceStyle iResourceStyle, EResourceScope iScope) const { std::vector<PRIVerificationItem> checkList = {}; if (iResourceType == EResourceType::Material) { // If resource type is `Material`, bind all dependencies of `Material` to checkList. const auto materialName = TryRemovePostfix(iSpecifier, kInstancingPostfix); const auto& metaMaterial = this->MIOMetaManager->GetMaterialMetaInformation(materialName); // Texture for (const auto& bindingTextureItem : metaMaterial.mTextureNames) { if (bindingTextureItem.mTextureSpecifier.empty() == true) { break; } checkList.emplace_back( bindingTextureItem.mTextureSpecifier, EResourceType::Texture, iResourceStyle, iScope); } // Shader (If supports instancing, must have postfix "__inst". auto shaderName = metaMaterial.mShaderSpecifier; if (HasPostfix(iSpecifier, kInstancingPostfix) == true) { shaderName += kInstancingPostfix; } checkList.emplace_back(shaderName, EResourceType::GLShader, iResourceStyle, iScope); } else if (iResourceType == EResourceType::GLFrameBuffer) { // If resource type is `FrameBuffer`, bind all dependencies of `FrameBuffer` to checkList. const auto& metaInfo = this->MIOMetaManager->GetGlFrameBufferMetaInformation(iSpecifier); // Get dependent attachment specifier list and add. for (const auto& [specifier, type] : metaInfo.mColorAttachmentList) { checkList.emplace_back(specifier, EResourceType::GLAttachment, iResourceStyle, iScope); } // If framebuffer also use depth buffer, enqueue it. if (metaInfo.mIsUsingDepthBuffer == true) { MDY_ASSERT_MSG( metaInfo.mDepthAttachmentSpecifier.empty() == false, "Depth attachment must be specified if use depth buffer."); checkList.emplace_back( metaInfo.mDepthAttachmentSpecifier, EResourceType::GLAttachment, iResourceStyle, iScope); } } else if (iResourceType == EResourceType::Model) { // If resource type is `Model` and if using builtin mesh specifier... const auto& metaInfo = this->MIOMetaManager->GetModelMetaInformation(iSpecifier); // Get dependent attachment specifier list and add. for (const auto& [meshSpecifier, materialSpecifier, isInstanced] : metaInfo.mMeshList) { // If this list is need to be instanced... std::string requiredMeshSpecifier = meshSpecifier; std::string requiredMatSpecifier = materialSpecifier; if (isInstanced == true) { // And mesh does not be a separated name if info. if (iResourceStyle == EResourceStyle::Resource) { requiredMeshSpecifier += kInstancingPostfix; } requiredMatSpecifier += kInstancingPostfix; } // Mesh with instancing or not... // Material with instancing or not... checkList.emplace_back(requiredMeshSpecifier, EResourceType::Mesh, iResourceStyle, iScope); checkList.emplace_back(requiredMatSpecifier, EResourceType::Material, iResourceStyle, iScope); } // If this model will use skeleton, add skeleton (information) also. // Skeleton resource only has `information`. if (metaInfo.mSkeleton.mIsUsingSkeleton == true) { checkList.emplace_back( metaInfo.mSkeleton.mSkeletonSpecifier, EResourceType::Skeleton, EResourceStyle::Information, iScope); } } else if (iResourceType == EResourceType::AnimationScrap) { // If resource type is `AnimationScrap`, `Skeleton` must be populated also. const auto& metaInfo = this->MIOMetaManager->GetModelAnimScrapMetaInformation(iSpecifier); MDY_ASSERT_MSG_FORCE( metaInfo.mSkeletonSpeicfier.empty() == false, "Skeleton specifier of animation scrap must not be empty."); // `AnimationScrap` could only be populated as `Information`, // so dependent Skeleton also be a `Information`. checkList.emplace_back(metaInfo.mSkeletonSpeicfier, EResourceType::Skeleton, iResourceStyle, iScope); } // Resource common dependencies. if (iResourceStyle == EResourceStyle::Resource) { switch (iResourceType) { case EResourceType::Mesh: { auto specifier = TryRemovePostfix(iSpecifier, kInstancingPostfix); checkList.emplace_back(specifier, iResourceType, EResourceStyle::Information, iScope); } break; case EResourceType::Material: case EResourceType::Model: case EResourceType::GLShader: case EResourceType::Texture: case EResourceType::GLAttachment: case EResourceType::GLFrameBuffer: { checkList.emplace_back(iSpecifier, iResourceType, EResourceStyle::Information, iScope); } break; default: MDY_UNEXPECTED_BRANCH_BUT_RETURN(checkList); } } return checkList; } EDySuccess TRescIO::InstantPopulateMaterialResource( const PDyMaterialInstanceMetaInfo& iDesc, TResourceBinder<EResourceType::Material>& refMat, EResourceScope iScope, bool(*callback)()) { MDY_ASSERT_MSG(callback == nullptr, "Callback material resource population is not supported yet."); MDY_ASSERT_MSG(iScope == EResourceScope::Temporal, "Temporary material resource population must be inputted."); // If resource type is `Material`, bind all dependencies of `Material` to checkList. std::vector<PRIVerificationItem> checkList = {}; { for (const auto& bindingTextureItem : iDesc.mTextureNames) { if (bindingTextureItem.mTextureSpecifier.empty() == true) { break; } checkList.emplace_back( bindingTextureItem.mTextureSpecifier, EResourceType::Texture, EResourceStyle::Resource, iScope); } checkList.emplace_back( iDesc.mShaderSpecifier, EResourceType::GLShader, EResourceStyle::Resource, iScope); } // If `checkList` is not empty, check dependencies. DRescIODeferredTask::TConditionList conditionList = {}; if (checkList.empty() == false) { // And get not-found list from dependency list. const auto notFoundRIList = this->pCheckAndUpdateReferenceInstance(checkList); if (notFoundRIList.empty() == false) { for (const auto& [instance, status] : notFoundRIList) { // Require depende resource tasks only if NotValid but RI is exist. const auto& [specifier, type, style, scope] = instance; if (status == ERIState::NotExist) { MDY_CALL_BUT_NOUSE_RESULT(outTryEnqueueTask(specifier, type, style, scope, true)); } conditionList.emplace_back(specifier, type, style); } } } // Require itself own resource task. MDY_CALL_ASSERT_SUCCESS(this->CreateReferenceInstance( iDesc.mSpecifierName, EResourceType::Material, EResourceStyle::Resource, iScope)); // Construct IO Tasks. DRescIOTask task; { task.mSpecifierName = iDesc.mSpecifierName; task.mResourceType = EResourceType::Material; task.mResourcecStyle = EResourceStyle::Resource; task.mScope = EResourceScope::Temporal; task.mTaskPriority = 192; task.mIsResourceDeferred = false; task.mBoundObjectStyle = EDyObject::Etc_NotBindedYet; task.mPtrBoundObject = &refMat; task.mRawInstanceForUsingLater = iDesc; } // Make deferred task and forward deferred task to list (atomic) if (conditionList.empty() == false) { this->SyncInsertTaskToDeferredList({task, conditionList}); return EDySuccess::DY_SUCCESS; } // Just insert task to queue, if anything does not happen. // Critical section. { MDY_SYNC_LOCK_GUARD(this->mMutexTaskQueue); if (this->mIsThreadStopped == true) { return EDySuccess::DY_FAILURE; } this->mIOTaskQueue.emplace(task); } this->mConditionVariable.notify_one(); return EDySuccess::DY_SUCCESS; } TRescIO::TDependencyList TRescIO::pCheckAndUpdateReferenceInstance(const std::vector<PRIVerificationItem>& dependencies) noexcept { TDependencyList resultNotFoundList = {}; for (const auto& [specifier, type, style, scope] : dependencies) { // Find if reference instance is on garbage collector. if (this->mGarbageCollector.IsReferenceInstanceExist(specifier, type, style) == true) { MDY_CALL_ASSERT_SUCCESS(this->outTryRetrieveReferenceInstanceFromGC(specifier, type, style)); continue; } // Find dependencies is on memory (not GCed, and avoid duplicated task queing) // Thread safety with RI container is okay, RI GC phase is held on Main thread. if (this->pIsReferenceInstanceExist(specifier, type, style) == true) { // Try enlarge scope of RI. RI scope is large following by Global > Level > Temporal. // Thread safety with RI container is okay, RI GC phase is held on Main thread. this->TryEnlargeResourceScope(scope, specifier, type, style); // Check if RI is bound by actual resource. if (this->pIsReferenceInstanceBound(specifier, type, style) == false) { resultNotFoundList.emplace_back( PRIVerificationItem{specifier, type, style, scope}, ERIState::NotBoundYet); } continue; } resultNotFoundList.emplace_back( PRIVerificationItem{specifier, type, style, scope}, ERIState::NotExist); } return resultNotFoundList; } void TRescIO::TryEnlargeResourceScope( EResourceScope scope, const std::string& specifier, EResourceType type, EResourceStyle style) { switch (style) { case EResourceStyle::Information: this->mRIInformationMap.TryEnlargeResourceScope(scope, specifier, type); break; case EResourceStyle::Resource: this->mRIResourceMap.TryEnlargeResourceScope(scope, specifier, type); break; default: MDY_UNEXPECTED_BRANCH(); } } void TRescIO::SyncInsertTaskToDeferredList(const DRescIODeferredTask& deferredTask) { MDY_SYNC_LOCK_GUARD(this->mMutexDeferredTask); this->mIODeferredTaskList.emplace_back(deferredTask); } EDySuccess TRescIO::outTryRetrieveReferenceInstanceFromGC( const std::string& specifier, EResourceType type, EResourceStyle style) { // Get RI from gc list. auto smtReferenceInstance = this->mGarbageCollector.MoveInstanceFromGC(specifier, type, style); if (smtReferenceInstance == nullptr) { DyPushLogError("Failed to get instance from IO GC, {}.", specifier); return EDySuccess::DY_FAILURE; } // Reinsert RI to appropriate position. switch (style) { case EResourceStyle::Information: return this->mRIInformationMap.MoveReferenceInstance(std::move(smtReferenceInstance)); case EResourceStyle::Resource: return this->mRIResourceMap.MoveReferenceInstance(std::move(smtReferenceInstance)); default: MDY_UNEXPECTED_BRANCH(); throw; } } void TRescIO::outForceProcessIOInsertPhase() noexcept { // CRITICAL PERFORMANCE DOWN! MUST BE CALLED IN SYNCHRONIZATION PHASE. MDY_SYNC_LOCK_GUARD(this->mResultListMutex); for (auto& resultItem : this->mWorkerResultList) { if (resultItem.mRawResultInstance == nullptr) { continue; } if (resultItem.mResourceStyle == EResourceStyle::Information) { this->mIODataManager->InsertResult(resultItem.mResourceType, resultItem.mRawResultInstance); MDY_CALL_ASSERT_SUCCESS(this->mRIInformationMap.TryUpdateValidity( resultItem.mResourceType, resultItem.mSpecifierName, true, resultItem.mRawResultInstance)); } else { this->mIOResourceManager->InsertResult(resultItem.mResourceType, resultItem.mRawResultInstance); MDY_CALL_ASSERT_SUCCESS(this->mRIResourceMap.TryUpdateValidity( resultItem.mResourceType, resultItem.mSpecifierName, true, resultItem.mRawResultInstance)); } // If need to insert resource task of deferred list into queue, do this. this->pTryUpdateDeferredTaskList( resultItem.mSpecifierName, resultItem.mResourceType, resultItem.mResourceStyle); } this->mWorkerResultList.clear(); } void TRescIO::pTryUpdateDeferredTaskList( const std::string& iSpecifier, EResourceType iType, EResourceStyle iStyle) { std::vector<DRescIOTask> reinsertionTasklist = {}; // Critical Section { MDY_SYNC_LOCK_GUARD(this->mMutexDeferredTask); for (auto it = this->mIODeferredTaskList.begin(); it != this->mIODeferredTaskList.end();) { auto& deferredTask = *it; // Try remove condition item. If removed something, try it'is satisfied with reinsertion condition. if (deferredTask.TryRemoveDependentItem(iSpecifier, iType, iStyle) == EDySuccess::DY_SUCCESS && deferredTask.IsSatisfiedReinsertCondition() == true) { reinsertionTasklist.emplace_back(deferredTask.mTask); it = this->mIODeferredTaskList.erase(it); } else { ++it; } } } // Reinserted deferred task will have more high priority. for (auto& task : reinsertionTasklist) { task.mTaskPriority = task.mTaskPriority + 1; } // Critical Section { MDY_SYNC_LOCK_GUARD(this->mMutexTaskQueue); for (const auto& task : reinsertionTasklist) { if (this->mIsThreadStopped == true) { return; } this->mIOTaskQueue.emplace(task); } } this->mConditionVariable.notify_one(); } //! //! Task resource population from main thread. //! void TRescIO::outMainForceProcessDeferredMainTaskList() { MDY_SYNC_LOCK_GUARD(this->mMutexMainProcessTask); for (const auto& task : this->mIOProcessMainTaskList) { SIOConnectionHelper::InsertWorkerResult(outMainProcessTask(task)); } this->mIOProcessMainTaskList.clear(); } DRescIOWorkerResult TRescIO::outMainProcessTask(_MIN_ const DRescIOTask& task) { DRescIOWorkerResult result{}; { // Copy properties to result instance. result.mResourceType = task.mResourceType; result.mResourceStyle = task.mResourcecStyle; result.mSpecifierName = task.mSpecifierName; result.mIsHaveDeferredTask = task.mIsResourceDeferred; } MDY_ASSERT_MSG( task.mResourcecStyle == EResourceStyle::Resource, "Main deferred task must be resource style."); const auto& infoManager = MIORescInfo::GetInstance(); switch (task.mResourceType) { case EResourceType::GLShader: { // Need to move it as independent function. const auto instance = new FResourceShader( *infoManager.GetPtrInformation<EResourceType::GLShader>(result.mSpecifierName)); result.mRawResultInstance = instance; } break; case EResourceType::Mesh: { // Get intermediate instance from task, and make mesh resource. Owner<FMeshVBOIntermediate*> ptrrawIntermediateInstance = std::any_cast<FMeshVBOIntermediate*>(task.mRawInstanceForUsingLater); const auto instance = new FResourceMesh(*ptrrawIntermediateInstance); MDY_DELETE_RAWHEAP_SAFELY(ptrrawIntermediateInstance); result.mRawResultInstance = instance; } break; case EResourceType::GLFrameBuffer: { // Only Resource, create fbo with attachment. const auto& refInfo = *infoManager.GetPtrInformation<EResourceType::GLFrameBuffer>(result.mSpecifierName); if (refInfo.IsPingPong() == true) { const auto instance = new FResourceFrameBufferPingPong(refInfo); result.mRawResultInstance = instance; } else { const auto instance = new FResourceFrameBufferGeneral(refInfo); result.mRawResultInstance = instance; } } break; default: MDY_UNEXPECTED_BRANCH(); break; }; return result; } //! //! Condition //! bool TRescIO::pIsReferenceInstanceExist(_MIN_ const std::string& specifier, _MIN_ EResourceType type, _MIN_ EResourceStyle style) { switch (style) { case EResourceStyle::Information: return this->mRIInformationMap.IsReferenceInstanceExist(specifier, type); case EResourceStyle::Resource: return this->mRIResourceMap.IsReferenceInstanceExist(specifier, type); default: MDY_UNEXPECTED_BRANCH_BUT_RETURN(false); } } EDySuccess TRescIO::TryBindBinderToResourceRI (const std::string& iSpecifier, EResourceType iType, IBinderBase& iPtrBinder) { return this->mRIResourceMap.TryBindBinderToResourceRI(iSpecifier, iType, iPtrBinder); } EDySuccess TRescIO::TryBindBinderToInformationRI (const std::string& iSpecifier, EResourceType iType, IBinderBase& iPtrBinder) { return this->mRIInformationMap.TryBindBinderToResourceRI(iSpecifier, iType, iPtrBinder); } EDySuccess TRescIO::TryDetachBinderFromResourceRI (const std::string& iSpecifier, EResourceType iType, IBinderBase& iPtrBinder) { return this->mRIResourceMap.TryDetachBinderFromResourceRI(iSpecifier, iType, iPtrBinder); } EDySuccess TRescIO::TryDetachBinderFromInformationRI (const std::string& iSpecifier, EResourceType iType, IBinderBase& iPtrBinder) { return this->mRIInformationMap.TryDetachBinderFromResourceRI(iSpecifier, iType, iPtrBinder); } bool TRescIO::pIsReferenceInstanceBound(_MIN_ const std::string& specifier, _MIN_ EResourceType type, _MIN_ EResourceStyle style) { switch (style) { case EResourceStyle::Information: return this->mRIInformationMap.IsReferenceInstanceBound(specifier, type); case EResourceStyle::Resource: return this->mRIResourceMap.IsReferenceInstanceBound(specifier, type); default: MDY_UNEXPECTED_BRANCH_BUT_RETURN(false); } } bool TRescIO::outIsMetaInformationExist(_MIN_ const std::string& specifier, _MIN_ EResourceType type) { MDY_ASSERT_MSG(MDY_CHECK_ISNOTNULL(this->MIOMetaManager), "MetaInformation manager must not be null."); switch (type) { case EResourceType::Script: return this->MIOMetaManager->IsScriptMetaInformationExist(specifier); case EResourceType::Mesh: return this->MIOMetaManager->IsMeshMetaInfoExist(specifier); case EResourceType::Model: return this->MIOMetaManager->IsModelMetaInfoExist(specifier); case EResourceType::Skeleton: return this->MIOMetaManager->IsModelSkeletonMetaInfoExist(specifier); case EResourceType::AnimationScrap: return this->MIOMetaManager->IsModelAnimScrapMetaInfoExist(specifier); case EResourceType::GLShader: return this->MIOMetaManager->IsGLShaderMetaInfoExist(specifier); case EResourceType::Texture: return this->MIOMetaManager->IsTextureMetaInfoExist(specifier); case EResourceType::Material: return this->MIOMetaManager->IsMaterialMetaInfoExist(specifier); case EResourceType::WidgetMeta: return this->MIOMetaManager->IsWidgetMetaInfoExist(specifier); case EResourceType::GLAttachment: return this->MIOMetaManager->IsAttachmentMetaInfoExist(specifier); case EResourceType::GLFrameBuffer: return this->MIOMetaManager->IsFrameBufferMetaInfoExist(specifier); case EResourceType::Sound: return this->MIOMetaManager->IsSoundMetaInfoExist(specifier); default: MDY_UNEXPECTED_BRANCH_BUT_RETURN(false); } } void TRescIO::BindSleepCallbackFunction(_MIN_ std::function<void()> iCbFunc) { if (this->mCbSleepFunction == nullptr) { mCbSleepFunction = nullptr; mCbSleepFunction = iCbFunc; } else { this->mCbNextSleepFunction = nullptr; this->mCbNextSleepFunction = iCbFunc; } } bool TRescIO::outIsIOThreadSlept() noexcept { bool sleptFlag; { MDY_SYNC_LOCK_GUARD(this->mMutexTaskQueue); MDY_SYNC_LOCK_GUARD(this->mMutexDeferredTask); MDY_SYNC_LOCK_GUARD(this->mResultListMutex); // Check all worker are idle. for (const auto& [instance, thread] : this->mWorkerList) { if (instance == nullptr) { continue; } if (instance->SyncIsIdle() == false) { sleptFlag = false; break; }; } // Check queue and list are empty. sleptFlag = this->mIOTaskQueue.empty() && this->mIODeferredTaskList.empty() && this->mWorkerResultList.empty(); } MDY_SLEEP_FOR_ATOMIC_TIME(); return sleptFlag; } EDySuccess TRescIO::outTryCallSleptCallbackFunction() { if (this->outIsIOThreadSlept() == false) { return EDySuccess::DY_FAILURE; } if (this->mCbSleepFunction == nullptr) { return EDySuccess::DY_FAILURE; } this->mCbSleepFunction(); this->mCbSleepFunction = nullptr; if (this->mCbNextSleepFunction != nullptr) { this->mCbSleepFunction = this->mCbNextSleepFunction; this->mCbNextSleepFunction = nullptr; } return EDySuccess::DY_SUCCESS; } void TRescIO::outInsertGcCandidate(std::unique_ptr<DIOReferenceInstance>& iRefRI) { this->mGarbageCollector.InsertGcCandidate(iRefRI); } void TRescIO::outTryForwardCandidateRIToGCList(EResourceScope iScope, EResourceStyle iStyle) { switch (iStyle) { case EResourceStyle::Information: { // Get GC-Candidate RI instance from list (condition is `mIsResourceValid == true` && `mReferenceCount == 0`. // and reinsert it to gc list. auto gcCandidateList = this->mRIInformationMap.GetForwardCandidateRIAsList(iScope); this->mGarbageCollector.InsertGcCandidateList(std::move(gcCandidateList)); } break; case EResourceStyle::Resource: { // Get GC-Candidate RI instance from list (condition is `mIsResourceValid == true` && `mReferenceCount == 0`. // and reinsert it to gc list. auto gcCandidateList = this->mRIResourceMap.GetForwardCandidateRIAsList(iScope); this->mGarbageCollector.InsertGcCandidateList(std::move(gcCandidateList)); } break; default: MDY_UNEXPECTED_BRANCH(); } this->mGarbageCollector.TryGarbageCollectCandidateList(); } bool TRescIO::IsGcCandidateExist() const noexcept { return this->mGarbageCollector.IsGcCandidateExist(); } void TRescIO::TryGC() { this->mGarbageCollector.TryGarbageCollectCandidateList(); } bool TRescIO::isoutIsMainTaskListIsEmpty() const noexcept { return this->mIOProcessMainTaskList.empty(); } bool TRescIO::SyncIsWorkerResultExist() noexcept { MDY_SYNC_LOCK_GUARD(this->mResultListMutex); return this->mWorkerResultList.empty() == false; } } /// :: dy namesapace
34.887615
129
0.721879
[ "mesh", "vector", "model" ]
54a99b0b567e38b36dceac6413182a2acf5bd261
5,518
hpp
C++
src/PluginVisSlice/LassoSelectionTool.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
4
2016-06-03T18:41:43.000Z
2020-04-17T20:28:58.000Z
src/PluginVisSlice/LassoSelectionTool.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
src/PluginVisSlice/LassoSelectionTool.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2022 The Voxie Authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <PluginVisSlice/Layer.hpp> #include <PluginVisSlice/Prototypes.forward.hpp> #include <PluginVisSlice/ToolUtils.hpp> #include <PluginVisSlice/Visualizer2DTool.hpp> #include <PluginVisSlice/ToolUtils.hpp> #include <QtWidgets/QPushButton> #include <math.h> #include <set> #include <Voxie/Gui/ErrorMessage.hpp> #include <Voxie/Interfaces/SegmentationI.hpp> #include <Voxie/Interfaces/StepManagerI.hpp> /** * @brief The LassoSelectionTool provides a way to select Voxels that are * inside a simple polygon that is span by the lasso. This selection can be used * in the segmentation. * @author Max Keller, Alex ... */ class SliceVisualizer; namespace vx { class LassoSelectionLayer; class GeometricPrimitiveData; class LassoSelectionTool : public Visualizer2DTool { Q_OBJECT public: LassoSelectionTool(QWidget* parent, SliceVisualizer* sv); ~LassoSelectionTool() {} QIcon getIcon() override { return QIcon(":/icons/ruler-triangle.png"); } QString getName() override { return "LassoSelection"; } public Q_SLOTS: void activateTool() override; void deactivateTool() override; void toolMousePressEvent(QMouseEvent* e) override; void toolMouseReleaseEvent(QMouseEvent* ev) override; void toolMouseMoveEvent(QMouseEvent* e) override; void toolKeyPressEvent(QKeyEvent* e) override; void toolKeyReleaseEvent(QKeyEvent* e) override; void toolWheelEvent(QWheelEvent* e) override { Q_UNUSED(e) } private: /** * @brief savePoint converts this point to a 3D point and saves it * @param point */ void savePoint(QPointF point); void getStepManager(); /** * @brief Triggers the lassoSelectionLayer redraw. */ void triggerLayerRedraw(); /** * @brief Resets the LassoSelection-Tool and -Layer, * e. g. clears node & line list in the tool & Layer */ void reset(); /** * @brief checks if newLine intersect with a line in lines * @param newLine line */ bool doesNewLineIntersect(QLineF newLine); /** * @brief checks if a new point closes the Polygon * @param point new point (not yet in nodes) */ bool doesPointClosePolygon(QPointF point); /** * @brief returns closest node to passed point * @param point new point (not yet in nodes) */ QPointF getClosestNode(QPointF point); private: vx::StepManagerI* stepManager = nullptr; quint8 minDistance = 10; // minimal distance in pixels between points (of // Polygon) before they are considered equal QList<QPointF> nodes; // points that span the Polygon QList<QLineF> lines; // Lines between the nodes SliceVisualizer* sv; LassoSelectionLayer* lassoLayer; QPushButton* valueButton; bool mousePressed; QPoint startPos; }; class LassoSelectionLayer : public Layer { Q_OBJECT REFCOUNTEDOBJ_DECL(LassoSelectionLayer) public: LassoSelectionLayer(SliceVisualizer* sv); ~LassoSelectionLayer() {} // QIcon getIcon() override { return QIcon(":/icons/ruler-triangle.png"); } QString getName() override { return "de.uni_stuttgart.Voxie.SliceVisualizer.Layer.LassoSelection"; } void render(QImage& outputImage, const QSharedPointer<vx::ParameterCopy>& parameters) override; public Q_SLOTS: /** * @brief newVisibility ; Use this slot when the visibility of points to * either side of the slice change * @param newVis */ void newVisibility(float newVis); /** * @brief adds a Node that should be drawn * @param node Point that should be drawn. */ void addNode(QPointF node); /** * @brief set all nodes That should be drawn (removes old nodes) * @param nodes List of nodes */ void setNodes(QList<QPointF> nodes); private: void drawPoint(QImage& outputImage, float visibility, QPointF point); void changePointName(QPoint point); /** * @brief redraw redraws all the points that have been saved */ void redraw(QImage& outputImage, float visibility); /** * @brief drawLine draws the line between the two points if they are in the * region of visibility around the slice * @param p1 * @param p2 */ void drawLine(QImage& outputImage, float visibility, QPointF p1, QPointF p2); private: SliceVisualizer* sv; float visibility; QList<QPointF> nodes; // all points that span the polygon QPoint mousePos; bool mousePosValid = false; }; } // namespace vx
29.827027
80
0.723813
[ "render", "3d" ]
54b22c984116c6bc5d9e580aa7b06a0af19bfa5b
17,822
cxx
C++
MUON/MUONmapping/AliMpSegmentation.cxx
zwound40/AliRoot
2eeb196e31e59937df6705c3b7fca0e6da4a8cb2
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
MUON/MUONmapping/AliMpSegmentation.cxx
zwound40/AliRoot
2eeb196e31e59937df6705c3b7fca0e6da4a8cb2
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
MUON/MUONmapping/AliMpSegmentation.cxx
zwound40/AliRoot
2eeb196e31e59937df6705c3b7fca0e6da4a8cb2
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * 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$ // $MpId: AliMpSegmentation.cxx,v 1.7 2006/05/24 13:58:34 ivana Exp $ // Category: management //----------------------------------------------------------------------------- // Class AliMpSegmentation // ----------------------- // Singleton container class for mapping segmentations // Authors: Ivana Hrivnacova, IPN Orsay // Laurent Aphecetche, SUBATECH //----------------------------------------------------------------------------- #include "AliMpSegmentation.h" #include "AliMpDataStreams.h" #include "AliMpDetElement.h" #include "AliMpDEStore.h" #include "AliMpDEManager.h" #include "AliMpDEIterator.h" #include "AliMpExMap.h" #include "AliMpFastSegmentation.h" //#include "AliMpFastSegmentationV2.h" #include "AliMpSector.h" #include "AliMpSectorReader.h" #include "AliMpSectorSegmentation.h" #include "AliMpSlat.h" #include "AliMpSlatSegmentation.h" #include "AliMpSt345Reader.h" #include "AliMpTrigger.h" #include "AliMpTriggerReader.h" #include "AliMpTriggerSegmentation.h" #include "AliMpCathodType.h" #include "AliMpSlatMotifMap.h" #include "AliLog.h" #include <Riostream.h> #include <TMap.h> #include <TObjString.h> #include <TSystem.h> #include <TClass.h> #include <cassert> /// \cond CLASSIMP ClassImp(AliMpSegmentation) /// \endcond AliMpSegmentation* AliMpSegmentation::fgInstance = 0; // // static methods // //______________________________________________________________________________ AliMpSegmentation* AliMpSegmentation::Instance(Bool_t warn) { /// Return its instance if ( ! fgInstance && warn ) { AliWarningClass("Segmentation has not been loaded"); } return fgInstance; } //______________________________________________________________________________ AliMpSegmentation* AliMpSegmentation::ReadData(const AliMpDataStreams& dataStreams, Bool_t warn) { /// Load the sementation from ASCII data files /// and return its instance if ( fgInstance ) { if ( warn ) AliWarningClass("Segmentation has been already loaded"); return fgInstance; } if ( dataStreams.GetReadFromFiles() ) AliInfoClass("Reading segmentation from ASCII files."); fgInstance = new AliMpSegmentation(dataStreams); return fgInstance; } // // ctors, dtor // //______________________________________________________________________________ AliMpSegmentation::AliMpSegmentation(const AliMpDataStreams& dataStreams) : TObject(), fDetElements(0), fMpSegmentations(true), fElCardsMap(), fSlatMotifMap(new AliMpSlatMotifMap) { /// Standard constructor - segmentation is loaded from ASCII data files AliDebug(1,""); fElCardsMap.SetOwner(kTRUE); // Load DE data if ( ! AliMpDEStore::Instance(false) ) AliMpDEStore::ReadData(dataStreams); fDetElements = AliMpDEStore::Instance(); // Create mapping segmentations for all detection elements AliMpDEIterator it; for ( it.First(); ! it.IsDone(); it.Next() ) { Int_t n(0); for ( Int_t cath = AliMp::kCath0; cath <= AliMp::kCath1; ++cath ) { if ( CreateMpSegmentation(dataStreams, it.CurrentDEId(), AliMp::GetCathodType(cath)) ) ++n; } if ( n == 2 && // should always be the case except when we play with the CreateMpSegmentation method... AliMpDEManager::GetStationType(it.CurrentDEId()) != AliMp::kStationTrigger ) // only for tracker { // Fill el cards map for all detection elements // of tracking chambers FillElCardsMap(it.CurrentDEId()); } } } //______________________________________________________________________________ AliMpSegmentation::AliMpSegmentation(TRootIOCtor* ioCtor) : TObject(), fDetElements(0), fMpSegmentations(), fElCardsMap(ioCtor), fSlatMotifMap(0) { /// Constructor for IO AliDebug(1,""); fgInstance = this; } //______________________________________________________________________________ AliMpSegmentation::~AliMpSegmentation() { /// Destructor AliDebug(1,""); delete fDetElements; // Segmentations are deleted with fMpSegmentations // El cards arrays are deleted with fElCardsMap delete fSlatMotifMap; fgInstance = 0; } // // private methods // //______________________________________________________________________________ AliMpVSegmentation* AliMpSegmentation::CreateMpSegmentation(const AliMpDataStreams& dataStreams, Int_t detElemId, AliMp::CathodType cath) { /// Create mapping segmentation for given detElemId and cath /// or return it if it was already built // Check detElemId & cath if ( ! AliMpDEManager::IsValidDetElemId(detElemId, true) ) return 0; // If segmentation is already built, just return it // AliMpDetElement* detElement = AliMpDEManager::GetDetElement(detElemId); TString deSegName = detElement->GetSegName(cath); TObject* object = fMpSegmentations.Get(deSegName); if ( object ) return (AliMpVSegmentation*)object; AliDebugStream(3) << "Creating segmentation for detElemId=" << detElemId << " cath=" << cath << endl; // Read mapping data and create segmentation // AliMp::StationType stationType = detElement->GetStationType(); AliMp::PlaneType planeType = detElement->GetPlaneType(cath); TString deTypeName = detElement->GetSegType(); AliMpVSegmentation* mpSegmentation = 0; if ( stationType == AliMp::kStation12 ) { AliMq::Station12Type station12Type = detElement->GetStation12Type(); AliMpSectorReader reader(station12Type, planeType); AliMpSector* sector = reader.BuildSector(dataStreams); mpSegmentation = new AliMpFastSegmentation(new AliMpSectorSegmentation(sector, true)); } else if ( stationType == AliMp::kStation345 ) { AliMpSt345Reader reader(fSlatMotifMap); AliMpSlat* slat = reader.ReadSlat(dataStreams, deTypeName, planeType); mpSegmentation = new AliMpFastSegmentation(new AliMpSlatSegmentation(slat, true)); } else if ( stationType == AliMp::kStationTrigger ) { AliMpTriggerReader reader(fSlatMotifMap); AliMpTrigger* trigger = reader.ReadSlat(dataStreams, deTypeName, planeType); mpSegmentation = new AliMpTriggerSegmentation(trigger, true); } else AliErrorStream() << "Unknown station type" << endl; if ( mpSegmentation ) fMpSegmentations.Add(deSegName, mpSegmentation); // StdoutToAliDebug(3, fSlatMotifMap.Print();); return mpSegmentation; } //_____________________________________________________________________________ AliMpExMap* AliMpSegmentation::FillElCardsMap(Int_t detElemId) { /// Fill the map of electronic cards IDs to segmentations for /// given detElemId AliDebugStream(2) << "detElemId=" << detElemId << endl;; AliMpExMap* mde = new AliMpExMap; mde->SetOwner(kFALSE); fElCardsMap.Add(detElemId,mde); const AliMpVSegmentation* seg[2]; TArrayI ecn[2]; for ( Int_t cathode = AliMp::kCath0; cathode <= AliMp::kCath1; ++cathode ) { seg[cathode] = GetMpSegmentation(detElemId,AliMp::GetCathodType(cathode)); seg[cathode]->GetAllElectronicCardIDs(ecn[cathode]); for ( Int_t i = 0; i < ecn[cathode].GetSize(); ++i ) { mde->Add(ecn[cathode][i],const_cast<AliMpVSegmentation*>(seg[cathode])); } } assert( mde->GetSize() > 0 ); return mde; } // // public methods // //______________________________________________________________________________ const AliMpVSegmentation* AliMpSegmentation::GetMpSegmentation( Int_t detElemId, AliMp::CathodType cath, Bool_t warn) const { /// Return mapping segmentation for given detElemId and cath // Check detElemId & cath if ( ! AliMpDEManager::IsValidDetElemId(detElemId, false) ) { if ( warn ) { AliWarningStream() << "Invalid detElemId " << detElemId << endl; } return 0; } // If segmentation is already built, just return it // AliMpDetElement* detElement = AliMpDEManager::GetDetElement(detElemId); TString deSegName = detElement->GetSegName(cath); TObject* object = fMpSegmentations.Get(deSegName); if ( ! object ) { // Should never happen AliErrorStream() << "Segmentation for detElemId/cathod " << detElemId << ", " << cath << " not defined" << endl; return 0; } return static_cast<AliMpVSegmentation*>(object); } //_____________________________________________________________________________ const AliMpVSegmentation* AliMpSegmentation::GetMpSegmentationByElectronics( Int_t detElemId, Int_t ecId, Bool_t warn) const { /// Return mapping segmentation for given detElemId and electronic card Id /// (motif position Id) AliMpExMap* m = static_cast<AliMpExMap*>(fElCardsMap.GetValue(detElemId)); if (!m) { // Should never happen AliErrorStream() << "Cannot find the el cards map for detElemId " << detElemId << endl; return 0; } TObject* object = m->GetValue(ecId); if ( ! object ) { if ( warn ) { AliErrorStream() << "Segmentation for electronic card " << ecId << " not found" << endl; } return 0; } return static_cast<AliMpVSegmentation*>(object); } //_____________________________________________________________________________ const AliMpSector* AliMpSegmentation::GetSector(const AliMpVSegmentation* kSegmentation, Bool_t warn) const { /// Return sector for given mapping segmentation. /// If segmentation is not of sector type, zero is returned /// and an Error is issued if warn is set true (default). if ( ! kSegmentation ) return 0; if ( kSegmentation->StationType() != AliMp::kStation12 ) { if ( warn ) { AliErrorStream() << "Segmentation is not of sector type" << endl; } return 0; } // If fast segmentation const AliMpFastSegmentation* fseg = dynamic_cast<const AliMpFastSegmentation*>(kSegmentation); if ( fseg ) { return static_cast<const AliMpSectorSegmentation*>(fseg->GetHelper())->GetSector(); } // If fast segmentation V2 /* const AliMpFastSegmentationV2* fsegV2 = dynamic_cast<const AliMpFastSegmentationV2*>(kSegmentation); if ( fsegV2 ) { return static_cast<const AliMpSectorSegmentation*>(fsegV2->GetHelper())->GetSector(); } */ // If sector segmentation const AliMpSectorSegmentation* sseg = dynamic_cast<const AliMpSectorSegmentation*>(kSegmentation); if ( sseg ) { return sseg->GetSector(); } // Should not get to this line AliErrorStream() << "Segemntation type not identified." << endl; return 0; } //_____________________________________________________________________________ const AliMpSector* AliMpSegmentation::GetSector(Int_t detElemId, AliMp::CathodType cath, Bool_t warn) const { /// Return sector for given detElemId and cath. /// If segmentation is not of sector type, zero is returned /// and an Error is issued if warn is set true (default). return GetSector(GetMpSegmentation(detElemId, cath, warn), warn); } //_____________________________________________________________________________ const AliMpSector* AliMpSegmentation::GetSectorByElectronics(Int_t detElemId, Int_t elCardID, Bool_t warn) const { /// Return sector for given detElemId and elCardID. /// If segmentation is not of sector type, zero is returned /// and an Error is issued if warn is set true (default). return GetSector(GetMpSegmentationByElectronics(detElemId, elCardID, warn), warn); } //_____________________________________________________________________________ const AliMpSlat* AliMpSegmentation::GetSlat(const AliMpVSegmentation* kSegmentation, Bool_t warn) const { /// Return slat for given mapping segmentation. /// If segmentation is not of slat type, zero is returned /// and an Error is issued if warn is set true (default). if ( ! kSegmentation ) return 0; if ( kSegmentation->StationType() != AliMp::kStation345 ) { if ( warn ) { AliErrorStream() << "Segmentation is not of slat type" << endl; } return 0; } // If fast segmentation const AliMpFastSegmentation* fseg = dynamic_cast<const AliMpFastSegmentation*>(kSegmentation); if ( fseg ) { return static_cast<const AliMpSlatSegmentation*>(fseg->GetHelper())->Slat(); } // If fast segmentation V2 /* const AliMpFastSegmentationV2* fsegV2 = dynamic_cast<const AliMpFastSegmentationV2*>(kSegmentation); if ( fsegV2 ) { return static_cast<const AliMpSlatSegmentation*>(fsegV2->GetHelper())->Slat(); } */ // If slat segmentation const AliMpSlatSegmentation* sseg = dynamic_cast<const AliMpSlatSegmentation*>(kSegmentation); if ( sseg ) { return sseg->Slat(); } // Should not get to this line AliErrorStream() << "Segemntation type not identified." << endl; return 0; } //_____________________________________________________________________________ const AliMpSlat* AliMpSegmentation::GetSlat(Int_t detElemId, AliMp::CathodType cath, Bool_t warn) const { /// Return slat for given detElemId and cath. /// If segmentation is not of slat type, zero is returned /// and an Error is issued if warn is set true (default). return GetSlat(GetMpSegmentation(detElemId, cath, warn), warn); } //_____________________________________________________________________________ const AliMpSlat* AliMpSegmentation::GetSlatByElectronics(Int_t detElemId, Int_t elCardID, Bool_t warn) const { /// Return slat for given detElemId and elCardID. /// If segmentation is not of slat type, zero is returned /// and an Error is issued if warn is set true (default). return GetSlat(GetMpSegmentationByElectronics(detElemId, elCardID, warn), warn); } //_____________________________________________________________________________ const AliMpTrigger* AliMpSegmentation::GetTrigger(const AliMpVSegmentation* kSegmentation, Bool_t warn) const { /// Return trigger for given mapping segmentation. /// If segmentation is not of trigger type, zero is returned /// and an Error is issued if warn is set true (default). if ( ! kSegmentation ) return 0; if ( kSegmentation->StationType() != AliMp::kStationTrigger ) { if ( warn ) { AliErrorStream() << "Segmentation is not of trigger type" << endl; } return 0; } // If slat segmentation const AliMpTriggerSegmentation* tseg = dynamic_cast<const AliMpTriggerSegmentation*>(kSegmentation); if ( tseg ) { return tseg->Slat(); } // If fast segmentation const AliMpFastSegmentation* fseg = dynamic_cast<const AliMpFastSegmentation*>(kSegmentation); if ( fseg ) { return static_cast<const AliMpTriggerSegmentation*>(fseg->GetHelper())->Slat(); } // If fast segmentation V2 /* const AliMpFastSegmentationV2* fsegV2 = dynamic_cast<const AliMpFastSegmentationV2*>(kSegmentation); if ( fsegV2 ) { return static_cast<const AliMpTriggerSegmentation*>(fsegV2->GetHelper())->Slat(); } */ // Should not get to this line AliErrorStream() << "Segemntation type not identified." << endl; return 0; } //_____________________________________________________________________________ const AliMpTrigger* AliMpSegmentation::GetTrigger(Int_t detElemId, AliMp::CathodType cath, Bool_t warn) const { /// Return trigger for given detElemId and cath. /// If segmentation is not of trigger type, zero is returned /// and an Error is issued if warn is set true (default). return GetTrigger(GetMpSegmentation(detElemId, cath, warn), warn); } //_____________________________________________________________________________ const AliMpTrigger* AliMpSegmentation::GetTriggerByElectronics(Int_t detElemId, Int_t elCardID, Bool_t warn) const { /// Return trigger for given detElemId and elCardID. /// If segmentation is not of trigger type, zero is returned /// and an Error is issued if warn is set true (default). return GetTrigger(GetMpSegmentationByElectronics(detElemId, elCardID, warn), warn); } //_____________________________________________________________________________ void AliMpSegmentation::Print(Option_t* opt) const { /// Print the list of segmentations fMpSegmentations.Print(opt); }
31.487633
108
0.678543
[ "object" ]
2a5e52d83fcad8d418e0f618c29d7fa13f1a7b65
860
hpp
C++
include/sequence_generator/get_perlin_noise_sequence.hpp
WentsingNee/Visual-Sort
df784c1291af124032264e6c16c0da0dcefe0548
[ "MIT" ]
2
2020-05-14T09:29:42.000Z
2020-06-01T14:59:04.000Z
include/sequence_generator/get_perlin_noise_sequence.hpp
WentsingNee/Visual-Sort
df784c1291af124032264e6c16c0da0dcefe0548
[ "MIT" ]
null
null
null
include/sequence_generator/get_perlin_noise_sequence.hpp
WentsingNee/Visual-Sort
df784c1291af124032264e6c16c0da0dcefe0548
[ "MIT" ]
null
null
null
/** * @file get_perlin_noise_sequence.hpp * @brief * @date 2020-07-28 * @author Peter * @copyright * Peter of [ThinkSpirit Laboratory](http://thinkspirit.org/) * of [Nanjing University of Information Science & Technology](http://www.nuist.edu.cn/) * all rights reserved */ #ifndef VISUAL_SORT_GET_PERLIN_NOISE_SEQUENCE_HPP #define VISUAL_SORT_GET_PERLIN_NOISE_SEQUENCE_HPP #include <vector> #include <iostream> #include <kerbal/random/perlin_noise.hpp> template <typename Tp, typename Engine> std::vector<Tp> get_perlin_noise_sequence(int n, Engine & eg) { std::vector<Tp> v; v.reserve(n); kerbal::random::perlin_noise<> noise(eg); for (int i = 0; i < n; ++i) { auto r = 6000 * noise(i * 0.01); // std::cout << r << std::endl; v.push_back(r); } return v; } #endif // VISUAL_SORT_GET_PERLIN_NOISE_SEQUENCE_HPP
23.888889
90
0.690698
[ "vector" ]
2a67a5c5fe38dc17abd1c2585f533e7f88852433
27,801
cpp
C++
CS2810/Assignments/CS19B021_A7.cpp
vikram-kv/CS2810-LabWork
1190c14d08d0aa1e8143df338766a6d075c47182
[ "Apache-2.0" ]
null
null
null
CS2810/Assignments/CS19B021_A7.cpp
vikram-kv/CS2810-LabWork
1190c14d08d0aa1e8143df338766a6d075c47182
[ "Apache-2.0" ]
null
null
null
CS2810/Assignments/CS19B021_A7.cpp
vikram-kv/CS2810-LabWork
1190c14d08d0aa1e8143df338766a6d075c47182
[ "Apache-2.0" ]
null
null
null
/************************ * $ID$ * File: CS19B021_A7.cpp - Use Prim's and Kruskal algorithms to find the minimum spanning tree/forest * of a given simple,undirected and weighted graph. * * Functionality: * *1) Class Template Graph:-(Parameter = edge weight type) * Stores an undirected weighted simple graph using adjacency lists. Supports the following operations: * * AddV() : Add a new vertex at the end(i.e,its index will be the first unused integer in {0,1,2,...}) * AddE(a,b,w) : Add an edge from vertex a to vertex b of weight w. * DelE(a,b): Delete the edge from vertex a to vertex b. * * Both AddE and DelE will generate appropriate error messages for invalid operations. * *2) Class Template MST:-(Parameter = edge weight type = T) * Derived from Graph<T>. Has a member tree for storing MST/MSF in adjacency list form. Supports the following operations: * * Prims(v): Computes a minimum weight spanning tree of the graph using prim's algorithm starting at the vertex v * and stores the. Sum of weights of edges in the MST is printed. If two vertices have same key value, * the one with lower vertex number is considered first. Will write an error message to the stderr if * 'v' is invalid. Will work correctly for connected graphs only(No Min. Spanning forest will be generated * for disconnected graphs). * Kruskal(): Computes a minimum weight spanning forest of the graph using Kruskal's algorithm and stores the tree. * Sum of weights of all the edges in the minimum spanning forest is printed. While considering the edges * in increasing order, if two edges (u1,v1) and (u2,v2) have same weight, then (u1, v1) is considered first * iff u1 < u2 or {u1 = u2 and v1 < v2}. * TreeUptodate(): This procedure checks if the minimum spanning tree/forest is up-to-date i.e. check if no edges/vertices * were added/deleted to the graph after Prims/Kruskal's was run. Prints YES if the tree is up-to-date, * NO otherwise. If Prims/Kruskal has not been executed once then the tree is considered not up-to-date. * If the addition/deletion of edge does not affect the structure of MST, then also the tree is considered * not up-to-date. * DisplayTree(): Outputs the edges of the spanning tree in the ascending order of edge weight. Each edge is printed in the * format u v w such that u < v. If two edges (u1,v1){st u1 < v1} and (u2,v2){st u2 < v2} have same edge * weights, then (u1,v1) is printed first iff u1<u2 or {u1 = u2 and v1 < v2}. * * Author: K V VIKRAM * * Created: [2021-04-05 14:22] by vikram * * Last Modified: [2021-04-06 20:37] by vikram * * Input Format: * Line 1: integer N denoting number of vertices initially in the graph. * Line 2: integer Q, representing the number of queries. * The next Q lines will have one query each which will be one of: * ADDV * ADDE a b w * DELE a b * Prims v * Kruskal * TreeUptodate * DisplayTree * * Constraints: * 1 <= No of vertices <= 500 * a,b,v belong to {0,1,2,...} * 1 <= Q <= 1000 * 1 <= w <= 5000 * * Output Format: * Prims v: Prints the weight of MST. * Kruskal: Prints the weight of MST. * TreeUptodate: Prints YES if the tree is up-to-date, NO otherwise. * DisplayTree: Prints the edges of the spanning tree/forest in ascending order with ties broken as in functionality. * Each edge (u, v) having weight w is printed in a new line in a format u v w * * Assumption: Sufficient dynamic memory is assumed to be available. This exception is neither caught nor handled. * * Practice: Array iterators in loops are typically named i or j. STL container iterators are named itr. * * Compilation: g++ CS19B021_A7.cpp -o solution, ./solution. * * Bugs: No major bugfixes or new releases *************/ #include <vector> #include <iostream> #include <climits> #include <queue> #include <list> #include <utility> using namespace std; // Structure Template Edge(parameter = edge weight type) - Represents an edge. // u,v are end-vertices(type = int) of the edge and w is weight of the edge(type = T). // Has a default constructor and parametrised constructor // We note the valid initialisations will have u,v such that u < v template <class T> struct Edge { T w; //weight int u,v; //end vertices Edge() //default constructor - sets u,v,w to illegal values { w = T{-1}; u = v = -1; } Edge(int a,int b, T weight) //parametrised Constructor - sets u,v and w to a,b and weight respectively { u = a; v = b; w = weight; } }; // Operator template(parameter = edge weight type = T) to define > operator for the type Edge<T> // We say for two edges a = (u1,v1) of weight w1 and b = (u2,v2) of weight w2, a > b iff // w1 > w2 or {w1 = w2 and u1 > u2} or {w1 = w2 and u1 = u2 and v1 > v2}. Here, we note that a and // b are "valid" in the sense that u1 < v1 and u2 < v2. template <class T> bool operator>(const Edge<T>& a,const Edge<T>& b) { if(a.w > b.w) return true; else if(a.w == b.w) { if(a.u != b.u) return a.u > b.u; else return a.v > b.v; } else return false; } // Functor template to use STL priority queue as a min heap. Overloads the function call operator to make it // return true iff param1 > param2 where param1 and param2 are of type T template <class T> struct GreaterThan { bool operator()(const T& a,const T& b) { return (a > b); } }; /* Begin {Definition of class DisjointSets} */ /* DisjointSets : Used to define a UNION-FIND data structure for Kruskal's algorithm. Data Members - parent(int*) and count(int) Mutators - Find(int) and Union(int,int) Constructor - parametrised: DisjointSets(int) Destructor - ~DisjointSets() Note: Number of elements = count. Initially, all sets are singletons. Elements are numbered from 0 to count - 1. For any element 'i', parent[i] will have the id of i's parent in the tree used to represent i's set. The root 'r' of the tree representing a set, will have parent[r] = r. The find algorithm implements path compression for lower avg access time. */ class DisjointSets { int* parent; //ptr to array of integers to store parent of each element int count; //number of elements public: DisjointSets(int); //constructor. Makes all elements singleton sets int Find(int); //returns the root of arg's tree after path compression void Union(int,int); //merges the sets of arg1 and arg2 if they are different ~DisjointSets(); //destructor. deallocates space used by parent array }; /* End {Definition of class DisjointSets} */ /* Begin {Implementation of class DisjointSets} */ /* DisjointSets(int) - Sets count(number of elements) to size, allocates necessary space for parent array and makes each element a singleton set by setting parent[i] = i. Args - int size */ DisjointSets::DisjointSets(int size) { count = size; parent = new int[size]; for(int i = 0; i < size; ++i) { parent[i] = i; } } /* Find(int) - Finds the representative(root) of num's set and returns it. Performs path compression to improve runtime of subsequent finds on num. Path compression is done by updating parent[num] to root of num's set. Args - int num = element id. Ret - int {root of num's set} Assumption - 0 <= num <= count - 1 (element id is valid). */ int DisjointSets::Find(int num) { if(parent[num] == num) return num; else { parent[num] = Find(parent[num]); return parent[num]; } } /* Union(int,int) - Merges the sets of num1 and num2 to a single set if num1 and num2 belong to different sets by setting parent of {root of num2's set} to {root of num1'2 set} Args - int num1,int num2 = element id's Ret - void Assumptions - 0 <= num1,num2 <= count - 1 (element ids are valid). */ void DisjointSets::Union(int num1,int num2) { int root1 = Find(num1); int root2 = Find(num2); if(root1 != root2) { parent[root2] = root1; } } /* ~DisjointSets() - deallocates space used by parent array */ DisjointSets::~DisjointSets() { delete[] parent; } /* End {Implementation of class DisjointSets} */ /* Begin {Definition of class template Graph} */ /* class template Graph(parameter = edge weight type = T) - To store a simple, undirected and weighted graph Data Members - adjLists(vector<list<pair<T,int>>>) and vertexCount(int) Mutator - AddV(), AddE(int,int,T), DelE(int,int) Constructor - Parametrised: Graph(int) Assumptions - T is well-ordered where <,>,= is well-defined. T has a default constructor and a parametrised constructor of the form T(int). Note: List is used to store adjacency list because of fast insertions/deletions. */ template <class T> class Graph { protected: vector<list<pair<T,int>>> adjLists; //vector of adjacency lists.list node = pair of (adj vertex id and edgeWeight) int vertexCount; //number of vertices in graph. vertices have ids 0,1...,(vertexCount-1) public: Graph(int); //initializes an empty graph with 'arg' vertices void AddV(); //adds a new vertex to the graph bool AddE(int,int,T); //adds an edge to the graph bool DelE(int,int); //deletes an edge from the graph }; /* End {Definition of class template Graph} */ /* Begin {Implementation of class template Graph} */ /* Graph(int) - for initialization of an empty graph with no of vertices as 'arg' Args - int noOfVertices */ template <class T> Graph<T>::Graph(int noOfVertices) { adjLists.clear(); adjLists.resize(noOfVertices); vertexCount = noOfVertices; } /* AddV() - for addition of new vertex with vertex id = first unused id in {0,1,...} Args - void Ret - void */ template <class T> void Graph<T>::AddV() { ++vertexCount; adjLists.resize(vertexCount); (adjLists.back()).clear(); } /* AddE() - for addition of a new edge of weight w between vertices a and b in the graph. If a or b is not a valid index then an error message is put in stderr and the function returns false.Otherwise, the new edge is placed at the end of both a and b's adj lists and the function returns true. Args - int a,int b and edgeType w Ret - bool */ template <class T> bool Graph<T>::AddE(int a, int b, T w) { if(a>=vertexCount || b>=vertexCount) //if a or b is invalid { cerr << "Invalid Input. Operation not done" << endl; //error msg is pushed to stderr return false; } else { adjLists[a].emplace_back(w,b); //stmts to add {w,b} in a's list and vice versa adjLists[b].emplace_back(w,a); return true; } } /* DelE() - deletes the edge between vertices a and b.if 1) a or b is invalid or 2) edge ab does not exist in graph, the corresponding error message is put in stderr and the function returns false. Otherwise, the edge ab is deleted and the function returns true. Args - int a,int b Ret - bool */ template <class T> bool Graph<T>::DelE(int a, int b) { string invInput = "Invalid Input. Operation not done"; //error condition 1's msg string absEdge = "Edge is not present. Operation not done"; //error condition 2's msg try { if(a>=vertexCount || b>=vertexCount) //if a or b is invalid, we have error condition 1 throw invInput; else { bool flag = false; //indicates whether ab exists or not for(auto itr = adjLists[a].begin();itr!=adjLists[a].end();++itr) //loop to traverse a's adj list { if(itr->second == b) //if entry of edge ab is found { flag = true; //we set flag to true and delete entry of ab adjLists[a].erase(itr); //and break from loop break; } } if(flag == false) //if ab doesnt exist, we have error condition 2 throw absEdge; //Stmts to delete ab from b's adj list for(auto itr = adjLists[b].begin();itr!=adjLists[b].end();++itr) { if(itr->second == a) { flag = true; adjLists[b].erase(itr); break; } } return true; //ret true as ab existed and was deleted } } catch(string errMsg) //catch mechanism to send crct err msg to stderr { cerr << errMsg << endl; return false; //ret false as operation was invalid } } /* End {Implementation of class template Graph} */ /* Begin {Definition of class template MST} */ /* class template MST(parameter = edge weight type = T) - To store the MST/MSF of a graph in adj list representation Inheritance - Inherited protectedly from the class Graph<T> Inherited data members - protected - adjLists, vertexCount Inherited member functions - protected - Graph<T>::{AddV(), AddE(int,int,T) and DelE(int,int)} Non-inherited members:- Data Members - tree(vector<list<pair<T,int>>>) and updateStatus(bool) Private Mutator - AddTreeEdge(int,int,T) Mutator - AddV(), AddE(int,int,T), DelE(int,int), Prims(int) and Kruskal() Accessor - TreeUptoDate(), DisplayTree() Constructor - Parametrised: MST(int) Assumptions - T is well-ordered where <,>,= is well-defined. T has a default constructor and a parametrised constructor of the form T(int).cout has been overloaded to work on edgeType type. Note: List is used to store adjacency list because of fast insertions/deletions. */ template <class T> class MST : protected Graph<T> { vector<list<pair<T,int>>> tree; //vector of adjacency lists of MST/MSF.list node = pair of (adj vertex id and edgeWeight) bool updateStatus; //updateStatus = true iff MST/MSF is up-to-date void AddTreeEdge(int,int,T); //adds an edge of weight arg3 between vertices arg1 and arg2 to the MST/MSF public: MST(int x):Graph<T>{x} //constructor to call Graph<T>{int} with argument x and set updateStatus to false {updateStatus = false;} void AddV(); //performs Graph<T>::AddV() and sets updateStatus to false void AddE(int,int,T); //performs Graph<T>::AddE(int,int,w) and changes updateStatus appropriately void DelE(int,int); //performs Graph<T>::DelE(int,int) and changes updateStatus appropriately void Prims(int v); //performs Prims(v) operation as in header void Kruskal(); //performs Kruskal() operation as in header void TreeUptodate(); //performs TreeUptodate() operation as in header void DisplayTree(); //performs DisplayTree() operation as in header }; /* End {Definition of class template MST} */ /* Begin {Implementation of class template MST} */ /* AddTreeEdge() - for addition of edge of weight w between vertices a and b in MST/MSF Args - int a,int b, T w Ret - void */ template <class T> void MST<T>::AddTreeEdge(int a,int b,T w) { tree[a].emplace_back(w,b); //stmts to add {w,b} at end of a's adj list in tree and vice versa tree[b].emplace_back(w,a); } /* AddV() - calls Graph<T>::AddV() and sets updateStatus to false Args - void Ret - void */ template <class T> void MST<T>::AddV() { Graph<T>::AddV(); updateStatus = false; //MST is not up-to-date after addition of a new vertex } /* AddE() - calls Graph<T>::AddE(a,b,w) and sets updateStatus to false if the call returns true Args - int a,int b, T w Ret - void */ template <class T> void MST<T>::AddE(int a,int b,T w) { if(Graph<T>::AddE(a,b,w)==true) //if addition of edge ab of weight w to the graph is successful, updateStatus = false; //the MST/MSF is not up-to-date } /* DelE() - calls Graph<T>::DelE(a,b) and sets updateStatus to false if the call returns true Args - int a,int b Ret - void */ template <class T> void MST<T>::DelE(int a,int b) { if(Graph<T>::DelE(a,b)==true) //if deletion of edge ab from the graph is successful, updateStatus = false; //the MST/MSF is not up-to-date } /* Prims() - Performs Prims(v) operation as in header and sets updateStatus to true Args - int v Ret - void Algorithm - Prim's Greedy Minimum Spanning Tree algorithm using minheap data structure. Note - MST is generated for connected graphs. MSF is not generated for disconnected graphs. So, it does not "work" for disconnected graphs */ template <class T> void MST<T>::Prims(int v) { //stmts to check v's validity and terminate after displaying error msg if v is invalid if(v >= this->vertexCount) { cerr << "Invalid Vertex Number... Query Not Executed." << endl; return ; } tree.clear(); //MST is cleared tree.resize(this->vertexCount); //MST is resized to store vertexCount many adj lists //bool array 'processed' of size vertexCount with all entries initialized to false //processed[i] will be set to true after vertex i is added to partially constructed MST vector<bool> processed(this->vertexCount,false); //array to store the value of edge of least weight connecting a vertex to the //partially constructed MST. Initially, all entries are set to T{INT_MAX}(No connection) vector<T> minConnectEdge(this->vertexCount,T{INT_MAX}); //minConnectVertex[i] = vertex u if the edge ui is the edge corresponding to the weight minConnectEdge(i) for i != v //Initially, all entries are set to -1(illegal vertex id) vector<int> minConnectVertex(this->vertexCount,-1); processed[v] = true; //v is added to the MST first typedef pair<T,int> qPair; //qPair = type of elements to be inserted in minheap pq defined below //pq is a minheap of qPairs which will be used for picking the edge to be added to partial MST priority_queue<qPair,vector<qPair>,greater<qPair>> pq; qPair curPair; //current qPair under consideration in while loop int curVertex; //= curPair.second T MSTWeight = T{0}; //weight of all edges in MST. Initialized to T{0} for(const auto& itr : this->adjLists[v]) //Loop to traverse v's adjList { //For a neighbour u of v, minConnectEdge[u] = weight of edge uv and minConnectVertex[u] = v //After this, the qPair (weight of uv,u) is pushed into the minheap pq minConnectEdge[itr.second] = itr.first; minConnectVertex[itr.second] = v; pq.emplace(itr.first,itr.second); } while(!pq.empty()) //till pq becomes empty { curPair = pq.top(); //curPair corr. to the "least" qPair pq.pop(); //pq's root(=curPair) is deleted curVertex = curPair.second; //curVertex is set if(!processed[curVertex]) //if curVertex has not been already added to partial MST { //curVertex is added to the partial MST using the edge "(minConnectVertex[curVertex],curVertex)" of weight //"curPair.first" and MSTWeight is updated processed[curVertex] = true; AddTreeEdge(minConnectVertex[curVertex],curVertex,curPair.first); MSTWeight += curPair.first; //Stmts to traverse curVertex's adjList and check whether a connection from curVertex to one of its //neighbours(say u) is cheaper than minConnectEdge[u]. If this is the case, we update the entries corr. //to u in minConnectEdge[] and minConnectVertex, and then we push the qPair "(weight of edge joining //curVertex and u,u)" into pq for(const auto& itr : this->adjLists[curVertex]) { if(itr.first < minConnectEdge[itr.second]) { pq.emplace(itr.first,itr.second); minConnectEdge[itr.second] = itr.first; minConnectVertex[itr.second] = curVertex; } } } } cout << MSTWeight << endl; //weight of MST is printed updateStatus = true; //tree is now up-to-date } /* Kruskal() - Performs Kruskal operation as in header and sets updateStatus to true Args - void Ret - void Algorithm - Kruskal's Greedy Minimum Spanning Forest algorithm using Union-Find and minheap data structure. */ template <class T> void MST<T>::Kruskal() { tree.clear(); //MSF is cleared tree.resize(this->vertexCount); //MSF is resized to store vertexCount many adj lists //edgeQueue is a min heap of Edge<T> objects priority_queue<Edge<T>,vector<Edge<T>>,GreaterThan<Edge<T>>> edgeQueue; Edge<T> curEdge; //current edge under process in loop int v1,v2; //end-vertices of current edge T MSTWeight = T{0}; //Weight of all edges in MSF. Initialized to T{0} //vertexGroups is a collection of disjoint sets of vertices of the graph //Initially, all sets are singletons(per constructor defn) DisjointSets vertexGroups{this->vertexCount}; //Loop to push all edges in the graph to edgeQueue for(int i = 0; i < this->vertexCount; ++i) //Loop to traverse all vertices in graph { for(const auto& itr : this->adjLists[i]) //Loop to traverse the adj list of vertex i in graph { if(i < itr.second) //Check to ensure each edge is inserted one time only edgeQueue.emplace(i,itr.second,itr.first); } } //Loop to pop the "least" edge from edgeQueue, add it to the MSF if its end-vertices are in two different //disjoint sets in vertexGroups till edgeQueue becomes empty. //We note that if the picked edge connects two different component-trees of partially constructed MSF, //then it wont form a cycle and will instead connect two small component-trees to form a larger component-tree while(!edgeQueue.empty()) { curEdge = edgeQueue.top(); //curEdge is set edgeQueue.pop(); v1 = curEdge.u; //v1 and v2 are set v2 = curEdge.v; if(vertexGroups.Find(v1)!=vertexGroups.Find(v2)) //if v1 and v2 belong to different component-trees { //stmts to merge the sets corr. to v1 and v2, add curEdge to MSF and update MSTWeight vertexGroups.Union(v1,v2); AddTreeEdge(v1,v2,curEdge.w); MSTWeight += curEdge.w; } } cout << MSTWeight << endl; //weight of MSF is printed updateStatus = true; //tree is now up-to-date } /* TreeUptodate() - Prints YES if MST/MSF is up-to-date. Otherwise, prints NO. Args - void Ret - void */ template <class T> void MST<T>::TreeUptodate() { string dispMsg = updateStatus ? "YES":"NO"; cout << dispMsg << endl; } /* DisplayTree() - Performs DisplayTree() operation as in header Args - void Ret - void */ template <class T> void MST<T>::DisplayTree() { //edgeSet is a minheap of edges. priority_queue<Edge<T>,vector<Edge<T>>,GreaterThan<Edge<T>>> edgeSet; for(int i = 0; i < Graph<T>::vertexCount; ++i) //Loop to traverse all vertices in MST/MSF { for(const auto& itr : tree[i]) //Loop to traverse the adj list of vertex i in MST/MSF { if(i < itr.second) //Check to ensure each edge is considered one time only { edgeSet.emplace(i,itr.second,itr.first); //As i < itr.second, the valid edge (i,itr.second) of } //weight itr.first is pushed into edgeSet } } Edge<T> curEdge; //var to store the current edge under process in while loop //Loop to remove the "least" edge from edgeSet and display the edge in the format u v w in a newline //till edgeSet becomes empty while(!edgeSet.empty()) { curEdge = edgeSet.top(); edgeSet.pop(); cout << curEdge.u << " " << curEdge.v << " " << curEdge.w << endl; } } /* End {Implementation of class template MST} */ int main() { int initialVertexNumber; //initial number of vertices in graph size_t queryCount; //number of queries string query; //var to store a query int u,v,w; //vars to store arguments of a query. u,v for vertices and w for edge weight cin >> initialVertexNumber; MST<int> G{initialVertexNumber}; //MST G of class MST<int> is initialized with underlying graph having "initialVertexNumber" many vertices cin >> queryCount; for(size_t i = 0;i<queryCount;++i) //Loop to perform all the input queries { cin >> query; if(query == "ADDE") //AddE(a,b,w) operation { cin >> u >> v >> w; G.AddE(u,v,w); } else if(query == "DELE") //DelE(a,b) operation { cin >> u >> v; G.DelE(u,v); } else if(query == "ADDV") //AddV() operation G.AddV(); else if(query == "Prims") //Prims(v) operation { cin >> u; G.Prims(u); } else if(query == "TreeUptodate") //TreeUptodate() operation G.TreeUptodate(); else if(query == "DisplayTree") //DisplayTree() operation G.DisplayTree(); else //Kruskal() operation G.Kruskal(); } return 0; }
44.624398
149
0.585375
[ "vector" ]
2a683436727216964d33a212122063416055bab6
3,200
cpp
C++
src/pke/demo/demo-sizeOf-plaintext.cpp
AnthonyTudorov/PALISADE-SizeOf-Fork
05e9903da0971933adb1ba0b9c98398c9722a45c
[ "BSD-2-Clause" ]
null
null
null
src/pke/demo/demo-sizeOf-plaintext.cpp
AnthonyTudorov/PALISADE-SizeOf-Fork
05e9903da0971933adb1ba0b9c98398c9722a45c
[ "BSD-2-Clause" ]
null
null
null
src/pke/demo/demo-sizeOf-plaintext.cpp
AnthonyTudorov/PALISADE-SizeOf-Fork
05e9903da0971933adb1ba0b9c98398c9722a45c
[ "BSD-2-Clause" ]
1
2021-05-24T13:38:28.000Z
2021-05-24T13:38:28.000Z
#include "palisade.h" #include <typeinfo> using namespace std; using namespace lbcrypto; int main() { int plaintextModulus = 256; double sigma = 4; double rootHermiteFactor = 1.006; //Set Crypto Parameters CryptoContext<DCRTPoly> cryptoContext1 = CryptoContextFactory<DCRTPoly>::genCryptoContextBFVrns( plaintextModulus, rootHermiteFactor, sigma, 0, 5, 0, OPTIMIZED, 6); uint32_t multDepth = 1; uint32_t scaleFactorBits = 50; uint32_t batchSize1 = 8; SecurityLevel securityLevel = HEStd_128_classic; CryptoContext<DCRTPoly> cryptoContext2 = CryptoContextFactory<DCRTPoly>::genCryptoContextCKKS( multDepth, scaleFactorBits, batchSize1, securityLevel); // usint m = 22; PlaintextModulus p = 2333; BigInteger modulusP(p); BigInteger modulusQ("955263939794561"); BigInteger squareRootOfRoot("941018665059848"); BigInteger bigmodulus("80899135611688102162227204937217"); BigInteger bigroot("77936753846653065954043047918387"); auto cycloPoly = GetCyclotomicPolynomial<BigVector>(m, modulusQ); ChineseRemainderTransformArb<BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ); float stdDev = 4; usint batchSize2 = 8; shared_ptr<ILParams> params(new ILParams(m, modulusQ, squareRootOfRoot, bigmodulus, bigroot)); EncodingParams encodingParams(new EncodingParamsImpl(p, batchSize2, PackedEncoding::GetAutomorphismGenerator(m))); PackedEncoding::SetParams(m, encodingParams); CryptoContext<Poly> cryptoContext3 = CryptoContextFactory<Poly>::genCryptoContextBGV(params, encodingParams, 8, stdDev); //////////////////////////////////////////////////////////// // Encode source data //////////////////////////////////////////////////////////// std::vector<complex<double>> vectorOfComplex = {5.0, 4.0, 3.0, 2.0, 1.0, .75, .5, .25}; Plaintext plaintext1 = cryptoContext2->MakeCKKSPackedPlaintext(vectorOfComplex); std::vector<int64_t> vectorOfInts1 = {5,4,3,2,1,0,5,4,3,2,1,0}; Plaintext plaintext2 = cryptoContext1->MakeCoefPackedPlaintext(vectorOfInts1); int64_t num = 7; int64_t den = 3; Plaintext plaintext3 = cryptoContext1->MakeFractionalPlaintext(num, den); int64_t x = 27; Plaintext plaintext4 = cryptoContext1->MakeIntegerPlaintext(x); std::vector<int64_t> vectorOfInts2 = {37, 22, 18, 4, 3, 2, 1, 9}; Plaintext plaintext5 = cryptoContext3->MakePackedPlaintext(vectorOfInts2); int64_t y = 35; Plaintext plaintext6 = cryptoContext1->MakeScalarPlaintext(y); string str = "Hello World"; Plaintext plaintext7 = cryptoContext1->MakeStringPlaintext(str); cout << "Size of plaintext1 (CKKSPackedPlaintext): " << plaintext1->SizeOf() << endl; cout << "Size of plaintext2 (CoefPackedPlaintext): " << plaintext2->SizeOf() << endl; cout << "Size of plaintext3 (FractionalPlaintext): " << plaintext3->SizeOf() << endl; cout << "Size of plaintext4 (IntegerPlaintext): " << plaintext4->SizeOf() << endl; cout << "Size of plaintext5 (PackedPlaintext): " << plaintext5->SizeOf() << endl; cout << "Size of plaintext6 (ScalarPlaintext): " << plaintext6->SizeOf() << endl; cout << "Size of plaintext7 (StringPlaintext): " << plaintext7->SizeOf() << endl; }
38.554217
121
0.706563
[ "vector" ]
2a7248e0f0279d596b2ff5a2d9dfd4b2498c134d
5,003
cpp
C++
src/Menge/MengeCore/BFSM/VelocityModifiers/VelModifierScale.cpp
flwmxd/Menge
7b7b4c171ab6e6d4a89cfb0d86269ce4541e1e7f
[ "Apache-2.0" ]
1
2021-08-20T10:57:16.000Z
2021-08-20T10:57:16.000Z
src/Menge/MengeCore/BFSM/VelocityModifiers/VelModifierScale.cpp
flwmxd/Menge
7b7b4c171ab6e6d4a89cfb0d86269ce4541e1e7f
[ "Apache-2.0" ]
null
null
null
src/Menge/MengeCore/BFSM/VelocityModifiers/VelModifierScale.cpp
flwmxd/Menge
7b7b4c171ab6e6d4a89cfb0d86269ce4541e1e7f
[ "Apache-2.0" ]
null
null
null
/* License Menge Copyright ?and trademark ?2012-14 University of North Carolina at Chapel Hill. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and non-profit purposes, without fee, and without a written agreement is hereby granted, provided that the above copyright notice, this paragraph, and the following four paragraphs appear in all copies. This software program and documentation are copyrighted by the University of North Carolina at Chapel Hill. The software program and documentation are supplied "as is," without any accompanying services from the University of North Carolina at Chapel Hill or the authors. The University of North Carolina at Chapel Hill and the authors do not warrant that the operation of the program will be uninterrupted or error-free. The end-user understands that the program was developed for research purposes and is advised not to rely exclusively on the program for any reason. IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. Any questions or comments should be sent to the authors {menge,geom}@cs.unc.edu */ #include "MengeCore/BFSM/VelocityModifiers/VelModifierScale.h" #include "MengeCore/Agents/BaseAgent.h" #include <iomanip> #include <sstream> namespace Menge { namespace BFSM { ///////////////////////////////////////////////////////////////////// // Implementation of ScaleVelModifier ///////////////////////////////////////////////////////////////////// ScaleVelModifier::ScaleVelModifier() : VelModifier(), _scale(1.f) {} ///////////////////////////////////////////////////////////////////// ScaleVelModifier::ScaleVelModifier(const float scale) : VelModifier(), _scale(scale) {} ///////////////////////////////////////////////////////////////////// void ScaleVelModifier::setScale(const float scale) { _scale = scale; } ///////////////////////////////////////////////////////////////////// void ScaleVelModifier::adaptPrefVelocity(const Agents::BaseAgent* agent, Agents::PrefVelocity& pVel) { pVel.setSpeed(pVel.getSpeed() * _scale); } ///////////////////////////////////////////////////////////////////// VelModifier* ScaleVelModifier::copy() const { return new ScaleVelModifier(_scale); }; ///////////////////////////////////////////////////////////////////// #if 0 VelModContext * ScaleVelModifier::getContext() { return new ScaleVMContext(this); } ///////////////////////////////////////////////////////////////////// // Implementation of ScaleVMContext ///////////////////////////////////////////////////////////////////// ScaleVMContext::ScaleVMContext(ScaleVelModifier *vm):VelModContext(), _vm(vm) { }; ///////////////////////////////////////////////////////////////////// std::string ScaleVMContext::getUIText( const std::string & indent ) const { std::stringstream ss; ss << indent << "Scale Applied: " << _vm->getScale(); return ss.str(); } ///////////////////////////////////////////////////////////////////// void ScaleVMContext::draw3DGL( const Agents::BaseAgent * agt) { // draw preferred velocity } #endif ///////////////////////////////////////////////////////////////////// // Implementation of ScaleVMFactory ///////////////////////////////////////////////////////////////////// ScaleVMFactory::ScaleVMFactory() : VelModFactory() { // TODO: This should support a numerical distribution _scaleID = _attrSet.addFloatAttribute("scale", true /*required*/); } ///////////////////////////////////////////////////////////////////// bool ScaleVMFactory::setFromXML(VelModifier* vm, TiXmlElement* node, const std::string& behaveFldr) const { ScaleVelModifier* cvm = dynamic_cast<ScaleVelModifier*>(vm); assert(cvm != 0x0 && "Trying to set attributes of a Scale Velocity Modifier on an " "incompatible object"); if (!VelModFactory::setFromXML(vm, node, behaveFldr)) return false; cvm->setScale(_attrSet.getFloat(_scaleID)); return true; } } // namespace BFSM } // namespace Menge
39.085938
87
0.594643
[ "object" ]
2a7f031a12035d34c102e87d54e937aef5049402
10,156
cpp
C++
sp/src/game/client/hoe/c_npc_chumtoad.cpp
timbaker/heart-of-evil
4e4729b7ae2dd314fb3695fe8d52545c601d2106
[ "Unlicense" ]
2
2016-01-11T19:20:59.000Z
2022-03-06T14:19:37.000Z
sp/src/game/client/hoe/c_npc_chumtoad.cpp
timbaker/heart-of-evil
4e4729b7ae2dd314fb3695fe8d52545c601d2106
[ "Unlicense" ]
null
null
null
sp/src/game/client/hoe/c_npc_chumtoad.cpp
timbaker/heart-of-evil
4e4729b7ae2dd314fb3695fe8d52545c601d2106
[ "Unlicense" ]
null
null
null
#include "cbase.h" #ifdef CHUMTOAD_FLASHLIGHT_EFFECT #include "flashlighteffect.h" #else #include "dlight.h" #include "iefx.h" #endif #include "c_AI_BaseNPC.h" #include "beam_shared.h" #include "beamdraw.h" #include "iviewrender_beams.h" #include "dlight.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define HEADLIGHT_DISTANCE 768.0f #define HEADLIGHT_WIDTH 32 class C_NPC_Chumtoad : public C_AI_BaseNPC { public: DECLARE_CLASS( C_NPC_Chumtoad, C_AI_BaseNPC ); DECLARE_CLIENTCLASS(); DECLARE_DATADESC(); C_NPC_Chumtoad(); ~C_NPC_Chumtoad(); void UpdateHeadlight( void ); virtual void Simulate( void ); virtual int DrawModel( int flags ); void DrawWake( void ); int m_nExactWaterLevel; Vector m_vecPhysVelocity; float m_flEngineSpeed; bool m_bHeadlightIsOn; #ifdef CHUMTOAD_FLASHLIGHT_EFFECT CHeadlightEffect *m_pHeadlight; // expensive shadow-casting light #else dlight_t *m_pDynamicLight; #endif dlight_t *m_pSelfLight; Vector m_vecHeadlightBeamStart; Vector m_vecHeadlightBeamEnd; Beam_t *m_pHeadlightBeam; }; //----------------------------------------------------------------------------- // Save/restore //----------------------------------------------------------------------------- BEGIN_DATADESC( C_NPC_Chumtoad ) END_DATADESC() //----------------------------------------------------------------------------- // Networking //----------------------------------------------------------------------------- IMPLEMENT_CLIENTCLASS_DT(C_NPC_Chumtoad, DT_NPC_Chumtoad, CNPC_Chumtoad) RecvPropBool( RECVINFO( m_bHeadlightIsOn ) ), RecvPropInt( RECVINFO( m_nExactWaterLevel ) ), RecvPropInt( RECVINFO( m_nWaterLevel ) ), RecvPropVector( RECVINFO( m_vecPhysVelocity ) ), END_RECV_TABLE() //----------------------------------------------------------------------------- C_NPC_Chumtoad::C_NPC_Chumtoad() { #ifdef CHUMTOAD_FLASHLIGHT_EFFECT m_pHeadlight = NULL; #endif m_flEngineSpeed = 100.0f; } //----------------------------------------------------------------------------- C_NPC_Chumtoad::~C_NPC_Chumtoad() { #ifdef CHUMTOAD_FLASHLIGHT_EFFECT if (m_pHeadlight) { delete m_pHeadlight; } #else if ( m_pHeadlightBeam ) { m_pHeadlightBeam->die = gpGlobals->curtime; // or beams->FreeBeam? m_pHeadlightBeam->flags &= ~FBEAM_FOREVER; } #endif } //----------------------------------------------------------------------------- void C_NPC_Chumtoad::Simulate( void ) { UpdateHeadlight(); BaseClass::Simulate(); } //----------------------------------------------------------------------------- // Purpose: Creates, destroys, and updates the headlight effect as needed. //----------------------------------------------------------------------------- void C_NPC_Chumtoad::UpdateHeadlight( void ) { if (m_bHeadlightIsOn) { #ifdef CHUMTOAD_FLASHLIGHT_EFFECT if (!m_pHeadlight) { // Turned on the headlight; create it. m_pHeadlight = new CHeadlightEffect(); if (!m_pHeadlight) return; m_pHeadlight->TurnOn(); } #else if ( !m_pDynamicLight || (m_pDynamicLight->key != entindex()) ) { m_pDynamicLight = effects->CL_AllocDlight( entindex() ); if ( !m_pDynamicLight ) return; } #endif if ( !m_pSelfLight || (m_pSelfLight->key != -entindex()) ) { m_pSelfLight = effects->CL_AllocDlight( -entindex() ); if ( !m_pSelfLight ) return; } int nHeadlightIndex = LookupAttachment( "headlight" ); Vector vecLightPos; QAngle angLightDir; GetAttachment(nHeadlightIndex, vecLightPos, angLightDir); #ifdef CHUMTOAD_FLASHLIGHT_EFFECT Vector vecLightDir, vecLightRight, vecLightUp; AngleVectors( angLightDir, &vecLightDir, &vecLightRight, &vecLightUp ); // Update the light with the new position and direction. m_pHeadlight->UpdateLight( vecLightPos, vecLightDir, vecLightRight, vecLightUp, HEADLIGHT_DISTANCE ); m_vecHeadlightBeamStart = vecLightPos; m_vecHeadlightBeamEnd = vecLightPos + vecLightDir * 500; #else Vector vecLightDir; AngleVectors( GetAbsAngles()/*angLightDir*/, &vecLightDir ); trace_t tr; UTIL_TraceLine( vecLightPos, vecLightPos + vecLightDir * 2024, MASK_OPAQUE, this, COLLISION_GROUP_NONE, &tr ); ColorRGBExp32 color; color.r = 255; color.g = 192; color.b = 64; color.exponent = 8; float frac = (tr.endpos - vecLightPos).Length() / 500; m_pDynamicLight->radius = 48 * clamp(frac,0.5,1.5); m_pDynamicLight->origin = tr.endpos - vecLightDir * 10; m_pDynamicLight->die = gpGlobals->curtime + 0.05f; m_pDynamicLight->color = color; m_vecHeadlightBeamStart = vecLightPos; m_vecHeadlightBeamEnd = vecLightPos + vecLightDir * 500; #endif m_pSelfLight->radius = 32; m_pSelfLight->origin = vecLightPos + vecLightDir * 10; m_pSelfLight->die = gpGlobals->curtime + 0.05f; m_pSelfLight->color = color; if ( m_pHeadlightBeam == NULL ) { BeamInfo_t beamInfo; beamInfo.m_vecStart = m_vecHeadlightBeamStart; beamInfo.m_vecEnd = m_vecHeadlightBeamEnd; beamInfo.m_pStartEnt = NULL; beamInfo.m_pEndEnt = NULL; beamInfo.m_nStartAttachment = 0; beamInfo.m_nEndAttachment = 0; beamInfo.m_pszModelName = "sprites/glow_test02.vmt"; beamInfo.m_pszHaloName = "sprites/light_glow03.vmt"; beamInfo.m_flHaloScale = 16.0f; beamInfo.m_flLife = 0.0f; beamInfo.m_flWidth = 14; beamInfo.m_flEndWidth = 14; beamInfo.m_flFadeLength = 0.0f; beamInfo.m_flAmplitude = 0; beamInfo.m_flBrightness = 48.0; beamInfo.m_flSpeed = 0.0; beamInfo.m_nStartFrame = 0.0; beamInfo.m_flFrameRate = 1.0f; beamInfo.m_flRed = 255.0f; beamInfo.m_flGreen = 255.0f; beamInfo.m_flBlue = 255.0f; beamInfo.m_nSegments = -1; beamInfo.m_bRenderable = true; beamInfo.m_nFlags = FBEAM_SHADEOUT|FBEAM_NOTILE|FBEAM_HALOBEAM; m_pHeadlightBeam = beams->CreateBeamEntPoint( beamInfo ); } #ifdef CHUMTOAD_FLASHLIGHT_EFFECT #else if ( m_pHeadlightBeam != NULL ) { float flDist = (tr.endpos - vecLightPos).Length(); flDist = clamp( flDist, 0, 500 ); m_pHeadlightBeam->fadeLength = flDist; } #endif } #ifdef CHUMTOAD_FLASHLIGHT_EFFECT else if (m_pHeadlight) { // Turned off the headlight; delete it. delete m_pHeadlight; m_pHeadlight = NULL; } #else else if ( m_pHeadlightBeam ) { m_pHeadlightBeam->die = gpGlobals->curtime; // or beams->FreeBeam? m_pHeadlightBeam->flags &= ~FBEAM_FOREVER; m_pHeadlightBeam = NULL; } #endif } //----------------------------------------------------------------------------- void C_NPC_Chumtoad::DrawWake( void ) { if ( GetWaterLevel() == 0 ) return; float flSpeed = m_vecPhysVelocity.Length(); float flSpeedFrac = flSpeed / m_flEngineSpeed; flSpeedFrac = clamp( flSpeedFrac, 0.0f, 1.0f ); if ( flSpeedFrac < 0.2 ) return; Vector startPos = GetAbsOrigin(); Vector wakeDir = m_vecPhysVelocity; wakeDir.NormalizeInPlace(); wakeDir *= -1; float wakeLength = 16 + flSpeedFrac * 48; float speed = flSpeed; float minSpeed = 150*0.2; float maxSpeed = 150; /////////////////////////////////////////////////// #define WAKE_STEPS 6 Vector wakeStep = wakeDir * ( wakeLength / (float) WAKE_STEPS ); Vector origin; float scale; CMatRenderContextPtr pRenderContext( materials ); IMaterial *mat = materials->FindMaterial( "effects/splashwake1", TEXTURE_GROUP_CLIENT_EFFECTS ); IMesh* pMesh = pRenderContext->GetDynamicMesh( 0, 0, 0, mat ); CMeshBuilder meshBuilder; meshBuilder.Begin( pMesh, MATERIAL_QUADS, WAKE_STEPS ); for ( int i = 0; i < WAKE_STEPS; i++ ) { origin = startPos + ( wakeStep * i ); origin[0] += random->RandomFloat( -4.0f, 4.0f ); origin[1] += random->RandomFloat( -4.0f, 4.0f ); origin[2] = m_nExactWaterLevel + 2.0f; float scaleRange = RemapVal( i, 0, WAKE_STEPS-1, 16, 32 ); scale = scaleRange + ( 8.0f * sin( gpGlobals->curtime * 5 * i ) ); float alpha = RemapValClamped( speed, minSpeed, maxSpeed, 0.05f, 0.25f ); float color[4] = { 1.0f, 1.0f, 1.0f, alpha }; // Needs to be time based so it'll freeze when the game is frozen float yaw = random->RandomFloat( 0, 360 ); Vector rRight = ( Vector(1,0,0) * cos( DEG2RAD( yaw ) ) ) - ( Vector(0,1,0) * sin( DEG2RAD( yaw ) ) ); Vector rUp = ( Vector(1,0,0) * cos( DEG2RAD( yaw+90.0f ) ) ) - ( Vector(0,1,0) * sin( DEG2RAD( yaw+90.0f ) ) ); Vector point; meshBuilder.Color4fv (color); meshBuilder.TexCoord2f (0, 0, 1); VectorMA (origin, -scale, rRight, point); VectorMA (point, -scale, rUp, point); meshBuilder.Position3fv (point.Base()); meshBuilder.AdvanceVertex(); meshBuilder.Color4fv (color); meshBuilder.TexCoord2f (0, 0, 0); VectorMA (origin, scale, rRight, point); VectorMA (point, -scale, rUp, point); meshBuilder.Position3fv (point.Base()); meshBuilder.AdvanceVertex(); meshBuilder.Color4fv (color); meshBuilder.TexCoord2f (0, 1, 0); VectorMA (origin, scale, rRight, point); VectorMA (point, scale, rUp, point); meshBuilder.Position3fv (point.Base()); meshBuilder.AdvanceVertex(); meshBuilder.Color4fv (color); meshBuilder.TexCoord2f (0, 1, 1); VectorMA (origin, -scale, rRight, point); VectorMA (point, scale, rUp, point); meshBuilder.Position3fv (point.Base()); meshBuilder.AdvanceVertex(); } meshBuilder.End(); pMesh->Draw(); } //----------------------------------------------------------------------------- int C_NPC_Chumtoad::DrawModel( int flags ) { if ( BaseClass::DrawModel( flags ) == false ) return 0; if ( m_bHeadlightIsOn ) { // IMaterial *pMat = materials->FindMaterial( "sprites/glow_test02.vmt", NULL ); if ( gpGlobals->frametime != 0 ) { if ( m_pHeadlightBeam != NULL ) { m_pHeadlightBeam->attachment[0] = m_vecHeadlightBeamStart; m_pHeadlightBeam->attachment[1] = m_vecHeadlightBeamEnd; VectorSubtract( m_pHeadlightBeam->attachment[1], m_pHeadlightBeam->attachment[0], m_pHeadlightBeam->delta ); #if 0 if ( m_pHeadlightBeam->amplitude >= 0.50 ) m_pHeadlightBeam->segments = VectorLength( m_pHeadlightBeam->delta ) * 0.25 + 3; // one per 4 pixels else m_pHeadlightBeam->segments = VectorLength( m_pHeadlightBeam->delta ) * 0.075 + 3; // one per 16 pixels #endif } } } DrawWake(); return 1; }
28.448179
113
0.647204
[ "vector" ]
2a80bb0b968c8f2794d9ab3a3ed5ecdcee776677
724
cpp
C++
leetcode.com/0518 Coin Change 2/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0518 Coin Change 2/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0518 Coin Change 2/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <algorithm> #include <iostream> #include <unordered_map> #include <vector> using namespace std; // dfs, too slow: 744ms class Solution { private: unordered_map<int, unordered_map<int, int>> dp; int n; int dfs(int idx, int remain, vector<int>& coins) { if (remain == 0) return 1; if (idx == n) return 0; if (dp[idx].count(remain)) return dp[idx][remain]; int res = 0; for (int i = remain / coins[idx]; i >= 0; --i) res += dfs(idx + 1, remain - i * coins[idx], coins); return dp[idx][remain] = res; } public: int change(int amount, vector<int>& coins) { sort(coins.rbegin(), coins.rend()); n = coins.size(); dp.clear(); return dfs(0, amount, coins); } };
24.133333
58
0.603591
[ "vector" ]
2a83231adf40a7fa93c90bba7f558b43b6099674
2,882
cc
C++
easyeye-compare/tests/easyeye_compare_main_test.cc
mike10004/easyeye
d9996cab2edcedbc1eb78ab6366866423c6be023
[ "MIT" ]
4
2017-01-27T16:38:53.000Z
2018-09-07T14:02:39.000Z
easyeye-compare/tests/easyeye_compare_main_test.cc
superchao1982/easyeye
d9996cab2edcedbc1eb78ab6366866423c6be023
[ "MIT" ]
1
2018-07-25T18:19:43.000Z
2018-07-25T18:19:43.000Z
easyeye-compare/tests/easyeye_compare_main_test.cc
superchao1982/easyeye
d9996cab2edcedbc1eb78ab6366866423c6be023
[ "MIT" ]
11
2015-02-20T05:28:22.000Z
2021-07-27T03:57:27.000Z
/* * File: main_test.cc * Author: mchaberski * * Created on Jul 16, 2013, 4:06:43 PM */ #include <stdlib.h> #include <iostream> #include <unistd.h> #include <cstring> #include <cstdio> #include <easyeye/common/mylog.h> #include "../src/easyeye_compare_main.h" #include <vector> #include <string> #include <sstream> #include <easyeye/common/easyeye_types.h> #include <easyeye/common/easyeye_utils.h> #include "../../easyeye/tests/testdata.h" using namespace easyeye::compare; using namespace std; void testeasyeye_compare_main_multi() { vector<string> args; args.push_back("easyeye-compare"); args.push_back("--delim"); args.push_back(" "); const int nencodings = NUM_SAMPLES; for (int i = 0; i < nencodings; i++) { args.push_back(serialized_encodings[i]); } Compare program; int rv = program.Main(args); if (rv != 0) { std::cout << "%TEST_FAILED% time=0 testname=testeasyeye_compare_main_multi (easyeye_compare_main_Test) message=exit status " << rv << ' ' << easyeye::Result::DescribeStatus(rv) << endl; } else { std::cout << "testeasyeye_compare_main_multi completed successfully (exit status 0)" << std::endl; } } void testeasyeye_compare_main() { vector<string> args; args.push_back("easyeye-compare"); args.push_back("-s"); args.push_back(serialized_encodings[0]); args.push_back(serialized_encodings[1]); const int argc =args.size(); for (int i = 0; i < argc; i++) { std::cout << " arg[" << i << "] = " << args[i] << std::endl; } Compare program; int rv = program.Main(args); if (rv != 0) { cout << "%TEST_FAILED% time=0 testname=testeasyeye_compare_main (easyeye_compare_main_Test) message=exit status " << rv << ' ' << easyeye::program::Program::DescribeCode(rv) << endl; } else { cout << "testeasyeye_compare_main completed successfully (exit status 0)" << std::endl; } } int main(int argc, char** argv) { std::cout << "%SUITE_STARTING% main_test" << std::endl; std::cout << "%SUITE_STARTED%" << std::endl; std::cout << "%TEST_STARTED% testeasyeye_compare_main (main_test)" << std::endl; cerr << "[start log for testeasyeye_compare_main]" << endl; testeasyeye_compare_main(); cerr << "[end log for testeasyeye_compare_main]" << endl; std::cout << "%TEST_FINISHED% time=0 testeasyeye_compare_main (main_test)" << std::endl; std::cout << "%TEST_STARTED% testeasyeye_compare_main_multi (main_test)" << std::endl; cerr << "[start log for testeasyeye_compare_main_multi]" << endl; testeasyeye_compare_main_multi(); cerr << "[end log for testeasyeye_compare_main_multi]" << endl; std::cout << "%TEST_FINISHED% time=0 testeasyeye_compare_main_multi (main_test)" << std::endl; std::cout << "%SUITE_FINISHED% time=0" << std::endl; return (EXIT_SUCCESS); }
34.309524
193
0.65857
[ "vector" ]
2a8e01b112fe9ba0fc47ef646dd83a5e4920dcb2
3,141
cpp
C++
IRadiance/src/IRadiance/Raytracer/Materials/Phong.cpp
Nickelium/IRadiance
7e7040460852a6f9f977cf466e6dcecf44618ae7
[ "MIT" ]
null
null
null
IRadiance/src/IRadiance/Raytracer/Materials/Phong.cpp
Nickelium/IRadiance
7e7040460852a6f9f977cf466e6dcecf44618ae7
[ "MIT" ]
null
null
null
IRadiance/src/IRadiance/Raytracer/Materials/Phong.cpp
Nickelium/IRadiance
7e7040460852a6f9f977cf466e6dcecf44618ae7
[ "MIT" ]
null
null
null
#include "pch.h" #include "Phong.h" #include "IRadiance/Raytracer/BxDF/Lambertian.h" #include "IRadiance/Raytracer/BxDF/GlossySpecular.h" #include "IRadiance/Raytracer/Renderer.h" #include "IRadiance/Raytracer/Tracers/Tracer.h" namespace IRadiance { Phong::Phong() : ambientBRDF(new Lambertian), diffuseBRDF(new Lambertian), glossySpecularBRDF(new GlossySpecular) { } RGBSpectrum Phong::Shading(HitRecord& _hr) { Vector wO = -_hr.ray.d; RGBSpectrum L; L = ambientBRDF->rho(_hr, wO) * _hr.renderer->GetScene()->GetAmbientLight()->L(_hr); for (const Light* light : _hr.renderer->GetScene()->GetLights()) { Vector wI = light->GetDirection(_hr); float nCosWi = Dot(wI, _hr.normal); if (nCosWi > 0.0f) { bool inShadow = false; if (light->CastShadow()) { Ray shadowRay; shadowRay.o = _hr.hitPoint; shadowRay.d = wI; inShadow = light->InShadow(shadowRay, _hr); } if(!inShadow) L += (diffuseBRDF->f(_hr, wO, wI) + glossySpecularBRDF->f(_hr, wO, wI)) * light->L(_hr) * nCosWi; } } return L; } RGBSpectrum Phong::WhittedShading(HitRecord& _hr) { return Phong::AreaLightShading(_hr); } RGBSpectrum Phong::AreaLightShading(HitRecord& _hr) { Vector wO = -_hr.ray.d; RGBSpectrum L = _hr.renderer->GetScene()->GetAmbientLight()->L(_hr) * ambientBRDF->rho(_hr, wO); const auto& lights = _hr.renderer->GetScene()->GetLights(); for (auto light : lights) { const int shadowRays = 1; for (int i = 0; i < shadowRays; ++i) { Vector wI = light->GetDirection(_hr); float nCosWi = Dot(_hr.normal, wI); if (nCosWi > 0.0f) { bool inShadow = false; if (light->CastShadow()) { Ray shadowRay; shadowRay.o = _hr.hitPoint; shadowRay.d = wI; inShadow = light->InShadow(shadowRay, _hr); } if (!inShadow) L += ((diffuseBRDF->f(_hr, wO, wI) + glossySpecularBRDF->f(_hr, wO, wI)) * light->L(_hr) * light->G(_hr) * nCosWi) / light->pdf(_hr); } } L /= shadowRays; } return L; } RGBSpectrum Phong::PathShading(HitRecord& _hr) { Vector wO = -_hr.ray.d; Vector wI; float pdf; RGBSpectrum f = glossySpecularBRDF->Sample_f(_hr, wO, wI, pdf); float nCosWi = Dot(_hr.normal, wI); Ray reflected; reflected.o = _hr.hitPoint; reflected.d = wI; return ((f * _hr.renderer->GetTracer()->RayTrace(reflected, _hr.depth + 1) * nCosWi) / pdf); } RGBSpectrum Phong::HybridPathShading(HitRecord& _hr) { return PathShading(_hr); } void Phong::SetKa(float _ka) { ambientBRDF->SetKa(_ka); } void Phong::SetKd(float _kd) { diffuseBRDF->SetKd(_kd); } void Phong::SetCd(const RGBSpectrum& _c) { ambientBRDF->SetCd(_c); diffuseBRDF->SetCd(_c); } void Phong::SetKs(const RGBSpectrum& _ks) { glossySpecularBRDF->SetKs(_ks); } void Phong::SetExp(float _exp) { glossySpecularBRDF->SetExp(_exp); } void Phong::SetCs(const RGBSpectrum& _cs) { glossySpecularBRDF->SetCs(_cs); } }
22.76087
99
0.615091
[ "vector" ]
2a8f410520b055f51bdca03feb0fbc6a6932b1d9
12,942
cpp
C++
frameworks/core/components/text_field/text_field_component.cpp
chaoyangcui/ace_ace_engine
05ebe2d6d2674777f5dc64fd735088dcf1a42cd9
[ "Apache-2.0" ]
null
null
null
frameworks/core/components/text_field/text_field_component.cpp
chaoyangcui/ace_ace_engine
05ebe2d6d2674777f5dc64fd735088dcf1a42cd9
[ "Apache-2.0" ]
null
null
null
frameworks/core/components/text_field/text_field_component.cpp
chaoyangcui/ace_ace_engine
05ebe2d6d2674777f5dc64fd735088dcf1a42cd9
[ "Apache-2.0" ]
1
2021-09-13T12:07:42.000Z
2021-09-13T12:07:42.000Z
/* * Copyright (c) 2021 Huawei Device Co., 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 "core/components/text_field/text_field_component.h" #include "core/components/text_field/render_text_field.h" #include "core/components/text_field/text_field_element.h" namespace OHOS::Ace { RefPtr<RenderNode> TextFieldComponent::CreateRenderNode() { return RenderTextField::Create(); } RefPtr<Element> TextFieldComponent::CreateElement() { return AceType::MakeRefPtr<TextFieldElement>(); } const std::string& TextFieldComponent::GetValue() const { return value_; } void TextFieldComponent::SetValue(const std::string& value) { value_ = value; isValueUpdated_ = true; } bool TextFieldComponent::IsValueUpdated() const { return isValueUpdated_; } const std::string& TextFieldComponent::GetPlaceholder() const { return placeholder_; } void TextFieldComponent::SetPlaceholder(const std::string& placeholder) { placeholder_ = placeholder; } const Color& TextFieldComponent::GetPlaceholderColor() const { return placeholderColor_; } void TextFieldComponent::SetPlaceholderColor(const Color& placeholderColor) { placeholderColor_ = placeholderColor; } void TextFieldComponent::SetTextMaxLines(uint32_t textMaxLines) { textMaxLines_ = textMaxLines; } TextAlign TextFieldComponent::GetTextAlign() const { return textAlign_; } void TextFieldComponent::SetTextAlign(TextAlign textAlign) { textAlign_ = textAlign; } uint32_t TextFieldComponent::GetTextMaxLines() const { return textMaxLines_; } const TextStyle& TextFieldComponent::GetTextStyle() const { return textStyle_; } void TextFieldComponent::SetTextStyle(const TextStyle& textStyle) { textStyle_ = textStyle; } const TextStyle& TextFieldComponent::GetErrorTextStyle() const { return errorTextStyle_; } void TextFieldComponent::SetErrorTextStyle(const TextStyle& errorTextStyle) { errorTextStyle_ = errorTextStyle; } const Dimension& TextFieldComponent::GetErrorSpacing() const { return errorSpacing_; } void TextFieldComponent::SetErrorSpacing(const Dimension& errorSpacing) { errorSpacing_ = errorSpacing; } bool TextFieldComponent::GetErrorIsInner() const { return errorIsInner_; } void TextFieldComponent::SetErrorIsInner(bool errorIsInner) { errorIsInner_ = errorIsInner; } const Dimension& TextFieldComponent::GetErrorBorderWidth() const { return errorBorderWidth_; } void TextFieldComponent::SetErrorBorderWidth(const Dimension& errorBorderWidth) { errorBorderWidth_ = errorBorderWidth; } const Color& TextFieldComponent::GetErrorBorderColor() const { return errorBorderColor_; } void TextFieldComponent::SetErrorBorderColor(const Color& errorBorderColor) { errorBorderColor_ = errorBorderColor; } bool TextFieldComponent::NeedFade() const { return needFade_; } void TextFieldComponent::SetNeedFade(bool needFade) { needFade_ = needFade; } RefPtr<Decoration> TextFieldComponent::GetDecoration() const { return decoration_; } void TextFieldComponent::SetDecoration(const RefPtr<Decoration>& decoration) { decoration_ = decoration; } void TextFieldComponent::SetOriginBorder(const Border& originBorder) { originBorder_ = originBorder; } const Border& TextFieldComponent::GetOriginBorder() const { return originBorder_; } bool TextFieldComponent::ShowCursor() const { return showCursor_; } void TextFieldComponent::SetShowCursor(bool show) { showCursor_ = show; } bool TextFieldComponent::NeedObscure() const { return obscure_; } void TextFieldComponent::SetObscure(bool obscure) { obscure_ = obscure; } bool TextFieldComponent::IsEnabled() const { return enabled_; } void TextFieldComponent::SetEnabled(bool enable) { enabled_ = enable; } TextInputType TextFieldComponent::GetTextInputType() const { return keyboard_; } void TextFieldComponent::SetTextInputType(TextInputType type) { keyboard_ = type; } TextInputAction TextFieldComponent::GetAction() const { return action_; } void TextFieldComponent::SetAction(TextInputAction action) { action_ = action; } void TextFieldComponent::SetCursorColor(const Color& color) { cursorColor_ = color; cursorColorIsSet_ = true; } const Color& TextFieldComponent::GetCursorColor() { return cursorColor_; } void TextFieldComponent::SetCursorRadius(const Dimension& radius) { cursorRadius_ = radius; } const Dimension& TextFieldComponent::GetCursorRadius() const { return cursorRadius_; } bool TextFieldComponent::IsCursorColorSet() const { return cursorColorIsSet_; } const std::string& TextFieldComponent::GetActionLabel() const { return actionLabel_; } void TextFieldComponent::SetActionLabel(const std::string& actionLabel) { actionLabel_ = actionLabel; } uint32_t TextFieldComponent::GetMaxLength() const { return maxLength_; } void TextFieldComponent::SetMaxLength(uint32_t maxLength) { maxLength_ = maxLength; lengthLimited_ = true; } bool TextFieldComponent::IsTextLengthLimited() const { return lengthLimited_; } const Dimension& TextFieldComponent::GetHeight() const { return height_; } void TextFieldComponent::SetHeight(const Dimension& height) { height_ = height; } bool TextFieldComponent::GetAutoFocus() const { return autoFocus_; } void TextFieldComponent::SetAutoFocus(bool autoFocus) { autoFocus_ = autoFocus; } bool TextFieldComponent::IsExtend() const { return extend_; } void TextFieldComponent::SetExtend(bool extend) { extend_ = extend; } bool TextFieldComponent::ShowEllipsis() const { return showEllipsis_; } void TextFieldComponent::SetShowEllipsis(bool showEllipsis) { showEllipsis_ = showEllipsis; } const std::string& TextFieldComponent::GetIconImage() const { return iconImage_; } void TextFieldComponent::SetIconImage(const std::string& iconImage) { iconImage_ = iconImage; } const std::string& TextFieldComponent::GetShowIconImage() const { return showImage_; } void TextFieldComponent::SetShowIconImage(const std::string& showImage) { showImage_ = showImage; } const std::string& TextFieldComponent::GetHideIconImage() const { return hideImage_; } void TextFieldComponent::SetHideIconImage(const std::string& hideImage) { hideImage_ = hideImage; } const Dimension& TextFieldComponent::GetIconSize() const { return iconSize_; } void TextFieldComponent::SetIconSize(const Dimension& iconSize) { iconSize_ = iconSize; } const Dimension& TextFieldComponent::GetIconHotZoneSize() const { return iconHotZoneSize_; } void TextFieldComponent::SetIconHotZoneSize(const Dimension& iconHotZoneSize) { iconHotZoneSize_ = iconHotZoneSize; } const EventMarker& TextFieldComponent::GetOnTextChange() const { return onTextChange_; } void TextFieldComponent::SetOnTextChange(const EventMarker& onTextChange) { onTextChange_ = onTextChange; } const EventMarker& TextFieldComponent::GetOnFinishInput() const { return onFinishInput_; } void TextFieldComponent::SetOnFinishInput(const EventMarker& onFinishInput) { onFinishInput_ = onFinishInput; } const EventMarker& TextFieldComponent::GetOnTap() const { return onTap_; } void TextFieldComponent::SetOnTap(const EventMarker& onTap) { onTap_ = onTap; } const EventMarker& TextFieldComponent::GetOnLongPress() const { return onLongPress_; } void TextFieldComponent::SetOnLongPress(const EventMarker& onLongPress) { onLongPress_ = onLongPress; } const RefPtr<TextEditController>& TextFieldComponent::GetTextEditController() const { return controller_; } void TextFieldComponent::SetTextEditController(const RefPtr<TextEditController>& controller) { controller_ = controller; } const RefPtr<TextFieldController>& TextFieldComponent::GetTextFieldController() const { return textFieldController_; } void TextFieldComponent::SetTextFieldController(const RefPtr<TextFieldController>& controller) { textFieldController_ = controller; } void TextFieldComponent::SetFocusBgColor(const Color& focusBgColor) { focusBgColor_ = focusBgColor; } const Color& TextFieldComponent::GetFocusBgColor() { return focusBgColor_; } void TextFieldComponent::SetFocusPlaceholderColor(const Color& focusPlaceholderColor) { focusPlaceholderColor_ = focusPlaceholderColor; } const Color& TextFieldComponent::GetFocusPlaceholderColor() { return focusPlaceholderColor_; } void TextFieldComponent::SetFocusTextColor(const Color& focusTextColor) { focusTextColor_ = focusTextColor; } const Color& TextFieldComponent::GetFocusTextColor() { return focusTextColor_; } void TextFieldComponent::SetBgColor(const Color& bgColor) { bgColor_ = bgColor; } const Color& TextFieldComponent::GetBgColor() { return bgColor_; } void TextFieldComponent::SetTextColor(const Color& textColor) { textColor_ = textColor; } const Color& TextFieldComponent::GetTextColor() { return textColor_; } void TextFieldComponent::SetWidthReserved(const Dimension& widthReserved) { widthReserved_ = widthReserved; } const Dimension& TextFieldComponent::GetWidthReserved() const { return widthReserved_; } const Color& TextFieldComponent::GetSelectedColor() const { return selectedColor_; } void TextFieldComponent::SetSelectedColor(const Color& selectedColor) { selectedColor_ = selectedColor; } const Color& TextFieldComponent::GetHoverColor() const { return hoverColor_; } void TextFieldComponent::SetHoverColor(const Color& hoverColor) { hoverColor_ = hoverColor; } const Color& TextFieldComponent::GetPressColor() const { return pressColor_; } void TextFieldComponent::SetPressColor(const Color& pressColor) { pressColor_ = pressColor; } void TextFieldComponent::SetBlockRightShade(bool blockRightShade) { blockRightShade_ = blockRightShade; } bool TextFieldComponent::GetBlockRightShade() const { return blockRightShade_; } void TextFieldComponent::SetIsVisible(bool isVisible) { isVisible_ = isVisible; } bool TextFieldComponent::IsVisible() const { return isVisible_; } void TextFieldComponent::SetResetToStart(bool resetToStart) { resetToStart_ = resetToStart; } bool TextFieldComponent::GetResetToStart() const { return resetToStart_; } void TextFieldComponent::SetShowCounter(bool showCounter) { showCounter_ = showCounter; } bool TextFieldComponent::ShowCounter() const { return showCounter_; } void TextFieldComponent::SetCountTextStyle(const TextStyle& countTextStyle) { countTextStyle_ = countTextStyle; } const TextStyle& TextFieldComponent::GetCountTextStyle() const { return countTextStyle_; } void TextFieldComponent::SetOverCountStyle(const TextStyle& overCountStyle) { overCountStyle_ = overCountStyle; } const TextStyle& TextFieldComponent::GetOverCountStyle() const { return overCountStyle_; } void TextFieldComponent::SetCountTextStyleOuter(const TextStyle& countTextStyleOuter) { countTextStyleOuter_ = countTextStyleOuter; } const TextStyle& TextFieldComponent::GetCountTextStyleOuter() const { return countTextStyleOuter_; } void TextFieldComponent::SetOverCountStyleOuter(const TextStyle& overCountStyleOuter) { overCountStyleOuter_ = overCountStyleOuter; } const TextStyle& TextFieldComponent::GetOverCountStyleOuter() const { return overCountStyleOuter_; } void TextFieldComponent::SetInputOptions(const std::vector<Framework::InputOption>& inputOptions) { inputOptions_ = inputOptions; } const std::vector<Framework::InputOption>& TextFieldComponent::GetInputOptions() const { return inputOptions_; } const EventMarker& TextFieldComponent::GetOnOptionsClick() const { return onOptionsClick_; } void TextFieldComponent::SetOnOptionsClick(const EventMarker& onOptionsClick) { onOptionsClick_ = onOptionsClick; } const EventMarker& TextFieldComponent::GetOnTranslate() const { return onTranslate_; } void TextFieldComponent::SetOnTranslate(const EventMarker& onTranslate) { onTranslate_ = onTranslate; } const EventMarker& TextFieldComponent::GetOnShare() const { return onShare_; } void TextFieldComponent::SetOnShare(const EventMarker& onShare) { onShare_ = onShare; } const EventMarker& TextFieldComponent::GetOnSearch() const { return onSearch_; } void TextFieldComponent::SetOnSearch(const EventMarker& onSearch) { onSearch_ = onSearch; } } // namespace OHOS::Ace
19.849693
97
0.771828
[ "vector" ]
2a96664678241c284f33c72951d32d88442cc69c
28,996
hpp
C++
wfa_lm_st.hpp
jeizenga/wfalm
523413af2824db88be9d7f52cfa37211eb920e83
[ "MIT" ]
16
2022-01-15T16:32:35.000Z
2022-02-08T08:25:10.000Z
wfa_lm_st.hpp
jeizenga/wfalm
523413af2824db88be9d7f52cfa37211eb920e83
[ "MIT" ]
3
2022-03-26T01:22:54.000Z
2022-03-31T19:27:01.000Z
wfa_lm_st.hpp
jeizenga/wfalm
523413af2824db88be9d7f52cfa37211eb920e83
[ "MIT" ]
null
null
null
// // wfa_lm_st.hpp // // MIT License // // Copyright (c) 2022 Jordan Eizenga // // 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 wfa_lm_st_hpp_included #define wfa_lm_st_hpp_included #include "wfa_lm.hpp" #include <sdsl/construct.hpp> #include <sdsl/cst_sada.hpp> #include <sdsl/cst_sct3.hpp> #include <sdsl/csa_bitcompressed.hpp> namespace wfalm { /* * Class that performs WFA with the standard, low-memory, or recusive variants. * This class differs from WFAligner in that it uses a longest-common-extension * algorithm based on a suffix tree to compute matches. In most cases, this is * slower than the default comparison-based match computation. */ template<int NumPW> class WFAlignerST : public WFAligner<NumPW> { public: /// Initialize with WFA-style score parameters. On opening an insertion or /// deletion, *both* the gap open and gap extend penalties are applied. /// Scores returned by alignment methods will also be WFA-style. WFAlignerST(uint32_t mismatch, std::array<uint32_t, std::max(1, NumPW)> gap_extend, std::array<uint32_t, NumPW> gap_open); /// Initialize with Smith-Waterman-Gotoh-style score parameters. On opening an /// insertion or deletion, *both* the gap open and gap extend penalties are applied. /// Scores returned by alignment methods will also be Smith-Waterman-Gotoh-style. WFAlignerST(uint32_t match, uint32_t mismatch, std::array<uint32_t, std::max(1, NumPW)> gap_extend, std::array<uint32_t, NumPW> gap_open); /// Default constructor. Performs edit distance alignment. WFAlignerST(); /***************************** * Configurable parameters * *****************************/ /// If set to a number >= 0, prunes diagonals that fall this many anti-diagonals /// behind the furthest-reaching diagonal. This can lead to suboptimal alignments, /// but it also can increase speed and reduce memory use. If set to a number < 0, /// no pruning is performed. using WFAligner<NumPW>::lagging_diagonal_prune; /*********************** * Alignment methods * ***********************/ /// Globally align two sequences using the fastest algorithm that will remain /// constrained to a given maximum memory, using a suffix tree to compute matches /// /// Args: /// seq1 First sequence to be aligned (need not be null-terminated) /// len1 Length of first sequence to be aligned /// seq2 Second sequence to be aligned (need not be null-terminated) /// len2 Length of second sequence to be aligned /// target_mem The target maximum memory use in bytes /// /// Return value: /// Pair consisting of CIGAR string for alignment and the alignment score. inline std::pair<std::vector<CIGAROp>, int32_t> wavefront_align_adaptive(const char* seq1, size_t len1, const char* seq2, size_t len2, uint64_t max_mem) const; /// Globally align two sequences in O(s log s) memory using the recursive WFA algorithm, /// using a suffix tree to compute matches. /// /// Args: /// seq1 First sequence to be aligned (need not be null-terminated) /// len1 Length of first sequence to be aligned /// seq2 Second sequence to be aligned (need not be null-terminated) /// len2 Length of second sequence to be aligned /// /// Return value: /// Pair consisting of CIGAR string for alignment and the alignment score. inline std::pair<std::vector<CIGAROp>, int32_t> wavefront_align_recursive(const char* seq1, size_t len1, const char* seq2, size_t len2) const; /// Globally align two sequences in O(s^3/2) memory using the low-memory WFA algorithm, /// using a suffix tree to compute matches. /// /// Args: /// seq1 First sequence to be aligned (need not be null-terminated) /// len1 Length of first sequence to be aligned /// seq2 Second sequence to be aligned (need not be null-terminated) /// len2 Length of second sequence to be aligned /// /// Return value: /// Pair consisting of CIGAR string for alignment and the alignment score. inline std::pair<std::vector<CIGAROp>, int32_t> wavefront_align_low_mem(const char* seq1, size_t len1, const char* seq2, size_t len2) const; /// Globally align two sequences in O(s^2) memory using the standard WFA algorithm, /// using a suffix tree to compute matches. /// /// Args: /// seq1 First sequence to be aligned (need not be null-terminated) /// len1 Length of first sequence to be aligned /// seq2 Second sequence to be aligned (need not be null-terminated) /// len2 Length of second sequence to be aligned /// /// Return value: /// Pair consisting of CIGAR string for alignment and the alignment score. inline std::pair<std::vector<CIGAROp>, int32_t> wavefront_align(const char* seq1, size_t len1, const char* seq2, size_t len2) const; /// Locally align two sequences from a seed using the adaptive WFA as an /// alignment engine. *Can only called if WFAligner was initialized with /// Smith-Waterman-Gotoh scoring parameters in the constructor.* /// /// Args: /// seq1 First sequence to be aligned (need not be null-terminated) /// len1 Length of first sequence to be aligned /// seq2 Second sequence to be aligned (need not be null-terminated) /// len2 Length of second sequence to be aligned /// max_mem The target maximum memory use in bytes /// anchor_begin_1 First index of the anchor on seq1 /// anchor_end_1 Past-the-last index of the anchor on seq1 /// anchor_begin_2 First index of the anchor on seq2 /// anchor_end_2 Past-the-last index of the anchor on seq2 /// anchor_is_match If false, the anchor sequence will be aligned, otherwise /// it will be assumed to be a match /// /// Return value: /// A tuple consisting of: /// - CIGAR string for alignment /// - the alignment score /// - a pair of indexes indicating the interval of aligned sequence on seq1 /// - a pair of indexes indicating the interval of aligned sequence on seq2 inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>> wavefront_align_local_adaptive(const char* seq1, size_t len1, const char* seq2, size_t len2, uint64_t max_mem, size_t anchor_begin_1, size_t anchor_end_1, size_t anchor_begin_2, size_t anchor_end_2, bool anchor_is_match = true) const; /// Locally align two sequences from a seed using the recursive WFA as an /// alignment engine. *Can only called if WFAligner was initialized with /// Smith-Waterman-Gotoh scoring parameters in the constructor.* /// /// Args: /// seq1 First sequence to be aligned (need not be null-terminated) /// len1 Length of first sequence to be aligned /// seq2 Second sequence to be aligned (need not be null-terminated) /// len2 Length of second sequence to be aligned /// anchor_begin_1 First index of the anchor on seq1 /// anchor_end_1 Past-the-last index of the anchor on seq1 /// anchor_begin_2 First index of the anchor on seq2 /// anchor_end_2 Past-the-last index of the anchor on seq2 /// anchor_is_match If false, the anchor sequence will be aligned, otherwise /// it will be assumed to be a match /// /// Return value: /// A tuple consisting of: /// - CIGAR string for alignment /// - the alignment score /// - a pair of indexes indicating the interval of aligned sequence on seq1 /// - a pair of indexes indicating the interval of aligned sequence on seq2 inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>> wavefront_align_local_recursive(const char* seq1, size_t len1, const char* seq2, size_t len2, size_t anchor_begin_1, size_t anchor_end_1, size_t anchor_begin_2, size_t anchor_end_2, bool anchor_is_match = true) const; /// Locally align two sequences from a seed using the low memory WFA as an /// alignment engine. *Can only called if WFAligner was initialized with /// Smith-Waterman-Gotoh scoring parameters in the constructor.* /// /// Args: /// seq1 First sequence to be aligned (need not be null-terminated) /// len1 Length of first sequence to be aligned /// seq2 Second sequence to be aligned (need not be null-terminated) /// len2 Length of second sequence to be aligned /// anchor_begin_1 First index of the anchor on seq1 /// anchor_end_1 Past-the-last index of the anchor on seq1 /// anchor_begin_2 First index of the anchor on seq2 /// anchor_end_2 Past-the-last index of the anchor on seq2 /// anchor_is_match If false, the anchor sequence will be aligned, otherwise /// it will be assumed to be a match /// /// Return value: /// A tuple consisting of: /// - CIGAR string for alignment /// - the alignment score /// - a pair of indexes indicating the interval of aligned sequence on seq1 /// - a pair of indexes indicating the interval of aligned sequence on seq2 inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>> wavefront_align_local_low_mem(const char* seq1, size_t len1, const char* seq2, size_t len2, size_t anchor_begin_1, size_t anchor_end_1, size_t anchor_begin_2, size_t anchor_end_2, bool anchor_is_match = true) const; /// Locally align two sequences from a seed using the standard WFA as an /// alignment engine. *Can only called if WFAligner was initialized with /// Smith-Waterman-Gotoh scoring parameters in the constructor.* /// /// Args: /// seq1 First sequence to be aligned (need not be null-terminated) /// len1 Length of first sequence to be aligned /// seq2 Second sequence to be aligned (need not be null-terminated) /// len2 Length of second sequence to be aligned /// anchor_begin_1 First index of the anchor on seq1 /// anchor_end_1 Past-the-last index of the anchor on seq1 /// anchor_begin_2 First index of the anchor on seq2 /// anchor_end_2 Past-the-last index of the anchor on seq2 /// anchor_is_match If false, the anchor sequence will be aligned, otherwise /// it will be assumed to be a match /// /// Return value: /// A tuple consisting of: /// - CIGAR string for alignment /// - the alignment score /// - a pair of indexes indicating the interval of aligned sequence on seq1 /// - a pair of indexes indicating the interval of aligned sequence on seq2 inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>> wavefront_align_local(const char* seq1, size_t len1, const char* seq2, size_t len2, size_t anchor_begin_1, size_t anchor_end_1, size_t anchor_begin_2, size_t anchor_end_2, bool anchor_is_match = true) const; }; /******************************************************************* ******************************************************************* *** Only internal methods below here *** ******************************************************************* *******************************************************************/ typedef sdsl::cst_sada<sdsl::csa_bitcompressed<>, sdsl::lcp_dac<1>, sdsl::bp_support_gg<sdsl::nearest_neighbour_dictionary<1>, sdsl::rank_support_v<>, sdsl::select_support_mcl<>, 64>, sdsl::rank_support_v<10, 2>, sdsl::select_support_mcl<10, 2>> SuffixTree; // a match computing function based on the suffix tree struct STMatchFunc { public: STMatchFunc() = default; ~STMatchFunc() = default; protected: template<typename StringType> void init(const StringType& seq1, const StringType& seq2) { offset = seq1.size() + 1; // encoding: // a/A 1 // c/C 2 // g/G 3 // t/T 4 // else 5 // $ 6 static const uint8_t separator = 6; static const uint8_t st_encode[256] { uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // 0 uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // 32 uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // uint8_t(5), uint8_t(1), uint8_t(5), uint8_t(2), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(3), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // 64 uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(4), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // uint8_t(5), uint8_t(1), uint8_t(5), uint8_t(2), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(3), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // 96 uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(4), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // 128 uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // 160 uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // 192 uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), // 224 uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5), uint8_t(5) // }; // TODO: i wish this were possible with an implicit copy, but looks like probably not // since the sdsl::store_to_file that backends the in-memory construction is only // specialized for string and char* // - but also this gets us around the StringView vs. string issues in local alignment... // encode the joined string and the sentinel in a 3-bit alphabet std::string combined_seq(seq1.size() + seq2.size() + 1, 0); size_t i; for (i = 0; i < seq1.size(); ++i) { combined_seq[i] = st_encode[seq1[i]]; } combined_seq[i] = separator; ++i; for (size_t j = 0; j < seq2.size(); ++i, ++j) { combined_seq[i] = st_encode[seq2[j]]; } // construct in memory with 1-byte words sdsl::construct_im(suffix_tree, combined_seq, 1); } inline size_t lce(size_t i, size_t j) const { // in sdsl, suffix array indexes are 0-based, but leaf ranks are 1-based return suffix_tree.depth(suffix_tree.lca(suffix_tree.select_leaf(suffix_tree.csa.isa[i] + 1), suffix_tree.select_leaf(suffix_tree.csa.isa[offset + j] + 1))); } SuffixTree suffix_tree; size_t offset; }; class FwdSTMatchFunc : STMatchFunc { public: FwdSTMatchFunc(const StringView& seq1, const StringView& seq2) { init<StringView>(seq1, seq2); } inline size_t operator()(size_t i, size_t j) const { return lce(i, j); } }; class RevSTMatchFunc : STMatchFunc { public: RevSTMatchFunc(const RevStringView& seq1, const RevStringView& seq2) { init<RevStringView>(seq1, seq2); } inline size_t operator()(size_t i, size_t j) const { return lce(i, j); } }; template<int NumPW> WFAlignerST<NumPW>::WFAlignerST() : WFAligner<NumPW>() {} template<int NumPW> WFAlignerST<NumPW>::WFAlignerST(uint32_t mismatch, std::array<uint32_t, std::max(1, NumPW)> gap_extend, std::array<uint32_t, NumPW> gap_open) : WFAligner<NumPW>(mismatch, gap_extend, gap_open) { // only need to delegate to WFAligner } template<int NumPW> WFAlignerST<NumPW>::WFAlignerST(uint32_t match, uint32_t mismatch, std::array<uint32_t, std::max(1, NumPW)> gap_extend, std::array<uint32_t, NumPW> gap_open) : WFAligner<NumPW>(match, mismatch, gap_extend, gap_open) { // only need to delegate to WFAligner } template<int NumPW> inline std::pair<std::vector<CIGAROp>, int32_t> WFAlignerST<NumPW>::wavefront_align(const char* seq1, size_t len1, const char* seq2, size_t len2) const { StringView str1(seq1, 0, len1); StringView str2(seq2, 0, len2); return WFAligner<NumPW>::template wavefront_dispatch<false, WFAligner<NumPW>::StdMem, FwdSTMatchFunc>(str1, str2, std::numeric_limits<uint64_t>::max()); } template<int NumPW> inline std::pair<std::vector<CIGAROp>, int32_t> WFAlignerST<NumPW>::wavefront_align_low_mem(const char* seq1, size_t len1, const char* seq2, size_t len2) const { StringView str1(seq1, 0, len1); StringView str2(seq2, 0, len2); return WFAligner<NumPW>::template wavefront_dispatch<false, WFAligner<NumPW>::LowMem, FwdSTMatchFunc>(str1, str2, std::numeric_limits<uint64_t>::max()); } template<int NumPW> inline std::pair<std::vector<CIGAROp>, int32_t> WFAlignerST<NumPW>::wavefront_align_recursive(const char* seq1, size_t len1, const char* seq2, size_t len2) const { StringView str1(seq1, 0, len1); StringView str2(seq2, 0, len2); return WFAligner<NumPW>::template wavefront_dispatch<false, WFAligner<NumPW>::Recursive, FwdSTMatchFunc>(str1, str2, std::numeric_limits<uint64_t>::max()); } template<int NumPW> inline std::pair<std::vector<CIGAROp>, int32_t> WFAlignerST<NumPW>::wavefront_align_adaptive(const char* seq1, size_t len1, const char* seq2, size_t len2, uint64_t max_mem) const { StringView str1(seq1, 0, len1); StringView str2(seq2, 0, len2); return WFAligner<NumPW>::template wavefront_dispatch<false, WFAligner<NumPW>::AdaptiveMem, FwdSTMatchFunc>(str1, str2, max_mem); } template<int NumPW> inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>> WFAlignerST<NumPW>::wavefront_align_local(const char* seq1, size_t len1, const char* seq2, size_t len2, size_t anchor_begin_1, size_t anchor_end_1, size_t anchor_begin_2, size_t anchor_end_2, bool anchor_is_match) const { // configure the alignment and match functions typedef typename WFAligner<NumPW>::template StandardSemilocalWFA<RevSTMatchFunc, RevStringView> PrefWFA; typedef typename WFAligner<NumPW>::template StandardGlobalWFA<FwdSTMatchFunc, StringView> AnchorWFA; typedef typename WFAligner<NumPW>::template StandardSemilocalWFA<FwdSTMatchFunc, StringView> SuffWFA; return WFAligner<NumPW>::template wavefront_align_local_core<PrefWFA, AnchorWFA, SuffWFA>(seq1, len1, seq2, len2, std::numeric_limits<uint64_t>::max(), anchor_begin_1, anchor_end_1, anchor_begin_2, anchor_end_2, anchor_is_match); } template<int NumPW> inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>> WFAlignerST<NumPW>::wavefront_align_local_low_mem(const char* seq1, size_t len1, const char* seq2, size_t len2, size_t anchor_begin_1, size_t anchor_end_1, size_t anchor_begin_2, size_t anchor_end_2, bool anchor_is_match) const { // configure the alignment and match functions typedef typename WFAligner<NumPW>::template LowMemSemilocalWFA<RevSTMatchFunc, RevStringView> PrefWFA; typedef typename WFAligner<NumPW>::template LowMemGlobalWFA<FwdSTMatchFunc, StringView> AnchorWFA; typedef typename WFAligner<NumPW>::template LowMemSemilocalWFA<FwdSTMatchFunc, StringView> SuffWFA; return WFAligner<NumPW>::template wavefront_align_local_core<PrefWFA, AnchorWFA, SuffWFA>(seq1, len1, seq2, len2, std::numeric_limits<uint64_t>::max(), anchor_begin_1, anchor_end_1, anchor_begin_2, anchor_end_2, anchor_is_match); } template<int NumPW> inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>> WFAlignerST<NumPW>::wavefront_align_local_recursive(const char* seq1, size_t len1, const char* seq2, size_t len2, size_t anchor_begin_1, size_t anchor_end_1, size_t anchor_begin_2, size_t anchor_end_2, bool anchor_is_match) const { // configure the alignment and match functions typedef typename WFAligner<NumPW>::template RecursiveSemilocalWFA<RevSTMatchFunc, RevStringView> PrefWFA; typedef typename WFAligner<NumPW>::template RecursiveGlobalWFA<FwdSTMatchFunc, StringView> AnchorWFA; typedef typename WFAligner<NumPW>::template RecursiveSemilocalWFA<FwdSTMatchFunc, StringView> SuffWFA; return WFAligner<NumPW>::template wavefront_align_local_core<PrefWFA, AnchorWFA, SuffWFA>(seq1, len1, seq2, len2, std::numeric_limits<uint64_t>::max(), anchor_begin_1, anchor_end_1, anchor_begin_2, anchor_end_2, anchor_is_match); } template<int NumPW> inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>> WFAlignerST<NumPW>::wavefront_align_local_adaptive(const char* seq1, size_t len1, const char* seq2, size_t len2, uint64_t max_mem, size_t anchor_begin_1, size_t anchor_end_1, size_t anchor_begin_2, size_t anchor_end_2, bool anchor_is_match) const { // configure the alignment and match functions typedef typename WFAligner<NumPW>::template AdaptiveSemilocalWFA<RevSTMatchFunc, RevStringView> PrefWFA; typedef typename WFAligner<NumPW>::template AdaptiveGlobalWFA<FwdSTMatchFunc, StringView> AnchorWFA; typedef typename WFAligner<NumPW>::template AdaptiveSemilocalWFA<FwdSTMatchFunc, StringView> SuffWFA; return WFAligner<NumPW>::template wavefront_align_local_core<PrefWFA, AnchorWFA, SuffWFA>(seq1, len1, seq2, len2, max_mem, anchor_begin_1, anchor_end_1, anchor_begin_2, anchor_end_2, anchor_is_match); } } // end namespace wfalm #endif /* wfa_lm_st.hpp */
52.33935
132
0.581046
[ "vector" ]
2a9dd29bec48fa9cc3d240ed4adaac9548d52da7
53,795
cpp
C++
DebuggerCore/DebuggerDispatch.cpp
codajs/edge-diagnostics-adaptor
0beea6055435e041a249a30cf9fa97b3699428f5
[ "MIT" ]
611
2015-03-17T15:35:53.000Z
2019-05-06T01:46:03.000Z
DebuggerCore/DebuggerDispatch.cpp
codajs/edge-diagnostics-adaptor
0beea6055435e041a249a30cf9fa97b3699428f5
[ "MIT" ]
52
2015-03-17T19:23:01.000Z
2018-05-25T12:46:45.000Z
DebuggerCore/DebuggerDispatch.cpp
codajs/edge-diagnostics-adaptor
0beea6055435e041a249a30cf9fa97b3699428f5
[ "MIT" ]
52
2015-03-20T02:52:00.000Z
2019-04-16T00:53:52.000Z
// // Copyright (C) Microsoft. All rights reserved. // #include "stdafx.h" #include "DebuggerDispatch.h" #include "ScriptHelpers.h" CDebuggerDispatch::CDebuggerDispatch() : m_dispatchThreadId(::GetCurrentThreadId()), // We are always created on the dispatch thread m_eventHelper(this->GetUnknown()), m_hasHitBreak(false) { } // IF12DebuggerExtension STDMETHODIMP CDebuggerDispatch::Initialize(_In_ HWND hwndDebugPipeHandler, _In_ IDispatchEx* pScriptDispatchEx, _In_ HANDLE hBreakNotificationComplete, _In_ BOOL isDocked, _In_ IUnknown* pDebugApplication) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(hwndDebugPipeHandler != nullptr, E_INVALIDARG); ATLENSURE_RETURN_HR(hBreakNotificationComplete != nullptr, E_INVALIDARG); ATLENSURE_RETURN_HR(pScriptDispatchEx != nullptr, E_INVALIDARG); ATLENSURE_RETURN_HR(pDebugApplication != nullptr, E_INVALIDARG); m_hwndDebugPipeHandler = hwndDebugPipeHandler; m_spScriptDispatch = pScriptDispatchEx; // Create the message queue used for getting the PDM events CComObject<PDMEventMessageQueue>* pMessageQueue; HRESULT hr = CComObject<PDMEventMessageQueue>::CreateInstance(&pMessageQueue); BPT_FAIL_IF_NOT_S_OK(hr); hr = pMessageQueue->Initialize(m_hwndDebugPipeHandler); BPT_FAIL_IF_NOT_S_OK(hr); m_spMessageQueue = pMessageQueue; // Create the source controller CComObject<SourceController>* pSourceController; hr = CComObject<SourceController>::CreateInstance(&pSourceController); BPT_FAIL_IF_NOT_S_OK(hr); hr = pSourceController->Initialize(m_spMessageQueue, m_hwndDebugPipeHandler); BPT_FAIL_IF_NOT_S_OK(hr); m_spSourceController = pSourceController; // Create the thread controller CComObject<ThreadController>* pThreadController; hr = CComObject<ThreadController>::CreateInstance(&pThreadController); BPT_FAIL_IF_NOT_S_OK(hr); hr = pThreadController->Initialize(m_hwndDebugPipeHandler, hBreakNotificationComplete, !!isDocked, m_spMessageQueue, m_spSourceController); BPT_FAIL_IF_NOT_S_OK(hr); m_spThreadController = pThreadController; // Call the helper function so that we also get the main thread id which is needed when hitting a breakpoint SetRemoteDebugApplication(pDebugApplication); return S_OK; } STDMETHODIMP CDebuggerDispatch::Deinitialize() { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); m_spScriptDispatch.Release(); m_spThreadController.Release(); m_spSourceController.Release(); m_spMessageQueue.Release(); return S_OK; } STDMETHODIMP CDebuggerDispatch::OnDebuggerNotification(_In_ const UINT notification, _In_ const UINT_PTR wParam, _In_ const LONG_PTR lParam) { HRESULT hr = S_OK; switch (notification) { case WM_PROCESSDEBUGGERPACKETS: { hr = this->FireQueuedEvents(); } break; case WM_DEBUGGINGENABLED: { // Update the PDM state with the new pointer if (lParam != NULL) { IUnknown* pData = reinterpret_cast<IUnknown*>(lParam); CComQIPtr<IRemoteDebugApplication> spRemoteDebugApplication(pData); if (spRemoteDebugApplication.p != nullptr) { hr = this->SetRemoteDebugApplication(spRemoteDebugApplication); } } bool succeeded = !!wParam; // Notify DebugProvider.ts const UINT argLength = 1; CComVariant params[argLength]; params[0] = succeeded; this->m_eventHelper.Fire_Event(L"debuggingenabled", params, argLength); } break; case WM_DEBUGGINGDISABLED: { // Inform the source controller that debugging is disabled, so // we can unbind breakpoints, if any this->DebuggingDisabled(); // Notify DebugProvider.ts this->m_eventHelper.Fire_Event(L"debuggingdisabled", nullptr, 0); } break; case WM_DOCKEDSTATECHANGED: { // Update the docking state bool isDocked = !!wParam; hr = this->DockedStateChanged(isDocked); } break; case WM_DEBUGAPPLICATIONCREATE: { bool isProfiling = !!wParam; // Notify DebugProvider.ts const UINT argLength = 1; CComVariant params[argLength]; params[0] = isProfiling; this->m_eventHelper.Fire_Event(L"debugapplicationcreate", params, argLength); } break; case WM_WEBWORKERSTARTED: { DWORD workerId = static_cast<DWORD>(wParam); CComBSTR workerLabel; workerLabel.Attach((const BSTR)lParam); // Notify DebugProvider.ts const UINT argLength = 2; CComVariant params[argLength]; params[1] = workerLabel; params[0] = workerId; this->m_eventHelper.Fire_Event(L"webworkerstarted", params, argLength); } break; case WM_WEBWORKERFINISHED: { DWORD workerId = static_cast<DWORD>(wParam); // Notify DebugProvider.ts const UINT argLength = 1; CComVariant params[argLength]; params[0] = workerId; this->m_eventHelper.Fire_Event(L"webworkerfinished", params, argLength); } break; case WM_EVENTBREAKPOINT: { bool isStarting = !!wParam; CString eventType((const BSTR)lParam); hr = this->OnEventBreakpoint(isStarting, eventType); } break; case WM_EVENTLISTENERUPDATED: { bool isListening = !!wParam; hr = this->OnEventListenerUpdated(isListening); } break; case WM_BREAKNOTIFICATIONEVENT: case WM_WAITFORATTACH: // Do nothing for these events since they are handled in the DebugPipeHandler break; default: // Unknown notification hr = E_INVALIDARG; } BPT_FAIL_IF_NOT_S_OK(hr); return hr; } HRESULT CDebuggerDispatch::SetRemoteDebugApplication(_In_ IUnknown* pDebugApplication) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pDebugApplication != nullptr, E_INVALIDARG); // Forward the call onto the thread controller so that it can update its internal state CComQIPtr<IRemoteDebugApplication> spRemoteDebugApp(pDebugApplication); ATLENSURE_RETURN_HR(spRemoteDebugApp.p != nullptr, E_NOINTERFACE); HRESULT hr = m_spSourceController->SetRemoteDebugApplication(spRemoteDebugApp); BPT_FAIL_IF_NOT_S_OK(hr); return m_spThreadController->SetRemoteDebugApplication(spRemoteDebugApp); } HRESULT CDebuggerDispatch::DockedStateChanged(_In_ BOOL isDocked) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); // Tell the thread controller about the dock state change return m_spThreadController->SetDockState(!!isDocked); } HRESULT CDebuggerDispatch::DebuggingDisabled() { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); // This function is called from the DebugEngineSite when profiling has caused debugging to become disabled // Since this caused chakra to delete all of the breakpoint information it had, we need to clear out // our own stored information so that we can re-bind correctly. m_spThreadController->SetEnabledState(false); return S_OK; } HRESULT CDebuggerDispatch::FireQueuedEvents() { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); if (m_spMessageQueue.p != nullptr && m_spThreadController.p != nullptr) { vector<PDMEventType> messages; m_spMessageQueue->PopAll(messages); for (auto& eventType : messages) { switch (eventType) { case PDMEventType::SourceUpdated: { // Source documents have changed, so request the new info, and inform the JavaScript vector<shared_ptr<DocumentInfo>> added; vector<shared_ptr<DocumentInfo>> updated; vector<ULONG> removed; vector<shared_ptr<ReboundBreakpointInfo>> rebound; HRESULT hr = m_spSourceController->RefreshSources(added, updated, removed, rebound); BPT_FAIL_IF_NOT_S_OK(hr); // Added if (!added.empty()) { vector<CComVariant> addedDocuments; for (const auto& node : added) { map<CString, CComVariant> properties; properties[L"docId"] = node->docId; properties[L"parentDocId"] = node->parentId; properties[L"url"] = node->url; properties[L"mimeType"] = node->mimeType; properties[L"length"] = node->textLength; properties[L"isDynamicCode"] = node->isDynamicCode; properties[L"sourceMapUrlFromHeader"] = node->sourceMapUrlFromHeader; properties[L"longDocumentId"] = node->longDocumentId; CComVariant object; hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, properties, object); ATLASSERT(hr == S_OK); // Assert in chk bits so we can tell if this fails. In ret bits, just continue with the next member instead if (hr == S_OK) { addedDocuments.push_back(object); } } this->FireDocumentEvent(L"onAddDocuments", addedDocuments); } // Updated if (!updated.empty()) { vector<CComVariant> updatedDocuments; for (const auto& node : updated) { map<CString, CComVariant> properties; properties[L"docId"] = node->docId; properties[L"url"] = node->url; properties[L"mimeType"] = node->mimeType; properties[L"length"] = node->textLength; CComVariant object; hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, properties, object); ATLASSERT(hr == S_OK); // Assert in chk bits so we can tell if this fails. In ret bits, just continue with the next member instead if (hr == S_OK) { updatedDocuments.push_back(object); } } this->FireDocumentEvent(L"onUpdateDocuments", updatedDocuments); } // Removed if (!removed.empty()) { vector<CComVariant> removedDocuments; for (const auto& docId : removed) { removedDocuments.push_back(CComVariant(docId)); } this->FireDocumentEvent(L"onRemoveDocuments", removedDocuments); } // Rebound breakpoints if (!rebound.empty()) { vector<CComVariant> reboundBreakpoints; for (const auto& node : rebound) { map<CString, CComVariant> properties; properties[L"breakpointId"] = node->breakpointId; properties[L"newDocId"] = node->newDocId; properties[L"start"] = node->start; properties[L"length"] = node->length; properties[L"isBound"] = node->isBound; CComVariant object; hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, properties, object); ATLASSERT(hr == S_OK); // Assert in chk bits so we can tell if this fails. In ret bits, just continue with the next member instead if (hr == S_OK) { reboundBreakpoints.push_back(object); } } this->FireDocumentEvent(L"onResolveBreakpoints", reboundBreakpoints); } } break; case PDMEventType::BreakpointHit: { // A breakpoint was hit, so inform the JavaScript // The JavaScript should also perform evaluation of any conditional so that we know to break or not shared_ptr<BreakEventInfo> spBreakInfo; HRESULT hr = m_spThreadController->GetBreakEventInfo(spBreakInfo); ATLENSURE_RETURN_HR(hr == S_OK || hr == E_NOT_VALID_STATE, hr); // Since we may have already resumed before if (hr == E_NOT_VALID_STATE) { break; } m_hasHitBreak = true; CComVariant breakpointsArray; if (spBreakInfo->breakReason == BREAKREASON_BREAKPOINT) { // Create the breakpoint specific infos vector<CComVariant> allBreakpoints; if (spBreakInfo->breakpoints.empty()) { // If we have no breakpoints registered at the location that the PDM broke into, // we need to insert a dummy breakpoint to make sure that the front end is still notified // of the break. It will end up showing the current callstack, but with limited location info. spBreakInfo->breakpoints.push_back(shared_ptr<BreakpointInfo>(new BreakpointInfo())); } for (const auto& bp : spBreakInfo->breakpoints) { CComVariant breakpointObject; hr = this->CreateScriptBreakpointInfo(*bp, breakpointObject); ATLASSERT(hr == S_OK); // In retail bits we just ignore the failed breakpoint if (hr == S_OK) { allBreakpoints.push_back(breakpointObject); } } hr = ScriptHelpers::CreateJScriptArray(m_spScriptDispatch, allBreakpoints, breakpointsArray); BPT_FAIL_IF_NOT_S_OK(hr); } else { // Null for no breakpoint breakpointsArray.ChangeType(VT_NULL, nullptr); } map<CString, CComVariant> properties; properties[L"firstFrameId"] = spBreakInfo->firstFrameId; properties[L"errorId"] = spBreakInfo->errorId; properties[L"breakReason"] = spBreakInfo->breakReason; properties[L"description"] = spBreakInfo->description; properties[L"isFirstChanceException"] = spBreakInfo->isFirstChanceException; properties[L"isUserUnhandled"] = spBreakInfo->isUserUnhandled; properties[L"breakpoints"] = breakpointsArray; properties[L"systemThreadId"] = spBreakInfo->systemThreadId; properties[L"breakEventType"] = spBreakInfo->breakEventType; CComVariant object; hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, properties, object); BPT_FAIL_IF_NOT_S_OK(hr); const UINT argLength = 1; CComVariant params[argLength] = { object }; bool isRealBreak = false; m_eventHelper.Fire_Event(L"onBreak", params, argLength, [&isRealBreak](const CComVariant *returnValue) { if (!isRealBreak) { isRealBreak = (returnValue->vt == VT_BOOL && returnValue->boolVal == VARIANT_TRUE); } }); // Since non-real breaks get resumed from straight away (example conditional breakpoint with a false condition), // We only inform IE about the break if the break is going to require the user to manually continue. // This should really be done synchronously with the PDM break event, but due to an issue with the pause overlay in IE, // we need to do this only if the break is not resumed, to avoid flashing the pause UI when a break is resumed fast. if (isRealBreak) { m_spThreadController->BeginBreakNotification(); } } break; case PDMEventType::PDMClosed: { // Disconnect HRESULT hr = m_spThreadController->Disconnect(); BPT_FAIL_IF_NOT_S_OK(hr); ::SendMessageW(m_hwndDebugPipeHandler, WM_FORCEDISABLEDYNAMICDEBUGGING, NULL, NULL); m_eventHelper.Fire_Event(L"onPdmClose", nullptr, 0); } break; } } } return S_OK; } HRESULT CDebuggerDispatch::OnEventBreakpoint(_In_ const bool isStarting, _In_ const CString& eventType) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(m_spSourceController.p != nullptr, E_NOT_VALID_STATE); ATLENSURE_RETURN_HR(m_spThreadController.p != nullptr, E_NOT_VALID_STATE); HRESULT hr = S_OK; if (isStarting) { bool isMappedEventType = false; hr = m_spSourceController->GetIsMappedEventType(eventType, isMappedEventType); BPT_FAIL_IF_NOT_S_OK(hr); if (isMappedEventType) { hr = m_spThreadController->SetNextEvent(eventType); BPT_FAIL_IF_NOT_S_OK(hr); hr = m_spThreadController->Pause(); } } else { hr = m_spThreadController->SetNextEvent(L""); } return hr; } // IScriptEventProvider STDMETHODIMP CDebuggerDispatch::addEventListener(_In_ BSTR eventName, _In_ IDispatch* listener) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(listener != nullptr, E_INVALIDARG); return m_eventHelper.addEventListener(eventName, listener); } STDMETHODIMP CDebuggerDispatch::removeEventListener(_In_ BSTR eventName, _In_ IDispatch* listener) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(listener != nullptr, E_INVALIDARG); return m_eventHelper.removeEventListener(eventName, listener); } STDMETHODIMP CDebuggerDispatch::isEventListenerAttached(_In_ BSTR eventName, _In_opt_ IDispatch* listener, _Out_ ULONG* pAttachedCount) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pAttachedCount != nullptr, E_INVALIDARG); return m_eventHelper.isEventListenerAttached(eventName, listener, pAttachedCount); } STDMETHODIMP CDebuggerDispatch::removeAllEventListeners() { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); return m_eventHelper.removeAllEventListeners(); } // IF12DebuggerDispatch STDMETHODIMP CDebuggerDispatch::enable(_Out_ VARIANT_BOOL* pSuccess) { // Called to switch into debug mode by enabling dynamic debugging ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); // Call through to the IE thread to enable debugging LRESULT result = -1; if (m_hwndDebugPipeHandler != nullptr) { result = ::SendMessageW(m_hwndDebugPipeHandler, WM_ENABLEDYNAMICDEBUGGING, NULL, NULL); } (*pSuccess) = (result == 0 ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::disable(_Out_ VARIANT_BOOL* pSuccess) { // Called to switch back into source rundown mode from debug mode ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); // Call through to the IE thread to disable debugging LRESULT result = -1; if (m_hwndDebugPipeHandler != nullptr) { result = ::SendMessageW(m_hwndDebugPipeHandler, WM_DISABLEDYNAMICDEBUGGING, NULL, NULL); } (*pSuccess) = (result == 0 ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::isEnabled(_Out_ VARIANT_BOOL* pIsEnabled) { // Returns true if debugging is enabled or false if we are still in source rundown mode ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pIsEnabled != nullptr, E_INVALIDARG); (*pIsEnabled) = (m_spThreadController->IsEnabled() ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::connect(_In_ BOOL enable, _Out_ LONG* pResult) { try { // Attaches our native code to the PDM as the active debugger ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pResult != nullptr, E_INVALIDARG); HRESULT hr = m_spThreadController->Connect(); // Return the result of the connection attempt switch (hr) { case S_OK: (*pResult) = (LONG)ConnectionResult::Succeeded; m_spThreadController->SetEnabledState(!!enable); break; case E_ALREADY_ATTACHED: (*pResult) = (LONG)ConnectionResult::FailedAlreadyAttached; break; default: (*pResult) = (LONG)ConnectionResult::Failed; break; } } catch (const bad_alloc&) { return E_OUTOFMEMORY; } catch (const CAtlException& err) { return err.m_hr; } return S_OK; } STDMETHODIMP CDebuggerDispatch::disconnect(_Out_ VARIANT_BOOL* pSuccess) { try { // Detaches our debugger from the PDM ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); HRESULT hr = m_spThreadController->Disconnect(); (*pSuccess) = (hr == S_OK ? VARIANT_TRUE : VARIANT_FALSE); } catch (const bad_alloc&) { return E_OUTOFMEMORY; } catch (const CAtlException& err) { return err.m_hr; } return S_OK; } STDMETHODIMP CDebuggerDispatch::shutdown(_Out_ VARIANT_BOOL* pSuccess) { // Cleans up all references and shuts down the message queue ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); // At this point we should already have moved into source rundown mode so now // we disconnect the debugger and clean up HRESULT hr = disconnect(pSuccess); ATLENSURE_RETURN_HR(hr == S_OK && *pSuccess != VARIANT_FALSE, E_FAIL); this->removeAllEventListeners(); m_spThreadController.Release(); m_spSourceController.Release(); m_spMessageQueue.Release(); (*pSuccess) = (hr == S_OK ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::isConnected(_Out_ VARIANT_BOOL* pIsConnected) { // Returns true if we have attached the the PDM ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pIsConnected != nullptr, E_INVALIDARG); (*pIsConnected) = (m_spThreadController->IsConnected() ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::causeBreak(_In_ ULONG causeBreakAction, _In_ ULONG /* workerId */, _Out_ VARIANT_BOOL* pSuccess) { // Causes the PDM to break on the next executed line of script (if there is one) ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); HRESULT hr = S_OK; if (!m_hasHitBreak) // Since the frontend doesn't yet have an concept of break id, we use this flag to determine if they are trying to break before resuming { switch ((CauseBreakAction)causeBreakAction) { case CauseBreakAction::BreakOnAny: // Cause an async break in the debugger when the next line of script executes hr = m_spThreadController->Pause(); break; case CauseBreakAction::BreakOnAnyNewWorkerStarting: hr = m_spThreadController->SetBreakOnNewWorker(true); break; case CauseBreakAction::BreakIntoSpecificWorker: // Not implemented break; case CauseBreakAction::UnsetBreakOnAnyNewWorkerStarting: hr = m_spThreadController->SetBreakOnNewWorker(false); break; default: ATLENSURE_RETURN_HR(false, E_INVALIDARG); break; } } (*pSuccess) = (hr == S_OK ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::resume(_In_ ULONG breakResumeAction, _Out_ VARIANT_BOOL* pSuccess) { // Causes the PDM to continue execution with the specified options ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); HRESULT hr = E_NOT_VALID_STATE; if (m_hasHitBreak) // Since the frontend doesn't yet have an concept of break id, we use this flag to determine if they are trying to resume a previous break { hr = m_spThreadController->Resume((BREAKRESUMEACTION)breakResumeAction); m_hasHitBreak = !(hr == S_OK); } (*pSuccess) = (hr == S_OK ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::addCodeBreakpoint(_In_ ULONG docId, _In_ ULONG start, _In_ BSTR condition, _In_ BOOL isTracepoint, _Out_ VARIANT* pvActualBp) { try { // Adds a breakpoint to the specified document, at the given location. // The return value specifies the breakpoint id that can be later used in a call to removeBreakpoint to identify it. ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pvActualBp != nullptr, E_INVALIDARG); // Give the out parameter a blank value before it is used in this function ::VariantInit(pvActualBp); shared_ptr<BreakpointInfo> spAddedBreakpoint; CComBSTR newCondition(condition); HRESULT hr = m_spSourceController->AddCodeBreakpoint(docId, start, newCondition, !!isTracepoint, spAddedBreakpoint); if (hr == S_OK) { // Create the breakpoint JavaScript object CComVariant bpObject; hr = this->CreateScriptBreakpointInfo(*spAddedBreakpoint, bpObject); BPT_FAIL_IF_NOT_S_OK(hr); hr = bpObject.Detach(pvActualBp); BPT_FAIL_IF_NOT_S_OK(hr); } else { // Failure to add a breakpoint here, so return 'null' to the JavaScript CComVariant nullObject; nullObject.ChangeType(VT_NULL, nullptr); hr = nullObject.Detach(pvActualBp); BPT_FAIL_IF_NOT_S_OK(hr); } } catch (const bad_alloc&) { return E_OUTOFMEMORY; } catch (const CAtlException& err) { return err.m_hr; } return S_OK; } STDMETHODIMP CDebuggerDispatch::addEventBreakpoint(_In_ VARIANT* pvEventTypes, _In_ BOOL isEnabled, _In_ BSTR condition, _In_ BOOL isTracepoint, _Out_ VARIANT* pvActualBp) { try { // Adds a breakpoint to the specified document, at the given location. // The return value specifies the breakpoint id that can be later used in a call to removeBreakpoint to identify it. ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pvActualBp != nullptr, E_INVALIDARG); ATLENSURE_RETURN_HR(pvEventTypes != nullptr && (pvEventTypes->vt == VT_NULL || (pvEventTypes->vt == VT_DISPATCH && pvEventTypes->pdispVal != nullptr)), E_INVALIDARG); // Give the out parameter a blank value before it is used in this function ::VariantInit(pvActualBp); shared_ptr<BreakpointInfo> spAddedBreakpoint; shared_ptr<vector<CComBSTR>> spEventTypes; if (pvEventTypes->vt == VT_DISPATCH) { spEventTypes.reset(new vector<CComBSTR>()); vector<CComVariant> variantEventTypesVector; HRESULT hr = ScriptHelpers::GetVectorFromScriptArray(*pvEventTypes, variantEventTypesVector); BPT_FAIL_IF_NOT_S_OK(hr); for (const auto& item : variantEventTypesVector) { ATLENSURE_RETURN_HR(item.vt == VT_BSTR, E_INVALIDARG); CComBSTR value(item.bstrVal); spEventTypes->push_back(value); } } CComBSTR newCondition(condition); HRESULT hr = m_spSourceController->AddEventBreakpoint(spEventTypes, !!isEnabled, newCondition, !!isTracepoint, spAddedBreakpoint); if (hr == S_OK) { // Create the breakpoint JavaScript object CComVariant bpObject; hr = this->CreateScriptBreakpointInfo(*spAddedBreakpoint, bpObject); BPT_FAIL_IF_NOT_S_OK(hr); hr = bpObject.Detach(pvActualBp); BPT_FAIL_IF_NOT_S_OK(hr); } else { // Failure to add a breakpoint here, so return 'null' to the JavaScript CComVariant nullObject; nullObject.ChangeType(VT_NULL, nullptr); hr = nullObject.Detach(pvActualBp); BPT_FAIL_IF_NOT_S_OK(hr); } } catch (const bad_alloc&) { return E_OUTOFMEMORY; } catch (const CAtlException& err) { return err.m_hr; } return S_OK; } STDMETHODIMP CDebuggerDispatch::addPendingBreakpoint(_In_ BSTR url, _In_ ULONG start, _In_ BSTR condition, _In_ BOOL isEnabled, _In_ BOOL isTracepoint, _Out_ ULONG* pBreakpointId) { HRESULT hr; try { // Adds a pending breakpoint at a given url, which is not bound to the backend. They get bound when a document with that url is added. // Returns id of the new breakpoint added. ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pBreakpointId != nullptr, E_INVALIDARG); ATLASSERT(::SysStringLen(url) > 0); CComBSTR newUrl(url); CComBSTR newCondition(condition); ULONG bpId = 0; hr = m_spSourceController->AddPendingBreakpoint(newUrl, start, newCondition, !!isEnabled, !!isTracepoint, bpId); (*pBreakpointId) = (hr == S_OK) ? bpId : 0; } catch (const bad_alloc&) { return E_OUTOFMEMORY; } catch (const CAtlException& err) { return err.m_hr; } return hr; } STDMETHODIMP CDebuggerDispatch::removeBreakpoint(_In_ ULONG breakpointId, _Out_ VARIANT_BOOL* pSuccess) { // Removes a breakpoint using the speicifed breakpoint id ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); HRESULT hr = m_spSourceController->RemoveBreakpoint(breakpointId); (*pSuccess) = (hr == S_OK ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::updateBreakpoint(_In_ ULONG breakpointId, _In_ BSTR condition, _In_ BOOL isTracepoint, _Out_ VARIANT_BOOL* pSuccess) { // Updates an existing breakpoint to have a different condition or tracepoint value ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); CComBSTR newCondition(condition); HRESULT hr = m_spSourceController->UpdateBreakpoint(breakpointId, newCondition, !!isTracepoint); (*pSuccess) = (hr == S_OK ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::setBreakpointEnabledState(_In_ ULONG breakpointId, _In_ BOOL enable, _Out_ VARIANT_BOOL* pSuccess) { // Toggles the state of an existing a breakpoint ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); HRESULT hr = m_spSourceController->SetBreakpointEnabledState(breakpointId, !!enable); (*pSuccess) = (hr == S_OK ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::getBreakpointIdFromSourceLocation(_In_ ULONG docId, _In_ ULONG start, _Out_ ULONG* pBreakpointId) { // Gets the breakpointId corrisponding to the breakpoint set at the specified document and location, // It will return 0 if there is no existing breakpoint found at that location. ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pBreakpointId != nullptr, E_INVALIDARG); ULONG existingId = 0; HRESULT hr = m_spSourceController->GetBreakpointId(docId, start, existingId); if (hr == S_OK) { // Return the valid breakpoint id (*pBreakpointId) = existingId; } else { // Could not find an existing breakpoint here so return 0 (meaning invalid) (*pBreakpointId) = 0; } return S_OK; } STDMETHODIMP CDebuggerDispatch::getThreadDescription(_Out_ BSTR* pThreadDescription) { // Gets a description of the current thread while at a breakpoint ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pThreadDescription != nullptr, E_INVALIDARG); CComBSTR description; HRESULT hr = m_spThreadController->GetCurrentThreadDescription(description); if (hr == S_OK) { // Copy the text into the out parameter hr = description.CopyTo(pThreadDescription); ATLASSERT(hr == S_OK); hr; } else { // Return an empty string instead instead of a bad HRESULT to avoid throwing an exceptions to the JavaScript (*pThreadDescription) = ::SysAllocString(L""); } return S_OK; } STDMETHODIMP CDebuggerDispatch::getThreads(_Out_ VARIANT* pvThreadDescriptions) { try { // Get the current executing threads (such as webworkers) ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pvThreadDescriptions != nullptr, E_INVALIDARG); vector<CComVariant> descriptions; vector<CComBSTR> spThreadDescriptions; HRESULT hr = m_spThreadController->GetThreadDescriptions(spThreadDescriptions); if (hr != S_OK) { for (const auto& desc : spThreadDescriptions) { descriptions.push_back(CComVariant(desc)); } } else { // Return an empty array to the JavaScript descriptions.clear(); } // Create the VARIANT that represents the array in JavaScript CComVariant descriptionsArray; hr = ScriptHelpers::CreateJScriptArray(m_spScriptDispatch, descriptions, descriptionsArray); BPT_FAIL_IF_NOT_S_OK(hr); // Set it to the out param ::VariantInit(pvThreadDescriptions); hr = descriptionsArray.Detach(pvThreadDescriptions); BPT_FAIL_IF_NOT_S_OK(hr); } catch (const bad_alloc&) { return E_OUTOFMEMORY; } catch (const CAtlException& err) { return err.m_hr; } return S_OK; } STDMETHODIMP CDebuggerDispatch::getFrames(_In_ LONG /* framesNeeded */, _Out_ VARIANT* pvFramesArray) { try { // Get the current callstack when stopped at a breakpoint ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pvFramesArray != nullptr, E_INVALIDARG); vector<CComVariant> currentFrames; vector<shared_ptr<CallFrameInfo>> spFrames; HRESULT hr = m_spThreadController->GetCallFrames(spFrames); if (hr == S_OK) { for (const auto& frame : spFrames) { // Create the script location map<CString, CComVariant> locationMap; locationMap[L"docId"] = frame->sourceLocation.docId; locationMap[L"start"] = frame->sourceLocation.charPosition; locationMap[L"length"] = frame->sourceLocation.contextCount; CComVariant locationObject; hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, locationMap, locationObject); BPT_FAIL_IF_NOT_S_OK(hr); // Create the frame object and add the location map<CString, CComVariant> frameMap; frameMap[L"callFrameId"] = frame->id; frameMap[L"functionName"] = frame->functionName; frameMap[L"isInTryBlock"] = frame->isInTryBlock; frameMap[L"isInternal"] = frame->isInternal; frameMap[L"location"] = locationObject; CComVariant frameObject; hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, frameMap, frameObject); if (hr == S_OK) { currentFrames.push_back(frameObject); } } } else { // Return an empty callstack array to the JavaScript currentFrames.clear(); } // Create the VARIANT that represents the array in JavaScript CComVariant framesArray; hr = ScriptHelpers::CreateJScriptArray(m_spScriptDispatch, currentFrames, framesArray); BPT_FAIL_IF_NOT_S_OK(hr); // Set it to the out param ::VariantInit(pvFramesArray); hr = framesArray.Detach(pvFramesArray); BPT_FAIL_IF_NOT_S_OK(hr); } catch (const bad_alloc&) { return E_OUTOFMEMORY; } catch (const CAtlException& err) { return err.m_hr; } return S_OK; } STDMETHODIMP CDebuggerDispatch::getSourceText(_In_ ULONG docId, _Out_ VARIANT* pvSourceTextResult) { try { // Returns a IGetSourceTextResult for the given document id. // The text should only be requested when this function is called, to prevent caching text if the front end is never going to show it. ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pvSourceTextResult != nullptr, E_INVALIDARG); CComBSTR sourceText; HRESULT hr = m_spSourceController->GetSourceText(docId, sourceText); bool loadFailed = !SUCCEEDED(hr); // Map that array onto an object with additional members map<CString, CComVariant> propertiesMap; propertiesMap[L"loadFailed"] = loadFailed; propertiesMap[L"text"] = loadFailed ? L"" : sourceText; // Create the VARIANT that represents that object in JavaScript CComVariant propertiesObject; hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, propertiesMap, propertiesObject); BPT_FAIL_IF_NOT_S_OK(hr); // Set it to the out param ::VariantInit(pvSourceTextResult); hr = propertiesObject.Detach(pvSourceTextResult); BPT_FAIL_IF_NOT_S_OK(hr); } catch (const bad_alloc&) { return E_OUTOFMEMORY; } catch (const CAtlException& err) { return err.m_hr; } return S_OK; } STDMETHODIMP CDebuggerDispatch::getLocals(_In_ ULONG frameId, _Out_ ULONG* pPropertyId) { try { // Get the local variables associated with a callstack frame when at a breakpoint ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pPropertyId != nullptr, E_INVALIDARG); ULONG propertyId; HRESULT hr = m_spThreadController->GetLocals(frameId, propertyId); if (hr == S_OK) { // Set the valid property id to the out parameter (*pPropertyId) = propertyId; } else { // No property id (*pPropertyId) = 0; } } catch (const bad_alloc&) { return E_OUTOFMEMORY; } catch (const CAtlException& err) { return err.m_hr; } return S_OK; } STDMETHODIMP CDebuggerDispatch::eval(_In_ ULONG frameId, _In_ BSTR evalString, _Out_ VARIANT* pvPropertyInfo) { try { // Evaluate an expression using the current breakpoint context ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(evalString != nullptr, E_INVALIDARG); ATLENSURE_RETURN_HR(pvPropertyInfo != nullptr, E_INVALIDARG); // Give the out parameter a blank value before it is used in this function ::VariantInit(pvPropertyInfo); shared_ptr<PropertyInfo> spPropertyInfo; HRESULT hr = m_spThreadController->Eval(frameId, CComBSTR(evalString), EVAL_RADIX, spPropertyInfo); if (hr == S_OK) { CComVariant propertyInfoObject; hr = this->GetPropertyObjectFromPropertyInfo(spPropertyInfo, propertyInfoObject); BPT_FAIL_IF_NOT_S_OK(hr); hr = propertyInfoObject.Detach(pvPropertyInfo); BPT_FAIL_IF_NOT_S_OK(hr); } else { // No result, so return 'null' to the JavaScript CComVariant nullObject; nullObject.ChangeType(VT_NULL, nullptr); hr = nullObject.Detach(pvPropertyInfo); BPT_FAIL_IF_NOT_S_OK(hr); } } catch (const bad_alloc&) { return E_OUTOFMEMORY; } catch (const CAtlException& err) { return err.m_hr; } return S_OK; } STDMETHODIMP CDebuggerDispatch::getChildProperties(_In_ ULONG propertyId, _In_ ULONG start, _In_ ULONG length, _Out_ VARIANT* pvPropertyInfosObject) { try { // Get the children of a valid variable when at a breakpoint ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pvPropertyInfosObject != nullptr, E_INVALIDARG); vector<CComVariant> properties; bool hasAdditionalChildren = false; vector<shared_ptr<PropertyInfo>> spPropertyInfos; HRESULT hr = m_spThreadController->EnumeratePropertyMembers(propertyId, EVAL_RADIX, spPropertyInfos); if (hr == S_OK && spPropertyInfos.size() < ULONG_MAX && start < (ULONG)spPropertyInfos.size()) { ULONG total = (ULONG)spPropertyInfos.size(); if (length == 0) { // Length 0 means to return all of the properties length = total; } ULONG end = start + length; if (end < total) { hasAdditionalChildren = true; } // Populate the list of properties for (ULONG i = start; i < total && i < end; i++) { CComVariant propertyInfoObject; hr = this->GetPropertyObjectFromPropertyInfo(spPropertyInfos[i], propertyInfoObject); BPT_FAIL_IF_NOT_S_OK(hr); properties.push_back(propertyInfoObject); } } else { // Return an empty array to the JavaScript properties.clear(); } // Create the VARIANT that represents the array in JavaScript CComVariant propertiesArray; hr = ScriptHelpers::CreateJScriptArray(m_spScriptDispatch, properties, propertiesArray); BPT_FAIL_IF_NOT_S_OK(hr); // Map that array onto an object with additional members map<CString, CComVariant> propertiesMap; propertiesMap[L"hasAdditionalChildren"] = hasAdditionalChildren; propertiesMap[L"propInfos"] = propertiesArray; // Create the VARIANT that represents that object in JavaScript CComVariant propertiesObject; hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, propertiesMap, propertiesObject); BPT_FAIL_IF_NOT_S_OK(hr); // Set it to the out param ::VariantInit(pvPropertyInfosObject); hr = propertiesObject.Detach(pvPropertyInfosObject); BPT_FAIL_IF_NOT_S_OK(hr); } catch (const bad_alloc&) { return E_OUTOFMEMORY; } catch (const CAtlException& err) { return err.m_hr; } return S_OK; } STDMETHODIMP CDebuggerDispatch::setPropertyValueAsString(_In_ ULONG propertyId, _In_ BSTR* pValue, _Out_ VARIANT_BOOL* pSuccess) { // Sets the value of a IDebugProperty given by propertyId ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pValue != nullptr, E_INVALIDARG); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); HRESULT hr = m_spThreadController->SetPropertyValueAsString(propertyId, pValue, EVAL_RADIX); (*pSuccess) = (hr == S_OK ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::canSetNextStatement(_In_ ULONG docId, _In_ ULONG position, _Out_ VARIANT_BOOL* pSuccess) { // Tests to see if the PDM can move the instruction pointer to the specified location while at a breakpoint ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); HRESULT hr = m_spThreadController->CanSetNextStatement(docId, position); (*pSuccess) = (hr == S_OK ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::setNextStatement(_In_ ULONG docId, _In_ ULONG position, _Out_ VARIANT_BOOL* pSuccess) { // Causes the PDM to move the instruction pointer to the specified location while at a breakpoint ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); HRESULT hr = m_spThreadController->SetNextStatement(docId, position); if (hr == S_OK) { // StepOver action moves execution from the current IP to the point where is should be next time (as per the user sets it). // We send in ERRORRESUMEACTION_SkipErrorStatement in case this step was during an exception break. In that case we want to ignore the exception // and step directly. hr = m_spThreadController->Resume(BREAKRESUMEACTION_STEP_OVER, ERRORRESUMEACTION_SkipErrorStatement); } (*pSuccess) = (hr == S_OK ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } STDMETHODIMP CDebuggerDispatch::setBreakOnFirstChanceExceptions(_In_ BOOL fValue, _Out_ VARIANT_BOOL* pSuccess) { // Causes the PDM to change its exception settings ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(pSuccess != nullptr, E_INVALIDARG); HRESULT hr = m_spThreadController->SetBreakOnFirstChanceExceptions(!!fValue); (*pSuccess) = (hr == S_OK ? VARIANT_TRUE : VARIANT_FALSE); return S_OK; } // Helper functions HRESULT CDebuggerDispatch::OnEventListenerUpdated(_In_ bool const isListening) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); ATLENSURE_RETURN_HR(m_spSourceController.p != nullptr, E_NOT_VALID_STATE); HRESULT hr = S_OK; if (isListening) { m_spSourceController->RebindAllEventBreakpoints(/*isEventListenerRegistered=*/ true); } else { // Now that the listeners have been removed in the BHO, unbind all the event breakpoints m_spSourceController->UnbindAllEventBreakpoints(/*removeListeners=*/ false); } return hr; } HRESULT CDebuggerDispatch::FireDocumentEvent(_In_ const CString& eventName, _In_ vector<CComVariant>& objects) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); HRESULT hr = S_OK; if (objects.empty()) { return hr; } CComVariant object; hr = ScriptHelpers::CreateJScriptArray(m_spScriptDispatch, objects, object); objects.clear(); BPT_FAIL_IF_NOT_S_OK(hr); const UINT argLength = 1; CComVariant params[argLength] = { object }; m_eventHelper.Fire_Event(eventName, params, argLength); return hr; } HRESULT CDebuggerDispatch::GetPropertyObjectFromPropertyInfo(_In_ const shared_ptr<PropertyInfo>& spPropertyInfo, _Out_ CComVariant& propertyInfoObject) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); // Copy the strings into the map object map<CString, CComVariant> mapNameValuePairs; mapNameValuePairs[L"propertyId"] = spPropertyInfo->propertyId; mapNameValuePairs[L"name"] = spPropertyInfo->name; mapNameValuePairs[L"type"] =spPropertyInfo->type; mapNameValuePairs[L"value"] = spPropertyInfo->value; mapNameValuePairs[L"fullName"] = spPropertyInfo->fullName; mapNameValuePairs[L"expandable"] = spPropertyInfo->isExpandable; mapNameValuePairs[L"readOnly"] = spPropertyInfo->isReadOnly; mapNameValuePairs[L"fake"] = spPropertyInfo->isFake; mapNameValuePairs[L"invalid"] = spPropertyInfo->isInvalid; mapNameValuePairs[L"returnValue"] = spPropertyInfo->isReturnValue; // Create the JavaScript object HRESULT hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, mapNameValuePairs, propertyInfoObject); BPT_FAIL_IF_NOT_S_OK(hr); return S_OK; } HRESULT CDebuggerDispatch::CreateScriptBreakpointInfo(_In_ const BreakpointInfo& breakpoint, _Out_ CComVariant& breakpointObject) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); HRESULT hr = breakpointObject.Clear(); BPT_FAIL_IF_NOT_S_OK(hr); map<CString, CComVariant> bpMap; bpMap[L"breakpointId"] = breakpoint.id; auto sourceLocation = breakpoint.spSourceLocation; if (sourceLocation != nullptr) { map<CString, CComVariant> sourceLocationMap; sourceLocationMap[L"docId"] = sourceLocation->docId; sourceLocationMap[L"start"] = sourceLocation->charPosition; sourceLocationMap[L"length"] = sourceLocation->contextCount; CComVariant sourceLocationObject; hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, sourceLocationMap, sourceLocationObject); BPT_FAIL_IF_NOT_S_OK(hr); bpMap[L"location"] = sourceLocationObject; } auto eventTypes = breakpoint.spEventTypes; if (eventTypes != nullptr) { CComVariant scriptEventTypes; // Convert the vector<CComBSTR> to vector<CComVariant> vector<CComVariant> variantEventTypes; for (const auto& item : *eventTypes) { CComBSTR newItem(item); variantEventTypes.push_back(CComVariant(newItem)); } hr = ScriptHelpers::CreateJScriptArray(m_spScriptDispatch, variantEventTypes, scriptEventTypes); BPT_FAIL_IF_NOT_S_OK(hr); bpMap[L"eventTypes"] = scriptEventTypes; } bpMap[L"condition"] = breakpoint.condition; bpMap[L"isTracepoint"] = breakpoint.isTracepoint; bpMap[L"isEnabled"] = breakpoint.isEnabled; bpMap[L"isBound"] = breakpoint.isBound; hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, bpMap, breakpointObject); BPT_FAIL_IF_NOT_S_OK(hr); return hr; } HRESULT CDebuggerDispatch::CreateSetMutationBreakpointResult(_In_ bool success, _In_ ULONG breakpointId, _In_ CComBSTR& objectName, _Out_ CComVariant& resultObject) { ATLENSURE_RETURN_HR(ThreadHelpers::IsOnDispatchThread(m_dispatchThreadId), E_UNEXPECTED); // Copy the strings into the map object map<CString, CComVariant> resultMap; resultMap[L"success"] = success; resultMap[L"breakpointId"] = breakpointId; resultMap[L"objectName"] = objectName; // Create the JavaScript object HRESULT hr = ScriptHelpers::CreateJScriptObject(m_spScriptDispatch, resultMap, resultObject); BPT_FAIL_IF_NOT_S_OK(hr); return S_OK; }
36.921757
205
0.647012
[ "object", "vector" ]
2a9e68d99252793ea60a102ac50c39efe96cedc2
1,961
hpp
C++
src/texture/core.hpp
IsraelEfraim/cpp-engine
039bcad97d55635a7a8f31d0d80ce59095ebb6cb
[ "MIT" ]
null
null
null
src/texture/core.hpp
IsraelEfraim/cpp-engine
039bcad97d55635a7a8f31d0d80ce59095ebb6cb
[ "MIT" ]
null
null
null
src/texture/core.hpp
IsraelEfraim/cpp-engine
039bcad97d55635a7a8f31d0d80ce59095ebb6cb
[ "MIT" ]
2
2021-03-15T18:51:32.000Z
2021-07-19T23:45:49.000Z
#ifndef CPP_ENGINE_TEXTURE_CORE_HPP #define CPP_ENGINE_TEXTURE_CORE_HPP #include <array> #include <cstdint> #include <SFML/Graphics/Image.hpp> #include "../gl.hpp" namespace engine { struct Texture { std::int32_t m_width; std::int32_t m_height; std::int64_t m_scaled_width; std::int64_t m_scaled_height; std::uint32_t m_id; std::vector<std::uint8_t> m_buffer; std::uint32_t m_vbo; Texture() : m_width(0), m_height(0), m_scaled_width(0), m_scaled_height(0), m_id(0), m_buffer() {} Texture(std::uint32_t id = 0) : m_width(0), m_height(0), m_scaled_width(0), m_scaled_height(0), m_id(id), m_buffer() {} template <class Path> Texture(Path && p, std::uint32_t id = 0) : m_id(id) { auto texture_img = sf::Image(); texture_img.loadFromFile(p); auto [width, height] = texture_img.getSize(); auto ptr = texture_img.getPixelsPtr(); m_width = static_cast<int>(width); m_height = static_cast<int>(height); m_scaled_width = m_width; m_scaled_height = m_height; m_buffer = std::vector(ptr, ptr + width * height * 4); } auto gen_buffer() -> void { glGenTextures(1, &m_vbo); glBindTexture(GL_TEXTURE_2D, m_vbo); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, std::data(m_buffer)); glGenerateMipmap(GL_TEXTURE_2D); } auto bind() -> void { glActiveTexture(GL_TEXTURE0 + m_id); glBindTexture(GL_TEXTURE_2D, m_vbo); } }; } #endif //CPP_ENGINE_TEXTURE_CORE_HPP
24.822785
118
0.64049
[ "vector" ]
2aa9742039bd78613d83c87a2ce7596f24b31c1e
752
hpp
C++
TGEngine/model/FBX_Loader.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/model/FBX_Loader.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/model/FBX_Loader.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../Stdbase.hpp" #include "../pipeline/buffer/VertexBuffer.hpp" #include <fbxsdk.h> #include "../pipeline/buffer/Texturebuffer.hpp" #include "../Error.hpp" #ifdef DEBUG #define FBX_CHECK(sucess) ASSERT_NONE_NULL_DB(sucess, "Failed to load " << name << " with error " << importer->GetStatus().GetErrorString(), TG_ERR_DB_NULLPTR) #else #define FBX_CHECK(sucess) sucess; #endif namespace FBX_Dictionary { extern std::vector<fbxsdk::FbxMesh*> fbx_meshes; extern std::vector<char*> names; extern std::vector<glm::vec4> colors; extern std::vector<Texture> textures; SINCE(0, 0, 3) uint32_t addAll(fbxsdk::FbxNode* mesh); SINCE(0, 0, 3) void addToDraw(VertexBuffer* buffer); }; SINCE(0, 0, 3) uint32_t load(char* name);
24.258065
159
0.722074
[ "mesh", "vector" ]
2ab0602e25f61cb56416e34d18aa5be29c60946f
9,560
cc
C++
auth/cephx/CephxServiceHandler.cc
liucxer/ceph-msg
2e5c18c0c72253b283bfd3d0576033c0b515ce55
[ "Apache-2.0" ]
null
null
null
auth/cephx/CephxServiceHandler.cc
liucxer/ceph-msg
2e5c18c0c72253b283bfd3d0576033c0b515ce55
[ "Apache-2.0" ]
null
null
null
auth/cephx/CephxServiceHandler.cc
liucxer/ceph-msg
2e5c18c0c72253b283bfd3d0576033c0b515ce55
[ "Apache-2.0" ]
null
null
null
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "CephxServiceHandler.h" #include "CephxProtocol.h" #include "CephxKeyServer.h" #include <errno.h> #include <sstream> #include "include/random.h" #include "common/config.h" #include "common/debug.h" #define dout_subsys ceph_subsys_auth #undef dout_prefix #define dout_prefix *_dout << "cephx server " << entity_name << ": " int CephxServiceHandler::start_session( const EntityName& name, size_t connection_secret_required_length, bufferlist *result_bl, AuthCapsInfo *caps, CryptoKey *session_key, std::string *connection_secret) { entity_name = name; uint64_t min = 1; // always non-zero uint64_t max = std::numeric_limits<uint64_t>::max(); server_challenge = ceph::util::generate_random_number<uint64_t>(min, max); ldout(cct, 10) << "start_session server_challenge " << hex << server_challenge << dec << dendl; CephXServerChallenge ch; ch.server_challenge = server_challenge; encode(ch, *result_bl); return 0; } int CephxServiceHandler::handle_request( bufferlist::const_iterator& indata, size_t connection_secret_required_len, bufferlist *result_bl, uint64_t *global_id, AuthCapsInfo *caps, CryptoKey *psession_key, std::string *pconnection_secret) { int ret = 0; struct CephXRequestHeader cephx_header; try { decode(cephx_header, indata); } catch (buffer::error& e) { ldout(cct, 0) << __func__ << " failed to decode CephXRequestHeader: " << e.what() << dendl; return -EPERM; } switch (cephx_header.request_type) { case CEPHX_GET_AUTH_SESSION_KEY: { ldout(cct, 10) << "handle_request get_auth_session_key for " << entity_name << dendl; CephXAuthenticate req; try { decode(req, indata); } catch (buffer::error& e) { ldout(cct, 0) << __func__ << " failed to decode CephXAuthenticate: " << e.what() << dendl; ret = -EPERM; break; } CryptoKey secret; if (!key_server->get_secret(entity_name, secret)) { ldout(cct, 0) << "couldn't find entity name: " << entity_name << dendl; ret = -EPERM; break; } if (!server_challenge) { ret = -EPERM; break; } uint64_t expected_key; std::string error; cephx_calc_client_server_challenge(cct, secret, server_challenge, req.client_challenge, &expected_key, error); if (!error.empty()) { ldout(cct, 0) << " cephx_calc_client_server_challenge error: " << error << dendl; ret = -EPERM; break; } ldout(cct, 20) << " checking key: req.key=" << hex << req.key << " expected_key=" << expected_key << dec << dendl; if (req.key != expected_key) { ldout(cct, 0) << " unexpected key: req.key=" << hex << req.key << " expected_key=" << expected_key << dec << dendl; ret = -EPERM; break; } CryptoKey session_key; CephXSessionAuthInfo info; bool should_enc_ticket = false; EntityAuth eauth; if (! key_server->get_auth(entity_name, eauth)) { ret = -EPERM; break; } CephXServiceTicketInfo old_ticket_info; if (cephx_decode_ticket(cct, key_server, CEPH_ENTITY_TYPE_AUTH, req.old_ticket, old_ticket_info)) { *global_id = old_ticket_info.ticket.global_id; ldout(cct, 10) << "decoded old_ticket with global_id=" << *global_id << dendl; should_enc_ticket = true; } ldout(cct,10) << __func__ << " auth ticket global_id " << *global_id << dendl; info.ticket.init_timestamps(ceph_clock_now(), cct->_conf->auth_mon_ticket_ttl); info.ticket.name = entity_name; info.ticket.global_id = *global_id; info.validity += cct->_conf->auth_mon_ticket_ttl; key_server->generate_secret(session_key); info.session_key = session_key; if (psession_key) { *psession_key = session_key; } info.service_id = CEPH_ENTITY_TYPE_AUTH; if (!key_server->get_service_secret(CEPH_ENTITY_TYPE_AUTH, info.service_secret, info.secret_id)) { ldout(cct, 0) << " could not get service secret for auth subsystem" << dendl; ret = -EIO; break; } vector<CephXSessionAuthInfo> info_vec; info_vec.push_back(info); build_cephx_response_header(cephx_header.request_type, 0, *result_bl); if (!cephx_build_service_ticket_reply( cct, eauth.key, info_vec, should_enc_ticket, old_ticket_info.session_key, *result_bl)) { ret = -EIO; break; } if (!key_server->get_service_caps(entity_name, CEPH_ENTITY_TYPE_MON, *caps)) { ldout(cct, 0) << " could not get mon caps for " << entity_name << dendl; ret = -EACCES; break; } else { char *caps_str = caps->caps.c_str(); if (!caps_str || !caps_str[0]) { ldout(cct,0) << "mon caps null for " << entity_name << dendl; ret = -EACCES; break; } if (req.other_keys) { // nautilus+ client // generate a connection_secret bufferlist cbl; if (pconnection_secret) { pconnection_secret->resize(connection_secret_required_len); if (connection_secret_required_len) { cct->random()->get_bytes(pconnection_secret->data(), connection_secret_required_len); } std::string err; if (encode_encrypt(cct, *pconnection_secret, session_key, cbl, err)) { lderr(cct) << __func__ << " failed to encrypt connection secret, " << err << dendl; ret = -EACCES; break; } } encode(cbl, *result_bl); // provite all of the other tickets at the same time vector<CephXSessionAuthInfo> info_vec; for (uint32_t service_id = 1; service_id <= req.other_keys; service_id <<= 1) { if (req.other_keys & service_id) { ldout(cct, 10) << " adding key for service " << ceph_entity_type_name(service_id) << dendl; CephXSessionAuthInfo svc_info; key_server->build_session_auth_info( service_id, info.ticket, svc_info); svc_info.validity += cct->_conf->auth_service_ticket_ttl; info_vec.push_back(svc_info); } } bufferlist extra; if (!info_vec.empty()) { CryptoKey no_key; cephx_build_service_ticket_reply( cct, session_key, info_vec, false, no_key, extra); } encode(extra, *result_bl); } // caller should try to finish authentication ret = 1; } } break; case CEPHX_GET_PRINCIPAL_SESSION_KEY: { ldout(cct, 10) << "handle_request get_principal_session_key" << dendl; bufferlist tmp_bl; CephXServiceTicketInfo auth_ticket_info; // note: no challenge here. if (!cephx_verify_authorizer( cct, key_server, indata, 0, auth_ticket_info, nullptr, nullptr, &tmp_bl)) { ret = -EPERM; break; } CephXServiceTicketRequest ticket_req; try { decode(ticket_req, indata); } catch (buffer::error& e) { ldout(cct, 0) << __func__ << " failed to decode CephXServiceTicketRequest: " << e.what() << dendl; ret = -EPERM; break; } ldout(cct, 10) << " ticket_req.keys = " << ticket_req.keys << dendl; ret = 0; vector<CephXSessionAuthInfo> info_vec; int found_services = 0; int service_err = 0; for (uint32_t service_id = 1; service_id <= ticket_req.keys; service_id <<= 1) { if (ticket_req.keys & service_id) { ldout(cct, 10) << " adding key for service " << ceph_entity_type_name(service_id) << dendl; CephXSessionAuthInfo info; int r = key_server->build_session_auth_info( service_id, auth_ticket_info.ticket, // parent ticket (client's auth ticket) info); // tolerate missing MGR rotating key for the purposes of upgrades. if (r < 0) { ldout(cct, 10) << " missing key for service " << ceph_entity_type_name(service_id) << dendl; service_err = r; continue; } info.validity += cct->_conf->auth_service_ticket_ttl; info_vec.push_back(info); ++found_services; } } if (!found_services && service_err) { ldout(cct, 10) << __func__ << " did not find any service keys" << dendl; ret = service_err; } CryptoKey no_key; build_cephx_response_header(cephx_header.request_type, ret, *result_bl); cephx_build_service_ticket_reply(cct, auth_ticket_info.session_key, info_vec, false, no_key, *result_bl); } break; case CEPHX_GET_ROTATING_KEY: { ldout(cct, 10) << "handle_request getting rotating secret for " << entity_name << dendl; build_cephx_response_header(cephx_header.request_type, 0, *result_bl); if (!key_server->get_rotating_encrypted(entity_name, *result_bl)) { ret = -EPERM; break; } } break; default: ldout(cct, 10) << "handle_request unknown op " << cephx_header.request_type << dendl; return -EINVAL; } return ret; } void CephxServiceHandler::build_cephx_response_header(int request_type, int status, bufferlist& bl) { struct CephXResponseHeader header; header.request_type = request_type; header.status = status; encode(header, bl); }
29.506173
104
0.646653
[ "vector" ]
2ab5fe0f865c517633e41a34140d58f49abb2593
2,844
cpp
C++
source/drivers/eeprom/eeprom24c02.cpp
lwIoT/lwIoT
07d2a3ba962aef508911e453268427b006c57701
[ "Apache-2.0" ]
1
2019-07-05T21:39:23.000Z
2019-07-05T21:39:23.000Z
source/drivers/eeprom/eeprom24c02.cpp
lwIoT/lwiot-core
07d2a3ba962aef508911e453268427b006c57701
[ "Apache-2.0" ]
null
null
null
source/drivers/eeprom/eeprom24c02.cpp
lwIoT/lwiot-core
07d2a3ba962aef508911e453268427b006c57701
[ "Apache-2.0" ]
null
null
null
/* * 24C02 EEPROM header. * * @author Michel Megens * @email dev@bietje.net */ #include <stdlib.h> #include <stdio.h> #include <lwiot.h> #include <lwiot/types.h> #include <lwiot/error.h> #include <lwiot/io/i2cbus.h> #include <lwiot/io/i2cmessage.h> #include <lwiot/device/eeprom24c02.h> #include <lwiot/scopedlock.h> namespace lwiot { Eeprom24C02::Eeprom24C02(lwiot::I2CBus &bus) : _bus(bus), _lock(false) { } void Eeprom24C02::write(uint8_t addr, uint8_t byte) { uint8_t data[] = {addr, byte}; ScopedLock lock(this->_lock); this->_bus.send(Eeprom24C02::SlaveAddress, data, sizeof(data)); } uint8_t Eeprom24C02::read(uint8_t addr) { I2CMessage rx(1); I2CMessage tx(1); stl::Vector<I2CMessage> msgs; ScopedLock lock(this->_lock); tx.setRepeatedStart(true); tx.write(addr); tx.setAddress(Eeprom24C02::SlaveAddress, false, false); rx.setAddress(Eeprom24C02::SlaveAddress, false, true); msgs.pushback(stl::move(tx)); msgs.pushback(stl::move(rx)); if(!this->_bus.transfer(msgs) || rx.length() == 0UL) { print_dbg("Unable to read byte from 24C02! Msg size: %u\n", rx.available()); return 0; } rx = stl::move(msgs.back()); return rx.at(0); } ssize_t Eeprom24C02::write(uint8_t addr, const void *data, size_t length) { size_t idx; uint8_t address, current; const uint8_t *ptr; current = length < Eeprom24C02::PageSize ? static_cast<uint8_t>(length) : Eeprom24C02::PageSize; length -= current; address = addr; ptr = static_cast<const uint8_t *>(data); idx = 0UL; do { I2CMessage msg(current + 1); msg.write(address); for(auto i = 0UL; i < current; i++) { msg.write(ptr[idx++]); } msg.setAddress(Eeprom24C02::SlaveAddress, false, false); if(!this->_bus.transfer(msg)) { print_dbg("Unable to write bytes to 24C02 chip!\n"); return -EINVALID; } address += current; current = length < Eeprom24C02::PageSize ? static_cast<uint8_t>(length) : Eeprom24C02::PageSize; length -= current; lwiot_sleep(10); } while(current > 0); return length; } ssize_t Eeprom24C02::read(uint8_t addr, void *data, size_t length) { I2CMessage tx(1), rx(length); stl::Vector<I2CMessage> msgs; ScopedLock lock(this->_lock); tx.setRepeatedStart(true); tx.setAddress(Eeprom24C02::SlaveAddress, false, false); tx.write(addr); rx.setAddress(Eeprom24C02::SlaveAddress, false, true); msgs.pushback(stl::move(tx)); msgs.pushback(stl::move(rx)); if(!this->_bus.transfer(msgs) || rx.length() != length) { print_dbg("Failed to read from 24C02. Received length: %lu\n", rx.length()); return -EINVALID; } rx = stl::move(msgs.back()); memcpy(data, rx.data(), rx.length()); return rx.length(); } }
24.517241
100
0.644515
[ "vector" ]
2ab87438dafae429585433b0770f7ce3f78f18ad
4,144
cpp
C++
snippets/cpp/VS_Snippets_Wpf/CompositionTargetRenderingAnimations/CPP/app.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-02-22T09:30:21.000Z
2021-08-02T23:44:31.000Z
snippets/cpp/VS_Snippets_Wpf/CompositionTargetRenderingAnimations/CPP/app.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_Wpf/CompositionTargetRenderingAnimations/CPP/app.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
//app.cpp file #include "FollowExample/FollowExample.h" #include "FrameIndependentFollowExample/FrameIndependentFollowExample.h" #include "ReusableFollowExample/ReusableFollowExample.h" #include "ParticleEffectExamples/ParticleEffectsExample.h" #include "SimpleExample/SimpleExample.h" namespace Microsoft { namespace Samples { namespace PerFrameAnimations { ref class app; ref class SampleViewer; } } } using namespace System; using namespace System::Windows; using namespace System::Windows::Navigation; using namespace System::Windows::Media; using namespace System::Windows::Media::Animation; using namespace System::Windows::Shapes; using namespace System::Windows::Controls; using namespace System::IO; namespace Microsoft { namespace Samples { namespace PerFrameAnimations { public ref class SampleViewer : Page { public: SampleViewer () { TabControl^ tControl = gcnew TabControl(); TabItem^ tItem = gcnew TabItem(); tItem->Header = "Color Changing Example"; Frame^ contentFrame = gcnew Frame(); contentFrame->Content = gcnew SimpleExample(); tItem->Content = contentFrame; tControl->Items->Add(tItem); tItem = gcnew TabItem(); tItem->Header = "Follow Animation"; contentFrame = gcnew Frame(); contentFrame->Content = gcnew FollowExample(); tItem->Content = contentFrame; tControl->Items->Add(tItem); tItem = gcnew TabItem(); tItem->Header = "Frame-Independent Follow Animation"; contentFrame = gcnew Frame(); contentFrame->Content = gcnew FrameIndependentFollowExample(); tItem->Content = contentFrame; tControl->Items->Add(tItem); tItem = gcnew TabItem(); tItem->Header = "Reusable Frame-Independent Follow Animation"; contentFrame = gcnew Frame(); contentFrame->Content = gcnew ReusableFollowExample(); tItem->Content = contentFrame; tControl->Items->Add(tItem); tItem = gcnew TabItem(); tItem->Header = "Particle Effect Examples"; contentFrame = gcnew Frame(); contentFrame->Content = gcnew ParticleEffectExamples(); tItem->Content = contentFrame; tControl->Items->Add(tItem); this->Content = tControl; this->Title = "Per-Frame Animation Sample"; }; }; public ref class app : Application { public: app () { AppDomain::CurrentDomain->UnhandledException += gcnew System::UnhandledExceptionEventHandler(this, &app::currentDomain_UnhandledException); }; protected: virtual void OnStartup (StartupEventArgs^ e) override { Window^ w = gcnew Window(); w->Content = gcnew SampleViewer(); w->Show(); Application::OnStartup(e); }; private: void currentDomain_UnhandledException (System::Object^ sender, System::UnhandledExceptionEventArgs^ args) { MessageBox::Show("Unhandled exception: " + args->ExceptionObject->ToString()); System::IO::StreamWriter^ s = gcnew System::IO::StreamWriter("error.txt"); s->Write(args->ExceptionObject->ToString()); s->Flush(); s->Close(); }; }; private ref class EntryClass sealed { public: [System::STAThread()] static void Main () { PerFrameAnimations::app^ app = gcnew PerFrameAnimations::app(); app->Run(); }; }; } } } //Entry Point: [System::STAThreadAttribute()] void main () { return Microsoft::Samples::PerFrameAnimations::EntryClass::Main(); }
33.419355
154
0.570463
[ "object" ]
2ab8b9bc74ba0bdb1c3558dffb3bcd71463e13e3
44,192
cpp
C++
Engine/source/T3D/aiPlayer.cpp
Torque3D-Games-Demos/CubistMT
67348a4c2f907b43da8b12d14a1046017480450b
[ "Unlicense" ]
6
2015-06-01T15:44:43.000Z
2021-01-07T06:50:21.000Z
Engine/source/T3D/aiPlayer.cpp
joticarroll/Torque3D
67348a4c2f907b43da8b12d14a1046017480450b
[ "Unlicense" ]
null
null
null
Engine/source/T3D/aiPlayer.cpp
joticarroll/Torque3D
67348a4c2f907b43da8b12d14a1046017480450b
[ "Unlicense" ]
null
null
null
//----------------------------------------------------------------------------- // 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 "platform/platform.h" #include "T3D/aiPlayer.h" #include "console/consoleInternal.h" #include "math/mMatrix.h" #include "T3D/gameBase/moveManager.h" #include "console/engineAPI.h" // start jc #include "terrain/terrData.h" //end jc // start jc #include "core/stream/bitStream.h" /* // AIPlayerData datablock functions IMPLEMENT_CO_DATABLOCK_V1(AIPlayerData); AIPlayerData::AIPlayerData() { // maxTurnRate = M_2PI_F; // default to 1 full circle per second } void AIPlayerData::initPersistFields() { Parent::initPersistFields(); // addField("maxTurnRate", TypeF32, Offset(maxTurnRate, AIPlayerData)); } void AIPlayerData::packData(BitStream* stream) { Parent::packData(stream); // stream->write(maxTurnRate); } void AIPlayerData::unpackData(BitStream* stream) { Parent::unpackData(stream); // stream->read(&maxTurnRate); } */ // end jc IMPLEMENT_CO_NETOBJECT_V1(AIPlayer); ConsoleDocClass( AIPlayer, "@brief A Player object not controlled by conventional input, but by an AI engine.\n\n" "The AIPlayer provides a Player object that may be controlled from script. You control " "where the player moves and how fast. You may also set where the AIPlayer is aiming at " "-- either a location or another game object.\n\n" "The AIPlayer class does not have a datablock of its own. It makes use of the PlayerData " "datablock to define how it looks, etc. As the AIPlayer is an extension of the Player class " "it can mount objects and fire weapons, or mount vehicles and drive them.\n\n" "While the PlayerData datablock is used, there are a number of additional callbacks that are " "implemented by AIPlayer on the datablock. These are listed here:\n\n" "void onReachDestination(AIPlayer obj) \n" "Called when the player has reached its set destination using the setMoveDestination() method. " "The actual point at which this callback is called is when the AIPlayer is within the mMoveTolerance " "of the defined destination.\n\n" "void onMoveStuck(AIPlayer obj) \n" "While in motion, if an AIPlayer has moved less than moveStuckTolerance within a single tick, this " "callback is called. From here you could choose an alternate destination to get the AIPlayer moving " "again.\n\n" "void onTargetEnterLOS(AIPlayer obj) \n" "When an object is being aimed at (following a call to setAimObject()) and the targeted object enters " "the AIPlayer's line of sight, this callback is called. The LOS test is a ray from the AIPlayer's eye " "position to the center of the target's bounding box. The LOS ray test only checks against interiors, " "statis shapes, and terrain.\n\n" "void onTargetExitLOS(AIPlayer obj) \n" "When an object is being aimed at (following a call to setAimObject()) and the targeted object leaves " "the AIPlayer's line of sight, this callback is called. The LOS test is a ray from the AIPlayer's eye " "position to the center of the target's bounding box. The LOS ray test only checks against interiors, " "statis shapes, and terrain.\n\n" "@tsexample\n" "// Create the demo player object\n" "%player = new AiPlayer()\n" "{\n" " dataBlock = DemoPlayer;\n" " path = \"\";\n" "};\n" "@endtsexample\n\n" "@see Player for a list of all inherited functions, variables, and base description\n" "@ingroup AI\n" "@ingroup gameObjects\n"); /** * Constructor */ AIPlayer::AIPlayer() { mMoveDestination.set( 0.0f, 0.0f, 0.0f ); // start jc - moved to player for variable motion. // mMoveSpeed = 1.0f; // end jc mMoveTolerance = 0.25f; mMoveStuckTolerance = 0.01f; mMoveStuckTestDelay = 30; mMoveStuckTestCountdown = 0; mMoveSlowdown = true; mMoveState = ModeStop; mAimObject = 0; mAimLocationSet = false; mTargetInLOS = false; mAimOffset = Point3F(0.0f, 0.0f, 0.0f); mIsAiControlled = true; // start jc mDataBlock = 0; // end jc // start ds //Added by Brendan Ledwich 2005-11-9 // mInterpolator = new BezierNodeInterpolator(); mAvoidPoint.set(0,0,0); mWidth = -1; mTurnDirection = 0; // mMaxTurnAngle = 0.2; mFollowObject = NULL; mFollowNodeIndex = -1; // mFollowSlotIndex = 0; mTurnRateMod = 1; //end ds } /** * Destructor */ AIPlayer::~AIPlayer() { // start ds // delete mInterpolator; // end ds } void AIPlayer::initPersistFields() { addGroup( "AI" ); addField( "moveTolerance", TypeF32, Offset( mMoveTolerance, AIPlayer ), "@brief Distance from destination before stopping.\n\n" "When the AIPlayer is moving to a given destination it will move to within " "this distance of the destination and then stop. By providing this tolerance " "it helps the AIPlayer from never reaching its destination due to minor obstacles, " "rounding errors on its position calculation, etc. By default it is set to 0.25.\n"); addField( "moveStuckTolerance", TypeF32, Offset( mMoveStuckTolerance, AIPlayer ), "@brief Distance tolerance on stuck check.\n\n" "When the AIPlayer is moving to a given destination, if it ever moves less than " "this tolerance during a single tick, the AIPlayer is considered stuck. At this point " "the onMoveStuck() callback is called on the datablock.\n"); addField( "moveStuckTestDelay", TypeS32, Offset( mMoveStuckTestDelay, AIPlayer ), "@brief The number of ticks to wait before testing if the AIPlayer is stuck.\n\n" "When the AIPlayer is asked to move, this property is the number of ticks to wait " "before the AIPlayer starts to check if it is stuck. This delay allows the AIPlayer " "to accelerate to full speed without its initial slow start being considered as stuck.\n" "@note Set to zero to have the stuck test start immediately.\n"); endGroup( "AI" ); Parent::initPersistFields(); } bool AIPlayer::onAdd() { if (!Parent::onAdd()) return false; // Use the eye as the current position (see getAIMove) MatrixF eye; getEyeTransform(&eye); mLastLocation = eye.getPosition(); return true; } // start jc - moved to player for variable motion. /** * Sets the speed at which this AI moves * * @param speed Speed to move, default player was 10 */ /* void AIPlayer::setMoveSpeed( F32 speed ) { mMoveSpeed = getMax(0.0f, getMin( 1.0f, speed )); } */ // end jc /** * Stops movement for this AI */ void AIPlayer::stopMove() { mMoveState = ModeStop; } /** * Sets how far away from the move location is considered * "on target" * * @param tolerance Movement tolerance for error */ void AIPlayer::setMoveTolerance( const F32 tolerance ) { mMoveTolerance = getMax( 0.1f, tolerance ); } /** * Sets the location for the bot to run to * * @param location Point to run to */ void AIPlayer::setMoveDestination( const Point3F &location, bool slowdown ) { // start ds /* mMoveDestination = location; */ clearFollowObject(); // Use the eye as the current position. // MatrixF eye; // getEyeTransform(&eye); // Point3F points[1]; /* points[0].set(eye.getPosition()); eye.getColumn(1,&points[1]); // points[1] *= 5; points[1] *= 2.0f/mDataBlock->maxTurnRate; points[1] += points[0]; points[2].set(location); mInterpolator->submitPoints(points,3); //Con::printf("going from (%f,%f,%f) to (%f,%f,%f)",points[0].x,points[0].y,points[0].z,points[1].x,points[1].y,points[1].z); //Con::printf("point 0 is (%f,%f,%f)",points[0].x,points[0].y,points[0].z); //Con::printf("point 1 is (%f,%f,%f)",points[1].x,points[1].y,points[1].z); //Con::printf("point 2 is (%f,%f,%f)",points[2].x,points[2].y,points[2].z); */ /* points[1].set(location); mInterpolator->submitPoints(points,2); */ // clearFollowObject(); mMoveDestination = location; /* points[0].set(location); mInterpolator->submitPoints(points,1); */ // end ds mMoveState = ModeMove; mMoveSlowdown = slowdown; mMoveStuckTestCountdown = mMoveStuckTestDelay; } // start ds /** * Sets the location for the bot to run to * * @param location Point to run to * @param approachVector direction to run to location from */ void AIPlayer::setMoveDestination( const Point3F &location, const Point3F &approachVector, bool slowdown ) { setMoveDestination(location, slowdown); /* // Use the eye as the current position. clearFollowObject(); MatrixF eye; getEyeTransform(&eye); Point3F points[4]; points[0].set(eye.getPosition()); eye.getColumn(1,&points[1]); // points[1] *= 50; // points[1] *= 100; // points[1] *= 10 * mDataBlock->AITurnSpeed; // points[1] *= 10 * mDataBlock->maxTurnRate; points[1] *= 2.0f/mDataBlock->maxTurnRate; // points[1] *= (1.0f - (mDataBlock->maxTurnRate*mTurnRateMod)); // todo: fix for diffent move speeds // points[1] *= (mDataBlock->maxForwardSpeed*100) * mMoveSpeed; points[1] += points[0]; // points[2].set(location-(approachVector * (1.0f - (mDataBlock->maxTurnRate*mTurnRateMod)))); // points[2].set(location-(approachVector * ((mDataBlock->maxForwardSpeed*100) * mMoveSpeed))); if(approachVector.isZero()) { points[2].set(location); mInterpolator->submitPoints(points,3); } else { // points[2].set(location-(approachVector*100)); points[2].set(location-(approachVector*(2.0f/mDataBlock->maxTurnRate))); points[3].set(location); //Con::printf("going from (%f,%f,%f) to (%f,%f,%f)",points[0].x,points[0].y,points[0].z,points[3].x,points[3].y,points[3].z); //Con::printf("point 0 is (%f,%f,%f)",points[0].x,points[0].y,points[0].z); //Con::printf("point 1 is (%f,%f,%f)",points[1].x,points[1].y,points[1].z); //Con::printf("point 2 is (%f,%f,%f)",points[2].x,points[2].y,points[2].z); //Con::printf("point 3 is (%f,%f,%f)",points[3].x,points[3].y,points[3].z); mInterpolator->submitPoints(points,4); } // points[1].set(location); // mInterpolator->submitPoints(points,2); //mMoveDestination = location; mMoveState = ModeMove; mMoveSlowdown = slowdown; */ } // end ds /** * Sets the object the bot is targeting * * @param targetObject The object to target */ void AIPlayer::setAimObject( GameBase *targetObject ) { mAimObject = targetObject; mTargetInLOS = false; mAimOffset = Point3F(0.0f, 0.0f, 0.0f); } // start ds void AIPlayer::setFollowObject( ShapeBase *targetObject, bool slowdown ) { mFollowObject = targetObject; mFollowNodeIndex = -1; mMoveState = ModeMove; mMoveSlowdown = slowdown; mMoveStuckTestCountdown = mMoveStuckTestDelay; } void AIPlayer::setFollowObjectNode( ShapeBase *targetObject, S32 nodeIndex, bool slowdown ) { mFollowObject = targetObject; mFollowNodeIndex = nodeIndex; // mFollowSlotIndex = slotIndex; mMoveState = ModeMove; mMoveSlowdown = slowdown; mMoveStuckTestCountdown = mMoveStuckTestDelay; } void AIPlayer::clearFollowObject( ) { mFollowObject = NULL; mFollowNodeIndex = -1; } // end ds /** * Sets the object the bot is targeting and an offset to add to target location * * @param targetObject The object to target * @param offset The offest from the target location to aim at */ void AIPlayer::setAimObject( GameBase *targetObject, Point3F offset ) { mAimObject = targetObject; mTargetInLOS = false; mAimOffset = offset; } /** * Sets the location for the bot to aim at * * @param location Point to aim at */ void AIPlayer::setAimLocation( const Point3F &location ) { mAimObject = 0; mAimLocationSet = true; mAimLocation = location; mAimOffset = Point3F(0.0f, 0.0f, 0.0f); } /** * Clears the aim location and sets it to the bot's * current destination so he looks where he's going */ void AIPlayer::clearAim() { mAimObject = 0; mAimLocationSet = false; mAimOffset = Point3F(0.0f, 0.0f, 0.0f); } // start ds /** * This method recalculates the move vector based on planned path and world influences */ void AIPlayer::updateMoveDestination(const Point3F &location, const Point3F &forwardVector, const bool is3D) { /* Point3F dest = getMoveDestination(); Point3F moveVec = dest-location; moveVec.z = 0; //RayInfo rInfo; if (mTurnDirection != 0 && mDot(moveVec, mAvoidPoint-location) <=0) { // we were avoiding something, but we've past it mTurnDirection = 0; } bool destSet = false; disableCollision(); if (mFollowObject) mFollowObject->disableCollision(); // calculate search length F32 searchLen = moveVec.len(); F32 velLen = (mVelocity.len()) / 4 + 1.5; if (searchLen > velLen) searchLen = velLen; //find the closest object to avoid Collision cInfo; // todo: do we need this is it worth it if (findClosestObjectInFront(searchLen, &cInfo)) { if(mFlying && static_cast<TerrainBlock*>(cInfo.object)) { Point3F pointToDest = dest - cInfo.point; // pointToDest.z = 0; Point3F oldPointToDest = dest - mAvoidPoint; // oldPointToDest.z = 0; mAvoidPoint = cInfo.point; mTurnDirection = 0.0f; Point3F pointVec = cInfo.point - getBoxCenter(); // pointVec.z = 0; F32 urgency = 1.0f; // mMoveDestination.set(location+rotateVec(forwardVector*20,mDataBlock->AITurnSpeed*urgency,1)); mMoveDestination.set(location+rotateVec(forwardVector*20,mDataBlock->maxTurnRate*urgency,1)); destSet = true; } else { Point3F pointToDest = dest - cInfo.point; pointToDest.z = 0; Point3F oldPointToDest = dest - mAvoidPoint; oldPointToDest.z = 0; if (mTurnDirection == 0 || (dest - cInfo.point).lenSquared() < (dest - mAvoidPoint).lenSquared()) { mAvoidPoint = cInfo.point; if (mTurnDirection == 0) { Point3F dir(cInfo.object->getBoxCenter() - location); F32 temp = dir.x; dir.x = -dir.y; dir.y = temp; if (mDot(forwardVector,dir) > 0) { //left mTurnDirection = 1; } else { //right mTurnDirection = -1; } } } Point3F pointVec = cInfo.point - getBoxCenter(); pointVec.z = 0; // F32 pointLenSquared = pointVec.lenSquared(); F32 urgency = 1.0f; // if (pointLenSquared > 0) // { // pointVec.z = 0; // // dot direction to point then divide by length // // lenSquared normalises the point vector and divides at same time // urgency = getMin(getMax(mDot(pointVec,forwardVector)/pointLenSquared,0.05f), 1.0f); // } // mMoveDestination.set(location+rotateVec(forwardVector*20,mTurnDirection*mDataBlock->AITurnSpeed*urgency,3)); mMoveDestination.set(location+rotateVec(forwardVector*20,mTurnDirection*mDataBlock->maxTurnRate*urgency,3)); destSet = true; } } enableCollision(); if (mFollowObject) mFollowObject->enableCollision(); if (!destSet) { */ if (mFollowObject) { if(mFollowNodeIndex != -1) { MatrixF mat; mFollowObject->getNodeWorldTransform(mFollowNodeIndex, &mat); mMoveDestination = mat.getPosition(); } else mMoveDestination = mFollowObject->getPosition(); /* } else { //Con::printf("getWayPoint((%f,%f,%f),(%f,%f,%f),%f)",location.x,location.y,location.z,v2.x,v2.y,v2.z,mMoveSpeed); //Con::printf("prediction scale = %f",mVelocity.len()/8+0.5); // mMoveDestination.set(((mInterpolator)->getWaypoint(location, forwardVector, mVelocity.len()/8+0.5))); //Con::printf(" = (%f,%f,%f)",mMoveDestination.x,mMoveDestination.y,mMoveDestination.z); } mMoveDestination -= mVelocity*0.05f; //get angle of vec around z axis F32 angle = -getVectorAngle(forwardVector, mMoveDestination-location,3); F32 maxTurnRate = mDataBlock->maxTurnRate*0.01; // if we're avoiding an object - and turning away - turn back towards if (angle < -0.01f && mTurnDirection < 0.0f) { // angle = mDataBlock->AITurnSpeed; angle = -maxTurnRate; mMoveDestination.set(location+(rotateVec(forwardVector,angle,3) * 20.0f)); } else if (angle > 0.01f && mTurnDirection > 0.0f) { // angle = mDataBlock->AITurnSpeed; angle = maxTurnRate; mMoveDestination.set(location+(rotateVec(forwardVector,angle,3) * 20.0f)); } //else if (angle > mDataBlock->AITurnSpeed || angle < -mDataBlock->AITurnSpeed) else if (angle > maxTurnRate || angle < -maxTurnRate) { //Con::printf("angle=%f",angle); // cap to approximately 5.7 degrees movement // angle = (angle>0)?mDataBlock->AITurnSpeed:-mDataBlock->AITurnSpeed; angle = (angle>0)?maxTurnRate:-maxTurnRate; mMoveDestination.set(location+(rotateVec(forwardVector,angle,3) * 20.0f)); //Con::printf("new dest=(%f,%f,%f)",mMoveDestination.x,mMoveDestination.y,mMoveDestination.z); } //get angle of vec around z axis if (is3D) { Point3F xyVec(mMoveDestination.x-location.x,mMoveDestination.y-location.y,0.0); F32 xyDist = xyVec.len(); if (xyDist > 0.0) { F32 ratio = (mMoveDestination.z-location.z)/xyDist; if (ratio > 0.5f || ratio < -0.5f) { Point3F save = mMoveDestination; // F32 originalLength = (mMoveDestination-location).len(); xyVec.z = (mMoveDestination.z > location.z )?xyDist:-xyDist; //xyVec *= originalLength/xyDist; mMoveDestination += xyVec; } } } */ } } // end ds /** * This method calculates the moves for the AI player * * @param movePtr Pointer to move the move list into */ bool AIPlayer::getAIMove(Move *movePtr) { *movePtr = NullMove; // Use the eye as the current position. MatrixF eye; getEyeTransform(&eye); Point3F location = eye.getPosition(); Point3F rotation = getRotation(); // start ds VectorF v2; eye.getColumn(1,&v2); bool is3D = mFlying || mSwimming; if (mWidth < 0.0) //un-initialised { mWidth = getObjBox().maxExtents.x - getObjBox().minExtents.x; mWidth = mWidth * 2.0f; } VectorF crosseyed(-v2.y,v2.x,0.0); crosseyed*= mWidth; // end ds // Orient towards the aim point, aim object, or towards // our destination. if (mAimObject || mAimLocationSet || mMoveState != ModeStop) { // start ds updateMoveDestination(getBoxCenter(), v2, is3D); // end ds // Update the aim position if we're aiming for an object if (mAimObject) mAimLocation = mAimObject->getPosition() + mAimOffset; else if (!mAimLocationSet) mAimLocation = mMoveDestination; F32 xDiff = mAimLocation.x - location.x; F32 yDiff = mAimLocation.y - location.y; // start ds /* if (!mIsZero(xDiff) || !mIsZero(yDiff)) { */ F32 zDiff = mAimLocation.z - location.z; if (!mIsZero(xDiff) || !mIsZero(yDiff) || (is3D && !mIsZero(zDiff) )) { // end ds // First do Yaw // use the cur yaw between -Pi and Pi F32 curYaw = rotation.z; while (curYaw > M_2PI_F) curYaw -= M_2PI_F; while (curYaw < -M_2PI_F) curYaw += M_2PI_F; // find the yaw offset F32 newYaw = mAtan2( xDiff, yDiff ); F32 yawDiff = newYaw - curYaw; // make it between 0 and 2PI if( yawDiff < 0.0f ) yawDiff += M_2PI_F; else if( yawDiff >= M_2PI_F ) yawDiff -= M_2PI_F; // now make sure we take the short way around the circle if( yawDiff >= M_PI_F ) yawDiff -= M_2PI_F; else if( yawDiff < -M_PI_F ) yawDiff += M_2PI_F; // start jc // todo: do we need this anymore // don't look too fast // if (yawDiff < 0.01 && yawDiff > -0.01) // if (yawDiff < 0.0001 && yawDiff > -0.0001) if (yawDiff < 0.001 && yawDiff > -0.001) { if (mMoveState == ModeStop) { throwCallback("onReachDestination"); } } // end jc movePtr->yaw = yawDiff; // start jc - Dan&rsquo;s mods (turning inertia) -> // movePtr->yaw *= mDataBlock->AITurnSpeed; // end jc - Dan&rsquo;s mods (turning inertia) // start jc // control the rotation of the AIPlayer // get the maximum amount we can yaw this tick F32 maxTurnRate = mDataBlock->maxTurnRate * TickSec; // limit the yaw if it exceeds the maxYaw if(mFabs(yawDiff) > maxTurnRate) movePtr->yaw = maxTurnRate * mSign(yawDiff); else movePtr->yaw = yawDiff; // end jc // Next do pitch. // start ds /* if (!mAimObject && !mAimLocationSet) { */ Point3F headRotation = getHeadRotation(); if (!mAimObject && !mAimLocationSet && !is3D) { // end ds // Level out if were just looking at our next way point. movePtr->pitch = -headRotation.x; // start jc - Dan&rsquo;s mods (turning inertia) -> // movePtr->pitch *= mDataBlock->AITurnSpeed; // movePtr->pitch *= mDataBlock->AITurnSpeed; // end jc - Dan&rsquo;s mods (turning inertia) } else { // This should be adjusted to run from the // eye point to the object's center position. Though this // works well enough for now. // start ds /* F32 vertDist = mAimLocation.z - location.z; F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff); F32 newPitch = mAtan2( horzDist, vertDist ) - ( M_PI_F / 2.0f ); */ // F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff); // F32 newPitch = mAtan2( horzDist, zDiff ) - ( M_PI_F / 2.0f ); // First do Yaw // use the cur yaw between -Pi and Pi F32 curPitch = headRotation.x; // while (curPitch > M_2PI_F) // curPitch -= M_2PI_F; // while (curPitch < -M_2PI_F) // curPitch += M_2PI_F; // find the yaw offset //F32 newPitch = mAtan2( xDiff, yDiff ); F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff); F32 newPitch = mAtan2( horzDist, zDiff ) - ( M_PI_F / 2.0f ); F32 pitchDiff = newPitch - curPitch; // F32 pitchDiff = newPitch - headRotation.x; // make it between 0 and 2PI if( pitchDiff < 0.0f ) pitchDiff += M_2PI_F; else if( pitchDiff >= M_2PI_F ) pitchDiff -= M_2PI_F; // now make sure we take the short way around the circle if( pitchDiff >= M_PI_F ) pitchDiff -= M_2PI_F; else if( pitchDiff < -M_PI_F ) pitchDiff += M_2PI_F; // end ds // start jc /* if (mFabs(newPitch) > 0.001f) { Point3F headRotation = getHeadRotation(); movePtr->pitch = newPitch - headRotation.x; } */ if (mFabs(pitchDiff) > 0.001f) { // if(!is3D) // { // if (mFabs(newPitch) > 0.01f) { // Point3F headRotation = getHeadRotation(); movePtr->pitch = pitchDiff; // } // else // { // movePtr->pitch = pitchDiff; /* // get the maximum amount we can yaw this tick F32 maxPitch = mDataBlock->maxTurnRate * TickSec; // limit the yaw if it exceeds the maxYaw if(mFabs(pitchDiff) > maxPitch) movePtr->pitch = (maxPitch * mSign(pitchDiff)); else movePtr->pitch = pitchDiff; */ // } } // never move more than we are aloud if(mFabs(movePtr->pitch) > maxTurnRate) movePtr->pitch = maxTurnRate * mSign(movePtr->pitch); // end jc } // start jc - todo fix max turn speed for pitch /* // control the rotation of the AIPlayer // get the maximum amount we can yaw this tick F32 maxPitch = mDataBlock->maxTurnRate * TickSec; // limit the yaw if it exceeds the maxYaw if(mFabs(pitchDiff) > maxPitch) movePtr->pitch = maxPitch * mSign(pitchDiff); else movePtr->pitch = pitchDiff; */ // end jc } } // start ds // else else if (!is3D || mMoveState == ModeStop) { // end ds // Level out if we're not doing anything else Point3F headRotation = getHeadRotation(); movePtr->pitch = -headRotation.x; } // Move towards the destination if (mMoveState != ModeStop) { F32 xDiff = mMoveDestination.x - location.x; F32 yDiff = mMoveDestination.y - location.y; //start ds /* // Check if we should mMove, or if we are 'close enough' if (mFabs(xDiff) < mMoveTolerance && mFabs(yDiff) < mMoveTolerance) { */ F32 zDiff = (is3D)?mMoveDestination.z - location.z:0; const Point3F finish = (mFollowObject) ? (mFollowObject->getPosition()) : mMoveDestination; // const Point3F * finish = (mFollowObject)?&(mFollowObject->getPosition()):mInterpolator->getPoint(mInterpolator->getNumPoints()-1); F32 xFinDiff = finish.x - location.x; F32 yFinDiff = finish.y - location.y; F32 zFinDiff = (is3D)?finish.z - location.z:0; // Check if we should mMove, or if we are 'close enough' if (mFabs(xFinDiff) < mMoveTolerance && mFabs(yFinDiff) < mMoveTolerance && (!is3D || mFabs(zFinDiff) < mMoveTolerance)) { //end ds mMoveState = ModeStop; throwCallback("onReachDestination"); } else { // Build move direction in world space // start ds /* if (mIsZero(xDiff)) movePtr->y = (location.y > mMoveDestination.y) ? -1.0f : 1.0f; else if (mIsZero(yDiff)) movePtr->x = (location.x > mMoveDestination.x) ? -1.0f : 1.0f; else if (mFabs(xDiff) > mFabs(yDiff)) { F32 value = mFabs(yDiff / xDiff); movePtr->y = (location.y > mMoveDestination.y) ? -value : value; movePtr->x = (location.x > mMoveDestination.x) ? -1.0f : 1.0f; } else { F32 value = mFabs(xDiff / yDiff); movePtr->x = (location.x > mMoveDestination.x) ? -value : value; movePtr->y = (location.y > mMoveDestination.y) ? -1.0f : 1.0f; } */ if (mIsZero(xDiff) && mIsZero(zDiff)) { movePtr->y = (location.y > mMoveDestination.y)? -1 : 1; } else if (mIsZero(yDiff) && mIsZero(zDiff)) { movePtr->x = (location.x > mMoveDestination.x)? -1 : 1; } else if (mIsZero(xDiff) && mIsZero(yDiff)&&is3D) { movePtr->z = (location.z > mMoveDestination.z)? -1 : 1; } else { F32 total = mSqrt(xDiff*xDiff+yDiff*yDiff+zDiff*zDiff); movePtr->x = xDiff/total; movePtr->y = yDiff/total; movePtr->z = zDiff/total; } // end ds // Rotate the move into object space (this really only needs // a 2D matrix) Point3F newMove; MatrixF moveMatrix; // start ds /* moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw))); moveMatrix.mulV( Point3F( movePtr->x, movePtr->y, 0.0f ), &newMove ); movePtr->x = newMove.x; movePtr->y = newMove.y; */ moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw))); moveMatrix.mulV( Point3F( movePtr->x, movePtr->y, movePtr->z ), &newMove ); movePtr->x = newMove.x; movePtr->y = newMove.y; movePtr->z = newMove.z; // end ds // Set movement speed. We'll slow down once we get close // to try and stop on the spot... // start jc if (mMoveSlowdown) { // if (mMoveState == ModeSlowing) { // end jc F32 speed = mMoveSpeed; // start ds /* F32 dist = mSqrt(xDiff*xDiff + yDiff*yDiff); */ F32 dist = mSqrt(xFinDiff*xFinDiff + yFinDiff*yFinDiff+ ((is3D)?zFinDiff*zFinDiff:0.0f)); // end ds // start ds // F32 maxDist = 5.0f; // F32 maxDist = 2.0f; // if (dist < maxDist) // speed *= dist / maxDist; F32 maxDist = 2.0f / mMoveSpeed; if (dist < maxDist) { speed *= dist / maxDist; mMoveState = ModeSlowing; } else mMoveState = ModeMove; // end jc // start jc - stay animating to avoid animation freak out if(speed < 0.002f) speed = 0.002f; // end jc movePtr->x *= speed; movePtr->y *= speed; if(is3D) movePtr->z *= speed; // mMoveState = ModeSlowing; // start jc } else { movePtr->x *= mMoveSpeed; movePtr->y *= mMoveSpeed; if(is3D) movePtr->z *= mMoveSpeed; mMoveState = ModeMove; } // Reset a previous stuck mode mMoveState = ModeMove; if (mMoveStuckTestCountdown > 0) { --mMoveStuckTestCountdown; } else { // We should check to see if we are stuck... F32 locationDelta = (location - mLastLocation).len(); if (locationDelta < mMoveStuckTolerance && mDamageState == Enabled) { // If we are slowing down, then it's likely that our location delta will be less than // our move stuck tolerance. Because we can be both slowing and stuck // we should TRY to check if we've moved. This could use better detection. if ( mMoveState != ModeSlowing || locationDelta == 0 ) { mMoveState = ModeStuck; throwCallback("onMoveStuck"); mMoveStuckTestCountdown = mMoveStuckTestDelay; } } } } } // Test for target location in sight if it's an object. The LOS is // run from the eye position to the center of the object's bounding, // which is not very accurate. if (mAimObject) { MatrixF eyeMat; getEyeTransform(&eyeMat); eyeMat.getColumn(3,&location); Point3F targetLoc = mAimObject->getBoxCenter(); // This ray ignores non-static shapes. Cast Ray returns true // if it hit something. RayInfo dummy; if (getContainer()->castRay( location, targetLoc, InteriorObjectType | StaticShapeObjectType | StaticObjectType | TerrainObjectType, &dummy)) { if (mTargetInLOS) { throwCallback( "onTargetExitLOS" ); mTargetInLOS = false; } } else if (!mTargetInLOS) { throwCallback( "onTargetEnterLOS" ); mTargetInLOS = true; } } // Replicate the trigger state into the move so that // triggers can be controlled from scripts. for( int i = 0; i < MaxTriggerKeys; i++ ) movePtr->trigger[i] = getImageTriggerState(i); mLastLocation = location; // start jc //yorks in start switch (mPose) { case StandPose: movePtr->trigger[3] = false; movePtr->trigger[4] = false; break; case CrouchPose: movePtr->trigger[3] = true; movePtr->trigger[4] = false; break; case PronePose: movePtr->trigger[3] = false; movePtr->trigger[4] = true; break; default: movePtr->trigger[3] = false; movePtr->trigger[4] = false; break; } //yorks in end // end jc return true; } /** * Utility function to throw callbacks. Callbacks always occure * on the datablock class. * * @param name Name of script function to call */ void AIPlayer::throwCallback( const char *name ) { Con::executef(getDataBlock(), name, getIdString()); } /** * Calculates the angle between two Point3F vectors * @param v1 the first vector * @param v2 the second vector * @param discardDimension the dimension (if any) to discard for calculation (1->x, 2->y, 3->z) */ F32 AIPlayer::getVectorAngle(const Point3F &v1, const Point3F &v2, U32 discardDimension) { /* F32 a2,b2,c2; F32 sign = 0; switch (discardDimension) { case 1: a2 = Point2F(v2.y-v1.y,v2.z-v1.z).lenSquared(); b2 = Point2F(v1.y,v1.z).lenSquared(); c2 = Point2F(v2.y,v2.z).lenSquared(); sign = ((-v1.z*v2.y+v1.y*v2.z)>0)?-1.0:1.0;//dot(tangent(v1),v2) break; case 2: a2 = Point2F(v2.x-v1.x,v2.z-v1.z).lenSquared(); b2 = Point2F(v1.x,v1.z).lenSquared(); c2 = Point2F(v2.x,v2.z).lenSquared(); sign = ((-v1.z*v2.x+v1.x*v2.z)>0)?-1.0:1.0;//dot(tangent(v1),v2) break; case 3: a2 = Point2F(v2.x-v1.x,v2.y-v1.y).lenSquared(); b2 = Point2F(v1.x,v1.y).lenSquared(); c2 = Point2F(v2.x,v2.y).lenSquared(); sign = ((-v1.y*v2.x+v1.x*v2.y)>0)?-1.0:1.0;//dot(tangent(v1),v2) break; default: Con::printf("AIPlayer::getAngle - unsupported discardDimension %d", discardDimension); return (F32)0.0; } //Con::printf("v1=(%f,%f,%f) v2=(%f,%f,%f) ",v1.x,v1.y,v1.z,v2.x,v2.y,v2.z); //Con::printf("a2=%f b2=%f c2=%f",a2,b2,c2); F32 val = (b2+c2-a2)/(2*mSqrt(b2)*mSqrt(c2)); if (val >= 1.0) return 0.0; if (val <= -1.0) return (F32)sign*M_PI; //Con::printf("val=%f",val); return (F32)sign*mAcos(val); */ F32 atanv1, atanv2; switch (discardDimension) { case 1: atanv1 = mAtan2(v1.y, v1.z); atanv2 = mAtan2(v2.y, v2.z); break; case 2: atanv1 = mAtan2(v1.x, v1.z); atanv2 = mAtan2(v2.x, v2.z); break; case 3: atanv1 = mAtan2(v1.x, v1.y); atanv2 = mAtan2(v2.x, v2.y); break; default: Con::printf("AIPlayer::getAngle - unsupported discardDimension %d", discardDimension); return (F32)0.0; } F32 result = atanv2 - atanv1; if (result > M_PI_F) { result = -M_2PI_F + result; } if (result <= -M_PI_F) { result = M_2PI_F + result; } return result; } /** * returns the result of rotating a Point3F vector around a given axis * @param vec the vector to rotate * @param angle the angle to rotate clockwise by * @param axis to rotate around (1->x, 2->y, 3->z) */ // start ds - mac fix /* inline Point3F AIPlayer::rotateVec(const Point3F &v,F32 angle, U32 axis) */ Point3F AIPlayer::rotateVec(const Point3F &v,F32 angle, U32 axis) // end ds { F32 cosAngle = mCos(angle); F32 sinAngle = mSin(angle); switch (axis) { case 1: return Point3F(v.x,v.y*cosAngle - v.z*sinAngle,v.y*sinAngle + v.z*cosAngle); case 2: return Point3F(v.x*cosAngle - v.z*sinAngle,v.y,v.x*sinAngle + v.z*cosAngle); case 3: return Point3F(v.x*cosAngle - v.y*sinAngle,v.x*sinAngle + v.y*cosAngle,v.z); default: return Point3F(v); } } bool AIPlayer::findClosestObjectInFront(F32 range, Collision *closest, U32 mask) { // PROFILE_START(AIPlayer_findClosestObjectInFront); static const U32 sAvoidMask = (InteriorObjectType | PlayerObjectType | StaticShapeObjectType | VehicleObjectType | TerrainObjectType ); /* Point3F start; mWorldBox.getCenter(&start); Point3F dif; mObjBox.getCenter(&dif); Point3F finish; mObjToWorld.mulP(dif+VectorF(0.0,range,0.0),&finish); */ Point3F start = getBoxCenter(); Point3F finish; mObjToWorld.getColumn(1,&finish); finish *= range; finish += start; bool result = mContainer->castRect(start,finish,mObjBox.len_x()*M_SQRT2,mObjBox.len_z(), sAvoidMask | mask, closest); // PROFILE_END(AIPlayer_findClosestObjectInFront); return result; } // -------------------------------------------------------------------------------------------- // Console Functions // -------------------------------------------------------------------------------------------- DefineEngineMethod( AIPlayer, stop, void, ( ),, "@brief Tells the AIPlayer to stop moving.\n\n") { object->stopMove(); } DefineEngineMethod( AIPlayer, clearAim, void, ( ),, "@brief Use this to stop aiming at an object or a point.\n\n" "@see setAimLocation()\n" "@see setAimObject()\n") { object->clearAim(); } DefineEngineMethod( AIPlayer, setMoveSpeed, void, ( F32 speed ),, "@brief Sets the move speed for an AI object.\n\n" "@param speed A speed multiplier between 0.0 and 1.0. " "This is multiplied by the AIPlayer's base movement rates (as defined in " "its PlayerData datablock)\n\n" "@see getMoveDestination()\n") { object->setMoveSpeed(speed); } // start jc DefineEngineMethod( AIPlayer, getMoveSpeed, F32, ( void ),, "@brief Gets the move speed for an AI object.\n\n" "@param speed A speed multiplier between 0.0 and 1.0. " "This is multiplied by the AIPlayer's base movement rates (as defined in " "its PlayerData datablock)\n\n" "@see getMoveDestination()\n") { return object->getMoveSpeed(); } // end jc DefineEngineMethod( AIPlayer, setMoveDestination, void, ( Point3F goal, bool slowDown ), ( true ), "@brief Tells the AI to move to the location provided\n\n" "@param goal Coordinates in world space representing location to move to.\n" "@param slowDown A boolean value. If set to true, the bot will slow down " "when it gets within 5-meters of its move destination. If false, the bot " "will stop abruptly when it reaches the move destination. By default, this is true.\n\n" "@note Upon reaching a move destination, the bot will clear its move destination and " "calls to getMoveDestination will return \"0 0 0\"." "@see getMoveDestination()\n") { object->setMoveDestination( goal, slowDown); } DefineEngineMethod( AIPlayer, getMoveDestination, Point3F, (),, "@brief Get the AIPlayer's current destination.\n\n" "@return Returns a point containing the \"x y z\" position " "of the AIPlayer's current move destination. If no move destination " "has yet been set, this returns \"0 0 0\"." "@see setMoveDestination()\n") { return object->getMoveDestination(); } DefineEngineMethod( AIPlayer, setAimLocation, void, ( Point3F target ),, "@brief Tells the AIPlayer to aim at the location provided.\n\n" "@param target An \"x y z\" position in the game world to target.\n\n" "@see getAimLocation()\n") { object->setAimLocation(target); } DefineEngineMethod( AIPlayer, getAimLocation, Point3F, (),, "@brief Returns the point the AIPlayer is aiming at.\n\n" "This will reflect the position set by setAimLocation(), " "or the position of the object that the bot is now aiming at. " "If the bot is not aiming at anything, this value will " "change to whatever point the bot's current line-of-sight intercepts." "@return World space coordinates of the object AI is aiming at. Formatted as \"X Y Z\".\n\n" "@see setAimLocation()\n" "@see setAimObject()\n") { return object->getAimLocation(); } ConsoleDocFragment _setAimObject( "@brief Sets the AIPlayer's target object. May optionally set an offset from target location\n\n" "@param targetObject The object to target\n" "@param offset Optional three-element offset vector which will be added to the position of the aim object.\n\n" "@tsexample\n" "// Without an offset\n" "%ai.setAimObject(%target);\n\n" "// With an offset\n" "// Cause our AI object to aim at the target\n" "// offset (0, 0, 1) so you don't aim at the target's feet\n" "%ai.setAimObject(%target, \"0 0 1\");\n" "@endtsexample\n\n" "@see getAimLocation()\n" "@see getAimObject()\n" "@see clearAim()\n", "AIPlayer", "void setAimObject(GameBase targetObject, Point3F offset);" ); ConsoleMethod( AIPlayer, setAimObject, void, 3, 4, "( GameBase obj, [Point3F offset] )" "Sets the bot's target object. Optionally set an offset from target location." "@hide") { Point3F off( 0.0f, 0.0f, 0.0f ); // Find the target GameBase *targetObject; if( Sim::findObject( argv[2], targetObject ) ) { if (argc == 4) dSscanf( argv[3], "%g %g %g", &off.x, &off.y, &off.z ); object->setAimObject( targetObject, off ); } else object->setAimObject( 0, off ); } DefineEngineMethod( AIPlayer, getAimObject, S32, (),, "@brief Gets the object the AIPlayer is targeting.\n\n" "@return Returns -1 if no object is being aimed at, " "or the SimObjectID of the object the AIPlayer is aiming at.\n\n" "@see setAimObject()\n") { GameBase* obj = object->getAimObject(); return obj? obj->getId(): -1; } // start jc ConsoleMethod( AIPlayer, setMoveDestAndAppVec, void, 4, 5, "(Point3F goal, Point3F appVec, bool slowDown=true)" "Tells the AI to move to the location provided.") { Point3F v( 0.0f, 0.0f, 0.0f ); Point3F v2( 0.0f, 0.0f, 0.0f ); dSscanf( argv[2], "%f %f %f", &v.x, &v.y, &v.z ); dSscanf( argv[3], "%f %f %f", &v2.x, &v2.y, &v2.z ); bool slowdown = (argc > 4)? dAtob(argv[4]): true; object->setMoveDestination( v, v2, slowdown); } ConsoleMethod( AIPlayer, clearFollowObject, void, 2, 2, "()" "Stop following.") { object->clearFollowObject(); } ConsoleMethod( AIPlayer, setFollowObject, void, 3, 4, "( ShapeBase obj, bool slowDown=true)" \ "Tells the AI to follow the object.") \ { \ ShapeBase *targetObject; \ if( Sim::findObject( argv[2], targetObject ) ) \ { \ bool slowdown = (argc > 3)? dAtob(argv[3]): true; \ object->setFollowObject( targetObject, slowdown ); \ } \ else \ { \ Con::warnf("%s::setFollowObject - unable to find object %s","AIClass",argv[2]); \ } \ } ConsoleMethod( AIPlayer, setFollowObjectNode, void, 3, 6, "( ShapeBase obj, char* nodeName, bool slowDown=true)" \ "Tells the AI to follow the object.") \ { \ ShapeBase *targetObject; \ if( Sim::findObject( argv[2], targetObject ) ) \ { \ S32 nodeIndex = (argc > 3)? targetObject->findNode(argv[3]) : 0; \ bool slowdown = (argc > 4)? dAtob(argv[4]): true; \ object->setFollowObjectNode( targetObject, nodeIndex, slowdown ); \ } \ else \ { \ Con::warnf("%s::setFollowObject - unable to find object %s","AIClass",argv[2]); \ } \ } // S32 slotIndex = (argc > 4)? dAtoi(argv[4]): 0; \ // end jc // start jc //yorks start void AIPlayer::changePose(S32 poseNumber) { Pose Pose = StandPose; if(poseNumber == 1) { Pose = CrouchPose; } else if(poseNumber == 2) { Pose = PronePose; } else if(poseNumber == 3) { Pose = SwimPose; } setPose(Pose); } //yorks end //yorks start DefineEngineMethod( AIPlayer, setPose, void, (U32 pose),, "(int pose) StandPose=0,CrouchPose=1,PronePose=2") { object->changePose(pose); }//yorks end // end jc // start jc bool AIPlayer::onNewDataBlock(GameBaseData* dptr, bool reload) { // mDataBlock = dynamic_cast<AIPlayerData*>(dptr); mDataBlock = dynamic_cast<PlayerData*>(dptr); if (!mDataBlock || !Parent::onNewDataBlock(dptr, reload)) return false; // mDataBlock->mStuckT scriptOnNewDataBlock(); return true; } // end jc
30.351648
138
0.620859
[ "object", "vector" ]
2abaae0681191dad892a4f8caaf1cdab294719a0
6,496
cpp
C++
src/component/trader_db.cpp
zhuzhenping/ft
c4be308ddd9c8358b2badbe4dff9f6c7d5b256cc
[ "MIT" ]
154
2020-05-14T14:34:06.000Z
2022-03-14T04:02:17.000Z
src/component/trader_db.cpp
zhuzhenping/ft
c4be308ddd9c8358b2badbe4dff9f6c7d5b256cc
[ "MIT" ]
22
2020-05-06T12:14:33.000Z
2021-06-02T08:50:30.000Z
src/component/trader_db.cpp
zhuzhenping/ft
c4be308ddd9c8358b2badbe4dff9f6c7d5b256cc
[ "MIT" ]
60
2020-05-18T02:49:11.000Z
2022-03-14T04:02:19.000Z
// Copyright [2020-present] <Copyright Kevin, kevin.lau.gd@gmail.com> #ifndef FT_INCLUDE_FT_UTILS_REDIS_H_ #define FT_INCLUDE_FT_UTILS_REDIS_H_ #include "ft/component/trader_db.h" #include <cassert> #include <memory> #include <string> #include <vector> #include "fmt/format.h" #include "ft/base/log.h" #include "hiredis.h" namespace ft { class RedisSession { private: struct RedisReplyDestructor { void operator()(redisReply* p) { if (p) { freeReplyObject(p); } } }; public: using RedisReply = std::shared_ptr<redisReply>; public: RedisSession() {} ~RedisSession() { if (ctx_) { redisFree(ctx_); } } bool Connect(const std::string& ip, int port) { ctx_ = redisConnect(ip.c_str(), port); if (!ctx_) { return false; } if (ctx_->err != 0) { redisFree(ctx_); ctx_ = nullptr; return false; } return true; } bool Set(const std::string& key, const void* p, size_t size) { const char* argv[3]; size_t argvlen[3]; argv[0] = "set"; argvlen[0] = 3; argv[1] = key.c_str(); argvlen[1] = key.length(); argv[2] = reinterpret_cast<const char*>(p); argvlen[2] = size; auto* reply = reinterpret_cast<redisReply*>(redisCommandArgv(ctx_, 3, argv, argvlen)); if (reply) { freeReplyObject(reply); return true; } return false; } RedisReply Get(const std::string& key) const { const char* argv[2]; size_t argvlen[2]; argv[0] = "get"; argvlen[0] = 3; argv[1] = key.c_str(); argvlen[1] = key.length(); auto* reply = reinterpret_cast<redisReply*>(redisCommandArgv(ctx_, 2, argv, argvlen)); return RedisReply(reply, RedisReplyDestructor()); } RedisReply Keys(const std::string& pattern) const { const char* argv[2]; size_t argvlen[2]; argv[0] = "keys"; argvlen[0] = 4; argv[1] = pattern.c_str(); argvlen[1] = pattern.length(); auto* reply = reinterpret_cast<redisReply*>(redisCommandArgv(ctx_, 2, argv, argvlen)); return RedisReply(reply, RedisReplyDestructor()); } bool Del(const std::string& key) { const char* argv[2]; size_t argvlen[2]; argv[0] = "del"; argvlen[0] = 3; argv[1] = key.c_str(); argvlen[1] = key.length(); auto* reply = reinterpret_cast<redisReply*>(redisCommandArgv(ctx_, 2, argv, argvlen)); if (reply) { freeReplyObject(reply); return true; } return false; } private: redisContext* ctx_ = nullptr; }; class TraderDBImpl { public: explicit TraderDBImpl(std::unique_ptr<RedisSession>&& redis_session) : redis_session_(std::move(redis_session)) {} bool GetPosition(const std::string& strategy, const std::string& ticker, Position* res) { auto reply = redis_session_->Get(GetKey(strategy, ticker)); if (!reply) { return false; } if (reply->str) { *res = *reinterpret_cast<Position*>(reply->str); } else { *res = Position{}; } return true; } bool GetAllPositions(const std::string& strategy, std::vector<Position>* res) { auto pattern = fmt::format("pos/{}/*", strategy); auto keys_reply = redis_session_->Keys(pattern); if (!keys_reply) { return false; } for (size_t i = 0; i < keys_reply->elements; ++i) { auto get_reply = redis_session_->Get(keys_reply->element[i]->str); if (!get_reply) { return false; } res->emplace_back(*reinterpret_cast<Position*>(get_reply->str)); } return true; } bool SetPosition(const std::string& strategy, const std::string& ticker, const Position& pos) { return redis_session_->Set(GetKey(strategy, ticker), &pos, sizeof(pos)); } bool ClearPositions(const std::string& strategy) { auto pattern = fmt::format("pos/{}/*", strategy); auto keys_reply = redis_session_->Keys(pattern); if (!keys_reply) { return false; } for (size_t i = 0; i < keys_reply->elements; ++i) { if (!redis_session_->Del(keys_reply->element[i]->str)) { return false; } } return true; } std::string GetKey(const std::string& strategy, const std::string& ticker) const { return fmt::format("pos/{}/{}", strategy, ticker); } private: std::unique_ptr<RedisSession> redis_session_; }; TraderDB::TraderDB() {} TraderDB::~TraderDB() { if (db_impl_) { delete reinterpret_cast<TraderDBImpl*>(db_impl_); } } bool TraderDB::Init(const std::string& address, const std::string& username, const std::string& password) { auto delim_pos = address.find_first_of(':'); if (delim_pos == std::string::npos || delim_pos == 0 || delim_pos == address.size() - 1) { LOG_ERROR("[TraderDB::Init] invalid TraderDB address {}", address); return false; } auto ip = address.substr(0, delim_pos); int port = -1; try { port = std::stoi(address.substr(delim_pos + 1)); } catch (...) { LOG_ERROR("[TraderDB::Init] invalid port. address:{}", address); return false; } auto redis_session = std::make_unique<RedisSession>(); if (!redis_session->Connect(ip, port)) { LOG_ERROR("[TraderDB::Init] failed to open db connection. address:{}", address); return false; } auto* db_impl = new TraderDBImpl(std::move(redis_session)); db_impl_ = db_impl; return true; } bool TraderDB::GetPosition(const std::string& strategy, const std::string& ticker, Position* res) const { if (!db_impl_) { return false; } return reinterpret_cast<TraderDBImpl*>(db_impl_)->GetPosition(strategy, ticker, res); } bool TraderDB::GetAllPositions(const std::string& strategy, std::vector<Position>* res) const { if (!db_impl_) { LOG_ERROR("[TraderDB::GetAllPositions] failed"); return false; } return reinterpret_cast<TraderDBImpl*>(db_impl_)->GetAllPositions(strategy, res); } bool TraderDB::SetPosition(const std::string& strategy, const std::string& ticker, const Position& pos) { if (!db_impl_) { LOG_ERROR("[TraderDB::SetPosition] failed"); return false; } return reinterpret_cast<TraderDBImpl*>(db_impl_)->SetPosition(strategy, ticker, pos); } bool TraderDB::ClearPositions(const std::string& strategy) { if (!db_impl_) { LOG_ERROR("[TraderDB::ClearPositions] failed"); return false; } return reinterpret_cast<TraderDBImpl*>(db_impl_)->ClearPositions(strategy); } } // namespace ft #endif // FT_INCLUDE_FT_UTILS_REDIS_H_
25.47451
97
0.636392
[ "vector" ]
2abd3d8f803b4a20cd06db643e556da4987782cb
20,584
cpp
C++
Benchmarks/Applications/FaceDetection/FaceDetection.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
8
2015-03-16T18:16:35.000Z
2020-10-30T06:35:31.000Z
Benchmarks/Applications/FaceDetection/FaceDetection.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
null
null
null
Benchmarks/Applications/FaceDetection/FaceDetection.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
3
2016-03-17T08:27:13.000Z
2020-10-30T06:46:50.000Z
/* * Copyright (c) 2006-2009 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* * FaceDetection.cpp * * Created on: June 11, 2011 * Author: jlclemon */ #include "FaceDetection.hpp" #ifdef USE_MARSS #warning "Using MARSS" #include "ptlcalls.h" #endif #ifdef USE_GEM5 #warning "Using GEM5" extern "C" { #include "m5op.h" } #endif #define TIMING_MAX_NUMBER_OF_THREADS 256 //#define TSC_TIMING #ifdef TSC_TIMING #include "tsc_class.hpp" #endif //#define CLOCK_GETTIME_TIMING #ifdef CLOCK_GETTIME_TIMING #include "time.h" #ifndef GET_TIME_WRAPPER #define GET_TIME_WRAPPER(dataStruct) clock_gettime(CLOCK_THREAD_CPUTIME_ID, &dataStruct) #endif #endif #ifdef TSC_TIMING vector<TSC_VAL_w> fd_timingVector; #endif #ifdef CLOCK_GETTIME_TIMING vector<struct timespec> fd_timeStructVector; #endif #ifdef TSC_TIMING void fd_writeTimingToFile(vector<TSC_VAL_w> timingVector) { ofstream outputFile; outputFile.open("timing.csv"); outputFile << "Thread,Start,Finish,Mid" << endl; for(int i = 0; i<(TIMING_MAX_NUMBER_OF_THREADS); i++) { outputFile << i << "," << timingVector[i] << "," << timingVector[i+TIMING_MAX_NUMBER_OF_THREADS]<< ","<< timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS] << endl; } outputFile.close(); } #endif #ifdef CLOCK_GETTIME_TIMING void fd_writeTimingToFile(vector<struct timespec> timingVector) { ofstream outputFile; outputFile.open("timing.csv"); outputFile << "Thread,Start sec, Start nsec,Finish sec, Finish nsec,Mid sec, Mid nsec" << endl; for(int i = 0; i<(TIMING_MAX_NUMBER_OF_THREADS); i++) { outputFile << i << "," << timingVector[i].tv_sec<<","<< timingVector[i].tv_nsec << "," << timingVector[i+TIMING_MAX_NUMBER_OF_THREADS].tv_sec<<","<< timingVector[i+TIMING_MAX_NUMBER_OF_THREADS].tv_nsec<< "," << timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS].tv_sec<<","<< timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS].tv_nsec <<endl; } outputFile.close(); } #endif void readFileListFromFile(string fileListFilename, string filesBaseDir,vector<string> &fileList) { ifstream fileListFile; fileListFile.open(fileListFilename.c_str(),ios::in); if(fileListFile.is_open()) { while(fileListFile.good()) { string currentLine; getline(fileListFile,currentLine); if(currentLine != "") { fileList.push_back(filesBaseDir+currentLine); } } fileListFile.close(); } } bool loadFaceDetectionConfigFile(vector<string> &commandArgs, string filename) { std::ifstream configFile; // int i = 3; string tmpString; bool returnVal = false; configFile.open(filename.c_str()); if(configFile.good()) { while(!configFile.eof()) { getline(configFile,tmpString); commandArgs.push_back(tmpString); } returnVal = true; cout << "Config file loaded!!!" << endl; } else { cout << "WARNING: Unable to open params config file" << endl; } return returnVal; } void parseFaceDetectionConfigCommandVector(FaceDetectionConfig & faceDetectionConfig, vector<string> & commandStringVector) { vector<string>::iterator it_start = commandStringVector.begin(); vector<string>::iterator it_end = commandStringVector.end(); vector<string>::iterator it_current; stringstream stringBuffer; faceDetectionConfig.cameraId[0] = 1; faceDetectionConfig.cameraId[1] = 0; faceDetectionConfig.inputMethod =FACE_DETECT_SINGLE_STREAM; faceDetectionConfig.faceScale = 2.0; faceDetectionConfig.outputRawImageExt = ".png"; faceDetectionConfig.outputRawImageBaseName = ""; faceDetectionConfig.bufferedImageList = false; faceDetectionConfig.showWindows = false; faceDetectionConfig.noWaitKey = false; //-desc sift -match knn_flann -classify linear_svm -queryDescFile test.yml -trainDescFile test.yml -loadClassificationStruct test.yml -loadMatchStruct test.yml for(it_current=it_start; it_current!=it_end; ++it_current) { if(!it_current->compare("-inputMethod") || !it_current->compare("-InputMethod")) { if(!(it_current+1)->compare("monoStream")) { faceDetectionConfig.inputMethod=FACE_DETECT_SINGLE_STREAM; } if(!(it_current+1)->compare("stereoStream")) { faceDetectionConfig.inputMethod=FACE_DETECT_STEREO_STREAM; } if(!(it_current+1)->compare("imageFileList")) { faceDetectionConfig.useImageList = true; faceDetectionConfig.inputMethod=FACE_DETECT_IMAGE_FILE_LIST; } if(!(it_current+1)->compare("videoFile")) { faceDetectionConfig.inputMethod=FACE_DETECT_VIDEO_FILE; } } if(!it_current->compare("-camera0") || !it_current->compare("-Camera0")) { stringBuffer.str(""); stringBuffer << *(it_current+1); if((stringBuffer >> faceDetectionConfig.cameraId[0]).fail()) { cout << "Camera0 Id could not be parsed." << endl; } } if(!it_current->compare("-camera1") || !it_current->compare("-Camera1")) { stringBuffer.str(""); stringBuffer << *(it_current+1); if((stringBuffer >> faceDetectionConfig.cameraId[1]).fail()) { cout << "Camera0 Id could not be parsed." << endl; } } if(!it_current->compare("-faceCascadeFile") || !it_current->compare("-FaceCascadeFile")) { faceDetectionConfig.cascadeFaceDetectorFilename = *(it_current+1); } if(!it_current->compare("-imageList") || !it_current->compare("-ImageList")) { faceDetectionConfig.imageListFilename = *(it_current+1); } if(!it_current->compare("-imageListBaseDir") || !it_current->compare("-ImageListBaseDir")) { faceDetectionConfig.imageListBaseDir = *(it_current+1); } if(!it_current->compare("-nVertCores")) { stringBuffer.str(""); stringBuffer.clear(); stringBuffer << *(it_current+1); cout << *(it_current+1) << endl; if((stringBuffer >> faceDetectionConfig.numberOfVerticalProcs).fail()) { cout << "Number of vertical cores could not be parsed." << endl; } } if(!it_current->compare("-nHoriCores")) { stringBuffer.str(""); stringBuffer.clear(); stringBuffer << *(it_current+1); cout << *(it_current+1) << endl; if((stringBuffer >> faceDetectionConfig.numberOfHorizontalProcs).fail()) { cout << "Number of horizontal cores could not be parsed." << endl; } } if(!it_current->compare("-faceScale") ||!it_current->compare("-FaceScale")) { stringBuffer.str(""); stringBuffer.clear(); stringBuffer << *(it_current+1); cout << *(it_current+1) << endl; if((stringBuffer >> faceDetectionConfig.faceScale).fail()) { cout << "Face scale could not be parsed." << endl; } } if( it_current->compare("-singleThreaded") == 0 || it_current->compare("-SingleThreaded") == 0) { faceDetectionConfig.singleThreaded= true; } if( it_current->compare("-showWindows") == 0 || it_current->compare("-ShowWindows") == 0) { faceDetectionConfig.showWindows = true; } if( it_current->compare("-noWaitKey") == 0 || it_current->compare("-NoWaitKey") == 0) { faceDetectionConfig.noWaitKey = true; } if( it_current->compare("-bufferedImageList") == 0 || it_current->compare("-BufferedImageList") == 0) { faceDetectionConfig.bufferedImageList = true; } if(!it_current->compare("-inputVideoFile") || !it_current->compare("-InputVideoFile")) { faceDetectionConfig.inputVideoFilename = *(it_current+1); } if(!it_current->compare("-outputRawVideoFile") || !it_current->compare("-OutputRawVideoFile")) { faceDetectionConfig.outputRawStreamFilename = *(it_current+1); } if(!it_current->compare("-outputAugmentedVideoFile") || !it_current->compare("-OutputAugmentedVideoFile")) { faceDetectionConfig.outputAugmentedStreamFilename = *(it_current+1); } if(!it_current->compare("-outputRawImageBaseName") || !it_current->compare("-OutputRawImageBaseName")) { faceDetectionConfig.outputRawImageBaseName = *(it_current+1); } if(!it_current->compare("-outputRawImageExt") || !it_current->compare("-OutputRawImageExt")) { faceDetectionConfig.outputRawImageExt = *(it_current+1); } } if(faceDetectionConfig.numberOfVerticalProcs ==1 && faceDetectionConfig.numberOfHorizontalProcs ==1) { faceDetectionConfig.singleThreaded = true; } else { faceDetectionConfig.singleThreaded = false; } faceDetectionConfig.bufferedImageListBufferSize = 5; return; } void faceDetectionSetupOutput( FaceDetectionConfig &faceDetectionConfig, FaceDetectionData &faceDetectionData) { if(faceDetectionConfig.outputRawStreamFilename!= "") { faceDetectionData.rawStreamWriter.open(faceDetectionConfig.outputRawStreamFilename,CV_FOURCC('M','J','P','G'),30.0,faceDetectionData.frameSize,true); } if(faceDetectionConfig.outputAugmentedStreamFilename!= "") { faceDetectionData.augmentedStreamWriter.open(faceDetectionConfig.outputAugmentedStreamFilename,CV_FOURCC('P','I','M','1'),30.0,faceDetectionData.frameSize, true); } if(faceDetectionConfig.outputRawImageBaseName != "") { faceDetectionData.currentOutputRawImageId = 0; } } void faceDetectionHandleWritingOutput( FaceDetectionConfig &faceDetectionConfig, FaceDetectionData &faceDetectionData) { if(faceDetectionData.rawStreamWriter.isOpened()) { faceDetectionData.rawStreamWriter << faceDetectionData.currentFrame[0]; } if(faceDetectionData.augmentedStreamWriter.isOpened()) { faceDetectionData.augmentedStreamWriter << faceDetectionData.currentAgumentedFrame[0]; } if(faceDetectionConfig.outputRawImageBaseName != "") { stringstream streamForId; string currentOutputId; streamForId << "_" <<faceDetectionData.currentOutputRawImageId; streamForId >> currentOutputId; string imageFileName = faceDetectionConfig.outputRawImageBaseName + currentOutputId + faceDetectionConfig.outputRawImageExt; imwrite(imageFileName,faceDetectionData.currentFrame[0]); faceDetectionData.currentOutputRawImageId++; } } void faceDetectionSetupInput( FaceDetectionConfig &faceDetectionConfig, FaceDetectionData &faceDetectionData) { switch(faceDetectionConfig.inputMethod) { case FACE_DETECT_VIDEO_FILE: { break; } case FACE_DETECT_STEREO_STREAM: { break; } case FACE_DETECT_IMAGE_FILE_LIST: { if(faceDetectionConfig.imageListFilename != "") { readFileListFromFile(faceDetectionConfig.imageListFilename , faceDetectionConfig.imageListBaseDir,faceDetectionData.imageList); faceDetectionData.currentInputImageId = 0; if(faceDetectionConfig.bufferedImageList) { for(int i = faceDetectionData.currentInputImageId; ((i < faceDetectionConfig.bufferedImageListBufferSize)&& (i<faceDetectionData.imageList.size())); i++) { faceDetectionData.imageListBuffer[0].push_back(imread(faceDetectionData.imageList[i])); } } Mat tmpMat = imread(faceDetectionData.imageList[0]); faceDetectionData.frameSize.width = tmpMat.cols; faceDetectionData.frameSize.height = tmpMat.rows; } else { cout << "Invalid image list." << endl; exit(0); } break; } case FACE_DETECT_SINGLE_STREAM: default: { faceDetectionData.capture[0].open(faceDetectionConfig.cameraId[0]); if(!faceDetectionData.capture[0].isOpened()) { cout << "Error: Unable to opeb input stream" << endl; exit(0); } faceDetectionData.frameSize.width = faceDetectionData.capture[0].get(CV_CAP_PROP_FRAME_WIDTH); faceDetectionData.frameSize.height = faceDetectionData.capture[0].get(CV_CAP_PROP_FRAME_HEIGHT); faceDetectionData.capture[0].set(CV_CAP_PROP_FRAME_WIDTH,640); faceDetectionData.capture[0].set(CV_CAP_PROP_FRAME_HEIGHT,480); break; } }; faceDetectionData.outOfImages = false; } void faceDetectionGetNextFrames(FaceDetectionConfig &faceDetectionConfig, FaceDetectionData &faceDetectionData) { switch(faceDetectionConfig.inputMethod) { case FACE_DETECT_VIDEO_FILE: { break; } case FACE_DETECT_STEREO_STREAM: { break; } case FACE_DETECT_IMAGE_FILE_LIST: { if(!faceDetectionConfig.bufferedImageList) { faceDetectionData.currentFrame[0] = imread(faceDetectionData.imageList[faceDetectionData.currentInputImageId]); } else { if(faceDetectionData.imageListBuffer[0].size() <=0) { if(faceDetectionData.currentInputImageId <faceDetectionData.imageList.size()) { for(int i = faceDetectionData.currentInputImageId; ((i < faceDetectionConfig.bufferedImageListBufferSize)&& (i<faceDetectionData.imageList.size())); i++) { faceDetectionData.imageListBuffer[0].push_back(imread(faceDetectionData.imageList[i])); } } else { faceDetectionData.outOfImages = true; } } faceDetectionData.currentFrame[0]= faceDetectionData.imageListBuffer[0].front(); faceDetectionData.imageListBuffer[0].pop_front(); } faceDetectionData.currentInputImageId++; break; } case FACE_DETECT_SINGLE_STREAM: default: { faceDetectionData.capture[0] >> faceDetectionData.frameBuffer[0]; faceDetectionData.currentFrame[0]=faceDetectionData.frameBuffer[0].clone(); break; } }; if(faceDetectionData.currentFrame[0].empty()) { faceDetectionData.outOfImages = true; } } void setupFaceDetectionData(FaceDetectionConfig & faceDetectionConfig, FaceDetectionData & faceDetectionData) { faceDetectionData.faceCascade.load(faceDetectionConfig.cascadeFaceDetectorFilename); } int faceDetection_main(int argc, const char * argv[]) { int key = -1; int lastKey = -1; FaceDetectionConfig faceDetectionConfig; FaceDetectionData faceDetectionData; cout << "Face Detection Application Starting" << endl; cout << "Beginning Setup" << endl; vector<string> commandLineArgs; for(int i = 0; i < argc; i++) { string currentString = argv[i]; commandLineArgs.push_back(currentString); } if((commandLineArgs[1].compare("-configFile") ==0) || (commandLineArgs[1].compare("-ConfigFile") ==0)) { loadFaceDetectionConfigFile(commandLineArgs, commandLineArgs[2]); } parseFaceDetectionConfigCommandVector(faceDetectionConfig, commandLineArgs); faceDetectionSetupInput( faceDetectionConfig,faceDetectionData); setupFaceDetectionData(faceDetectionConfig, faceDetectionData); cout << "Setup Complete" << endl; if(faceDetectionConfig.inputMethod ==FACE_DETECT_SINGLE_STREAM) { cout << "Allowing stream to setup" << endl; namedWindow("Stream warmup"); key = -1; lastKey = -1; while(key != 27 && key != 'r' && key != 'd' && key != ' ') { faceDetectionData.capture[0] >> faceDetectionData.frameBuffer[0]; faceDetectionData.currentFrame[0]=faceDetectionData.frameBuffer[0].clone(); imshow("Stream warmup",faceDetectionData.currentFrame[0]); key = waitKey(33) & 0xff; } destroyWindow("Stream warmup"); } faceDetectionSetupOutput( faceDetectionConfig,faceDetectionData); if(faceDetectionConfig.showWindows) { cout << "Creating display windows" << endl; namedWindow("Current Frame Original"); namedWindow("Current Frame Grayscale"); namedWindow("Current Frame Augmented"); } cout << "Beginning Main Loop" << endl; key = -1; lastKey = -1; bool done = false; Mat tmpBuffer; vector<Rect> faces; // const static Scalar colors[] = { CV_RGB(0,0,255), // CV_RGB(0,128,255), // CV_RGB(0,255,255), // CV_RGB(0,255,0), // CV_RGB(255,128,0), // CV_RGB(255,255,0), // CV_RGB(255,0,0), // CV_RGB(255,0,255)} ; Mat gray, smallImg( cvRound (faceDetectionData.frameSize.height/faceDetectionConfig.faceScale), cvRound(faceDetectionData.frameSize.width/faceDetectionConfig.faceScale), CV_8UC1 ); Mat augmentedFrame; #ifdef USE_MARSS cout << "Switching to simulation in Face Detection." << endl; ptlcall_switch_to_sim(); //ptlcall_single_enqueue("-logfile augReality.log"); //ptlcall_single_enqueue("-stats faceDetect.stats"); ptlcall_single_flush("-stats faceDetect.stats"); //ptlcall_single_enqueue("-loglevel 0"); #endif #ifdef USE_GEM5 #ifdef GEM5_CHECKPOINT_WORK m5_checkpoint(0, 0); #endif #ifdef GEM5_SWITCHCPU_AT_WORK m5_switchcpu(); #endif m5_dumpreset_stats(0, 0); #endif #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fd_timingVector[0] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fd_timeStructVector[0]); #endif while(!done) { faceDetectionGetNextFrames(faceDetectionConfig, faceDetectionData); //cout << "Top of Loop" << endl; if(faceDetectionData.outOfImages == true) { break; } cvtColor( faceDetectionData.currentFrame[0], gray, CV_BGR2GRAY ); resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR ); equalizeHist( smallImg, smallImg ); faceDetectionData.faceCascade.detectMultiScale( smallImg, faces, 1.1, 2, 0 //|CV_HAAR_FIND_BIGGEST_OBJECT //|CV_HAAR_DO_ROUGH_SEARCH |CV_HAAR_SCALE_IMAGE , Size(30, 30) ); if(faceDetectionConfig.showWindows) { imshow("Current Frame Original", faceDetectionData.currentFrame[0]); imshow("Current Frame Grayscale", smallImg); augmentedFrame = faceDetectionData.currentFrame[0].clone(); for( vector<Rect>::const_iterator r = faces.begin(); r != faces.end(); r++ ) { vector<Rect> nestedObjects; Point center; Scalar color = CV_RGB(255,0,0); int radius; center.x = cvRound((r->x + r->width*0.5)*faceDetectionConfig.faceScale); center.y = cvRound((r->y + r->height*0.5)*faceDetectionConfig.faceScale); radius = cvRound((r->width + r->height)*0.25*faceDetectionConfig.faceScale); circle( augmentedFrame, center, radius, color, 3, 8, 0 ); } imshow("Current Frame Augmented", augmentedFrame); } lastKey = key; if(!faceDetectionConfig.noWaitKey) { key = waitKey(30) & 0xff; } else { key = -1; } if(key == 'q' || key =='d' || key == 27) { done = true; } } #ifdef USE_MARSS ptlcall_kill(); #endif #ifdef USE_GEM5 m5_dumpreset_stats(0, 0); #ifdef GEM5_EXIT_AFTER_WORK m5_exit(0); #endif #endif #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fd_timingVector[0+ TIMING_MAX_NUMBER_OF_THREADS] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fd_timeStructVector[0+ TIMING_MAX_NUMBER_OF_THREADS]); #endif #ifdef TSC_TIMING fd_writeTimingToFile(fd_timingVector); #endif #ifdef CLOCK_GETTIME_TIMING fd_writeTimingToFile(fd_timeStructVector); #endif cout << "Face Detection completed. " << faces.size()<< " Faces found in last iteration" <<endl; if(faceDetectionConfig.showWindows) { cout << "Destroying display windows" << endl; destroyWindow("Current Frame Original"); destroyWindow("Current Frame Grayscale"); destroyWindow("Current Frame Augmented"); } return 0; } #ifndef FACE_DETECTION_MODULE int main(int argc, const char * argv[]) { #ifdef TSC_TIMING fd_timingVector.resize(TIMING_MAX_NUMBER_OF_THREADS*3); #endif #ifdef CLOCK_GETTIME_TIMING //fd_timingVector.resize(16); fd_timeStructVector.resize(TIMING_MAX_NUMBER_OF_THREADS*3); #endif return faceDetection_main(argc, argv); } #endif
23.364359
338
0.719151
[ "vector" ]
2ac1264315ac13c51c1c39b971f238ddf632a9c4
1,775
cpp
C++
18.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
18.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
18.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ull = uint64_t; using ll = int64_t; using ld = long double; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; class Solution { public: vector< vector<int> > fourSum(vector<int>& nums, int target) { vector<vi> ret; int num = (int) nums.size(); sort(nums.begin(), nums.end()); // Enumerate the first and second elements in a four sum for (int i = 0; i != num; ++i) { for (int j = i + 1; j != num; ++j) { int front_ptr = j + 1; int rear_ptr = num - 1; int rest = target - nums[i] - nums[j]; // Find the valid combination of the third and fourth elements while (front_ptr < rear_ptr) { if (nums[front_ptr] + nums[rear_ptr] < rest) // increase the third element ++front_ptr; else if (nums[front_ptr] + nums[rear_ptr] > rest) // decrease the fourth element --rear_ptr; else // valid four sum { vi quadruplet(4, 0); quadruplet[0] = nums[i]; quadruplet[1] = nums[j]; quadruplet[2] = nums[front_ptr]; quadruplet[3] = nums[rear_ptr]; ret.push_back(quadruplet); while (front_ptr <= rear_ptr && nums[front_ptr] == quadruplet[2]) // update the pointer of the third element to the next different value ++front_ptr; while (rear_ptr >= front_ptr && nums[rear_ptr] == quadruplet[3]) // update the pointer of the fourth element to the next different value --rear_ptr; } } while (j + 1 < num && nums[j + 1] == nums[j]) // update the pointer of the second element to the last same value ++j; } while (i + 1 < num && nums[i + 1] == nums[i]) // update the pointer of the first element to the last same value ++i; } return ret; } };
29.583333
142
0.607887
[ "vector" ]
2ad27ab88049bc7df5df522323ff9ce7cb563fc5
9,861
cpp
C++
TAO/performance-tests/Protocols/receiver.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/performance-tests/Protocols/receiver.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/performance-tests/Protocols/receiver.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: receiver.cpp 95746 2012-05-13 12:51:05Z johnnyw $ #include "ace/Get_Opt.h" #include "ace/OS_NS_stdio.h" #include "ace/OS_NS_string.h" #include "ace/OS_NS_unistd.h" #include "ace/Sample_History.h" #include "ace/High_Res_Timer.h" #include "ace/Stats.h" #include "ace/Throughput_Stats.h" #include "tao/debug.h" #include "testS.h" static const ACE_TCHAR *ior_file = ACE_TEXT ("receiver.ior"); static int do_dump_history = 0; static int print_missed_invocations = 0; static ACE_High_Res_Timer::global_scale_factor_type gsf = 0; static int parse_args (int argc, ACE_TCHAR **argv) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("d:f:m:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'd': do_dump_history = ACE_OS::atoi (get_opts.opt_arg ()); break; case 'f': ior_file = get_opts.opt_arg (); break; case 'm': print_missed_invocations = ACE_OS::atoi (get_opts.opt_arg ()); break; default: ACE_ERROR_RETURN ((LM_ERROR, "usage: %s\n" "\t-d <show history> (defaults to %d)\n" "\t-f <ior_file> (defaults to %s)\n" "\t-m <print missed invocations for paced workers> (defaults to %d)\n" "\n", argv[0], do_dump_history, ior_file, print_missed_invocations), -1); } return 0; } class test_i : public POA_test { public: test_i (CORBA::ORB_ptr orb, PortableServer::POA_ptr poa); ~test_i (void); void start_test (CORBA::Long session_id, const char *protocol, CORBA::ULong invocation_rate, CORBA::ULong message_size, CORBA::ULong iterations); void end_test (void); void oneway_sync (void); void twoway_sync (void); void oneway_method (CORBA::Long session_id, CORBA::ULong iteration, const ::test::octets &payload); void twoway_method (CORBA::Long &session_id, CORBA::ULong &iteration, ::test::octets &payload); //FUZZ: disable check_for_lack_ACE_OS void shutdown (void); //FUZZ: enable check_for_lack_ACE_OS PortableServer::POA_ptr _default_POA (void); private: CORBA::ORB_var orb_; PortableServer::POA_var poa_; typedef ACE_Array_Base<CORBA::Boolean> Invocations; Invocations invocations_received_; ACE_hrtime_t time_of_last_call_; ACE_hrtime_t test_start_; ACE_hrtime_t test_end_; CORBA::Boolean first_invocation_; ACE_Sample_History *inter_arrival_times_; CORBA::ULong iterations_; CORBA::ULong number_of_invocations_received_; CORBA::Long session_id_; }; test_i::test_i (CORBA::ORB_ptr orb, PortableServer::POA_ptr poa) : orb_ (CORBA::ORB::_duplicate (orb)), poa_ (PortableServer::POA::_duplicate (poa)), inter_arrival_times_ (0), iterations_ (0), session_id_ (-1) { } test_i::~test_i (void) { } void test_i::start_test (CORBA::Long session_id, const char *protocol, CORBA::ULong invocation_rate, CORBA::ULong message_size, CORBA::ULong iterations) { if (TAO_debug_level > 0) { ACE_DEBUG ((LM_DEBUG, "Session id starts %d\n", session_id)); } ACE_DEBUG ((LM_DEBUG, "Protocol = %5s Invocation Rate = %3d Message Size = %5d Expected Latency = %4d ", ACE_TEXT_CHAR_TO_TCHAR (protocol), invocation_rate, message_size, 1000 / invocation_rate)); // Remember test parameters. this->session_id_ = session_id; this->iterations_ = iterations; this->number_of_invocations_received_ = 0; // // Initialize counters and tables. // this->inter_arrival_times_ = new ACE_Sample_History (iterations); this->first_invocation_ = 1; this->invocations_received_.size (iterations); for (CORBA::ULong i = 0; i < iterations; ++i) this->invocations_received_[i] = 0; // Record start time. this->test_start_ = ACE_OS::gethrtime (); } void test_i::end_test (void) { // Record end time. this->test_end_ = ACE_OS::gethrtime (); if (do_dump_history) { this->inter_arrival_times_->dump_samples (ACE_TEXT("Inter-arrival times"), gsf); } ACE_Basic_Stats stats; this->inter_arrival_times_->collect_basic_stats (stats); ACE_DEBUG ((LM_DEBUG, "Max Latency = %6d ", stats.max_ / gsf / 1000)); ACE_DEBUG ((LM_DEBUG, "Invocations expected / received / missed / missed %% = %6d / %6d / %6d / %5.2f\n", this->iterations_, this->number_of_invocations_received_, this->iterations_ - this->number_of_invocations_received_, (this->iterations_ - this->number_of_invocations_received_) / (double) this->iterations_ * 100)); if (print_missed_invocations) { ACE_DEBUG ((LM_DEBUG, "\nFollowing invocations were never received:\n")); for (CORBA::ULong i = 0; i < this->iterations_; ++i) { if (this->invocations_received_[i] == 0) { ACE_DEBUG ((LM_DEBUG, "%d ", i)); } } ACE_DEBUG ((LM_DEBUG, "\n")); } if (TAO_debug_level > 0) { ACE_DEBUG ((LM_DEBUG, "Session id ends %d\n", this->session_id_)); stats.dump_results (ACE_TEXT("Inter-arrival times"), gsf); ACE_Throughput_Stats::dump_throughput (ACE_TEXT("Inter-arrival times"), gsf, this->test_end_ - this->test_start_, stats.samples_count ()); } this->session_id_ = -1; delete this->inter_arrival_times_; } void test_i::oneway_sync (void) { } void test_i::twoway_sync (void) { } void test_i::oneway_method (CORBA::Long session_id, CORBA::ULong iteration, const ::test::octets &payload) { if (this->session_id_ != session_id) { ACE_DEBUG ((LM_DEBUG, "Late message with iteration id = %d: will not count message\n", iteration)); return; } if (TAO_debug_level > 0) { ACE_DEBUG ((LM_DEBUG, "test_i::oneway_method -> session id = %d iteration = %d payload size = %d\n", session_id, iteration, payload.length ())); } this->invocations_received_[iteration] = 1; ++this->number_of_invocations_received_; ACE_hrtime_t time_of_current_call = ACE_OS::gethrtime (); if (this->first_invocation_) this->first_invocation_ = 0; else this->inter_arrival_times_->sample (time_of_current_call - this->time_of_last_call_); this->time_of_last_call_ = time_of_current_call; } void test_i::twoway_method (CORBA::Long &session_id, CORBA::ULong &iteration, ::test::octets &payload) { if (this->session_id_ != session_id) { ACE_DEBUG ((LM_DEBUG, "Late message with iteration id = %d: will not count message\n", iteration)); return; } if (TAO_debug_level > 0) { ACE_DEBUG ((LM_DEBUG, "test_i::twoway_method -> session id = %d iteration = %d payload size = %d\n", session_id, iteration, payload.length ())); } this->invocations_received_[iteration] = 1; ++this->number_of_invocations_received_; ACE_hrtime_t time_of_current_call = ACE_OS::gethrtime (); if (this->first_invocation_) this->first_invocation_ = 0; else this->inter_arrival_times_->sample (time_of_current_call - this->time_of_last_call_); this->time_of_last_call_ = time_of_current_call; } PortableServer::POA_ptr test_i::_default_POA (void) { return PortableServer::POA::_duplicate (this->poa_.in ()); } void test_i::shutdown (void) { ACE_DEBUG ((LM_DEBUG, "test_i::shutdown\n")); this->orb_->shutdown (0); } int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { gsf = ACE_High_Res_Timer::global_scale_factor (); try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); int parse_args_result = parse_args (argc, argv); if (parse_args_result != 0) return parse_args_result; CORBA::Object_var object = orb->resolve_initial_references ("RootPOA"); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (object.in ()); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); test_i *servant = new test_i (orb.in (), root_poa.in ()); PortableServer::ServantBase_var safe_servant (servant); test_var test = servant->_this (); CORBA::String_var ior = orb->object_to_string (test.in ()); FILE *output_file = ACE_OS::fopen (ior_file, "w"); ACE_ASSERT (output_file != 0); u_int result = ACE_OS::fprintf (output_file, "%s", ior.in ()); ACE_ASSERT (result == ACE_OS::strlen (ior.in ())); ACE_UNUSED_ARG (result); ACE_OS::fclose (output_file); poa_manager->activate (); orb->run (); ACE_OS::sleep(1); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught"); return -1; } return 0; }
25.349614
111
0.578339
[ "object", "3d" ]
2ad5a2e1bda353975506ebf87330dba59094b501
3,113
hh
C++
lib/spot-2.8.1/spot/twaalgos/sum.hh
AlessandroCaste/SynkrisisJupyter
a9c2b21ec1ae7ac0c05ef5deebc63a369274650f
[ "Unlicense" ]
1
2018-03-02T14:29:57.000Z
2018-03-02T14:29:57.000Z
lib/spot-2.8.1/spot/twaalgos/sum.hh
AlessandroCaste/SynkrisisJupyter
a9c2b21ec1ae7ac0c05ef5deebc63a369274650f
[ "Unlicense" ]
null
null
null
lib/spot-2.8.1/spot/twaalgos/sum.hh
AlessandroCaste/SynkrisisJupyter
a9c2b21ec1ae7ac0c05ef5deebc63a369274650f
[ "Unlicense" ]
1
2015-06-05T12:42:07.000Z
2015-06-05T12:42:07.000Z
// -*- coding: utf-8 -*- // Copyright (C) 2017 Laboratoire de Recherche et // Développement de l'Epita (LRDE). // // This file is part of Spot, a model checking library. // // Spot is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // Spot 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/>. #pragma once #include <spot/misc/common.hh> #include <spot/twa/fwd.hh> namespace spot { /// \ingroup twa_algorithms /// \brief Sum two twa into a new twa, performing the union of the two input /// automata. /// /// \param left Left term of the sum. /// \param right Right term of the sum. /// \return A spot::twa_graph containing the sum of \a left and \a right SPOT_API twa_graph_ptr sum(const const_twa_graph_ptr& left, const const_twa_graph_ptr& right); /// \ingroup twa_algorithms /// \brief Sum two twa into a new twa, performing the union of the two input /// automata. /// /// \param left Left term of the sum. /// \param right Right term of the sum. /// \param left_state Initial state of the left term of the sum. /// \param right_state Initial state of the right term of the sum. /// \return A spot::twa_graph containing the sum of \a left and \a right SPOT_API twa_graph_ptr sum(const const_twa_graph_ptr& left, const const_twa_graph_ptr& right, unsigned left_state, unsigned right_state); /// \ingroup twa_algorithms /// \brief Sum two twa into a new twa, using a universal initial transition, /// performing the intersection of the two languages of the input automata. /// /// \param left Left term of the sum. /// \param right Right term of the sum. /// \return A spot::twa_graph containing the sum of \a left and \a right SPOT_API twa_graph_ptr sum_and(const const_twa_graph_ptr& left, const const_twa_graph_ptr& right); /// \ingroup twa_algorithms /// \brief Sum two twa into a new twa, using a universal initial transition, /// performing the intersection of the two languages of the input automata. /// /// \param left Left term of the sum. /// \param right Right term of the sum. /// \param left_state Initial state of the left term of the sum. /// \param right_state Initial state of the right term of the sum. /// \return A spot::twa_graph containing the sum of \a left and \a right SPOT_API twa_graph_ptr sum_and(const const_twa_graph_ptr& left, const const_twa_graph_ptr& right, unsigned left_state, unsigned right_state); }
39.405063
78
0.679409
[ "model" ]
2ad7f761ae185ecd3d7c188efd419c6336cff7c4
3,628
cpp
C++
Image Generator/Source/GloomhavenReco/Tile.cpp
ericdepotter/Gloomhaven-Monster-Recognizer
8ec29cb5c83583bd383bdb2626da8f35e840795c
[ "MIT" ]
null
null
null
Image Generator/Source/GloomhavenReco/Tile.cpp
ericdepotter/Gloomhaven-Monster-Recognizer
8ec29cb5c83583bd383bdb2626da8f35e840795c
[ "MIT" ]
null
null
null
Image Generator/Source/GloomhavenReco/Tile.cpp
ericdepotter/Gloomhaven-Monster-Recognizer
8ec29cb5c83583bd383bdb2626da8f35e840795c
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "SpawnLocation.h" #include "Monster.h" #include "Tile.h" #include "Kismet/KismetMathLibrary.h" #include "Math/UnrealMathUtility.h" #include "Engine.h" // Sets default values ATile::ATile() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; USceneComponent* Root = CreateDefaultSubobject<USceneComponent>(FName("RootSceneComponent")); Root->AttachToComponent( nullptr, FAttachmentTransformRules::SnapToTargetNotIncludingScale ); SetRootComponent(Root); StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(FName("MeshComponent")); StaticMeshComponent->AttachToComponent( Root, FAttachmentTransformRules::SnapToTargetIncludingScale ); auto Result = ConstructorHelpers::FObjectFinder<UStaticMesh>(TEXT("StaticMesh'/Engine/BasicShapes/Cube.Cube'")); if (Result.Object) { StaticMeshComponent->SetStaticMesh(Result.Object); } } // Called when the game starts or when spawned void ATile::BeginPlay() { Super::BeginPlay(); } TArray<USpawnLocation*> ATile::GetSpawnLocations() const { TArray<USpawnLocation*> OutComponents; GetComponents<USpawnLocation>(OutComponents); return OutComponents; } void ATile::PopulateTile(FVector CameraPosition, int NumberMonsters) { if (Monsters.Num() > 0) { ClearTile(); } TArray<USpawnLocation*> SpawnLocations = GetSpawnLocations(); NumberMonsters = FMath::Clamp(NumberMonsters, 1, SpawnLocations.Num()); for (int i = 0; i < NumberMonsters; i++) { int index = FMath::RandRange(0, SpawnLocations.Num() - 1); USpawnLocation* SpawnLocation = SpawnLocations[index]; SpawnLocations.RemoveAt(index); FVector Location = SpawnLocation->GetComponentLocation() + FVector(0, 0, -20); FRotator LookAtCameraRotation = UKismetMathLibrary::FindLookAtRotation(Location, CameraPosition); float Yaw = LookAtCameraRotation.Yaw - 90 + 180 * FMath::RandRange(0, 1) + FMath::RandRange(-30.f, 30.f); SpawnMonster(Location, FRotator(0, Yaw, 0)); } } void ATile::SwitchToMask() { if (MaskMaterial) { StaticMeshComponent->SetMaterial(0, MaskMaterial); } else { UE_LOG(LogTemp, Error, TEXT("Tile '%s' does not have a mask material"), *GetName()); } for (AMonster* Monster: Monsters) { Monster->SwitchToBlack(); } } void ATile::ClearTile() { StaticMeshComponent->SetMaterial(0, TileMaterial); for (AMonster* Monster: Monsters) { Monster->Destroy(); } Monsters.Empty(); } TArray<FString> ATile::GetBoundingBoxDescriptionsOfMonsters() const { TArray<FString> result; //result.Add("Monster,Center_X,Center_Y,Width,Height"); for (AMonster* Monster: Monsters) { TArray<FString> MonsterDescription; FBox2D BoundingBox = Monster->GetScreenBoundingBox(); FVector2D Center = BoundingBox.GetCenter(); FVector2D Size = BoundingBox.GetSize(); FVector2D ScreenSize = FVector2D(1, 1); if (GEngine && GEngine->GameViewport) { GEngine->GameViewport->GetViewportSize(ScreenSize); } MonsterDescription.Add(Monster->GetMonsterName()); MonsterDescription.Add(FString::SanitizeFloat((ScreenSize.X - Center.X) / ScreenSize.X)); MonsterDescription.Add(FString::SanitizeFloat((ScreenSize.Y - Center.Y) / ScreenSize.Y)); MonsterDescription.Add(FString::SanitizeFloat(Size.X / ScreenSize.X)); MonsterDescription.Add(FString::SanitizeFloat(Size.Y / ScreenSize.Y)); result.Add(FString::Join(MonsterDescription, TEXT(","))); } return result; } int ATile::GetNumberSpawnPoints() const { return NumberSpawnPoints; }
26.874074
115
0.746692
[ "object" ]
2ad8b5b9ddc3203dacd2fe1703ca60ea33c903c7
530
cpp
C++
Problem101-150/p136_1.cpp
dingqunfei/LeetCode
c74a21ea56ee7b35308d2f387ef24ab29b031e24
[ "Apache-2.0" ]
null
null
null
Problem101-150/p136_1.cpp
dingqunfei/LeetCode
c74a21ea56ee7b35308d2f387ef24ab29b031e24
[ "Apache-2.0" ]
null
null
null
Problem101-150/p136_1.cpp
dingqunfei/LeetCode
c74a21ea56ee7b35308d2f387ef24ab29b031e24
[ "Apache-2.0" ]
null
null
null
/** * @file p136_1.cpp * @brief * @author dingqunfei (dqflying@gmail.com) * @version 1.0 * @date 2021-04-30 * * @copyright Copyright (c) 2021 DQFLYING * * @par : * * * Date : 2021-04-30 * Version : 1.0 * Author : dqflying * Lisence : * Description : * * * * */ class Solution { public: int singleNumber(vector<int>& nums) { int res = 0;; for(int i = 0; i < nums.size(); ++i) { res = res ^ nums[i]; } return res; } };
15.142857
44
0.471698
[ "vector" ]
2adc642537ca6ecedb4edd94ba785facb6e26710
1,397
cc
C++
src/FVPM/CircularQuadRule.cc
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
1
2020-10-21T01:56:55.000Z
2020-10-21T01:56:55.000Z
src/FVPM/CircularQuadRule.cc
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
src/FVPM/CircularQuadRule.cc
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
//---------------------------------Spheral++----------------------------------// // CircularQuadRule // // Created by JNJ, Sun Jul 11 12:50:51 PDT 2010 //----------------------------------------------------------------------------// #include "CircularQuadRule.hh" namespace Spheral { //------------------------------------------------------------------- template <typename Dimension> CircularQuadRule<Dimension>:: CircularQuadRule(const TableKernel<Dimension>& W): QuadRule<Dimension>(W) { } //------------------------------------------------------------------- //------------------------------------------------------------------- template <typename Dimension> CircularQuadRule<Dimension>:: ~CircularQuadRule() { } //------------------------------------------------------------------- //------------------------------------------------------------------- template <typename Dimension> void CircularQuadRule<Dimension>:: setDomain(const Vector& x1, const SymTensor& H1, const Vector& x2, const SymTensor& H2) { // We assume that the smoothing tensors are isotropic. double detH1 = H1.det(); double r1 = this->mW.kernelExtent() / Dimension::rootnu(detH1); double detH2 = H2.det(); double r2 = this->mW.kernelExtent() / Dimension::rootnu(detH2); setDomain(x1, r1, x2, r2); } //------------------------------------------------------------------- }
29.723404
80
0.413744
[ "vector" ]
2add2dc54b23f1573a3351e4f8a178373bee9aa1
24,546
cpp
C++
2019/18-2/src/main.cpp
rhymu8354/advent-of-code
f3f08fbadd1c92c2c342a518dc07be988ed78a53
[ "MIT" ]
10
2020-01-02T03:17:29.000Z
2021-05-14T11:35:40.000Z
2019/18-2/src/main.cpp
rhymu8354/advent-of-code
f3f08fbadd1c92c2c342a518dc07be988ed78a53
[ "MIT" ]
1
2019-12-13T22:49:45.000Z
2019-12-13T22:51:57.000Z
2019/18-2/src/main.cpp
rhymu8354/advent-of-code
f3f08fbadd1c92c2c342a518dc07be988ed78a53
[ "MIT" ]
1
2020-01-10T21:39:16.000Z
2020-01-10T21:39:16.000Z
/** * @file main.cpp * * This module holds the main() function, which is the entrypoint * to the program. * * © 2019 by Richard Walters */ #include <algorithm> #include <fstream> #include <functional> #include <inttypes.h> #include <limits> #include <map> #include <memory> #include <queue> #include <set> #include <sstream> #include <stdlib.h> #include <stdio.h> #include <stack> #include <string> #include <vector> #ifdef _WIN32 #include <crtdbg.h> #endif /* _WIN32 */ /** * This template is used to find a path from one position * to another, where the type of position is a template argument. */ template< typename T > struct PathFinding { /** * This structure represents a place reachable along a path from * a starting position. */ struct SearchStep { // Properties /** * This is the position of this step. */ T position; /** * This is the previous position that led to this position. */ T previous; /** * This is the cost incurred so far to reach this step. */ int cost = 0; // Methods /** * This is the default constructor of the class. */ SearchStep() = default; /** * This is used to construct the object in place * from its properties. * * @param[in] position * This is the position of this step. * * @param[in] previous * This is the previous position that led to this position. * * @param[in] cost * This is the cost incurred so far to reach this step. */ SearchStep( const T& position, const T& previous, unsigned int cost ) : position(position) , previous(previous) , cost(cost) { } /** * This is the sorting order comparison operator. * * @param[in] other * This is the other object to which to compare this object. * * @return * An indication of whether or not this object comes before * the other object is returned. */ bool operator<(const SearchStep& other) const { return cost > other.cost; } }; /** * This is the type of function which determines the immediate * neighbors of a given position. * * @param[in] position * This is the position for which to find neighbors. * * @return * The immediate neighbors of the given position are returned. */ typedef std::function< std::vector< T >(const T& position) > NeighborFunction; /** * This is the type of function which computes the cost * of moving from one position to another. * * @param[in] start * This is the starting position. * * @param[in] end * This is the end position. * * @return * The cost of moving from the start position to the end * position is returned. */ typedef std::function< int( const T& start, const T& end ) > CostFunction; /** * This structure holds information returned by the FindPath function. */ struct Path { /** * This indicates whether or not the destination can be reached. */ bool reachable = false; /** * This is the total estimated cost of reaching the * destination. */ int cost = 0; /** * These are the positions of each step from the starting * position to the destination. */ std::vector< T > steps; }; /** * This method finds a path from a given starting position * to a given destination. * * @param[in] startingPosition * This is the starting position from which to find * a path to the given destination. * * @param[in] destination * This is the position to which to find a path. * * @param[in] findNeighbors * This function is used to find the neighbors of given positions. * * @param[in] moveCost * This function computes the cost of moving from one position * to an adjacent position. * * @param[in] heuristic * This function estimates the remaining cost of moving from * a given position to another. * * @param[in] maxCost * If non-zero, this sets a maximum cost for the path to * find. * * @return * Information about the path from the given starting position * to the given destination is returned. */ static Path FindPath( const T& startingPosition, const T& destination, NeighborFunction findNeighbors, CostFunction moveCost, CostFunction heuristic, int maxCost = 0 ) { std::priority_queue< SearchStep > frontier; std::map< T, SearchStep > steps; frontier.emplace(startingPosition, startingPosition, 0); steps[startingPosition] = frontier.top(); while (!frontier.empty()) { auto lastStep = frontier.top(); if (lastStep.position == destination) { Path path; path.reachable = true; path.cost = steps[lastStep.position].cost; for (auto position = lastStep.position; position != startingPosition; position = steps[position].previous) { path.steps.push_back(position); } std::reverse(path.steps.begin(), path.steps.end()); return path; } frontier.pop(); for (const auto& nextStepPosition: findNeighbors(lastStep.position)) { auto nextStepCost = moveCost(lastStep.position, nextStepPosition); const auto nextStepHeuristic = heuristic(nextStepPosition, destination); nextStepCost += steps[lastStep.position].cost; if ( (maxCost > 0) && (nextStepCost + nextStepHeuristic > maxCost) ) { continue; } auto step = steps.find(nextStepPosition); if ( (step == steps.end()) || (nextStepCost < step->second.cost) ) { steps[nextStepPosition].cost = nextStepCost; steps[nextStepPosition].previous = lastStep.position; frontier.emplace( nextStepPosition, lastStep.position, nextStepCost + nextStepHeuristic ); } } } return Path(); } /** * This method finds all the places that are reachable from the * given starting position, and the total cost to reach them. * * @param[in] startingPosition * This is the starting position from which to find * all reachable places. * * @param[in] findNeighbors * This function is used to find the neighbors of given positions. * * @param[in] moveCost * This function computes the cost of moving from one position * to an adjacent position. * * @param[in] maxCost * If non-zero, this sets a maximum cost after which no more * reachable places are sought after. * * @return * A list of places and the total cost to reach them is returned. * This list is sorted by increasing total cost. */ static std::vector< SearchStep > FindReachablePlaces( const T& startingPosition, NeighborFunction findNeighbors, CostFunction moveCost, int maxCost = 0 ) { std::vector< SearchStep > places; std::priority_queue< SearchStep > frontier; std::map< T, SearchStep > steps; frontier.emplace(startingPosition, startingPosition, 0); steps[startingPosition] = frontier.top(); while (!frontier.empty()) { auto lastStep = frontier.top(); frontier.pop(); for (const auto& nextStepPosition: findNeighbors(lastStep.position)) { auto nextStepCost = moveCost(lastStep.position, nextStepPosition); nextStepCost += steps[lastStep.position].cost; if ( (maxCost > 0) && (nextStepCost > maxCost) ) { continue; } auto step = steps.find(nextStepPosition); if ( (step == steps.end()) || (nextStepCost < step->second.cost) ) { auto& nextStep = steps[nextStepPosition]; nextStep.position = nextStepPosition; nextStep.previous = lastStep.position; nextStep.cost = nextStepCost; frontier.emplace( nextStepPosition, lastStep.position, nextStepCost ); } } } for (const auto& step: steps) { if (step.first != startingPosition) { places.push_back(step.second); } } std::sort( places.begin(), places.end(), []( const SearchStep& a, const SearchStep& b ){ return a.cost < b.cost; } ); return places; } }; enum class Cell { Unexplored, Floor, Wall, OxygenSystem, Path, }; struct Position { int x = 0; int y = 0; Position() { } Position(int x, int y) : x(x) , y(y) { } bool operator==(const Position& other) const { return ( (x == other.x) && (y == other.y) ); } bool operator!=(const Position& other) const { return !(*this == other); } bool operator<(const Position& other) const { if (x < other.x) { return true; } else if (x > other.x) { return false; } else { return (y < other.y); } } Position& operator+=(const Position& other) { x += other.x; y += other.y; return *this; } Position operator+(const Position& other) { Position sum = *this; sum.x += other.x; sum.y += other.y; return sum; } }; intmax_t GetNextNumber( const std::string& input, size_t& pos ) { auto delimiter = input.find(',', pos); if (delimiter == std::string::npos) { delimiter = input.length(); } intmax_t number; if (sscanf(input.substr(pos, delimiter - pos).c_str(), "%" SCNdMAX, &number) != 1) { (void)fprintf(stderr, "Bad input detected at position %zu\n", pos); exit(1); } pos = delimiter + 1; return number; } struct Machine { size_t id = 0; size_t pos = 0; std::vector< intmax_t > numbers; std::vector< intmax_t > input; bool halted = false; intmax_t relativeBase = 0; void ExpandToFit(size_t index) { if (index >= numbers.size()) { numbers.resize(index + 1); } } size_t LoadIndex( size_t pos, int mode ) { switch (mode) { case 0: { // position const auto index = (size_t)numbers[pos]; return index; } break; case 2: { // relative const auto offset = numbers[pos]; const auto index = (size_t)(relativeBase + offset); return index; } break; default: { (void)fprintf(stderr, "Invalid index mode for offset %zu\n", pos); exit(1); } } return 0; } intmax_t LoadArgument( size_t pos, int mode ) { switch (mode) { case 0: { // position const auto index = (size_t)numbers[pos]; ExpandToFit(index); const auto arg = numbers[index]; return arg; } break; case 1: { // immediate const auto arg = numbers[pos]; return arg; } break; case 2: { // relative const auto offset = numbers[pos]; const auto index = (size_t)(relativeBase + offset); ExpandToFit(index); const auto arg = numbers[index]; return arg; } break; default: { (void)fprintf(stderr, "Invalid argument mode for offset %zu\n", pos); exit(1); } } return 0; } void Store( size_t index, intmax_t value ) { ExpandToFit(index); numbers[index] = value; } void Run(std::vector< intmax_t >& output) { while (!halted) { const auto opcode = numbers[pos] % 100; switch (opcode) { case 1: { // add const auto arg1 = LoadArgument(pos + 1, (numbers[pos] / 100) % 10); const auto arg2 = LoadArgument(pos + 2, (numbers[pos] / 1000) % 10); const auto index3 = LoadIndex(pos + 3, (numbers[pos] / 10000) % 10); Store(index3, arg1 + arg2); pos += 4; } break; case 2: { // multiply const auto arg1 = LoadArgument(pos + 1, (numbers[pos] / 100) % 10); const auto arg2 = LoadArgument(pos + 2, (numbers[pos] / 1000) % 10); const auto index3 = LoadIndex(pos + 3, (numbers[pos] / 10000) % 10); Store(index3, arg1 * arg2); pos += 4; } break; case 3: { // input const auto index = LoadIndex(pos + 1, (numbers[pos] / 100) % 10); if (input.empty()) { return; } const auto inputValue = input[0]; (void)input.erase(input.begin()); Store(index, inputValue); pos += 2; } break; case 4: { // output const auto outputValue = LoadArgument(pos + 1, (numbers[pos] / 100) % 10); output.push_back(outputValue); pos += 2; } break; case 5: { // jump-if-true const auto arg1 = LoadArgument(pos + 1, (numbers[pos] / 100) % 10); const auto arg2 = (size_t)LoadArgument(pos + 2, (numbers[pos] / 1000) % 10); if (arg1 != 0) { pos = arg2; } else { pos += 3; } } break; case 6: { // jump-if-false const auto arg1 = LoadArgument(pos + 1, (numbers[pos] / 100) % 10); const auto arg2 = (size_t)LoadArgument(pos + 2, (numbers[pos] / 1000) % 10); if (arg1 == 0) { pos = arg2; } else { pos += 3; } } break; case 7: { // less-than const auto arg1 = LoadArgument(pos + 1, (numbers[pos] / 100) % 10); const auto arg2 = LoadArgument(pos + 2, (numbers[pos] / 1000) % 10); const auto index3 = LoadIndex(pos + 3, (numbers[pos] / 10000) % 10); Store( index3, ( (arg1 < arg2) ? 1 : 0 ) ); pos += 4; } break; case 8: { // equals const auto arg1 = LoadArgument(pos + 1, (numbers[pos] / 100) % 10); const auto arg2 = LoadArgument(pos + 2, (numbers[pos] / 1000) % 10); const auto index3 = LoadIndex(pos + 3, (numbers[pos] / 10000) % 10); Store( index3, ( (arg1 == arg2) ? 1 : 0 ) ); pos += 4; } break; case 9: { // adjust relative base const auto arg1 = LoadArgument(pos + 1, (numbers[pos] / 100) % 10); relativeBase += arg1; pos += 2; } break; case 99: { // stop halted = true; } break; default: { // ERROR!! (void)fprintf(stderr, "Invalid opcode (%" PRIdMAX ")\n", opcode); exit(1); } break; } } printf("*** Machine %zu Halted ***\n", id); } }; std::vector< Position > Neighbors(const Position& position) { return { {position.x - 1, position.y}, {position.x + 1, position.y}, {position.x, position.y - 1}, {position.x, position.y + 1}, }; } int Cost( const std::vector< std::string >& lines, const std::set< char >& keys, const Position& end ) { const auto height = lines.size(); const auto width = lines[0].length(); const auto cell = lines[end.y][end.x]; if (cell == '#') { return 1000001; } else if (cell == '.') { return 1; } else if (cell == '@') { return 1; } else if ( (cell >= 'a') && (cell <= 'z') ) { return 1; } else if ( (cell >= 'A') && (cell <= 'Z') ) { if (keys.find(cell + 'a' - 'A') == keys.end()) { return 1000001; } else { return 1; } } else { return 0; } } int PositionHeuristic(const Position& start, const Position& end) { return ( abs(end.x - start.x) + abs(end.y - start.y) ); } std::string EncodePath( const std::vector< char >& keyOrder, const std::vector< Position >& positions, int steps ) { std::ostringstream buffer; bool first = true; for (const auto& position: positions) { if (!first) { buffer << ','; } first = false; buffer << position.x << ',' << position.y; } buffer << ',' << steps; buffer << ','; for (auto key: keyOrder) { buffer << key; } return buffer.str(); } void FindShortestPath( const std::vector< std::string >& lines, const std::set< char >& keySet, const std::vector< char >& keyOrder, const std::vector< Position >& positions, std::map< std::string, int >& pathsTried, int& bestSteps, int steps, size_t totalKeys ) { const auto path = EncodePath(keyOrder, positions, steps); const auto pathsTriedEntry = pathsTried.find(path); if ( (pathsTriedEntry != pathsTried.end()) && (steps >= pathsTriedEntry->second) ) { return; } printf("%s - %d\n", path.c_str(), bestSteps); if (keySet.size() == totalKeys) { printf("Found path with %d steps.\n", steps); bestSteps = ( (bestSteps == 0) ? steps : std::min(bestSteps, steps) ); return; } const auto height = lines.size(); const auto width = lines[0].length(); for (size_t i = 0; i < positions.size(); ++i) { const auto places = PathFinding< Position >::FindReachablePlaces( positions[i], Neighbors, [&](const Position& start, const Position& end){ return Cost(lines, keySet, end); }, 1000000 ); for (const auto& place: places) { const auto cell = lines[place.position.y][place.position.x]; if ( (cell >= 'a') && (cell <= 'z') && (keySet.find(cell) == keySet.end()) ) { if ( (bestSteps > 0) && (steps + place.cost >= bestSteps) ) { break; } std::set< char > nextKeySet = keySet; std::vector< char > nextKeyOrder = keyOrder; (void)nextKeySet.insert(cell); nextKeyOrder.push_back(cell); std::vector< Position > nextPositions = positions; nextPositions[i] = place.position; FindShortestPath( lines, nextKeySet, nextKeyOrder, nextPositions, pathsTried, bestSteps, steps + place.cost, totalKeys ); } } } pathsTried[path] = steps; } /** * This function is the entrypoint of the program. * * @param[in] argc * This is the number of command-line arguments given to the program. * * @param[in] argv * This is the array of command-line arguments given to the program. */ int main(int argc, char* argv[]) { #ifdef _WIN32 //_crtBreakAlloc = 18; _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif /* _WIN32 */ (void)setbuf(stdout, NULL); // Open the input file and read in the map. std::ifstream input("input.txt"); std::vector< std::string > lines; std::string line; while (std::getline(input, line)) { lines.push_back(std::move(line)); line.clear(); } const auto height = lines.size(); const auto width = lines[0].length(); Position position; size_t totalKeys = 0; std::map< char, Position > keyPositions; for (size_t y = 0; y < height; ++y) { for (size_t x = 0; x < width; ++x) { const auto cell = lines[y][x]; if (cell == '@') { position.x = (int)x; position.y = (int)y; } else if ( (cell >= 'a') && (cell <= 'z') ) { ++totalKeys; keyPositions[cell].x = (int)x; keyPositions[cell].y = (int)y; } } } printf( "Map is %zux%zu, entrance is at %dx%d, and there are %zu keys.\n", width, height, position.x, position.y, totalKeys ); // Split map into four quadrants lines[position.y - 1][position.x] = '#'; lines[position.y + 1][position.x] = '#'; lines[position.y][position.x - 1] = '#'; lines[position.y][position.x + 1] = '#'; // This is the solution worked out on paper. // // TODO: Code needs to be written to come up with this solution! const std::string solution = "om bg u v r t i n c fy zak p hl e x s d w q j "; std::vector< Position > positions; positions.push_back({position.x - 1, position.y - 1}); positions.push_back({position.x + 1, position.y - 1}); positions.push_back({position.x + 1, position.y + 1}); positions.push_back({position.x - 1, position.y + 1}); std::set< char > keySet; int steps = 0; for (size_t i = 0; i < solution.length(); ++i) { if (solution[i] == ' ') { continue; } const auto path = PathFinding< Position >::FindPath( positions[i % 4], keyPositions[solution[i]], Neighbors, [&](const Position& start, const Position& end){ return Cost(lines, keySet, end); }, PositionHeuristic, 1000000 ); printf("Advancing to key '%c' (%d steps)\n", solution[i], path.cost); steps += path.cost; positions[i % 4] = keyPositions[solution[i]]; (void)keySet.insert(solution[i]); } printf("Shortest path is %d steps.\n", steps); return EXIT_SUCCESS; }
30.080882
124
0.481382
[ "object", "vector" ]
2aede148aa97820b96337c62215ce32958996ed3
2,395
cpp
C++
tests/bytes.cpp
jmalmari/hid-rd
20dcabbd80fe6b7ac9e9ec4e1478a77f839939cb
[ "MIT" ]
1
2017-11-28T21:46:53.000Z
2017-11-28T21:46:53.000Z
tests/bytes.cpp
jmalmari/hid-rd
20dcabbd80fe6b7ac9e9ec4e1478a77f839939cb
[ "MIT" ]
null
null
null
tests/bytes.cpp
jmalmari/hid-rd
20dcabbd80fe6b7ac9e9ec4e1478a77f839939cb
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cstring> #include "hidrd/bytes.hpp" using hidrd::bytes::Bytes; using hidrd::bytes::Byte; using hidrd::bytes::ByteType; typedef Bytes< Byte<'a'>, Byte<'b'>, Byte<'c'>, Byte<'d'> > Bytes1; typedef Bytes< Bytes<Byte<'a'>>, Bytes<Byte<'b'>, Byte<'c'>, Byte<'d'>> > Bytes2; typedef Bytes< Bytes< Bytes< Bytes< Byte<'a'> > > > > Bytes3; typedef Bytes< Bytes< Byte<'1'>, Byte<'2'>, Byte<'3'> >, Bytes< Byte<'4'>, Byte<'5'>, Byte<'6'> > > Bytes4; typedef Bytes< Byte<'1'>, Bytes< Bytes<Byte<'2'>> > > Bytes5; typedef Bytes< Bytes1, Bytes4, Bytes1 > Bytes6; typedef Bytes1::Flatten Flatten1; typedef Bytes2::Flatten Flatten2; typedef Bytes3::Flatten Flatten3; typedef Bytes4::Flatten Flatten4; typedef Bytes5::Flatten Flatten5; typedef Bytes6::Flatten Flatten6; struct TestItem { std::string name; std::string expected; ByteType const * const data; std::size_t dataSize; }; #define APPEND_DATA(Type) &Type::data[0], Type::data.size() TestItem items[] = { { "simple list", "abcd", APPEND_DATA(Flatten1) }, { "nested list", "abcd", APPEND_DATA(Flatten2) }, { "deep", "a", APPEND_DATA(Flatten3) }, { "two lists", "123456", APPEND_DATA(Flatten4) }, { "byte followed by list", "12", APPEND_DATA(Flatten5) }, { "complex", "abcd123456abcd", APPEND_DATA(Flatten6) } }; int main(int, char*[]) { for (auto const& item : items) { if (item.expected.size() != item.dataSize) { std::cout << "Test \"" << item.name << "\" failed.\n"; std::cout << "Data length don't match." << std::endl; return 1; } else if (memcmp(item.expected.c_str(), item.data, item.dataSize)) { std::cout << "Test " << item.name << " failed.\n"; std::cout << "Data don't match. Expected " << item.expected << ", got:\n"; for (std::size_t i = 0; i < item.dataSize; ++i) { ByteType byte = item.data[i]; std::cout << std::hex << "0x" << (0xff & byte) << "(" << byte << ") "; } std::cout << std::endl; return 2; } } return 0; }
24.947917
86
0.51858
[ "vector" ]
6307ffd1265da9502317782176c81d3d5e7690c2
15,342
cpp
C++
Game/Source/Scene.cpp
TheGewehr/D-Platformer
a6b5ac312f64a989bf1932d62a0967829f07778c
[ "MIT" ]
null
null
null
Game/Source/Scene.cpp
TheGewehr/D-Platformer
a6b5ac312f64a989bf1932d62a0967829f07778c
[ "MIT" ]
null
null
null
Game/Source/Scene.cpp
TheGewehr/D-Platformer
a6b5ac312f64a989bf1932d62a0967829f07778c
[ "MIT" ]
2
2021-12-14T12:22:06.000Z
2021-12-14T12:25:56.000Z
#include "App.h" #include "Input.h" #include "Textures.h" #include "Audio.h" #include "Render.h" #include "Physics.h" #include "Window.h" #include "Scene.h" #include "Player.h" #include "Physics.h" #include "Map.h" #include "PathFinding.h" #include "WalkingEnemy.h" #include "FlyingEnemy.h" #include "EntityManager.h" #include "Entity.h" #include "LevelManager.h" #include "GuiManager.h" #include "SDL_mixer/include/SDL_mixer.h" #include <iostream> #include "Defs.h" #include "Log.h" enum class ENTITY_TYPE; Scene::Scene(bool startEnabled) : Module() { active = startEnabled; name.Create("scene"); pugi::xml_document configFile; pugi::xml_node config; pugi::xml_node configApp; config = app->LoadConfig(configFile).child("map"); app->pathfinding = new PathFinding(true); app->physics = new Physics(true); app->map = new Map(true); app->entitymanager = new EntityManager(true); List<Module*> a; a.add(app->entitymanager); a.add(app->physics); a.add(app->pathfinding); a.add(app->map); app->modules.InsertAfter(0, a); stop_phys = false; app->map->Awake(config); app->pathfinding->Start(); app->physics->Start(); app->map->Start(); Start(); app->entitymanager->Start(); } // Destructor Scene::~Scene() { delete(app->pathfinding); delete(app->physics); delete(app->map); delete(app->entitymanager); } // Called before render is available bool Scene::Awake() { //LOG("Loading Scene"); bool ret = true; return ret; } // Called before the first frame bool Scene::Start() { app->physics->world = new b2World(b2Vec2(GRAVITY_X, -GRAVITY_Y)); app->physics->world->SetContactListener(app->physics); app->entitymanager->player->SetPlayerLifes(3); // Creating buttons // Level 1 Box2D points if (currentLevel != 2) { // Show level 1 Box2D points } // Level 2 Box2D points if (currentLevel == 2) { // Show level 2 Box2D points } // List of Box2D points int map[142] = { -2, -3, -2, 417, 127, 417, 127, 444, 352, 444, 352, 417, 383, 417, 383, 571, 455, 573, 448, 480, 511, 417, 606, 417, 606, 587, 704, 593, 705, 481, 705, 353, 832, 225, 1310, 225, 1310, 285, 831, 286, 831, 417, 927, 417, 929, 445, 1028, 445, 1031, 418, 1047, 418, 1050, 445, 1159, 444, 1159, 417, 1176, 417, 1179, 442, 1278, 442, 1280, 417, 1312, 417, 1439, 288, 1504, 288, 1600, 383, 1600, 413, 1855, 413, 1855, 385, 1951, 288, 2015 ,288, 2015, 600, 2112, 600, 2112, 319, 2080, 319, 2080, 288, 2175, 288, 2175, 319, 2143, 319, 2143, 600, 2240, 600, 2240, 319, 2208, 319, 2208, 288, 2303, 288, 2303, 319, 2271, 319, 2271, 600, 2368, 600, 2368, 319, 2336, 319, 2336, 288, 2431, 288, 2431, 319, 2399, 319, 2399, 600, 2496, 600, 2496, 288, 2570, 288, 2570, -3 }; int platform01[8] = { 129, 289, 383, 288, 383, 317, 129, 317 }; int platform02[8] = { 448, 192, 480, 192, 480, 224, 449, 224 }; int platform03[8] = { 544, 256, 607, 256, 607, 286, 545, 286 }; int platform04[8] = { 1664, 288, 1664, 319, 1695, 319, 1695, 288 }; int platform05[8] = { 1760, 288, 1760, 319, 1791, 319, 1791, 288 }; int platform06[8] = { 2048, 128, 2048, 159, 2079, 159, 2079, 128 }; int platform07[8] = { 2176, 128, 2176, 159, 2207, 159, 2207, 128 }; int platform08[8] = { 2304, 128, 2304, 159, 2335, 159, 2335, 128 }; int platform09[8] = { 2432, 128, 2432, 159, 2463, 159, 2463, 128 }; // id's : // 0 map // 1 player // 2 water // 3 holes // 4 win // map static_chains.add(app->physics->CreateStaticChain(0, 0, map, 142)); static_chains.getLast()->data->id = 0; static_chains.getLast()->data->listener = this; static_chains.add(app->physics->CreateStaticChain(0, 0, platform01, 8)); static_chains.getLast()->data->id = 0; static_chains.getLast()->data->listener = this; static_chains.add(app->physics->CreateStaticChain(0, 0, platform02, 8)); static_chains.getLast()->data->id = 0; static_chains.getLast()->data->listener = this; static_chains.add(app->physics->CreateStaticChain(0, 0, platform03, 8)); static_chains.getLast()->data->id = 0; static_chains.getLast()->data->listener = this; static_chains.add(app->physics->CreateStaticChain(0, 0, platform04, 8)); static_chains.getLast()->data->id = 0; static_chains.getLast()->data->listener = this; static_chains.add(app->physics->CreateStaticChain(0, 0, platform05, 8)); static_chains.getLast()->data->id = 0; static_chains.getLast()->data->listener = this; static_chains.add(app->physics->CreateStaticChain(0, 0, platform06, 8)); static_chains.getLast()->data->id = 0; static_chains.getLast()->data->listener = this; static_chains.add(app->physics->CreateStaticChain(0, 0, platform07, 8)); static_chains.getLast()->data->id = 0; static_chains.getLast()->data->listener = this; static_chains.add(app->physics->CreateStaticChain(0, 0, platform08, 8)); static_chains.getLast()->data->id = 0; static_chains.getLast()->data->listener = this; static_chains.add(app->physics->CreateStaticChain(0, 0, platform09, 8)); static_chains.getLast()->data->id = 0; static_chains.getLast()->data->listener = this; // FlyingEnemiesList.add(app->flyingenemy->CreateFlyingEnemy(50,50)); // water sensor_water01 = app->physics->CreateRectangleSensor(240, 455, 250, 60); sensor_water01->id = 2; sensor_water01->listener = this; sensor_water02 = app->physics->CreateRectangleSensor(1060, 455, 500, 60); sensor_water02->id = 2; sensor_water02->listener = this; sensor_water03 = app->physics->CreateRectangleSensor(1727, 420, 265, 60); sensor_water03->id = 2; sensor_water03->listener = this; // holes sensor_fall01 = app->physics->CreateRectangleSensor(420, 550, 100, 60); sensor_fall01->id = 3; sensor_fall01->listener = this; sensor_fall02 = app->physics->CreateRectangleSensor(660, 550, 110, 85); sensor_fall02->id = 3; sensor_fall02->listener = this; sensor_fall03 = app->physics->CreateRectangleSensor(2255, 550, 523, 100); sensor_fall03->id = 3; sensor_fall03->listener = this; // win sensor_win = app->physics->CreateRectangleSensor(2550, 310, 20, 85); sensor_win->id = 4; sensor_win->listener = this; if (app->map->Load("level1_walk.tmx") == true) { int w, h; uchar* data = NULL; if (app->map->CreateWalkabilityMap(w, h, &data, 1)) app->pathfinding->SetMap(w, h, data); RELEASE_ARRAY(data); } originTex = app->tex->Load("Assets/sprites/Cross.png"); // Uploading the assets // app->map->Load("level1.tmx"); app->audio->PlayMusic("Assets/audio/music/music_spy.ogg"); img = app->tex->Load("Assets/background/Background.png"); winTexture= app->tex->Load("Assets/sprites/WinningScreen(1).png"); if (app->entitymanager->player->Awake() == 0) { app->entitymanager->player->Awake(); } gui_lifes01 = (GuiButton*)app->guiManager->CreateGuiControl(GuiControlType::DISPLAY, 9, "LifesDisplay", { -app->render->camera.w, 0, 25, 25 }, this); gui_lifes02 = (GuiButton*)app->guiManager->CreateGuiControl(GuiControlType::DISPLAY, 9, "LifesDisplay.", { -app->render->camera.w + 50, 0, 25, 25 }, this); gui_lifes03 = (GuiButton*)app->guiManager->CreateGuiControl(GuiControlType::DISPLAY, 9, "LifesDisplay..", { -app->render->camera.w + 100, 0, 25, 25 }, this); gui_lifes04 = (GuiButton*)app->guiManager->CreateGuiControl(GuiControlType::DISPLAY, 9, "LifesDisplay...", { -app->render->camera.w + 150, 0, 25, 25 }, this); //if (app->entitymanager->player->GetPlayerLifes()==4) //{ // gui_lifes04 = (GuiButton*)app->guiManager->CreateGuiControl(GuiControlType::DISPLAY, 9, "LifesDisplay", { -app->render->camera.w + 150, 0, 25, 25 }, this); //} //if (app->entitymanager->player->GetPlayerLifes()==3) //{ // gui_lifes03 = (GuiButton*)app->guiManager->CreateGuiControl(GuiControlType::DISPLAY, 9, "LifesDisplay", { -app->render->camera.w + 100, 0, 25, 25 }, this); //} //if (app->entitymanager->player->GetPlayerLifes()==2) //{ // gui_lifes02 = (GuiButton*)app->guiManager->CreateGuiControl(GuiControlType::DISPLAY, 9, "LifesDisplay", { -app->render->camera.w + 50, 0, 25, 25 }, this); //} //if (app->entitymanager->player->GetPlayerLifes()==1) //{ // gui_lifes01 = (GuiButton*)app->guiManager->CreateGuiControl(GuiControlType::DISPLAY, 9, "LifesDisplay", { -app->render->camera.w, 0, 25, 25 }, this); //} return true; } // Called each loop iteration bool Scene::PreUpdate() { gui_lifes01->SetPos(app->render->camera.x, 430); gui_lifes02->SetPos(app->render->camera.x+50, 430); gui_lifes03->SetPos(app->render->camera.x+100, 430); gui_lifes04->SetPos(app->render->camera.x+150, 430); return true; } // Called each loop iteration bool Scene::Update(float dt) { app->render->DrawTexture(img, 0, 0, NULL); // L02: DONE 3: Request Load / Save when pressing L/S if (app->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN) app->LoadGameRequest(); if (app->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN) app->SaveGameRequest(); //std::cout << " " << app->player->xposition << " " << app->player->yposition <<std::endl; if ((app->input->GetKey(SDL_SCANCODE_F3) == KEY_DOWN) || (app->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN)) { //app->audio->PlayFx(app->lvlmanager->ehit_fx); //app->audio->PlayFx(app->lvlmanager->pdeath_fx); ResetLevel(); } //app->guiManager->DestroyGuiControl(gui_lifes03); //app->guiManager->DestroyGuiControl(gui_lifes04); if (app->entitymanager->player->GetPlayerLifes() == 4) { //if (gui_lifes04 != nullptr) //{ // app->guiManager->DestroyGuiControl(gui_lifes04); //} gui_lifes04->id = 9; gui_lifes03->id = 9; gui_lifes02->id = 9; gui_lifes01->id = 9; } if (app->entitymanager->player->GetPlayerLifes() == 3) { //if (gui_lifes04 != nullptr) //{ // app->guiManager->DestroyGuiControl(gui_lifes04); //} gui_lifes04->id = 10; gui_lifes03->id = 9; gui_lifes02->id = 9; gui_lifes01->id = 9; } if (app->entitymanager->player->GetPlayerLifes() == 2) { gui_lifes04->id = 10; gui_lifes03->id = 10; gui_lifes02->id = 9; gui_lifes01->id = 9; } if (app->entitymanager->player->GetPlayerLifes() == 1) { gui_lifes04->id = 10; gui_lifes03->id = 10; gui_lifes02->id = 10; gui_lifes01->id = 9; } if (app->entitymanager->player->GetPlayerLifes() == 0) { gui_lifes04->id = 10; gui_lifes03->id = 10; gui_lifes02->id = 10; gui_lifes01->id = 10; } else { } //app->entitymanager->player->GetPlayerLifes(); //app->render->DrawTexture(img, 380, 100); // Placeholder not needed any more // Draw map app->map->Draw(); // L03: DONE 7: Set the window title with map/tileset info // SString title("Map:%dx%d Tiles:%dx%d Tilesets:%d", // app->map->mapData.width, app->map->mapData.height, // app->map->mapData.tileWidth, app->map->mapData.tileHeight, // app->map->mapData.tilesets.count()); // // app->win->SetTitle(title.GetString()); //app->collisions->AddCollider(); if (app->entitymanager->player->GetPlayerWin()==true) { SDL_Rect U = { 0, 0, 1080, 480 }; app->render->DrawTexture(winTexture, app->render->camera.x, app->render->camera.y, &U); gui_lifes04->id = 10; gui_lifes03->id = 10; gui_lifes02->id = 10; gui_lifes01->id = 10; } return true; } // Called each loop iteration bool Scene::PostUpdate() { bool ret = true; if (app->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false; return ret; } // Used to pass to the second level bool Scene::PassLevelCondition() { if (app->entitymanager->player->GetPlayerWin() == true) { if (app->entitymanager->player->GetPlayerLifes() > 0) { return true; } } else { return false; } } // Win and Loss screens and consequences bool Scene::WinLoseCondition() { if (PassLevelCondition() == true) { // Show winning screen // Destroy all the chains return currentLevel = 2; } else if (app->entitymanager->player->GetPlayerLifes() < 1) { // Show loosing screen // Press x to restart the level } } // Called before quitting bool Scene::CleanUp() { //LOG("Freeing scene"); app->DeleteModule(app->pathfinding); app->DeleteModule(app->physics); app->DeleteModule(app->map); app->DeleteModule(app->entitymanager); app->entitymanager->CleanUp(); return true; } void Scene::OnCollision(PhysBody* bodyA, PhysBody* bodyB) { /*if (bodyB == nullptr) { } else { if ((bodyA->id == 1) && (bodyB->id == 2)) { if (app->entitymanager->player->GetPlayerLifes() > 0) { // fall in water loose one life app->audio->PlayFx(water_fx); //app->player->life app->entitymanager->player->SetPlayerLifes(app->entitymanager->player->GetPlayerLifes() - 1); bodyA->body->ApplyLinearImpulse({ 0, -3.5f}, app->entitymanager->player->EntityCollider->GetPosition_(), true); } else { //app->player->currentAnimation = &app->player->deathFromLeftAnim; //app->player->SetPlayerLifes(3); } } else if ((bodyA->id == 1) && (bodyB->id == 3)) { // fall and loose if (app->entitymanager->player->GetPlayerLifes() > 0) { app->audio->PlayFx(fall_fx); app->entitymanager->player->SetPlayerLifes(app->entitymanager->player->GetPlayerLifes() - 1); bodyA->body->ApplyLinearImpulse({ 0, -5.5f }, app->entitymanager->player->EntityCollider->GetPosition_(), true); } else { //app->player->currentAnimation=&app->player->deathFromRightAnim; //app->player->SetPlayerLifes(3); } } else if ((bodyA->id == 1) && (bodyB->id == 0)) { if (app->entitymanager->player->GetPlayerLifes() > 0) { } else { //app->player->currentAnimation=&app->player->deathFromRightAnim; app->entitymanager->player->deathAnimAllowed = true; //app->player->SetPlayerLifes(3); } } else if ((bodyA->id == 1) && (bodyB->id == 4)) { if (app->entitymanager->player->GetPlayerLifes() > 0) { Mix_HaltMusic(); app->audio->PlayFx(win_fx); app->entitymanager->player->SetPlayerWin(true); } else { } } }*/ } void Scene::ResetLevel() { b2Vec2 v; //player v.x = PIXEL_TO_METERS(16); v.y = PIXEL_TO_METERS(16); app->entitymanager->player->SetPlayerLifes(4); app->entitymanager->player->isAlive = true; app->entitymanager->player->deathAnimAllowed = false; app->entitymanager->player->SetPlayerWin(false); app->audio->PlayMusic("Assets/audio/music/music_spy.ogg"); app->entitymanager->player->GetColHitbox()->body->SetTransform(v, 0); // Walking Enemy v.x = PIXEL_TO_METERS(app->map->MapToWorld(30, 6).x); v.y = PIXEL_TO_METERS(app->map->MapToWorld(30, 6).y); app->entitymanager->walkingEnemies->lifes = 2; app->entitymanager->walkingEnemies->isAlive = true; app->entitymanager->walkingEnemies->deathAnimAllowed = false; app->entitymanager->walkingEnemies->statesInt = 0; app->entitymanager->walkingEnemies->EntityCollider->body->SetAwake(true); app->entitymanager->walkingEnemies->EntityCollider->body->SetTransform(v, 0); // Flying enemy v.x = PIXEL_TO_METERS(300); v.y = PIXEL_TO_METERS(150); app->entitymanager->flyingEnemies->lifes = 2; app->entitymanager->flyingEnemies->isAlive = true; app->entitymanager->flyingEnemies->deathAnimAllowed = false; app->entitymanager->flyingEnemies->statesInt = 0; app->entitymanager->flyingEnemies->EntityCollider->body->SetAwake(true); app->entitymanager->flyingEnemies->EntityCollider->body->SetTransform(v, 0); }
22.495601
159
0.665037
[ "render" ]
debd3f342040928eadc6907fecaf61d36793bc28
2,640
cpp
C++
src/RodinExternal/MMG/Mesh3D.cpp
carlos-brito-pacheco/rodin
f2c946b290ebb2487a21c617de01be91a0692c72
[ "BSL-1.0" ]
1
2021-12-02T19:04:38.000Z
2021-12-02T19:04:38.000Z
src/RodinExternal/MMG/Mesh3D.cpp
cbritopacheco/rodin
f2c946b290ebb2487a21c617de01be91a0692c72
[ "BSL-1.0" ]
null
null
null
src/RodinExternal/MMG/Mesh3D.cpp
cbritopacheco/rodin
f2c946b290ebb2487a21c617de01be91a0692c72
[ "BSL-1.0" ]
null
null
null
/* * Copyright Carlos BRITO PACHECO 2021 - 2022. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at * https://www.boost.org/LICENSE_1_0.txt) */ #include <limits> #include <cstring> #include <fstream> #include "Rodin/Alert/Exception.h" #include "Rodin/Alert/Warning.h" #include "Utility.h" #include "Mesh3D.h" namespace Rodin::External::MMG { Mesh3D::Mesh3D() { m_mesh = nullptr; auto calloc = [this]() { // Returns false on fail MMG5_SAFE_CALLOC(m_mesh, 1, MMG5_Mesh, return false); // Returns true on success return true; }; if (!calloc()) Alert::Exception("Failed to allocate memory for the mesh").raise(); m_mesh->dim = 3; m_mesh->ver = 2; m_mesh->nsols = 0; MMG3D_Set_commonFunc(); MMG3D_Init_parameters(m_mesh); MMG3D_Init_fileNames(m_mesh, nullptr); // Verbosity is high when in Debug MMG3D_Set_iparameter( getHandle(), nullptr, MMG3D_IPARAM_verbose, VERBOSITY_LEVEL); } Mesh3D::Mesh3D(const Mesh3D& other) : Mesh3D() { MMG5_Mesh_Copy(other.getHandle(), getHandle()); } Mesh3D::Mesh3D(Mesh3D&& other) { m_mesh = other.m_mesh; other.m_mesh = nullptr; } Mesh3D::~Mesh3D() { if (m_mesh) MMG3D_Free_all(MMG5_ARG_start, MMG5_ARG_ppMesh, &m_mesh, MMG5_ARG_end); } Mesh3D& Mesh3D::load(const boost::filesystem::path& filename) { if (!MMG3D_loadMesh(getHandle(), filename.c_str())) { Alert::Exception( "Failed to open file for reading: " + filename.string()).raise(); } return *this; } void Mesh3D::save(const boost::filesystem::path& filename) { if (!MMG3D_saveMesh(getHandle(), filename.c_str())) { Alert::Exception( "Failed to open file for writing: " + filename.string()).raise(); } } int Mesh3D::count(Mesh3D::Entity e) const { switch (e) { case Entity::Vertex: return getHandle()->np; case Entity::Edge: return getHandle()->na; case Entity::Triangle: return getHandle()->nt; case Entity::Tetrahedra: return getHandle()->ne; default: Alert::Exception("Unknown Mesh3D::Entity").raise(); } return 0; } MMG5_pMesh& Mesh3D::getHandle() { return m_mesh; } const MMG5_pMesh& Mesh3D::getHandle() const { return m_mesh; } }
22.372881
80
0.572348
[ "mesh" ]
debf0729bbc7f53bcb7c494fc41f22a045ffee78
99,739
cc
C++
alljoyn/alljoyn_core/router/ns/IpNsProtocol.cc
WigWagCo/alljoyn
1b148edd934882ca32fd319af86a5a927f9d35a7
[ "0BSD" ]
null
null
null
alljoyn/alljoyn_core/router/ns/IpNsProtocol.cc
WigWagCo/alljoyn
1b148edd934882ca32fd319af86a5a927f9d35a7
[ "0BSD" ]
null
null
null
alljoyn/alljoyn_core/router/ns/IpNsProtocol.cc
WigWagCo/alljoyn
1b148edd934882ca32fd319af86a5a927f9d35a7
[ "0BSD" ]
null
null
null
/** * @file * The simple name service protocol implementation */ /****************************************************************************** * Copyright (c) 2010-2014, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #include <assert.h> #include <qcc/Debug.h> #include <qcc/SocketTypes.h> #include <qcc/IPAddress.h> #include <qcc/StringUtil.h> #include "IpNsProtocol.h" #define QCC_MODULE "NS" // // Strangely, Android doesn't define the IPV4 presentation format string length // even though it does define the IPv6 version. // #ifndef INET_ADDRSTRLEN #define INET_ADDRSTRLEN 16 #endif using namespace std; using namespace qcc; namespace ajn { _Packet::_Packet() : m_timer(0), m_destination("0.0.0.0", 0), m_destinationSet(false), m_interfaceIndex(-1), m_interfaceIndexSet(false), m_addressFamily(qcc::QCC_AF_UNSPEC), m_addressFamilySet(false), m_retries(0), m_tick(0), m_version(0) { } _Packet::~_Packet() { }; StringData::StringData() : m_size(0) { } StringData::~StringData() { } void StringData::Set(qcc::String string) { m_size = string.size(); m_string = string; } qcc::String StringData::Get(void) const { return m_string; } size_t StringData::GetSerializedSize(void) const { return 1 + m_size; } size_t StringData::Serialize(uint8_t* buffer) const { QCC_DbgPrintf(("StringData::Serialize(): %s to buffer 0x%x", m_string.c_str(), buffer)); assert(m_size == m_string.size()); buffer[0] = static_cast<uint8_t>(m_size); memcpy(reinterpret_cast<void*>(&buffer[1]), const_cast<void*>(reinterpret_cast<const void*>(m_string.c_str())), m_size); return 1 + m_size; } size_t StringData::Deserialize(uint8_t const* buffer, uint32_t bufsize) { QCC_DbgPrintf(("StringData::Deserialize()")); // // If there's not enough data in the buffer to even get the string size out // then bail. // if (bufsize < 1) { QCC_DbgPrintf(("StringData::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } m_size = buffer[0]; --bufsize; // // If there's not enough data in the buffer then bail. // if (bufsize < m_size) { QCC_DbgPrintf(("StringData::Deserialize(): Insufficient bufsize %d", bufsize)); m_size = 0; return 0; } if (m_size > 0) { m_string.assign(reinterpret_cast<const char*>(buffer + 1), m_size); } else { m_string.clear(); } QCC_DbgPrintf(("StringData::Deserialize(): %s from buffer", m_string.c_str())); return 1 + m_size; } IsAt::IsAt() : m_version(0), m_flagG(false), m_flagC(false), m_flagT(false), m_flagU(false), m_flagS(false), m_flagF(false), m_flagR4(false), m_flagU4(false), m_flagR6(false), m_flagU6(false), m_port(0), m_reliableIPv4Port(0), m_unreliableIPv4Port(0), m_reliableIPv6Port(0), m_unreliableIPv6Port(0) { } IsAt::~IsAt() { } void IsAt::SetGuid(const qcc::String& guid) { m_guid = guid; m_flagG = true; } qcc::String IsAt::GetGuid(void) const { return m_guid; } void IsAt::SetPort(uint16_t port) { m_port = port; } uint16_t IsAt::GetPort(void) const { return m_port; } void IsAt::ClearIPv4(void) { m_ipv4.clear(); m_flagF = false; } void IsAt::SetIPv4(qcc::String ipv4) { m_ipv4 = ipv4; m_flagF = true; } qcc::String IsAt::GetIPv4(void) const { return m_ipv4; } void IsAt::ClearIPv6(void) { m_ipv6.clear(); m_flagS = false; } void IsAt::SetIPv6(qcc::String ipv6) { m_ipv6 = ipv6; m_flagS = true; } qcc::String IsAt::GetIPv6(void) const { return m_ipv6; } void IsAt::ClearReliableIPv4(void) { m_reliableIPv4Address.clear(); m_reliableIPv4Port = 0; m_flagR4 = false; } void IsAt::SetReliableIPv4(qcc::String addr, uint16_t port) { m_reliableIPv4Address = addr; m_reliableIPv4Port = port; m_flagR4 = true; } qcc::String IsAt::GetReliableIPv4Address(void) const { return m_reliableIPv4Address; } uint16_t IsAt::GetReliableIPv4Port(void) const { return m_reliableIPv4Port; } void IsAt::ClearUnreliableIPv4(void) { m_unreliableIPv4Address.clear(); m_unreliableIPv4Port = 0; m_flagU4 = false; } void IsAt::SetUnreliableIPv4(qcc::String addr, uint16_t port) { m_unreliableIPv4Address = addr; m_unreliableIPv4Port = port; m_flagU4 = true; } qcc::String IsAt::GetUnreliableIPv4Address(void) const { return m_unreliableIPv4Address; } uint16_t IsAt::GetUnreliableIPv4Port(void) const { return m_unreliableIPv4Port; } void IsAt::ClearReliableIPv6(void) { m_reliableIPv6Address.clear(); m_reliableIPv6Port = 0; m_flagR6 = false; } void IsAt::SetReliableIPv6(qcc::String addr, uint16_t port) { m_reliableIPv6Address = addr; m_reliableIPv6Port = port; m_flagR6 = true; } qcc::String IsAt::GetReliableIPv6Address(void) const { return m_reliableIPv6Address; } uint16_t IsAt::GetReliableIPv6Port(void) const { return m_reliableIPv6Port; } void IsAt::ClearUnreliableIPv6(void) { m_unreliableIPv6Address.clear(); m_unreliableIPv6Port = 0; m_flagU6 = false; } void IsAt::SetUnreliableIPv6(qcc::String addr, uint16_t port) { m_unreliableIPv6Address = addr; m_unreliableIPv6Port = port; m_flagU6 = true; } qcc::String IsAt::GetUnreliableIPv6Address(void) const { return m_unreliableIPv6Address; } uint16_t IsAt::GetUnreliableIPv6Port(void) const { return m_unreliableIPv6Port; } void IsAt::Reset(void) { m_names.clear(); } void IsAt::AddName(qcc::String name) { m_names.push_back(name); } void IsAt::RemoveName(uint32_t index) { if (index < m_names.size()) { m_names.erase(m_names.begin() + index); } } uint32_t IsAt::GetNumberNames(void) const { return m_names.size(); } qcc::String IsAt::GetName(uint32_t index) const { assert(index < m_names.size()); return m_names[index]; } size_t IsAt::GetSerializedSize(void) const { size_t size; // // The message version is in the least significant nibble of the version. // We don't care about the peer name service protocol version which is // meta-data about the other side and is in the most significant nibble. // switch (m_version & 0xf) { case 0: // // We have one octet for type and flags, one octet for count and // two octets for port. Four octets to start. // size = 4; // // If the F bit is set, we are going to include an IPv4 address // which is 32 bits long; // if (m_flagF) { size += 32 / 8; } // // If the S bit is set, we are going to include an IPv6 address // which is 128 bits long; // if (m_flagS) { size += 128 / 8; } // // Let the string data decide for themselves how long the rest of the // message will be. The rest of the message will be a possible GUID // string and the names. // if (m_flagG) { StringData s; s.Set(m_guid); size += s.GetSerializedSize(); } for (uint32_t i = 0; i < m_names.size(); ++i) { StringData s; s.Set(m_names[i]); size += s.GetSerializedSize(); } break; case 1: // // We have one octet for type and flags, one octet for count and // two octets for the transport mask. Four octets to start. // size = 4; // // If the R4 bit is set, we are going to include an IPv4 address // which is 32 bits long and a port which is 16 bits long. // if (m_flagR4) { size += 6; } // // If the U4 bit is set, we are going to include an IPv4 address // which is 32 bits long and a port which is 16 bits long. // if (m_flagU4) { size += 6; } // // If the R6 bit is set, we are going to include an IPv6 address // which is 128 bits long and a port which is 16 bits long. // if (m_flagR6) { size += 18; } // // If the U6 bit is set, we are going to include an IPv6 address // which is 32 bits long and a port which is 16 bits long. // if (m_flagU6) { size += 18; } // // Let the string data decide for themselves how long the rest of the // message will be. The rest of the message will be a possible GUID // string and the names. // if (m_flagG) { StringData s; s.Set(m_guid); size += s.GetSerializedSize(); } for (uint32_t i = 0; i < m_names.size(); ++i) { StringData s; s.Set(m_names[i]); size += s.GetSerializedSize(); } break; default: assert(false && "IsAt::GetSerializedSize(): Unexpected version"); QCC_LogError(ER_WARNING, ("IsAt::GetSerializedSize(): Unexpected version %d", m_version & 0xf)); size = 0; break; } return size; } size_t IsAt::Serialize(uint8_t* buffer) const { QCC_DbgPrintf(("IsAt::Serialize(): to buffer 0x%x", buffer)); // // We keep track of the size so testers can check coherence between // GetSerializedSize() and Serialize() and Deserialize(). // size_t size = 0; uint8_t typeAndFlags; uint8_t* p = NULL; // // The message version is in the least significant nibble of the version. // We don't care about the peer name service protocol version which is // meta-data about the other side and is in the most significant nibble. // switch (m_version & 0xf) { case 0: // // The first octet is type (M = 1) and flags. // typeAndFlags = 1 << 6; if (m_flagG) { QCC_DbgPrintf(("IsAt::Serialize(): G flag")); typeAndFlags |= 0x20; } if (m_flagC) { QCC_DbgPrintf(("IsAt::Serialize(): C flag")); typeAndFlags |= 0x10; } if (m_flagT) { QCC_DbgPrintf(("IsAt::Serialize(): T flag")); typeAndFlags |= 0x8; } if (m_flagU) { QCC_DbgPrintf(("IsAt::Serialize(): U flag")); typeAndFlags |= 0x4; } if (m_flagS) { QCC_DbgPrintf(("IsAt::Serialize(): S flag")); typeAndFlags |= 0x2; } if (m_flagF) { QCC_DbgPrintf(("IsAt::Serialize(): F flag")); typeAndFlags |= 0x1; } buffer[0] = typeAndFlags; size += 1; // // The second octet is the count of bus names. // assert(m_names.size() < 256); buffer[1] = static_cast<uint8_t>(m_names.size()); QCC_DbgPrintf(("IsAt::Serialize(): Count %d", m_names.size())); size += 1; // // The following two octets are the port number in network byte // order (big endian, or most significant byte first). // buffer[2] = static_cast<uint8_t>(m_port >> 8); buffer[3] = static_cast<uint8_t>(m_port); QCC_DbgPrintf(("IsAt::Serialize(): Port %d", m_port)); size += 2; // // From this point on, things are not at fixed addresses // p = &buffer[4]; // // If the F bit is set, we need to include the IPv4 address. // if (m_flagF) { qcc::IPAddress::StringToIPv4(m_ipv4, p, 4); QCC_DbgPrintf(("IsAt::Serialize(): IPv4: %s", m_ipv4.c_str())); p += 4; size += 4; } // // If the S bit is set, we need to include the IPv6 address. // if (m_flagS) { qcc::IPAddress::StringToIPv6(m_ipv6, p, 16); QCC_DbgPrintf(("IsAt::Serialize(): IPv6: %s", m_ipv6.c_str())); p += 16; size += 16; } // // Let the string data decide for themselves how long the rest of the // message will be. If the G bit is set, we need to include the GUID // string. // if (m_flagG) { StringData stringData; stringData.Set(m_guid); QCC_DbgPrintf(("IsAt::Serialize(): GUID %s", m_guid.c_str())); size_t stringSize = stringData.Serialize(p); size += stringSize; p += stringSize; } for (uint32_t i = 0; i < m_names.size(); ++i) { StringData stringData; stringData.Set(m_names[i]); QCC_DbgPrintf(("IsAt::Serialize(): name %s", m_names[i].c_str())); size_t stringSize = stringData.Serialize(p); size += stringSize; p += stringSize; } break; case 1: // // The first octet is type (M = 1) and flags. // typeAndFlags = 1 << 6; if (m_flagG) { QCC_DbgPrintf(("IsAt::Serialize(): G flag")); typeAndFlags |= 0x20; } if (m_flagC) { QCC_DbgPrintf(("IsAt::Serialize(): C flag")); typeAndFlags |= 0x10; } if (m_flagR4) { QCC_DbgPrintf(("IsAt::Serialize(): R4 flag")); typeAndFlags |= 0x8; } if (m_flagU4) { QCC_DbgPrintf(("IsAt::Serialize(): U4 flag")); typeAndFlags |= 0x4; } if (m_flagR6) { QCC_DbgPrintf(("IsAt::Serialize(): R6 flag")); typeAndFlags |= 0x2; } if (m_flagU6) { QCC_DbgPrintf(("IsAt::Serialize(): U6 flag")); typeAndFlags |= 0x1; } buffer[0] = typeAndFlags; size += 1; // // The second octet is the count of bus names. // assert(m_names.size() < 256); buffer[1] = static_cast<uint8_t>(m_names.size()); QCC_DbgPrintf(("IsAt::Serialize(): Count %d", m_names.size())); size += 1; // // The following two octets are the transport mask in network byte // order (big endian, or most significant byte first). // buffer[2] = static_cast<uint8_t>(m_transportMask >> 8); buffer[3] = static_cast<uint8_t>(m_transportMask); QCC_DbgPrintf(("IsAt::Serialize(): TransportMask 0x%x", m_transportMask)); size += 2; // // From this point on, things are not at fixed addresses // p = &buffer[4]; // // If the R4 bit is set, we need to include the reliable IPv4 address // and port. // if (m_flagR4) { qcc::IPAddress::StringToIPv4(m_reliableIPv4Address, p, 4); QCC_DbgPrintf(("IsAt::Serialize(): Reliable IPv4: %s", m_reliableIPv4Address.c_str())); p += 4; size += 4; *p++ = static_cast<uint8_t>(m_reliableIPv4Port >> 8); *p++ = static_cast<uint8_t>(m_reliableIPv4Port); QCC_DbgPrintf(("IsAt::Serialize(): Reliable IPv4 port %d", m_reliableIPv4Port)); size += 2; } // // If the U4 bit is set, we need to include the unreliable IPv4 address // and port. // if (m_flagU4) { qcc::IPAddress::StringToIPv4(m_unreliableIPv4Address, p, 4); QCC_DbgPrintf(("IsAt::Serialize(): Unreliable IPv4: %s", m_unreliableIPv4Address.c_str())); p += 4; size += 4; *p++ = static_cast<uint8_t>(m_unreliableIPv4Port >> 8); *p++ = static_cast<uint8_t>(m_unreliableIPv4Port); QCC_DbgPrintf(("IsAt::Serialize(): Unreliable IPv4 port %d", m_unreliableIPv4Port)); size += 2; } // // If the R6 bit is set, we need to include the reliable IPv6 address // and port. // if (m_flagR6) { qcc::IPAddress::StringToIPv6(m_reliableIPv6Address, p, 16); QCC_DbgPrintf(("IsAt::Serialize(): Reliable IPv6: %s", m_reliableIPv6Address.c_str())); p += 16; size += 16; *p++ = static_cast<uint8_t>(m_reliableIPv6Port >> 8); *p++ = static_cast<uint8_t>(m_reliableIPv6Port); QCC_DbgPrintf(("IsAt::Serialize(): Reliable IPv6 port %d", m_reliableIPv6Port)); size += 2; } // // If the U6 bit is set, we need to include the unreliable IPv6 address // and port. // if (m_flagU6) { qcc::IPAddress::StringToIPv6(m_unreliableIPv6Address, p, 16); QCC_DbgPrintf(("IsAt::Serialize(): Unreliable IPv6: %s", m_unreliableIPv6Address.c_str())); p += 16; size += 16; *p++ = static_cast<uint8_t>(m_unreliableIPv6Port >> 8); *p++ = static_cast<uint8_t>(m_unreliableIPv6Port); QCC_DbgPrintf(("IsAt::Serialize(): Unreliable IPv6 port %d", m_unreliableIPv6Port)); size += 2; } // // Let the string data decide for themselves how long the rest of the // message will be. If the G bit is set, we need to include the GUID // string. // if (m_flagG) { StringData stringData; stringData.Set(m_guid); QCC_DbgPrintf(("IsAt::Serialize(): GUID %s", m_guid.c_str())); size_t stringSize = stringData.Serialize(p); size += stringSize; p += stringSize; } for (uint32_t i = 0; i < m_names.size(); ++i) { StringData stringData; stringData.Set(m_names[i]); QCC_DbgPrintf(("IsAt::Serialize(): name %s", m_names[i].c_str())); size_t stringSize = stringData.Serialize(p); size += stringSize; p += stringSize; } break; default: assert(false && "IsAt::Serialize(): Unexpected version"); break; } return size; } size_t IsAt::Deserialize(uint8_t const* buffer, uint32_t bufsize) { QCC_DbgPrintf(("IsAt::Deserialize()")); // // We keep track of the size (the size of the buffer we read) so testers // can check coherence between GetSerializedSize() and Serialize() and // Deserialize(). // size_t size = 0; uint8_t typeAndFlags = 0; uint8_t const* p = NULL; uint8_t numberNames = 0; // // The message version is in the least significant nibble of the version. // We don't care about the peer name service protocol version which is // meta-data about the other side and is in the most significant nibble. // switch (m_version & 0xf) { case 0: // // If there's not enough room in the buffer to get the fixed part out then // bail (one byte of type and flags, one byte of name count and two bytes // of port). // if (bufsize < 4) { QCC_DbgPrintf(("IsAt::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } size = 0; // // The first octet is type (1) and flags. // typeAndFlags = buffer[0]; size += 1; // // This had better be an IsAt message we're working on // if ((typeAndFlags & 0xc0) != 1 << 6) { QCC_DbgPrintf(("IsAt::Deserialize(): Incorrect type %d", typeAndFlags & 0xc0)); return 0; } m_flagG = (typeAndFlags & 0x20) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): G flag %d", m_flagG)); m_flagC = (typeAndFlags & 0x10) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): C flag %d", m_flagC)); m_flagT = (typeAndFlags & 0x8) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): T flag %d", m_flagT)); m_flagU = (typeAndFlags & 0x4) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): U flag %d", m_flagU)); m_flagS = (typeAndFlags & 0x2) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): S flag %d", m_flagS)); m_flagF = (typeAndFlags & 0x1) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): F flag %d", m_flagF)); // // The second octet is the count of bus names. // numberNames = buffer[1]; QCC_DbgPrintf(("IsAt::Deserialize(): Count %d", numberNames)); size += 1; // // The following two octets are the port number in network byte // order (big endian, or most significant byte first). // m_port = (static_cast<uint16_t>(buffer[2]) << 8) | (static_cast<uint16_t>(buffer[3]) & 0xff); QCC_DbgPrintf(("IsAt::Deserialize(): Port %d", m_port)); size += 2; // // From this point on, things are not at fixed addresses // p = &buffer[4]; bufsize -= 4; // // If the F bit is set, we need to read off an IPv4 address; and we'd better // have enough buffer to read it out of. // if (m_flagF) { if (bufsize < 4) { QCC_DbgPrintf(("IsAt::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } m_ipv4 = qcc::IPAddress::IPv4ToString(p); QCC_DbgPrintf(("IsAt::Deserialize(): IPv4: %s", m_ipv4.c_str())); p += 4; size += 4; bufsize -= 4; } // // If the S bit is set, we need to read off an IPv6 address; and we'd better // have enough buffer to read it out of. // if (m_flagS) { if (bufsize < 16) { QCC_DbgPrintf(("IsAt::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } m_ipv6 = qcc::IPAddress::IPv6ToString(p); QCC_DbgPrintf(("IsAt::Deserialize(): IPv6: %s", m_ipv6.c_str())); p += 16; size += 16; bufsize -= 16; } // // If the G bit is set, we need to read off a GUID string. // if (m_flagG) { QCC_DbgPrintf(("IsAt::Deserialize(): StringData::Deserialize() GUID")); StringData stringData; // // Tell the string to read itself out. If there's not enough buffer // it will complain by returning 0. We pass the complaint on up. // size_t stringSize = stringData.Deserialize(p, bufsize); if (stringSize == 0) { QCC_DbgPrintf(("IsAt::Deserialize(): StringData::Deserialize(): Error")); return 0; } SetGuid(stringData.Get()); size += stringSize; p += stringSize; bufsize -= stringSize; } // // Now we need to read out <numberNames> names that the packet has told us // will be there. // for (uint32_t i = 0; i < numberNames; ++i) { QCC_DbgPrintf(("IsAt::Deserialize(): StringData::Deserialize() name %d", i)); StringData stringData; // // Tell the string to read itself out. If there's not enough buffer // it will complain by returning 0. We pass the complaint on up. // size_t stringSize = stringData.Deserialize(p, bufsize); if (stringSize == 0) { QCC_DbgPrintf(("IsAt::Deserialize(): StringData::Deserialize(): Error")); return 0; } AddName(stringData.Get()); size += stringSize; p += stringSize; bufsize -= stringSize; } break; case 1: // // If there's not enough room in the buffer to get the fixed part out then // bail (one byte of type and flags, one byte of name count) // if (bufsize < 2) { QCC_DbgPrintf(("IsAt::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } // // We keep track of the size (the size of the buffer we read) so testers // can check coherence between GetSerializedSize() and Serialize() and // Deserialize(). // size = 0; // // The first octet is type (1) and flags. // typeAndFlags = buffer[0]; size += 1; // // This had better be an IsAt message we're working on // if ((typeAndFlags & 0xc0) != 1 << 6) { QCC_DbgPrintf(("IsAt::Deserialize(): Incorrect type %d", typeAndFlags & 0xc0)); return 0; } m_flagG = (typeAndFlags & 0x20) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): G flag %d", m_flagG)); m_flagC = (typeAndFlags & 0x10) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): C flag %d", m_flagC)); m_flagR4 = (typeAndFlags & 0x8) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): R4 flag %d", m_flagR4)); m_flagU4 = (typeAndFlags & 0x4) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): U4 flag %d", m_flagU4)); m_flagR6 = (typeAndFlags & 0x2) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): R6 flag %d", m_flagR6)); m_flagU6 = (typeAndFlags & 0x1) != 0; QCC_DbgPrintf(("IsAt::Deserialize(): F flag %d", m_flagU6)); // // The second octet is the count of bus names. // numberNames = buffer[1]; QCC_DbgPrintf(("IsAt::Deserialize(): Count %d", numberNames)); size += 1; m_transportMask = (static_cast<uint16_t>(buffer[2]) << 8) | (static_cast<uint16_t>(buffer[3]) & 0xff); QCC_DbgPrintf(("IsAt::Serialize(): TransportMask 0x%x", m_transportMask)); size += 2; // // From this point on, things are not at fixed addresses // p = &buffer[4]; bufsize -= 4; // // If the R4 bit is set, we need to read off an IPv4 address and port; // and we'd better have enough buffer to read it out of. // if (m_flagR4) { if (bufsize < 6) { QCC_DbgPrintf(("IsAt::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } m_reliableIPv4Address = qcc::IPAddress::IPv4ToString(p); QCC_DbgPrintf(("IsAt::Deserialize(): Reliable IPv4: %s", m_reliableIPv4Address.c_str())); p += 4; size += 4; bufsize -= 4; m_reliableIPv4Port = (static_cast<uint16_t>(p[0]) << 8) | (static_cast<uint16_t>(p[1]) & 0xff); QCC_DbgPrintf(("IsAt::Deserialize(): Reliable IPv4 port %d", m_reliableIPv4Port)); p += 2; size += 2; bufsize -= 2; } // // If the R4 bit is set, we need to read off an IPv4 address and port; // and we'd better have enough buffer to read it out of. // if (m_flagU4) { if (bufsize < 6) { QCC_DbgPrintf(("IsAt::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } m_unreliableIPv4Address = qcc::IPAddress::IPv4ToString(p); QCC_DbgPrintf(("IsAt::Deserialize(): Unreliable IPv4: %s", m_unreliableIPv4Address.c_str())); p += 4; size += 4; bufsize -= 4; m_unreliableIPv4Port = (static_cast<uint16_t>(p[0]) << 8) | (static_cast<uint16_t>(p[1]) & 0xff); QCC_DbgPrintf(("IsAt::Deserialize(): Unreliable IPv4 port %d", m_unreliableIPv4Port)); p += 2; size += 2; bufsize -= 2; } // // If the R6 bit is set, we need to read off an IPv6 address and port; and we'd better // have enough buffer to read it out of. // if (m_flagR6) { if (bufsize < 18) { QCC_DbgPrintf(("IsAt::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } m_reliableIPv6Address = qcc::IPAddress::IPv6ToString(p); QCC_DbgPrintf(("IsAt::Deserialize(): Reliable IPv6: %s", m_reliableIPv6Address.c_str())); p += 16; size += 16; bufsize -= 16; m_reliableIPv6Port = (static_cast<uint16_t>(p[0]) << 8) | (static_cast<uint16_t>(p[1]) & 0xff); QCC_DbgPrintf(("IsAt::Deserialize(): Reliable IPv6 port %d", m_reliableIPv6Port)); p += 2; size += 2; bufsize -= 2; } // // If the U6 bit is set, we need to read off an IPv6 address and port; and we'd better // have enough buffer to read it out of. // if (m_flagU6) { if (bufsize < 18) { QCC_DbgPrintf(("IsAt::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } m_unreliableIPv6Address = qcc::IPAddress::IPv6ToString(p); QCC_DbgPrintf(("IsAt::Deserialize(): Unreliable IPv6: %s", m_unreliableIPv6Address.c_str())); p += 16; size += 16; bufsize -= 16; m_unreliableIPv6Port = (static_cast<uint16_t>(p[0]) << 8) | (static_cast<uint16_t>(p[1]) & 0xff); QCC_DbgPrintf(("IsAt::Deserialize(): Unreliable IPv6 port %d", m_unreliableIPv6Port)); p += 2; size += 2; bufsize -= 2; } // // If the G bit is set, we need to read off a GUID string. // if (m_flagG) { QCC_DbgPrintf(("IsAt::Deserialize(): StringData::Deserialize() GUID")); StringData stringData; // // Tell the string to read itself out. If there's not enough buffer // it will complain by returning 0. We pass the complaint on up. // size_t stringSize = stringData.Deserialize(p, bufsize); if (stringSize == 0) { QCC_DbgPrintf(("IsAt::Deserialize(): StringData::Deserialize(): Error")); return 0; } SetGuid(stringData.Get()); size += stringSize; p += stringSize; bufsize -= stringSize; } // // Now we need to read out <numberNames> names that the packet has told us // will be there. // for (uint32_t i = 0; i < numberNames; ++i) { QCC_DbgPrintf(("IsAt::Deserialize(): StringData::Deserialize() name %d", i)); StringData stringData; // // Tell the string to read itself out. If there's not enough buffer // it will complain by returning 0. We pass the complaint on up. // size_t stringSize = stringData.Deserialize(p, bufsize); if (stringSize == 0) { QCC_DbgPrintf(("IsAt::Deserialize(): StringData::Deserialize(): Error")); return 0; } AddName(stringData.Get()); size += stringSize; p += stringSize; bufsize -= stringSize; } break; default: assert(false && "IsAt::Deserialize(): Unexpected version"); break; } return size; } WhoHas::WhoHas() : m_version(0), m_transportMask(TRANSPORT_NONE), m_flagT(false), m_flagU(false), m_flagS(false), m_flagF(false) { } WhoHas::~WhoHas() { } void WhoHas::Reset(void) { m_names.clear(); } void WhoHas::AddName(qcc::String name) { m_names.push_back(name); } uint32_t WhoHas::GetNumberNames(void) const { return m_names.size(); } qcc::String WhoHas::GetName(uint32_t index) const { assert(index < m_names.size()); return m_names[index]; } size_t WhoHas::GetSerializedSize(void) const { // // Version zero and one are identical with the exeption of the definition // of the flags, so the size is the same. // size_t size = 0; // // The message version is in the least significant nibble of the version. // We don't care about the peer name service protocol version which is // meta-data about the other side and is in the most significant nibble. // switch (m_version & 0xf) { case 0: case 1: // // We have one octet for type and flags and one octet for count. // Two octets to start. // size = 2; // // Let the string data decide for themselves how long the rest // of the message will be. // for (uint32_t i = 0; i < m_names.size(); ++i) { StringData s; s.Set(m_names[i]); size += s.GetSerializedSize(); } break; default: assert(false && "WhoHas::GetSerializedSize(): Unexpected version"); break; } return size; } size_t WhoHas::Serialize(uint8_t* buffer) const { QCC_DbgPrintf(("WhoHas::Serialize(): to buffer 0x%x", buffer)); // // We keep track of the size so testers can check coherence between // GetSerializedSize() and Serialize() and Deserialize(). // size_t size = 0; // // The first octet is type (M = 2) and flags. // uint8_t typeAndFlags = 2 << 6; // // The only difference between version zero and one is that in version one // the flags are deprecated and revert to reserved. So we just don't // serialize them if we are writing a version one object. // // The message version is in the least significant nibble of the version. // We don't care about the peer name service protocol version which is // meta-data about the other side and is in the most significant nibble. // if ((m_version & 0xf) == 0) { if (m_flagT) { QCC_DbgPrintf(("WhoHas::Serialize(): T flag")); typeAndFlags |= 0x8; } if (m_flagU) { QCC_DbgPrintf(("WhoHas::Serialize(): U flag")); typeAndFlags |= 0x4; } if (m_flagS) { QCC_DbgPrintf(("WhoHas::Serialize(): S flag")); typeAndFlags |= 0x2; } if (m_flagF) { QCC_DbgPrintf(("WhoHas::Serialize(): F flag")); typeAndFlags |= 0x1; } } else { typeAndFlags |= 0x4; } buffer[0] = typeAndFlags; size += 1; // // The second octet is the count of bus names. // assert(m_names.size() < 256); buffer[1] = static_cast<uint8_t>(m_names.size()); QCC_DbgPrintf(("WhoHas::Serialize(): Count %d", m_names.size())); size += 1; // // From this point on, things are not at fixed addresses // uint8_t* p = &buffer[2]; // // Let the string data decide for themselves how long the rest // of the message will be. // for (uint32_t i = 0; i < m_names.size(); ++i) { StringData stringData; stringData.Set(m_names[i]); QCC_DbgPrintf(("Whohas::Serialize(): name %s", m_names[i].c_str())); size_t stringSize = stringData.Serialize(p); size += stringSize; p += stringSize; } return size; } size_t WhoHas::Deserialize(uint8_t const* buffer, uint32_t bufsize) { QCC_DbgPrintf(("WhoHas::Deserialize()")); // // If there's not enough room in the buffer to get the fixed part out then // bail (one byte of type and flags, one byte of name count). // if (bufsize < 2) { QCC_DbgPrintf(("WhoHas::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } // // We keep track of the size so testers can check coherence between // GetSerializedSize() and Serialize() and Deserialize(). // size_t size = 0; // // The first octet is type (1) and flags. // uint8_t typeAndFlags = buffer[0]; size += 1; // // This had better be an WhoHas message we're working on // if ((typeAndFlags & 0xc0) != 2 << 6) { QCC_DbgPrintf(("WhoHas::Deserialize(): Incorrect type %d", typeAndFlags & 0xc0)); return 0; } // // Due to an oversight, the transport mask was not actually serialized, // so we initialize it to 0, which means no transport. // m_transportMask = TRANSPORT_NONE; // // The only difference between the version zero and version one protocols // is that the flags are deprecated in version one. In the case of // deserializing a version one object, we just don't set the old flags. // // The message version is in the least significant nibble of the version. // We don't care about the peer name service protocol version which is // meta-data about the other side and is in the most significant nibble. // switch (m_version & 0xf) { case 0: m_flagT = (typeAndFlags & 0x8) != 0; QCC_DbgPrintf(("WhoHas::Deserialize(): T flag %d", m_flagT)); m_flagU = (typeAndFlags & 0x4) != 0; QCC_DbgPrintf(("WhoHas::Deserialize(): U flag %d", m_flagU)); m_flagS = (typeAndFlags & 0x2) != 0; QCC_DbgPrintf(("WhoHas::Deserialize(): S flag %d", m_flagS)); m_flagF = (typeAndFlags & 0x1) != 0; QCC_DbgPrintf(("WhoHas::Deserialize(): F flag %d", m_flagF)); break; case 1: m_flagU = (typeAndFlags & 0x4) != 0; m_flagT = m_flagS = m_flagF = false; break; default: assert(false && "WhoHas::Deserialize(): Unexpected version"); break; } // // The second octet is the count of bus names. // uint8_t numberNames = buffer[1]; QCC_DbgPrintf(("WhoHas::Deserialize(): Count %d", numberNames)); size += 1; // // From this point on, things are not at fixed addresses // uint8_t const* p = &buffer[2]; bufsize -= 2; // // Now we need to read out <numberNames> names that the packet has told us // will be there. // for (uint32_t i = 0; i < numberNames; ++i) { QCC_DbgPrintf(("WhoHas::Deserialize(): StringData::Deserialize() name %d", i)); StringData stringData; // // Tell the string to read itself out. If there's not enough buffer // it will complain by returning 0. We pass the complaint on up. // size_t stringSize = stringData.Deserialize(p, bufsize); if (stringSize == 0) { QCC_DbgPrintf(("WhoHas::Deserialize(): StringData::Deserialize(): Error")); return 0; } AddName(stringData.Get()); size += stringSize; p += stringSize; bufsize -= stringSize; } return size; } _NSPacket::_NSPacket() { } _NSPacket::~_NSPacket() { } void _Packet::SetTimer(uint8_t timer) { m_timer = timer; } uint8_t _Packet::GetTimer(void) const { return m_timer; } void _NSPacket::Reset(void) { m_questions.clear(); m_answers.clear(); } void _NSPacket::AddQuestion(WhoHas question) { m_questions.push_back(question); } uint32_t _NSPacket::GetNumberQuestions(void) const { return m_questions.size(); } WhoHas _NSPacket::GetQuestion(uint32_t index) const { assert(index < m_questions.size()); return m_questions[index]; } void _NSPacket::GetQuestion(uint32_t index, WhoHas** question) { assert(index < m_questions.size()); *question = &m_questions[index]; } void _NSPacket::AddAnswer(IsAt answer) { m_answers.push_back(answer); } void _NSPacket::RemoveAnswer(uint32_t index) { if (index < m_answers.size()) { m_answers.erase(m_answers.begin() + index); } } uint32_t _NSPacket::GetNumberAnswers(void) const { return m_answers.size(); } IsAt _NSPacket::GetAnswer(uint32_t index) const { assert(index < m_answers.size()); return m_answers[index]; } void _NSPacket::GetAnswer(uint32_t index, IsAt** answer) { assert(index < m_answers.size()); *answer = &m_answers[index]; } size_t _NSPacket::GetSerializedSize(void) const { // // We have one octet for version, one four question count, one for answer // count and one for timer. Four octets to start. // size_t size = 4; // // Let the questions data decide for themselves how long the question part // of the message will be. // for (uint32_t i = 0; i < m_questions.size(); ++i) { WhoHas whoHas = m_questions[i]; size += whoHas.GetSerializedSize(); } // // Let the answers decide for themselves how long the answer part // of the message will be. // for (uint32_t i = 0; i < m_answers.size(); ++i) { IsAt isAt = m_answers[i]; size += isAt.GetSerializedSize(); } return size; } size_t _NSPacket::Serialize(uint8_t* buffer) const { QCC_DbgPrintf(("NSPacket::Serialize(): to buffer 0x%x", buffer)); // // We keep track of the size so testers can check coherence between // GetSerializedSize() and Serialize() and Deserialize(). // size_t size = 0; // // The first octet is version // buffer[0] = m_version; QCC_DbgPrintf(("NSPacket::Serialize(): version = %d", m_version)); size += 1; // // The second octet is the count of questions. // buffer[1] = static_cast<uint8_t>(m_questions.size()); QCC_DbgPrintf(("NSPacket::Serialize(): QCount = %d", m_questions.size())); size += 1; // // The third octet is the count of answers. // buffer[2] = static_cast<uint8_t>(m_answers.size()); QCC_DbgPrintf(("NSPacket::Serialize(): ACount = %d", m_answers.size())); size += 1; // // The fourth octet is the timer for the answers. // buffer[3] = GetTimer(); QCC_DbgPrintf(("NSPacket::Serialize(): timer = %d", GetTimer())); size += 1; // // From this point on, things are not at fixed addresses // uint8_t* p = &buffer[4]; // // Let the questions push themselves out. // for (uint32_t i = 0; i < m_questions.size(); ++i) { QCC_DbgPrintf(("NSPacket::Serialize(): WhoHas::Serialize() question %d", i)); WhoHas whoHas = m_questions[i]; size_t questionSize = whoHas.Serialize(p); size += questionSize; p += questionSize; } // // Let the answers push themselves out. // for (uint32_t i = 0; i < m_answers.size(); ++i) { QCC_DbgPrintf(("NSPacket::Serialize(): IsAt::Serialize() answer %d", i)); IsAt isAt = m_answers[i]; size_t answerSize = isAt.Serialize(p); size += answerSize; p += answerSize; } return size; } size_t _NSPacket::Deserialize(uint8_t const* buffer, uint32_t bufsize) { // // If there's not enough room in the buffer to get the fixed part out then // bail (one byte of version, one byte of question count, one byte of answer // count and one byte of timer). // if (bufsize < 4) { QCC_DbgPrintf(("NSPacket::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } // // We keep track of the size so testers can check coherence between // GetSerializedSize() and Serialize() and Deserialize(). // size_t size = 0; // // The first octet is version. We need to filter out bogus versions here // since we are going to promptly set this version in the included who-has // and is-at messages and they will assert that the versions we set actually // make sense. // uint8_t msgVersion; msgVersion = buffer[0] & 0xf; if (msgVersion != 0 && msgVersion != 1) { QCC_DbgPrintf(("Header::Deserialize(): Bad message version %d", msgVersion)); return 0; } m_version = buffer[0]; size += 1; // // The second octet is the count of questions. // uint8_t qCount = buffer[1]; size += 1; // // The third octet is the count of answers. // uint8_t aCount = buffer[2]; size += 1; // // The fourth octet is the timer for the answers. // SetTimer(buffer[3]); size += 1; // // From this point on, things are not at fixed addresses // uint8_t const* p = &buffer[4]; bufsize -= 4; // // Now we need to read out <qCount> questions that the packet has told us // will be there. // for (uint8_t i = 0; i < qCount; ++i) { QCC_DbgPrintf(("NSPacket::Deserialize(): WhoHas::Deserialize() question %d", i)); WhoHas whoHas; whoHas.SetVersion(m_version >> 4, m_version & 0xf); // // Tell the question to read itself out. If there's not enough buffer // it will complain by returning 0. We pass the complaint on up. // size_t qSize = whoHas.Deserialize(p, bufsize); if (qSize == 0) { QCC_DbgPrintf(("NSPacket::Deserialize(): WhoHas::Deserialize(): Error")); return 0; } m_questions.push_back(whoHas); size += qSize; p += qSize; bufsize -= qSize; } // // Now we need to read out <aCount> answers that the packet has told us // will be there. // for (uint8_t i = 0; i < aCount; ++i) { QCC_DbgPrintf(("NSPacket::Deserialize(): IsAt::Deserialize() answer %d", i)); IsAt isAt; isAt.SetVersion(m_version >> 4, m_version & 0xf); // // Tell the answer to read itself out. If there's not enough buffer // it will complain by returning 0. We pass the complaint on up. // size_t aSize = isAt.Deserialize(p, bufsize); if (aSize == 0) { QCC_DbgPrintf(("NSPacket::Deserialize(): IsAt::Deserialize(): Error")); return 0; } m_answers.push_back(isAt); size += aSize; p += aSize; bufsize -= aSize; } return size; } //MDNSDomainName void MDNSDomainName::SetName(String name) { m_name = name; } String MDNSDomainName::GetName() const { return m_name; } MDNSDomainName::MDNSDomainName() { } MDNSDomainName::~MDNSDomainName() { } size_t MDNSDomainName::GetSerializedSize(std::map<qcc::String, uint32_t>& offsets) const { size_t size = 0; String name = m_name; while (true) { if (name.empty()) { size++; break; } else if (offsets.find(name) != offsets.end()) { size++; size++; break; } else { offsets[name] = 0; /* 0 is used as a placeholder so that the serialized size is computed correctly */ size_t newPos = name.find_first_of('.'); String temp = name.substr(0, newPos); size++; size += temp.length(); size_t pos = (newPos == String::npos) ? String::npos : (newPos + 1); name = name.substr(pos); } } return size; } size_t MDNSDomainName::Serialize(uint8_t* buffer, std::map<qcc::String, uint32_t>& offsets, uint32_t headerOffset) const { size_t size = 0; String name = m_name; while (true) { if (name.empty()) { buffer[size++] = 0; break; } else if (offsets.find(name) != offsets.end()) { buffer[size++] = 0xc0 | ((offsets[name] & 0xFF00) >> 8); buffer[size++] = (offsets[name] & 0xFF); break; } else { offsets[name] = size + headerOffset; size_t newPos = name.find_first_of('.'); String temp = name.substr(0, newPos); buffer[size++] = temp.length(); memcpy(reinterpret_cast<void*>(&buffer[size]), const_cast<void*>(reinterpret_cast<const void*>(temp.c_str())), temp.size()); size += temp.length(); size_t pos = (newPos == String::npos) ? String::npos : (newPos + 1); name = name.substr(pos); } } return size; } size_t MDNSDomainName::Deserialize(uint8_t const* buffer, uint32_t bufsize, std::map<uint32_t, qcc::String>& compressedOffsets, uint32_t headerOffset) { m_name.clear(); size_t size = 0; if (bufsize < 1) { QCC_DbgPrintf(("MDNSDomainName::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } vector<uint32_t> offsets; while (bufsize > 0) { if (((buffer[size] & 0xc0) >> 6) == 3 && bufsize > 1) { uint32_t pointer = ((buffer[size] << 8 | buffer[size + 1]) & 0x3FFF); if (compressedOffsets.find(pointer) != compressedOffsets.end()) { if (m_name.length() > 0) { m_name.append('.'); } m_name.append(compressedOffsets[pointer]); size += 2; break; } else { return 0; } } size_t temp_size = buffer[size++]; bufsize--; // // If there's not enough data in the buffer then bail. // if (bufsize < temp_size) { QCC_DbgPrintf(("MDNSDomainName::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } if (m_name.length() > 0) { m_name.append('.'); } if (temp_size > 0) { offsets.push_back(headerOffset + size - 1); m_name.append(reinterpret_cast<const char*>(buffer + size), temp_size); bufsize -= temp_size; size += temp_size; } else { break; } } for (uint32_t i = 0; i < offsets.size(); ++i) { compressedOffsets[offsets[i]] = m_name.substr(offsets[i] - headerOffset); } return size; } //MDNSQuestion MDNSQuestion::MDNSQuestion(qcc::String qName, uint16_t qType, uint16_t qClass) : m_qType(qType), m_qClass(qClass | QU_BIT) { m_qName.SetName(qName); } void MDNSQuestion::SetQName(String qName) { m_qName.SetName(qName); } String MDNSQuestion::GetQName() { return m_qName.GetName(); } void MDNSQuestion::SetQType(uint16_t qType) { m_qType = qType; } uint16_t MDNSQuestion::GetQType() { return m_qType; } void MDNSQuestion::SetQClass(uint16_t qClass) { m_qClass = qClass | QU_BIT; QCC_DbgPrintf(("%X %X ", qClass, m_qClass)); } uint16_t MDNSQuestion::GetQClass() { return m_qClass & ~QU_BIT; } size_t MDNSQuestion::GetSerializedSize(std::map<qcc::String, uint32_t>& offsets) const { return m_qName.GetSerializedSize(offsets) + 4; } size_t MDNSQuestion::Serialize(uint8_t* buffer, std::map<qcc::String, uint32_t>& offsets, uint32_t headerOffset) const { // Serialize the QNAME first size_t size = m_qName.Serialize(buffer, offsets, headerOffset); //Next two octets are QTYPE buffer[size] = (m_qType & 0xFF00) >> 8; buffer[size + 1] = (m_qType & 0xFF); //Next two octets are QCLASS buffer[size + 2] = (m_qClass & 0xFF00) >> 8; buffer[size + 3] = (m_qClass & 0xFF); QCC_DbgPrintf(("Set %X %X", buffer[size + 2], buffer[size + 3])); return size + 4; } size_t MDNSQuestion::Deserialize(uint8_t const* buffer, uint32_t bufsize, std::map<uint32_t, qcc::String>& compressedOffsets, uint32_t headerOffset) { // Deserialize the QNAME first size_t size = m_qName.Deserialize(buffer, bufsize, compressedOffsets, headerOffset); if (size >= bufsize) { return 0; } bufsize -= size; if (size == 0 || bufsize < 4) { //Error while deserializing QNAME or insufficient buffer size QCC_DbgPrintf(("MDNSQuestion::Deserialize Error while deserializing QName")); return 0; } //Next two octets are QTYPE m_qType = (buffer[size] << 8) | buffer[size + 1]; size += 2; //Next two octets are QCLASS m_qClass = (buffer[size] << 8) | buffer[size + 1]; size += 2; return size; } MDNSRData::~MDNSRData() { } //MDNSResourceRecord MDNSResourceRecord::MDNSResourceRecord() : m_rdata(NULL) { } MDNSResourceRecord::MDNSResourceRecord(qcc::String domainName, RRType rrType, RRClass rrClass, uint16_t ttl, MDNSRData* rdata) : m_rrType(rrType), m_rrClass(rrClass), m_rrTTL(ttl) { m_rrDomainName.SetName(domainName); m_rdata = rdata->GetDeepCopy(); } MDNSResourceRecord::MDNSResourceRecord(const MDNSResourceRecord& r) : m_rrDomainName(r.m_rrDomainName), m_rrType(r.m_rrType), m_rrClass(r.m_rrClass), m_rrTTL(r.m_rrTTL) { m_rdata = r.m_rdata->GetDeepCopy(); } MDNSResourceRecord& MDNSResourceRecord::operator=(const MDNSResourceRecord& r) { if (this != &r) { m_rrDomainName = r.m_rrDomainName; m_rrType = r.m_rrType; m_rrClass = r.m_rrClass; m_rrTTL = r.m_rrTTL; if (m_rdata) { delete m_rdata; } m_rdata = r.m_rdata->GetDeepCopy(); } return *this; } MDNSResourceRecord::~MDNSResourceRecord() { if (m_rdata) { delete m_rdata; m_rdata = NULL; } } size_t MDNSResourceRecord::GetSerializedSize(std::map<qcc::String, uint32_t>& offsets) const { assert(m_rdata); size_t size = m_rrDomainName.GetSerializedSize(offsets); size += 8; size += m_rdata->GetSerializedSize(offsets); return size; } size_t MDNSResourceRecord::Serialize(uint8_t* buffer, std::map<qcc::String, uint32_t>& offsets, uint32_t headerOffset) const { assert(m_rdata); // // Serialize the NAME first // size_t size = m_rrDomainName.Serialize(buffer, offsets, headerOffset); //Next two octets are TYPE buffer[size] = (m_rrType & 0xFF00) >> 8; buffer[size + 1] = (m_rrType & 0xFF); //Next two octets are CLASS buffer[size + 2] = (m_rrClass & 0xFF00) >> 8; buffer[size + 3] = (m_rrClass & 0xFF); //Next four octets are TTL buffer[size + 4] = (m_rrTTL & 0xFF000000) >> 24; buffer[size + 5] = (m_rrTTL & 0xFF0000) >> 16; buffer[size + 6] = (m_rrTTL & 0xFF00) >> 8; buffer[size + 7] = (m_rrTTL & 0xFF); size += 8; uint8_t* p = &buffer[size]; size += m_rdata->Serialize(p, offsets, headerOffset + size); return size; } size_t MDNSResourceRecord::Deserialize(uint8_t const* buffer, uint32_t bufsize, std::map<uint32_t, qcc::String>& compressedOffsets, uint32_t headerOffset) { if (m_rdata) { delete m_rdata; m_rdata = NULL; } // // Deserialize the NAME first // size_t size = m_rrDomainName.Deserialize(buffer, bufsize, compressedOffsets, headerOffset); if (size == 0 || bufsize < 8) { //error QCC_DbgPrintf((" MDNSResourceRecord::Deserialize() Error occured while deserializing domain name or insufficient buffer")); return 0; } //Next two octets are TYPE if (size > bufsize || ((size + 8) > bufsize)) { return 0; } m_rrType = (RRType)((buffer[size] << 8) | buffer[size + 1]); switch (m_rrType) { case A: m_rdata = new MDNSARData(); break; case NS: case MD: case MF: case CNAME: case MB: case MG: case MR: case PTR: m_rdata = new MDNSPtrRData(); break; case RNULL: m_rdata = new MDNSDefaultRData(); break; case HINFO: case TXT: m_rdata = new MDNSTextRData(); break; case AAAA: m_rdata = new MDNSAAAARData(); break; case SRV: m_rdata = new MDNSSrvRData(); break; default: m_rdata = new MDNSDefaultRData(); QCC_DbgPrintf(("Ignoring unrecognized rrtype %d", m_rrType)); break; } if (!m_rdata) { return 0; } //Next two octets are CLASS m_rrClass = (RRClass)((buffer[size + 2] << 8) | buffer[size + 3]); //Next four octets are TTL m_rrTTL = (buffer[size + 4] << 24) | (buffer[size + 5] << 16) | (buffer[size + 6] << 8) | buffer[size + 7]; bufsize -= (size + 8); size += 8; headerOffset += size; uint8_t const* p = &buffer[size]; size_t processed = m_rdata->Deserialize(p, bufsize, compressedOffsets, headerOffset); if (!processed) { QCC_DbgPrintf(("MDNSResourceRecord::Deserialize() Error occured while deserializing resource data")); return 0; } size += processed; return size; } void MDNSResourceRecord::SetDomainName(qcc::String domainName) { m_rrDomainName.SetName(domainName); } qcc::String MDNSResourceRecord::GetDomainName() const { return m_rrDomainName.GetName(); } void MDNSResourceRecord::SetRRType(RRType rrtype) { m_rrType = rrtype; } MDNSResourceRecord::RRType MDNSResourceRecord::GetRRType() const { return m_rrType; } void MDNSResourceRecord::SetRRClass(RRClass rrclass) { m_rrClass = rrclass; } MDNSResourceRecord::RRClass MDNSResourceRecord::GetRRClass() const { return m_rrClass; } void MDNSResourceRecord::SetRRttl(uint16_t ttl) { m_rrTTL = ttl; } uint16_t MDNSResourceRecord::GetRRttl() const { return m_rrTTL; } void MDNSResourceRecord::SetRData(MDNSRData* rdata) { if (m_rdata) { delete m_rdata; m_rdata = NULL; } m_rdata = rdata; } MDNSRData* MDNSResourceRecord::GetRData() { return m_rdata; } //MDNSDefaultRData size_t MDNSDefaultRData::GetSerializedSize(std::map<qcc::String, uint32_t>& offsets) const { return 0; } size_t MDNSDefaultRData::Serialize(uint8_t* buffer, std::map<qcc::String, uint32_t>& offsets, uint32_t headerOffset) const { return 0; } size_t MDNSDefaultRData::Deserialize(uint8_t const* buffer, uint32_t bufsize, std::map<uint32_t, qcc::String>& compressedOffsets, uint32_t headerOffset) { // // If there's not enough data in the buffer to even get the string size out // then bail. // if (bufsize < 2) { QCC_DbgPrintf(("MDNSDefaultRData::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } uint16_t rdlen = buffer[0] << 8 | buffer[1]; bufsize -= 2; if (bufsize < rdlen) { QCC_DbgPrintf(("MDNSDefaultRData::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } return rdlen + 2; } //MDNSTextRData const uint16_t MDNSTextRData::TXTVERS = 0; MDNSTextRData::MDNSTextRData(uint16_t version, bool uniquifyKeys) : version(version), uniquifier(uniquifyKeys ? 1 : 0) { m_fields["txtvers"] = U32ToString(version); } void MDNSTextRData::SetUniqueCount(uint16_t count) { uniquifier = count; } uint16_t MDNSTextRData::GetUniqueCount() { return uniquifier; } void MDNSTextRData::Reset() { m_fields.clear(); m_fields["txtvers"] = U32ToString(version); if (uniquifier) { uniquifier = 1; } } void MDNSTextRData::RemoveEntry(qcc::String key) { m_fields.erase(key); } void MDNSTextRData::SetValue(String key, String value) { if (uniquifier) { key += "_" + U32ToString(uniquifier++); } m_fields[key] = value; } void MDNSTextRData::SetValue(String key, uint16_t value) { if (uniquifier) { key += "_" + U32ToString(uniquifier++); } m_fields[key] = U32ToString(value); } void MDNSTextRData::SetValue(String key) { if (uniquifier) { key += "_" + U32ToString(uniquifier++); } m_fields[key] = String(); } String MDNSTextRData::GetValue(String key) { if (m_fields.find(key) != m_fields.end()) { return m_fields[key]; } else { return ""; } } uint16_t MDNSTextRData::GetU16Value(String key) { if (m_fields.find(key) != m_fields.end()) { return StringToU32(m_fields[key]); } else { return 0; } } uint16_t MDNSTextRData::GetNumFields(String key) { key += "_"; uint16_t numNames = 0; for (Fields::const_iterator it = m_fields.begin(); it != m_fields.end(); ++it) { if (it->first.find(key) == 0) { ++numNames; } } return numNames; } qcc::String MDNSTextRData::GetFieldAt(String key, int i) { key += "_"; Fields::const_iterator it; for (it = m_fields.begin(); it != m_fields.end(); ++it) { if (it->first.find(key) == 0 && (i-- == 0)) { break; } } if (it != m_fields.end()) { return it->second; } else { return String(); } } void MDNSTextRData::RemoveFieldAt(String key, int i) { key += "_"; Fields::const_iterator it; for (it = m_fields.begin(); it != m_fields.end(); ++it) { if (it->first.find(key) == 0 && (i-- == 0)) { break; } } if (it != m_fields.end()) { MDNSTextRData::RemoveEntry(it->first); } } size_t MDNSTextRData::GetSerializedSize(std::map<qcc::String, uint32_t>& offsets) const { size_t rdlen = 0; Fields::const_iterator it = m_fields.begin(); while (it != m_fields.end()) { String str = it->first; if (!it->second.empty()) { str += "=" + it->second; } rdlen += str.length() + 1; it++; } return rdlen + 2; } size_t MDNSTextRData::Serialize(uint8_t* buffer, std::map<qcc::String, uint32_t>& offsets, uint32_t headerOffset) const { size_t rdlen = 0; uint8_t* p = &buffer[2]; // // txtvers must appear first in the record // Fields::const_iterator txtvers = m_fields.find("txtvers"); assert(txtvers != m_fields.end()); String str = txtvers->first + "=" + txtvers->second; *p++ = str.length(); memcpy(reinterpret_cast<void*>(p), const_cast<void*>(reinterpret_cast<const void*>(str.c_str())), str.length()); p += str.length(); rdlen += str.length() + 1; // // Then we rely on the Fields comparison object so make sure things are // serialized in the proper order // for (Fields::const_iterator it = m_fields.begin(); it != m_fields.end(); ++it) { if (it == txtvers) { continue; } String str = it->first; if (!it->second.empty()) { str += "=" + it->second; } *p++ = str.length(); memcpy(reinterpret_cast<void*>(p), const_cast<void*>(reinterpret_cast<const void*>(str.c_str())), str.length()); p += str.length(); rdlen += str.length() + 1; } buffer[0] = (rdlen & 0xFF00) >> 8; buffer[1] = (rdlen & 0xFF); return rdlen + 2; } size_t MDNSTextRData::Deserialize(uint8_t const* buffer, uint32_t bufsize, std::map<uint32_t, qcc::String>& compressedOffsets, uint32_t headerOffset) { // // If there's not enough data in the buffer to even get the string size out // then bail. // if (bufsize < 2) { QCC_DbgPrintf(("MDNSTextRecord::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } uint16_t rdlen = buffer[0] << 8 | buffer[1]; bufsize -= 2; size_t size = 2 + rdlen; // // If there's not enough data in the buffer then bail. // if (bufsize < rdlen) { QCC_DbgPrintf(("MDNSTextRecord::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } uint8_t const* p = &buffer[2]; while (rdlen > 0 && bufsize > 0) { uint8_t sz = *p++; String str; bufsize--; if (bufsize < sz) { QCC_DbgPrintf(("MDNSTextRecord::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } str.assign(reinterpret_cast<const char*>(p), sz); size_t eqPos = str.find_first_of('=', 0); if (eqPos != String::npos) { m_fields[str.substr(0, eqPos)] = str.substr(eqPos + 1); } else { m_fields[str.substr(0, eqPos)] = String(); } p += sz; rdlen -= sz + 1; bufsize -= sz; } if (rdlen != 0) { QCC_DbgPrintf(("MDNSTextRecord::Deserialize(): Mismatched RDLength")); return 0; } return size; } //MDNSARecord void MDNSARData::SetAddr(qcc::String ipAddr) { m_ipv4Addr = ipAddr; } qcc::String MDNSARData::GetAddr() { return m_ipv4Addr; } size_t MDNSARData::GetSerializedSize(std::map<qcc::String, uint32_t>& offsets) const { //4 bytes for address, 2 bytes length return 4 + 2; } size_t MDNSARData::Serialize(uint8_t* buffer, std::map<qcc::String, uint32_t>& offsets, uint32_t headerOffset) const { buffer[0] = 0; buffer[1] = 4; uint8_t* p = &buffer[2]; QStatus status = qcc::IPAddress::StringToIPv4(m_ipv4Addr, p, 4); if (status != ER_OK) { QCC_DbgPrintf(("MDNSARData::Serialize Error occured during conversion of String to IPv4 address")); return 0; } return 6; } size_t MDNSARData::Deserialize(uint8_t const* buffer, uint32_t bufsize, std::map<uint32_t, qcc::String>& compressedOffsets, uint32_t headerOffset) { if (bufsize < 6) { QCC_DbgPrintf(("MDNSTextRecord::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } if (buffer[0] != 0 || buffer[1] != 4) { QCC_DbgPrintf(("MDNSTextRecord::Deserialize(): Invalid RDLength")); return 0; } uint8_t const* p = &buffer[2]; m_ipv4Addr = qcc::IPAddress::IPv4ToString(p); bufsize -= 6; return 6; } //MDNSAAAARecord void MDNSAAAARData::SetAddr(qcc::String ipAddr) { m_ipv6Addr = ipAddr; } qcc::String MDNSAAAARData::GetAddr() const { return m_ipv6Addr; } size_t MDNSAAAARData::GetSerializedSize(std::map<qcc::String, uint32_t>& offsets) const { //16 bytes for address, 2 bytes length return 16 + 2; } size_t MDNSAAAARData::Serialize(uint8_t* buffer, std::map<qcc::String, uint32_t>& offsets, uint32_t headerOffset) const { buffer[0] = 0; buffer[1] = 16; uint8_t* p = &buffer[2]; qcc::IPAddress::StringToIPv6(m_ipv6Addr, p, 16); return 18; } size_t MDNSAAAARData::Deserialize(uint8_t const* buffer, uint32_t bufsize, std::map<uint32_t, qcc::String>& compressedOffsets, uint32_t headerOffset) { if (bufsize < 18) { QCC_DbgPrintf(("MDNSTextRecord::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } if (buffer[0] != 0 || buffer[1] != 16) { QCC_DbgPrintf(("MDNSTextRecord::Deserialize(): Invalid RDLength")); return 0; } uint8_t const* p = &buffer[2]; m_ipv6Addr = qcc::IPAddress::IPv6ToString(p); bufsize -= 18; return 18; } //MDNSPtrRData void MDNSPtrRData::SetPtrDName(qcc::String rdataStr) { m_rdataStr = rdataStr; } qcc::String MDNSPtrRData::GetPtrDName() const { return m_rdataStr; } size_t MDNSPtrRData::GetSerializedSize(std::map<qcc::String, uint32_t>& offsets) const { size_t size = 2; String name = m_rdataStr; while (true) { if (name.empty()) { size++; break; } else if (offsets.find(name) != offsets.end()) { size++; size++; break; } else { offsets[name] = 0; /* 0 is used as a placeholder so that the serialized size is computed correctly */ size_t newPos = name.find_first_of('.'); String temp = name.substr(0, newPos); size++; size += temp.length(); size_t pos = (newPos == String::npos) ? String::npos : (newPos + 1); name = name.substr(pos); } } return size; } size_t MDNSPtrRData::Serialize(uint8_t* buffer, std::map<qcc::String, uint32_t>& offsets, uint32_t headerOffset) const { size_t size = 2; String name = m_rdataStr; while (true) { if (name.empty()) { buffer[size++] = 0; break; } else if (offsets.find(name) != offsets.end()) { buffer[size++] = 0xc0 | ((offsets[name] & 0xFF00) >> 8); buffer[size++] = (offsets[name] & 0xFF); break; } else { offsets[name] = size + headerOffset; size_t newPos = name.find_first_of('.'); String temp = name.substr(0, newPos); buffer[size++] = temp.length(); memcpy(reinterpret_cast<void*>(&buffer[size]), const_cast<void*>(reinterpret_cast<const void*>(temp.c_str())), temp.size()); size += temp.length(); size_t pos = (newPos == String::npos) ? String::npos : (newPos + 1); name = name.substr(pos); } } buffer[0] = ((size - 2) & 0xFF00) >> 8; buffer[1] = ((size - 2) & 0xFF); return size; } size_t MDNSPtrRData::Deserialize(uint8_t const* buffer, uint32_t bufsize, std::map<uint32_t, qcc::String>& compressedOffsets, uint32_t headerOffset) { m_rdataStr.clear(); // // If there's not enough data in the buffer to even get the string size out // then bail. // if (bufsize < 2) { QCC_DbgPrintf(("MDNSPtrRecord::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } uint16_t szStr = buffer[0] << 8 | buffer[1]; bufsize -= 2; size_t size = 2; vector<uint32_t> offsets; // If there's not enough data in the buffer then bail. // if (bufsize < szStr) { QCC_DbgPrintf(("MDNSPtrRecord::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } while (bufsize > 0) { if (((buffer[size] & 0xc0) >> 6) == 3 && bufsize > 1) { uint32_t pointer = ((buffer[size] << 8 | buffer[size + 1]) & 0x3FFF); if (compressedOffsets.find(pointer) != compressedOffsets.end()) { if (m_rdataStr.length() > 0) { m_rdataStr.append('.'); } m_rdataStr.append(compressedOffsets[pointer]); size += 2; break; } else { return 0; } } size_t temp_size = buffer[size++]; bufsize--; // // If there's not enough data in the buffer then bail. // if (bufsize < temp_size) { QCC_DbgPrintf(("MDNSPtrRecord::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } if (m_rdataStr.length() > 0) { m_rdataStr.append('.'); } if (temp_size > 0) { offsets.push_back(headerOffset + size - 1); m_rdataStr.append(reinterpret_cast<const char*>(buffer + size), temp_size); bufsize -= temp_size; size += temp_size; } else { break; } } for (uint32_t i = 0; i < offsets.size(); ++i) { compressedOffsets[offsets[i]] = m_rdataStr.substr(offsets[i] - 2 - headerOffset); } return size; } //MDNSSrvRData MDNSSrvRData::MDNSSrvRData(uint16_t priority, uint16_t weight, uint16_t port, qcc::String target) : m_priority(priority), m_weight(weight), m_port(port) { m_target.SetName(target); } void MDNSSrvRData::SetPriority(uint16_t priority) { m_priority = priority; } uint16_t MDNSSrvRData::GetPriority() const { return m_priority; } void MDNSSrvRData::SetWeight(uint16_t weight) { m_weight = weight; } uint16_t MDNSSrvRData::GetWeight() const { return m_weight; } void MDNSSrvRData::SetPort(uint16_t port) { m_port = port; } uint16_t MDNSSrvRData::GetPort() const { return m_port; } void MDNSSrvRData::SetTarget(qcc::String target) { m_target.SetName(target); } qcc::String MDNSSrvRData::GetTarget() const { return m_target.GetName(); } size_t MDNSSrvRData::GetSerializedSize(std::map<qcc::String, uint32_t>& offsets) const { //2 bytes length return 2 + 6 + m_target.GetSerializedSize(offsets); } size_t MDNSSrvRData::Serialize(uint8_t* buffer, std::map<qcc::String, uint32_t>& offsets, uint32_t headerOffset) const { //length filled in after we know it below //priority buffer[2] = (m_priority & 0xFF00) >> 8; buffer[3] = (m_priority & 0xFF); //weight buffer[4] = (m_weight & 0xFF00) >> 8; buffer[5] = (m_weight & 0xFF); //port buffer[6] = (m_port & 0xFF00) >> 8; buffer[7] = (m_port & 0xFF); size_t size = 2 + 6; uint8_t* p = &buffer[size]; size += m_target.Serialize(p, offsets, headerOffset + size); uint16_t length = size - 2; buffer[0] = (length & 0xFF00) >> 8; buffer[1] = (length & 0xFF); return size; } size_t MDNSSrvRData::Deserialize(uint8_t const* buffer, uint32_t bufsize, std::map<uint32_t, qcc::String>& compressedOffsets, uint32_t headerOffset) { // // If there's not enough data in the buffer to even get the string size out // then bail. // if (bufsize < 2) { QCC_DbgPrintf(("MDNSSrvRecord::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } uint16_t length = buffer[0] << 8 | buffer[1]; bufsize -= 2; if (bufsize < length || length < 6) { QCC_DbgPrintf(("MDNSSrvRecord::Deserialize(): Insufficient bufsize %d or invalid length %d", bufsize, length)); return 0; } m_priority = buffer[2] << 8 | buffer[3]; bufsize -= 2; m_weight = buffer[4] << 8 | buffer[5]; bufsize -= 2; m_port = buffer[6] << 8 | buffer[7]; bufsize -= 2; size_t size = 8; headerOffset += 8; uint8_t const* p = &buffer[size]; size += m_target.Deserialize(p, bufsize, compressedOffsets, headerOffset); return size; } //MDNSAdvertiseRecord void MDNSAdvertiseRData::Reset() { MDNSTextRData::Reset(); } void MDNSAdvertiseRData::SetTransport(TransportMask tm) { MDNSTextRData::SetValue("t", U32ToString(tm, 16)); } void MDNSAdvertiseRData::AddName(qcc::String name) { MDNSTextRData::SetValue("n", name); } void MDNSAdvertiseRData::SetValue(String key, String value) { // // Commonly used keys name and implements get abbreviated over the air. // if (key == "name") { MDNSTextRData::SetValue("n", value); } else if (key == "transport") { MDNSTextRData::SetValue("t", value); } else if (key == "implements") { MDNSTextRData::SetValue("i", value); } else { MDNSTextRData::SetValue(key, value); } } void MDNSAdvertiseRData::SetValue(String key) { MDNSTextRData::SetValue(key); } uint16_t MDNSAdvertiseRData::GetNumFields() { return m_fields.size(); } uint16_t MDNSAdvertiseRData::GetNumNames(TransportMask transportMask) { uint16_t numNames = 0; Fields::const_iterator it; for (it = m_fields.begin(); it != m_fields.end(); ++it) { if (it->first.find("t_") != String::npos && (StringToU32(it->second, 16) == transportMask)) { it++; while (it != m_fields.end() && it->first.find("t_") == String::npos) { if (it->first.find("n_") != String::npos) { numNames++; } it++; } break; } } return numNames; } qcc::String MDNSAdvertiseRData::GetNameAt(TransportMask transportMask, int index) { Fields::const_iterator it; for (it = m_fields.begin(); it != m_fields.end(); ++it) { if (it->first.find("t_") != String::npos && (StringToU32(it->second, 16) == transportMask)) { it++; while (it != m_fields.end() && it->first.find("t_") == String::npos) { if (it->first.find("n_") != String::npos && index-- == 0) { return it->second; } it++; } break; } } return ""; } void MDNSAdvertiseRData::RemoveNameAt(TransportMask transportMask, int index) { Fields::const_iterator it; for (it = m_fields.begin(); it != m_fields.end(); ++it) { if (it->first.find("t_") != String::npos && (StringToU32(it->second, 16) == transportMask)) { it++; while (it != m_fields.end() && it->first.find("t_") == String::npos) { Fields::const_iterator nxt = it; nxt++; if (it->first.find("n_") != String::npos && index-- == 0) { MDNSTextRData::RemoveEntry(it->first); } it = nxt; } break; } } } std::pair<qcc::String, qcc::String> MDNSAdvertiseRData::GetFieldAt(int i) { Fields::const_iterator it = m_fields.begin(); while (i-- && it != m_fields.end()) { ++it; } if (it == m_fields.end()) { return pair<String, String>("", ""); } String key = it->first; key = key.substr(0, key.find_last_of('_')); if (key == "n") { key = "name"; } else if (key == "i") { key = "implements"; } else if (key == "t") { key = "transport"; } return pair<String, String>(key, it->second); } //MDNSSearchRecord MDNSSearchRData::MDNSSearchRData(qcc::String name, uint16_t version) : MDNSTextRData(version, true) { MDNSTextRData::SetValue("n", name); } void MDNSSearchRData::SetValue(String key, String value) { // // Commonly used keys name and implements get abbreviated over the air. // if (key == "name") { MDNSTextRData::SetValue("n", value); } else if (key == "implements") { MDNSTextRData::SetValue("i", value); } else { MDNSTextRData::SetValue(key, value); } } void MDNSSearchRData::SetValue(String key) { MDNSTextRData::SetValue(key); } uint16_t MDNSSearchRData::GetNumFields() { return m_fields.size(); } uint16_t MDNSSearchRData::GetNumSearchCriteria() { int numEntries = GetNumFields() - 1 /*txtvers*/; return (numEntries > 0) ? (MDNSTextRData::GetNumFields(";") + 1) : 0; } String MDNSSearchRData::GetSearchCriterion(int index) { Fields::const_iterator it = m_fields.begin(); String ret = ""; while (it != m_fields.end()) { String key = it->first; key = key.substr(0, key.find_last_of('_')); if (key == ";") { if (index-- == 0) { break; } ret = ""; } else if (key != "txtvers") { if (key == "n") { key = "name"; } else if (key == "i") { key = "implements"; } if (!ret.empty()) { ret += ","; } ret += key + "='" + it->second + "'"; } ++it; } return ret; } void MDNSSearchRData::RemoveSearchCriterion(int index) { Fields::iterator it = m_fields.begin(); String ret = ""; while (it != m_fields.end() && index > 0) { String key = it->first; key = key.substr(0, key.find_last_of('_')); if (key == ";") { if (--index == 0) { it++; break; } ret = ""; } else if (key != "txtvers") { if (key == "n") { key = "name"; } else if (key == "i") { key = "implements"; } if (!ret.empty()) { ret += ","; } ret += key + "='" + it->second + "'"; } ++it; } if (it != m_fields.end()) { while (it != m_fields.end()) { String key = it->first; key = key.substr(0, key.find_last_of('_')); if (key == ";") { m_fields.erase(it); break; } else if (key == "txtvers") { it++; } else { m_fields.erase(it++); } } } } std::pair<qcc::String, qcc::String> MDNSSearchRData::GetFieldAt(int i) { Fields::const_iterator it = m_fields.begin(); while (i-- && it != m_fields.end()) { ++it; } if (it == m_fields.end()) { return pair<String, String>("", ""); } String key = it->first; key = key.substr(0, key.find_last_of('_')); if (key == "n") { key = "name"; } else if (key == "i") { key = "implements"; } return pair<String, String>(key, it->second); } //MDNSPingRecord MDNSPingRData::MDNSPingRData(qcc::String name, uint16_t version) : MDNSTextRData(version) { MDNSTextRData::SetValue("n", name); } String MDNSPingRData::GetWellKnownName() { return MDNSTextRData::GetValue("n"); } void MDNSPingRData::SetWellKnownName(qcc::String name) { MDNSTextRData::SetValue("n", name); } //MDNSPingReplyRecord MDNSPingReplyRData::MDNSPingReplyRData(qcc::String name, uint16_t version) : MDNSTextRData(version) { MDNSTextRData::SetValue("n", name); } String MDNSPingReplyRData::GetWellKnownName() { return MDNSTextRData::GetValue("n"); } void MDNSPingReplyRData::SetWellKnownName(qcc::String name) { MDNSTextRData::SetValue("n", name); } String MDNSPingReplyRData::GetReplyCode() { return MDNSTextRData::GetValue("replycode"); } void MDNSPingReplyRData::SetReplyCode(qcc::String replyCode) { MDNSTextRData::SetValue("replycode", replyCode); } //MDNSSenderRData MDNSSenderRData::MDNSSenderRData(uint16_t version) : MDNSTextRData(version) { MDNSTextRData::SetValue("pv", NS_VERSION); } uint16_t MDNSSenderRData::GetSearchID() { return MDNSTextRData::GetU16Value("sid"); } void MDNSSenderRData::SetSearchID(uint16_t searchId) { MDNSTextRData::SetValue("sid", searchId); } uint16_t MDNSSenderRData::GetIPV4ResponsePort() { return MDNSTextRData::GetU16Value("upcv4"); } void MDNSSenderRData::SetIPV4ResponsePort(uint16_t ipv4Port) { MDNSTextRData::SetValue("upcv4", ipv4Port); } qcc::String MDNSSenderRData::GetIPV4ResponseAddr() { return MDNSTextRData::GetValue("ipv4"); } void MDNSSenderRData::SetIPV4ResponseAddr(qcc::String ipv4Addr) { MDNSTextRData::SetValue("ipv4", ipv4Addr); } //MDNSHeader MDNSHeader::MDNSHeader() : m_queryId(0), m_qrType(0), m_authAnswer(0), m_rCode(NOT_ERROR), m_qdCount(0), m_anCount(0), m_nsCount(0), m_arCount(0) { } MDNSHeader::MDNSHeader(uint16_t id, bool qrType, uint16_t qdCount, uint16_t anCount, uint16_t nsCount, uint16_t arCount) : m_queryId(id), m_qrType(qrType), m_authAnswer(0), m_rCode(NOT_ERROR), m_qdCount(qdCount), m_anCount(anCount), m_nsCount(nsCount), m_arCount(arCount) { } MDNSHeader::MDNSHeader(uint16_t id, bool qrType) : m_queryId(id), m_qrType(qrType), m_authAnswer(0), m_rCode(NOT_ERROR), m_qdCount(0), m_anCount(0), m_nsCount(0), m_arCount(0) { } MDNSHeader::~MDNSHeader() { } void MDNSHeader::SetId(uint16_t id) { m_queryId = id; } uint16_t MDNSHeader::GetId() { return m_queryId; } void MDNSHeader::SetQRType(bool qrType) { m_qrType = qrType; } bool MDNSHeader::GetQRType() { return m_qrType; } void MDNSHeader::SetQDCount(uint16_t qdCount) { m_qdCount = qdCount; } uint16_t MDNSHeader::GetQDCount() { return m_qdCount; } void MDNSHeader::SetANCount(uint16_t anCount) { m_anCount = anCount; } uint16_t MDNSHeader::GetANCount() { return m_anCount; } void MDNSHeader::SetNSCount(uint16_t nsCount) { m_nsCount = nsCount; } uint16_t MDNSHeader::GetNSCount() { return m_nsCount; } void MDNSHeader::SetARCount(uint16_t arCount) { m_arCount = arCount; } uint16_t MDNSHeader::GetARCount() { return m_arCount; } size_t MDNSHeader::Serialize(uint8_t* buffer) const { QCC_DbgPrintf(("MDNSHeader::Serialize(): to buffer 0x%x", buffer)); // // We keep track of the size so testers can check coherence between // GetSerializedSize() and Serialize() and Deserialize(). // size_t size = 0; // // The first two octets are ID // buffer[0] = (m_queryId & 0xFF00) >> 8; buffer[1] = (m_queryId & 0xFF); size += 2; // // The third octet is |QR| Opcode |AA|TC|RD|RA| // // QR = packet type Query/Response. // Opcode = 0 a standard query (QUERY) // AA = 0 for now // TC = 0 for now // RD = 0 for now // RA = 0 for now buffer[2] = m_qrType << 7; QCC_DbgPrintf(("Header::Serialize(): Third octet = %x", buffer[2])); size += 1; // // The fourth octet is | Z | RCODE | // Z = reserved for future use. Must be zero. buffer[3] = m_rCode; QCC_DbgPrintf(("Header::Serialize(): RCode = %d", buffer[3])); size += 1; // // The next two octets are QDCOUNT // //assert((m_qdCount == 0) || (m_qdCount == 1)); buffer[4] = 0; buffer[5] = m_qdCount; QCC_DbgPrintf(("Header::Serialize(): QDCOUNT = %d", buffer[5])); size += 2; // // The next two octets are ANCOUNT // //assert((m_anCount == 0) || (m_anCount == 1)); buffer[6] = 0; buffer[7] = m_anCount; QCC_DbgPrintf(("Header::Serialize(): ANCOUNT = %d", buffer[7])); size += 2; // // The next two octets are NSCOUNT // buffer[8] = m_nsCount >> 8; buffer[9] = m_nsCount & 0xFF; QCC_DbgPrintf(("Header::Serialize(): NSCOUNT = %d", m_nsCount)); size += 2; // // The next two octets are ARCOUNT // buffer[10] = m_arCount >> 8; buffer[11] = m_arCount & 0xFF; QCC_DbgPrintf(("Header::Serialize(): ARCOUNT = %d", m_arCount)); size += 2; return size; } size_t MDNSHeader::Deserialize(uint8_t const* buffer, uint32_t bufsize) { // // If there's not enough room in the buffer to get the fixed part out then // bail (one byte of version, one byte of question count, one byte of answer // count and one byte of timer). // if (bufsize < 12) { QCC_DbgPrintf(("Header::Deserialize(): Insufficient bufsize %d", bufsize)); return 0; } // // We keep track of the size so testers can check coherence between // GetSerializedSize() and Serialize() and Deserialize(). // size_t size = 0; // // The first two octets are ID // m_queryId = (buffer[0] << 8) | buffer[1]; size += 2; // // The third octet is |QR| Opcode |AA|TC|RD|RA| // // QR = packet type Query/Response. // Opcode = 0 a standard query (QUERY) // AA = 0 for now // TC = 0 for now // RD = 0 for now // RA = 0 for now // Extract QR type m_qrType = buffer[2] >> 7; size += 1; // // The fourth octet is | Z | RCODE | // Z = reserved for future use. Must be zero. // Extract RCode. m_rCode = (RCodeType)(buffer[3] & 0x0F); size += 1; // // The next two octets are QDCOUNT // m_qdCount = buffer[5]; //assert((m_qdCount == 0) || (m_qdCount == 1)); size += 2; // // The next two octets are ANCOUNT // m_anCount = (buffer[6] << 8) | buffer[7]; //assert((m_anCount == 0) || (m_anCount == 1)); size += 2; // // The next two octets are NSCOUNT // m_nsCount = (buffer[8] << 8) | buffer[9]; QCC_DbgPrintf(("Header::Deserialize(): NSCOUNT = %d", m_nsCount)); size += 2; // // The next two octets are ARCOUNT // m_arCount = (buffer[10] << 8) | buffer[11]; size += 2; bufsize -= 12; return size; } size_t MDNSHeader::GetSerializedSize(void) const { // // We have 12 octets in the header. // return 12; } //MDNSPacket _MDNSPacket::_MDNSPacket() { m_questions.reserve(MIN_RESERVE); m_answers.reserve(MIN_RESERVE); m_authority.reserve(MIN_RESERVE); m_additional.reserve(MIN_RESERVE); } _MDNSPacket::~_MDNSPacket() { } void _MDNSPacket::Clear() { m_questions.clear(); m_answers.clear(); m_authority.clear(); m_additional.clear(); } void _MDNSPacket::SetHeader(MDNSHeader header) { m_header = header; } MDNSHeader _MDNSPacket::GetHeader() { return m_header; } void _MDNSPacket::AddQuestion(MDNSQuestion question) { m_questions.push_back(question); assert(m_questions.size() <= MIN_RESERVE); m_header.SetQDCount(m_questions.size()); } bool _MDNSPacket::GetQuestionAt(uint32_t i, MDNSQuestion** question) { if (i >= m_questions.size()) { return false; } *question = &m_questions[i]; return true; } bool _MDNSPacket::GetQuestion(qcc::String str, MDNSQuestion** question) { std::vector<MDNSQuestion>::iterator it1 = m_questions.begin(); while (it1 != m_questions.end()) { if (((*it1).GetQName() == str)) { *question = &(*it1); return true; } it1++; } return false; } uint16_t _MDNSPacket::GetNumQuestions() { return m_questions.size(); } void _MDNSPacket::AddAdditionalRecord(MDNSResourceRecord record) { m_additional.push_back(record); assert(m_additional.size() <= MIN_RESERVE); m_header.SetARCount(m_additional.size()); } bool _MDNSPacket::GetAdditionalRecordAt(uint32_t i, MDNSResourceRecord** additional) { if (i >= m_additional.size()) { return false; } *additional = &m_additional[i]; return true; } uint16_t _MDNSPacket::GetNumAdditionalRecords() { return m_additional.size(); } void _MDNSPacket::RemoveAdditionalRecord(qcc::String str, MDNSResourceRecord::RRType type) { std::vector<MDNSResourceRecord>::iterator it1 = m_additional.begin(); while (it1 != m_additional.end()) { if (((*it1).GetDomainName() == str) && ((*it1).GetRRType() == type)) { m_additional.erase(it1++); m_header.SetARCount(m_additional.size()); return; } it1++; } } bool _MDNSPacket::GetAdditionalRecord(qcc::String str, MDNSResourceRecord::RRType type, MDNSResourceRecord** additional) { size_t starPos = str.find_last_of('*'); String name = str.substr(0, starPos); std::vector<MDNSResourceRecord>::iterator it1 = m_additional.begin(); while (it1 != m_additional.end()) { String dname = (*it1).GetDomainName(); bool nameMatches = (starPos == String::npos) ? (dname == name) : (dname.find(name) == 0); if (nameMatches && ((*it1).GetRRType() == type)) { *additional = &(*it1); return true; } it1++; } return false; } bool _MDNSPacket::GetAdditionalRecord(qcc::String str, MDNSResourceRecord::RRType type, uint16_t version, MDNSResourceRecord** additional) { if (type != MDNSResourceRecord::TXT) { return false; } size_t starPos = str.find_last_of('*'); String name = str.substr(0, starPos); std::vector<MDNSResourceRecord>::iterator it1 = m_additional.begin(); while (it1 != m_additional.end()) { String dname = (*it1).GetDomainName(); bool nameMatches = (starPos == String::npos) ? (dname == name) : (dname.find(name) == 0); if (nameMatches && ((*it1).GetRRType() == type) && (static_cast<MDNSTextRData*>((*it1).GetRData())->GetU16Value("txtvers") == version)) { *additional = &(*it1); return true; } it1++; } return false; } uint32_t _MDNSPacket::GetNumMatches(qcc::String str, MDNSResourceRecord::RRType type, uint16_t version) { if (type != MDNSResourceRecord::TXT) { return false; } uint32_t numMatches = 0; size_t starPos = str.find_last_of('*'); String name = str.substr(0, starPos); std::vector<MDNSResourceRecord>::iterator it1 = m_additional.begin(); while (it1 != m_additional.end()) { String dname = (*it1).GetDomainName(); bool nameMatches = (starPos == String::npos) ? (dname == name) : (dname.find(name) == 0); if (nameMatches && ((*it1).GetRRType() == type) && (static_cast<MDNSTextRData*>((*it1).GetRData())->GetU16Value("txtvers") == version)) { numMatches++; } it1++; } return numMatches; } bool _MDNSPacket::GetAdditionalRecordAt(qcc::String str, MDNSResourceRecord::RRType type, uint16_t version, uint32_t index, MDNSResourceRecord** additional) { if (type != MDNSResourceRecord::TXT) { return false; } size_t starPos = str.find_last_of('*'); String name = str.substr(0, starPos); uint32_t i = 0; std::vector<MDNSResourceRecord>::iterator it1 = m_additional.begin(); while (it1 != m_additional.end()) { String dname = (*it1).GetDomainName(); bool nameMatches = (starPos == String::npos) ? (dname == name) : (dname.find(name) == 0); if (nameMatches && ((*it1).GetRRType() == type) && (static_cast<MDNSTextRData*>((*it1).GetRData())->GetU16Value("txtvers") == version)) { if (i++ == index) { *additional = &(*it1); return true; } } it1++; } return false; } bool _MDNSPacket::GetAnswer(qcc::String str, MDNSResourceRecord::RRType type, MDNSResourceRecord** answer) { std::vector<MDNSResourceRecord>::iterator it1 = m_answers.begin(); while (it1 != m_answers.end()) { if (((*it1).GetDomainName() == str) && ((*it1).GetRRType() == type)) { *answer = &(*it1); return true; } it1++; } return false; } bool _MDNSPacket::GetAnswer(qcc::String str, MDNSResourceRecord::RRType type, uint16_t version, MDNSResourceRecord** answer) { if (type != MDNSResourceRecord::TXT) { return false; } std::vector<MDNSResourceRecord>::iterator it1 = m_answers.begin(); while (it1 != m_answers.end()) { if (((*it1).GetDomainName() == str) && ((*it1).GetRRType() == type) && (static_cast<MDNSTextRData*>((*it1).GetRData())->GetU16Value("txtvers") == version)) { *answer = &(*it1); return true; } it1++; } return false; } void _MDNSPacket::AddAnswer(MDNSResourceRecord record) { m_answers.push_back(record); assert(m_answers.size() <= MIN_RESERVE); m_header.SetANCount(m_answers.size()); } bool _MDNSPacket::GetAnswerAt(uint32_t i, MDNSResourceRecord** answer) { if (i >= m_answers.size()) { return false; } *answer = &m_answers[i]; return true; } uint16_t _MDNSPacket::GetNumAnswers() { return m_answers.size(); } size_t _MDNSPacket::GetSerializedSize(void) const { std::map<qcc::String, uint32_t> offsets; size_t ret; size_t size = m_header.GetSerializedSize(); std::vector<MDNSQuestion>::const_iterator it = m_questions.begin(); while (it != m_questions.end()) { ret = (*it).GetSerializedSize(offsets); size += ret; it++; } std::vector<MDNSResourceRecord>::const_iterator it1 = m_answers.begin(); while (it1 != m_answers.end()) { ret = (*it1).GetSerializedSize(offsets); size += ret; it1++; } it1 = m_authority.begin(); while (it1 != m_authority.end()) { ret = (*it1).GetSerializedSize(offsets); size += ret; it1++; } it1 = m_additional.begin(); while (it1 != m_additional.end()) { ret = (*it1).GetSerializedSize(offsets); size += ret; it1++; } return size; } size_t _MDNSPacket::Serialize(uint8_t* buffer) const { std::map<qcc::String, uint32_t> offsets; size_t ret; size_t size = m_header.Serialize(buffer); size_t headerOffset = size; uint8_t* p = &buffer[size]; std::vector<MDNSQuestion>::const_iterator it = m_questions.begin(); while (it != m_questions.end()) { ret = (*it).Serialize(p, offsets, headerOffset); size += ret; headerOffset += ret; p += ret; it++; } std::vector<MDNSResourceRecord>::const_iterator it1 = m_answers.begin(); while (it1 != m_answers.end()) { ret = (*it1).Serialize(p, offsets, headerOffset); size += ret; headerOffset += ret; p += ret; it1++; } it1 = m_authority.begin(); while (it1 != m_authority.end()) { ret = (*it1).Serialize(p, offsets, headerOffset); size += ret; headerOffset += ret; p += ret; it1++; } it1 = m_additional.begin(); while (it1 != m_additional.end()) { ret = (*it1).Serialize(p, offsets, headerOffset); size += ret; headerOffset += ret; p += ret; it1++; } return size; } size_t _MDNSPacket::Deserialize(uint8_t const* buffer, uint32_t bufsize) { Clear(); std::map<uint32_t, qcc::String> compressedOffsets; size_t size = m_header.Deserialize(buffer, bufsize); size_t ret; if (size == 0) { QCC_DbgPrintf(("Error occured while deserializing header")); return size; } if (m_header.GetQRType() == MDNSHeader::MDNS_QUERY && m_header.GetQDCount() == 0) { //QRType = 0 and QDCount = 0. Invalid return 0; } if (size >= bufsize) { return 0; } bufsize -= size; uint8_t const* p = &buffer[size]; size_t headerOffset = size; for (int i = 0; i < m_header.GetQDCount(); i++) { MDNSQuestion q; ret = q.Deserialize(p, bufsize, compressedOffsets, headerOffset); if (ret == 0 || ret > bufsize) { QCC_DbgPrintf(("Error while deserializing question")); return 0; } size += ret; bufsize -= ret; p += ret; headerOffset += ret; m_questions.push_back(q); } for (int i = 0; i < m_header.GetANCount(); i++) { MDNSResourceRecord r; ret = r.Deserialize(p, bufsize, compressedOffsets, headerOffset); if (ret == 0 || ret > bufsize) { QCC_DbgPrintf(("Error while deserializing answer")); return 0; } size += ret; bufsize -= ret; p += ret; headerOffset += ret; m_answers.push_back(r); } for (int i = 0; i < m_header.GetNSCount(); i++) { MDNSResourceRecord r; ret = r.Deserialize(p, bufsize, compressedOffsets, headerOffset); if (ret == 0 || ret > bufsize) { QCC_DbgPrintf(("Error while deserializing NS")); return 0; } size += ret; bufsize -= ret; p += ret; headerOffset += ret; m_authority.push_back(r); } for (int i = 0; i < m_header.GetARCount(); i++) { MDNSResourceRecord r; ret = r.Deserialize(p, bufsize, compressedOffsets, headerOffset); if (ret == 0 || ret > bufsize) { QCC_DbgPrintf(("Error while deserializing additional")); return 0; } size += ret; bufsize -= ret; p += ret; headerOffset += ret; m_additional.push_back(r); } return size; } TransportMask _MDNSPacket::GetTransportMask() { TransportMask transportMask = TRANSPORT_NONE; if (GetHeader().GetQRType() == MDNSHeader::MDNS_QUERY) { MDNSQuestion* question; if (GetQuestion("_alljoyn._tcp.local.", &question)) { transportMask |= TRANSPORT_TCP; } if (GetQuestion("_alljoyn._udp.local.", &question)) { transportMask |= TRANSPORT_UDP; } } else { MDNSResourceRecord* answer; if (GetAnswer("_alljoyn._tcp.local.", MDNSResourceRecord::PTR, &answer)) { transportMask |= TRANSPORT_TCP; } if (GetAnswer("_alljoyn._udp.local.", MDNSResourceRecord::PTR, &answer)) { transportMask |= TRANSPORT_UDP; } } return transportMask; } void _MDNSPacket::RemoveAnswer(qcc::String str, MDNSResourceRecord::RRType type) { std::vector<MDNSResourceRecord>::iterator it1 = m_answers.begin(); while (it1 != m_answers.end()) { if (((*it1).GetDomainName() == str) && ((*it1).GetRRType() == type)) { m_answers.erase(it1++); return; } it1++; } } } // namespace ajn
27.154642
223
0.575983
[ "object", "vector" ]
ded0d518e72c2dbebbda30a795e68284ee6b674b
8,992
hxx
C++
src/Point.hxx
kb1vc/GeoProfII
d943d5777017af72b56ab8440d399e98b8d54e54
[ "BSD-2-Clause" ]
null
null
null
src/Point.hxx
kb1vc/GeoProfII
d943d5777017af72b56ab8440d399e98b8d54e54
[ "BSD-2-Clause" ]
null
null
null
src/Point.hxx
kb1vc/GeoProfII
d943d5777017af72b56ab8440d399e98b8d54e54
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2019 Matthew H. Reilly (kb1vc) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef POINT_HDR_DEF #define POINT_HDR_DEF #include <string> #include <regex> #include <cmath> #include <boost/format.hpp> /** * \class GeoProf::Point * * \brief Point implements navigation operations on a geographic point * on the surface of the earth. The Point object includes methods to * calculate the distance and bearing from one point to another, or the * location (point) at a given distance and bearing from a starting location. * * \author $Author: kb1vc $ * * \date $Date: 2005/04/14 14:16:20 $ * * Contact: kb1vc@kb1vc.org * */ namespace GeoProf { class Point { public: /** * @brief Create a point object from latitude, and longitude * * @param _lat the latitude of the point -- negative values are south of the equator * @param _lon the longitude of the point -- negative values are west of Grenwich * * Note that bearings between the poles are unlikely to make sense. * In places where every direction is "south" or "north" the math * is often beyond sensible limits. If your application requires * pole-to-pole paths, then look elsewhere, or just point south. */ Point(double _lat = 0.0, double _lon = 0.0) { lat = _lat; lon = _lon; } /** * @brief Create a point object from another point object * * @param orig the point that we're cloning. */ Point(const Point & orig) { lat = orig.lat; lon = orig.lon; } /** * @brief Create a point from a Maidenhead Grid specifier * * @param grid A Maidenhead Grid specifier of the form XXnnxx (capital * letter pair, digit pair, letter pair) */ Point(const std::string & grid) { grid2Pt(grid); } /** * @brief Return degrees latitude (negative is south of the equator) * * @return latitude */ double getLatitude() const { return lat; } /** * @brief Return degrees longitude (negative is west of the Grenwich) * * @return longitude */ double getLongitude() const { return lon; } /** * @brief Calculate the bearing (in degrees -- 0 is north) from this point to anothe point * along the shorter great circle route * * @param other the other point * @return bearing in degrees. */ double bearingTo(const Point & other) const; /** * @brief Calculate the great circle distance (in meters) from this point to another point * * @param other the other point * @return great circle distance in meters */ double distanceTo(const Point & other) const; /** * @brief Calculate the bearing (in degrees -- 0 is north) and distance (in meters) * from this point to another point * along the shorter great circle route * * @param other the other point * @param bearing (output) direction to the other point along the shorter great circle path * @param reverse_bearing direction of travel from other point to this point (in degrees, 0 is north) * @param distance (output) distance in meters to the other point along the shorter great circle path */ void bearingDistanceTo(const Point & other, double & bearing, double & reverse_bearing, double & distance) const; /** * @brief Return the point at which one would arrive after traveling on the * great circle path from this point at the specified bearing and for the specified distance. * * @param bearing direction of travel (in degrees, 0 is north) * @param distance of travel in meters * @param next (output) the point at which we'll arrive. */ void stepTo(double bearing, double distance, Point & next) const; /** * @brief convert this point to its Maidenhead Grid specifier * * @param grid (output) The Maidenhead Grid string XXnnxx */ void pt2Grid(std::string & grid) const; /** * @brief Set this point to the location of a Maidenhead Grid specifier * * @param grid A Maidenhead Grid specifier of the form XXnnxx (capital * letter pair, digit pair, letter pair) */ void grid2Pt(const std::string & grid); /** * @brief Set this point from a string describing the location in * degrees-minutes-seconds of latitude and logitude. Specification is * in lat degrees/minutes/seconds and lon degrees/minutes/seconds as * doubles. North/South/East/West * * @param lat_d latitude degrees * @param lat_m latitude minutes * @param lat_s latitude seconds * @param ns true if latitude is north of the equator * @param lon_d longitude degrees * @param lon_m longitude minutes * @param lon_s longitude seconds * @param ew true if latitude is east of Grenwich */ void dms2Pt(double lat_d, double lat_m, double lat_s, char ns, double lon_d, double lon_m, double lon_s, char ew); /** * @brief Correct the calculated bearing and distance by iterating * around the calculated values to find the minimum error. * * @param other the other point * @param bearing direction to the other point along the shorter great circle path * @param distance distance in meters to the other point along the shorter great circle path * @param new_bearing (output) corrected bearing * @param new_distance (output) corrected range * */ void correctBearingDistanceTo(const Point & other, const double bearing, const double distance, double & new_bearing, double & new_distance) const; std::string toString() const { char ns = ' '; if (lat > 0.) { ns = 'N'; } if (lat < 0.0) { ns = 'S'; } char ew = ' '; if (lon > 0.0) { ew = 'E'; } if (lon < 0.0) { ew = 'W'; } return (boost::format("%g %c %g %c") % lat % ns % lon % ew).str(); } private: /// Latitude South is negative, North is positive. double lat; /// Longitude West is negative, East is positive. double lon; static std::regex grid_regexp; // ("[A-R][A-R][0-9][0-9][A-X][A-X]", std::regex_constants::icase); /** * @brief Validate a string as a Maidenhead Grid specifier * * @param grid A Maidenhead Grid specifier of the form XXnnxx (capital * letter pair, digit pair, letter pair) * @return true if this is a properly formatted grid, false otherwise. */ bool checkGrid(const std::string & grid) const; /** * @brief Helper for translating char positions in a grid * locator into double offsets from 0 degrees. */ double gridDiff(char v, char s, double mul) const; /** * @brief four quadrant arc tangent returning result in the range 0..2pi * * @param y rise * @param x run * @return arctan in range 0..2pi */ double atan2Pt(double y, double x) const; /** * @brief translate an angle into the range 0..2pi * * @param ang angle in radians * @return angle in range 0..2pi */ double inSpan(double ang) const; // recursive helper to correctBearingDistanceTo bool recCorrectBearingDistanceTo(const Point & other, const double bearing, const double distance, const double b_span, const double d_span, double & new_bearing, double & new_distance ) const; // Useful constants static const double clarke_66_al; /*Clarke 1866 ellipsoid*/ static const double clarke_66_bl; static const double rad_per_deg; }; } #endif
32.698182
117
0.65714
[ "object" ]
ded98167f12c7e479b19aef1eb0d60b42355b792
6,851
cpp
C++
C++/src/bio/exes/main-pssm-calculate-normalisations.cpp
JohnReid/biopsy
1eeb714ba5b53f2ecf776d865d32e2078cbc0338
[ "MIT" ]
null
null
null
C++/src/bio/exes/main-pssm-calculate-normalisations.cpp
JohnReid/biopsy
1eeb714ba5b53f2ecf776d865d32e2078cbc0338
[ "MIT" ]
null
null
null
C++/src/bio/exes/main-pssm-calculate-normalisations.cpp
JohnReid/biopsy
1eeb714ba5b53f2ecf776d865d32e2078cbc0338
[ "MIT" ]
null
null
null
/** @file Copyright John Reid 2007, 2013 */ #include "bio-pch.h" #include <bio/application.h> #include <bio/hmm_gen_sequence.h> #include <bio/hmm_dna.h> #include <bio/options.h> #include <bio/random.h> #include <bio/biobase_filter.h> #include <bio/environment.h> #include <bio/biobase_likelihoods.h> #include <bio/serialisable.h> USING_BIO_NS; #include <boost/progress.hpp> #include <boost/program_options.hpp> using namespace boost; namespace po = boost::program_options; #include <iostream> #include <fstream> #include <vector> using namespace std; //#include <windows.h> #ifdef min #undef min #endif #ifdef max #undef max #endif /** * Calculates normalisations that are used to score PSSMs using old(ish) scoring method. Generates random sequences and then * applies PSSMs to them in order to empirically estimate a distribution of scores (or likeilhoods?). * Can either generate sequences from a uniform background distribution or from higher-order Markov models trained * on specific species. Will run indefinitely until interrupted with Ctrl-C and will store estimates on a regular basis or when * requested to using Ctrl-BREAK. */ struct CalculateNormalisationsApp : Application { size_t seq_length; bool use_uniform_dist; unsigned hmm_num_states; unsigned hmm_order; unsigned serialise_every_so_often; bool want_to_exit; bool want_to_serialise; bool have_reported_count_mismatch; CalculateNormalisationsApp() : want_to_exit( false ) , want_to_serialise( false ) , have_reported_count_mismatch( false ) { get_options().add_options() ("seq_length", po::value(&seq_length)->default_value(2000), "length of sequence to normalise over") ("use_uniform_dist", po::bool_switch(&use_uniform_dist)->default_value(false), "use a uniform distribution") ("hmm_num_states", po::value(&hmm_num_states)->default_value(1), "number of states in HMM") ("hmm_order", po::value(&hmm_order)->default_value(3), "order of HMM") ("serialise,s", po::value(&serialise_every_so_often)->default_value(0), "serialise every so often (s)") ; } virtual bool ctrl_handler( CtrlSignal signal ) { want_to_serialise = true; want_to_exit = CTRL_BREAK_SIGNAL != signal; if ( want_to_exit ) { cout << "Will store values and exit at next iteration" << endl; } else { cout << "Will store values and continue at next iteration" << endl; } return true; } struct has_total_counts_at_most { unsigned num; has_total_counts_at_most( unsigned num ) : num( num ) { } template< typename MapValue > bool operator()( const MapValue & value ) const { return num >= LikelihoodsCache::singleton().get_total_counts( value.first ); } }; template< typename PssmIt > void calculate_scores( PssmIt pssms_begin, PssmIt pssms_end, const seq_t & norm_seq) { //first see what the maximum and minimum # scores for each pssm unsigned min_total_counts = pssms_end == pssms_begin ? 0 : std::numeric_limits< unsigned >::max(); unsigned max_total_counts = 0; for( PssmIt p = pssms_begin; pssms_end != p; ++p ) { const TableLink link = p->first; const unsigned total_counts = LikelihoodsCache::singleton().get_total_counts( link ); min_total_counts = std::min( total_counts, min_total_counts ); max_total_counts = std::max( total_counts, max_total_counts ); } if( min_total_counts != max_total_counts && ! have_reported_count_mismatch ) { std::cout << "Smallest # normalisation counts: " << min_total_counts << endl << "Largest # normalisation counts: " << max_total_counts << endl; have_reported_count_mismatch = true; } //restrict the iterators to those with the counts at most a weighted avg of min and max const unsigned count_threshold = ( min_total_counts + 9 * max_total_counts ) / 10; LikelihoodsCache::singleton().quantise_counts( make_filter_iterator( has_total_counts_at_most( count_threshold ), pssms_begin, pssms_end ), make_filter_iterator( has_total_counts_at_most( count_threshold ), pssms_end, pssms_end ), norm_seq ); } int task() { cout << "Using sequence length of " << seq_length << endl; if (use_uniform_dist) { cout << "Will generate sequences from uniform random distribution" << endl; } else { cout << "Will generate sequences from species HMMs" << endl; } if( serialise_every_so_often > 0 ) { cout << "Will serialise normalisations every " << serialise_every_so_often << " seconds\n"; } else { cout << "Will only serialise normalisations on request\n"; } register_ctrl_handler(); cout << endl << "Hit Ctrl-BREAK to save current state" << endl << "Hit Ctrl-C to save current state and exit" << endl << endl; const BiobasePssmFilter filter = BiobasePssmFilter::get_all_pssms_filter(); //use the timer to decide whether to serialise every so often boost::timer timer; //repeat until user breaks cout << "Updating counts over random sequences" << endl; while( true ) { seq_t norm_seq; norm_seq.reserve( seq_length ); { if ( use_uniform_dist ) { generate_random_nucleotide_seq( inserter( norm_seq, norm_seq.begin() ), seq_length ); } else { DnaHmmOrderNumStateMap & hmm_map = DnaHmmOrderNumStateMap::singleton(); if (! hmm_map.contains_model(hmm_num_states, hmm_order)) { throw std::logic_error( "Do not have model with that # states and order" ); } hmm_map.get_model( hmm_num_states, hmm_order ).append_random_sequence( norm_seq, seq_length ); } } //check we have some pssms to work on if( get_matrices_begin( filter ) == get_matrices_end( filter ) && get_sites_begin( filter ) == get_sites_end( filter ) ) { throw std::logic_error( "No pssms to work on - pssm filter too restrictive" ); } //estimate the scores for each matrix and site on the sequence calculate_scores( get_matrices_begin( filter ), get_matrices_end( filter ), norm_seq); calculate_scores( get_sites_begin( filter ), get_sites_end( filter ), norm_seq); //do we want to serialise because we have been running for so long? if( serialise_every_so_often > 0 && timer.elapsed() > double( serialise_every_so_often ) ) { want_to_serialise = true; timer.restart(); } //are we going to serialise the scores? if( want_to_serialise ) { cout << "Storing values" << endl; serialise< false >( LikelihoodsCache::singleton(), boost::filesystem::path( BioEnvironment::singleton().get_likelihoods_cache_file() ) ); want_to_serialise = false; have_reported_count_mismatch = false; //do we want to exit? if( want_to_exit ) { break; } } } return 0; } }; int main(int argc, char * argv []) { return CalculateNormalisationsApp().main(argc, argv); }
26.972441
127
0.704423
[ "vector", "model" ]
dedea8a2f1fdf8de97d9cbbeaa53e78d8c421aae
10,002
cpp
C++
src/leetcodeChallenge/BackTracking.cpp
jlyharia/Algorithm
5afc78013cf2e46f21e512492bf18d96400afd0c
[ "MIT" ]
null
null
null
src/leetcodeChallenge/BackTracking.cpp
jlyharia/Algorithm
5afc78013cf2e46f21e512492bf18d96400afd0c
[ "MIT" ]
null
null
null
src/leetcodeChallenge/BackTracking.cpp
jlyharia/Algorithm
5afc78013cf2e46f21e512492bf18d96400afd0c
[ "MIT" ]
null
null
null
// // Created by Yihung Lee on 2018-12-01. // #include "BackTracking.hpp" vector<string> BackTracking::letterCombinations(string digits) { if (digits.empty()) return {}; const unordered_map<char, string> map{ {'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}, }; vector<string> ans; letterCombinationsHelper(ans, digits, "", 0, map); return ans; } void BackTracking::letterCombinationsHelper(vector<string> &ans, const string digits, string res, int idx, const unordered_map<char, string> &map) { if (res.size() == digits.size()) { ans.push_back(res); } else { for (auto s : map.at(digits[idx])) { letterCombinationsHelper(ans, digits, res + s, idx + 1, map); } } } /** * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. */ vector<string> BackTracking::generateParenthesis(int n) { vector<string> ans; generateParenthesisHelper(n, n, "", ans); return ans; } void BackTracking::generateParenthesisHelper(int L, int R, string res, vector<string> &ans) { if (L == 0 && R == 0) { ans.push_back(res); } else if (L >= 0 && L <= R) { generateParenthesisHelper(L - 1, R, res + '(', ans); generateParenthesisHelper(L, R - 1, res + ')', ans); } } /** * http://www.cnblogs.com/grandyang/p/4428207.html */ void BackTracking::nextPermutation(vector<int> &nums) { int n = nums.size(), i = n - 2, j = n - 1; while (i >= 0 && nums[i] >= nums[i + 1]) --i; if (i >= 0) { while (nums[j] <= nums[i]) --j; swap(nums[i], nums[j]); } reverse(nums.begin() + i + 1, nums.end()); } bool BackTracking::isValidSudoku(vector<vector<char>> &board) { // row for (int i = 0; i < 9; i++) { std::vector<bool> check(9, false); for (int j = 0; j < 9; j++) { if (std::isdigit(board[i][j])) { int d = board[i][j] - '0'; if (check[d - 1]) { return false; } else { check[d - 1] = true; } } } } // column for (int j = 0; j < 9; j++) { std::vector<bool> check(9, false); for (int i = 0; i < 9; i++) { if (std::isdigit(board[i][j])) { int d = board[i][j] - '0'; if (check[d - 1]) { return false; } else { check[d - 1] = true; } } } } // 3x3 section for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { std::vector<bool> check(9, false); // section for (int si = 0; si < 3; si++) { for (int sj = 0; sj < 3; sj++) { int r = 3 * i + si; int c = 3 * j + sj; if (std::isdigit(board[r][c])) { int d = board[r][c] - '0'; if (check[d - 1]) { return false; } else { check[d - 1] = true; } } } } } } return true; } void BackTracking::solveSudoku(vector<vector<char>> &board) { if (board.empty() || board.size() != 9 || board[0].size() != 9) return; solveSudokuHelper(board, 0, 0); } bool BackTracking::solveSudokuHelper(vector<vector<char>> &board, int i, int j) { if (i == 9) return true; if (j >= 9) return solveSudokuHelper(board, i + 1, 0); if (board[i][j] == '.') { for (int k = 1; k < 10; k++) { board[i][j] = (char) ('0' + k); if (isValidSudokuNumber(board, i, j)) { if (solveSudokuHelper(board, i, j + 1)) return true; } board[i][j] = '.'; } } else { return solveSudokuHelper(board, i, j + 1); } return false; } bool BackTracking::isValidSudokuNumber(vector<vector<char>> &board, int i, int j) { vector<int> check(9, false); // col for (int col = 0; col < 9; col++) { if (col != j && board[i][j] == board[i][col]) return false; } // row for (int row = 0; row < 9; row++) { if (i != row && board[i][j] == board[row][j]) { return false; } } // section for (int row = i / 3 * 3; row < i / 3 * 3 + 3; ++row) { for (int col = j / 3 * 3; col < j / 3 * 3 + 3; ++col) { if ((row != i || col != j) && board[i][j] == board[row][col]) return false; } } return true; } /** * * http://www.cnblogs.com/grandyang/p/4419259.html * Similar Question * Path Sum II,Subsets II,Permutations,Permutations II,Combinations */ vector<vector<int>> BackTracking::combinationSum(vector<int> &&candidates, int target) { vector<vector<int>> res; combinationSumDFS(candidates, target, 0, {}, res); return res; } void BackTracking::combinationSumDFS(vector<int> &candidates, int target, int start, vector<int> out, vector<vector<int>> &ans) { if (target == 0) { ans.push_back(out); } else { for (int i = start; i < candidates.size(); i++) { int temp = target - candidates[i]; if (temp < 0) { break; } out.push_back(candidates[i]); combinationSumDFS(candidates, temp, i, out, ans); out.pop_back(); } } } vector<vector<int>> BackTracking::subsets(vector<int> &&nums) { vector<vector<int>> ans; vector<int> out; std::sort(nums.begin(), nums.end()); dfsSubsets(nums, 0, out, ans); return ans; } void BackTracking::dfsSubsets(vector<int> &nums, int pos, vector<int> &out, vector<vector<int>> &ans) { if (pos == nums.size()) { ans.push_back(out); } else { out.push_back(nums[pos]); dfsSubsets(nums, pos + 1, out, ans); out.pop_back(); dfsSubsets(nums, pos + 1, out, ans); } } vector<vector<int>> BackTracking::permute(vector<int> &nums) { } vector<vector<int>> BackTracking::permuteUnique(vector<int> &&nums) { vector<vector<int>> res; vector<int> out, visited(nums.size(), 0); sort(nums.begin(), nums.end()); permuteUniqueDFS(nums, 0, visited, out, res); return res; } void BackTracking::permuteUniqueDFS(vector<int> &nums, int level, vector<int> &visited, vector<int> &out, vector<vector<int>> &res) { if (level >= nums.size()) { res.push_back(out); return; } for (int i = 0; i < nums.size(); ++i) { if (visited[i] == 1) continue; if (i > 0 && nums[i] == nums[i - 1] && visited[i - 1] == 0) { continue; } visited[i] = 1; out.push_back(nums[i]); permuteUniqueDFS(nums, level + 1, visited, out, res); out.pop_back(); visited[i] = 0; } } vector<vector<int>> BackTracking::combinationSum2(vector<int> &&candidates, int target) { vector<int> out; vector<vector<int>> ans; std::sort(candidates.begin(), candidates.end()); combinationSum2DFS(candidates, target, 0, out, ans); return ans; } void BackTracking::combinationSum2DFS(vector<int> &candidates, int target, int pos, vector<int> &out, vector<vector<int>> &ans) { if (target == 0) { ans.push_back(out); } else { for (int i = pos; i < candidates.size(); i++) { int temp = target - candidates[i]; if (temp < 0) { break; } if (i > pos && candidates[i - 1] == candidates[i]) { continue; } out.push_back(candidates[i]); combinationSum2DFS(candidates, temp, i + 1, out, ans); out.pop_back(); } } } vector<vector<int>> BackTracking::subsetsWithDup(vector<int> &&nums) { vector<bool> visit(nums.size(), false); vector<int> out; vector<vector<int>> ans; std::sort(nums.begin(), nums.end()); dfsSubsetsWithDup(nums, 0, visit, out, ans); return ans; } void BackTracking::dfsSubsetsWithDup(vector<int> &nums, int pos, vector<bool> &visit, vector<int> &out, vector<vector<int>> &ans) { if (pos == nums.size()) { ans.push_back(out); } else { if (!(pos > 0 && nums[pos] == nums[pos - 1] && !visit[pos - 1])) { visit[pos] = true; out.push_back(nums[pos]); dfsSubsetsWithDup(nums, pos + 1, visit, out, ans); out.pop_back(); visit[pos] = false; } dfsSubsetsWithDup(nums, pos + 1, visit, out, ans); } } vector<vector<int>> BackTracking::combinationSum3(int k, int n) { } int BackTracking::numIslands(vector<vector<char>> &grid) { if (grid.empty() || grid[0].empty()) return 0; vector<vector<bool>> visited(grid.size(), vector<bool>(grid[0].size(), false)); int num = 0; for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[i].size(); j++) { if (grid[i][j] == '1' && !visited[i][j]) { numIslandsDfs(grid, visited, i, j); num++; } } } return num; } void BackTracking::numIslandsDfs(vector<vector<char>> &grid, vector<vector<bool>> &visited, int x, int y) { if (x < 0 || y < 0 || x >= grid.size() || y >= grid[0].size() || visited[x][y] || grid[x][y] == '0') { return; } visited[x][y] = true; numIslandsDfs(grid, visited, x + 1, y); numIslandsDfs(grid, visited, x - 1, y); numIslandsDfs(grid, visited, x, y + 1); numIslandsDfs(grid, visited, x, y - 1); }
30.493902
107
0.492901
[ "vector" ]
deeb51c4dd4150a65164b684b5331a93c58bee87
4,133
cpp
C++
plugins/community/repos/DHE-Modules/plugin/src/tapers.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
233
2018-07-02T16:49:36.000Z
2022-02-27T21:45:39.000Z
plugins/community/repos/DHE-Modules/plugin/src/tapers.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-09T11:32:15.000Z
2022-01-07T01:45:43.000Z
plugins/community/repos/DHE-Modules/plugin/src/tapers.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-14T21:55:30.000Z
2021-05-04T04:20:34.000Z
#include "dhe-modules.h" #include "display/controls.h" #include "display/panel.h" #include "util/rotation.h" #include "util/sigmoid.h" #include "util/signal.h" namespace DHE { class Tapers : public rack::Module { public: Tapers() : Module{PARAMETER_COUNT, INPUT_COUNT, OUTPUT_COUNT} {} void step() override { outputs[OUT_1].value = taper(level1(), is_uni_1(), curvature1(), is_s_1()); outputs[OUT_2].value = taper(level2(), is_uni_2(), curvature2(), is_s_2()); } enum ParameterIds { LEVEL_1_KNOB, LEVEL_1_AV, RANGE_1_SWITCH, CURVE_1_KNOB, CURVE_1_AV, SHAPE_1_SWITCH, LEVEL_2_KNOB, LEVEL_2_AV, RANGE_2_SWITCH, CURVE_2_KNOB, CURVE_2_AV, SHAPE_2_SWITCH, PARAMETER_COUNT }; enum InputIds { LEVEL_1_CV, CURVE_1_CV, LEVEL_2_CV, CURVE_2_CV, INPUT_COUNT }; enum OutputIds { OUT_1, OUT_2, OUTPUT_COUNT }; private: auto curvature(ParameterIds knob, InputIds cv, ParameterIds av) const -> float { auto curvature = modulated(knob, cv, av); return Sigmoid::curvature(curvature); } auto curvature1() const -> float { return curvature(CURVE_1_KNOB, CURVE_1_CV, CURVE_1_AV); } auto curvature2() const -> float { return curvature(CURVE_2_KNOB, CURVE_2_CV, CURVE_2_AV); } auto is_uni_1() const -> bool { return params[RANGE_1_SWITCH].value > 0.5f; } auto is_uni_2() const -> bool { return params[RANGE_2_SWITCH].value > 0.5f; } auto is_s_1() const -> bool { return params[SHAPE_1_SWITCH].value > 0.5f; } auto is_s_2() const -> bool { return params[SHAPE_2_SWITCH].value > 0.5f; } auto level1() const -> float { return modulated(LEVEL_1_KNOB, LEVEL_1_CV, LEVEL_1_AV); } auto level2() const -> float { return modulated(LEVEL_2_KNOB, LEVEL_2_CV, LEVEL_2_AV); } auto modulated(ParameterIds knob_param, InputIds cv_input, ParameterIds av_param) const -> float { auto rotation = params[knob_param].value; auto cv = inputs[cv_input].value; auto av = params[av_param].value; return Rotation::modulated(rotation, cv, av); } auto taper(float level, bool is_uni, float curve, bool is_s) const -> float { auto tapered = Sigmoid::taper(level, curve, is_s); return Signal::range(is_uni).scale(tapered); } }; class TapersPanel : public Panel<TapersPanel> { public: explicit TapersPanel(Tapers *module) : Panel{module, hp} { auto widget_right_edge = width(); auto column_1 = width() / 5.f + 0.333333333f; auto column_2 = widget_right_edge / 2.f; auto column_3 = widget_right_edge - column_1; auto y = 24.f; auto dy = 16.f; auto panel_buffer = 4.f; install(column_1, y, input(Tapers::LEVEL_1_CV)); install(column_2, y, knob<TinyKnob>(Tapers::LEVEL_1_AV)); install(column_3, y, knob<MediumKnob>(Tapers::LEVEL_1_KNOB)); y += dy; install(column_1, y, input(Tapers::CURVE_1_CV)); install(column_2, y, knob<TinyKnob>(Tapers::CURVE_1_AV)); install(column_3, y, knob<MediumKnob>(Tapers::CURVE_1_KNOB)); y += dy; install(column_1, y, toggle<2>(Tapers::SHAPE_1_SWITCH, 0)); install(column_2, y, toggle<2>(Tapers::RANGE_1_SWITCH, 1)); install(column_3, y, output(Tapers::OUT_1)); y += dy + panel_buffer; install(column_1, y, input(Tapers::LEVEL_2_CV)); install(column_2, y, knob<TinyKnob>(Tapers::LEVEL_2_AV)); install(column_3, y, knob<MediumKnob>(Tapers::LEVEL_2_KNOB)); y += dy; install(column_1, y, input(Tapers::CURVE_2_CV)); install(column_2, y, knob<TinyKnob>(Tapers::CURVE_2_AV)); install(column_3, y, knob<MediumKnob>(Tapers::CURVE_2_KNOB)); y += dy; install(column_1, y, toggle<2>(Tapers::SHAPE_2_SWITCH, 0)); install(column_2, y, toggle<2>(Tapers::RANGE_2_SWITCH, 1)); install(column_3, y, output(Tapers::OUT_2)); } static constexpr auto module_slug = "tapers"; public: static constexpr auto hp = 9; }; } // namespace DHE RACK_PLUGIN_MODEL_INIT(DHE_Modules, Tapers) { rack::Model *modelTapers = rack::Model::create<DHE::Tapers, DHE::TapersPanel>( "DHE-Modules", "Tapers", "Tapers", rack::UTILITY_TAG); return modelTapers; }
31.310606
81
0.681345
[ "model" ]
def48b75dfa3c2e6fb31891e0f08d72441727b28
749
cpp
C++
code/shopaholic.cpp
matthewReff/Kattis-Problems
848628af630c990fb91bde6256a77afad6a3f5f6
[ "MIT" ]
8
2020-02-21T22:21:01.000Z
2022-02-16T05:30:54.000Z
code/shopaholic.cpp
matthewReff/Kattis-Problems
848628af630c990fb91bde6256a77afad6a3f5f6
[ "MIT" ]
null
null
null
code/shopaholic.cpp
matthewReff/Kattis-Problems
848628af630c990fb91bde6256a77afad6a3f5f6
[ "MIT" ]
3
2020-08-05T05:42:35.000Z
2021-08-30T05:39:51.000Z
#define _USE_MATH_DEFINES #include <iostream> #include <stdio.h> #include <cmath> #include <iomanip> #include <vector> #include <string> #include <algorithm> #include <unordered_set> #include <unordered_map> #include <ctype.h> #include <queue> #include <map> #include <set> typedef long long ll; typedef unsigned long long ull; using namespace std; int main() { ll i, j, k; ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll items; cin >> items; vector<ll> prices(items); for(i = 0; i < items; i++) { cin >> prices[i]; } sort(prices.rbegin(), prices.rend()); ll total = 0; for(i = 2; i < items; i+=3) { total += prices[i]; } cout << total; return 0; }
15.285714
41
0.594126
[ "vector" ]
def6ad896a289259405ddca085b6cdd7baeb9eaa
1,302
cpp
C++
Matrix/LargestRectangleContainingAllOnes/LargestRectangleContainingAllOnes.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Matrix/LargestRectangleContainingAllOnes/LargestRectangleContainingAllOnes.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Matrix/LargestRectangleContainingAllOnes/LargestRectangleContainingAllOnes.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
/* Problem statement: Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area. Bonus if you can solve it in O(n^2) or less. Example : A : [ 1 1 1 0 1 1 1 0 0 ] Output : 4 As the max area rectangle is created by the 2x2 rectangle created by (0,1), (0,2), (1,1) and (1,2) */ int Solution::maximalRectangle(vector<vector<int> > &A) { int ans = 0; for(int top = 0;top < A.size();top++) { vector<int> v(A[0].size(),0); for(int bottom = top;bottom < A.size();bottom++) { for(int i = 0; i < A[0].size();i++) { if(A[bottom][i] == 0) { v[i] = INT_MIN; } else { v[i] += A[bottom][i]; } } int max_so_far = INT_MIN, max_ending_here = 0; for (int i = 0; i < v.size(); i++) { max_ending_here = max_ending_here + v[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } ans = max(ans,max_so_far); } } return ans; }
25.529412
136
0.459293
[ "vector" ]
defced9cde068c07654ed502b0e410f08ef74449
4,606
cpp
C++
src/plugins/lmp/biopropproxy.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/plugins/lmp/biopropproxy.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/plugins/lmp/biopropproxy.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "biopropproxy.h" #include <algorithm> #include <QStandardItemModel> #include <QApplication> #include <QtDebug> #include <util/models/rolenamesmixin.h> namespace LeechCraft { namespace LMP { namespace { class ArtistImagesModel : public Util::RoleNamesMixin<QStandardItemModel> { public: enum Role { ThumbURL = Qt::UserRole + 1, FullURL, Title, Author, Date }; ArtistImagesModel (QObject *parent) : Util::RoleNamesMixin<QStandardItemModel> (parent) { QHash<int, QByteArray> roleNames; roleNames [Role::ThumbURL] = "thumbURL"; roleNames [Role::FullURL] = "fullURL"; roleNames [Role::Title] = "title"; roleNames [Role::Author] = "author"; roleNames [Role::Date] = "date"; setRoleNames (roleNames); } }; } BioPropProxy::BioPropProxy (QObject *parent) : QObject (parent) , ArtistImages_ (new ArtistImagesModel (this)) { } void BioPropProxy::SetBio (const Media::ArtistBio& bio) { Bio_ = bio; QStringList tags; std::transform (Bio_.BasicInfo_.Tags_.begin (), Bio_.BasicInfo_.Tags_.end (), std::back_inserter (tags), [] (decltype (Bio_.BasicInfo_.Tags_.front ()) item) { return item.Name_; }); CachedTags_ = tags.join ("; "); CachedInfo_ = Bio_.BasicInfo_.FullDesc_.isEmpty () ? Bio_.BasicInfo_.ShortDesc_ : Bio_.BasicInfo_.FullDesc_; CachedInfo_.replace ("\n", "<br />"); if (auto rc = ArtistImages_->rowCount ()) ArtistImages_->removeRows (0, rc); QList<QStandardItem*> rows; for (const auto& imageItem : bio.OtherImages_) { auto item = new QStandardItem (); item->setData (imageItem.Thumb_, ArtistImagesModel::Role::ThumbURL); item->setData (imageItem.Full_, ArtistImagesModel::Role::FullURL); item->setData (imageItem.Title_, ArtistImagesModel::Role::Title); item->setData (imageItem.Author_, ArtistImagesModel::Role::Author); item->setData (imageItem.Date_, ArtistImagesModel::Role::Date); rows << item; } if (!rows.isEmpty ()) ArtistImages_->invisibleRootItem ()->appendRows (rows); emit artistNameChanged (GetArtistName ()); emit artistImageURLChanged (GetArtistImageURL ()); emit artistBigImageURLChanged (GetArtistBigImageURL ()); emit artistTagsChanged (GetArtistTags ()); emit artistInfoChanged (GetArtistInfo ()); emit artistPageURLChanged (GetArtistPageURL ()); } QString BioPropProxy::GetArtistName () const { return Bio_.BasicInfo_.Name_; } QUrl BioPropProxy::GetArtistImageURL () const { return Bio_.BasicInfo_.Image_; } QUrl BioPropProxy::GetArtistBigImageURL () const { return Bio_.BasicInfo_.LargeImage_; } QString BioPropProxy::GetArtistTags () const { return CachedTags_; } QString BioPropProxy::GetArtistInfo () const { return CachedInfo_; } QUrl BioPropProxy::GetArtistPageURL () const { return Bio_.BasicInfo_.Page_; } QObject* BioPropProxy::GetArtistImagesModel () const { return ArtistImages_; } } }
30.706667
80
0.701911
[ "object", "transform" ]
72098339b4c484616edc10b4f9b629d17e19bdaa
2,558
cpp
C++
extension/sv_helper/SGA/Util/Contig.cpp
GenePlus/ncsv
f0f426ae4b64de86eee88518e3a1daf5718ce407
[ "Apache-2.0", "MIT" ]
1
2020-09-30T09:31:20.000Z
2020-09-30T09:31:20.000Z
extension/sv_helper/SGA/Util/Contig.cpp
GenePlus/ncsv
f0f426ae4b64de86eee88518e3a1daf5718ce407
[ "Apache-2.0", "MIT" ]
null
null
null
extension/sv_helper/SGA/Util/Contig.cpp
GenePlus/ncsv
f0f426ae4b64de86eee88518e3a1daf5718ce407
[ "Apache-2.0", "MIT" ]
null
null
null
#include "Contig.h" // // Statics // static const char* IDFIELD = "ID"; static const char* LENFIELD = "LN"; static const char* COVFIELD = "CV"; static const char* SEQFIELD = "SQ"; static const char* UNQFIELD = "UN"; static const char* ANTFIELD = "AN"; Contig::Contig() : m_length(0), m_coverage(0.0f), m_uniqueFlag(UF_UNKNOWN) {} // // // std::istream& readFasta(std::istream& in, Contig& c) { in.ignore(1); // skip ">" in >> c.m_id >> c.m_length >> c.m_coverage; // read header in.ignore(1); // skip newline in >> c.m_seq; // read seq in.ignore(1); // place the ifstream at the next line return in; } std::istream& readCAF(std::istream& in, Contig& c) { std::string line; getline(in, line); std::stringstream tokenizer(line); std::string token; while(tokenizer >> token) { std::string key; std::string value; splitKeyValue(token, key, value); c.setFromKeyValue(key, value); } assert(c.getSequence().size() == c.getLength()); return in; } // // // SequenceVector Contig::getVariants() const { SequenceVector out; out.push_back(getSequence()); out.insert(out.end(), m_variants.begin(), m_variants.end()); return out; } // // // void Contig::addVariants(const SequenceVector& seqs) { m_variants.insert(m_variants.end(), seqs.begin(), seqs.end()); } // // // std::ostream& writeCAF(std::ostream& out, Contig& c) { std::vector<std::string> fields; // ID fields.push_back(makeKeyValue(IDFIELD, c.m_id)); fields.push_back(makeKeyValue(LENFIELD, c.m_length)); fields.push_back(makeKeyValue(COVFIELD, c.m_coverage)); fields.push_back(makeKeyValue(SEQFIELD, c.m_seq)); fields.push_back(makeKeyValue(UNQFIELD, c.m_uniqueFlag)); std::copy(fields.begin(), fields.end(), std::ostream_iterator<std::string>(out, "\t")); return out; } // // Set a field based on a key/value pair // void Contig::setFromKeyValue(std::string& key, std::string& value) { std::stringstream parser(value); if(key == IDFIELD) parser >> m_id; else if(key == LENFIELD) parser >> m_length; else if(key == COVFIELD) parser >> m_coverage; else if(key == SEQFIELD) parser >> m_seq; else if(key == ANTFIELD) parser >> m_annotation; else if(key == UNQFIELD) { int v; parser >> v; m_uniqueFlag = (UniqueFlag)v; } else assert(false && "Unknown token found while parsing contig"); }
23.254545
91
0.608679
[ "vector" ]
720dd79bdb0181184c6a47353ffcf393f50858b9
76,238
cpp
C++
Common_3/OS/Image/Image.cpp
ValtoLibraries/The-Forge
56edfc8828bdb31da60e3386478334d8f95c2b8e
[ "Apache-2.0" ]
null
null
null
Common_3/OS/Image/Image.cpp
ValtoLibraries/The-Forge
56edfc8828bdb31da60e3386478334d8f95c2b8e
[ "Apache-2.0" ]
null
null
null
Common_3/OS/Image/Image.cpp
ValtoLibraries/The-Forge
56edfc8828bdb31da60e3386478334d8f95c2b8e
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018-2019 Confetti Interactive Inc. * * This file is part of The-Forge * (see https://github.com/ConfettiFX/The-Forge). * * 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. */ //this is needed for unix as PATH_MAX is defined instead of MAX_PATH #ifndef _WIN32 #include <limits.h> #define MAX_PATH PATH_MAX #endif #include "../../ThirdParty/OpenSource/EASTL/functional.h" #include "../../ThirdParty/OpenSource/EASTL/unordered_map.h" #define IMAGE_CLASS_ALLOWED #include "Image.h" #include "../Interfaces/ILog.h" #include "../../ThirdParty/OpenSource/TinyEXR/tinyexr.h" //stb_image #define STB_IMAGE_IMPLEMENTATION #define STBI_MALLOC conf_malloc #define STBI_REALLOC conf_realloc #define STBI_FREE conf_free #define STBI_ASSERT ASSERT #if defined(__ANDROID__) #define STBI_NO_SIMD #endif #include "../../ThirdParty/OpenSource/Nothings/stb_image.h" //stb_image_write #define STB_IMAGE_WRITE_IMPLEMENTATION #define STBIW_MALLOC conf_malloc #define STBIW_REALLOC conf_realloc #define STBIW_FREE conf_free #define STBIW_ASSERT ASSERT #include "../../ThirdParty/OpenSource/Nothings/stb_image_write.h" #define STB_IMAGE_RESIZE_IMPLEMENTATION #include "../../ThirdParty/OpenSource/Nothings/stb_image_resize.h" #include "../Interfaces/IMemory.h" // --- IMAGE HEADERS --- #pragma pack(push, 1) #define DDPF_ALPHAPIXELS 0x00000001 #define DDPF_FOURCC 0x00000004 #define DDPF_RGB 0x00000040 #define DDSD_CAPS 0x00000001 #define DDSD_HEIGHT 0x00000002 #define DDSD_WIDTH 0x00000004 #define DDSD_PITCH 0x00000008 #define DDSD_PIXELFORMAT 0x00001000 #define DDSD_MIPMAPCOUNT 0x00020000 #define DDSD_LINEARSIZE 0x00080000 #define DDSD_DEPTH 0x00800000 #define DDSCAPS_COMPLEX 0x00000008 #define DDSCAPS_TEXTURE 0x00001000 #define DDSCAPS_MIPMAP 0x00400000 #define DDSCAPS2_CUBEMAP 0x00000200 #define DDSCAPS2_VOLUME 0x00200000 #define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400 #define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800 #define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000 #define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000 #define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000 #define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000 #define DDSCAPS2_CUBEMAP_ALL_FACES \ (DDSCAPS2_CUBEMAP_POSITIVEX | DDSCAPS2_CUBEMAP_NEGATIVEX | DDSCAPS2_CUBEMAP_POSITIVEY | DDSCAPS2_CUBEMAP_NEGATIVEY | \ DDSCAPS2_CUBEMAP_POSITIVEZ | DDSCAPS2_CUBEMAP_NEGATIVEZ) #define D3D10_RESOURCE_MISC_TEXTURECUBE 0x4 #define D3D10_RESOURCE_DIMENSION_BUFFER 1 #define D3D10_RESOURCE_DIMENSION_TEXTURE1D 2 #define D3D10_RESOURCE_DIMENSION_TEXTURE2D 3 #define D3D10_RESOURCE_DIMENSION_TEXTURE3D 4 struct DDSHeader { uint32 mDWMagic; uint32 mDWSize; uint32 mDWFlags; uint32 mDWHeight; uint32 mDWWidth; uint32 mDWPitchOrLinearSize; uint32 mDWDepth; uint32 mDWMipMapCount; uint32 mReserved[11]; struct { uint32 mDWSize; uint32 mDWFlags; uint32 mDWFourCC; uint32 mDWRGBBitCount; uint32 mDWRBitMask; uint32 mDWGBitMask; uint32 mDWBBitMask; uint32 mDWRGBAlphaBitMask; } mPixelFormat; struct { uint32 mDWCaps1; uint32 mDWCaps2; uint32 mReserved[2]; //caps3 and caps4 } mCaps; uint32 mDWReserved2; }; struct DDSHeaderDX10 { uint32 mDXGIFormat; uint32 mResourceDimension; uint32 mMiscFlag; uint32 mArraySize; uint32 mReserved; }; // Describes the header of a PVR header-texture typedef struct PVR_Header_Texture_TAG { uint32_t mVersion; uint32_t mFlags; //!< Various format flags. uint64_t mPixelFormat; //!< The pixel format, 8cc value storing the 4 channel identifiers and their respective sizes. uint32_t mColorSpace; //!< The Color Space of the texture, currently either linear RGB or sRGB. uint32_t mChannelType; //!< Variable type that the channel is stored in. Supports signed/uint32_t/short/char/float. uint32_t mHeight; //!< Height of the texture. uint32_t mWidth; //!< Width of the texture. uint32_t mDepth; //!< Depth of the texture. (Z-slices) uint32_t mNumSurfaces; //!< Number of members in a Texture Array. uint32_t mNumFaces; //!< Number of faces in a Cube Map. Maybe be a value other than 6. uint32_t mNumMipMaps; //!< Number of MIP Maps in the texture - NB: Includes top level. uint32_t mMetaDataSize; //!< Size of the accompanying meta data. } PVR_Texture_Header; #ifdef TARGET_IOS const uint32_t gPvrtexV3HeaderVersion = 0x03525650; #endif // KTX Container Data typedef enum KTXInternalFormat { KTXInternalFormat_RGB_UNORM = 0x1907, //GL_RGB KTXInternalFormat_BGR_UNORM = 0x80E0, //GL_BGR KTXInternalFormat_RGBA_UNORM = 0x1908, //GL_RGBA KTXInternalFormat_BGRA_UNORM = 0x80E1, //GL_BGRA KTXInternalFormat_BGRA8_UNORM = 0x93A1, //GL_BGRA8_EXT // unorm formats KTXInternalFormat_R8_UNORM = 0x8229, //GL_R8 KTXInternalFormat_RG8_UNORM = 0x822B, //GL_RG8 KTXInternalFormat_RGB8_UNORM = 0x8051, //GL_RGB8 KTXInternalFormat_RGBA8_UNORM = 0x8058, //GL_RGBA8 KTXInternalFormat_R16_UNORM = 0x822A, //GL_R16 KTXInternalFormat_RG16_UNORM = 0x822C, //GL_RG16 KTXInternalFormat_RGB16_UNORM = 0x8054, //GL_RGB16 KTXInternalFormat_RGBA16_UNORM = 0x805B, //GL_RGBA16 KTXInternalFormat_RGB10A2_UNORM = 0x8059, //GL_RGB10_A2 KTXInternalFormat_RGB10A2_SNORM_EXT = 0xFFFC, // snorm formats KTXInternalFormat_R8_SNORM = 0x8F94, //GL_R8_SNORM KTXInternalFormat_RG8_SNORM = 0x8F95, //GL_RG8_SNORM KTXInternalFormat_RGB8_SNORM = 0x8F96, //GL_RGB8_SNORM KTXInternalFormat_RGBA8_SNORM = 0x8F97, //GL_RGBA8_SNORM KTXInternalFormat_R16_SNORM = 0x8F98, //GL_R16_SNORM KTXInternalFormat_RG16_SNORM = 0x8F99, //GL_RG16_SNORM KTXInternalFormat_RGB16_SNORM = 0x8F9A, //GL_RGB16_SNORM KTXInternalFormat_RGBA16_SNORM = 0x8F9B, //GL_RGBA16_SNORM // unsigned integer formats KTXInternalFormat_R8U = 0x8232, //GL_R8UI KTXInternalFormat_RG8U = 0x8238, //GL_RG8UI KTXInternalFormat_RGB8U = 0x8D7D, //GL_RGB8UI KTXInternalFormat_RGBA8U = 0x8D7C, //GL_RGBA8UI KTXInternalFormat_R16U = 0x8234, //GL_R16UI KTXInternalFormat_RG16U = 0x823A, //GL_RG16UI KTXInternalFormat_RGB16U = 0x8D77, //GL_RGB16UI KTXInternalFormat_RGBA16U = 0x8D76, //GL_RGBA16UI KTXInternalFormat_R32U = 0x8236, //GL_R32UI KTXInternalFormat_RG32U = 0x823C, //GL_RG32UI KTXInternalFormat_RGB32U = 0x8D71, //GL_RGB32UI KTXInternalFormat_RGBA32U = 0x8D70, //GL_RGBA32UI KTXInternalFormat_RGB10A2U = 0x906F, //GL_RGB10_A2UI KTXInternalFormat_RGB10A2I_EXT = 0xFFFB, // signed integer formats KTXInternalFormat_R8I = 0x8231, //GL_R8I KTXInternalFormat_RG8I = 0x8237, //GL_RG8I KTXInternalFormat_RGB8I = 0x8D8F, //GL_RGB8I KTXInternalFormat_RGBA8I = 0x8D8E, //GL_RGBA8I KTXInternalFormat_R16I = 0x8233, //GL_R16I KTXInternalFormat_RG16I = 0x8239, //GL_RG16I KTXInternalFormat_RGB16I = 0x8D89, //GL_RGB16I KTXInternalFormat_RGBA16I = 0x8D88, //GL_RGBA16I KTXInternalFormat_R32I = 0x8235, //GL_R32I KTXInternalFormat_RG32I = 0x823B, //GL_RG32I KTXInternalFormat_RGB32I = 0x8D83, //GL_RGB32I KTXInternalFormat_RGBA32I = 0x8D82, //GL_RGBA32I // Floating formats KTXInternalFormat_R16F = 0x822D, //GL_R16F KTXInternalFormat_RG16F = 0x822F, //GL_RG16F KTXInternalFormat_RGB16F = 0x881B, //GL_RGB16F KTXInternalFormat_RGBA16F = 0x881A, //GL_RGBA16F KTXInternalFormat_R32F = 0x822E, //GL_R32F KTXInternalFormat_RG32F = 0x8230, //GL_RG32F KTXInternalFormat_RGB32F = 0x8815, //GL_RGB32F KTXInternalFormat_RGBA32F = 0x8814, //GL_RGBA32F KTXInternalFormat_R64F_EXT = 0xFFFA, //GL_R64F KTXInternalFormat_RG64F_EXT = 0xFFF9, //GL_RG64F KTXInternalFormat_RGB64F_EXT = 0xFFF8, //GL_RGB64F KTXInternalFormat_RGBA64F_EXT = 0xFFF7, //GL_RGBA64F // sRGB formats KTXInternalFormat_SR8 = 0x8FBD, //GL_SR8_EXT KTXInternalFormat_SRG8 = 0x8FBE, //GL_SRG8_EXT KTXInternalFormat_SRGB8 = 0x8C41, //GL_SRGB8 KTXInternalFormat_SRGB8_ALPHA8 = 0x8C43, //GL_SRGB8_ALPHA8 // Packed formats KTXInternalFormat_RGB9E5 = 0x8C3D, //GL_RGB9_E5 KTXInternalFormat_RG11B10F = 0x8C3A, //GL_R11F_G11F_B10F KTXInternalFormat_RG3B2 = 0x2A10, //GL_R3_G3_B2 KTXInternalFormat_R5G6B5 = 0x8D62, //GL_RGB565 KTXInternalFormat_RGB5A1 = 0x8057, //GL_RGB5_A1 KTXInternalFormat_RGBA4 = 0x8056, //GL_RGBA4 KTXInternalFormat_RG4_EXT = 0xFFFE, // Luminance Alpha formats KTXInternalFormat_LA4 = 0x8043, //GL_LUMINANCE4_ALPHA4 KTXInternalFormat_L8 = 0x8040, //GL_LUMINANCE8 KTXInternalFormat_A8 = 0x803C, //GL_ALPHA8 KTXInternalFormat_LA8 = 0x8045, //GL_LUMINANCE8_ALPHA8 KTXInternalFormat_L16 = 0x8042, //GL_LUMINANCE16 KTXInternalFormat_A16 = 0x803E, //GL_ALPHA16 KTXInternalFormat_LA16 = 0x8048, //GL_LUMINANCE16_ALPHA16 // Depth formats KTXInternalFormat_D16 = 0x81A5, //GL_DEPTH_COMPONENT16 KTXInternalFormat_D24 = 0x81A6, //GL_DEPTH_COMPONENT24 KTXInternalFormat_D16S8_EXT = 0xFFF6, KTXInternalFormat_D24S8 = 0x88F0, //GL_DEPTH24_STENCIL8 KTXInternalFormat_D32 = 0x81A7, //GL_DEPTH_COMPONENT32 KTXInternalFormat_D32F = 0x8CAC, //GL_DEPTH_COMPONENT32F KTXInternalFormat_D32FS8X24 = 0x8CAD, //GL_DEPTH32F_STENCIL8 KTXInternalFormat_S8_EXT = 0x8D48, //GL_STENCIL_INDEX8 // Compressed formats KTXInternalFormat_RGB_DXT1 = 0x83F0, //GL_COMPRESSED_RGB_S3TC_DXT1_EXT KTXInternalFormat_RGBA_DXT1 = 0x83F1, //GL_COMPRESSED_RGBA_S3TC_DXT1_EXT KTXInternalFormat_RGBA_DXT3 = 0x83F2, //GL_COMPRESSED_RGBA_S3TC_DXT3_EXT KTXInternalFormat_RGBA_DXT5 = 0x83F3, //GL_COMPRESSED_RGBA_S3TC_DXT5_EXT KTXInternalFormat_R_ATI1N_UNORM = 0x8DBB, //GL_COMPRESSED_RED_RGTC1 KTXInternalFormat_R_ATI1N_SNORM = 0x8DBC, //GL_COMPRESSED_SIGNED_RED_RGTC1 KTXInternalFormat_RG_ATI2N_UNORM = 0x8DBD, //GL_COMPRESSED_RG_RGTC2 KTXInternalFormat_RG_ATI2N_SNORM = 0x8DBE, //GL_COMPRESSED_SIGNED_RG_RGTC2 KTXInternalFormat_RGB_BP_UNSIGNED_FLOAT = 0x8E8F, //GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT KTXInternalFormat_RGB_BP_SIGNED_FLOAT = 0x8E8E, //GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT KTXInternalFormat_RGB_BP_UNORM = 0x8E8C, //GL_COMPRESSED_RGBA_BPTC_UNORM KTXInternalFormat_RGB_PVRTC_4BPPV1 = 0x8C00, //GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG KTXInternalFormat_RGB_PVRTC_2BPPV1 = 0x8C01, //GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG KTXInternalFormat_RGBA_PVRTC_4BPPV1 = 0x8C02, //GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG KTXInternalFormat_RGBA_PVRTC_2BPPV1 = 0x8C03, //GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG KTXInternalFormat_RGBA_PVRTC_4BPPV2 = 0x9137, //GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG KTXInternalFormat_RGBA_PVRTC_2BPPV2 = 0x9138, //GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG KTXInternalFormat_ATC_RGB = 0x8C92, //GL_ATC_RGB_AMD KTXInternalFormat_ATC_RGBA_EXPLICIT_ALPHA = 0x8C93, //GL_ATC_RGBA_EXPLICIT_ALPHA_AMD KTXInternalFormat_ATC_RGBA_INTERPOLATED_ALPHA = 0x87EE, //GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD KTXInternalFormat_RGB_ETC = 0x8D64, //GL_COMPRESSED_RGB8_ETC1 KTXInternalFormat_RGB_ETC2 = 0x9274, //GL_COMPRESSED_RGB8_ETC2 KTXInternalFormat_RGBA_PUNCHTHROUGH_ETC2 = 0x9276, //GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 KTXInternalFormat_RGBA_ETC2 = 0x9278, //GL_COMPRESSED_RGBA8_ETC2_EAC KTXInternalFormat_R11_EAC = 0x9270, //GL_COMPRESSED_R11_EAC KTXInternalFormat_SIGNED_R11_EAC = 0x9271, //GL_COMPRESSED_SIGNED_R11_EAC KTXInternalFormat_RG11_EAC = 0x9272, //GL_COMPRESSED_RG11_EAC KTXInternalFormat_SIGNED_RG11_EAC = 0x9273, //GL_COMPRESSED_SIGNED_RG11_EAC KTXInternalFormat_RGBA_ASTC_4x4 = 0x93B0, //GL_COMPRESSED_RGBA_ASTC_4x4_KHR KTXInternalFormat_RGBA_ASTC_5x4 = 0x93B1, //GL_COMPRESSED_RGBA_ASTC_5x4_KHR KTXInternalFormat_RGBA_ASTC_5x5 = 0x93B2, //GL_COMPRESSED_RGBA_ASTC_5x5_KHR KTXInternalFormat_RGBA_ASTC_6x5 = 0x93B3, //GL_COMPRESSED_RGBA_ASTC_6x5_KHR KTXInternalFormat_RGBA_ASTC_6x6 = 0x93B4, //GL_COMPRESSED_RGBA_ASTC_6x6_KHR KTXInternalFormat_RGBA_ASTC_8x5 = 0x93B5, //GL_COMPRESSED_RGBA_ASTC_8x5_KHR KTXInternalFormat_RGBA_ASTC_8x6 = 0x93B6, //GL_COMPRESSED_RGBA_ASTC_8x6_KHR KTXInternalFormat_RGBA_ASTC_8x8 = 0x93B7, //GL_COMPRESSED_RGBA_ASTC_8x8_KHR KTXInternalFormat_RGBA_ASTC_10x5 = 0x93B8, //GL_COMPRESSED_RGBA_ASTC_10x5_KHR KTXInternalFormat_RGBA_ASTC_10x6 = 0x93B9, //GL_COMPRESSED_RGBA_ASTC_10x6_KHR KTXInternalFormat_RGBA_ASTC_10x8 = 0x93BA, //GL_COMPRESSED_RGBA_ASTC_10x8_KHR KTXInternalFormat_RGBA_ASTC_10x10 = 0x93BB, //GL_COMPRESSED_RGBA_ASTC_10x10_KHR KTXInternalFormat_RGBA_ASTC_12x10 = 0x93BC, //GL_COMPRESSED_RGBA_ASTC_12x10_KHR KTXInternalFormat_RGBA_ASTC_12x12 = 0x93BD, //GL_COMPRESSED_RGBA_ASTC_12x12_KHR // sRGB formats KTXInternalFormat_SRGB_DXT1 = 0x8C4C, //GL_COMPRESSED_SRGB_S3TC_DXT1_EXT KTXInternalFormat_SRGB_ALPHA_DXT1 = 0x8C4D, //GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT KTXInternalFormat_SRGB_ALPHA_DXT3 = 0x8C4E, //GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT KTXInternalFormat_SRGB_ALPHA_DXT5 = 0x8C4F, //GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT KTXInternalFormat_SRGB_BP_UNORM = 0x8E8D, //GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM KTXInternalFormat_SRGB_PVRTC_2BPPV1 = 0x8A54, //GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT KTXInternalFormat_SRGB_PVRTC_4BPPV1 = 0x8A55, //GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT KTXInternalFormat_SRGB_ALPHA_PVRTC_2BPPV1 = 0x8A56, //GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT KTXInternalFormat_SRGB_ALPHA_PVRTC_4BPPV1 = 0x8A57, //GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT KTXInternalFormat_SRGB_ALPHA_PVRTC_2BPPV2 = 0x93F0, //COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV2_IMG KTXInternalFormat_SRGB_ALPHA_PVRTC_4BPPV2 = 0x93F1, //GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV2_IMG KTXInternalFormat_SRGB8_ETC2 = 0x9275, //GL_COMPRESSED_SRGB8_ETC2 KTXInternalFormat_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277, //GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 KTXInternalFormat_SRGB8_ALPHA8_ETC2_EAC = 0x9279, //GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC KTXInternalFormat_SRGB8_ALPHA8_ASTC_4x4 = 0x93D0, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_5x4 = 0x93D1, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_5x5 = 0x93D2, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_6x5 = 0x93D3, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_6x6 = 0x93D4, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_8x5 = 0x93D5, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_8x6 = 0x93D6, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_8x8 = 0x93D7, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_10x5 = 0x93D8, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_10x6 = 0x93D9, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_10x8 = 0x93DA, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_10x10 = 0x93DB, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_12x10 = 0x93DC, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR KTXInternalFormat_SRGB8_ALPHA8_ASTC_12x12 = 0x93DD, //GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR KTXInternalFormat_ALPHA8 = 0x803C, KTXInternalFormat_ALPHA16 = 0x803E, KTXInternalFormat_LUMINANCE8 = 0x8040, KTXInternalFormat_LUMINANCE16 = 0x8042, KTXInternalFormat_LUMINANCE8_ALPHA8 = 0x8045, KTXInternalFormat_LUMINANCE16_ALPHA16 = 0x8048, KTXInternalFormat_R8_USCALED_GTC = 0xF000, KTXInternalFormat_R8_SSCALED_GTC, KTXInternalFormat_RG8_USCALED_GTC, KTXInternalFormat_RG8_SSCALED_GTC, KTXInternalFormat_RGB8_USCALED_GTC, KTXInternalFormat_RGB8_SSCALED_GTC, KTXInternalFormat_RGBA8_USCALED_GTC, KTXInternalFormat_RGBA8_SSCALED_GTC, KTXInternalFormat_RGB10A2_USCALED_GTC, KTXInternalFormat_RGB10A2_SSCALED_GTC, KTXInternalFormat_R16_USCALED_GTC, KTXInternalFormat_R16_SSCALED_GTC, KTXInternalFormat_RG16_USCALED_GTC, KTXInternalFormat_RG16_SSCALED_GTC, KTXInternalFormat_RGB16_USCALED_GTC, KTXInternalFormat_RGB16_SSCALED_GTC, KTXInternalFormat_RGBA16_USCALED_GTC, KTXInternalFormat_RGBA16_SSCALED_GTC, } KTXInternalFormat; typedef enum KTXExternalFormat { KTXExternalFormat_NONE = 0, //GL_NONE KTXExternalFormat_RED = 0x1903, //GL_RED KTXExternalFormat_RG = 0x8227, //GL_RG KTXExternalFormat_RGB = 0x1907, //GL_RGB KTXExternalFormat_BGR = 0x80E0, //GL_BGR KTXExternalFormat_RGBA = 0x1908, //GL_RGBA KTXExternalFormat_BGRA = 0x80E1, //GL_BGRA KTXExternalFormat_RED_INTEGER = 0x8D94, //GL_RED_INTEGER KTXExternalFormat_RG_INTEGER = 0x8228, //GL_RG_INTEGER KTXExternalFormat_RGB_INTEGER = 0x8D98, //GL_RGB_INTEGER KTXExternalFormat_BGR_INTEGER = 0x8D9A, //GL_BGR_INTEGER KTXExternalFormat_RGBA_INTEGER = 0x8D99, //GL_RGBA_INTEGER KTXExternalFormat_BGRA_INTEGER = 0x8D9B, //GL_BGRA_INTEGER KTXExternalFormat_DEPTH = 0x1902, //GL_DEPTH_COMPONENT KTXExternalFormat_DEPTH_STENCIL = 0x84F9, //GL_DEPTH_STENCIL KTXExternalFormat_STENCIL = 0x1901, //GL_STENCIL_INDEX KTXExternalFormat_LUMINANCE = 0x1909, //GL_LUMINANCE KTXExternalFormat_ALPHA = 0x1906, //GL_ALPHA KTXExternalFormat_LUMINANCE_ALPHA = 0x190A, //GL_LUMINANCE_ALPHA KTXExternalFormat_SRGB_EXT = 0x8C40, //SRGB_EXT KTXExternalFormat_SRGB_ALPHA_EXT = 0x8C42 //SRGB_ALPHA_EXT } KTXExternalFormat; typedef enum KTXType { KTXType_NONE = 0, //GL_NONE KTXType_I8 = 0x1400, //GL_BYTE KTXType_U8 = 0x1401, //GL_UNSIGNED_BYTE KTXType_I16 = 0x1402, //GL_SHORT KTXType_U16 = 0x1403, //GL_UNSIGNED_SHORT KTXType_I32 = 0x1404, //GL_INT KTXType_U32 = 0x1405, //GL_UNSIGNED_INT KTXType_I64 = 0x140E, //GL_INT64_ARB KTXType_U64 = 0x140F, //GL_UNSIGNED_INT64_ARB KTXType_F16 = 0x140B, //GL_HALF_FLOAT KTXType_F16_OES = 0x8D61, //GL_HALF_FLOAT_OES KTXType_F32 = 0x1406, //GL_FLOAT KTXType_F64 = 0x140A, //GL_DOUBLE KTXType_UINT32_RGB9_E5_REV = 0x8C3E, //GL_UNSIGNED_INT_5_9_9_9_REV KTXType_UINT32_RG11B10F_REV = 0x8C3B, //GL_UNSIGNED_INT_10F_11F_11F_REV KTXType_UINT8_RG3B2 = 0x8032, //GL_UNSIGNED_BYTE_3_3_2 KTXType_UINT8_RG3B2_REV = 0x8362, //GL_UNSIGNED_BYTE_2_3_3_REV KTXType_UINT16_RGB5A1 = 0x8034, //GL_UNSIGNED_SHORT_5_5_5_1 KTXType_UINT16_RGB5A1_REV = 0x8366, //GL_UNSIGNED_SHORT_1_5_5_5_REV KTXType_UINT16_R5G6B5 = 0x8363, //GL_UNSIGNED_SHORT_5_6_5 KTXType_UINT16_R5G6B5_REV = 0x8364, //GL_UNSIGNED_SHORT_5_6_5_REV KTXType_UINT16_RGBA4 = 0x8033, //GL_UNSIGNED_SHORT_4_4_4_4 KTXType_UINT16_RGBA4_REV = 0x8365, //GL_UNSIGNED_SHORT_4_4_4_4_REV KTXType_UINT32_RGBA8 = 0x8035, //GL_UNSIGNED_SHORT_8_8_8_8 KTXType_UINT32_RGBA8_REV = 0x8367, //GL_UNSIGNED_SHORT_8_8_8_8_REV KTXType_UINT32_RGB10A2 = 0x8036, //GL_UNSIGNED_INT_10_10_10_2 KTXType_UINT32_RGB10A2_REV = 0x8368, //GL_UNSIGNED_INT_2_10_10_10_REV KTXType_UINT8_RG4_REV_GTC = 0xFFFD, KTXType_UINT16_A1RGB5_GTC = 0xFFFC } KTXType; typedef struct KTXFormatDesc { KTXExternalFormat mExternal; KTXType mType; } KTXFormatDesc; static KTXFormatDesc gKTXFormatToImageFormat[ImageFormat::COUNT] = {}; static eastl::unordered_map<KTXInternalFormat, bool> gKTXSrgbFormats; typedef struct KTXHeader { uint8_t mIdentifier[12]; uint32_t mEndianness; uint32_t mGlType; uint32_t mGlTypeSize; uint32_t mGlFormat; uint32_t mGlInternalFormat; uint32_t mGlBaseInternalFormat; uint32_t mWidth; uint32_t mHeight; uint32_t mDepth; uint32_t mArrayElementCount; uint32_t mFaceCount; uint32_t mMipmapCount; uint32_t mKeyValueDataLength; } KTXHeader; #pragma pack(pop) // --- BLOCK DECODING --- void iDecodeColorBlock( unsigned char* dest, int w, int h, int xOff, int yOff, ImageFormat::Enum format, int red, int blue, unsigned char* src) { unsigned char colors[4][3]; uint16 c0 = *(uint16*)src; uint16 c1 = *(uint16*)(src + 2); colors[0][0] = ((c0 >> 11) & 0x1F) << 3; colors[0][1] = ((c0 >> 5) & 0x3F) << 2; colors[0][2] = (c0 & 0x1F) << 3; colors[1][0] = ((c1 >> 11) & 0x1F) << 3; colors[1][1] = ((c1 >> 5) & 0x3F) << 2; colors[1][2] = (c1 & 0x1F) << 3; if (c0 > c1 || format == ImageFormat::DXT5) { for (int i = 0; i < 3; i++) { colors[2][i] = (2 * colors[0][i] + colors[1][i] + 1) / 3; colors[3][i] = (colors[0][i] + 2 * colors[1][i] + 1) / 3; } } else { for (int i = 0; i < 3; i++) { colors[2][i] = (colors[0][i] + colors[1][i] + 1) >> 1; colors[3][i] = 0; } } src += 4; for (int y = 0; y < h; y++) { unsigned char* dst = dest + yOff * y; unsigned int indexes = src[y]; for (int x = 0; x < w; x++) { unsigned int index = indexes & 0x3; dst[red] = colors[index][0]; dst[1] = colors[index][1]; dst[blue] = colors[index][2]; indexes >>= 2; dst += xOff; } } } void iDecodeDXT3Block(unsigned char* dest, int w, int h, int xOff, int yOff, unsigned char* src) { for (int y = 0; y < h; y++) { unsigned char* dst = dest + yOff * y; unsigned int alpha = ((unsigned short*)src)[y]; for (int x = 0; x < w; x++) { *dst = (alpha & 0xF) * 17; alpha >>= 4; dst += xOff; } } } void iDecodeDXT5Block(unsigned char* dest, int w, int h, int xOff, int yOff, unsigned char* src) { unsigned char a0 = src[0]; unsigned char a1 = src[1]; uint64_t alpha = (*(uint64_t*)src) >> 16; for (int y = 0; y < h; y++) { unsigned char* dst = dest + yOff * y; for (int x = 0; x < w; x++) { int k = ((unsigned int)alpha) & 0x7; if (k == 0) { *dst = a0; } else if (k == 1) { *dst = a1; } else if (a0 > a1) { *dst = (unsigned char)(((8 - k) * a0 + (k - 1) * a1) / 7); } else if (k >= 6) { *dst = (k == 6) ? 0 : 255; } else { *dst = (unsigned char)(((6 - k) * a0 + (k - 1) * a1) / 5); } alpha >>= 3; dst += xOff; } if (w < 4) alpha >>= (3 * (4 - w)); } } void iDecodeCompressedImage(unsigned char* dest, unsigned char* src, const int width, const int height, const ImageFormat::Enum format) { int sx = (width < 4) ? width : 4; int sy = (height < 4) ? height : 4; int nChannels = ImageFormat::GetChannelCount(format); for (int y = 0; y < height; y += 4) { for (int x = 0; x < width; x += 4) { unsigned char* dst = dest + (y * width + x) * nChannels; if (format == ImageFormat::DXT3) { iDecodeDXT3Block(dst + 3, sx, sy, nChannels, width * nChannels, src); src += 8; } else if (format == ImageFormat::DXT5) { iDecodeDXT5Block(dst + 3, sx, sy, nChannels, width * nChannels, src); src += 8; } if (format <= ImageFormat::DXT5) { iDecodeColorBlock(dst, sx, sy, nChannels, width * nChannels, format, 0, 2, src); src += 8; } else { if (format == ImageFormat::ATI1N) { iDecodeDXT5Block(dst, sx, sy, 1, width, src); src += 8; } else if ((format == ImageFormat::ATI2N)) { iDecodeDXT5Block(dst, sx, sy, 2, width * 2, src + 8); iDecodeDXT5Block(dst + 1, sx, sy, 2, width * 2, src); src += 16; } else return; } } } } template <typename T> inline void swapPixelChannels(T* pixels, int num_pixels, const int channels, const int ch0, const int ch1) { for (int i = 0; i < num_pixels; i++) { T tmp = pixels[ch1]; pixels[ch1] = pixels[ch0]; pixels[ch0] = tmp; pixels += channels; } } Image::Image() { pData = NULL; mLoadFileName = ""; mWidth = 0; mHeight = 0; mDepth = 0; mMipMapCount = 0; mArrayCount = 0; mFormat = ImageFormat::NONE; mAdditionalDataSize = 0; pAdditionalData = NULL; mSrgb = false; mOwnsMemory = true; mLinearLayout = true; } Image::Image(const Image& img) { mWidth = img.mWidth; mHeight = img.mHeight; mDepth = img.mDepth; mMipMapCount = img.mMipMapCount; mArrayCount = img.mArrayCount; mFormat = img.mFormat; mLinearLayout = img.mLinearLayout; mSrgb = img.mSrgb; int size = GetMipMappedSize(0, mMipMapCount) * mArrayCount; pData = (unsigned char*)conf_malloc(sizeof(unsigned char) * size); memcpy(pData, img.pData, size); mLoadFileName = img.mLoadFileName; mAdditionalDataSize = img.mAdditionalDataSize; pAdditionalData = (unsigned char*)conf_malloc(sizeof(unsigned char) * mAdditionalDataSize); memcpy(pAdditionalData, img.pAdditionalData, mAdditionalDataSize); } unsigned char* Image::Create(const ImageFormat::Enum fmt, const int w, const int h, const int d, const int mipMapCount, const int arraySize) { mFormat = fmt; mWidth = w; mHeight = h; mDepth = d; mMipMapCount = mipMapCount; mArrayCount = arraySize; mOwnsMemory = true; uint holder = GetMipMappedSize(0, mMipMapCount); pData = (unsigned char*)conf_malloc(sizeof(unsigned char) * holder * mArrayCount); memset(pData, 0x00, holder * mArrayCount); mLoadFileName = "Undefined"; return pData; } unsigned char* Image::Create(const ImageFormat::Enum fmt, const int w, const int h, const int d, const int mipMapCount, const int arraySize, const unsigned char* rawData) { mFormat = fmt; mWidth = w; mHeight = h; mDepth = d; mMipMapCount = mipMapCount; mArrayCount = arraySize; mOwnsMemory = false; pData = (uint8_t*)rawData; mLoadFileName = "Undefined"; return pData; } void Image::RedefineDimensions( const ImageFormat::Enum fmt, const int w, const int h, const int d, const int mipMapCount, const int arraySize, bool srgb) { //Redefine image that was loaded in mFormat = fmt; mWidth = w; mHeight = h; mDepth = d; mMipMapCount = mipMapCount; mArrayCount = arraySize; mSrgb = srgb; switch (mFormat) { case ImageFormat::PVR_2BPP: case ImageFormat::PVR_2BPPA: case ImageFormat::PVR_4BPP: case ImageFormat::PVR_4BPPA: mLinearLayout = false; break; default: mLinearLayout = true; } } void Image::Destroy() { if (pData && mOwnsMemory) { conf_free(pData); pData = NULL; } if (pAdditionalData) { conf_free(pAdditionalData); pAdditionalData = NULL; } } void Image::Clear() { Destroy(); mWidth = 0; mHeight = 0; mDepth = 0; mMipMapCount = 0; mArrayCount = 0; mFormat = ImageFormat::NONE; mAdditionalDataSize = 0; } unsigned char* Image::GetPixels(unsigned char* pDstData, const uint mipMapLevel, const uint dummy) { UNREF_PARAM(dummy); return (mipMapLevel < mMipMapCount) ? pDstData + GetMipMappedSize(0, mipMapLevel) : NULL; } unsigned char* Image::GetPixels(const uint mipMapLevel) const { return (mipMapLevel < mMipMapCount) ? pData + GetMipMappedSize(0, mipMapLevel) : NULL; } unsigned char* Image::GetPixels(const uint mipMapLevel, const uint arraySlice) const { if (mipMapLevel >= mMipMapCount || arraySlice >= mArrayCount) return NULL; return pData + GetMipMappedSize(0, mMipMapCount) * arraySlice + GetMipMappedSize(0, mipMapLevel); } uint Image::GetWidth(const int mipMapLevel) const { int a = mWidth >> mipMapLevel; return (a == 0) ? 1 : a; } uint Image::GetHeight(const int mipMapLevel) const { int a = mHeight >> mipMapLevel; return (a == 0) ? 1 : a; } uint Image::GetDepth(const int mipMapLevel) const { int a = mDepth >> mipMapLevel; return (a == 0) ? 1 : a; } uint Image::GetMipMapCountFromDimensions() const { uint m = max(mWidth, mHeight); m = max(m, mDepth); int i = 0; while (m > 0) { m >>= 1; i++; } return i; } uint Image::GetArraySliceSize(const uint mipMapLevel, ImageFormat::Enum srcFormat) const { int w = GetWidth(mipMapLevel); int h = GetHeight(mipMapLevel); if (srcFormat == ImageFormat::NONE) srcFormat = mFormat; int size; if (ImageFormat::IsCompressedFormat(srcFormat)) { size = ((w + 3) >> 2) * ((h + 3) >> 2) * ImageFormat::GetBytesPerBlock(srcFormat); } else { size = w * h * ImageFormat::GetBytesPerPixel(srcFormat); } return size; } uint Image::GetNumberOfPixels(const uint firstMipMapLevel, uint nMipMapLevels) const { int w = GetWidth(firstMipMapLevel); int h = GetHeight(firstMipMapLevel); int d = GetDepth(firstMipMapLevel); int size = 0; while (nMipMapLevels) { size += w * h * d; w >>= 1; h >>= 1; d >>= 1; if (w + h + d == 0) break; if (w == 0) w = 1; if (h == 0) h = 1; if (d == 0) d = 1; nMipMapLevels--; } return (mDepth == 0) ? 6 * size : size; } bool Image::GetColorRange(float& min, float& max) { if (mFormat < ImageFormat::R32F || mFormat > ImageFormat::RGBA32F) return false; int nElements = GetNumberOfPixels(0, mMipMapCount) * ImageFormat::GetChannelCount(mFormat) * mArrayCount; if (nElements <= 0) return false; float minVal = FLT_MAX; float maxVal = -FLT_MAX; for (int i = 0; i < nElements; i++) { float d = ((float*)pData)[i]; if (d > maxVal) maxVal = d; if (d < minVal) minVal = d; } max = maxVal; min = minVal; return true; } bool Image::Normalize() { if (mFormat < ImageFormat::R32F || mFormat > ImageFormat::RGBA32F) return false; float min, max; GetColorRange(min, max); int nElements = GetNumberOfPixels(0, mMipMapCount) * ImageFormat::GetChannelCount(mFormat) * mArrayCount; float s = 1.0f / (max - min); float b = -min * s; for (int i = 0; i < nElements; i++) { float d = ((float*)pData)[i]; ((float*)pData)[i] = d * s + b; } return true; } bool Image::Uncompress() { if (((mFormat >= ImageFormat::PVR_2BPP) && (mFormat <= ImageFormat::PVR_4BPPA)) || ((mFormat >= ImageFormat::ETC1) && (mFormat <= ImageFormat::ATCI))) { // no decompression return false; } if (ImageFormat::IsCompressedFormat(mFormat)) { ImageFormat::Enum destFormat; if (mFormat >= ImageFormat::ATI1N) { destFormat = (mFormat == ImageFormat::ATI1N) ? ImageFormat::I8 : ImageFormat::IA8; } else { destFormat = (mFormat == ImageFormat::DXT1) ? ImageFormat::RGB8 : ImageFormat::RGBA8; } ubyte* newPixels = (ubyte*)conf_malloc(sizeof(ubyte) * GetMipMappedSize(0, mMipMapCount, destFormat)); int level = 0; ubyte *src, *dst = newPixels; while ((src = GetPixels(level)) != NULL) { int w = GetWidth(level); int h = GetHeight(level); int d = (mDepth == 0) ? 6 : GetDepth(level); int dstSliceSize = GetArraySliceSize(level, destFormat); int srcSliceSize = GetArraySliceSize(level, mFormat); for (int slice = 0; slice < d; slice++) { iDecodeCompressedImage(dst, src, w, h, mFormat); dst += dstSliceSize; src += srcSliceSize; } level++; } mFormat = destFormat; Destroy(); pData = newPixels; } return true; } bool Image::Unpack() { int pixelCount = GetNumberOfPixels(0, mMipMapCount); ubyte* newPixels; if (mFormat == ImageFormat::RGBE8) { mFormat = ImageFormat::RGB32F; newPixels = (unsigned char*)conf_malloc(sizeof(unsigned char) * GetMipMappedSize(0, mMipMapCount)); for (int i = 0; i < pixelCount; i++) { ((vec3*)newPixels)[i] = rgbeToRGB(pData + 4 * i); } } else if (mFormat == ImageFormat::RGB565) { mFormat = ImageFormat::RGB8; newPixels = (unsigned char*)conf_malloc(sizeof(unsigned char) * GetMipMappedSize(0, mMipMapCount)); for (int i = 0; i < pixelCount; i++) { unsigned int rgb565 = (unsigned int)(((uint16_t*)pData)[i]); newPixels[3 * i] = (ubyte)(((rgb565 >> 11) * 2106) >> 8); newPixels[3 * i + 1] = (ubyte)(((rgb565 >> 5) & 0x3F) * 1037 >> 8); newPixels[3 * i + 2] = (ubyte)(((rgb565 & 0x1F) * 2106) >> 8); } } else if (mFormat == ImageFormat::RGBA4) { mFormat = ImageFormat::RGBA8; newPixels = (unsigned char*)conf_malloc(sizeof(unsigned char) * GetMipMappedSize(0, mMipMapCount)); for (int i = 0; i < pixelCount; i++) { newPixels[4 * i] = (pData[2 * i + 1] & 0xF) * 17; newPixels[4 * i + 1] = (pData[2 * i] >> 4) * 17; newPixels[4 * i + 2] = (pData[2 * i] & 0xF) * 17; newPixels[4 * i + 3] = (pData[2 * i + 1] >> 4) * 17; } } else if (mFormat == ImageFormat::RGB10A2) { mFormat = ImageFormat::RGBA16; newPixels = (unsigned char*)conf_malloc(sizeof(unsigned char) * GetMipMappedSize(0, mMipMapCount)); for (int i = 0; i < pixelCount; i++) { uint32 src = ((uint32*)pData)[i]; ((ushort*)newPixels)[4 * i] = (((src)&0x3FF) * 4198340) >> 16; ((ushort*)newPixels)[4 * i + 1] = (((src >> 10) & 0x3FF) * 4198340) >> 16; ((ushort*)newPixels)[4 * i + 2] = (((src >> 20) & 0x3FF) * 4198340) >> 16; ((ushort*)newPixels)[4 * i + 3] = (((src >> 30) & 0x003) * 21845); } } else { return false; } conf_free(pData); pData = newPixels; return true; } uint Image::GetMipMappedSize(const uint firstMipMapLevel, uint nMipMapLevels, ImageFormat::Enum srcFormat) const { uint w = GetWidth(firstMipMapLevel); uint h = GetHeight(firstMipMapLevel); uint d = GetDepth(firstMipMapLevel); if (srcFormat == ImageFormat::NONE) srcFormat = mFormat; return (mDepth == 0 ? 6 : 1) * ImageFormat::GetMipMappedSize(w, h, d, nMipMapLevels - firstMipMapLevel, srcFormat); } // Load Image Data form mData functions bool iLoadDDSFromMemory(Image* pImage, const char* memory, uint32_t memSize, memoryAllocationFunc pAllocator, void* pUserData) { DDSHeader header; if (memory == NULL || memSize == 0) return false; MemoryBuffer file(memory, (unsigned)memSize); file.Read(&header, sizeof(header)); if (header.mDWMagic != MAKE_CHAR4('D', 'D', 'S', ' ')) { return false; } uint32_t width = header.mDWWidth; uint32_t height = header.mDWHeight; uint32_t depth = (header.mCaps.mDWCaps2 & DDSCAPS2_CUBEMAP) ? 0 : (header.mDWDepth == 0) ? 1 : header.mDWDepth; uint32_t mipMapCount = max(1U, header.mDWMipMapCount); uint32_t arrayCount = 1; ImageFormat::Enum imageFormat = ImageFormat::NONE; bool srgb = false; if (header.mPixelFormat.mDWFourCC == MAKE_CHAR4('D', 'X', '1', '0')) { DDSHeaderDX10 dx10Header; file.Read(&dx10Header, sizeof(dx10Header)); switch (dx10Header.mDXGIFormat) { case 61: imageFormat = ImageFormat::R8; break; case 49: imageFormat = ImageFormat::RG8; break; case 28: imageFormat = ImageFormat::RGBA8; break; case 29: imageFormat = ImageFormat::RGBA8; srgb = true; break; case 56: imageFormat = ImageFormat::R16; break; case 35: imageFormat = ImageFormat::RG16; break; case 11: imageFormat = ImageFormat::RGBA16; break; case 54: imageFormat = ImageFormat::R16F; break; case 34: imageFormat = ImageFormat::RG16F; break; case 10: imageFormat = ImageFormat::RGBA16F; break; case 41: imageFormat = ImageFormat::R32F; break; case 16: imageFormat = ImageFormat::RG32F; break; case 6: imageFormat = ImageFormat::RGB32F; break; case 2: imageFormat = ImageFormat::RGBA32F; break; case 67: imageFormat = ImageFormat::RGB9E5; break; case 26: imageFormat = ImageFormat::RG11B10F; break; case 24: imageFormat = ImageFormat::RGB10A2; break; case 71: imageFormat = ImageFormat::DXT1; break; case 72: imageFormat = ImageFormat::DXT1; srgb = true; break; case 74: imageFormat = ImageFormat::DXT3; break; case 75: imageFormat = ImageFormat::DXT3; srgb = true; break; case 77: imageFormat = ImageFormat::DXT5; break; case 78: imageFormat = ImageFormat::DXT5; srgb = true; break; case 80: imageFormat = ImageFormat::ATI1N; break; case 83: imageFormat = ImageFormat::ATI2N; break; case 95: // unsigned float imageFormat = ImageFormat::GNF_BC6HUF; break; case 96: // signed float imageFormat = ImageFormat::GNF_BC6HSF; break; case 98: // regular imageFormat = ImageFormat::GNF_BC7; break; case 99: // srgb imageFormat = ImageFormat::GNF_BC7; srgb = true; break; default: return false; } } else { switch (header.mPixelFormat.mDWFourCC) { case 34: imageFormat = ImageFormat::RG16; break; case 36: imageFormat = ImageFormat::RGBA16; break; case 111: imageFormat = ImageFormat::R16F; break; case 112: imageFormat = ImageFormat::RG16F; break; case 113: imageFormat = ImageFormat::RGBA16F; break; case 114: imageFormat = ImageFormat::R32F; break; case 115: imageFormat = ImageFormat::RG32F; break; case 116: imageFormat = ImageFormat::RGBA32F; break; case MAKE_CHAR4('A', 'T', 'C', ' '): imageFormat = ImageFormat::ATC; break; case MAKE_CHAR4('A', 'T', 'C', 'A'): imageFormat = ImageFormat::ATCA; break; case MAKE_CHAR4('A', 'T', 'C', 'I'): imageFormat = ImageFormat::ATCI; break; case MAKE_CHAR4('A', 'T', 'I', '1'): imageFormat = ImageFormat::ATI1N; break; case MAKE_CHAR4('A', 'T', 'I', '2'): imageFormat = ImageFormat::ATI2N; break; case MAKE_CHAR4('E', 'T', 'C', ' '): imageFormat = ImageFormat::ETC1; break; case MAKE_CHAR4('D', 'X', 'T', '1'): imageFormat = ImageFormat::DXT1; break; case MAKE_CHAR4('D', 'X', 'T', '3'): imageFormat = ImageFormat::DXT3; break; case MAKE_CHAR4('D', 'X', 'T', '5'): imageFormat = ImageFormat::DXT5; break; default: switch (header.mPixelFormat.mDWRGBBitCount) { case 8: imageFormat = ImageFormat::I8; break; case 16: imageFormat = (header.mPixelFormat.mDWRGBAlphaBitMask == 0xF000) ? ImageFormat::RGBA4 : (header.mPixelFormat.mDWRGBAlphaBitMask == 0xFF00) ? ImageFormat::IA8 : (header.mPixelFormat.mDWBBitMask == 0x1F) ? ImageFormat::RGB565 : ImageFormat::I16; break; case 24: imageFormat = ImageFormat::RGB8; break; case 32: imageFormat = (header.mPixelFormat.mDWRBitMask == 0x3FF00000) ? ImageFormat::RGB10A2 : ImageFormat::RGBA8; break; default: return false; } } } pImage->RedefineDimensions(imageFormat, width, height, depth, mipMapCount, arrayCount, srgb); int size = pImage->GetMipMappedSize(); if (pAllocator) { pImage->SetPixels((unsigned char*)pAllocator(pImage, size, pUserData)); } else { pImage->SetPixels((unsigned char*)conf_malloc(sizeof(unsigned char) * size), true); } if (pImage->IsCube()) { for (int face = 0; face < 6; face++) { for (uint mipMapLevel = 0; mipMapLevel < pImage->GetMipMapCount(); mipMapLevel++) { int faceSize = pImage->GetMipMappedSize(mipMapLevel, 1) / 6; unsigned char* src = pImage->GetPixels(mipMapLevel, 0) + face * faceSize; file.Read(src, faceSize); } } } else { file.Read(pImage->GetPixels(), size); } if ((imageFormat == ImageFormat::RGB8 || imageFormat == ImageFormat::RGBA8) && header.mPixelFormat.mDWBBitMask == 0xFF) { int nChannels = ImageFormat::GetChannelCount(imageFormat); swapPixelChannels(pImage->GetPixels(), size / nChannels, nChannels, 0, 2); } return true; } bool iLoadPVRFromMemory(Image* pImage, const char* memory, uint32_t size, memoryAllocationFunc pAllocator, void* pUserData) { #ifndef TARGET_IOS LOGF(LogLevel::eERROR, "Load PVR failed: Only supported on iOS targets."); return false; #else // TODO: Image // - no support for PVRTC2 at the moment since it isn't supported on iOS devices. // - only new PVR header V3 is supported at the moment. Should we add legacy for V2 and V1? // - metadata is ignored for now. Might be useful to implement it if the need for metadata arises (eg. padding, atlas coordinates, orientations, border data, etc...). // - flags are also ignored for now. Currently a flag of 0x02 means that the color have been pre-multiplied byt the alpha values. // Assumptions: // - it's assumed that the texture is already twiddled (ie. Morton). This should always be the case for PVRTC V3. PVR_Texture_Header* psPVRHeader = (PVR_Texture_Header*)memory; if (psPVRHeader->mVersion != gPvrtexV3HeaderVersion) { LOGF(LogLevel::eERROR, "Load PVR failed: Not a valid PVR V3 header."); return 0; } if (psPVRHeader->mPixelFormat > 3) { LOGF(LogLevel::eERROR, "Load PVR failed: Not a supported PVR pixel format. Only PVRTC is supported at the moment."); return 0; } if (psPVRHeader->mNumSurfaces > 1 && psPVRHeader->mNumFaces > 1) { LOGF(LogLevel::eERROR, "Load PVR failed: Loading arrays of cubemaps isn't supported."); return 0; } uint32_t width = psPVRHeader->mWidth; uint32_t height = psPVRHeader->mHeight; uint32_t depth = (psPVRHeader->mNumFaces > 1) ? 0 : psPVRHeader->mDepth; uint32_t mipMapCount = psPVRHeader->mNumMipMaps; uint32_t arrayCount = psPVRHeader->mNumSurfaces; bool srgb = (psPVRHeader->mColorSpace == 1); ImageFormat::Enum imageFormat = ImageFormat::NONE; switch (psPVRHeader->mPixelFormat) { case 0: imageFormat = ImageFormat::PVR_2BPP; break; case 1: imageFormat = ImageFormat::PVR_2BPPA; break; case 2: imageFormat = ImageFormat::PVR_4BPP; break; case 3: imageFormat = ImageFormat::PVR_4BPPA; break; default: // NOT SUPPORTED LOGF(LogLevel::eERROR, "Load PVR failed: pixel type not supported. "); ASSERT(0); return false; } if (depth != 0) arrayCount *= psPVRHeader->mNumFaces; pImage->RedefineDimensions(imageFormat, width, height, depth, mipMapCount, arrayCount, srgb); // Extract the pixel data size_t totalHeaderSizeWithMetadata = sizeof(PVR_Texture_Header) + psPVRHeader->mMetaDataSize; size_t pixelDataSize = pImage->GetMipMappedSize(); if (pAllocator) { pImage->SetPixels((unsigned char*)pAllocator(pImage, sizeof(unsigned char) * pixelDataSize, pUserData)); } else { pImage->SetPixels((unsigned char*)conf_malloc(sizeof(unsigned char) * pixelDataSize), true); } memcpy(pImage->GetPixels(), (unsigned char*)psPVRHeader + totalHeaderSizeWithMetadata, pixelDataSize); return true; #endif } bool iLoadKTXFromMemory(Image* pImage, const char* memory, uint32_t memSize, memoryAllocationFunc pAllocator /*= NULL*/, void* pUserData /*= NULL*/) { #define byte_swap(num) ((((num) >> 24) & 0xff) | (((num) << 8) & 0xff0000) | (((num) >> 8) & 0xff00) | (((num) << 24) & 0xff000000)) // KTX File Structure // Header // MetaData // ImageSize for Mip 0 [ header.arrayCount x header.faceCount ] // ImageData for Mip 0 // Array 0 to header.arrayCount // Face 0 to header.faceCount // ImageSize for Mip 1 // Array 0 to header.arrayCount // Face 0 to header.faceCount // ... MemoryBuffer file(memory, (unsigned)memSize); KTXHeader header = {}; file.Read(&header, sizeof(header)); char *format = (char *)(header.mIdentifier + 1); if (strncmp(format, "KTX 11", 6) != 0) { LOGF(LogLevel::eERROR, "Load KTX failed: Not a valid KTX header."); return false; } bool endianSwap = (header.mEndianness == 0x01020304); uint32_t width = endianSwap ? (uint32_t)byte_swap(header.mWidth) : header.mWidth; uint32_t height = endianSwap ? (uint32_t)byte_swap(header.mHeight) : header.mHeight; uint32_t depth = max(1U, endianSwap ? (uint32_t)byte_swap(header.mDepth) : header.mDepth); uint32_t arrayCount = max(1U, endianSwap ? (uint32_t)byte_swap(header.mArrayElementCount) : header.mArrayElementCount); uint32_t faceCount = endianSwap ? (uint32_t)byte_swap(header.mFaceCount) : header.mFaceCount; uint32_t internalFormat = endianSwap ? (uint32_t)byte_swap(header.mGlInternalFormat) : header.mGlInternalFormat; uint32_t externalFormat = endianSwap ? (uint32_t)byte_swap(header.mGlFormat) : header.mGlFormat; uint32_t type = endianSwap ? (uint32_t)byte_swap(header.mGlType) : header.mGlType; uint32_t mipCount = endianSwap ? (uint32_t)byte_swap(header.mMipmapCount) : header.mMipmapCount; uint32_t keyValueDataLength = endianSwap ? (uint32_t)byte_swap(header.mKeyValueDataLength) : header.mKeyValueDataLength; bool srgb = false; ImageFormat::Enum imageFormat = ImageFormat::NONE; if (arrayCount > 1 && faceCount > 1) { LOGF(LogLevel::eERROR, "Load KTX failed: Loading arrays of cubemaps isn't supported."); return false; } if (gKTXSrgbFormats.find((KTXInternalFormat)internalFormat) != gKTXSrgbFormats.end()) { srgb = true; } // Uncompressed if (externalFormat != 0) { for (uint32_t i = 0; i < ImageFormat::COUNT; ++i) { if (externalFormat == gKTXFormatToImageFormat[i].mExternal && type == gKTXFormatToImageFormat[i].mType) { imageFormat = (ImageFormat::Enum)i; break; } } } // Compressed - Support only ASTC for now else { #if !defined(TARGET_IOS) && !defined(__ANDROID__) LOGF(LogLevel::eERROR, "Load KTX failed: Compressed formats supported on mobile targets only."); return false; #else if (!(internalFormat >= KTXInternalFormat_RGBA_ASTC_4x4 && internalFormat <= KTXInternalFormat_SRGB8_ALPHA8_ASTC_12x12)) { LOGF(LogLevel::eERROR, "Load KTX failed: Support for loading ASTC compressed textures only."); return false; } imageFormat = (ImageFormat::Enum)(ImageFormat::ASTC_4x4 + (internalFormat - (srgb ? KTXInternalFormat_SRGB8_ALPHA8_ASTC_4x4 : KTXInternalFormat_RGBA_ASTC_4x4))); #endif } depth = (faceCount > 1) ? 0 : depth; if (depth != 0) arrayCount *= faceCount; pImage->RedefineDimensions(imageFormat, width, height, depth, mipCount, arrayCount, srgb); // Skip ahead to the pixel data const uint32_t offsetToPixelData = sizeof(KTXHeader) + keyValueDataLength; file.Seek(offsetToPixelData, SEEK_DIR_BEGIN); const uint32_t dataLength = file.GetSize() - offsetToPixelData; if (pAllocator) { pImage->SetPixels((uint8_t*)pAllocator(pImage, dataLength, pUserData)); } else { pImage->SetPixels((uint8_t*)conf_malloc(sizeof(uint8_t) * dataLength), true); } uint8_t* pData = pImage->GetPixels(); uint32_t levelOffset = 0; while (!file.IsEof()) { uint32_t levelSize = file.ReadUInt() / pImage->GetArrayCount(); if (pImage->GetArrayCount() > 1) levelSize /= faceCount; for (uint32_t i = 0; i < pImage->GetArrayCount(); ++i) { for (uint32_t j = 0; j < faceCount; ++j) { file.Read(pData + levelOffset, levelSize); levelOffset += levelSize; // No need to worry about cube padding since block size is a multiple of 4 } } // No need to worry about mip padding since block size is a multiple of 4 } return true; } #if defined(ORBIS) // loads GNF header from memory static GnfError iLoadGnfHeaderFromMemory(struct sce::Gnf::Header* outHeader, MemoryBuffer* mp) { if (outHeader == NULL) // || gnfFile == NULL) { return kGnfErrorInvalidPointer; } outHeader->m_magicNumber = 0; outHeader->m_contentsSize = 0; mp->Read(outHeader, sizeof(sce::Gnf::Header)); //MemFopen::fread(outHeader, sizeof(sce::Gnf::Header), 1, mp); // fseek(gnfFile, 0, SEEK_SET); // fread(outHeader, sizeof(sce::Gnf::Header), 1, gnfFile); if (outHeader->m_magicNumber != sce::Gnf::kMagic) { return kGnfErrorNotGnfFile; } return kGnfErrorNone; } // content size is sizeof(sce::Gnf::Contents)+gnfContents->m_numTextures*sizeof(sce::Gnm::Texture)+ paddings which is a variable of: gnfContents->alignment static uint32_t iComputeContentSize(const sce::Gnf::Contents* gnfContents) { // compute the size of used bytes uint32_t headerSize = sizeof(sce::Gnf::Header) + sizeof(sce::Gnf::Contents) + gnfContents->m_numTextures * sizeof(sce::Gnm::Texture); // add the paddings uint32_t align = 1 << gnfContents->m_alignment; // actual alignment size_t mask = align - 1; uint32_t missAligned = (headerSize & mask); // number of bytes after the alignemnet point if (missAligned) // if none zero we have to add paddings { headerSize += align - missAligned; } return headerSize - sizeof(sce::Gnf::Header); } // loads GNF content from memory static GnfError iReadGnfContentsFromMemory(sce::Gnf::Contents* outContents, uint32_t contentsSizeInBytes, MemoryBuffer* memstart) { // now read the content data ... memstart->Read(outContents, contentsSizeInBytes); //MemFopen::fread(outContents, contentsSizeInBytes, 1, memstart); if (outContents->m_alignment > 31) { return kGnfErrorAlignmentOutOfRange; } if (outContents->m_version == 1) { if ((outContents->m_numTextures * sizeof(sce::Gnm::Texture) + sizeof(sce::Gnf::Contents)) != contentsSizeInBytes) { return kGnfErrorContentsSizeMismatch; } } else { if (outContents->m_version != sce::Gnf::kVersion) { return kGnfErrorVersionMismatch; } else { if (iComputeContentSize(outContents) != contentsSizeInBytes) return kGnfErrorContentsSizeMismatch; } } return kGnfErrorNone; } //------------------------------------------------------------------------------ // Loads a GNF file from memory. // bool Image::iLoadGNFFromMemory(const char* memory, size_t memSize, const bool useMipMaps) { GnfError result = kGnfErrorNone; MemoryBuffer m1(memory, memSize); sce::Gnf::Header header; result = iLoadGnfHeaderFromMemory(&header, m1); if (result != 0) { return false; } char* memoryArray = (char*)conf_calloc(header.m_contentsSize, sizeof(char)); sce::Gnf::Contents* gnfContents = NULL; gnfContents = (sce::Gnf::Contents*)memoryArray; // move the pointer behind the header const char* mp = memory + sizeof(sce::Gnf::Header); MemoryBuffer m2(mp, memSize - sizeof(sce::Gnf::Header)); result = iReadGnfContentsFromMemory(gnfContents, header.m_contentsSize, m2); mWidth = gnfContents->m_textures[0].getWidth(); mHeight = gnfContents->m_textures[0].getHeight(); mDepth = gnfContents->m_textures[0].getDepth(); mMipMapCount = ((!useMipMaps) || (gnfContents->m_textures[0].getLastMipLevel() == 0)) ? 1 : gnfContents->m_textures[0].getLastMipLevel(); mArrayCount = (gnfContents->m_textures[0].getLastArraySliceIndex() > 1) ? gnfContents->m_textures[0].getLastArraySliceIndex() : 1; uint32 dataFormat = gnfContents->m_textures[0].getDataFormat().m_asInt; if (dataFormat == sce::Gnm::kDataFormatBc1Unorm.m_asInt || dataFormat == sce::Gnm::kDataFormatBc1UnormSrgb.m_asInt) mFormat = ImageFormat::GNF_BC1; // else if(dataFormat == sce::Gnm::kDataFormatBc2Unorm.m_asInt || dataFormat == sce::Gnm::kDataFormatBc2UnormSrgb.m_asInt) // format = ImageFormat::GNF_BC2; else if (dataFormat == sce::Gnm::kDataFormatBc3Unorm.m_asInt || dataFormat == sce::Gnm::kDataFormatBc3UnormSrgb.m_asInt) mFormat = ImageFormat::GNF_BC3; // else if(dataFormat == sce::Gnm::kDataFormatBc4Unorm.m_asInt || dataFormat == sce::Gnm::kDataFormatBc4UnormSrgb.m_asInt) // format = ImageFormat::GNF_BC4; // it seems in the moment there is no kDataFormatBc5UnormSrgb .. so I just check for the SRGB flag else if ( dataFormat == sce::Gnm::kDataFormatBc5Unorm.m_asInt || ((dataFormat == sce::Gnm::kDataFormatBc5Unorm.m_asInt) && (gnfContents->m_textures[0].getDataFormat().getTextureChannelType() == sce::Gnm::kTextureChannelTypeSrgb))) mFormat = ImageFormat::GNF_BC5; // else if(dataFormat == sce::Gnm::kDataFormatBc6Unorm.m_asInt || dataFormat == sce::Gnm::kDataFormatBc6UnormSrgb.m_asInt) // format = ImageFormat::GNF_BC6; else if (dataFormat == sce::Gnm::kDataFormatBc7Unorm.m_asInt || dataFormat == sce::Gnm::kDataFormatBc7UnormSrgb.m_asInt) mFormat = ImageFormat::GNF_BC7; else { LOGF(LogLevel::eERROR, "Couldn't find the data format of the texture"); return false; } // // storing the GNF header in the extra data // // we do this because on the addTexture level, we would like to have all this data to allocate and load the data // pAdditionalData = (unsigned char*)conf_calloc(header.m_contentsSize, sizeof(unsigned char)); memcpy(pAdditionalData, gnfContents, header.m_contentsSize); // storing all the pixel data in pixels // // unfortunately that means we have the data twice in pixels and then in VRAM ... // sce::Gnm::SizeAlign pixelsSa = getTexturePixelsSize(gnfContents, 0); // move pointer forward const char* memPoint = mp + header.m_contentsSize + getTexturePixelsByteOffset(gnfContents, 0); MemoryBuffer m3(memPoint, memSize - (sizeof(sce::Gnf::Header) + header.m_contentsSize + getTexturePixelsByteOffset(gnfContents, 0))); // dealing with mip-map stuff ... ??? int size = pixelsSa.m_size; //getMipMappedSize(0, nMipMaps); pData = (unsigned char*)conf_malloc(sizeof(unsigned char) * size); m3.Read(pData, size); //MemFopen::fread(pData, 1, size, m3); /* if (isCube()){ for (int face = 0; face < 6; face++) { for (uint mipMapLevel = 0; mipMapLevel < nMipMaps; mipMapLevel++) { int faceSize = getMipMappedSize(mipMapLevel, 1) / 6; unsigned char *src = getPixels(mipMapLevel) + face * faceSize; memread(src, 1, faceSize, mp); } if ((useMipMaps ) && header.dwMipMapCount > 1) { memseek(mp, memory, getMipMappedSize(1, header.dwMipMapCount - 1) / 6, SEEK_CUR); } } } else { memread(pixels, 1, size, mpoint); } */ conf_free(gnfContents); return !result; } #endif // Image loading // struct of table for file format to loading function struct ImageLoaderDefinition { eastl::string mExtension; Image::ImageLoaderFunction pLoader; }; static eastl::vector<ImageLoaderDefinition> gImageLoaders; struct StaticImageLoader { StaticImageLoader() { gImageLoaders.push_back({ ".dds", iLoadDDSFromMemory }); gImageLoaders.push_back({ ".pvr", iLoadPVRFromMemory }); gImageLoaders.push_back({ ".ktx", iLoadKTXFromMemory }); #if defined(ORBIS) gImageLoaders.push_back({ ".gnf", iLoadGNFFromMemory }); #endif gKTXFormatToImageFormat[ImageFormat::R8] = { KTXExternalFormat::KTXExternalFormat_RED, KTXType_U8 }; gKTXFormatToImageFormat[ImageFormat::RG8] = { KTXExternalFormat::KTXExternalFormat_RG, KTXType_U8 }; gKTXFormatToImageFormat[ImageFormat::RGB8] = { KTXExternalFormat::KTXExternalFormat_RGB, KTXType_U8 }; gKTXFormatToImageFormat[ImageFormat::RGBA8] = { KTXExternalFormat::KTXExternalFormat_RGBA, KTXType_U8 }; gKTXFormatToImageFormat[ImageFormat::R8S] = { KTXExternalFormat::KTXExternalFormat_RED, KTXType_I8 }; gKTXFormatToImageFormat[ImageFormat::RG8S] = { KTXExternalFormat::KTXExternalFormat_RG, KTXType_I8 }; gKTXFormatToImageFormat[ImageFormat::RGB8S] = { KTXExternalFormat::KTXExternalFormat_RGB, KTXType_I8 }; gKTXFormatToImageFormat[ImageFormat::RGBA8S] = { KTXExternalFormat::KTXExternalFormat_RGBA, KTXType_I8 }; gKTXFormatToImageFormat[ImageFormat::R16F] = { KTXExternalFormat::KTXExternalFormat_RED, KTXType_F16 }; gKTXFormatToImageFormat[ImageFormat::RG16F] = { KTXExternalFormat::KTXExternalFormat_RG, KTXType_F16 }; gKTXFormatToImageFormat[ImageFormat::RGB16F] = { KTXExternalFormat::KTXExternalFormat_RGB, KTXType_F16 }; gKTXFormatToImageFormat[ImageFormat::RGBA16F] = { KTXExternalFormat::KTXExternalFormat_RGBA, KTXType_F16 }; gKTXFormatToImageFormat[ImageFormat::R32F] = { KTXExternalFormat::KTXExternalFormat_RED, KTXType_F32 }; gKTXFormatToImageFormat[ImageFormat::RG32F] = { KTXExternalFormat::KTXExternalFormat_RG, KTXType_F32 }; gKTXFormatToImageFormat[ImageFormat::RGB32F] = { KTXExternalFormat::KTXExternalFormat_RGB, KTXType_F32 }; gKTXFormatToImageFormat[ImageFormat::RGBA32F] = { KTXExternalFormat::KTXExternalFormat_RGBA, KTXType_F32 }; gKTXSrgbFormats[KTXInternalFormat_SR8] = true; gKTXSrgbFormats[KTXInternalFormat_SRG8] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8] = true; // Compressed sRGB formats gKTXSrgbFormats[KTXInternalFormat_SRGB_DXT1] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB_ALPHA_DXT1] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB_ALPHA_DXT3] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB_ALPHA_DXT5] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB_BP_UNORM] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB_PVRTC_2BPPV1] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB_PVRTC_4BPPV1] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB_ALPHA_PVRTC_2BPPV1] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB_ALPHA_PVRTC_4BPPV1] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB_ALPHA_PVRTC_2BPPV2] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB_ALPHA_PVRTC_4BPPV2] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ETC2] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ETC2_EAC] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_4x4] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_5x4] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_5x5] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_6x5] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_6x6] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_8x5] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_8x6] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_8x8] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_10x5] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_10x6] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_10x8] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_10x10] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_12x10] = true; gKTXSrgbFormats[KTXInternalFormat_SRGB8_ALPHA8_ASTC_12x12] = true; } } gImageLoaderInst; void Image::AddImageLoader(const char* pExtension, ImageLoaderFunction pFunc) { gImageLoaders.push_back({ pExtension, pFunc }); } bool Image::LoadFromMemory( void const* mem, uint32_t size, char const* extension, memoryAllocationFunc pAllocator, void* pUserData) { // try loading the format bool loaded = false; for (uint32_t i = 0; i < (uint32_t)gImageLoaders.size(); ++i) { ImageLoaderDefinition const& def = gImageLoaders[i]; if (stricmp(extension, def.mExtension.c_str()) == 0) { loaded = def.pLoader(this, (char const*)mem, size, pAllocator, pUserData); break; } } return loaded; } bool Image::LoadFromFile(const char* origFileName, memoryAllocationFunc pAllocator, void* pUserData, FSRoot root) { // clear current image Clear(); eastl::string extension = FileSystem::GetExtension(origFileName); uint32_t loaderIndex = -1; if (extension.size()) { for (int i = 0; i < (int)gImageLoaders.size(); i++) { if (stricmp(extension.c_str(), gImageLoaders[i].mExtension.c_str()) == 0) { loaderIndex = i; break; } } if (loaderIndex == -1) extension = ""; } char fileName[MAX_PATH] = {}; strcpy(fileName, origFileName); if (!extension.size()) { #if defined(__ANDROID__) extension = ".ktx"; #elif defined(TARGET_IOS) extension = ".ktx"; #elif defined(__linux__) extension = ".dds"; #elif defined(__APPLE__) extension = ".dds"; #else extension = ".dds"; #endif strcpy(fileName + strlen(origFileName), extension.c_str()); } // open file File file = {}; file.Open(fileName, FM_ReadBinary, root); if (!file.IsOpen()) { LOGF(LogLevel::eERROR, "\"%s\": Image file not found.", fileName); return false; } // load file into memory uint32_t length = file.GetSize(); if (length == 0) { //char output[256]; //sprintf(output, "\"%s\": Image file is empty.", fileName); LOGF(LogLevel::eERROR, "\"%s\": Image is an empty file.", fileName); file.Close(); return false; } // read and close file. char* data = (char*)conf_malloc(length * sizeof(char)); file.Read(data, (unsigned)length); file.Close(); // try loading the format bool loaded = false; bool support = false; for (int i = 0; i < (int)gImageLoaders.size(); i++) { if (stricmp(extension.c_str(), gImageLoaders[i].mExtension.c_str()) == 0) { support = true; loaded = gImageLoaders[i].pLoader(this, data, length, pAllocator, pUserData); if (loaded) { break; } } } if (!support) { LOGF(LogLevel::eERROR, "Can't load this file format for image : %s", fileName); } else { mLoadFileName = fileName; } // cleanup the compressed data conf_free(data); return loaded; } bool Image::Convert(const ImageFormat::Enum newFormat) { ubyte* newPixels; uint nPixels = GetNumberOfPixels(0, mMipMapCount) * mArrayCount; if (mFormat == ImageFormat::RGBE8 && (newFormat == ImageFormat::RGB32F || newFormat == ImageFormat::RGBA32F)) { newPixels = (ubyte*)conf_malloc(sizeof(ubyte) * GetMipMappedSize(0, mMipMapCount, newFormat) * mArrayCount); float* dest = (float*)newPixels; bool writeAlpha = (newFormat == ImageFormat::RGBA32F); ubyte* src = pData; do { *((vec3*)dest) = rgbeToRGB(src); if (writeAlpha) { dest[3] = 1.0f; dest += 4; } else { dest += 3; } src += 4; } while (--nPixels); } else { if (!ImageFormat::IsPlainFormat(mFormat) || !(ImageFormat::IsPlainFormat(newFormat) || newFormat == ImageFormat::RGB10A2 || newFormat == ImageFormat::RGBE8 || newFormat == ImageFormat::RGB9E5)) { LOGF(LogLevel::eERROR, "Image: %s fail to convert from %s to %s", mLoadFileName.c_str(), ImageFormat::GetFormatString(mFormat), ImageFormat::GetFormatString(newFormat)); return false; } if (mFormat == newFormat) return true; ubyte* src = pData; ubyte* dest = newPixels = (ubyte*)conf_malloc(sizeof(ubyte) * GetMipMappedSize(0, mMipMapCount, newFormat) * mArrayCount); if (mFormat == ImageFormat::RGB8 && newFormat == ImageFormat::RGBA8) { // Fast path for RGB->RGBA8 do { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; dest[3] = 255; dest += 4; src += 3; } while (--nPixels); } else if (mFormat == ImageFormat::RGBA8 && newFormat == ImageFormat::BGRA8) { // Fast path for RGBA8->BGRA8 (just swizzle) do { dest[0] = src[2]; dest[1] = src[1]; dest[2] = src[0]; dest[3] = src[3]; dest += 4; src += 4; } while (--nPixels); } else { int srcSize = ImageFormat::GetBytesPerPixel(mFormat); int nSrcChannels = ImageFormat::GetChannelCount(mFormat); int destSize = ImageFormat::GetBytesPerPixel(newFormat); int nDestChannels = ImageFormat::GetChannelCount(newFormat); do { float rgba[4]; if (ImageFormat::IsFloatFormat(mFormat)) { if (mFormat <= ImageFormat::RGBA16F) { for (int i = 0; i < nSrcChannels; i++) rgba[i] = ((half*)src)[i]; } else { for (int i = 0; i < nSrcChannels; i++) rgba[i] = ((float*)src)[i]; } } else if (mFormat >= ImageFormat::I16 && mFormat <= ImageFormat::RGBA16) { for (int i = 0; i < nSrcChannels; i++) rgba[i] = ((ushort*)src)[i] * (1.0f / 65535.0f); } else { for (int i = 0; i < nSrcChannels; i++) rgba[i] = src[i] * (1.0f / 255.0f); } if (nSrcChannels < 4) rgba[3] = 1.0f; if (nSrcChannels == 1) rgba[2] = rgba[1] = rgba[0]; if (nDestChannels == 1) rgba[0] = 0.30f * rgba[0] + 0.59f * rgba[1] + 0.11f * rgba[2]; if (ImageFormat::IsFloatFormat(newFormat)) { if (newFormat <= ImageFormat::RGBA32F) { if (newFormat <= ImageFormat::RGBA16F) { for (int i = 0; i < nDestChannels; i++) ((half*)dest)[i] = rgba[i]; } else { for (int i = 0; i < nDestChannels; i++) ((float*)dest)[i] = rgba[i]; } } else { if (newFormat == ImageFormat::RGBE8) { *(uint32*)dest = rgbToRGBE8(vec3(rgba[0], rgba[1], rgba[2])); } else { *(uint32*)dest = rgbToRGB9E5(vec3(rgba[0], rgba[1], rgba[2])); } } } else if (newFormat >= ImageFormat::I16 && newFormat <= ImageFormat::RGBA16) { for (int i = 0; i < nDestChannels; i++) ((ushort*)dest)[i] = (ushort)(65535 * saturate(rgba[i]) + 0.5f); } else if (/*isPackedFormat(newFormat)*/ newFormat == ImageFormat::RGB10A2) { *(uint*)dest = (uint(1023.0f * saturate(rgba[0]) + 0.5f) << 22) | (uint(1023.0f * saturate(rgba[1]) + 0.5f) << 12) | (uint(1023.0f * saturate(rgba[2]) + 0.5f) << 2) | (uint(3.0f * saturate(rgba[3]) + 0.5f)); } else { for (int i = 0; i < nDestChannels; i++) dest[i] = (unsigned char)(255 * saturate(rgba[i]) + 0.5f); } src += srcSize; dest += destSize; } while (--nPixels); } } conf_free(pData); pData = newPixels; mFormat = newFormat; return true; } template <typename T> void buildMipMap(T* dst, const T* src, const uint w, const uint h, const uint d, const uint c) { uint xOff = (w < 2) ? 0 : c; uint yOff = (h < 2) ? 0 : c * w; uint zOff = (d < 2) ? 0 : c * w * h; for (uint z = 0; z < d; z += 2) { for (uint y = 0; y < h; y += 2) { for (uint x = 0; x < w; x += 2) { for (uint i = 0; i < c; i++) { *dst++ = (src[0] + src[xOff] + src[yOff] + src[yOff + xOff] + src[zOff] + src[zOff + xOff] + src[zOff + yOff] + src[zOff + yOff + xOff]) / 8; src++; } src += xOff; } src += yOff; } src += zOff; } } bool Image::GenerateMipMaps(const uint32_t mipMaps) { if (ImageFormat::IsCompressedFormat(mFormat)) return false; if (!(mWidth) || !isPowerOf2(mHeight) || !isPowerOf2(mDepth)) return false; uint actualMipMaps = min(mipMaps, GetMipMapCountFromDimensions()); if (mMipMapCount != actualMipMaps) { int size = GetMipMappedSize(0, actualMipMaps); if (mArrayCount > 1) { ubyte* newPixels = (ubyte*)conf_malloc(sizeof(ubyte) * size * mArrayCount); // Copy top mipmap of all array slices to new location int firstMipSize = GetMipMappedSize(0, 1); int oldSize = GetMipMappedSize(0, mMipMapCount); for (uint i = 0; i < mArrayCount; i++) { memcpy(newPixels + i * size, pData + i * oldSize, firstMipSize); } conf_free(pData); pData = newPixels; } else { pData = (ubyte*)conf_realloc(pData, size); } mMipMapCount = actualMipMaps; } int nChannels = ImageFormat::GetChannelCount(mFormat); int n = IsCube() ? 6 : 1; for (uint arraySlice = 0; arraySlice < mArrayCount; arraySlice++) { ubyte* src = GetPixels(0, arraySlice); ubyte* dst = GetPixels(1, arraySlice); for (uint level = 1; level < mMipMapCount; level++) { int w = GetWidth(level - 1); int h = GetHeight(level - 1); int d = GetDepth(level - 1); int srcSize = GetMipMappedSize(level - 1, 1) / n; int dstSize = GetMipMappedSize(level, 1) / n; for (int i = 0; i < n; i++) { if (ImageFormat::IsPlainFormat(mFormat)) { if (ImageFormat::IsFloatFormat(mFormat)) { buildMipMap((float*)dst, (float*)src, w, h, d, nChannels); } else if (mFormat >= ImageFormat::I16) { buildMipMap((ushort*)dst, (ushort*)src, w, h, d, nChannels); } else { buildMipMap(dst, src, w, h, d, nChannels); } } src += srcSize; dst += dstSize; } } } return true; } bool Image::iSwap(const int c0, const int c1) { if (!ImageFormat::IsPlainFormat(mFormat)) return false; unsigned int nPixels = GetNumberOfPixels(0, mMipMapCount) * mArrayCount; unsigned int nChannels = ImageFormat::GetChannelCount(mFormat); if (mFormat <= ImageFormat::RGBA8) { swapPixelChannels((uint8_t*)pData, nPixels, nChannels, c0, c1); } else if (mFormat <= ImageFormat::RGBA16F) { swapPixelChannels((uint16_t*)pData, nPixels, nChannels, c0, c1); } else { swapPixelChannels((float*)pData, nPixels, nChannels, c0, c1); } return true; } // -- IMAGE SAVING -- bool Image::iSaveDDS(const char* fileName) { DDSHeader header; DDSHeaderDX10 headerDX10; memset(&header, 0, sizeof(header)); memset(&headerDX10, 0, sizeof(headerDX10)); header.mDWMagic = MAKE_CHAR4('D', 'D', 'S', ' '); header.mDWSize = 124; header.mDWWidth = mWidth; header.mDWHeight = mHeight; header.mDWDepth = (mDepth > 1) ? mDepth : 0; header.mDWPitchOrLinearSize = 0; header.mDWMipMapCount = (mMipMapCount > 1) ? mMipMapCount : 0; header.mPixelFormat.mDWSize = 32; header.mDWFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT | (mMipMapCount > 1 ? DDSD_MIPMAPCOUNT : 0) | (mDepth > 1 ? DDSD_DEPTH : 0); int nChannels = ImageFormat::GetChannelCount(mFormat); if (mFormat == ImageFormat::RGB10A2 || mFormat <= ImageFormat::I16) { if (mFormat <= ImageFormat::RGBA8) { header.mPixelFormat.mDWRGBBitCount = 8 * nChannels; header.mPixelFormat.mDWRGBAlphaBitMask = (nChannels == 4) ? 0xFF000000 : (nChannels == 2) ? 0xFF00 : 0; header.mPixelFormat.mDWRBitMask = (nChannels > 2) ? 0x00FF0000 : 0xFF; header.mPixelFormat.mDWGBitMask = (nChannels > 1) ? 0x0000FF00 : 0; header.mPixelFormat.mDWBBitMask = (nChannels > 1) ? 0x000000FF : 0; } else if (mFormat == ImageFormat::I16) { header.mPixelFormat.mDWRGBBitCount = 16; header.mPixelFormat.mDWRBitMask = 0xFFFF; } else { header.mPixelFormat.mDWRGBBitCount = 32; header.mPixelFormat.mDWRGBAlphaBitMask = 0xC0000000; header.mPixelFormat.mDWRBitMask = 0x3FF00000; header.mPixelFormat.mDWGBitMask = 0x000FFC00; header.mPixelFormat.mDWBBitMask = 0x000003FF; } header.mPixelFormat.mDWFlags = ((nChannels < 3) ? 0x00020000 : DDPF_RGB) | ((nChannels & 1) ? 0 : DDPF_ALPHAPIXELS); } else { header.mPixelFormat.mDWFlags = DDPF_FOURCC; switch (mFormat) { case ImageFormat::RG16: header.mPixelFormat.mDWFourCC = 34; break; case ImageFormat::RGBA16: header.mPixelFormat.mDWFourCC = 36; break; case ImageFormat::R16F: header.mPixelFormat.mDWFourCC = 111; break; case ImageFormat::RG16F: header.mPixelFormat.mDWFourCC = 112; break; case ImageFormat::RGBA16F: header.mPixelFormat.mDWFourCC = 113; break; case ImageFormat::R32F: header.mPixelFormat.mDWFourCC = 114; break; case ImageFormat::RG32F: header.mPixelFormat.mDWFourCC = 115; break; case ImageFormat::RGBA32F: header.mPixelFormat.mDWFourCC = 116; break; case ImageFormat::DXT1: header.mPixelFormat.mDWFourCC = MAKE_CHAR4('D', 'X', 'T', '1'); break; case ImageFormat::DXT3: header.mPixelFormat.mDWFourCC = MAKE_CHAR4('D', 'X', 'T', '3'); break; case ImageFormat::DXT5: header.mPixelFormat.mDWFourCC = MAKE_CHAR4('D', 'X', 'T', '5'); break; case ImageFormat::ATI1N: header.mPixelFormat.mDWFourCC = MAKE_CHAR4('A', 'T', 'I', '1'); break; case ImageFormat::ATI2N: header.mPixelFormat.mDWFourCC = MAKE_CHAR4('A', 'T', 'I', '2'); break; default: header.mPixelFormat.mDWFourCC = MAKE_CHAR4('D', 'X', '1', '0'); headerDX10.mArraySize = 1; headerDX10.mDXGIFormat = (mDepth == 0) ? D3D10_RESOURCE_MISC_TEXTURECUBE : 0; if (Is1D()) headerDX10.mResourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE1D; else if (Is2D()) headerDX10.mResourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D; else if (Is3D()) headerDX10.mResourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE3D; switch (mFormat) { case ImageFormat::RGB32F: headerDX10.mDXGIFormat = 6; break; case ImageFormat::RGB9E5: headerDX10.mDXGIFormat = 67; break; case ImageFormat::RG11B10F: headerDX10.mDXGIFormat = 26; break; default: return false; } } } // header. header.mCaps.mDWCaps1 = DDSCAPS_TEXTURE | (mMipMapCount > 1 ? DDSCAPS_MIPMAP | DDSCAPS_COMPLEX : 0) | (mDepth != 1 ? DDSCAPS_COMPLEX : 0); header.mCaps.mDWCaps2 = (mDepth > 1) ? DDSCAPS2_VOLUME : (mDepth == 0) ? DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_ALL_FACES : 0; header.mCaps.mReserved[0] = 0; header.mCaps.mReserved[1] = 0; header.mDWReserved2 = 0; File file; if (!file.Open(fileName, FileMode::FM_WriteBinary, FSR_Textures)) return false; file.Write(&header, sizeof(header)); if (headerDX10.mDXGIFormat) file.Write(&headerDX10, sizeof(headerDX10) * 1); int size = GetMipMappedSize(0, mMipMapCount); // RGB to BGR if (mFormat == ImageFormat::RGB8 || mFormat == ImageFormat::RGBA8) swapPixelChannels(pData, size / nChannels, nChannels, 0, 2); if (IsCube()) { for (int face = 0; face < 6; face++) { for (uint mipMapLevel = 0; mipMapLevel < mMipMapCount; mipMapLevel++) { int faceSize = GetMipMappedSize(mipMapLevel, 1) / 6; ubyte* src = GetPixels(mipMapLevel) + face * faceSize; file.Write(src, faceSize); } } } else { file.Write(pData, size); } file.Close(); // Restore to RGB if (mFormat == ImageFormat::RGB8 || mFormat == ImageFormat::RGBA8) swapPixelChannels(pData, size / nChannels, nChannels, 0, 2); return true; } bool convertAndSaveImage(const Image& image, bool (Image::*saverFunction)(const char*), const char* fileName) { bool bSaveImageSuccess = false; Image imgCopy(image); imgCopy.Uncompress(); if (imgCopy.Convert(ImageFormat::RGBA8)) { bSaveImageSuccess = (imgCopy.*saverFunction)(fileName); } imgCopy.Destroy(); return bSaveImageSuccess; } bool Image::iSaveTGA(const char* fileName) { switch (mFormat) { case ImageFormat::R8: return 0 != stbi_write_tga(fileName, mWidth, mHeight, 1, pData); break; case ImageFormat::RG8: return 0 != stbi_write_tga(fileName, mWidth, mHeight, 2, pData); break; case ImageFormat::RGB8: return 0 != stbi_write_tga(fileName, mWidth, mHeight, 3, pData); break; case ImageFormat::RGBA8: return 0 != stbi_write_tga(fileName, mWidth, mHeight, 4, pData); break; default: { // uncompress/convert and try again return convertAndSaveImage(*this, &Image::iSaveTGA, fileName); } } //return false; //Unreachable } bool Image::iSaveBMP(const char* fileName) { switch (mFormat) { case ImageFormat::R8: stbi_write_bmp(fileName, mWidth, mHeight, 1, pData); break; case ImageFormat::RG8: stbi_write_bmp(fileName, mWidth, mHeight, 2, pData); break; case ImageFormat::RGB8: stbi_write_bmp(fileName, mWidth, mHeight, 3, pData); break; case ImageFormat::RGBA8: stbi_write_bmp(fileName, mWidth, mHeight, 4, pData); break; default: { // uncompress/convert and try again return convertAndSaveImage(*this, &Image::iSaveBMP, fileName); } } return true; } bool Image::iSavePNG(const char* fileName) { switch (mFormat) { case ImageFormat::R8: stbi_write_png(fileName, mWidth, mHeight, 1, pData, 0); break; case ImageFormat::RG8: stbi_write_png(fileName, mWidth, mHeight, 2, pData, 0); break; case ImageFormat::RGB8: stbi_write_png(fileName, mWidth, mHeight, 3, pData, 0); break; case ImageFormat::RGBA8: stbi_write_png(fileName, mWidth, mHeight, 4, pData, 0); break; default: { // uncompress/convert and try again return convertAndSaveImage(*this, &Image::iSavePNG, fileName); } } return true; } bool Image::iSaveHDR(const char* fileName) { switch (mFormat) { case ImageFormat::R32F: stbi_write_hdr(fileName, mWidth, mHeight, 1, (float*)pData); break; case ImageFormat::RG32F: stbi_write_hdr(fileName, mWidth, mHeight, 2, (float*)pData); break; case ImageFormat::RGB32F: stbi_write_hdr(fileName, mWidth, mHeight, 3, (float*)pData); break; case ImageFormat::RGBA32F: stbi_write_hdr(fileName, mWidth, mHeight, 4, (float*)pData); break; default: { // uncompress/convert and try again return convertAndSaveImage(*this, &Image::iSaveHDR, fileName); } } return true; } bool Image::iSaveJPG(const char* fileName) { switch (mFormat) { case ImageFormat::R8: stbi_write_jpg(fileName, mWidth, mHeight, 1, pData, 0); break; case ImageFormat::RG8: stbi_write_jpg(fileName, mWidth, mHeight, 2, pData, 0); break; case ImageFormat::RGB8: stbi_write_jpg(fileName, mWidth, mHeight, 3, pData, 0); break; case ImageFormat::RGBA8: stbi_write_jpg(fileName, mWidth, mHeight, 4, pData, 0); break; default: { // uncompress/convert and try again return convertAndSaveImage(*this, &Image::iSaveJPG, fileName); } } return true; } struct ImageSaverDefinition { typedef bool (Image::*ImageSaverFunction)(const char*); const char* Extension; ImageSaverFunction Loader; }; static ImageSaverDefinition gImageSavers[] = { #if !defined(NO_STBI) { ".bmp", &Image::iSaveBMP }, { ".hdr", &Image::iSaveHDR }, { ".png", &Image::iSavePNG }, { ".tga", &Image::iSaveTGA }, { ".jpg", &Image::iSaveJPG }, #endif { ".dds", &Image::iSaveDDS } }; bool Image::Save(const char* fileName) { const char* extension = strrchr(fileName, '.'); bool support = false; ; for (int i = 0; i < sizeof(gImageSavers) / sizeof(gImageSavers[0]); i++) { if (stricmp(extension, gImageSavers[i].Extension) == 0) { support = true; return (this->*gImageSavers[i].Loader)(fileName); } } if (!support) { LOGF(LogLevel::eERROR, "Can't save this file format for image : %s", fileName); } return false; }
32.127265
170
0.712046
[ "vector" ]
720e593ab0d59a89d016955ffa08ebc577a7ca15
13,423
cc
C++
project2/solution/exp_converter.cc
natianxing/CompilerProject
7999e4d94c22716f8a4c7c4448046db0eb628adc
[ "MIT" ]
null
null
null
project2/solution/exp_converter.cc
natianxing/CompilerProject
7999e4d94c22716f8a4c7c4448046db0eb628adc
[ "MIT" ]
null
null
null
project2/solution/exp_converter.cc
natianxing/CompilerProject
7999e4d94c22716f8a4c7c4448046db0eb628adc
[ "MIT" ]
null
null
null
// // Created by luoyuchu on 2020/6/20. // #include "exp_converter.h" #include <bits/stdc++.h> #include <json/json.h> using namespace std; int flagfirst=0; class myNode { public: enum NODETYPE {OP, LEAF, CONST, TREF, SREF}; public: NODETYPE type; char op; string id, expText; set<string> indSet; vector<string> index; vector<int> dimension; myNode *pa, *child[2]; myNode *dv; void debug_dfs() { debug_print(); if (type == OP) { child[0]->debug_dfs(); child[1]->debug_dfs(); } } void build_d(myNode *fdv) { if(type==OP) { if(op=='+') { child[0]->build_d(fdv); child[1]->build_d(fdv); } else if(op=='-') { child[0]->build_d(fdv); myNode *tmp=new myNode; tmp->type=CONST; tmp->expText="0"; myNode *tmp1=new myNode; tmp1->type=OP; tmp1->op='-'; tmp1->child[0]=tmp; tmp1->child[1]=child[1]; child[1]->build_d(tmp1); } else if(op=='*') { myNode *tmp=new myNode; tmp->type=OP; tmp->op='*'; tmp->child[0]=child[1]; tmp->child[1]=fdv; child[0]->build_d(tmp); myNode *tmp1=new myNode; tmp1->type=OP; tmp1->op='*'; tmp1->child[0]=child[0]; tmp1->child[1]=fdv; child[1]->build_d(tmp1); } else if(op=='/') { myNode *tmp=new myNode; tmp->type=OP; tmp->op='/'; tmp->child[0]=fdv; tmp->child[1]=child[1]; child[0]->build_d(tmp); myNode *tmp1=new myNode; tmp1->type=OP; tmp1->op='*'; tmp1->child[0]=child[1]; tmp1->child[1]=child[1]; myNode *tmp2=new myNode; tmp2->type=OP; tmp2->op='*'; tmp2->child[0]=child[0]; tmp2->child[1]=fdv; myNode *tmp3=new myNode; tmp3->type=OP; tmp3->op='/'; tmp3->child[0]=tmp2; tmp3->child[1]=tmp3; child[1]->build_d(tmp3); } } else if(type==TREF||type==SREF) { dv=fdv; return; } } string der_target(string target) { if(type == OP) { string r1, r2; r1 = child[0]->der_target(target); r2 = child[1]->der_target(target); return r1 + r2; } else if(type==TREF||type==SREF) { if(id==target) { if(flagfirst==0) { string expr="d"+expText+"="+dv->mid_dfs()+";"; flagfirst=1; return expr; } else { // string expr="d"+expText+"=d"+expText+"+"+dv->mid_dfs()+";"; string expr="d"+expText+"+="+dv->mid_dfs()+";"; return expr; } } } return ""; } string mid_dfs() { if(type==OP) { if(op=='+') { return child[0]->mid_dfs()+"+"+child[1]->mid_dfs(); } else if(op=='-') { return child[0]->mid_dfs()+"-"+child[1]->mid_dfs(); } else if(op=='*') { return child[0]->mid_dfs()+"*"+child[1]->mid_dfs(); } else if(op=='/') { return child[0]->mid_dfs()+"/"+child[1]->mid_dfs(); } } else { return expText; } } void debug_print() { cerr << "{" << endl; if (type == CONST) { cerr << "\tConst" << endl; cerr << "\t" << expText << endl; } if (type == SREF) { cerr << "\tSRef" << endl; cerr << "\tid = " << id << endl; cerr << "\texp = " << expText << endl; cerr << "\tdimension: "; for (auto i : dimension) cerr << i << ", "; cerr << endl; } if (type == TREF) { cerr << "\tTRef" << endl; cerr << "\tid = " << id << endl; cerr << "\texp = " << expText << endl; cerr << "\tdimension: "; for (auto i : dimension) cerr << i << ", "; cerr << endl; cerr << "\tindices: "; for (auto i : index) cerr << i << ", "; cerr << endl; } if (type == OP) { cerr << "\tOP" << endl; cerr << "\top = " << op << endl; cerr << "\tleft child = " << child[0]->expText << endl; cerr << "\tright child = " << child[1]->expText << endl; } cerr << "}" << endl; } }; class buildAST { public: int op_priority[256]; myNode *astRoot; string lRef; public: buildAST() { memset(op_priority, 0, sizeof(op_priority)); astRoot = NULL; lRef = ""; } void initialize() { op_priority[')'] = 1; op_priority['+'] = op_priority['-'] = 2; op_priority['*'] = op_priority['/'] = op_priority['%'] = op_priority['#'] = 3; op_priority['('] = 4; op_priority[';'] = op_priority['='] = 5; } vector<string> splitBy(string str, string delimiter) { size_t tpos = 0; vector<string> result; while ((tpos = str.find(delimiter)) != string::npos) { if (tpos != 0) { result.push_back(str.substr(0, tpos)); } str.erase(0, tpos + delimiter.length()); } if (!str.empty()) result.push_back(str); return result; } myNode* getItem(string &exp) { size_t tpos = 0; int nest = 0; //find a item, like:A<...>[..] for (tpos = 0; tpos < exp.length(); ++tpos) { if (exp[tpos] == '[') nest++; if (exp[tpos] == ']') nest--; if (nest == 0 && op_priority[exp[tpos]] != 0) break; } string item(exp.substr(0,tpos)); exp = exp.substr(tpos); myNode *result = new myNode; result->expText = item; //const if (item.find('<') == string::npos) { result->type = myNode::NODETYPE::CONST; } else { //id vector<int> dimension; result->id = item.substr(0, item.find('<')); item = item.substr(item.find('<') + 1); for (auto i : splitBy(item.substr(0, item.find('>')), ",")) { dimension.push_back(atoi(i.c_str())); } result->dimension = dimension; item = item.substr(item.find('>') + 1); if (item.empty()) { result->type = myNode::NODETYPE::SREF; } else { result->type = myNode::NODETYPE::TREF; result->index = splitBy(item.substr(1, item.find(']') - 1), ","); } } return result; // cerr << item << endl; } myNode* build(string stmt) { size_t tpos = 0; //delete space while ((tpos = stmt.find(' ')) != string::npos) { stmt.erase(tpos,1); } //replace integer divide to # while ((tpos = stmt.find("//")) != string::npos) { stmt.replace(tpos, 2, "#"); } //split by '=' tpos = stmt.find('='); string lref(stmt.substr(0, tpos)); string exp(stmt.substr(tpos + 1)); lRef = lref; //cerr << stmt << endl; //cerr << lref << ' ' << exp << endl; //build ast stack<myNode*> nodeStack; stack<char> opStack; exp = exp + ")"; opStack.push('('); while (!exp.empty()) { if (op_priority[exp[0]] != 0) { char curOp = exp[0]; exp.erase(0,1); while (opStack.top() != '(' && op_priority[curOp] <= op_priority[opStack.top()]) { myNode *result = new myNode, *tmp; result->type = myNode::NODETYPE::OP; result->op = opStack.top(); result->child[1] = nodeStack.top(); nodeStack.pop(); result->child[0] = nodeStack.top(); nodeStack.pop(); result->expText = result->child[0]->expText + result->op + result->child[1]->expText; nodeStack.push(result); opStack.pop(); } if (curOp == ')') { opStack.pop(); if (!opStack.empty()) nodeStack.top()->expText = "(" + nodeStack.top()->expText + ")"; } else opStack.push(curOp); } else { nodeStack.push(getItem(exp)); } } //nodeStack.top()->debug_dfs(); astRoot = nodeStack.top(); return nodeStack.top(); } //eliminate operator in LHS indices //full of bug !!!! but able to pass all testcase :((((( //never do it again void simplifyLeft(string &stmt) { myNode *tmpNode = getItem(stmt); if (tmpNode->type != myNode::NODETYPE::TREF) { stmt = tmpNode->expText + stmt; return; } string deltaStr; //assumption: 'z', 'y', 'x' etc. do not show up as index :) char newInd = 'z'; int firstInd = 0; size_t tpos; string newHead = tmpNode->expText.substr(0, tmpNode->expText.find('>') + 1); newHead += '['; for (auto &i : tmpNode->index) { if (firstInd++) newHead += ','; if (i.find('+') != string::npos || i.find('-') != string::npos || i.find('*') != string::npos || i.find('/') != string::npos || i.find('#') != string::npos || i.find('%') != string::npos) { deltaStr += "!["; deltaStr += newInd; deltaStr += "," + i + "]"; i = newInd; newInd -= 1; } newHead += i; } newHead += ']'; stmt = newHead + deltaStr + stmt; } void changeJson(Json::Value &root) { string exp = root["kernel"].asString(); string result, tmpStr; initialize(); build(exp.erase(exp.find(";"), 1)); for (int i = 0; i < root["grad_to"].size(); ++i) { myNode *tmp=new myNode; tmp->type=myNode::NODETYPE::TREF; tmp->expText="d" + lRef; tmp->id="d" + root["grad_to"][i].asString(); astRoot->build_d(tmp); flagfirst=0; result = result + astRoot->der_target(root["grad_to"][i].asString()); } //input param set<string> existParam; vector<string> inputParam; tmpStr = result; while (!tmpStr.empty()) { if (op_priority[tmpStr[0]] != 0) { tmpStr.erase(0, 1); } else { myNode *tmpNode = getItem(tmpStr); if (tmpNode->type == myNode::NODETYPE::TREF) { existParam.insert(tmpNode->id); } } } for (int i = 0; i < root["ins"].size(); ++i) { tmpStr = root["ins"][i].asString(); if (existParam.count(tmpStr) != 0) { inputParam.push_back(tmpStr); } } root["ins"] = Json::arrayValue; for (auto i : inputParam) { root["ins"].append(i); } //output param tmpStr = root["outs"][0].asString(); root["outs"] = Json::arrayValue; root["outs"].append("d" + tmpStr); for (int i = 0; i < root["grad_to"].size(); ++i) { root["outs"].append("d" + root["grad_to"][i].asString()); } //kernel size_t tpos = 0; string newKernel; while ((tpos = result.find(';')) != string::npos) { tmpStr = result.substr(0, tpos + 1); simplifyLeft(tmpStr); result.erase(0, tpos + 1); newKernel += tmpStr; } while ((tpos = newKernel.find("#")) != string::npos) { newKernel.replace(tpos, 1, "/"); } root["kernel"] = newKernel; } }; void exp_converter(Json::Value &root) { buildAST *builder = new buildAST; builder->changeJson(root); }
30.300226
113
0.399687
[ "vector" ]
7213f9fa28055993143fbacf396e5264f78200f3
2,066
hpp
C++
include/lug/Graphics/GltfLoader.hpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
275
2016-10-08T15:33:17.000Z
2022-03-30T06:11:56.000Z
include/lug/Graphics/GltfLoader.hpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
24
2016-09-29T20:51:20.000Z
2018-05-09T21:41:36.000Z
include/lug/Graphics/GltfLoader.hpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
37
2017-02-25T05:03:48.000Z
2021-05-10T19:06:29.000Z
#pragma once #include <vector> #include <gltf2/glTF2.hpp> #include <lug/Graphics/Export.hpp> #include <lug/Graphics/Loader.hpp> #include <lug/Graphics/Render/Material.hpp> #include <lug/Graphics/Render/Mesh.hpp> #include <lug/Graphics/Render/Texture.hpp> #include <lug/Graphics/Scene/Node.hpp> namespace lug { namespace Graphics { class Renderer; /** * @brief Class for loading glTF files */ class LUG_GRAPHICS_API GltfLoader final : public Loader { private: struct LoadedAssets { std::vector<Resource::SharedPtr<Render::Texture>> textures; Resource::SharedPtr<Render::Material> defaultMaterial; std::vector<Resource::SharedPtr<Render::Material>> materials; std::vector<Resource::SharedPtr<Render::Mesh>> meshes; }; public: GltfLoader(Renderer& renderer); GltfLoader(const GltfLoader&) = delete; GltfLoader(GltfLoader&&) = delete; GltfLoader& operator=(const GltfLoader&) = delete; GltfLoader& operator=(GltfLoader&&) = delete; ~GltfLoader() = default; /** * @brief Loads a glTF ressource from a file * @param[in] filename The filename * @return SharedPtr to the resulting Resource */ Resource::SharedPtr<Resource> loadFile(const std::string& filename) override final; private: Resource::SharedPtr<Render::Texture> createTexture(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index); Resource::SharedPtr<Render::Material> createMaterial(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index); Resource::SharedPtr<Render::Material> createDefaultMaterial(Renderer& renderer, GltfLoader::LoadedAssets& loadedAssets); Resource::SharedPtr<Render::Mesh> createMesh(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index); bool createNode(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index, Scene::Node& parent); }; } // Graphics } // lug
35.016949
159
0.726041
[ "mesh", "render", "vector" ]
7214ba5c0a9d5850f776b5496bec308f0643d974
2,779
cpp
C++
MeetingCodes/Meeting12/ScaleBigScalarField.cpp
SubhoB/spectre-cpp-basics
0f581b879e83e88d1491b31e22aa447419d471a3
[ "MIT" ]
15
2020-06-01T19:48:57.000Z
2021-11-01T07:33:42.000Z
MeetingCodes/Meeting12/ScaleBigScalarField.cpp
SubhoB/spectre-cpp-basics
0f581b879e83e88d1491b31e22aa447419d471a3
[ "MIT" ]
1
2020-06-02T02:43:41.000Z
2020-06-02T03:55:50.000Z
MeetingCodes/Meeting12/ScaleBigScalarField.cpp
SubhoB/spectre-cpp-basics
0f581b879e83e88d1491b31e22aa447419d471a3
[ "MIT" ]
6
2020-06-23T22:36:56.000Z
2021-06-14T14:46:49.000Z
#include <chrono> #include <cstddef> #include <iostream> #include <numeric> #include <vector> class ScalarField { public: std::vector<double> x{}; size_t size = 0; ScalarField(const size_t initial_size) noexcept { x.resize(initial_size); size = initial_size; } void resize(const size_t new_size) noexcept { x.resize(new_size); size = new_size; } }; ScalarField initialize_scalar_field(const size_t size, const double initial_value) noexcept { ScalarField field{size}; std::iota(field.x.begin(), field.x.end(), initial_value); return field; } ScalarField scale_scalar_field(const ScalarField& field, const double scale_factor) noexcept { ScalarField result = field; for (auto it = result.x.begin(); it != result.x.end(); ++it) { *it *= scale_factor; } return result; } ScalarField scale_scalar_field(ScalarField&& field, const double scale_factor) noexcept { for (auto it = field.x.begin(); it != field.x.end(); ++it) { *it *= scale_factor; } return std::move(field); } int main() { constexpr size_t size = 1000000000; constexpr double initial_value = 0.0; constexpr double scale_factor = 10.0; using clock = std::chrono::high_resolution_clock; auto start_time = clock::now(); auto stop_time = clock::now(); std::cout << "Initializing scalar field of size " << size << "\n"; start_time = clock::now(); ScalarField field_a = initialize_scalar_field(size, initial_value); stop_time = clock::now(); std::cout << field_a.x[size / 2] << " (" << std::chrono::duration_cast<std::chrono::microseconds>(stop_time - start_time) .count() << " microseconds)\n"; std::cout << "Scaling scalar field by " << scale_factor << "\n"; start_time = clock::now(); ScalarField field_b = scale_scalar_field(field_a, scale_factor); stop_time = clock::now(); std::cout << field_b.x[size / 2] << " (" << std::chrono::duration_cast<std::chrono::microseconds>(stop_time - start_time) .count() << " microseconds)\n"; std::cout << "(std::move) scaling scalar field by " << scale_factor << "\n"; start_time = clock::now(); ScalarField field_c = scale_scalar_field(std::move(field_a), scale_factor); stop_time = clock::now(); std::cout << field_c.x[size / 2] << " (" << std::chrono::duration_cast<std::chrono::microseconds>(stop_time - start_time) .count() << " microseconds)\n"; return 0; }
29.88172
80
0.579345
[ "vector" ]
721a995643d2a4efa311d1edf50708e2aa5864ab
1,691
cpp
C++
ASN 3/Plane.cpp
Oseous/cs3388
1b382d6cfb392d17bc38accb7677a56558fc2592
[ "MIT" ]
1
2021-06-20T06:46:09.000Z
2021-06-20T06:46:09.000Z
ASN 3/Plane.cpp
Oseous/cs3388
1b382d6cfb392d17bc38accb7677a56558fc2592
[ "MIT" ]
null
null
null
ASN 3/Plane.cpp
Oseous/cs3388
1b382d6cfb392d17bc38accb7677a56558fc2592
[ "MIT" ]
1
2020-03-02T02:31:00.000Z
2020-03-02T02:31:00.000Z
/* Plane.cpp CS3388 Assignment 3 By: Andrew Simpson SN: 250 633 280 EM: asimps53@uwo.ca Plane is an implementation of the GenericObject super class. Obviously, it's a plane. This class implements the specific intersect and normal functions for a plane, and also adds its own constructor to allow different coloured planes to be created easily. NOTE: As in the class slides, I have only created a plane that is on the X-Y plane: Z=0. Other planes were not discussed, so I've assumed that we do not need to implement them for this project. */ #include "Plane.h" #include "RenderUtils.h" Plane::Plane() { transformSet(cv::Mat::eye(4, 4, CV_32FC1)); for (int i = 0; i < 3; i++) { rho_a[i] = rho_s[i] = 0; rho_d[i] = 0.9; } } Plane::Plane(cv::Mat trans, cv::Scalar rho_a, cv::Scalar rho_d, cv::Scalar rho_s) { transformSet(trans); // Also handles setting up the inverse transform this->rho_a = rho_a; this->rho_d = rho_d; this->rho_s = rho_s; } Plane::~Plane() { } bool Plane::intersect(cv::Mat e, cv::Mat d, float &dist) { if (d.at<float>(2) == 0) { // Doesn't intersect return false; } // Calculate the distance to the intersection dist = -e.at<float>(2) / d.at<float>(2); // Intersects! return true; } cv::Mat Plane::normal(cv::Mat point) { // Point isn't actually needed to get the normal. // Only needed for complying to the super class (other objects need the point). // Normal in base plane coordinates cv::Mat ret = cv::Mat::zeros(4, 1, CV_32FC1); ret.at<float>(2) = 1; // Transform into world coordinates ret = _M*ret; // Normalize RenderUtils::homoNormalize(ret); return ret; }
21.679487
81
0.664695
[ "transform" ]
7229f9a4cd30acd66ee7016adb65686d51878ce1
964
cpp
C++
src/quasicrystals_pointset.cpp
reneruhr/quacry
cb2f3448b348a26dd8dec018285e7bf030b4e395
[ "MIT" ]
null
null
null
src/quasicrystals_pointset.cpp
reneruhr/quacry
cb2f3448b348a26dd8dec018285e7bf030b4e395
[ "MIT" ]
null
null
null
src/quasicrystals_pointset.cpp
reneruhr/quacry
cb2f3448b348a26dd8dec018285e7bf030b4e395
[ "MIT" ]
null
null
null
#include "quasicrystals_pointset.h" namespace quacry{ void PointSet4::Init() { MakeSample(); std::string name = "PointSet"; auto layout = new kipod::GLRenderLayout; layout->SetupPointSet(&sample_); AddLayout(name, std::move(*layout)); } void PointSet4::Draw() { RenderObject::Draw("PointSet"); } void PointSet4::UpdateSample() { sample_.clear(); MakeSample(); auto layout = new kipod::GLRenderLayout; layout->SetupPointSet(&sample_); ChangeLayout("PointSet", std::move(*layout)); } std::vector<Vector4>* PointSet4::MakeSample() { int X0 = sample_size_[0], X = sample_size_[1], Y0 = sample_size_[2], Y = sample_size_[3], Z0 = sample_size_[4], Z = sample_size_[5], W0 = sample_size_[6], W = sample_size_[7]; for(int x=X0; x<=X; x++) for(int y=Y0; y<=Y; y++) for(int z=Z0; z<=Z; z++) for(int w=W0; w<=W; w++) sample_.emplace_back(Vector4(x,y,z,w)); return &sample_; } }
21.909091
49
0.623444
[ "vector" ]
722c58180398aa1b2170c7999eee19690dc3236e
8,971
cpp
C++
MathLib/Source/Transform.cpp
jkorn2324/jkornEngine
5822f2a311ed62e6ca495919872f0f436d300733
[ "MIT" ]
null
null
null
MathLib/Source/Transform.cpp
jkorn2324/jkornEngine
5822f2a311ed62e6ca495919872f0f436d300733
[ "MIT" ]
null
null
null
MathLib/Source/Transform.cpp
jkorn2324/jkornEngine
5822f2a311ed62e6ca495919872f0f436d300733
[ "MIT" ]
null
null
null
#include "MathPCH.h" #include "Transform.h" #include "Math.h" namespace MathLib { using Mat3x3 = MathLib::Matrix3x3; using Mat4x4 = MathLib::Matrix4x4; Transform2D::Transform2D() : m_position(Vector2::Zero), m_rotation(0.0f), m_scale(1.0f, 1.0f), m_parentTransformMatrix(Matrix4x4::Identity) { } Transform2D::Transform2D(const Vector2& pos, float rot, const Vector2& scale) : m_position(pos), m_rotation(rot), m_scale(scale), m_parentTransformMatrix(Matrix4x4::Identity) { } Transform2D::Transform2D(const Transform3D& transform) : m_position(transform.GetLocalPosition().x, transform.GetLocalPosition().y), m_rotation(transform.GetLocalEulerAngles(false).z), m_scale(transform.GetLocalScale().x, transform.GetLocalScale().y), m_parentTransformMatrix(transform.GetParentTransformMatrix()) { } Transform2D& Transform2D::operator=(const Transform3D& transform) { m_position = MathLib::Vector2{ transform.GetLocalPosition().x, transform.GetLocalPosition().y }; m_rotation = transform.GetLocalEulerAngles().z; m_scale = MathLib::Vector2{ transform.GetLocalScale().x, transform.GetLocalScale().y }; m_parentTransformMatrix = transform.GetParentTransformMatrix(); return *this; } void Transform2D::SetParentTransformMatrix(const Matrix4x4& mat) { m_parentTransformMatrix = mat; } void Transform2D::SetLocalPosition(float x, float y) { m_position.x = x; m_position.y = y; } void Transform2D::SetLocalPosition(const Vector2& position) { SetLocalPosition(position.x, position.y); } const Vector2& Transform2D::GetLocalPosition() const { return m_position; } void Transform2D::SetLocalScale(float scale) { SetLocalScale(scale, scale); } void Transform2D::SetLocalScale(float x, float y) { m_scale.x = x; m_scale.y = y; } void Transform2D::SetLocalScale(const Vector2& scale) { SetLocalScale(scale.x, scale.y); } const Vector2& Transform2D::GetLocalScale() const { return m_scale; } void Transform2D::SetLocalRotation(float rotation, bool inDegrees) { m_rotation = inDegrees ? MathLib::DEG2RAD * rotation : rotation; } float Transform2D::GetLocalRotation() const { return m_rotation; } float Transform2D::GetLocalRotation(bool inDegrees) const { return inDegrees ? MathLib::RAD2DEG * m_rotation : m_rotation; } void Transform2D::LookAt(const MathLib::Vector2& position) { Vector2 dir = Normalize(position - GetWorldPosition()); float angle = MathLib::ATan2(dir.y, dir.x); m_rotation = angle; } Vector2 Transform2D::GetLocalForward() const { float x = Cos(m_rotation, false); float y = Sin(m_rotation, false); return Normalize(Vector2(x, y)); } Vector2 Transform2D::GetWorldPosition() const { Vector3 worldPosition = m_parentTransformMatrix.GetTranslation(); return Vector2(worldPosition.x, worldPosition.y) + m_position; } Vector2 Transform2D::GetWorldForward() const { Vector3 parentForward = m_parentTransformMatrix.GetZAxis(); Vector2 forwardAdded = Vector2(parentForward.x, parentForward.y) + GetLocalForward(); forwardAdded.Normalize(); return forwardAdded; } Vector2 Transform2D::GetWorldScale() const { Vector3 scaleVec3 = m_parentTransformMatrix.GetScale(); return Vector2(scaleVec3.x, scaleVec3.y) * m_scale; } Matrix4x4 Transform2D::GetTransformMatrix() const { return m_parentTransformMatrix * GetLocalTransformMatrix(); } Matrix4x4 Transform2D::GetLocalTransformMatrix() const { return Matrix4x4::CreateScale(MathLib::Vector3(m_scale, 1.0f)) * Matrix4x4::CreateRotationZ(m_rotation) * Matrix4x4::CreateTranslation( MathLib::Vector3(m_position, 0.0f)); } Transform3D::Transform3D() : m_position(0.0f, 0.0f, 0.0f), m_scale(1.0f, 1.0f, 1.0f), m_rotator(), m_parentTransformMatrix(Mat4x4::Identity) { } Transform3D::Transform3D(const Vector3& pos, const Quaternion& rot, const Vector3& scale) : m_position(pos), m_scale(scale), m_rotator(rot), m_parentTransformMatrix(Mat4x4::Identity), m_hasParentTransformMatrix(false) { } Transform3D::Transform3D(const Transform2D& transform) : m_position(transform.GetLocalPosition(), 0.0f), m_scale(transform.GetLocalScale(), 1.0f), m_rotator(0.0f, 0.0f, transform.GetLocalRotation(false)), m_parentTransformMatrix(transform.GetParentTransformMatrix()), m_hasParentTransformMatrix(false) { } Transform3D& Transform3D::operator=(const Transform2D& transform) { m_position = MathLib::Vector3{ transform.GetLocalPosition(), 0.0f }; m_scale = MathLib::Vector3{ transform.GetLocalScale(), 1.0f }; m_rotator.eulers = MathLib::Vector3{ 0.0f, 0.0f, transform.GetLocalRotation(false) }; m_rotator.quaternion = Quaternion::FromEuler(m_rotator.eulers, false); m_parentTransformMatrix = transform.GetParentTransformMatrix(); return *this; } void Transform3D::SetParentTransformMatrix(const Matrix4x4& matrix) { m_hasParentTransformMatrix = matrix != MathLib::Matrix4x4::Identity; m_parentTransformMatrix = matrix; } void Transform3D::SetLocalPosition(const Vector3& pos) { SetLocalPosition(pos.x, pos.y, pos.z); } void Transform3D::SetLocalPosition(float x, float y, float z) { m_position.x = x; m_position.y = y; m_position.z = z; } const Vector3& Transform3D::GetLocalPosition() const { return m_position; } void Transform3D::SetLocalScale(float x, float y, float z) { m_scale.x = x; m_scale.y = y; m_scale.z = z; } void Transform3D::SetLocalScale(float s) { SetLocalScale(s, s, s); } void Transform3D::SetLocalScale(const Vector3& vec) { SetLocalScale(vec.x, vec.y, vec.z); } const Vector3& Transform3D::GetLocalScale() const { return m_scale; } MathLib::Matrix4x4 Transform3D::GetTransformMatrix() const { return m_parentTransformMatrix * GetLocalTransformMatrix(); } Mat4x4 Transform3D::GetLocalTransformMatrix() const { return Mat4x4::CreateScale(m_scale) * Mat4x4::CreateFromQuaternion(m_rotator.quaternion) * Mat4x4::CreateTranslation(m_position); } void Transform3D::SetLocalEulerAngles(const Vector3& eulers, bool inDegrees) { SetLocalEulerAngles(eulers.y, eulers.x, eulers.z, inDegrees); } void Transform3D::SetLocalEulerAngles(float yaw, float pitch, float roll, bool inDegrees) { m_rotator.eulers.x = inDegrees ? MathLib::DEG2RAD * pitch : pitch; m_rotator.eulers.y = inDegrees ? MathLib::DEG2RAD * yaw : yaw; m_rotator.eulers.z = inDegrees ? MathLib::DEG2RAD * roll : roll; m_rotator.quaternion = Quaternion::FromEuler(m_rotator.eulers, false); } const Vector3 Transform3D::GetLocalEulerAngles(bool inDegrees) const { if (!inDegrees) return m_rotator.eulers; return Vector3(m_rotator.eulers.x * MathLib::RAD2DEG, m_rotator.eulers.y * MathLib::RAD2DEG, m_rotator.eulers.z * MathLib::RAD2DEG); } void Transform3D::SetLocalRotation(const Quaternion& quat) { m_rotator.quaternion = quat; m_rotator.eulers = quat.ToEuler(false); } const Quaternion& Transform3D::GetLocalRotation() const { return m_rotator.quaternion; } Vector3 Transform3D::GetWorldPosition() const { return m_parentTransformMatrix.GetTranslation() + m_position; } Vector3 Transform3D::GetWorldScale() const { return m_parentTransformMatrix.GetScale() * m_scale; } MathLib::Vector3 Transform3D::GetLocalForward() const { return Rotate(GetLocalRotation(), MathLib::Vector3::UnitZ); } MathLib::Vector3 Transform3D::GetLocalUp() const { return Rotate(GetLocalRotation(), MathLib::Vector3::UnitY); } MathLib::Vector3 Transform3D::GetLocalRight() const { return Rotate(GetLocalRotation(), MathLib::Vector3::UnitZ); } Vector3 Transform3D::GetWorldForward() const { Vector3 combinedDirections = m_parentTransformMatrix.GetZAxis() + GetLocalForward(); combinedDirections.Normalize(); return combinedDirections; } Vector3 Transform3D::GetWorldUp() const { Vector3 combinedDirections = m_parentTransformMatrix.GetYAxis() + GetLocalUp(); combinedDirections.Normalize(); return combinedDirections; } Vector3 Transform3D::GetWorldRight() const { Vector3 combinedDirections = m_parentTransformMatrix.GetXAxis() + GetLocalRight(); combinedDirections.Normalize(); return combinedDirections; } void Transform3D::LookAt(const MathLib::Vector3& position, const MathLib::Vector3& up) { Vector3 newForward = position - m_position; newForward.Normalize(); Vector3 currentForward = GetWorldForward(); Vector3 forwardNormal = Cross(newForward, currentForward); float forwardAngle = ACos(Dot(newForward, currentForward), false); float dotOfNormalAndForward = Dot( Cross(forwardNormal, currentForward), newForward); if (dotOfNormalAndForward <= 0.0f) { forwardAngle *= -1.0f; } Quaternion angleAxis = Quaternion(forwardNormal, forwardAngle); SetLocalRotation(Concatenate(angleAxis, GetLocalRotation())); } void Transform3D::LookAt(const MathLib::Vector3& position) { LookAt(position, Vector3::UnitY); } }
25.631429
98
0.743284
[ "transform" ]
72308fefe5dc00c253a2a840ee0ea62b1f34e700
1,300
cpp
C++
competitive_programming/programming_contests/uri/contest.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
205
2018-12-01T17:49:49.000Z
2021-12-22T07:02:27.000Z
competitive_programming/programming_contests/uri/contest.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
2
2020-01-01T16:34:29.000Z
2020-04-26T19:11:13.000Z
competitive_programming/programming_contests/uri/contest.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
50
2018-11-28T20:51:36.000Z
2021-11-29T04:08:25.000Z
// https://www.urionlinejudge.com.br/judge/en/problems/view/1514 #include <iostream> #include <vector> using namespace std; int main() { int n1, n2, x; cin >> n1 >> n2; while (n1 + n2 != 0) { vector< vector<int> > matrix; vector<int> v; int num_problems = 0, solved; bool nobody_solved_all_problems = true; bool solved_by_one_person = true; bool no_problem_solved_by_everyone = true; bool solved_one_problem = true; for (int i = 0; i < n1; i++) { for (int j = 0; j < n2; j++) { cin >> x; v.push_back(x); } matrix.push_back(v); v.clear(); } for (int i = 0; i < n1; i++) { solved = 0; for (int j = 0; j < n2; j++) if (matrix[i][j] == 1) solved++; if (solved == n2) nobody_solved_all_problems = false; if (solved == 0) solved_one_problem = false; } for (int i = 0; i < n2; i++) { solved = 0; for (int j = 0; j < n1; j++) if (matrix[j][i] == 1) solved++; if (solved == n1) no_problem_solved_by_everyone = false; if (solved == 0) solved_by_one_person = false; } if (nobody_solved_all_problems) num_problems++; if (solved_by_one_person) num_problems++; if (no_problem_solved_by_everyone) num_problems++; if (solved_one_problem) num_problems++; cout << num_problems << endl; cin >> n1 >> n2; } return 0; }
22.807018
64
0.612308
[ "vector" ]
cf0de4839e8f7c6f0e20198c96a29c6dd293f8d5
772
cpp
C++
cpp/trees/0105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp
karolinyoliveira/leetcode-ebbinghaus-practice
5149e06f1c187b87e280fd58541c11d8ab8626d3
[ "MIT" ]
2
2021-05-28T03:41:39.000Z
2021-10-19T16:53:16.000Z
cpp/trees/0105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp
karolinyoliveira/leetcode-ebbinghaus-practice
5149e06f1c187b87e280fd58541c11d8ab8626d3
[ "MIT" ]
null
null
null
cpp/trees/0105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp
karolinyoliveira/leetcode-ebbinghaus-practice
5149e06f1c187b87e280fd58541c11d8ab8626d3
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> #include <structures.h> using namespace std; TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return build(preorder, inorder, 0, inorder.size() - 1); } TreeNode* build(vector<int>& preorder, vector<int>& inorder, int start, int end) { if (start > end) return nullptr; int val = preorder[0]; preorder.erase(preorder.begin()); TreeNode* root = new TreeNode(val); if (start != end) { int index = find(inorder.begin() + start, inorder.begin() + end, val) - inorder.begin(); if (index > start) root->left = build(preorder, inorder, start, index - 1); if (index < end) root->right = build(preorder, inorder, index + 1, end); } return root; }
28.592593
96
0.623057
[ "vector" ]
cf1aebbdc2299488030cd3f99837dfc5f1d2182d
25,234
cc
C++
opticalflow/src/extensions/matrixlstm_helpers.cc
96lives/matrixlstm
83332111a459dd3fbca944898fffd935faac8820
[ "Apache-2.0" ]
19
2020-08-11T09:18:28.000Z
2022-03-10T13:53:13.000Z
N-ROD/evrepr/thirdparty/matrixlstm/opticalflow/src/extensions/matrixlstm_helpers.cc
Chiaraplizz/home
18cc93a795ce132e05b886aa34565a102915b1c6
[ "MIT" ]
4
2021-01-04T11:55:50.000Z
2021-09-18T14:00:50.000Z
N-ROD/evrepr/thirdparty/matrixlstm/opticalflow/src/extensions/matrixlstm_helpers.cc
Chiaraplizz/home
18cc93a795ce132e05b886aa34565a102915b1c6
[ "MIT" ]
4
2020-09-03T07:12:55.000Z
2021-08-19T11:37:55.000Z
#include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/shape_inference.h" using namespace tensorflow; // NOLINT(build/namespaces) using shape_inference::InferenceContext; using shape_inference::ShapeHandle; using shape_inference::DimensionHandle; /********************/ /* helper functions */ /********************/ int ReadGPUIntegerScalar(const int* tensor_data); void Zero1DKernelLauncher(int* input, int N); void Zero2DKernelLauncher(int* input, int N, int M); void Zero3DKernelLauncher(float* input, int N, int M, int K); /************************/ /* n_rf_events function */ /************************/ REGISTER_OP("NRfEvents") .Input("rf_idx: int32") .Input("lengths: int32") .Attr("num_rf: int") .Output("rf_events_count: int32") .SetShapeFn([](InferenceContext* c) { // Retrieve the num_rf attribute int num_rf; TF_RETURN_IF_ERROR(c->GetAttr("num_rf", &num_rf)); // Retrieve the input batch size auto input_shape = c->input(0); auto batch_size = c->Dim(input_shape, 0); c->set_output(0, c->MakeShape({batch_size, num_rf})); return Status::OK(); }); void NRfEventsKernelLauncher(const int* rf_idx, const int* lengths, int batch_size, int event_size, int num_rf, int* rf_events_count); class NRfEventsOp : public OpKernel { private: int num_rf_; public: explicit NRfEventsOp(OpKernelConstruction* context) : OpKernel(context) { // Grab the attributes (aka, method's inputs that are fixed // after graph construction) OP_REQUIRES_OK(context, context->GetAttr("num_rf", &num_rf_)); } void Compute(OpKernelContext* context) override { // Grab the input tensors const Tensor& rf_idx_tensor = context->input(0); auto rf_idx = rf_idx_tensor.flat<int32>(); const Tensor& lengths_tensor = context->input(1); auto lengths = lengths_tensor.flat<int32>(); // Retrieve the input tensor shapes auto shape_vec = rf_idx_tensor.shape(); auto batch_size = shape_vec.dim_size(0); auto event_size = shape_vec.dim_size(1); // Create an output tensor Tensor* rf_events_count_tensor = nullptr; OP_REQUIRES_OK( context, context->allocate_output(0, TensorShape({batch_size, num_rf_}), &rf_events_count_tensor)); auto rf_events_count = rf_events_count_tensor->template flat<int32>(); // Set all the elements of the output tensor to 0 Zero2DKernelLauncher(rf_events_count.data(), batch_size, num_rf_); // Launch the kernel NRfEventsKernelLauncher(rf_idx.data(), lengths.data(), batch_size, event_size, num_rf_, rf_events_count.data()); } }; REGISTER_KERNEL_BUILDER(Name("NRfEvents").Device(DEVICE_GPU), NRfEventsOp); /*****************************/ /* group_rf_bounded function */ /*****************************/ REGISTER_OP("GroupRfBounded") .Input("features: float32") .Input("rf_ids: int32") .Input("lengths: int32") .Input("rf_offsets: int32") .Input("rf_counts: int32") .Input("new_event_size: int32") .Input("new_batch_size: int32") .Input("max_rf_events: int32") .Attr("h: int") .Attr("w: int") .Output("gr_batch_id: int32") .Output("gr_last_id: int32") .Output("gr_h: int32") .Output("gr_w: int32") .Output("groups: float32") .SetShapeFn([](InferenceContext* c) { auto feature_size = c->Dim(c->input(0), 2); ShapeHandle new_event_size_shape, new_batch_size_shape, groups_shape; TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(5, &new_event_size_shape)); TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(6, &new_batch_size_shape)); TF_RETURN_IF_ERROR(c->Concatenate(new_event_size_shape, new_batch_size_shape, &groups_shape)); TF_RETURN_IF_ERROR(c->Concatenate(groups_shape, c->MakeShape({feature_size}), &groups_shape)); c->set_output(0, new_batch_size_shape); c->set_output(1, new_batch_size_shape); c->set_output(2, new_batch_size_shape); c->set_output(3, new_batch_size_shape); c->set_output(4, groups_shape); return Status::OK(); }); void GroupRfBoundedKernelLauncher(const float* features, const int* rf_ids, const int* lengths, const int* rf_offsets, const int* rf_counts, float* groups, int* gr_last_id, int* gr_batch_id, int* gr_h, int* gr_w, const int w, const int h, const int batch_size, const int event_size, const int feature_size, const int new_batch_size, const int max_rf_events); class GroupRfBoundedOp : public OpKernel { private: int h_, w_; public: explicit GroupRfBoundedOp(OpKernelConstruction* context) : OpKernel(context) { // Grab the attributes (aka, method's inputs that are fixed // after graph construction) OP_REQUIRES_OK(context, context->GetAttr("h", &h_)); OP_REQUIRES_OK(context, context->GetAttr("w", &w_)); } void Compute(OpKernelContext* context) override { // Grab the input tensors const Tensor& features_tensor = context->input(0); auto features = features_tensor.flat<float>(); const Tensor& rf_ids_tensor = context->input(1); auto rf_ids = rf_ids_tensor.flat<int32>(); const Tensor& lengths_tensor = context->input(2); auto lengths = lengths_tensor.flat<int32>(); const Tensor& rf_offsets_tensor = context->input(3); auto rf_offsets = rf_offsets_tensor.flat<int32>(); const Tensor& rf_counts_tensor = context->input(4); auto rf_counts = rf_counts_tensor.flat<int32>(); const Tensor& new_event_size_tensor = context->input(5); const Tensor& new_batch_size_tensor = context->input(6); const Tensor& max_rf_events_tensor = context->input(7); OP_REQUIRES(context, new_event_size_tensor.dims() == 1, errors::InvalidArgument("new_event_size must be 1-D", new_event_size_tensor.shape().DebugString())); OP_REQUIRES(context, new_event_size_tensor.dim_size(0) == 1, errors::InvalidArgument("new_event_size must have 1 element", new_event_size_tensor.shape().DebugString())); OP_REQUIRES(context, new_batch_size_tensor.dims() == 1, errors::InvalidArgument("new_batch_size must be 1-D", new_batch_size_tensor.shape().DebugString())); OP_REQUIRES(context, new_batch_size_tensor.dim_size(0) == 1, errors::InvalidArgument("new_batch_size must have 1 element", new_batch_size_tensor.shape().DebugString())); OP_REQUIRES(context, max_rf_events_tensor.dims() == 1, errors::InvalidArgument("max_rf_events must be 1-D", max_rf_events_tensor.shape().DebugString())); OP_REQUIRES(context, max_rf_events_tensor.dim_size(0) == 1, errors::InvalidArgument("max_rf_events must have 1 element", max_rf_events_tensor.shape().DebugString())); int new_event_size = ReadGPUIntegerScalar( new_event_size_tensor.flat<int32>().data()); int new_batch_size = ReadGPUIntegerScalar( new_batch_size_tensor.flat<int32>().data()); int max_rf_events = ReadGPUIntegerScalar( max_rf_events_tensor.flat<int32>().data()); // Retrieve the input tensor shapes const auto shape_vec = features_tensor.shape(); const auto batch_size = shape_vec.dim_size(0); const auto event_size = shape_vec.dim_size(1); const auto feature_size = shape_vec.dim_size(2); // Create output tensors Tensor* gr_batch_id_tensor = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({new_batch_size}), &gr_batch_id_tensor)); auto gr_batch_id = gr_batch_id_tensor->template flat<int32>(); Tensor* gr_last_id_tensor = nullptr; OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape({new_batch_size}), &gr_last_id_tensor)); auto gr_last_id = gr_last_id_tensor->template flat<int32>(); Tensor* gr_h_tensor = nullptr; OP_REQUIRES_OK(context, context->allocate_output(2, TensorShape({new_batch_size}), &gr_h_tensor)); auto gr_h = gr_h_tensor->template flat<int32>(); Tensor* gr_w_tensor = nullptr; OP_REQUIRES_OK(context, context->allocate_output(3, TensorShape({new_batch_size}), &gr_w_tensor)); auto gr_w = gr_w_tensor->template flat<int32>(); Tensor* groups_tensor = nullptr; OP_REQUIRES_OK(context, context->allocate_output(4, TensorShape({new_event_size, new_batch_size, feature_size}), &groups_tensor)); auto groups = groups_tensor->template flat<float>(); // Set all the elements of the output tensors to 0 Zero1DKernelLauncher(gr_batch_id.data(), new_batch_size); Zero1DKernelLauncher(gr_last_id.data(), new_batch_size); Zero1DKernelLauncher(gr_h.data(), new_batch_size); Zero1DKernelLauncher(gr_w.data(), new_batch_size); Zero3DKernelLauncher(groups.data(), new_event_size, new_batch_size, feature_size); // Launch the kernel GroupRfBoundedKernelLauncher(features.data(), rf_ids.data(), lengths.data(), rf_offsets.data(), rf_counts.data(), groups.data(), gr_last_id.data(), gr_batch_id.data(), gr_h.data(), gr_w.data(), w_, h_, batch_size, event_size, feature_size, new_batch_size, max_rf_events); } }; REGISTER_KERNEL_BUILDER(Name("GroupRfBounded").Device(DEVICE_GPU), GroupRfBoundedOp); /***************************/ /* sparse_adj_idx function */ /***************************/ REGISTER_OP("SparseAdjIdx") .Input("rf_ev_step: int32") .Input("rf_offsets: int32") .Input("rf_lens: int32") .Input("out_num_idx: int32") .Attr("max_rf_len: int") .Output("sparse_idx: int32") .SetShapeFn([](InferenceContext* c) { // Retrieve the max_rf_len attribute int max_rf_len; TF_RETURN_IF_ERROR(c->GetAttr("max_rf_len", &max_rf_len)); // The output has shape [out_num_idx, 3] ShapeHandle out_shape; TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(3, &out_shape)); TF_RETURN_IF_ERROR(c->Concatenate(out_shape, c->MakeShape({3}), &out_shape)); c->set_output(0, out_shape); return Status::OK(); }); void SparseAdjIdxKernelLauncher(const int* rf_ev_step, const int* rf_offsets, const int* rf_lens, const int num_rf, const int max_rf_len, int* sparse_idx); class SparseAdjIdxOp : public OpKernel { private: int max_rf_len_; public: explicit SparseAdjIdxOp(OpKernelConstruction* context) : OpKernel(context) { // Grab the attributes (aka, method's inputs that are fixed // after graph construction) OP_REQUIRES_OK(context, context->GetAttr("max_rf_len", &max_rf_len_)); } void Compute(OpKernelContext* context) override { // Grab the input tensors const Tensor& rf_ev_step_tensor = context->input(0); auto rf_ev_step = rf_ev_step_tensor.flat<int>(); const Tensor& rf_offsets_tensor = context->input(1); auto rf_offsets = rf_offsets_tensor.flat<int>(); const Tensor& rf_lens_tensor = context->input(2); auto rf_lens = rf_lens_tensor.flat<int>(); const Tensor& out_num_idx_tensor = context->input(3); OP_REQUIRES(context, out_num_idx_tensor.dims() == 1, errors::InvalidArgument("out_num_idx_tensor must be 1-D", out_num_idx_tensor.shape().DebugString())); OP_REQUIRES(context, out_num_idx_tensor.dim_size(0) == 1, errors::InvalidArgument("out_num_idx_tensor must have 1 element", out_num_idx_tensor.shape().DebugString())); auto shape_vec = rf_ev_step_tensor.shape(); auto num_rf = shape_vec.dim_size(0); auto out_num_idx_cpu = ReadGPUIntegerScalar( out_num_idx_tensor.flat<int32>().data()); // Create output tensors Tensor* sparse_idx_tensor = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({out_num_idx_cpu, 3}), &sparse_idx_tensor)); auto sparse_idx = sparse_idx_tensor->template flat<int32>(); // Launch the kernel SparseAdjIdxKernelLauncher(rf_ev_step.data(), rf_offsets.data(), rf_lens.data(), num_rf, max_rf_len_, sparse_idx.data()); } }; REGISTER_KERNEL_BUILDER(Name("SparseAdjIdx").Device(DEVICE_GPU), SparseAdjIdxOp); /**************************/ /* get_centroids function */ /**************************/ REGISTER_OP("GetCentroids") .Input("events: float32") .Input("rf_ev_step: int32") .Attr("max_rf_len: int") .Output("centroids: float32") .SetShapeFn([](InferenceContext* c) { // Retrieve the max_rf_len attribute int max_rf_len; TF_RETURN_IF_ERROR(c->GetAttr("max_rf_len", &max_rf_len)); // Retrieve the input sizes // events.shape = [num_rf, max_padded_time, feature_size] auto input_shape = c->input(0); auto num_rf = c->Dim(input_shape, 0); auto feature_size = c->Dim(input_shape, 2); c->set_output(0, c->MakeShape({num_rf, max_rf_len, feature_size})); return Status::OK(); }); void GetCentroidsKernelLauncher(const float* events, const int* rf_ev_step, const int max_rf_len, const int num_rf, const int event_size, const int feature_size, float* centroids); class GetCentroidsOp : public OpKernel { private: int max_rf_len_; public: explicit GetCentroidsOp(OpKernelConstruction* context) : OpKernel(context) { // Grab the attributes (aka, method's inputs that are fixed // after graph construction) OP_REQUIRES_OK(context, context->GetAttr("max_rf_len", &max_rf_len_)); } void Compute(OpKernelContext* context) override { // Grab the input tensors const Tensor& events_tensor = context->input(0); auto events = events_tensor.flat<float>(); const Tensor& rf_ev_step_tensor = context->input(1); auto rf_ev_step = rf_ev_step_tensor.flat<int>(); auto shape_vec = events_tensor.shape(); auto num_rf = shape_vec.dim_size(0); auto event_size = shape_vec.dim_size(1); auto feature_size = shape_vec.dim_size(2); // Create output tensors Tensor* centroids_tensor = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({num_rf, max_rf_len_, feature_size}), &centroids_tensor)); auto centroids = centroids_tensor->template flat<float>(); // Launch the kernel GetCentroidsKernelLauncher(events.data(), rf_ev_step.data(), max_rf_len_, num_rf, event_size, feature_size, centroids.data()); } }; REGISTER_KERNEL_BUILDER(Name("GetCentroids").Device(DEVICE_GPU), GetCentroidsOp); /******************************/ /* n_interval_events function */ /******************************/ REGISTER_OP("NIntervalEvents") .Input("ts_percent: float32") .Input("lengths: int32") .Attr("n_intervals: int") .Output("interval_events_count: int32") .SetShapeFn([](InferenceContext* c) { // Retrieve the num_rf attribute int n_intervals; TF_RETURN_IF_ERROR(c->GetAttr("n_intervals", &n_intervals)); // Retrieve the input batch size auto input_shape = c->input(0); auto batch_size = c->Dim(input_shape, 0); c->set_output(0, c->MakeShape({batch_size, n_intervals})); return Status::OK(); }); void NIntervalEventsKernelLauncher(const float* ts_percent, const int* lengths, int batch_size, int event_size, int n_intervals, int* interval_events_count); class NIntervalEventsOp : public OpKernel { private: int n_intervals_; public: explicit NIntervalEventsOp(OpKernelConstruction* context) : OpKernel(context) { // Grab the attributes (aka, method's inputs that are fixed // after graph construction) OP_REQUIRES_OK(context, context->GetAttr("n_intervals", &n_intervals_)); } void Compute(OpKernelContext* context) override { // Grab the input tensors const Tensor& ts_percent_tensor = context->input(0); auto ts_percent = ts_percent_tensor.flat<float>(); const Tensor& lengths_tensor = context->input(1); auto lengths = lengths_tensor.flat<int32>(); // Retrieve the input tensor shapes auto shape_vec = ts_percent_tensor.shape(); auto batch_size = shape_vec.dim_size(0); auto event_size = shape_vec.dim_size(1); // Create an output tensor Tensor* interval_events_count_tensor = nullptr; OP_REQUIRES_OK( context, context->allocate_output(0, TensorShape({batch_size, n_intervals_}), &interval_events_count_tensor)); auto interval_events_count = interval_events_count_tensor->template flat<int32>(); // Set all the elements of the output tensor to 0 Zero2DKernelLauncher(interval_events_count.data(), batch_size, n_intervals_); // Launch the kernel NIntervalEventsKernelLauncher(ts_percent.data(), lengths.data(), batch_size, event_size, n_intervals_, interval_events_count.data()); } }; REGISTER_KERNEL_BUILDER(Name("NIntervalEvents").Device(DEVICE_GPU), NIntervalEventsOp); /*******************************/ /* intervals_to_batch function */ /*******************************/ REGISTER_OP("IntervalsToBatch") .Input("events: float32") .Input("n_interval_events: int32") .Input("new_event_size: int32") .Output("interval_events: float32") .SetShapeFn([](InferenceContext* c) { // Retrieve the input batch size auto events_shape = c->input(0); auto batch_size = c->Dim(events_shape, 0); auto features_size = c->Dim(events_shape, 2); auto intervals_shape = c->input(1); auto n_intervals = c->Dim(intervals_shape, 1); DimensionHandle new_batch_size_dim; ShapeHandle new_event_size_shape, new_events_shape; TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(2, &new_event_size_shape)); TF_RETURN_IF_ERROR(c->Multiply(n_intervals, batch_size, &new_batch_size_dim)); TF_RETURN_IF_ERROR(c->Concatenate(c->MakeShape({new_batch_size_dim}), new_event_size_shape, &new_events_shape)); TF_RETURN_IF_ERROR(c->Concatenate(new_events_shape, c->MakeShape({features_size}), &new_events_shape)); // shape: [batch_size * n_intervals, new_event_size, features_size] c->set_output(0, new_events_shape); return Status::OK(); }); void IntervalsToBatchKernelLauncher(const float* events, const int* n_interval_events, int batch_size, int event_size, int feature_size, int n_intervals, int new_event_size, float* new_events); class IntervalsToBatchOp : public OpKernel { public: explicit IntervalsToBatchOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { // Grab the input tensors const Tensor& events_tensor = context->input(0); auto events = events_tensor.flat<float>(); const Tensor& n_interval_events_tensor = context->input(1); auto n_interval_events = n_interval_events_tensor.flat<int32>(); const Tensor& new_event_size_tensor = context->input(2); // Retrieve the input tensor shapes int new_event_size = ReadGPUIntegerScalar( new_event_size_tensor.flat<int32>().data()); auto events_shape = events_tensor.shape(); auto batch_size = events_shape.dim_size(0); auto event_size = events_shape.dim_size(1); auto feature_size = events_shape.dim_size(2); auto intervals_shape = n_interval_events_tensor.shape(); auto n_intervals = intervals_shape.dim_size(1); // Create an output tensor Tensor* new_events_tensor = nullptr; OP_REQUIRES_OK( context, context->allocate_output(0, TensorShape({batch_size * n_intervals, new_event_size, feature_size}), &new_events_tensor)); auto new_events = new_events_tensor->template flat<float>(); // Set all the elements of the output tensor to 0 Zero3DKernelLauncher(new_events.data(), batch_size * n_intervals, new_event_size, feature_size); // Launch the kernel IntervalsToBatchKernelLauncher(events.data(), n_interval_events.data(), batch_size, event_size, feature_size, n_intervals, new_event_size, new_events.data()); } }; REGISTER_KERNEL_BUILDER(Name("IntervalsToBatch").Device(DEVICE_GPU), IntervalsToBatchOp);
44.038394
95
0.553816
[ "shape" ]
cf2afb88635f62e4fd96d31ce81247a432000ec6
10,418
cpp
C++
src/CPU/10_ts_decomposition/src/main.cpp
csrhau/DiffusionOptimisationStudy
77fb718123d18c8358ccab4e958382b760901d55
[ "MIT" ]
null
null
null
src/CPU/10_ts_decomposition/src/main.cpp
csrhau/DiffusionOptimisationStudy
77fb718123d18c8358ccab4e958382b760901d55
[ "MIT" ]
null
null
null
src/CPU/10_ts_decomposition/src/main.cpp
csrhau/DiffusionOptimisationStudy
77fb718123d18c8358ccab4e958382b760901d55
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <chrono> #include <numeric> #define TIMESTEPS 600 #define STENCIL_RADIUS 1 #define IMAX 800 #define JMAX 800 #define KMAX 800 #define HOTCORNER_IMAX 25 #define HOTCORNER_JMAX 25 #define HOTCORNER_KMAX 25 #define INDEX3D(i, j, k) ((((k) * (JMAX) * (IMAX)) + ((j) * (IMAX)) + (i))) const double nu = 0.05; const double sigma = 0.25; const double width = 2; const double height = 2; const double dx = width / (IMAX-1); const double dy = height / (JMAX-1); const double dz = height / (KMAX-1); const double dt = sigma * dx * dy * dz / nu; const int t_threshold = 20; const int i_threshold = 10; const int j_threshold = 10; const int k_threshold = 10; std::vector<double> talpha(IMAX * JMAX * KMAX); std::vector<double> tbeta(IMAX * JMAX * KMAX); double *state[2] = {talpha.data(), tbeta.data()}; #define STATE_NOW (state[ts &1]) #define STATE_NEXT (state[(ts + 1) &1]) #define STATE_INITIAL talpha #define STATE_FINAL (state[(TIMESTEPS)&1]) inline void BaseTrapezoid(int t0, int t1, int i0, int del_i0, int i1, int del_i1, int j0, int del_j0, int j1, int del_j1, int k0, int del_k0, int k1, int del_k1) { for (int ts = t0; ts < t1; ++ts) { for (int k = k0; k < k1; ++k) { for (int j = j0; j < j1; ++j) { for (int i = i0; i < i1; ++i) { // Diffusion STATE_NEXT[INDEX3D(i, j, k)] = STATE_NOW[INDEX3D(i, j, k)] + (nu * dt / (dx * dx)) * (STATE_NOW[INDEX3D(i-1, j, k)]-2.0* STATE_NOW[INDEX3D(i, j, k)] + STATE_NOW[INDEX3D(i+1, j, k)]) + (nu * dt / (dy * dy)) * (STATE_NOW[INDEX3D(i, j-1, k)]-2.0* STATE_NOW[INDEX3D(i, j, k)] + STATE_NOW[INDEX3D(i, j+1, k)]) + (nu * dt / (dz * dz)) * (STATE_NOW[INDEX3D(i, j, k-1)]-2.0* STATE_NOW[INDEX3D(i, j, k)] + STATE_NOW[INDEX3D(i, j, k+1)]); // Reflective Boundary Conditions if (i==1) { STATE_NEXT[INDEX3D(i-1, j, k)] = STATE_NEXT[INDEX3D(i, j, k)]; } else if (i == IMAX - 2) { STATE_NEXT[INDEX3D(i+1, j, k)] = STATE_NEXT[INDEX3D(i, j, k)]; } if (j == 1) { STATE_NEXT[INDEX3D(i, j-1, k)] = STATE_NEXT[INDEX3D(i, j, k)]; } else if (j == JMAX - 2) { STATE_NEXT[INDEX3D(i, j+1, k)] = STATE_NEXT[INDEX3D(i, j, k)]; } if (k == 1) { STATE_NEXT[INDEX3D(i, j, k-1)] = STATE_NEXT[INDEX3D(i, j, k)]; } else if (k == KMAX - 2) { STATE_NEXT[INDEX3D(i, j, k+1)] = STATE_NEXT[INDEX3D(i, j, k)]; } } } } i0 += del_i0; i1 += del_i1; j0 += del_j0; j1 += del_j1; k0 += del_k0; k1 += del_k1; } } inline void RecursiveTrapezoid(int t0, int t1, int i0, int del_i0, int i1, int del_i1, int j0, int del_j0, int j1, int del_j1, int k0, int del_k0, int k1, int del_k1) { int t_span = t1 - t0; int i_span = i1 - i0; int j_span = j1 - j0; int k_span = k1 - k0; int split_threshold = 2 * STENCIL_RADIUS * t_span * 2; if (t_span > 1) { // Trapezoid slope becomes meaningless over a single timestep if (i_span > i_threshold && i_span >= j_span && i_span >= k_span && i_span > split_threshold) { int half_i_span = i_span/2; // Core trapezoids (x2) RecursiveTrapezoid(t0, t1, i0, STENCIL_RADIUS, i0 + half_i_span, -STENCIL_RADIUS, j0, del_j0, j1, del_j1, k0, del_k0, k1, del_k1); RecursiveTrapezoid(t0, t1, i0 + half_i_span, STENCIL_RADIUS, i1, -STENCIL_RADIUS, j0, del_j0, j1, del_j1, k0, del_k0, k1, del_k1); // Filler trapezoids (x3, possibly empty) RecursiveTrapezoid(t0, t1, i0, del_i0, i0, STENCIL_RADIUS, j0, del_j0, j1, del_j1, k0, del_k0, k1, del_k1); RecursiveTrapezoid(t0, t1, i0+half_i_span, -STENCIL_RADIUS, i0+half_i_span, STENCIL_RADIUS, j0, del_j0, j1, del_j1, k0, del_k0, k1, del_k1); RecursiveTrapezoid(t0, t1, i1, -STENCIL_RADIUS, i1, del_i1, j0, del_j0, j1, del_j1, k0, del_k0, k1, del_k1); return; } if (j_span > j_threshold && j_span >= k_span && j_span > split_threshold) { int half_j_span = j_span/2; // Core trapezoids (x2) RecursiveTrapezoid(t0, t1, i0, del_i0, i1, del_i1, j0, STENCIL_RADIUS, j0 + half_j_span, -STENCIL_RADIUS, k0, del_k0, k1, del_k1); RecursiveTrapezoid(t0, t1, i0, del_i0, i1, del_i1, j0 + half_j_span, STENCIL_RADIUS, j1, -STENCIL_RADIUS, k0, del_k0, k1, del_k1); // Filler trapezoids (x3, possibly empty) RecursiveTrapezoid(t0, t1, i0, del_i0, i1, del_i1, j0, del_j0, j0, STENCIL_RADIUS, k0, del_k0, k1, del_k1); RecursiveTrapezoid(t0, t1, i0, del_i0, i1, del_i1, j0+half_j_span, -STENCIL_RADIUS, j0+half_j_span, STENCIL_RADIUS, k0, del_k0, k1, del_k1); RecursiveTrapezoid(t0, t1, i0, del_i0, i1, del_i1, j1, -STENCIL_RADIUS, j1, del_j1, k0, del_k0, k1, del_k1); return; } if (k_span > k_threshold && k_span > split_threshold) { int half_k_span = k_span/2; // Core trapezoids (x2) RecursiveTrapezoid(t0, t1, i0, del_i0, i1, del_i1, j0, del_j0, j1, del_j1, k0, STENCIL_RADIUS, k0 + half_k_span, -STENCIL_RADIUS); RecursiveTrapezoid(t0, t1, i0, del_i0, i1, del_i1, j0, del_j0, j1, del_j1, k0 + half_k_span, STENCIL_RADIUS, k1, -STENCIL_RADIUS); // Filler trapezoids (x3, possibly empty) RecursiveTrapezoid(t0, t1, i0, del_i0, i1, del_i1, j0, del_j0, j1, del_j1, k0, del_k0, k0, STENCIL_RADIUS); RecursiveTrapezoid(t0, t1, i0, del_i0, i1, del_i1, j0, del_j0, j1, del_j1, k0+half_k_span, -STENCIL_RADIUS, k0+half_k_span, STENCIL_RADIUS); RecursiveTrapezoid(t0, t1, i0, del_i0, i1, del_i1, j0, del_j0, j1, del_j1, k1, -STENCIL_RADIUS, k1, del_k1); return; } if (t_span > t_threshold) { int half_t_span = t_span / 2; RecursiveTrapezoid(t0, t0 + half_t_span, i0, del_i0, i1, del_i1, j0, del_j0, j1, del_j1, k0, del_k0, k1, del_k1); RecursiveTrapezoid(t0 + half_t_span, t1, i0 + del_i0 * half_t_span , del_i0, i1 + del_i1 * half_t_span, del_i1, j0 + del_j0 * half_t_span , del_j0, j1 + del_j1 * half_t_span, del_j1, k0 + del_k0 * half_t_span , del_k0, k1 + del_k1 * half_t_span, del_k1); return; } } BaseTrapezoid(t0, t1, i0, del_i0, i1, del_i1, j0, del_j0, j1, del_j1, k0, del_k0, k1, del_k1); } int main() { for (int k = 0; k < KMAX; ++k) { for (int j = 0; j < JMAX; ++j) { for (int i = 0; i < IMAX; ++i) { if (i < HOTCORNER_IMAX && j < HOTCORNER_JMAX && k < HOTCORNER_KMAX) { STATE_INITIAL[INDEX3D(i, j, k)] = 2.0; } else { STATE_INITIAL[INDEX3D(i, j, k)] = 1.0; } } } } std::chrono::steady_clock::time_point t_start = std::chrono::steady_clock::now(); // Calculate initial (inner) temperature const unsigned long all_cells = (IMAX-2) * (JMAX-2) * (KMAX-2); const unsigned long hot_cells = (HOTCORNER_IMAX-1) * (HOTCORNER_JMAX-1) * (HOTCORNER_KMAX-1); double expected = hot_cells * 2.0 + (all_cells-hot_cells) * 1.0; double temperature = 0.0; for (int k = 1; k < KMAX-1; ++k) { for (int j = 1; j < JMAX-1; ++j) { temperature = std::accumulate(&STATE_INITIAL[INDEX3D(1, j, k)], &STATE_INITIAL[INDEX3D(IMAX-1, j, k)], temperature); } } std::cout << "Initial Temperature: " << temperature << " Expected: " << expected << std::endl; std::chrono::steady_clock::time_point t_sim_start = std::chrono::steady_clock::now(); RecursiveTrapezoid(0, TIMESTEPS, 1, 0, IMAX-1, 0, 1, 0, JMAX-1, 0, 1, 0, KMAX-1, 0); std::chrono::steady_clock::time_point t_sim_end = std::chrono::steady_clock::now(); temperature = 0.0; for (int k = 1; k < KMAX-1; ++k) { for (int j = 1; j < JMAX-1; ++j) { temperature = std::accumulate(&STATE_FINAL[INDEX3D(1, j, k)], &STATE_FINAL[INDEX3D(IMAX-1, j, k)], temperature); } } std::chrono::steady_clock::time_point t_end = std::chrono::steady_clock::now(); std::chrono::duration<double> runtime = std::chrono::duration_cast<std::chrono::duration<double>>(t_end - t_start); std::chrono::duration<double> sim_runtime = std::chrono::duration_cast<std::chrono::duration<double>>(t_sim_end-t_sim_start); std::cout << "Final Temperature: " << temperature << " Expected: " << expected << std::endl; std::cout << "Time Elapsed (simulation): " << sim_runtime.count() << "s" << std::endl; std::cout << "Time Elapsed (total): " << runtime.count() << "s" << std::endl; return EXIT_SUCCESS; }
41.839357
192
0.498752
[ "vector" ]
cf2ef8ba667b232c559e0cd5df73a13ec072c316
855
hpp
C++
src/dep_win/watcher.hpp
degarashi/sprinkler
afc6301ae2c7185f514148100da63dcef94d7f00
[ "MIT" ]
null
null
null
src/dep_win/watcher.hpp
degarashi/sprinkler
afc6301ae2c7185f514148100da63dcef94d7f00
[ "MIT" ]
null
null
null
src/dep_win/watcher.hpp
degarashi/sprinkler
afc6301ae2c7185f514148100da63dcef94d7f00
[ "MIT" ]
null
null
null
#pragma once #include "../domain.hpp" #include <QRect> #include <QObject> #include <unordered_set> #include <windows.h> #include <QModelIndex> Q_DECLARE_METATYPE(HWND) class QHBoxLayout; class QStandardItemModel; namespace dg { class Watcher : public QObject { Q_OBJECT public: Watcher(QObject* parent=nullptr); QAbstractItemModel* model() const noexcept; void startLoop(); void makeArea(QHBoxLayout* addArea); public slots: void draggedPosition(QPoint p); private slots: void _removeRow(QModelIndex idx, int first, int last); void _refreshWindowRect(); signals: void onWatchedRectChanged(const dg::DomainV& rect); private: using HWNDSet = std::unordered_set<HWND>; HWNDSet _wset; // Watcherクラスからのみアクセス QStandardItemModel* _model; void _makeModelFromWSet(); bool _cursorOnQtWindow(); }; }
20.853659
57
0.726316
[ "model" ]
cf332ce983b7b7d2eeb61a67f3495eb75f7c1101
3,068
cc
C++
leetcode/17_4sum.cc
norlanliu/algorithm
1684db2631f259b4de567164b3ee866351e5b1b6
[ "MIT" ]
null
null
null
leetcode/17_4sum.cc
norlanliu/algorithm
1684db2631f259b4de567164b3ee866351e5b1b6
[ "MIT" ]
null
null
null
leetcode/17_4sum.cc
norlanliu/algorithm
1684db2631f259b4de567164b3ee866351e5b1b6
[ "MIT" ]
null
null
null
/* * ===================================================================================== * * Filename: 15_3sum.cc * * Description: * * Version: 1.0 * Created: 03/11/2015 11:03:41 AM * Revision: none * Compiler: gcc * * Author: (Qi Liu), liuqi.edward@gmail.com * Organization: antq.com * * ===================================================================================== */ #include<iostream> #include<unordered_map> #include<vector> #include<algorithm> using namespace std; class Solution{ public: vector<vector<int> > fourSum(vector<int> &num, int target){ if(num.size() < 4) return vector<vector<int>>(); unsigned int i, j; int k; vector<vector<int> > tuples; vector<int> tuple(4); unordered_map<int, vector<unsigned int> > map; size_t size = num.size() - 1; std::sort(num.begin(), num.end()); for(i = 0; i < size; ++i) { while((i+2) <= size && num[i+2] == num[i]) i++; for(j = i + 1; j < size; ++j) { if(num[j+1] != num[j]) { k = num[i]+num[j]; map[k].push_back(i); } if(num[i+1] == num[i]) i++; } k = num[i]+num[j]; map[k].push_back(i); while(num[i+1] == num[i]) i++; } size -= 1; for(i = 0; i < size; ++i) { for(j = i + 1; j < size; ++j) { k = target - (num[i] + num[j]); vector<unsigned int>& vk = map[k]; if(vk.size() > 0) { tuple[0] = num[i]; tuple[1] = num[j]; for(auto it : vk) { if(it > j) { tuple[2] = num[it]; tuple[3] = k - tuple[2]; tuples.push_back(tuple); } } } while(num[j+1] == num[j]) j++; } while(num[i+1] == num[i]) i++; } return tuples; } vector<vector<int> > fourSumTwoPointers(vector<int> &num, int target){ if(num.size() < 4) return vector<vector<int>>(); unsigned int i, j; int k, tmp, head, tail; vector<vector<int> > tuples; vector<int> tuple(4); size_t size = num.size() - 1; std::sort(num.begin(), num.end()); for(i = 0; i < size; ++i) { for(j = i + 1; j < size; ++j) { k = num[i] + num[j]; head = j + 1; tail = size; while(head < tail) { tmp = k + num[head] + num[tail]; if(tmp < target) head++; else if(tmp > target) tail--; else { tuple[0] = num[i]; tuple[1] = num[j]; tuple[2] = num[head]; tuple[3] = num[tail]; tuples.push_back(tuple); while(head < tail && num[head] == tuple[2]) head++; while(head < tail && num[tail] == tuple[3]) tail--; } } while(num[j+1] == num[j]) j++; } while(num[i+1] == num[i]) i++; } return tuples; } }; int main(){ vector<int> num = {-1, 0, 1, 0, -2, 2}; Solution sln; vector<vector<int> > ans = sln.fourSum(num, 0); for(auto out : ans) { for(auto inside : out) { cout << inside << " "; } cout<<endl; } return 0; }
20.453333
88
0.440678
[ "vector" ]
cf33323e6113026c037803879811c129feb66263
12,112
cpp
C++
gilbreth_gazebo/src/conveyor_spawner.cpp
ben-greenberg/gilbreth
887d22916ed9ca68f9d907cec77fbe81b95e8b6f
[ "BSD-3-Clause" ]
null
null
null
gilbreth_gazebo/src/conveyor_spawner.cpp
ben-greenberg/gilbreth
887d22916ed9ca68f9d907cec77fbe81b95e8b6f
[ "BSD-3-Clause" ]
null
null
null
gilbreth_gazebo/src/conveyor_spawner.cpp
ben-greenberg/gilbreth
887d22916ed9ca68f9d907cec77fbe81b95e8b6f
[ "BSD-3-Clause" ]
null
null
null
#include <boost/filesystem.hpp> #include <gazebo_msgs/SpawnModel.h> #include <gazebo_msgs/SetModelState.h> #include "gilbreth_gazebo/conveyor_spawner.h" #include "gilbreth_gazebo/urdf_creator.h" #include <random> #include <ros/package.h> #include <XmlRpcException.h> #include <tf/transform_datatypes.h> #include <boost/format.hpp> const static std::string GAZEBO_SPAWN_SERVICE = "gazebo/spawn_urdf_model"; const static std::string START_SPAWN_SERVICE = "start_spawn"; const static std::string STOP_SPAWN_SERVICE = "stop_spawn"; const static std::string SPAWNED_PART_TOPIC = "spawned_part"; static const std::string GAZEBO_SET_MODEL_STATE_SERVICE = "gazebo/set_model_state"; static const std::string GAZEBO_DISPOSED_MODELS_TOPIC = "gazebo/disposed_models"; const static double SRV_TIMEOUT = 10.0f; std::string generateObjectName(int id) { return "object_" + std::to_string(id); } namespace gilbreth { namespace simulation { ConveyorSpawner::ConveyorSpawner(ros::NodeHandle& nh) : nh_(nh) { } bool ConveyorSpawner::init(XmlRpc::XmlRpcValue& p) { // Load the parameters if(!loadSpawnParameters(p, params_)) { return false; } // Connect to ROS topics/services/actions/etc. if(!connectToROS()) { return false; } // Initialize the randomization engine srand(params_.randomization_seed); start_server_ = nh_.advertiseService(START_SPAWN_SERVICE, &ConveyorSpawner::start, this); stop_server_ = nh_.advertiseService(STOP_SPAWN_SERVICE, &ConveyorSpawner::stop, this); timer_ = nh_.createTimer(ros::Duration(params_.spawn_period), &ConveyorSpawner::spawnObjectTimerCb, this, false, false); pub_ = nh_.advertise<std_msgs::Header>(SPAWNED_PART_TOPIC, 10, true); return true; } void ConveyorSpawner::run() { ros::spin(); } bool ConveyorSpawner::loadSpawnParameters(const XmlRpc::XmlRpcValue& p, SpawnParameters& spawn_params) const { XmlRpc::XmlRpcValue params = p; try { // Get the top-level parameters // Get the reference frame XmlRpc::XmlRpcValue& frame = params["reference_frame"]; spawn_params.reference_frame = static_cast<std::string>(frame); // Get the spawn timing XmlRpc::XmlRpcValue& period = params["spawn_period"]; spawn_params.spawn_period = static_cast<double>(period); // Get the randomization seed XmlRpc::XmlRpcValue& seed = params["randomization_seed"]; spawn_params.randomization_seed = static_cast<int>(seed); // Get max objects XmlRpc::XmlRpcValue& max_objects = params["max_objects"]; spawn_params.max_objects = static_cast<int>(max_objects); // Get the spawned objects XmlRpc::XmlRpcValue& objects = params["objects"]; for(int i = 0; i < objects.size(); ++i) { XmlRpc::XmlRpcValue& obj = objects[i]; ObjectParameters object_params; if(!loadObjectParameters(obj, object_params)) { return false; } // Add the object's parameters to the list spawn_params.objects.push_back(object_params); } } catch(XmlRpc::XmlRpcException& ex) { ROS_ERROR("Exception in loading spawner parameters:\n%s'", ex.getMessage().c_str()); return false; } return true; } bool ConveyorSpawner::loadObjectParameters(const XmlRpc::XmlRpcValue& object, ObjectParameters& object_params) const { XmlRpc::XmlRpcValue obj = object; try { // Get the name XmlRpc::XmlRpcValue& name = obj["name"]; object_params.name = static_cast<std::string>(name); // Get the relative URDF path file XmlRpc::XmlRpcValue& filepath = obj["mesh_resource"]; object_params.mesh_resource = static_cast<std::string>(filepath); // Get the initial pose XmlRpc::XmlRpcValue& initial_pose = obj["initial_pose"]; XmlRpc::XmlRpcValue& position = initial_pose["position"]; object_params.initial_pose.position.x = static_cast<double>(position[0]); object_params.initial_pose.position.y = static_cast<double>(position[1]); object_params.initial_pose.position.z = static_cast<double>(position[2]); XmlRpc::XmlRpcValue& orientation = initial_pose["orientation"]; object_params.initial_pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(static_cast<double>(orientation[0]), static_cast<double>(orientation[1]), static_cast<double>(orientation[2])); // Get the lateral placement variance XmlRpc::XmlRpcValue& lpv = obj["lateral_placement_variance"]; object_params.lateral_placement_variance = static_cast<double>(lpv); // Get the yaw placement_variance XmlRpc::XmlRpcValue& ypv = obj["yaw_placement_variance"]; object_params.yaw_placement_variance = static_cast<double>(ypv) * M_PI / 180.0f; // Get the spawn timing variance XmlRpc::XmlRpcValue& stv = obj["spawn_timing_variance"]; object_params.spawn_timing_variance = static_cast<double>(stv); } catch(const XmlRpc::XmlRpcException& ex) { ROS_ERROR("Exception in loading object parameters:\n%s", ex.getMessage().c_str()); return false; } return true; } bool ConveyorSpawner::connectToROS() { spawn_client_ = nh_.serviceClient<gazebo_msgs::SpawnModel>(GAZEBO_SPAWN_SERVICE); if(!spawn_client_.waitForExistence(ros::Duration(SRV_TIMEOUT))) { ROS_ERROR("Timeout waiting for '%s' service", spawn_client_.getService().c_str()); return false; } set_state_client_ = nh_.serviceClient<gazebo_msgs::SetModelState>(GAZEBO_SET_MODEL_STATE_SERVICE); if(!set_state_client_.waitForExistence(ros::Duration(SRV_TIMEOUT))) { ROS_ERROR("Timeout waiting for '%s' service", set_state_client_.getService().c_str()); return false; } disposed_objs_subs_ = nh_.subscribe<gazebo_msgs::ModelStates>(GAZEBO_DISPOSED_MODELS_TOPIC,1, &ConveyorSpawner::disposedObjectsCallback,this); return true; } bool ConveyorSpawner::start(std_srvs::EmptyRequest& req, std_srvs::EmptyResponse& res) { ROS_INFO("Starting conveyor spawner..."); timer_.start(); return true; } bool ConveyorSpawner::stop(std_srvs::EmptyRequest& req, std_srvs::EmptyResponse& res) { ROS_INFO("Stopping conveyor spawner..."); timer_.stop(); return true; } void ConveyorSpawner::spawnObjectTimerCb(const ros::TimerEvent& e) { if(object_counter_ < params_.max_objects) { spawnObject(); } else { recirculateObject(); } } void ConveyorSpawner::spawnObject() { ++object_counter_; // Randomize the model to be spawned int idx = rand() % params_.objects.size(); auto obj = params_.objects.begin(); std::advance(obj, idx); // Populate the spawn service request gazebo_msgs::SpawnModel srv; srv.request.reference_frame = params_.reference_frame; srv.request.robot_namespace = "gilbreth"; srv.request.model_xml = createObjectURDF(obj->name, obj->mesh_resource); srv.request.initial_pose = obj->initial_pose; srv.request.model_name = generateObjectName(object_counter_); // Randomize the object's lateral spawn position // Create a new pseudo-random number between 0 and 1 double r_lpv = static_cast<double>(rand()) / static_cast<double>(RAND_MAX); double& lpv = obj->lateral_placement_variance; double lpv_delta = -lpv + 2.0*r_lpv*lpv; srv.request.initial_pose.position.y += lpv_delta; // Randomize the object's spawn yaw angle // Create a new psuedo-random number between 0 and 1 double r_ypv = static_cast<double>(rand()) / static_cast<double>(RAND_MAX); double& ypv = obj->yaw_placement_variance; double ypv_delta = -ypv + 2.0*r_ypv*ypv; tf::Quaternion q; tf::quaternionMsgToTF(srv.request.initial_pose.orientation, q); tf::Quaternion dq = tf::createQuaternionFromRPY(0.0, 0.0, ypv_delta); q *= dq; tf::quaternionTFToMsg(q, srv.request.initial_pose.orientation); // Randomize the delay in spawning the object // Create a new psuedo-random number between 0 and 1 double r_tv = static_cast<double>(rand()) / static_cast<double>(RAND_MAX); ros::Duration time_var (r_tv * obj->spawn_timing_variance); time_var.sleep(); // Call the spawn service if(!spawn_client_.call(srv)) { ROS_ERROR("Failed to call '%s' service", spawn_client_.getService().c_str()); --object_counter_; return; } else { if(!srv.response.success) { ROS_ERROR("%s", static_cast<std::string>(srv.response.status_message).c_str()); --object_counter_; return; } else { // Publish which part was just spawned onto the conveyor std_msgs::Header msg; msg.frame_id = obj->name; msg.stamp = ros::Time::now(); msg.seq = object_counter_; pub_.publish(msg); } } ROS_DEBUG_STREAM(boost::str(boost::format("Spawned new object '%1%' with id '%2%'") % obj->name % srv.request.model_name)); // storing model name for tracking purposes spawned_objects_map_.insert(std::make_pair(srv.request.model_name, obj->name)); } void ConveyorSpawner::recirculateObject() { if(inactive_objects_ids_.empty()) { return; // no objects to recirculate yet } // randomize object choice from inactive list int idx = rand() % inactive_objects_ids_.size(); auto obj_id = inactive_objects_ids_.begin(); std::advance(obj_id,idx); // locating object from list std::string obj_name = spawned_objects_map_[*obj_id]; std::vector<ObjectParameters>::iterator obj = std::find_if(params_.objects.begin(), params_.objects.end(), [&obj_name](const ObjectParameters& obj){ return obj_name == obj.name; }); // create the set state request gazebo_msgs::SetModelState srv; gazebo_msgs::ModelState& ms = srv.request.model_state; ms.model_name = *obj_id; ms.pose = obj->initial_pose; ms.reference_frame = params_.reference_frame; tf::vector3TFToMsg(tf::Vector3(0,0,0),ms.twist.linear); tf::vector3TFToMsg(tf::Vector3(0,0,0),ms.twist.angular); // randomizing the y placement (along conveyor width) double r_lpv = static_cast<double>(rand()) / static_cast<double>(RAND_MAX); double& lpv = obj->lateral_placement_variance; double lpv_delta = -lpv + 2.0*r_lpv*lpv; ms.pose.position.y += lpv_delta; // Randomize the object's yaw angle double r_ypv = static_cast<double>(rand()) / static_cast<double>(RAND_MAX); double& ypv = obj->yaw_placement_variance; double ypv_delta = -ypv + 2.0*r_ypv*ypv; tf::Quaternion q; tf::quaternionMsgToTF(ms.pose.orientation, q); tf::Quaternion dq = tf::createQuaternionFromRPY(0.0, 0.0, ypv_delta); q *= dq; tf::quaternionTFToMsg(q, ms.pose.orientation); // Randomize the request call delay double r_tv = static_cast<double>(rand()) / static_cast<double>(RAND_MAX); ros::Duration time_var (r_tv * obj->spawn_timing_variance); time_var.sleep(); // call the service if(!set_state_client_.call(srv)) { ROS_ERROR_STREAM(boost::str(boost::format("Failed to call the '%1%' service") % set_state_client_.getService())); return; } if(!srv.response.success) { ROS_ERROR("The 'set_state' call failed"); return; } ROS_DEBUG_STREAM(boost::str(boost::format("Recirculated object '%1%' with id '%2%'") % obj->name % *obj_id)); // Publish which part was just recycled onto the conveyor std_msgs::Header msg; msg.frame_id = obj->name; msg.stamp = ros::Time::now(); pub_.publish(msg); inactive_objects_ids_.erase(obj_id); } void ConveyorSpawner::disposedObjectsCallback(const gazebo_msgs::ModelStatesConstPtr& msg) { for(const auto& n: msg->name) { if(spawned_objects_map_.count(n)) { inactive_objects_ids_.push_back(n); } else { ROS_WARN_STREAM(boost::str(boost::format("An unknown object '%1%' was received, ignoring ...") % n)); } } } } // namespace simulation } // namespace gilbreth
31.957784
125
0.688491
[ "object", "vector", "model" ]
cf35213a7407843fdca1605bce77d938c52e5bc2
2,760
hpp
C++
examples/session_view.hpp
kamyu104/libtorrent-1
87ec445943324a243be2b9499b74dc0983a42af9
[ "BSL-1.0", "BSD-3-Clause" ]
9
2019-11-05T16:47:12.000Z
2022-03-05T15:21:25.000Z
examples/session_view.hpp
kamyu104/libtorrent-1
87ec445943324a243be2b9499b74dc0983a42af9
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
examples/session_view.hpp
kamyu104/libtorrent-1
87ec445943324a243be2b9499b74dc0983a42af9
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2014, 2016-2020, Arvid Norberg Copyright (c) 2016, Alden Torres All rights reserved. You may use, distribute and modify this code under the terms of the BSD license, see LICENSE file. */ #ifndef SESSION_VIEW_HPP_ #define SESSION_VIEW_HPP_ #include <cstdint> #include <vector> #include "libtorrent/session_stats.hpp" #include "libtorrent/span.hpp" #include "libtorrent/time.hpp" struct session_view { session_view(); void set_pos(int pos); void set_width(int width); int pos() const; int height() const; void render(); void update_counters(lt::span<std::int64_t const> stats_counters, lt::clock_type::time_point t); private: int m_position = 0; int m_width = 80; // there are two sets of counters. the current one and the last one. This // is used to calculate rates std::vector<std::int64_t> m_cnt[2]; std::int64_t value(int idx) const; std::int64_t prev_value(int idx) const; // the timestamps of the counters in m_cnt[0] and m_cnt[1] // respectively. lt::clock_type::time_point m_timestamp[2]; int const m_queued_bytes_idx = lt::find_metric_idx("disk.queued_write_bytes"); int const m_wasted_bytes_idx = lt::find_metric_idx("net.recv_redundant_bytes"); int const m_failed_bytes_idx = lt::find_metric_idx("net.recv_failed_bytes"); int const m_num_peers_idx = lt::find_metric_idx("peer.num_peers_connected"); int const m_recv_idx = lt::find_metric_idx("net.recv_bytes"); int const m_sent_idx = lt::find_metric_idx("net.sent_bytes"); int const m_unchoked_idx = lt::find_metric_idx("peer.num_peers_up_unchoked"); int const m_unchoke_slots_idx = lt::find_metric_idx("ses.num_unchoke_slots"); int const m_limiter_up_queue_idx = lt::find_metric_idx("net.limiter_up_queue"); int const m_limiter_down_queue_idx = lt::find_metric_idx("net.limiter_down_queue"); int const m_queued_writes_idx = lt::find_metric_idx("disk.num_write_jobs"); int const m_queued_reads_idx = lt::find_metric_idx("disk.num_read_jobs"); int const m_num_blocks_read_idx = lt::find_metric_idx("disk.num_blocks_read"); int const m_blocks_in_use_idx = lt::find_metric_idx("disk.disk_blocks_in_use"); int const m_blocks_written_idx = lt::find_metric_idx("disk.num_blocks_written"); int const m_write_ops_idx = lt::find_metric_idx("disk.num_write_ops"); int const m_utp_idle = lt::find_metric_idx("utp.num_utp_idle"); int const m_utp_syn_sent = lt::find_metric_idx("utp.num_utp_syn_sent"); int const m_utp_connected = lt::find_metric_idx("utp.num_utp_connected"); int const m_utp_fin_sent = lt::find_metric_idx("utp.num_utp_fin_sent"); int const m_utp_close_wait = lt::find_metric_idx("utp.num_utp_close_wait"); int const m_queued_tracker_announces = lt::find_metric_idx("tracker.num_queued_tracker_announces"); }; #endif
34.074074
100
0.776087
[ "render", "vector" ]
cf374aa940884ed8dc187db49ab2794c46c27a29
2,264
cpp
C++
a2oj/Graphs/trafficn.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
a2oj/Graphs/trafficn.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
a2oj/Graphs/trafficn.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
// Created by Tanuj Jain #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int,int> pii; template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; const int MAXN=1e4+5; const int INF = 0x3f3f3f3f; vector<int>dist1(MAXN,INF); vector<int>dist2(MAXN,INF); unordered_map<int,vector<pair<int,int>>>ada,ada_rev; void dijkstra(int src, int dest) { priority_queue<pii, vector<pii>, greater<pii>>pq; pq.push({0,src}); dist1[src]=0; dist2[dest]=0; while(!pq.empty()) { int curr_cost=pq.top().first; int curr=pq.top().second; pq.pop(); for(auto edges:ada[curr]) { if(dist1[edges.first]>curr_cost+edges.second) { dist1[edges.first]=curr_cost+edges.second; pq.push({dist1[edges.first],edges.first}); } } } pq.push({0,dest}); while(!pq.empty()) { int curr_cost=pq.top().first; int curr=pq.top().second; pq.pop(); for(auto edges:ada_rev[curr]) { if(dist2[edges.first]>curr_cost+edges.second) { dist2[edges.first]=curr_cost+edges.second; pq.push({dist2[edges.first],edges.first}); } } } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("inputf.in","r",stdin); freopen("outputf.in","w",stdout); #endif int t; cin>>t; while(t--) { dist1=vector<int>(MAXN,INF); dist2=vector<int>(MAXN,INF); int n,m,k,s,t; cin>>n>>m>>k>>s>>t; while(m--) { int src,dest,cost; cin>>src>>dest>>cost; ada[src].pb({dest,cost}); ada_rev[dest].pb({src,cost}); } dijkstra(s,t); int ans=dist1[t]; while(k--) { //these are two way roads int src,dest,cost; cin>>src>>dest>>cost; ans=min(ans,dist1[src]+cost+dist2[dest]); ans=min(ans,dist1[dest]+cost+dist2[src]); } // for(int i=1;i<t;i++) // cout<<dist1[i]<<" "; // cout<<endl; // for(int i=1;i<t;i++) // cout<<dist2[i]<<" "; if(ans==INF) cout<<-1<<endl; else cout<<ans<<endl; ada.clear(); ada_rev.clear(); } }
20.962963
106
0.603799
[ "vector" ]
cf398aa039cbd8c6da8152cabfe477848e465225
285
cpp
C++
GPS_Berkley/src/gps_agent_pkg/src/util.cpp
bvsk35/Hopping_Bot
5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216
[ "MIT" ]
null
null
null
GPS_Berkley/src/gps_agent_pkg/src/util.cpp
bvsk35/Hopping_Bot
5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216
[ "MIT" ]
null
null
null
GPS_Berkley/src/gps_agent_pkg/src/util.cpp
bvsk35/Hopping_Bot
5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216
[ "MIT" ]
1
2020-03-02T07:27:04.000Z
2020-03-02T07:27:04.000Z
#include "gps_agent_pkg/util.h" #include <sstream> namespace util { void split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } } }
19
77
0.642105
[ "vector" ]
cf3a4f64657174614b3c734586cef1edfeaf87c2
3,028
cpp
C++
test/TestMariaDB.cpp
DatabasesWorks/qtl-database-library-for-MySQL-SQLite-and-ODBC
cb88ba251b4e7e4e28ba0f82dfb1963b585a2702
[ "Apache-2.0" ]
157
2017-01-24T03:38:50.000Z
2022-03-28T03:17:20.000Z
test/TestMariaDB.cpp
DatabasesWorks/qtl-database-library-for-MySQL-SQLite-and-ODBC
cb88ba251b4e7e4e28ba0f82dfb1963b585a2702
[ "Apache-2.0" ]
16
2019-02-12T09:27:17.000Z
2022-03-15T06:20:12.000Z
test/TestMariaDB.cpp
DatabasesWorks/qtl-database-library-for-MySQL-SQLite-and-ODBC
cb88ba251b4e7e4e28ba0f82dfb1963b585a2702
[ "Apache-2.0" ]
63
2017-01-24T05:35:05.000Z
2022-03-18T04:26:49.000Z
#include "stdafx.h" #include "../include/qtl_mysql.hpp" #include <vector> #include <thread> #include <system_error> #include <time.h> #include <limits.h> #include "../include/qtl_mysql_pool.hpp" #include "../include/qtl_asio.hpp" #if MARIADB_VERSION_ID < 0100000 #error "The program need mariadb version > 10.0" #endif using namespace qtl::mysql; void LogError(const error& e) { fprintf(stderr, "MySQL Error(%d): %s\n", e.code(), e.what()); } const char mysql_server[]="localhost"; const char mysql_user[]="root"; const char mysql_password[]="123456"; const char mysql_database[]="test"; class MariaDBTest { public: MariaDBTest() { Open(); _service.run(); } private: void Open(); void Close(); void SimpleQuery(); void Execute(); void Query(); void MultiQuery(); private: async_connection _connection; qtl::asio::service _service; }; void MariaDBTest::Open() { _connection.open(_service, [this](const error& e) { if (e) { LogError(e); _service.stop(); } else { printf("Connect to mysql ok.\n"); SimpleQuery(); } }, mysql_server, mysql_user, mysql_password, mysql_database); } void MariaDBTest::Close() { _connection.close([this]() { printf("Connection is closed.\n"); _service.stop(); }); } void MariaDBTest::SimpleQuery() { _connection.simple_query("select * from test", 0, [](MYSQL_ROW row, int field_count) { for (int i = 0; i != field_count; i++) printf("%s\t", row[i]); printf("\n"); return true; }, [this](const error& e, size_t row_count) { if (e) { LogError(e); Close(); } else { printf("Total %lu rows.\n", row_count); Execute(); } }); } void MariaDBTest::Execute() { _connection.execute([this](const error& e, uint64_t affected) mutable { if (e) { LogError(e); Close(); } else { printf("Insert %llu records ok.\n", affected); Query(); } }, "insert into test(name, createtime, company) values(?, now(), ?)", 0, std::make_tuple("test name", "test company")); } void MariaDBTest::Query() { _connection.query("select id, name, CreateTime, Company from test", 0, [](int64_t id, const std::string& name, const qtl::mysql::time& create_time, const std::string& company) { char szTime[128] = { 0 }; if (create_time.year != 0) { struct tm tm; create_time.as_tm(tm); strftime(szTime, 128, "%c", &tm); } printf("%lld\t%s\t%s\t%s\n", id, name.data(), szTime, company.data()); }, [this](const error& e) { printf("query has completed.\n"); if (e) { LogError(e); Close(); } else { MultiQuery(); } }); } void MariaDBTest::MultiQuery() { _connection.query_multi("call test_proc", [this](const error& e) { if (e) LogError(e); Close(); }, [](uint32_t i, const std::string& str) { printf("0=\"%d\", 'hello world'=\"%s\"\n", i, str.data()); }, [](const qtl::mysql::time& time) { struct tm tm; time.as_tm(tm); printf("current time is: %s\n", asctime(&tm)); }); } int main(int argc, char* argv[]) { MariaDBTest test; return 0; }
19.044025
120
0.624835
[ "vector" ]
cf3b1707807ce60e5f7450fb24c43ed7ef741912
11,310
cpp
C++
jlp_gseg_wxwid/to_be_deleted/jlp_wx_gspanel.cpp
jlprieur/jlplib
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
[ "MIT" ]
null
null
null
jlp_gseg_wxwid/to_be_deleted/jlp_wx_gspanel.cpp
jlprieur/jlplib
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
[ "MIT" ]
null
null
null
jlp_gseg_wxwid/to_be_deleted/jlp_wx_gspanel.cpp
jlprieur/jlplib
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
[ "MIT" ]
1
2020-07-09T00:20:49.000Z
2020-07-09T00:20:49.000Z
/**************************************************************************** * Name: jlp_wx_gspanel.cpp * * JLP * Version 06/11/2016 ***************************************************************************/ #include <stdio.h> // jlp_splot : #include "jlp_gdev_idv.h" #include "jlp_splot.h" #include "jlp_plotlib.h" // jlp_wxplot : #include "jlp_gdev_wxwid.h" #include "jlp_wxlogbook.h" // JLP_wxLogbook #include "jlp_wx_video_panel.h" // JLP_wxVideoPanel // jlp_gseg_wxwid #include "jlp_wx_gspanel.h" // ZZ #include "jlp_bitmaps.h" // JLP bitmaps // mBookCtrl enum{ ID_DRAW_CGDEV = 2850, ID_DRAW_ZOOM_IN, ID_DRAW_ZOOM_OUT, ID_DRAW_MOVE_RIGHT, ID_DRAW_MOVE_LEFT, ID_DRAW_VIDEO_PREVIOUS, ID_DRAW_VIDEO_NEXT, ID_DRAW_VIDEO_PREVIOUS_FAST, ID_DRAW_VIDEO_NEXT_FAST }; BEGIN_EVENT_TABLE(JLP_wxGsegPanel, wxPanel) EVT_BUTTON (ID_DRAW_ZOOM_IN, JLP_wxGsegPanel::OnZoomButton) EVT_BUTTON (ID_DRAW_ZOOM_OUT, JLP_wxGsegPanel::OnZoomButton) EVT_BUTTON (ID_DRAW_MOVE_LEFT, JLP_wxGsegPanel::OnMoveButton) EVT_BUTTON (ID_DRAW_MOVE_RIGHT, JLP_wxGsegPanel::OnMoveButton) EVT_BUTTON (ID_DRAW_VIDEO_PREVIOUS, JLP_wxGsegPanel::OnShowVideoPlane) EVT_BUTTON (ID_DRAW_VIDEO_NEXT, JLP_wxGsegPanel::OnShowVideoPlane) EVT_BUTTON (ID_DRAW_VIDEO_PREVIOUS_FAST, JLP_wxGsegPanel::OnShowVideoPlane) EVT_BUTTON (ID_DRAW_VIDEO_NEXT_FAST, JLP_wxGsegPanel::OnShowVideoPlane) // catch size events EVT_SIZE (JLP_wxGsegPanel::OnResize) END_EVENT_TABLE() // ============================================================================ // implementation // ============================================================================ /******************************************************************************* * Constructor as a subwindow from wxFrame: *******************************************************************************/ JLP_wxGsegPanel::JLP_wxGsegPanel( wxFrame *frame, const int my_wxID, JLP_wxLogbook *logbook, JLP_wxVideoPanel *jlp_video_panel0, int x, int y, int iwidth, int iheight) : wxPanel( frame, my_wxID, wxPoint(x, y), wxSize(iwidth, iheight)) { wxString input_filename; // Transform coma into point for numbers: setlocale(LC_NUMERIC, "C"); initialized = 0; m_width = iwidth; m_height = iheight; wavel_start1 = 0.; wavel_step1 = 1.; jlp_logbook = logbook; jlp_video_panel = jlp_video_panel0; // Setup drawing panel Setup_DrawingPanel(my_wxID); initialized = 1234; return; } /******************************************************************************* * Constructor as a subwindow from wxFrame: *******************************************************************************/ JLP_wxGsegPanel::JLP_wxGsegPanel( wxFrame *frame, const int my_wxID, JLP_wxLogbook *logbook, int x, int y, int iwidth, int iheight) : wxPanel( frame, my_wxID, wxPoint(x, y), wxSize(iwidth, iheight)) { wxString input_filename; // Transform coma into point for numbers: setlocale(LC_NUMERIC, "C"); initialized = 0; m_width = iwidth; m_height = iheight; wavel_start1 = 0.; wavel_step1 = 1.; jlp_logbook = logbook; jlp_video_panel = NULL; // Setup drawing panel Setup_DrawingPanel(my_wxID); initialized = 1234; return; } //********************************************************************* // Setup drawing panel //********************************************************************* void JLP_wxGsegPanel::Setup_DrawingPanel(const int ID0) { int status; wxString buffer; wxBoxSizer *topsizer = new wxBoxSizer( wxVERTICAL ); m_StaticHelp = new wxStaticText(this, -1, wxT("Processing mode = 0 : click and drag to select box")); m_StaticCoord = new wxStaticText(this, -1, wxT("x=12.3456 y=12.3456"), wxPoint(-1,-1), wxSize(140,20)); // New JLP_wxGseg_Canvas object (for display on the screen) // Start at wxpoint(0,0) from top left corner: jlp_wxgseg_canvas1 = new JLP_wxGseg_Canvas(this, ID0, wxPoint(0, 0), wxSize(m_width, m_height - 60), m_StaticCoord, m_StaticHelp); topsizer->Add(jlp_wxgseg_canvas1, 1, wxEXPAND); // Get idev number: status = jlp_wxgseg_canvas1->Get_idev(Drawing_idev); if(status) { fprintf(stderr, "Setup_DrawingPanel/Fatal error: Drawing_idev = %d\n", Drawing_idev); buffer.Printf(wxT("Setup_DrawingPanel/Fatal error: Drawing_idev = %d"), Drawing_idev); wxMessageBox(buffer, wxT("JLP_wxGsegPanel"), wxOK | wxICON_ERROR); exit(-1); } // Create two buttons that are horizontally unstretchable, // with an all-around border with a width of 10 and implicit top alignment wxBoxSizer *button_sizer = new wxBoxSizer( wxHORIZONTAL ); // Bitmap colors: 1=yellow 2=red 3= blue m_ZoomInButton = new wxBitmapButton(this, ID_DRAW_ZOOM_IN, wxBITMAP(zoom_plus3)); button_sizer->Add( m_ZoomInButton, 0); m_ZoomOutButton = new wxBitmapButton(this, ID_DRAW_ZOOM_OUT, wxBITMAP(zoom_minus3)); button_sizer->Add( m_ZoomOutButton, 0, wxLEFT, 10); m_MoveRightButton = new wxBitmapButton(this, ID_DRAW_MOVE_RIGHT, wxBITMAP(move_right3)); button_sizer->Add( m_MoveRightButton, 0, wxLEFT, 10); m_MoveLeftButton = new wxBitmapButton(this, ID_DRAW_MOVE_LEFT, wxBITMAP(move_left3)); button_sizer->Add( m_MoveLeftButton, 0, wxLEFT, 10); // Yellow buttons (like for "jlp_wx_video_panel.cpp") if(jlp_video_panel != NULL) { m_VideoNextFastButton = new wxBitmapButton(this, ID_DRAW_VIDEO_NEXT_FAST, wxBITMAP(move_right_fast1)); button_sizer->Add( m_VideoNextFastButton, 0, wxLEFT, 10); m_VideoNextButton = new wxBitmapButton(this, ID_DRAW_VIDEO_NEXT, wxBITMAP(move_right1)); button_sizer->Add( m_VideoNextButton, 0, wxLEFT, 10); m_VideoPreviousButton = new wxBitmapButton(this, ID_DRAW_VIDEO_PREVIOUS, wxBITMAP(move_left1)); button_sizer->Add( m_VideoPreviousButton, 0, wxLEFT, 10); m_VideoPreviousFastButton = new wxBitmapButton(this, ID_DRAW_VIDEO_PREVIOUS_FAST, wxBITMAP(move_left_fast1)); button_sizer->Add( m_VideoPreviousFastButton, 0, wxLEFT, 10); } // Static text with the coordinates button_sizer->Add( m_StaticCoord, 0, wxLEFT | wxALIGN_CENTER_VERTICAL, 10); // Help static tex on the next line: button_sizer->Add( m_StaticHelp, 0, wxLEFT | wxALIGN_CENTER_VERTICAL, 20); // Create a sizer with no border and centered horizontally topsizer->Add(button_sizer, 0, wxALIGN_CENTER | wxALL, 10); // To set the minimum size that fits this setup: SetSizerAndFit(topsizer); // use the sizer for layout return; } /************************************************************************ * Destructor *************************************************************************/ JLP_wxGsegPanel::~JLP_wxGsegPanel() { // Free Memory: delete jlp_wxgseg_canvas1; Close(); } /************************************************************************ * To enlarge the window at the maximum size: * JLP 2015: resize events should be handled here * (attempts to make it at the jlp_cgdev class level have failed !) * (=> It should be done using the instanciation not the class !!) ************************************************************************/ void JLP_wxGsegPanel::OnResize(wxSizeEvent &event ) { JLP_ResizeGraphicPanel(); // Skip this event (to avoid infinite processing of the same event): event.Skip(); return; } /************************************************************************ * To enlarge the window at the maximum size: * JLP 2015: resize events should be handled here * (attempts to make it at the jlp_cgdev class level have failed !) * (=> It should be done using the instanciation not the class !!) * * Routine defined here outside of resize events to be called manually ************************************************************************/ void JLP_wxGsegPanel::JLP_ResizeGraphicPanel() { int width0, height0; if(initialized != 1234) return; // Both GetSize() or GetClientSize() give a bad size (too large) GetClientSize(&width0, &height0); /* printf("JLP_wxGsegPanel::GetClientSize/width,height = %d,%d\n", width0, height0); */ // Step 1: resize the drawing panel with the large size and update the drawings jlp_wxgseg_canvas1->SetNewBitmapSize(width0, height0); jlp_wxgseg_canvas1->Get_ClientSize(&width0, &height0); /* printf("JLP_wxGsegPanel/From Drawing_cgdex::GetClientSize/width,height = %d,%d\n", width0, height0); */ // Step 2: resize the drawing panel with the smaller size and update the drawings jlp_wxgseg_canvas1->SetNewBitmapSize(width0, height0); // JLP2016: it is necessary to refresh the drawing window to make it fill // the whole allocated panel space: jlp_wxgseg_canvas1->Refresh(); return; } /********************************************************************* * ZoomIn/ZoomOut button *********************************************************************/ void JLP_wxGsegPanel::OnZoomButton(wxCommandEvent &event) { bool zoom_in; if(initialized != 1234) return; switch(event.GetId()) { default: case ID_DRAW_ZOOM_IN: zoom_in = true; break; case ID_DRAW_ZOOM_OUT: zoom_in = false; break; } jlp_wxgseg_canvas1->BoxLimitsZoom(zoom_in); jlp_wxgseg_canvas1->RedrawToBackupDC(8001); // Update cursor: if(jlp_video_panel != NULL) jlp_video_panel->UpdateCursorInSpectrumPanel(); return; } /********************************************************************* * Move right/left button *********************************************************************/ void JLP_wxGsegPanel::OnMoveButton(wxCommandEvent &event) { bool move_to_right; if(initialized != 1234) return; switch(event.GetId()) { default: case ID_DRAW_MOVE_RIGHT: move_to_right = true; break; case ID_DRAW_MOVE_LEFT: move_to_right = false; break; } jlp_wxgseg_canvas1->BoxLimitsMove(move_to_right); jlp_wxgseg_canvas1->RedrawToBackupDC(8002); // Update cursor: if(jlp_video_panel != NULL) jlp_video_panel->UpdateCursorInSpectrumPanel(); return; } /********************************************************************* * Show Video Plane button *********************************************************************/ void JLP_wxGsegPanel::OnShowVideoPlane(wxCommandEvent &event) { if((initialized != 1234) || (jlp_video_panel == NULL)) return; switch(event.GetId()) { default: case ID_DRAW_VIDEO_PREVIOUS: jlp_video_panel->DisplayPreviousFrame(); break; case ID_DRAW_VIDEO_PREVIOUS_FAST: jlp_video_panel->DisplayFastPreviousFrame(); break; case ID_DRAW_VIDEO_NEXT: jlp_video_panel->DisplayNextFrame(); break; case ID_DRAW_VIDEO_NEXT_FAST: jlp_video_panel->DisplayFastNextFrame(); break; } return; }
33.070175
84
0.590186
[ "object", "transform" ]
cf3cf1ccfdef416546f0a13556d54f79c3187001
11,824
hpp
C++
invertible_bloom_filter.hpp
DominikHorn/invertible-bloom-filter
5b5412bc7354cd71120ec632f354fbb15bcaa89f
[ "MIT" ]
null
null
null
invertible_bloom_filter.hpp
DominikHorn/invertible-bloom-filter
5b5412bc7354cd71120ec632f354fbb15bcaa89f
[ "MIT" ]
null
null
null
invertible_bloom_filter.hpp
DominikHorn/invertible-bloom-filter
5b5412bc7354cd71120ec632f354fbb15bcaa89f
[ "MIT" ]
null
null
null
#pragma once #include <array> #include <cstdint> #include <optional> #include <random> #include <unordered_set> #include <vector> namespace ibf { /** * InvertibleBloomDictionarys are probabilistic structures * that can, in some cases, only answer probabilistically */ enum ContainsResult { not_found, might_exist, exists }; /** * InvertibleBloomFilter is a probabilistic set data structure. * * It can do everything a normal bloom filter is capable of probabilistically * recovering the original keyset */ template <class Key, class HashFn, size_t K = 3, class BucketCounter = std::uint16_t> class InvertibleBloomFilter { struct Bucket { Key cumulative_key = 0; BucketCounter count = 0; } /*__attribute((packed))*/; const HashFn hasher; using Seed = std::uint64_t; std::array<Seed, K> seeds; std::vector<Bucket> buckets; size_t count; size_t hash_index(const Key &key, const Seed &seed) const { const auto hash = (hasher(key) ^ seed); return hash % buckets.size(); // TODO: use fast modulo } public: /** * Constructs and InvertibleBloomFilter given a target directory size and * seed (defaults to std::random_device()()). Note that the directory never * resizes during InvertibleBloomFilter's lifetime, hence you must pick a * value that fits your keys upfront */ InvertibleBloomFilter(size_t size, unsigned int seed = std::random_device()()) : buckets(size), count(0) { std::default_random_engine rng(seed); std::uniform_int_distribution<Seed> dist(std::numeric_limits<Seed>::min(), std::numeric_limits<Seed>::max()); for (size_t i = 0; i < K; i++) { // generate until we find a new random seed Seed rand_seed = 0; bool already_exists = false; do { rand_seed = dist(rng); for (size_t j = 0; j < i; j++) already_exists |= seeds[j] == rand_seed; } while (already_exists); seeds[i] = rand_seed; } } /** * Count of keys in this InvertibleBloomFilter */ size_t size() const { return count; } /** * Size of internal bucket directory */ size_t directory_size() const { return buckets.size(); } /** * Exposes internally used seeds, useful for testing or external serialization */ std::array<Seed, K> listSeeds() const { return seeds; } /** * Inserts a single key with its corresponding value */ void insert(const Key &key) { // keep track of indices we already set to avoid issues with two hashes // going to same bucket std::unordered_set<size_t> seen_indices; for (const auto &seed : seeds) { const auto index = hash_index(key, seed); // fix issue with hashfn hashing to same slot if (seen_indices.find(index) != seen_indices.end()) continue; seen_indices.insert(index); auto &bucket = buckets[index]; bucket.cumulative_key ^= key; bucket.count++; } count += 1; } /** * Checks whether a key is contained in this IBF. May return false positives, * but never false negatives */ ContainsResult contains(const Key &key) const { bool might_exist = false; for (const auto &seed : seeds) { const auto index = hash_index(key, seed); const auto &bucket = buckets[index]; if (bucket.count == 1) return key == bucket.cumulative_key ? ContainsResult::exists : ContainsResult::not_found; might_exist |= bucket.count > 1; } return might_exist ? ContainsResult::might_exist : ContainsResult::not_found; } /** * Removes a single key and its corresponding value from * the struct. Note that it is possible for this operation * to fail (return false) not because the key doesn't exist, * but because it is not uniquely identifyable */ bool remove(Key key) { if (contains(key) != ContainsResult::exists) return false; // keep track of indices we already set to avoid issues with two hashes // going to same bucket std::unordered_set<size_t> seen_indices; for (const auto &seed : seeds) { const auto index = hash_index(key, seed); // fix issue with hashfn hashing to same slot if (seen_indices.find(index) != seen_indices.end()) continue; seen_indices.insert(index); auto &bucket = buckets[index]; assert(bucket.count > 0); bucket.cumulative_key ^= key; bucket.count--; } count -= 1; return true; } /** * Attempts to retrieve all key, value pairs. This operation might fail * due to the probabilistic nature of this struct */ std::optional<std::unordered_set<Key>> listAll() const { std::unordered_set<Key> res; res.reserve(count); auto copy = *this; // TODO: come up with faster algorithm bool finished = false; bool has_changed = true; while (!finished && has_changed) { finished = true; has_changed = false; for (size_t i = 0; i < copy.buckets.size(); i++) { const auto &bucket = copy.buckets[i]; // skip already empty buckets if (bucket.count == 0) continue; // skip ambiguous buckets if (bucket.count > 1) { finished = false; continue; } res.insert(bucket.cumulative_key); has_changed = copy.remove(bucket.cumulative_key); assert(bucket.count == 0); } } if (!finished || res.size() != count) return std::nullopt; return std::make_optional(res); } }; /** * InvertibleBloomDictionary is a probabilistic dictionary data structure. * * It can do everything a normal bloom filter is capable of and, with a certain * probability < 1, recover associated values and also the original keyset */ template <class Key, class Value, class HashFn, size_t K = 3, class BucketCounter = std::uint16_t> class InvertibleBloomDictionary { struct Bucket { Key cumulative_key = 0; Value cumulative_value = 0; BucketCounter count = 0; } /*__attribute((packed))*/; const HashFn hasher; using Seed = std::uint64_t; std::array<Seed, K> seeds; std::vector<Bucket> buckets; size_t count; size_t hash_index(const Key &key, const Seed &seed) const { const auto hash = (hasher(key) ^ seed); return hash % buckets.size(); // TODO: use fast modulo } public: /** * Constructs and InvertibleBloomDictionary given a target directory size and * seed (defaults to std::random_device()()). Note that the directory never * resizes during InvertibleBloomDictionary's lifetime, hence you must pick a * value that fits your keys upfront */ InvertibleBloomDictionary(size_t size, unsigned int seed = std::random_device()()) : buckets(size), count(0) { std::default_random_engine rng(seed); std::uniform_int_distribution<Seed> dist(std::numeric_limits<Seed>::min(), std::numeric_limits<Seed>::max()); for (size_t i = 0; i < K; i++) { // generate until we find a new random seed Seed rand_seed = 0; bool already_exists = false; do { rand_seed = dist(rng); for (size_t j = 0; j < i; j++) already_exists |= seeds[j] == rand_seed; } while (already_exists); seeds[i] = rand_seed; } } /** * Count of keys in this InvertibleBloomDictionary */ size_t size() const { return count; } /** * Size of internal bucket directory */ size_t directory_size() const { return buckets.size(); } /** * Exposes internally used seeds, useful for testing or external serialization */ std::array<Seed, K> listSeeds() const { return seeds; } /** * Inserts a single key with its corresponding value */ void insert(const Key &key, const Value &value) { // keep track of indices we already set to avoid issues with two hashes // going to same bucket std::unordered_set<size_t> seen_indices; for (const auto &seed : seeds) { const auto index = hash_index(key, seed); // fix issue with hashfn hashing to same slot if (seen_indices.find(index) != seen_indices.end()) continue; seen_indices.insert(index); auto &bucket = buckets[index]; bucket.cumulative_key ^= key; bucket.cumulative_value ^= value; bucket.count++; } count += 1; } /** * Checks whether a key is contained in this IBF. May return false positives, * but never false negatives */ ContainsResult contains(const Key &key) const { bool might_exist = false; for (const auto &seed : seeds) { const auto index = hash_index(key, seed); const auto &bucket = buckets[index]; if (bucket.count == 1) return key == bucket.cumulative_key ? ContainsResult::exists : ContainsResult::not_found; might_exist |= bucket.count > 1; } return might_exist ? ContainsResult::might_exist : ContainsResult::not_found; } /** * Returns the value associated with key if retrievable. * Can return nullopt, eiher if key does not exist or if it's value is not * uniquely identifyable. */ std::optional<Value> get(const Key &key) const { for (const auto &seed : seeds) { const auto index = hash_index(key, seed); const auto &bucket = buckets[index]; if (bucket.count == 1) return key == bucket.cumulative_key ? std::make_optional(bucket.cumulative_value) : std::nullopt; } return std::nullopt; } /** * Removes a single key and its corresponding value from * the struct. Note that it is possible for this operation * to fail (return false) not because the key doesn't exist, * but because it is not uniquely identifyable */ bool remove(Key key) { const auto value = get(key); if (!value) return false; assert(value.has_value()); // keep track of indices we already set to avoid issues with two hashes // going to same bucket std::unordered_set<size_t> seen_indices; for (const auto &seed : seeds) { const auto index = hash_index(key, seed); // fix issue with hashfn hashing to same slot if (seen_indices.find(index) != seen_indices.end()) continue; seen_indices.insert(index); auto &bucket = buckets[index]; assert(bucket.count > 0); bucket.cumulative_key ^= key; bucket.cumulative_value ^= *value; bucket.count--; } count -= 1; return true; } /** * Attempts to retrieve all key, value pairs. This operation might fail * due to the probabilistic nature of this struct */ std::optional<std::vector<std::pair<Key, Value>>> listAll() const { std::vector<std::pair<Key, Value>> res; res.reserve(count); auto copy = *this; // TODO: come up with faster algorithm bool finished = false; bool has_changed = true; while (!finished && has_changed) { finished = true; has_changed = false; for (size_t i = 0; i < copy.buckets.size(); i++) { const auto &bucket = copy.buckets[i]; // skip already empty buckets if (bucket.count == 0) continue; // skip ambiguous buckets if (bucket.count > 1) { finished = false; continue; } res.push_back({bucket.cumulative_key, bucket.cumulative_value}); has_changed = copy.remove(bucket.cumulative_key); assert(bucket.count == 0); } } if (!finished || res.size() != count) return std::nullopt; return std::make_optional(res); } }; } // namespace ibf
27.952719
80
0.625507
[ "vector" ]
cf49862a6ef314af8d17a2b3d8da5b1dd55cf086
11,163
cpp
C++
WMI/WMI.cpp
zhaotianff/WindowsProgramming
3d208e3793c4efb568f75065fa5749f58a2ba73c
[ "MIT" ]
9
2020-10-28T09:08:24.000Z
2022-02-27T08:31:40.000Z
WMI/WMI.cpp
zhaotianff/WindowsProgramming
3d208e3793c4efb568f75065fa5749f58a2ba73c
[ "MIT" ]
null
null
null
WMI/WMI.cpp
zhaotianff/WindowsProgramming
3d208e3793c4efb568f75065fa5749f58a2ba73c
[ "MIT" ]
1
2021-01-22T09:21:25.000Z
2021-01-22T09:21:25.000Z
// WMI.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #define _WIN32_DCOM #include <iostream> #include <WbemIdl.h> #include<Windows.h> #include <comdef.h> #include<vector> #pragma comment(lib,"wbemuuid.lib") void GetWMIDataSync(); void EnumWMIData(); void CallWMIProviderMethod(); void EnumWMIMethod(); void DisableNetoworkAdapter(); void SetNetworkAdapeterIP(BSTR ip); int main() { //所有的WMI Provider可以在这里找到 https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-provider EnumWMIMethod(); } void GetWMIDataSync() { //初始化COM [MTAThread] HRESULT hr; hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hr)) { return; } //设置COM安全级别 hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); if (FAILED(hr)) { CoUninitialize(); return; } //创建WMI命名空间的连接 IWbemLocator* pLoc = NULL; hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc); IWbemServices* pSvc = NULL; //连接WMI hr = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc); if (FAILED(hr)) { pLoc->Release(); CoUninitialize(); return; } //在代理上设置安全级别 hr = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE); if (FAILED(hr)) { pSvc->Release(); pLoc->Release(); CoUninitialize(); } //查询WMI对象 //使用IWbemServices指针创建WMI请求 IEnumWbemClassObject* pEnumerator = NULL; pSvc->ExecQuery(bstr_t("WQL"), bstr_t("Select * from win32_OperatingSystem"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator); if (FAILED(hr)) { pSvc->Release(); pLoc->Release(); CoUninitialize(); return; } //获取数据 IWbemClassObject* pclsObj = NULL; ULONG uReturn = 0; while (pEnumerator) { hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) { break; } VARIANT vtProp{}; hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0); std::wcout << "OS Name : " << vtProp.bstrVal << std::endl; VariantClear(&vtProp); pclsObj->Release(); } pSvc->Release(); pLoc->Release(); pEnumerator->Release(); CoUninitialize(); } void EnumWMIData() { HRESULT hr; std::vector<VARIANT> bb{}; hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hr)) { std::cout << "COM初始化失败.错误码 = 0x" << std::hex << hr << std::endl; return; } hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); if (FAILED(hr)) { std::cout << "初始化安全性失败.错误码 = 0x" << std::hex << hr << std::endl; } IWbemLocator* pLoc = NULL; hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc); if (FAILED(hr)) { std::cout << "创建IWbemLocator对象失败.错误码 = 0x" << std::hex << hr << std::endl; CoUninitialize(); return; } IWbemServices* pSvc = NULL; hr = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc); if (FAILED(hr)) { std::cout << "连接WMI失败.错误码 = 0x" << std::hex << hr << std::endl; pLoc->Release(); CoUninitialize(); return; } IEnumWbemClassObject* pEnumerator = NULL; hr = pSvc->ExecQuery(_bstr_t(L"WQL"), _bstr_t(L"Select * from win32_OperatingSystem"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator); if (FAILED(hr)) { std::cout << "查询Win32_OperatingSystem失败.错误码 = 0x" << std::hex << hr << std::endl; pSvc->Release(); pLoc->Release(); CoUninitialize(); return; } IWbemClassObject* pclsObj = NULL; ULONG uReturn = 0; while (pEnumerator) { hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) { break; } if (pclsObj->BeginEnumeration(WBEM_FLAG_NONSYSTEM_ONLY) == WBEM_S_NO_ERROR) { BSTR name = NULL; VARIANT vtProp; VariantInit(&vtProp); while (pclsObj->Next(0, &name, &vtProp, 0, 0) == WBEM_S_NO_ERROR) { bb.push_back(vtProp); //这里暂时只输出字符串 if (vtProp.vt == VT_NULL || vtProp.vt != VT_BSTR) continue; std::wcout << name << "\t" << vtProp.bstrVal << std::endl; } SysFreeString(name); VariantClear(&vtProp); } pclsObj->Release(); } pEnumerator->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); } void CallWMIProviderMethod() { HRESULT hr; hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hr)) { return; } hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); if (FAILED(hr)) { CoUninitialize(); return; } IWbemLocator* pLoc = NULL; hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc); if (FAILED(hr)) { CoUninitialize(); return; } IWbemServices* pSvc = NULL; hr = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0,0, &pSvc); if (FAILED(hr)) { pLoc->Release(); CoUninitialize(); return; } hr = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE); if (FAILED(hr)) { pSvc->Release(); pLoc->Release(); CoUninitialize(); return; } BSTR methodName = SysAllocString(L"Create"); BSTR className = SysAllocString(L"Win32_Process"); IWbemClassObject* pClass = NULL; hr = pSvc->GetObjectW(className, 0, NULL, &pClass, NULL); IWbemClassObject* pInParamDefinition = NULL; hr = pClass->GetMethod(methodName, 0, &pInParamDefinition, NULL); IWbemClassObject* pClassInstance = NULL; hr = pInParamDefinition->SpawnInstance(0, &pClassInstance); VARIANT varCommand; VariantInit(&varCommand); varCommand.vt = VT_BSTR; varCommand.bstrVal = _bstr_t(L"notepad.exe"); hr = pClassInstance->Put(L"CommandLine", 0, &varCommand, 0); IWbemClassObject* pOutParams = NULL; hr = pSvc->ExecMethod(className, methodName, 0, NULL, pClassInstance, &pOutParams, NULL); if (FAILED(hr)) { VariantClear(&varCommand); SysFreeString(className); SysFreeString(methodName); pClass->Release(); pClassInstance->Release(); pInParamDefinition->Release(); pOutParams->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); return; } VARIANT varReturnValue; VariantInit(&varReturnValue); hr = pOutParams->Get(BSTR(L"ReturnValue"), 0, &varReturnValue, NULL, 0); if (SUCCEEDED(hr)) { VariantClear(&varReturnValue); } VariantClear(&varCommand); SysFreeString(className); SysFreeString(methodName); pClass->Release(); pClassInstance->Release(); pInParamDefinition->Release(); pOutParams->Release(); pLoc->Release(); pSvc->Release(); CoUninitialize(); } void EnumWMIMethod() { HRESULT hr; hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hr)) { return; } hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); if (FAILED(hr)) { CoUninitialize(); return; } IWbemLocator* pLoc = NULL; hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc); if (FAILED(hr)) { CoUninitialize(); return; } IWbemServices* pSvc = NULL; hr = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc); if (FAILED(hr)) { pLoc->Release(); CoUninitialize(); return; } hr = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE); if (FAILED(hr)) { pSvc->Release(); pLoc->Release(); CoUninitialize(); return; } BSTR className = SysAllocString(L"Win32_NetworkAdapter"); IWbemClassObject* pClass = NULL; hr = pSvc->GetObjectW(className, 0, NULL, &pClass, NULL); IWbemClassObject* pInParamDefinition = NULL; IWbemClassObject* pOutParamDefinition = NULL; hr = pClass->BeginMethodEnumeration(WBEM_FLAG_LOCAL_ONLY); if (SUCCEEDED(hr)) { BSTR name = NULL; while (pClass->NextMethod(0, &name, &pInParamDefinition, &pOutParamDefinition) == WBEM_S_NO_ERROR) { std::wcout << name << std::endl; } } if (FAILED(hr)) { SysFreeString(className); pClass->Release(); if (pInParamDefinition != NULL) { pInParamDefinition->Release(); } if (pOutParamDefinition != NULL) { pOutParamDefinition->Release(); } pSvc->Release(); pLoc->Release(); CoUninitialize(); return; } SysFreeString(className); pClass->Release(); if (pInParamDefinition != NULL) { pInParamDefinition->Release(); } if (pOutParamDefinition != NULL) { pOutParamDefinition->Release(); } pLoc->Release(); pSvc->Release(); CoUninitialize(); } void SetNetworkAdapeterIP(BSTR ip) { //借助Win32_NetworkAdapterConfiguration的EnableStatic 方法可以设置网卡IP地址 } void DisableNetoworkAdapter() { using namespace std; HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (FAILED(hr)) { cout << "Unable to launch COM: 0x" << std::hex << hr << endl; return; } if ((FAILED(hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0)))) { cout << "Unable to initialize security: 0x" << std::hex << hr << endl; return; } IWbemLocator* pLocator = NULL; if (FAILED(hr = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_ALL, IID_PPV_ARGS(&pLocator)))) { cout << "Unable to create a WbemLocator: " << std::hex << hr << endl; return; } IWbemServices* pService = NULL; hr = pLocator->ConnectServer(_bstr_t("root\\CIMV2"), NULL, NULL, NULL, WBEM_FLAG_CONNECT_USE_MAX_WAIT, NULL, NULL, &pService); if (FAILED(hr)) { pLocator->Release(); cout << "Unable to connect to \"CIMV2\": " << std::hex << hr << endl; return; } IEnumWbemClassObject* pEnumerator = NULL; //可以先列出全部网卡,然后选择对应网卡禁用 hr = pService->ExecQuery(_bstr_t("WQL"), _bstr_t("SELECT * FROM Win32_NetworkAdapter WHERE Name Like 'Intel(R) Ethernet Connection (2) I219-V'"), WBEM_FLAG_FORWARD_ONLY, NULL, &pEnumerator); if (FAILED(hr)) { pLocator->Release(); pService->Release(); cout << "Unable to retrive the network adapter: " << std::hex << hr << endl; return; } IWbemClassObject* clsObj = NULL; int numElems; while ((hr = pEnumerator->Next(WBEM_INFINITE, 1, &clsObj, (ULONG*)&numElems)) != WBEM_S_FALSE) { if (FAILED(hr)) break; VARIANT vtPath; VariantInit(&vtPath); if (FAILED(clsObj->Get(L"__Path", 0, &vtPath, NULL, NULL))) { cout << "Object has no __Path!" << endl; clsObj->Release(); continue; } IWbemClassObject* pResult = NULL; //禁用或启用网卡 hr = pService->ExecMethod(vtPath.bstrVal, _bstr_t("Disable"), 0, NULL, NULL, &pResult, NULL); if (FAILED(hr)) cout << "Unable to disable networkadapter: " << std::hex << hr << endl; else { VARIANT vtRet; VariantInit(&vtRet); if (FAILED(hr = pResult->Get(L"ReturnValue", 0, &vtRet, NULL, 0))) cout << "Unable to get return value of call: " << std::hex << hr << endl; else cout << "Method returned: " << vtRet.intVal << endl; VariantClear(&vtRet); pResult->Release(); } VariantClear(&vtPath); clsObj->Release(); } pEnumerator->Release(); pService->Release(); pLocator->Release(); }
22.460765
192
0.683866
[ "object", "vector" ]
cf5618f37de0d929a5f79a38e2e6406102dec945
2,060
hpp
C++
src/Control/Walker/Options/VelocityVariant.hpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
src/Control/Walker/Options/VelocityVariant.hpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
src/Control/Walker/Options/VelocityVariant.hpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
// ***************************************************************************** /*! \file src/Control/Walker/Options/VelocityVariant.hpp \copyright 2012-2015 J. Bakosi, 2016-2018 Los Alamos National Security, LLC., 2019 Triad National Security, LLC. All rights reserved. See the LICENSE file for details. \brief Velocity model variants \details Velocity model variants for walker. */ // ***************************************************************************** #ifndef VelocityVariantOptions_h #define VelocityVariantOptions_h #include <brigand/sequences/list.hpp> #include "Toggle.hpp" #include "Keywords.hpp" #include "PUPUtil.hpp" namespace walker { namespace ctr { //! Velocity model variant types enum class VelocityVariantType : uint8_t { SLM=0 , GLM }; //! \brief Pack/Unpack VelocityVariantType: forward overload to generic enum //! class packer inline void operator|( PUP::er& p, VelocityVariantType& e ) { PUP::pup( p, e ); } //! Velocity model variants: outsource to base templated on enum type class VelocityVariant : public tk::Toggle< VelocityVariantType > { public: //! Valid expected choices to make them also available at compile-time using keywords = brigand::list< kw::slm , kw::glm >; //! \brief Options constructor //! \details Simply initialize in-line and pass associations to base, which //! will handle client interactions explicit VelocityVariant() : tk::Toggle< VelocityVariantType >( //! Group, i.e., options, name "Model variant", //! Enums -> names { { VelocityVariantType::SLM, kw::slm::name() }, { VelocityVariantType::GLM, kw::glm::name() } }, //! keywords -> Enums { { kw::slm::string(), VelocityVariantType::SLM }, { kw::glm::string(), VelocityVariantType::GLM } } ) {} }; } // ctr:: } // walker:: #endif // VelocityVariantOptions_h
33.225806
80
0.574272
[ "model" ]
cf5c4733b278de222ad8d6d019eebe7602d431f0
9,857
cpp
C++
jsk_recognition/jsk_pcl_ros/src/incremental_model_registration_nodelet.cpp
VT-ASIM-LAB/autoware.ai
211dff3bee2d2782cb10444272c5d98d1f30d33a
[ "Apache-2.0" ]
null
null
null
jsk_recognition/jsk_pcl_ros/src/incremental_model_registration_nodelet.cpp
VT-ASIM-LAB/autoware.ai
211dff3bee2d2782cb10444272c5d98d1f30d33a
[ "Apache-2.0" ]
null
null
null
jsk_recognition/jsk_pcl_ros/src/incremental_model_registration_nodelet.cpp
VT-ASIM-LAB/autoware.ai
211dff3bee2d2782cb10444272c5d98d1f30d33a
[ "Apache-2.0" ]
null
null
null
// -*- mode: c++ -*- /********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, JSK Lab * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/o2r other materials provided * with the distribution. * * Neither the name of the JSK Lab nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ #define BOOST_PARAMETER_MAX_ARITY 7 #include <sstream> #include "jsk_pcl_ros/incremental_model_registration.h" #include "jsk_recognition_utils/pcl_conversion_util.h" #include <pcl/common/transforms.h> #include <pcl/filters/extract_indices.h> #include <jsk_recognition_msgs/ICPAlign.h> namespace jsk_pcl_ros { CapturedSamplePointCloud::CapturedSamplePointCloud() { } CapturedSamplePointCloud::CapturedSamplePointCloud(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud, const Eigen::Affine3f& pose): original_cloud_(cloud), original_pose_(pose), refined_cloud_(new pcl::PointCloud<pcl::PointXYZRGB>) { } pcl::PointCloud<pcl::PointXYZRGB>::Ptr CapturedSamplePointCloud::getOriginalPointCloud() { return original_cloud_; } Eigen::Affine3f CapturedSamplePointCloud::getOriginalPose() { return original_pose_; } pcl::PointCloud<pcl::PointXYZRGB>::Ptr CapturedSamplePointCloud::getRefinedPointCloud() { return refined_cloud_; } Eigen::Affine3f CapturedSamplePointCloud::getRefinedPose() { return refined_pose_; } void CapturedSamplePointCloud::setRefinedPointCloud( pcl::PointCloud<pcl::PointXYZRGB> cloud) { *refined_cloud_ = cloud; // copying } void CapturedSamplePointCloud::setRefinedPose( Eigen::Affine3f pose) { refined_pose_ = Eigen::Affine3f(pose); } void IncrementalModelRegistration::onInit() { DiagnosticNodelet::onInit(); pnh_->param("frame_id", frame_id_, std::string("multisense/left_camera_optical_frame")); start_registration_srv_ = pnh_->advertiseService( "start_registration", &IncrementalModelRegistration::startRegistration, this); pub_cloud_non_registered_ = pnh_->advertise<sensor_msgs::PointCloud2>("output/non_registered", 1); pub_registered_ = pnh_->advertise<sensor_msgs::PointCloud2>("output/registered", 1); sub_cloud_.subscribe(*pnh_, "input", 1); sub_indices_.subscribe(*pnh_, "input/indices", 1); sub_pose_.subscribe(*pnh_, "input/pose", 1); sync_ = boost::make_shared<message_filters::Synchronizer<SyncPolicy> >(100); sync_->connectInput(sub_cloud_, sub_indices_, sub_pose_); sync_->registerCallback(boost::bind( &IncrementalModelRegistration::newsampleCallback, this, _1, _2, _3)); onInitPostProcess(); } void IncrementalModelRegistration::transformPointCloudRepsectedToPose( pcl::PointCloud<pcl::PointXYZRGB>::Ptr input, pcl::PointCloud<pcl::PointXYZRGB>::Ptr output, const geometry_msgs::PoseStamped::ConstPtr& pose_msg) { Eigen::Affine3f posef; tf::poseMsgToEigen(pose_msg->pose, posef); Eigen::Affine3f transform = posef.inverse(); pcl::transformPointCloud<pcl::PointXYZRGB>( *input, *output, transform); } void IncrementalModelRegistration::newsampleCallback( const sensor_msgs::PointCloud2::ConstPtr& cloud_msg, const pcl_msgs::PointIndices::ConstPtr& indices_msg, const geometry_msgs::PoseStamped::ConstPtr& pose_msg) { boost::mutex::scoped_lock lock(mutex_); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>); pcl::PointCloud<pcl::PointXYZRGB>::Ptr filtered_cloud (new pcl::PointCloud<pcl::PointXYZRGB>); pcl::fromROSMsg(*cloud_msg, *cloud); pcl::PointCloud<pcl::PointXYZRGB>::Ptr transformed_cloud (new pcl::PointCloud<pcl::PointXYZRGB>); pcl::PointIndices::Ptr indices (new pcl::PointIndices); indices->indices = indices_msg->indices; pcl::ExtractIndices<pcl::PointXYZRGB> ex; ex.setInputCloud(cloud); ex.setIndices(indices); ex.filter(*filtered_cloud); transformPointCloudRepsectedToPose( filtered_cloud, transformed_cloud, pose_msg); Eigen::Affine3f initial_pose; if (samples_.size() == 0) { // first pointcloud, it will be the `origin` tf::poseMsgToEigen(pose_msg->pose, origin_); initial_pose = origin_; } else { // compute transformation from origin_ Eigen::Affine3f offset; tf::poseMsgToEigen(pose_msg->pose, offset); initial_pose = origin_.inverse() * offset; } CapturedSamplePointCloud::Ptr sample (new CapturedSamplePointCloud(transformed_cloud, initial_pose)); samples_.push_back(sample); all_cloud_ = all_cloud_ + *transformed_cloud; sensor_msgs::PointCloud2 ros_all_cloud; pcl::toROSMsg(all_cloud_, ros_all_cloud); ros_all_cloud.header = cloud_msg->header; pub_cloud_non_registered_.publish(ros_all_cloud); } void IncrementalModelRegistration::callICP( pcl::PointCloud<pcl::PointXYZRGB>::Ptr reference, pcl::PointCloud<pcl::PointXYZRGB>::Ptr target, Eigen::Affine3f& output_transform) { ros::ServiceClient icp = pnh_->serviceClient<jsk_recognition_msgs::ICPAlign>("icp_service"); sensor_msgs::PointCloud2 reference_ros, target_ros; pcl::toROSMsg(*reference, reference_ros); pcl::toROSMsg(*target, target_ros); ros::Time now = ros::Time::now(); reference_ros.header.stamp = target_ros.header.stamp = now; reference_ros.header.frame_id = target_ros.header.frame_id = "map"; jsk_recognition_msgs::ICPAlign srv; srv.request.reference_cloud = reference_ros; srv.request.target_cloud = target_ros; icp.call(srv); tf::poseMsgToEigen(srv.response.result.pose, output_transform); } bool IncrementalModelRegistration::startRegistration( std_srvs::Empty::Request& req, std_srvs::Empty::Response& res) { if (samples_.size() <= 1) { ROS_ERROR("no enough samples"); return false; } ROS_INFO("Starting registration %lu samples", samples_.size()); // setup initial CapturedSamplePointCloud::Ptr initial_sample = samples_[0]; initial_sample->setRefinedPointCloud( *(initial_sample->getOriginalPointCloud())); initial_sample->setRefinedPose(initial_sample->getOriginalPose()); for (size_t i = 0; i < samples_.size() - 1; i++) { CapturedSamplePointCloud::Ptr from_sample = samples_[i]; CapturedSamplePointCloud::Ptr to_sample = samples_[i+1]; pcl::PointCloud<pcl::PointXYZRGB>::Ptr reference_cloud = from_sample->getRefinedPointCloud(); pcl::PointCloud<pcl::PointXYZRGB>::Ptr target_cloud = to_sample->getOriginalPointCloud(); Eigen::Affine3f transform; callICP(reference_cloud, target_cloud, transform); to_sample->setRefinedPose(to_sample->getOriginalPose() * transform); // transform pointcloud pcl::PointCloud<pcl::PointXYZRGB>::Ptr transformed_cloud (new pcl::PointCloud<pcl::PointXYZRGB>); pcl::transformPointCloud<pcl::PointXYZRGB>( *target_cloud, *transformed_cloud, transform); to_sample->setRefinedPointCloud(*transformed_cloud); } pcl::PointCloud<pcl::PointXYZRGB>::Ptr registered_cloud (new pcl::PointCloud<pcl::PointXYZRGB>); pcl::PointCloud<pcl::PointXYZRGB>::Ptr non_registered_cloud (new pcl::PointCloud<pcl::PointXYZRGB>); for (size_t i = 0; i < samples_.size(); i++) { *registered_cloud = *(samples_[i]->getRefinedPointCloud()) + *registered_cloud; *non_registered_cloud = *(samples_[i]->getOriginalPointCloud()) + *non_registered_cloud; } sensor_msgs::PointCloud2 registered_ros_cloud, nonregistered_ros_cloud; pcl::toROSMsg(*registered_cloud, registered_ros_cloud); registered_ros_cloud.header.stamp = ros::Time::now(); registered_ros_cloud.header.frame_id = frame_id_; pub_registered_.publish(registered_ros_cloud); pcl::toROSMsg(*non_registered_cloud, nonregistered_ros_cloud); nonregistered_ros_cloud.header.stamp = ros::Time::now(); nonregistered_ros_cloud.header.frame_id = frame_id_; pub_cloud_non_registered_.publish(nonregistered_ros_cloud); } } #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS (jsk_pcl_ros::IncrementalModelRegistration, nodelet::Nodelet);
39.586345
105
0.707416
[ "transform" ]
cf62fc80be95dd340a64749bdb543e3eea612bf9
1,032
cpp
C++
aoj/0508.cpp
utgw/programming-contest
eb7f28ae913296c6f4f9a8136dca8bd321e01e79
[ "MIT" ]
null
null
null
aoj/0508.cpp
utgw/programming-contest
eb7f28ae913296c6f4f9a8136dca8bd321e01e79
[ "MIT" ]
null
null
null
aoj/0508.cpp
utgw/programming-contest
eb7f28ae913296c6f4f9a8136dca8bd321e01e79
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define FOR(i,m,n) for(int i=m;i<(n);i++) #define REP(i,n) FOR(i,0,n) #define ALL(x) (x).begin(),(x).end() using namespace std; typedef long long ll; const ll inf = INT_MAX; const double eps = 1e-8; const double pi = acos(-1.0); const int di[][2] = {{1,0},{0,1},{-1,0},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}}; int main(void){ int n; while(cin>>n,n){ vector<vector<int>> e(100); REP(i,n){ int a,b;cin>>a>>b; e[a-1].push_back(b-1); e[b-1].push_back(a-1); } REP(i,100)sort(ALL(e[i])); int ans=0; REP(i,100){ if(e[i].empty())continue; stack<pair<int,int>> next; next.push(make_pair(i,1)); vector<bool> visited(100,false); while(!next.empty()){ auto a=next.top();next.pop(); int p=a.first,d=a.second; ans=max(ans,d); if(visited[p])continue; visited[p]=true; for(int j:e[p]){ if(!visited[j])next.push(make_pair(j,d+1)); } } } cout<<ans<<endl; } return 0; }
24
76
0.518411
[ "vector" ]
cf649299b4ceda9c402246bd1644849326a20f16
4,308
cpp
C++
fk/hal/linux/linux_memory.cpp
fieldkit/firmware
09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6
[ "BSD-3-Clause" ]
10
2019-11-26T11:35:56.000Z
2021-07-03T07:21:38.000Z
fk/hal/linux/linux_memory.cpp
fieldkit/firmware
09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6
[ "BSD-3-Clause" ]
1
2019-07-03T06:27:21.000Z
2019-09-06T09:21:27.000Z
fk/hal/linux/linux_memory.cpp
fieldkit/firmware
09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6
[ "BSD-3-Clause" ]
1
2019-09-23T18:13:51.000Z
2019-09-23T18:13:51.000Z
#include "hal/linux/linux.h" #include "utilities.h" #if defined(linux) #include <cstring> namespace fk { FK_DECLARE_LOGGER("memory"); uint8_t LinuxDataMemory::EraseByte = 0xff; LinuxDataMemory::LinuxDataMemory(uint32_t number_of_blocks) : number_of_blocks_(number_of_blocks), memory_(nullptr) { } LinuxDataMemory::~LinuxDataMemory() { if (memory_ != nullptr) { free(memory_); memory_ = nullptr; } } bool LinuxDataMemory::begin() { geometry_.page_size = PageSize; geometry_.block_size = BlockSize; geometry_.nblocks = number_of_blocks_; geometry_.total_size = BlockSize * number_of_blocks_; geometry_.prog_size = 512; geometry_.real_page_size = PageSize; if (memory_ == nullptr) { memory_ = (uint8_t *)fk_malloc(geometry_.total_size); memset(memory_, 0xff, geometry_.total_size); } log_.logging(false); log_.clear(); log_.append(LogEntry{ OperationType::Opened, 0x0, memory_ }); return true; } void LinuxDataMemory::erase_all() { memset(memory_, 0xff, geometry_.total_size); } int32_t LinuxDataMemory::execute(uint32_t *got, uint32_t *entry) { FK_ASSERT(false); return 0; } FlashGeometry LinuxDataMemory::geometry() const { return geometry_; } int32_t LinuxDataMemory::read(uint32_t address, uint8_t *data, size_t length, MemoryReadFlags flags) { assert(address >= 0 && address < geometry_.total_size); assert(address + length <= geometry_.total_size); assert(length <= PageSize); logverbose("[" PRADDRESS "] read %zd bytes", address, length); if (affects_bad_block_from_factory(address)) { bzero(data, length); return length; } // NOTE Disabled temporarily to test LFS storage. size_t page = address / PageSize; assert((address + length - 1) / PageSize == page); size_t block = address / BlockSize; size_t start_of_block = block * BlockSize; assert(address >= start_of_block && address + length <= start_of_block + BlockSize); auto p = memory_ + address; memcpy(data, p, length); log_.append(LogEntry{ OperationType::Read, address, p, length }); return length; } int32_t LinuxDataMemory::write(uint32_t address, const uint8_t *data, size_t length, MemoryWriteFlags flags) { assert(address >= 0 && address < geometry_.total_size); assert(address + length <= geometry_.total_size); assert(length <= PageSize); logverbose("[" PRADDRESS "] write %zd bytes", address, length); if (affects_bad_region(address, length)) { return 0; } // NOTE Disabled temporarily to test LFS storage. size_t page = address / PageSize; assert((address + length - 1) / PageSize == page); size_t block = address / BlockSize; size_t start_of_block = block * BlockSize; assert(address >= start_of_block && address + length <= start_of_block + BlockSize); auto p = memory_ + address; memcpy(p, data, length); log_.append(LogEntry{ OperationType::Write, address, p, length }); return length; } int32_t LinuxDataMemory::erase(uint32_t address, size_t length) { return for_each_block_between(address, length, BlockSize, [=](uint32_t block_address) { return erase_block(block_address); }); } int32_t LinuxDataMemory::erase_block(uint32_t address) { assert(address >= 0 && address < geometry_.total_size); assert(address % BlockSize == 0); logverbose("[" PRADDRESS "] erase-block %zd bytes", address, BlockSize); if (affects_bad_block_from_wear(address)) { return -1; } auto p = memory_ + address; memset(p, EraseByte, BlockSize); log_.append(LogEntry{ OperationType::EraseBlock, address, p }); return 0; } int32_t LinuxDataMemory::copy_page(uint32_t source, uint32_t destiny, size_t length, uint8_t *buffer, size_t buffer_size) { assert(source >= 0 && source < geometry_.total_size); assert(source % PageSize == 0); assert(destiny >= 0 && destiny < geometry_.total_size); assert(destiny % PageSize == 0); assert(length == PageSize); logverbose("[" PRADDRESS "] copy [" PRADDRESS "] %zd bytes", destiny, source, length); memcpy(memory_ + destiny, memory_ + source, PageSize); return 0; } int32_t LinuxDataMemory::flush() { return true; } } #endif
27.43949
123
0.681523
[ "geometry" ]
cf6a7348877956c71c9d2a0b69074d259f6234c8
4,059
cpp
C++
media/libaudioclient/tests/test_create_audiorecord.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
media/libaudioclient/tests/test_create_audiorecord.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
media/libaudioclient/tests/test_create_audiorecord.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
2
2021-07-08T07:42:11.000Z
2021-07-09T21:56:10.000Z
/* * Copyright (C) 2017 The Android Open Source Project * * 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 <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <binder/MemoryBase.h> #include <binder/MemoryDealer.h> #include <binder/MemoryHeapBase.h> #include <media/AudioRecord.h> #include "test_create_utils.h" #define NUM_ARGUMENTS 8 #define VERSION_VALUE "1.0" #define PACKAGE_NAME "AudioRecord test" namespace android { int testRecord(FILE *inputFile, int outputFileFd) { char line[MAX_INPUT_FILE_LINE_LENGTH]; uint32_t testCount = 0; Vector<String16> args; int ret = 0; if (inputFile == nullptr) { sp<AudioRecord> record = new AudioRecord(AUDIO_SOURCE_DEFAULT, 0 /* sampleRate */, AUDIO_FORMAT_DEFAULT, AUDIO_CHANNEL_IN_MONO, String16(PACKAGE_NAME)); if (record == 0 || record->initCheck() != NO_ERROR) { write(outputFileFd, "Error creating AudioRecord\n", sizeof("Error creating AudioRecord\n")); } else { record->dump(outputFileFd, args); } return 0; } // check version if (!checkVersion(inputFile, VERSION_VALUE)) { return 1; } while (readLine(inputFile, line, MAX_INPUT_FILE_LINE_LENGTH) == 0) { uint32_t sampleRate; audio_format_t format; audio_channel_mask_t channelMask; size_t frameCount; int32_t notificationFrames; audio_input_flags_t flags; audio_session_t sessionId; audio_source_t inputSource; audio_attributes_t attributes; status_t status; char statusStr[MAX_OUTPUT_FILE_LINE_LENGTH]; bool fast = false; if (sscanf(line, " %u %x %x %zu %d %x %u %u", &sampleRate, &format, &channelMask, &frameCount, &notificationFrames, &flags, &sessionId, &inputSource) != NUM_ARGUMENTS) { fprintf(stderr, "Malformed line for test #%u in input file\n", testCount+1); ret = 1; continue; } testCount++; if ((flags & AUDIO_INPUT_FLAG_FAST) != 0) { fast = true; } memset(&attributes, 0, sizeof(attributes)); attributes.source = inputSource; sp<AudioRecord> record = new AudioRecord(String16(PACKAGE_NAME)); record->set(AUDIO_SOURCE_DEFAULT, sampleRate, format, channelMask, frameCount, fast ? callback : nullptr, nullptr, notificationFrames, false, sessionId, fast ? AudioRecord::TRANSFER_CALLBACK : AudioRecord::TRANSFER_DEFAULT, flags, getuid(), getpid(), &attributes, AUDIO_PORT_HANDLE_NONE); status = record->initCheck(); sprintf(statusStr, "\n#### Test %u status %d\n", testCount, status); write(outputFileFd, statusStr, strlen(statusStr)); if (status != NO_ERROR) { continue; } record->dump(outputFileFd, args); } return ret; } }; // namespace android int main(int argc, char **argv) { return android::main(argc, argv, android::testRecord); }
31.223077
89
0.575511
[ "vector" ]
cf6c01826e5fd5302b7820c07c145270a26b91ce
9,879
cpp
C++
module/mpc-be/SRC/src/DSUtil/MediaDescription.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/DSUtil/MediaDescription.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/DSUtil/MediaDescription.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
/* * (C) 2006-2018 see Authors.txt * * This file is part of MPC-BE. * * MPC-BE is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * MPC-BE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "stdafx.h" #include <ks.h> #include <ksmedia.h> #include <MMReg.h> #include <moreuuids.h> #include "MediaDescription.h" #include "AudioParser.h" #include "DSUtil.h" CString GetMediaTypeDesc(std::vector<CMediaType>& mts, LPCWSTR pName, CBaseFilter* pFilter) { if (mts.empty()) { return pName; } CLSID clSID; HRESULT hr = pFilter->GetClassID(&clSID); if (clSID == GUIDFromCString(L"{1365BE7A-C86A-473C-9A41-C0A6E82C9FA3}") || clSID == GUIDFromCString(L"{DC257063-045F-4BE2-BD5B-E12279C464F0}")) { // skip MPEGSource/Splitter ... return pName; } return GetMediaTypeDesc(&mts[0], pName); } CString GetMediaTypeDesc(const CMediaType* pmt, LPCWSTR pName) { if (!pmt) { return pName; } std::list<CString> Infos; if (pmt->majortype == MEDIATYPE_Video) { const VIDEOINFOHEADER *pVideoInfo = nullptr; const VIDEOINFOHEADER2 *pVideoInfo2 = nullptr; BOOL bAdd = FALSE; if (pmt->formattype == FORMAT_VideoInfo) { pVideoInfo = GetFormatHelper(pVideoInfo, pmt); } else if (pmt->formattype == FORMAT_MPEGVideo) { Infos.emplace_back(L"MPEG"); const MPEG1VIDEOINFO *pInfo = GetFormatHelper(pInfo, pmt); pVideoInfo = &pInfo->hdr; bAdd = TRUE; } else if (pmt->formattype == FORMAT_MPEG2_VIDEO) { const MPEG2VIDEOINFO *pInfo = GetFormatHelper(pInfo, pmt); pVideoInfo2 = &pInfo->hdr; bool bIsAVC = false; bool bIsHEVC = false; bool bIsMPEG2 = false; if (pInfo->hdr.bmiHeader.biCompression == FCC('AVC1') || pInfo->hdr.bmiHeader.biCompression == FCC('H264')) { bIsAVC = true; Infos.emplace_back(L"AVC (H.264)"); bAdd = TRUE; } else if (pInfo->hdr.bmiHeader.biCompression == FCC('AMVC') || pInfo->hdr.bmiHeader.biCompression == FCC('MVC1')) { bIsAVC = true; Infos.emplace_back(L"MVC Full (H.264)"); bAdd = TRUE; } else if (pInfo->hdr.bmiHeader.biCompression == FCC('EMVC')) { bIsAVC = true; Infos.emplace_back(L"MVC Subset (H.264)"); bAdd = TRUE; } else if (pInfo->hdr.bmiHeader.biCompression == 0) { Infos.emplace_back(L"MPEG2"); bIsMPEG2 = true; bAdd = TRUE; } else if (pInfo->hdr.bmiHeader.biCompression == FCC('HEVC') || pInfo->hdr.bmiHeader.biCompression == FCC('HVC1')) { Infos.emplace_back(L"HEVC (H.265)"); bIsHEVC = true; bAdd = TRUE; } if (bIsMPEG2) { Infos.emplace_back(MPEG2_Profile[pInfo->dwProfile]); } else if (pInfo->dwProfile) { if (bIsAVC) { switch (pInfo->dwProfile) { case 44: Infos.emplace_back(L"CAVLC Profile"); break; case 66: Infos.emplace_back(L"Baseline Profile"); break; case 77: Infos.emplace_back(L"Main Profile"); break; case 88: Infos.emplace_back(L"Extended Profile"); break; case 100: Infos.emplace_back(L"High Profile"); break; case 110: Infos.emplace_back(L"High 10 Profile"); break; case 118: Infos.emplace_back(L"Multiview High Profile"); break; case 122: Infos.emplace_back(L"High 4:2:2 Profile"); break; case 128: Infos.emplace_back(L"Stereo High Profile"); break; case 244: Infos.emplace_back(L"High 4:4:4 Profile"); break; default: Infos.emplace_back(FormatString(L"Profile %u", pInfo->dwProfile)); break; } } else if (bIsHEVC) { switch (pInfo->dwProfile) { case 1: Infos.emplace_back(L"Main Profile"); break; case 2: Infos.emplace_back(L"Main/10 Profile"); break; default: Infos.emplace_back(FormatString(L"Profile %u", pInfo->dwProfile)); break; } } else { Infos.emplace_back(FormatString(L"Profile %u", pInfo->dwProfile)); } } if (bIsMPEG2) { Infos.emplace_back(MPEG2_Level[pInfo->dwLevel]); } else if (pInfo->dwLevel) { if (bIsAVC) { Infos.emplace_back(FormatString(L"Level %1.1f", double(pInfo->dwLevel) / 10.0)); } else if (bIsHEVC) { Infos.emplace_back(FormatString(L"Level %u.%u", pInfo->dwLevel / 30, (pInfo->dwLevel % 30) / 3)); } else { Infos.emplace_back(FormatString(L"Level %u", pInfo->dwLevel)); } } } else if (pmt->formattype == FORMAT_VIDEOINFO2) { const VIDEOINFOHEADER2 *pInfo = GetFormatHelper(pInfo, pmt); pVideoInfo2 = pInfo; } if (!bAdd) { BITMAPINFOHEADER bih; bool fBIH = ExtractBIH(pmt, &bih); if (fBIH) { CString codecName = CMediaTypeEx::GetVideoCodecName(pmt->subtype, bih.biCompression); if (!codecName.IsEmpty()) { Infos.emplace_back(codecName); } } } if (pVideoInfo2) { if (pVideoInfo2->bmiHeader.biWidth && pVideoInfo2->bmiHeader.biHeight) { Infos.emplace_back(FormatString(L"%dx%d", pVideoInfo2->bmiHeader.biWidth, pVideoInfo2->bmiHeader.biHeight)); } if (pVideoInfo2->AvgTimePerFrame) { Infos.emplace_back(FormatString(L"%.3f fps", 10000000.0 / pVideoInfo2->AvgTimePerFrame)); } if (pVideoInfo2->dwBitRate) { Infos.emplace_back(FormatBitrate(pVideoInfo2->dwBitRate)); } } else if (pVideoInfo) { if (pVideoInfo->bmiHeader.biWidth && pVideoInfo->bmiHeader.biHeight) { Infos.emplace_back(FormatString(L"%dx%d", pVideoInfo->bmiHeader.biWidth, pVideoInfo->bmiHeader.biHeight)); } if (pVideoInfo->AvgTimePerFrame) { Infos.emplace_back(FormatString(L"%.3f fps", 10000000.0 / pVideoInfo->AvgTimePerFrame)); } if (pVideoInfo->dwBitRate) { Infos.emplace_back(FormatBitrate(pVideoInfo->dwBitRate)); } } } else if (pmt->majortype == MEDIATYPE_Audio) { if (pmt->formattype == FORMAT_WaveFormatEx) { const WAVEFORMATEX *pInfo = GetFormatHelper(pInfo, pmt); if (pmt->subtype == MEDIASUBTYPE_DVD_LPCM_AUDIO) { Infos.emplace_back(L"DVD LPCM"); } else if (pmt->subtype == MEDIASUBTYPE_HDMV_LPCM_AUDIO) { const WAVEFORMATEX_HDMV_LPCM *pInfoHDMV = GetFormatHelper(pInfoHDMV, pmt); UNREFERENCED_PARAMETER(pInfoHDMV); Infos.emplace_back(L"HDMV LPCM"); } if (pmt->subtype == MEDIASUBTYPE_DOLBY_DDPLUS) { Infos.emplace_back(L"Dolby Digital Plus"); } else { if (pInfo->wFormatTag == WAVE_FORMAT_MPEG && pmt->cbFormat >= sizeof(MPEG1WAVEFORMAT)) { const MPEG1WAVEFORMAT* pInfoMPEG1 = GetFormatHelper(pInfoMPEG1, pmt); int layer = GetHighestBitSet32(pInfoMPEG1->fwHeadLayer) + 1; Infos.emplace_back(FormatString(L"MPEG1 - Layer %d", layer)); } else { CString codecName = CMediaTypeEx::GetAudioCodecName(pmt->subtype, pInfo->wFormatTag); if (!codecName.IsEmpty()) { if (codecName == L"DTS" && pInfo->cbSize == 1) { const auto profile = ((BYTE *)(pInfo + 1))[0]; switch (profile) { case DCA_PROFILE_HD_HRA: codecName = L"DTS-HD HRA"; break; case DCA_PROFILE_HD_MA: codecName = L"DTS-HD MA"; break; case DCA_PROFILE_EXPRESS: codecName = L"DTS Express"; break; } } Infos.emplace_back(codecName); } } } if (pInfo->nSamplesPerSec) { Infos.emplace_back(FormatString(L"%.1f kHz", double(pInfo->nSamplesPerSec) / 1000.0)); } if (pInfo->nChannels) { DWORD layout = 0; if (IsWaveFormatExtensible(pInfo)) { const WAVEFORMATEXTENSIBLE* wfex = (WAVEFORMATEXTENSIBLE*)pInfo; layout = wfex->dwChannelMask; } else { layout = GetDefChannelMask(pInfo->nChannels); } BYTE lfe = 0; WORD nChannels = pInfo->nChannels; if (layout & SPEAKER_LOW_FREQUENCY) { nChannels--; lfe = 1; } Infos.emplace_back(FormatString(L"%u.%u chn", nChannels, lfe)); } if (pInfo->wBitsPerSample) { Infos.emplace_back(FormatString(L"%u bit", pInfo->wBitsPerSample)); } if (pInfo->nAvgBytesPerSec && pInfo->wFormatTag != WAVE_FORMAT_OPUS) { Infos.emplace_back(FormatBitrate(pInfo->nAvgBytesPerSec * 8)); } } else if (pmt->formattype == FORMAT_VorbisFormat) { const VORBISFORMAT *pInfo = GetFormatHelper(pInfo, pmt); Infos.emplace_back(CMediaTypeEx::GetAudioCodecName(pmt->subtype, 0)); if (pInfo->nSamplesPerSec) { Infos.emplace_back(FormatString(L"%.1f kHz", double(pInfo->nSamplesPerSec) / 1000.0)); } if (pInfo->nChannels) { Infos.emplace_back(FormatString(L"%u chn", pInfo->nChannels)); } if (pInfo->nAvgBitsPerSec) { Infos.emplace_back(FormatString(L"%u bit", pInfo->nAvgBitsPerSec)); } if (pInfo->nAvgBitsPerSec) { Infos.emplace_back(FormatBitrate(pInfo->nAvgBitsPerSec * 8)); } } else if (pmt->formattype == FORMAT_VorbisFormat2) { const VORBISFORMAT2 *pInfo = GetFormatHelper(pInfo, pmt); Infos.emplace_back(CMediaTypeEx::GetAudioCodecName(pmt->subtype, 0)); if (pInfo->SamplesPerSec) { Infos.emplace_back(FormatString(L"%.1f kHz", double(pInfo->SamplesPerSec) / 1000.0)); } if (pInfo->Channels) { Infos.emplace_back(FormatString(L"%u chn", pInfo->Channels)); } } } if (!Infos.empty()) { CString Ret = pName; Ret += L" ("; bool bFirst = true; for (const auto& str : Infos) { if (bFirst) { Ret += str; } else { Ret += L", " + str; } bFirst = false; } Ret += L')'; return Ret; } return pName; }
30.490741
146
0.651888
[ "vector" ]
cf7a88b2887d5b08c940802c41fde6b904056ede
852
cpp
C++
USACOTasks/Section 3.1 Humble Numbers/humble.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
USACOTasks/Section 3.1 Humble Numbers/humble.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
USACOTasks/Section 3.1 Humble Numbers/humble.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
/* ID: yezhiyo1 PROG: humble LANG: C++ */ #include <iostream> #include <fstream> #include <vector> #include <queue> #include <map> #include <algorithm> #include <memory.h> using namespace std; ifstream fin("humble.in"); ofstream fout("humble.out"); int k,n; std::vector <int> primes; std::vector <long> lastIndex; std::vector <long> c; int main (){ fin>>k>>n; primes.resize(k); lastIndex.resize(k,0); for (int i=0;i<k;i++){ fin>>primes[i]; } c.push_back(1); while (c.size()<n+1){ long minVal=0x7fffffff; int minIndex=-1; for (int i=0;i<k;i++){ long newVal=c[lastIndex[i]]*primes[i]; if (newVal<minVal && newVal>c[c.size()-1]){ minVal=newVal; minIndex=i; } } for (int i=0;i<k;i++){ if (c[lastIndex[i]]*primes[i] == minVal){ lastIndex[i]++; } } c.push_back(minVal); } fout<<c[n]<<endl; return 0; }
17.75
46
0.610329
[ "vector" ]